delete useless multi-vm and py-vm, create a mcjit branch
llvm-svn: 195627
diff --git a/vmkit/CREDITS.TXT b/vmkit/CREDITS.TXT
deleted file mode 100644
index 3afdb2c..0000000
--- a/vmkit/CREDITS.TXT
+++ /dev/null
@@ -1,32 +0,0 @@
-This file is a partial list of people who have contributed to the VMKit
-project. If you have contributed a patch or made some other contribution to
-VMKit, please submit a patch to this file to add yourself, and it will be
-done!
-
-The list is sorted by name and formatted to allow easy grepping and
-beautification by scripts. The fields are: name (N), email (E), web-address
-(W), PGP key ID and fingerprint (P), description (D), and snail-mail address
-(S).
-
-N: Bertil Folliot
-E: bertil.folliot@lip6.fr
-W: http://www-src.lip6.fr/homepages/Bertil.Folliot/
-D: Provider of much wisdom
-
-N: Nicolas Geoffray
-E: nicolas.geoffray@lip6.fr
-W: http://www-src.lip6.fr/homepages/Nicolas.Geoffray/
-D: Architect of J3, originally a port of JnJVM to LLVM
-D: Architect of N3
-
-N: Sylvain Marechal
-E: sylvain.marechal@lip6.fr
-D: Original autoconf support
-
-N: Tilmann Scheller
-D: Generics support in N3.
-
-N: Gael Thomas
-E: gael.thomas@lip6.fr
-W: http://www-src.lip6.fr/homepages/Gael.Thomas/
-D: Primary architect of JnJVM
diff --git a/vmkit/LICENSE.TXT b/vmkit/LICENSE.TXT
deleted file mode 100644
index a6bc3a9..0000000
--- a/vmkit/LICENSE.TXT
+++ /dev/null
@@ -1,66 +0,0 @@
-==============================================================================
-VMKit Release License
-==============================================================================
-University of Illinois/NCSA
-Open Source License
-
-Copyright (c) 2003-2010 University of Pierre et Marie Curie.
-All rights reserved.
-
-Developed by:
-
- VVM Team
-
- University of Pierre et Marie Curie, Paris
-
- http://llvm.org
-
-Permission is hereby granted, free of charge, to any person obtaining a copy of
-this software and associated documentation files (the "Software"), to deal with
-the Software without restriction, including without limitation the rights to
-use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
-of the Software, and to permit persons to whom the Software is furnished to do
-so, subject to the following conditions:
-
- * Redistributions of source code must retain the above copyright notice,
- this list of conditions and the following disclaimers.
-
- * Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following disclaimers in the
- documentation and/or other materials provided with the distribution.
-
- * Neither the names of the LLVM Team, the VVM Team, University of Illinois
- at Urbana-Champaign, University of Pierre et Marie Curie, nor the names
- of its contributors may be used to endorse or promote products derived
- from this Software without specific prior written permission.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
-FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS WITH THE
-SOFTWARE.
-
-==============================================================================
-Copyrights and Licenses for Third Party Software Distributed with VMKit:
-==============================================================================
-The VMKit software contains code written by third parties. Such software will
-have its own individual LICENSE.TXT file in the directory in which it appears.
-This file will describe the copyrights, license, and restrictions which apply
-to that code.
-
-The disclaimer of warranty in the University of Illinois Open Source License
-applies to all code in the VMKit Distribution, and nothing in any of the
-other licenses gives permission to use the names of the VVM Team or the
-University of Illinois to endorse or promote products derived from this
-Software.
-
-The following pieces of software have additional or alternate copyrights,
-licenses, and/or restrictions:
-
-Program Directory
-------- ---------
-Mono libraries vmkit/lib/N3/Mono
-PNetlib libraries vmkit/lib/N3/PNet
-MMTk vmkit/mmtk/
diff --git a/vmkit/Makefile b/vmkit/Makefile
deleted file mode 100644
index f89e018..0000000
--- a/vmkit/Makefile
+++ /dev/null
@@ -1,35 +0,0 @@
-#===- ./Makefile -------------------------------------------*- Makefile -*--===#
-#
-# The vmkit project
-#
-# This file is distributed under the University of Illinois Open Source
-# License. See LICENSE.TXT for details.
-#
-#===------------------------------------------------------------------------===#
-
-LEVEL := .
-
-include $(LEVEL)/Makefile.config
-
-# Top-Level vmkit Build Stages:
-#
-DIRS := lib tools/vmjc
-
-ifeq ($(GC_MMTK), 1)
- DIRS += mmtk
-endif
-
-DIRS += tools
-
-EXTRA_DIST=include
-
-include $(LEVEL)/Makefile.common
-
-#------------------------------------------------------------------------
-# Make sure the generated headers are up-to-date. This must be kept in
-# sync with the AC_CONFIG_HEADER invocations in autoconf/configure.ac
-#------------------------------------------------------------------------
-FilesToConfig := \
- include/llvm/Config/config.h \
- lib/J3/Classpath/Classpath.h \
-FilesToConfigPATH := $(addprefix $(LLVM_OBJ_ROOT)/,$(FilesToConfig))
diff --git a/vmkit/Makefile.common.in b/vmkit/Makefile.common.in
deleted file mode 100755
index 759c8e8..0000000
--- a/vmkit/Makefile.common.in
+++ /dev/null
@@ -1,46 +0,0 @@
-# Set the name of the project here
-PROJECT_NAME := @PACKAGE_NAME@
-PROJ_VERSION := @PACKAGE_VERSION@
-
-# Set this variable to the top of the LLVM source tree.
-LLVM_SRC_ROOT = @LLVM_SRC@
-
-# Set this variable to the top level directory where LLVM was built
-# (this is *not* the same as OBJ_ROOT as defined in LLVM's Makefile.config).
-LLVM_OBJ_ROOT = @LLVM_OBJ@
-
-# Set the directory root of this project's source files
-PROJ_SRC_ROOT := $(subst //,/,@abs_top_srcdir@)
-
-# Set the root directory of this project's object files
-PROJ_OBJ_ROOT := $(subst //,/,@abs_top_objdir@)
-
-# Set the root directory of this project's install prefix
-PROJ_INSTALL_ROOT := @prefix@
-
-# Define BYTECODE_LIBRARY before including LLVM's Makefile.common to get
-# dependencies right.
-ifeq ($(WITH_LLVM_GCC), 1)
- BYTECODE_LIBRARY = 1
-endif
-
-# Include LLVM's Master Makefile.
-include $(LLVM_OBJ_ROOT)/Makefile.common
-
-CXX.Flags += @LLVM_FLAGS@ @GC_FLAGS@ @VM_FLAGS@ @EXCEPTION_FLAGS@ -Wno-variadic-macros -fno-omit-frame-pointer -fno-strict-aliasing -Wno-deprecated -ansi -DENABLE_THREADS -fno-rtti
-
-# GNU Classpath flags
-CLASSPATH_FLAGS = @classpathinclude@
-GLIBJ = @classpathglibj@
-
-# Pnet location
-PNETLIB = @pnetlocalprefix@
-
-LIBS += -lz
-
-# GC configuration
-ifeq ($(GCLIB), BoehmGC)
- LIBS += -lgc
-endif
-
-include $(PROJ_SRC_ROOT)/Makefile.rules
diff --git a/vmkit/Makefile.config.in b/vmkit/Makefile.config.in
deleted file mode 100755
index 024d607..0000000
--- a/vmkit/Makefile.config.in
+++ /dev/null
@@ -1,17 +0,0 @@
-GCLIB = @GC_LIBS@
-WITH_N3 = @WITH_N3@
-WITH_N3_PNETLIB = @WITH_N3_PNETLIB@
-WITH_N3_MONO = @WITH_N3_MONO@
-WITH_J3 = @WITH_J3@
-N3_LIB = @N3_LIB@
-GC_MULTI_MMAP = @GC_MULTI_MMAP@
-GC_SINGLE_MMAP = @GC_SINGLE_MMAP@
-GC_BOEHM = @GC_BOEHM@
-GC_MMAP2 = @GC_MMAP2@
-GC_MMTK = @GC_MMTK@
-MMTK_PLAN = @MMTK_PLAN@
-MMTK_PLAN_HEADER = @MMTK_PLAN_HEADER@
-WITH_64 = @WITH_64@
-WITH_LLVM_GCC = @WITH_LLVM_GCC@
-
-ANT = @ANT@
diff --git a/vmkit/Makefile.rules b/vmkit/Makefile.rules
deleted file mode 100644
index 52a4eae..0000000
--- a/vmkit/Makefile.rules
+++ /dev/null
@@ -1,154 +0,0 @@
-
-ifdef VMKIT_RUNTIME
-
-
-.PRECIOUS: LLVMRuntime.inc
-
-# All of these files depend on tblgen and the .td files.
-LLVMRuntime.inc : $(LLVMAS) $(LLC) $(VMKIT_RUNTIME)
-
-LLVMRuntime.gen.ll : $(VMKIT_RUNTIME)
- $(Verb) cat $(VMKIT_RUNTIME) > LLVMRuntime.gen.ll
-
-LLVMRuntime.inc : LLVMRuntime.gen.ll
- $(Echo) "Building LLVM runtime with $(VMKIT_RUNTIME)"
- $(Verb) $(LLVMAS) -f $(<F) -o - | $(LLC) -march=cpp -cppgen=contents -o $@
-
-
-clean-local::
- $(Verb) $(RM) -f LLVMRuntime.inc LLVMRuntime.gen.ll LLVMRuntime.bc
-
-endif
-
-ifdef VMKIT_ASSEMBLY
-
-.PRECIOUS: LLVMAssembly.s
-
-LLVMAssembly.o : $(LLVMAS) $(LLC) $(VMKIT_ASSEMBLY)
-
-LLVMAssembly.gen.ll : $(VMKIT_ASSEMBLY)
- $(Verb) cat $(VMKIT_ASSEMBLY) > LLVMAssembly.gen.ll
-
-LLVMAssembly.s : LLVMAssembly.gen.ll
- $(Echo) "Building LLVM assembly with $(VMKIT_ASSEMBLY)"
- $(Verb) $(LLVMAS) -f $(<F) -o - | $(LLC) -o $@
-
-$(ObjDir)/%.lo $(ObjDir)/%.o: %.s $(ObjDir)/.dir $(BUILT_SOURCES)
- $(Echo) "Compiling $*.s for $(BuildMode) build " $(PIC_FLAG)
- $(Verb) $(GAS) $< -o $(ObjDir)/$*.o
-
-clean-local::
- $(Verb) $(RM) -f LLVMAssembly.s LLVMAssembly.bc LLVMAssembly.gen.ll
-
-endif
-
-ifndef VMJC
-VMJC := $(ToolDir)/vmjc$(EXEEXT)
-endif
-
-
-ifdef VMJC_ASSEMBLY
-
-.PRECIOUS: glibj.zip.s
-
-glibj.zip.s : $(LOPT) $(LLC) $(VMJC)
-
-
-glibj.zip.bc :
- $(Echo) "Compiling glibj.zip to llvm"
- $(Verb) if test -d $(GLIBJ); then \
- $(VMJC) -f -std-compile-opts $(GLIBJ)/glibj.zip -o glibj.zip.bc; \
- else \
- $(VMJC) -f -std-compile-opts $(GLIBJ) -o glibj.zip.bc; \
- fi
-
-glibj-optimized.zip.bc : glibj.zip.bc
- $(Echo) "Optimizing glibj.zip"
- $(Verb) $(LOPT) -std-compile-opts -f glibj.zip.bc -o glibj-optimized.zip.bc
-
-glibj.zip.s : glibj-optimized.zip.bc
- $(Echo) "Compiling glibj.zip.bc to native"
- $(Verb) $(LLC) -relocation-model=pic -disable-fp-elim glibj-optimized.zip.bc -o glibj.zip.s
-
-$(ObjDir)/%.o: %.s $(ObjDir)/.dir $(BUILT_SOURCES)
- $(Echo) "Compiling $*.s for $(BuildMode) build" $(PIC_FLAG)
- $(Verb) $(Compile.C) $< -o $(ObjDir)/$*.o
-
-clean-local::
- $(Verb) $(RM) -f glibj.zip.s glibj.zip.bc glibj-optimized.zip.bc
-endif
-
-
-
-ifdef VMKIT_BUILD_ARCHIVE
-
-LibName.A := $(LibDir)/lib$(VMKIT_LIBRARYNAME).a
-
-all-local:: $(LibName.A)
-
-$(LibName.A): $(ProjLibsPaths) $(LibDir)/.dir
- $(Echo) Building $(BuildMode) Archive Library $(notdir $@)
- -$(Verb) $(RM) -f $@
- $(Verb) $(Archive) $@ $(ProjLibsPaths)
- $(Verb) $(Ranlib) $@
-
-clean-local::
-ifneq ($(strip $(LibName.A)),)
- -$(Verb) $(RM) -f $(LibName.A)
-endif
-
-endif
-
-
-
-ifdef MODULESNAME
-ifdef USEDMODULES
-
-ProjLibsPaths := $(addprefix $(LibDir)/,$(USEDMODULES))
-
-$(MODULESNAME).bc : $(ProjLibsPaths)
- $(Echo) Building $(BuildMode) Bytecode Module $(notdir $@)
- $(Verb) $(LLVMLD) -link-as-library -o $@ $(ProjLibsPaths)
-
-$(MODULESNAME).s : $(MODULESNAME).bc
- $(Echo) Building $(BuildMode) Assembly file $(notdir $@)
- $(Verb) $(LOPT) -load=$(LibDir)/StaticGCPass$(SHLIBEXT) -std-compile-opts -StaticGCPass -f $(MODULESNAME).bc -o vmkitoptimized.bc
- $(Verb) $(LLC) -disable-fp-elim vmkitoptimized.bc -o $(MODULESNAME).s
-
-$(ObjDir)/%.o: %.s $(ObjDir)/.dir $(BUILT_SOURCES)
- $(Echo) "Compiling $*.s for $(BuildMode) build" $(PIC_FLAG)
- $(Verb) $(Compile.C) $< -o $(ObjDir)/$*.o
-
-clean-local::
- $(Verb) $(RM) -f vmkitoptimized.bc $(MODULESNAME).bc $(MODULESNAME).s
-
-endif
-endif
-
-ifdef RUN_ANT
-ifdef ANT
-
-ifneq ($(DISABLE_MMTK_COMPILE), 1)
- ADDITIONAL_ARGS := -load-bc=$(LibDir)/MMTKRuntime.bc
-
-all:: $(LibDir)/FinalMMTk.bc
-
-$(LibDir)/FinalMMTk.bc: $(JARNAME).jar $(VMJC) $(LibDir)/MMTKAlloc.bc $(LibDir)/MMTKMagic$(SHLIBEXT) $(LibDir)/MMTKRuntime.bc
- $(Echo) Building $(BuildMode) FinalMMTk $(notdir $@)
- $(Verb) $(LOPT) -load=$(LibDir)/JITGCPass$(SHLIBEXT) -std-compile-opts -JITGCPass -f $(LibDir)/MMTKAlloc.bc -o $(LibDir)/MMTKAlloc.bc
- $(Verb) $(VMJC) -std-compile-opts $(ADDITIONAL_ARGS) -load=$(LibDir)/MMTKMagic$(SHLIBEXT) -LowerMagic $(PROJ_OBJ_ROOT)/mmtk/java/$(JARNAME).jar -disable-exceptions -disable-cooperativegc -with-clinit=org/mmtk/vm/VM,org/mmtk/utility/*,org/mmtk/policy/*,org/j3/config/* -Dmmtk.hostjvm=org.j3.mmtk.Factory -o $(JARNAME).bc -Dmmtk.properties=$(PROJ_SRC_ROOT)/mmtk/java/vmkit.properties -disable-stubs -assume-compiled -llvm-lazy
- $(Verb) $(LOPT) -load=$(LibDir)/MMTKMagic$(SHLIBEXT) -std-compile-opts -LowerJavaRT -f $(JARNAME).bc -o $(JARNAME)-optimized.bc
- $(Verb) $(LLVMLD) -r -o $(LibDir)/FinalMMTk.bc $(LibDir)/MMTKAlloc.bc $(JARNAME)-optimized.bc $(LibDir)/MMTKRuntime.bc
- $(Verb) $(LOPT) -std-compile-opts $(LibDir)/FinalMMTk.bc -o $(LibDir)/FinalMMTk.bc
- $(Verb) $(LLC) -march=cpp -cppgen=function -cppfor=gcmalloc $(LibDir)/FinalMMTk.bc -o $(PROJ_SRC_ROOT)/mmtk/inline/MMTkInline.inc
-
-$(JARNAME).jar: $(shell find $(PROJ_SRC_ROOT)/mmtk/java/src -type f -name "*.java")
- $(Echo) Building $(BuildMode) $(JARNAME).jar $(notdir $@)
- $(Verb) $(ANT) -buildfile $(PROJ_OBJ_ROOT)/mmtk/java/build.xml
-
-endif
-
-endif
-clean-local::
- $(Verb) $(RM) -rf classes $(JARNAME).jar $(JARNAME).bc $(JARNAME)-optimized.bc
-endif
diff --git a/vmkit/README.txt b/vmkit/README.txt
deleted file mode 100644
index 21b1a58..0000000
--- a/vmkit/README.txt
+++ /dev/null
@@ -1,26 +0,0 @@
-//===---------------------------------------------------------------------===//
-// General notes
-//===---------------------------------------------------------------------===//
-
-VMKit is the composition of three libraries:
-1) MVM: threads, GCs, and JIT interface
-2) J3: a Java Virtual Machine implemented with MVM and LLVM
-3) N3: a CLI implementation with MVM and LLVM
-
-These are the options you should pass to the ./configure script
---with-llvmsrc: the source directory of LLVM
---with-llvmobj: the object directory of LLVM
---with-gnu-classpath-libs: GNU classpath libraries
---with-gnu-classpath-glibj: GNU classpath glibj.zip
---with-pnet-local-prefix: the local build of PNET
---with-pnetlib: PNET's mscorlib.dll
---with-mono: Mono's mscorlib.dll
---with-gc: use either gc-mmap or MMTk (requires --with-llvmgcc)
-
-Running make on the root tree will produce the following "tools":
-1) Debug|Release/bin/j3: running the J3 like any other JVM.
-2) Debug|Release/bin/n3-pnetlib: running N3 like CLR.
-2) Debug|Release/bin/vmkit: shell-like vm launcher.
-2) Debug|Release/bin/vmjc: ahead of time compiler for .class files.
-
-J3 also has a README note.
diff --git a/vmkit/autoconf/AutoRegen.sh b/vmkit/autoconf/AutoRegen.sh
deleted file mode 100755
index 2ab53d4..0000000
--- a/vmkit/autoconf/AutoRegen.sh
+++ /dev/null
@@ -1,52 +0,0 @@
-#!/bin/sh
-die () {
- echo "$@" 1>&2
- exit 1
-}
-test -d autoconf && test -f autoconf/configure.ac && cd autoconf
-test -f configure.ac || die "Can't find 'autoconf' dir; please cd into it first"
-autoconf --version | egrep '2\.[5-6][0-9]' > /dev/null
-if test $? -ne 0 ; then
- die "Your autoconf was not detected as being 2.5x or 2.6x"
-fi
-cwd=`pwd`
-if test -d ../../../autoconf/m4 ; then
- cd ../../../autoconf/m4
- llvm_m4=`pwd`
- llvm_src_root=../../..
- llvm_obj_root=../../..
- cd $cwd
-elif test -d ../../llvm/autoconf/m4 ; then
- cd ../../llvm/autoconf/m4
- llvm_m4=`pwd`
- llvm_src_root=../..
- llvm_obj_root=../..
- cd $cwd
-else
- while true ; do
- echo "LLVM source root not found."
- read -p "Enter full path to LLVM source:"
- if test -d "$REPLY/autoconf/m4" ; then
- llvm_src_root="$REPLY"
- llvm_m4="$REPLY/autoconf/m4"
- read -p "Enter full path to LLVM objects (empty for same as source):"
- if test -d "$REPLY" ; then
- llvm_obj_root="$REPLY"
- else
- llvm_obj_root="$llvm_src_root"
- fi
- break
- fi
- done
-fi
-# Patch the LLVM_ROOT in configure.ac, if it needs it
-cp configure.ac configure.bak
-sed -e "s#^LLVM_SRC_ROOT=.*#LLVM_SRC_ROOT=\"$llvm_src_root\"#" \
- -e "s#^LLVM_OBJ_ROOT=.*#LLVM_OBJ_ROOT=\"$llvm_obj_root\"#" configure.bak > configure.ac
-echo "Regenerating aclocal.m4 with aclocal"
-rm -f aclocal.m4
-aclocal -I $llvm_m4 -I "$llvm_m4/.." || die "aclocal failed"
-echo "Regenerating configure with autoconf 2.5x or 2.6x"
-autoconf --warnings=all -o ../configure configure.ac || die "autoconf failed"
-cd ..
-exit 0
diff --git a/vmkit/autoconf/config.guess b/vmkit/autoconf/config.guess
deleted file mode 100755
index 7d0185e..0000000
--- a/vmkit/autoconf/config.guess
+++ /dev/null
@@ -1,1447 +0,0 @@
-#! /bin/sh
-# Attempt to guess a canonical system name.
-# Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999,
-# 2000, 2001, 2002, 2003, 2004 Free Software Foundation, Inc.
-
-timestamp='2004-09-07'
-
-# This file is free software; you can redistribute it and/or modify it
-# under the terms of the GNU General Public License as published by
-# the Free Software Foundation; either version 2 of the License, or
-# (at your option) any later version.
-#
-# This program is distributed in the hope that it will be useful, but
-# WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-# General Public License for more details.
-#
-# You should have received a copy of the GNU General Public License
-# along with this program; if not, write to the Free Software
-# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
-#
-# As a special exception to the GNU General Public License, if you
-# distribute this file as part of a program that contains a
-# configuration script generated by Autoconf, you may include it under
-# the same distribution terms that you use for the rest of that program.
-
-# Originally written by Per Bothner <per@bothner.com>.
-# Please send patches to <config-patches@gnu.org>. Submit a context
-# diff and a properly formatted ChangeLog entry.
-#
-# This script attempts to guess a canonical system name similar to
-# config.sub. If it succeeds, it prints the system name on stdout, and
-# exits with 0. Otherwise, it exits with 1.
-#
-# The plan is that this can be called by configure scripts if you
-# don't specify an explicit build system type.
-
-me=`echo "$0" | sed -e 's,.*/,,'`
-
-usage="\
-Usage: $0 [OPTION]
-
-Output the configuration name of the system \`$me' is run on.
-
-Operation modes:
- -h, --help print this help, then exit
- -t, --time-stamp print date of last modification, then exit
- -v, --version print version number, then exit
-
-Report bugs and patches to <config-patches@gnu.org>."
-
-version="\
-GNU config.guess ($timestamp)
-
-Originally written by Per Bothner.
-Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004
-Free Software Foundation, Inc.
-
-This is free software; see the source for copying conditions. There is NO
-warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE."
-
-help="
-Try \`$me --help' for more information."
-
-# Parse command line
-while test $# -gt 0 ; do
- case $1 in
- --time-stamp | --time* | -t )
- echo "$timestamp" ; exit 0 ;;
- --version | -v )
- echo "$version" ; exit 0 ;;
- --help | --h* | -h )
- echo "$usage"; exit 0 ;;
- -- ) # Stop option processing
- shift; break ;;
- - ) # Use stdin as input.
- break ;;
- -* )
- echo "$me: invalid option $1$help" >&2
- exit 1 ;;
- * )
- break ;;
- esac
-done
-
-if test $# != 0; then
- echo "$me: too many arguments$help" >&2
- exit 1
-fi
-
-trap 'exit 1' 1 2 15
-
-# CC_FOR_BUILD -- compiler used by this script. Note that the use of a
-# compiler to aid in system detection is discouraged as it requires
-# temporary files to be created and, as you can see below, it is a
-# headache to deal with in a portable fashion.
-
-# Historically, `CC_FOR_BUILD' used to be named `HOST_CC'. We still
-# use `HOST_CC' if defined, but it is deprecated.
-
-# Portable tmp directory creation inspired by the Autoconf team.
-
-set_cc_for_build='
-trap "exitcode=\$?; (rm -f \$tmpfiles 2>/dev/null; rmdir \$tmp 2>/dev/null) && exit \$exitcode" 0 ;
-trap "rm -f \$tmpfiles 2>/dev/null; rmdir \$tmp 2>/dev/null; exit 1" 1 2 13 15 ;
-: ${TMPDIR=/tmp} ;
- { tmp=`(umask 077 && mktemp -d -q "$TMPDIR/cgXXXXXX") 2>/dev/null` && test -n "$tmp" && test -d "$tmp" ; } ||
- { test -n "$RANDOM" && tmp=$TMPDIR/cg$$-$RANDOM && (umask 077 && mkdir $tmp) ; } ||
- { tmp=$TMPDIR/cg-$$ && (umask 077 && mkdir $tmp) && echo "Warning: creating insecure temp directory" >&2 ; } ||
- { echo "$me: cannot create a temporary directory in $TMPDIR" >&2 ; exit 1 ; } ;
-dummy=$tmp/dummy ;
-tmpfiles="$dummy.c $dummy.o $dummy.rel $dummy" ;
-case $CC_FOR_BUILD,$HOST_CC,$CC in
- ,,) echo "int x;" > $dummy.c ;
- for c in cc gcc c89 c99 ; do
- if ($c -c -o $dummy.o $dummy.c) >/dev/null 2>&1 ; then
- CC_FOR_BUILD="$c"; break ;
- fi ;
- done ;
- if test x"$CC_FOR_BUILD" = x ; then
- CC_FOR_BUILD=no_compiler_found ;
- fi
- ;;
- ,,*) CC_FOR_BUILD=$CC ;;
- ,*,*) CC_FOR_BUILD=$HOST_CC ;;
-esac ;'
-
-# This is needed to find uname on a Pyramid OSx when run in the BSD universe.
-# (ghazi@noc.rutgers.edu 1994-08-24)
-if (test -f /.attbin/uname) >/dev/null 2>&1 ; then
- PATH=$PATH:/.attbin ; export PATH
-fi
-
-UNAME_MACHINE=`(uname -m) 2>/dev/null` || UNAME_MACHINE=unknown
-UNAME_RELEASE=`(uname -r) 2>/dev/null` || UNAME_RELEASE=unknown
-UNAME_SYSTEM=`(uname -s) 2>/dev/null` || UNAME_SYSTEM=unknown
-UNAME_VERSION=`(uname -v) 2>/dev/null` || UNAME_VERSION=unknown
-
-# Note: order is significant - the case branches are not exclusive.
-
-case "${UNAME_MACHINE}:${UNAME_SYSTEM}:${UNAME_RELEASE}:${UNAME_VERSION}" in
- *:NetBSD:*:*)
- # NetBSD (nbsd) targets should (where applicable) match one or
- # more of the tupples: *-*-netbsdelf*, *-*-netbsdaout*,
- # *-*-netbsdecoff* and *-*-netbsd*. For targets that recently
- # switched to ELF, *-*-netbsd* would select the old
- # object file format. This provides both forward
- # compatibility and a consistent mechanism for selecting the
- # object file format.
- #
- # Note: NetBSD doesn't particularly care about the vendor
- # portion of the name. We always set it to "unknown".
- sysctl="sysctl -n hw.machine_arch"
- UNAME_MACHINE_ARCH=`(/sbin/$sysctl 2>/dev/null || \
- /usr/sbin/$sysctl 2>/dev/null || echo unknown)`
- case "${UNAME_MACHINE_ARCH}" in
- armeb) machine=armeb-unknown ;;
- arm*) machine=arm-unknown ;;
- sh3el) machine=shl-unknown ;;
- sh3eb) machine=sh-unknown ;;
- *) machine=${UNAME_MACHINE_ARCH}-unknown ;;
- esac
- # The Operating System including object format, if it has switched
- # to ELF recently, or will in the future.
- case "${UNAME_MACHINE_ARCH}" in
- arm*|i386|m68k|ns32k|sh3*|sparc|vax)
- eval $set_cc_for_build
- if echo __ELF__ | $CC_FOR_BUILD -E - 2>/dev/null \
- | grep __ELF__ >/dev/null
- then
- # Once all utilities can be ECOFF (netbsdecoff) or a.out (netbsdaout).
- # Return netbsd for either. FIX?
- os=netbsd
- else
- os=netbsdelf
- fi
- ;;
- *)
- os=netbsd
- ;;
- esac
- # The OS release
- # Debian GNU/NetBSD machines have a different userland, and
- # thus, need a distinct triplet. However, they do not need
- # kernel version information, so it can be replaced with a
- # suitable tag, in the style of linux-gnu.
- case "${UNAME_VERSION}" in
- Debian*)
- release='-gnu'
- ;;
- *)
- release=`echo ${UNAME_RELEASE}|sed -e 's/[-_].*/\./'`
- ;;
- esac
- # Since CPU_TYPE-MANUFACTURER-KERNEL-OPERATING_SYSTEM:
- # contains redundant information, the shorter form:
- # CPU_TYPE-MANUFACTURER-OPERATING_SYSTEM is used.
- echo "${machine}-${os}${release}"
- exit 0 ;;
- amd64:OpenBSD:*:*)
- echo x86_64-unknown-openbsd${UNAME_RELEASE}
- exit 0 ;;
- amiga:OpenBSD:*:*)
- echo m68k-unknown-openbsd${UNAME_RELEASE}
- exit 0 ;;
- cats:OpenBSD:*:*)
- echo arm-unknown-openbsd${UNAME_RELEASE}
- exit 0 ;;
- hp300:OpenBSD:*:*)
- echo m68k-unknown-openbsd${UNAME_RELEASE}
- exit 0 ;;
- luna88k:OpenBSD:*:*)
- echo m88k-unknown-openbsd${UNAME_RELEASE}
- exit 0 ;;
- mac68k:OpenBSD:*:*)
- echo m68k-unknown-openbsd${UNAME_RELEASE}
- exit 0 ;;
- macppc:OpenBSD:*:*)
- echo powerpc-unknown-openbsd${UNAME_RELEASE}
- exit 0 ;;
- mvme68k:OpenBSD:*:*)
- echo m68k-unknown-openbsd${UNAME_RELEASE}
- exit 0 ;;
- mvme88k:OpenBSD:*:*)
- echo m88k-unknown-openbsd${UNAME_RELEASE}
- exit 0 ;;
- mvmeppc:OpenBSD:*:*)
- echo powerpc-unknown-openbsd${UNAME_RELEASE}
- exit 0 ;;
- sgi:OpenBSD:*:*)
- echo mips64-unknown-openbsd${UNAME_RELEASE}
- exit 0 ;;
- sun3:OpenBSD:*:*)
- echo m68k-unknown-openbsd${UNAME_RELEASE}
- exit 0 ;;
- *:OpenBSD:*:*)
- echo ${UNAME_MACHINE}-unknown-openbsd${UNAME_RELEASE}
- exit 0 ;;
- *:ekkoBSD:*:*)
- echo ${UNAME_MACHINE}-unknown-ekkobsd${UNAME_RELEASE}
- exit 0 ;;
- macppc:MirBSD:*:*)
- echo powerppc-unknown-mirbsd${UNAME_RELEASE}
- exit 0 ;;
- *:MirBSD:*:*)
- echo ${UNAME_MACHINE}-unknown-mirbsd${UNAME_RELEASE}
- exit 0 ;;
- alpha:OSF1:*:*)
- case $UNAME_RELEASE in
- *4.0)
- UNAME_RELEASE=`/usr/sbin/sizer -v | awk '{print $3}'`
- ;;
- *5.*)
- UNAME_RELEASE=`/usr/sbin/sizer -v | awk '{print $4}'`
- ;;
- esac
- # According to Compaq, /usr/sbin/psrinfo has been available on
- # OSF/1 and Tru64 systems produced since 1995. I hope that
- # covers most systems running today. This code pipes the CPU
- # types through head -n 1, so we only detect the type of CPU 0.
- ALPHA_CPU_TYPE=`/usr/sbin/psrinfo -v | sed -n -e 's/^ The alpha \(.*\) processor.*$/\1/p' | head -n 1`
- case "$ALPHA_CPU_TYPE" in
- "EV4 (21064)")
- UNAME_MACHINE="alpha" ;;
- "EV4.5 (21064)")
- UNAME_MACHINE="alpha" ;;
- "LCA4 (21066/21068)")
- UNAME_MACHINE="alpha" ;;
- "EV5 (21164)")
- UNAME_MACHINE="alphaev5" ;;
- "EV5.6 (21164A)")
- UNAME_MACHINE="alphaev56" ;;
- "EV5.6 (21164PC)")
- UNAME_MACHINE="alphapca56" ;;
- "EV5.7 (21164PC)")
- UNAME_MACHINE="alphapca57" ;;
- "EV6 (21264)")
- UNAME_MACHINE="alphaev6" ;;
- "EV6.7 (21264A)")
- UNAME_MACHINE="alphaev67" ;;
- "EV6.8CB (21264C)")
- UNAME_MACHINE="alphaev68" ;;
- "EV6.8AL (21264B)")
- UNAME_MACHINE="alphaev68" ;;
- "EV6.8CX (21264D)")
- UNAME_MACHINE="alphaev68" ;;
- "EV6.9A (21264/EV69A)")
- UNAME_MACHINE="alphaev69" ;;
- "EV7 (21364)")
- UNAME_MACHINE="alphaev7" ;;
- "EV7.9 (21364A)")
- UNAME_MACHINE="alphaev79" ;;
- esac
- # A Pn.n version is a patched version.
- # A Vn.n version is a released version.
- # A Tn.n version is a released field test version.
- # A Xn.n version is an unreleased experimental baselevel.
- # 1.2 uses "1.2" for uname -r.
- echo ${UNAME_MACHINE}-dec-osf`echo ${UNAME_RELEASE} | sed -e 's/^[PVTX]//' | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'`
- exit 0 ;;
- Alpha\ *:Windows_NT*:*)
- # How do we know it's Interix rather than the generic POSIX subsystem?
- # Should we change UNAME_MACHINE based on the output of uname instead
- # of the specific Alpha model?
- echo alpha-pc-interix
- exit 0 ;;
- 21064:Windows_NT:50:3)
- echo alpha-dec-winnt3.5
- exit 0 ;;
- Amiga*:UNIX_System_V:4.0:*)
- echo m68k-unknown-sysv4
- exit 0;;
- *:[Aa]miga[Oo][Ss]:*:*)
- echo ${UNAME_MACHINE}-unknown-amigaos
- exit 0 ;;
- *:[Mm]orph[Oo][Ss]:*:*)
- echo ${UNAME_MACHINE}-unknown-morphos
- exit 0 ;;
- *:OS/390:*:*)
- echo i370-ibm-openedition
- exit 0 ;;
- *:OS400:*:*)
- echo powerpc-ibm-os400
- exit 0 ;;
- arm:RISC*:1.[012]*:*|arm:riscix:1.[012]*:*)
- echo arm-acorn-riscix${UNAME_RELEASE}
- exit 0;;
- SR2?01:HI-UX/MPP:*:* | SR8000:HI-UX/MPP:*:*)
- echo hppa1.1-hitachi-hiuxmpp
- exit 0;;
- Pyramid*:OSx*:*:* | MIS*:OSx*:*:* | MIS*:SMP_DC-OSx*:*:*)
- # akee@wpdis03.wpafb.af.mil (Earle F. Ake) contributed MIS and NILE.
- if test "`(/bin/universe) 2>/dev/null`" = att ; then
- echo pyramid-pyramid-sysv3
- else
- echo pyramid-pyramid-bsd
- fi
- exit 0 ;;
- NILE*:*:*:dcosx)
- echo pyramid-pyramid-svr4
- exit 0 ;;
- DRS?6000:unix:4.0:6*)
- echo sparc-icl-nx6
- exit 0 ;;
- DRS?6000:UNIX_SV:4.2*:7*)
- case `/usr/bin/uname -p` in
- sparc) echo sparc-icl-nx7 && exit 0 ;;
- esac ;;
- sun4H:SunOS:5.*:*)
- echo sparc-hal-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'`
- exit 0 ;;
- sun4*:SunOS:5.*:* | tadpole*:SunOS:5.*:*)
- echo sparc-sun-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'`
- exit 0 ;;
- i86pc:SunOS:5.*:*)
- echo i386-pc-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'`
- exit 0 ;;
- sun4*:SunOS:6*:*)
- # According to config.sub, this is the proper way to canonicalize
- # SunOS6. Hard to guess exactly what SunOS6 will be like, but
- # it's likely to be more like Solaris than SunOS4.
- echo sparc-sun-solaris3`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'`
- exit 0 ;;
- sun4*:SunOS:*:*)
- case "`/usr/bin/arch -k`" in
- Series*|S4*)
- UNAME_RELEASE=`uname -v`
- ;;
- esac
- # Japanese Language versions have a version number like `4.1.3-JL'.
- echo sparc-sun-sunos`echo ${UNAME_RELEASE}|sed -e 's/-/_/'`
- exit 0 ;;
- sun3*:SunOS:*:*)
- echo m68k-sun-sunos${UNAME_RELEASE}
- exit 0 ;;
- sun*:*:4.2BSD:*)
- UNAME_RELEASE=`(sed 1q /etc/motd | awk '{print substr($5,1,3)}') 2>/dev/null`
- test "x${UNAME_RELEASE}" = "x" && UNAME_RELEASE=3
- case "`/bin/arch`" in
- sun3)
- echo m68k-sun-sunos${UNAME_RELEASE}
- ;;
- sun4)
- echo sparc-sun-sunos${UNAME_RELEASE}
- ;;
- esac
- exit 0 ;;
- aushp:SunOS:*:*)
- echo sparc-auspex-sunos${UNAME_RELEASE}
- exit 0 ;;
- # The situation for MiNT is a little confusing. The machine name
- # can be virtually everything (everything which is not
- # "atarist" or "atariste" at least should have a processor
- # > m68000). The system name ranges from "MiNT" over "FreeMiNT"
- # to the lowercase version "mint" (or "freemint"). Finally
- # the system name "TOS" denotes a system which is actually not
- # MiNT. But MiNT is downward compatible to TOS, so this should
- # be no problem.
- atarist[e]:*MiNT:*:* | atarist[e]:*mint:*:* | atarist[e]:*TOS:*:*)
- echo m68k-atari-mint${UNAME_RELEASE}
- exit 0 ;;
- atari*:*MiNT:*:* | atari*:*mint:*:* | atarist[e]:*TOS:*:*)
- echo m68k-atari-mint${UNAME_RELEASE}
- exit 0 ;;
- *falcon*:*MiNT:*:* | *falcon*:*mint:*:* | *falcon*:*TOS:*:*)
- echo m68k-atari-mint${UNAME_RELEASE}
- exit 0 ;;
- milan*:*MiNT:*:* | milan*:*mint:*:* | *milan*:*TOS:*:*)
- echo m68k-milan-mint${UNAME_RELEASE}
- exit 0 ;;
- hades*:*MiNT:*:* | hades*:*mint:*:* | *hades*:*TOS:*:*)
- echo m68k-hades-mint${UNAME_RELEASE}
- exit 0 ;;
- *:*MiNT:*:* | *:*mint:*:* | *:*TOS:*:*)
- echo m68k-unknown-mint${UNAME_RELEASE}
- exit 0 ;;
- m68k:machten:*:*)
- echo m68k-apple-machten${UNAME_RELEASE}
- exit 0 ;;
- powerpc:machten:*:*)
- echo powerpc-apple-machten${UNAME_RELEASE}
- exit 0 ;;
- RISC*:Mach:*:*)
- echo mips-dec-mach_bsd4.3
- exit 0 ;;
- RISC*:ULTRIX:*:*)
- echo mips-dec-ultrix${UNAME_RELEASE}
- exit 0 ;;
- VAX*:ULTRIX*:*:*)
- echo vax-dec-ultrix${UNAME_RELEASE}
- exit 0 ;;
- 2020:CLIX:*:* | 2430:CLIX:*:*)
- echo clipper-intergraph-clix${UNAME_RELEASE}
- exit 0 ;;
- mips:*:*:UMIPS | mips:*:*:RISCos)
- eval $set_cc_for_build
- sed 's/^ //' << EOF >$dummy.c
-#ifdef __cplusplus
-#include <stdio.h> /* for printf() prototype */
- int main (int argc, char *argv[]) {
-#else
- int main (argc, argv) int argc; char *argv[]; {
-#endif
- #if defined (host_mips) && defined (MIPSEB)
- #if defined (SYSTYPE_SYSV)
- printf ("mips-mips-riscos%ssysv\n", argv[1]); exit (0);
- #endif
- #if defined (SYSTYPE_SVR4)
- printf ("mips-mips-riscos%ssvr4\n", argv[1]); exit (0);
- #endif
- #if defined (SYSTYPE_BSD43) || defined(SYSTYPE_BSD)
- printf ("mips-mips-riscos%sbsd\n", argv[1]); exit (0);
- #endif
- #endif
- exit (-1);
- }
-EOF
- $CC_FOR_BUILD -o $dummy $dummy.c \
- && $dummy `echo "${UNAME_RELEASE}" | sed -n 's/\([0-9]*\).*/\1/p'` \
- && exit 0
- echo mips-mips-riscos${UNAME_RELEASE}
- exit 0 ;;
- Motorola:PowerMAX_OS:*:*)
- echo powerpc-motorola-powermax
- exit 0 ;;
- Motorola:*:4.3:PL8-*)
- echo powerpc-harris-powermax
- exit 0 ;;
- Night_Hawk:*:*:PowerMAX_OS | Synergy:PowerMAX_OS:*:*)
- echo powerpc-harris-powermax
- exit 0 ;;
- Night_Hawk:Power_UNIX:*:*)
- echo powerpc-harris-powerunix
- exit 0 ;;
- m88k:CX/UX:7*:*)
- echo m88k-harris-cxux7
- exit 0 ;;
- m88k:*:4*:R4*)
- echo m88k-motorola-sysv4
- exit 0 ;;
- m88k:*:3*:R3*)
- echo m88k-motorola-sysv3
- exit 0 ;;
- AViiON:dgux:*:*)
- # DG/UX returns AViiON for all architectures
- UNAME_PROCESSOR=`/usr/bin/uname -p`
- if [ $UNAME_PROCESSOR = mc88100 ] || [ $UNAME_PROCESSOR = mc88110 ]
- then
- if [ ${TARGET_BINARY_INTERFACE}x = m88kdguxelfx ] || \
- [ ${TARGET_BINARY_INTERFACE}x = x ]
- then
- echo m88k-dg-dgux${UNAME_RELEASE}
- else
- echo m88k-dg-dguxbcs${UNAME_RELEASE}
- fi
- else
- echo i586-dg-dgux${UNAME_RELEASE}
- fi
- exit 0 ;;
- M88*:DolphinOS:*:*) # DolphinOS (SVR3)
- echo m88k-dolphin-sysv3
- exit 0 ;;
- M88*:*:R3*:*)
- # Delta 88k system running SVR3
- echo m88k-motorola-sysv3
- exit 0 ;;
- XD88*:*:*:*) # Tektronix XD88 system running UTekV (SVR3)
- echo m88k-tektronix-sysv3
- exit 0 ;;
- Tek43[0-9][0-9]:UTek:*:*) # Tektronix 4300 system running UTek (BSD)
- echo m68k-tektronix-bsd
- exit 0 ;;
- *:IRIX*:*:*)
- echo mips-sgi-irix`echo ${UNAME_RELEASE}|sed -e 's/-/_/g'`
- exit 0 ;;
- ????????:AIX?:[12].1:2) # AIX 2.2.1 or AIX 2.1.1 is RT/PC AIX.
- echo romp-ibm-aix # uname -m gives an 8 hex-code CPU id
- exit 0 ;; # Note that: echo "'`uname -s`'" gives 'AIX '
- i*86:AIX:*:*)
- echo i386-ibm-aix
- exit 0 ;;
- ia64:AIX:*:*)
- if [ -x /usr/bin/oslevel ] ; then
- IBM_REV=`/usr/bin/oslevel`
- else
- IBM_REV=${UNAME_VERSION}.${UNAME_RELEASE}
- fi
- echo ${UNAME_MACHINE}-ibm-aix${IBM_REV}
- exit 0 ;;
- *:AIX:2:3)
- if grep bos325 /usr/include/stdio.h >/dev/null 2>&1; then
- eval $set_cc_for_build
- sed 's/^ //' << EOF >$dummy.c
- #include <sys/systemcfg.h>
-
- main()
- {
- if (!__power_pc())
- exit(1);
- puts("powerpc-ibm-aix3.2.5");
- exit(0);
- }
-EOF
- $CC_FOR_BUILD -o $dummy $dummy.c && $dummy && exit 0
- echo rs6000-ibm-aix3.2.5
- elif grep bos324 /usr/include/stdio.h >/dev/null 2>&1; then
- echo rs6000-ibm-aix3.2.4
- else
- echo rs6000-ibm-aix3.2
- fi
- exit 0 ;;
- *:AIX:*:[45])
- IBM_CPU_ID=`/usr/sbin/lsdev -C -c processor -S available | sed 1q | awk '{ print $1 }'`
- if /usr/sbin/lsattr -El ${IBM_CPU_ID} | grep ' POWER' >/dev/null 2>&1; then
- IBM_ARCH=rs6000
- else
- IBM_ARCH=powerpc
- fi
- if [ -x /usr/bin/oslevel ] ; then
- IBM_REV=`/usr/bin/oslevel`
- else
- IBM_REV=${UNAME_VERSION}.${UNAME_RELEASE}
- fi
- echo ${IBM_ARCH}-ibm-aix${IBM_REV}
- exit 0 ;;
- *:AIX:*:*)
- echo rs6000-ibm-aix
- exit 0 ;;
- ibmrt:4.4BSD:*|romp-ibm:BSD:*)
- echo romp-ibm-bsd4.4
- exit 0 ;;
- ibmrt:*BSD:*|romp-ibm:BSD:*) # covers RT/PC BSD and
- echo romp-ibm-bsd${UNAME_RELEASE} # 4.3 with uname added to
- exit 0 ;; # report: romp-ibm BSD 4.3
- *:BOSX:*:*)
- echo rs6000-bull-bosx
- exit 0 ;;
- DPX/2?00:B.O.S.:*:*)
- echo m68k-bull-sysv3
- exit 0 ;;
- 9000/[34]??:4.3bsd:1.*:*)
- echo m68k-hp-bsd
- exit 0 ;;
- hp300:4.4BSD:*:* | 9000/[34]??:4.3bsd:2.*:*)
- echo m68k-hp-bsd4.4
- exit 0 ;;
- 9000/[34678]??:HP-UX:*:*)
- HPUX_REV=`echo ${UNAME_RELEASE}|sed -e 's/[^.]*.[0B]*//'`
- case "${UNAME_MACHINE}" in
- 9000/31? ) HP_ARCH=m68000 ;;
- 9000/[34]?? ) HP_ARCH=m68k ;;
- 9000/[678][0-9][0-9])
- if [ -x /usr/bin/getconf ]; then
- sc_cpu_version=`/usr/bin/getconf SC_CPU_VERSION 2>/dev/null`
- sc_kernel_bits=`/usr/bin/getconf SC_KERNEL_BITS 2>/dev/null`
- case "${sc_cpu_version}" in
- 523) HP_ARCH="hppa1.0" ;; # CPU_PA_RISC1_0
- 528) HP_ARCH="hppa1.1" ;; # CPU_PA_RISC1_1
- 532) # CPU_PA_RISC2_0
- case "${sc_kernel_bits}" in
- 32) HP_ARCH="hppa2.0n" ;;
- 64) HP_ARCH="hppa2.0w" ;;
- '') HP_ARCH="hppa2.0" ;; # HP-UX 10.20
- esac ;;
- esac
- fi
- if [ "${HP_ARCH}" = "" ]; then
- eval $set_cc_for_build
- sed 's/^ //' << EOF >$dummy.c
-
- #define _HPUX_SOURCE
- #include <stdlib.h>
- #include <unistd.h>
-
- int main ()
- {
- #if defined(_SC_KERNEL_BITS)
- long bits = sysconf(_SC_KERNEL_BITS);
- #endif
- long cpu = sysconf (_SC_CPU_VERSION);
-
- switch (cpu)
- {
- case CPU_PA_RISC1_0: puts ("hppa1.0"); break;
- case CPU_PA_RISC1_1: puts ("hppa1.1"); break;
- case CPU_PA_RISC2_0:
- #if defined(_SC_KERNEL_BITS)
- switch (bits)
- {
- case 64: puts ("hppa2.0w"); break;
- case 32: puts ("hppa2.0n"); break;
- default: puts ("hppa2.0"); break;
- } break;
- #else /* !defined(_SC_KERNEL_BITS) */
- puts ("hppa2.0"); break;
- #endif
- default: puts ("hppa1.0"); break;
- }
- exit (0);
- }
-EOF
- (CCOPTS= $CC_FOR_BUILD -o $dummy $dummy.c 2>/dev/null) && HP_ARCH=`$dummy`
- test -z "$HP_ARCH" && HP_ARCH=hppa
- fi ;;
- esac
- if [ ${HP_ARCH} = "hppa2.0w" ]
- then
- # avoid double evaluation of $set_cc_for_build
- test -n "$CC_FOR_BUILD" || eval $set_cc_for_build
- if echo __LP64__ | (CCOPTS= $CC_FOR_BUILD -E -) | grep __LP64__ >/dev/null
- then
- HP_ARCH="hppa2.0w"
- else
- HP_ARCH="hppa64"
- fi
- fi
- echo ${HP_ARCH}-hp-hpux${HPUX_REV}
- exit 0 ;;
- ia64:HP-UX:*:*)
- HPUX_REV=`echo ${UNAME_RELEASE}|sed -e 's/[^.]*.[0B]*//'`
- echo ia64-hp-hpux${HPUX_REV}
- exit 0 ;;
- 3050*:HI-UX:*:*)
- eval $set_cc_for_build
- sed 's/^ //' << EOF >$dummy.c
- #include <unistd.h>
- int
- main ()
- {
- long cpu = sysconf (_SC_CPU_VERSION);
- /* The order matters, because CPU_IS_HP_MC68K erroneously returns
- true for CPU_PA_RISC1_0. CPU_IS_PA_RISC returns correct
- results, however. */
- if (CPU_IS_PA_RISC (cpu))
- {
- switch (cpu)
- {
- case CPU_PA_RISC1_0: puts ("hppa1.0-hitachi-hiuxwe2"); break;
- case CPU_PA_RISC1_1: puts ("hppa1.1-hitachi-hiuxwe2"); break;
- case CPU_PA_RISC2_0: puts ("hppa2.0-hitachi-hiuxwe2"); break;
- default: puts ("hppa-hitachi-hiuxwe2"); break;
- }
- }
- else if (CPU_IS_HP_MC68K (cpu))
- puts ("m68k-hitachi-hiuxwe2");
- else puts ("unknown-hitachi-hiuxwe2");
- exit (0);
- }
-EOF
- $CC_FOR_BUILD -o $dummy $dummy.c && $dummy && exit 0
- echo unknown-hitachi-hiuxwe2
- exit 0 ;;
- 9000/7??:4.3bsd:*:* | 9000/8?[79]:4.3bsd:*:* )
- echo hppa1.1-hp-bsd
- exit 0 ;;
- 9000/8??:4.3bsd:*:*)
- echo hppa1.0-hp-bsd
- exit 0 ;;
- *9??*:MPE/iX:*:* | *3000*:MPE/iX:*:*)
- echo hppa1.0-hp-mpeix
- exit 0 ;;
- hp7??:OSF1:*:* | hp8?[79]:OSF1:*:* )
- echo hppa1.1-hp-osf
- exit 0 ;;
- hp8??:OSF1:*:*)
- echo hppa1.0-hp-osf
- exit 0 ;;
- i*86:OSF1:*:*)
- if [ -x /usr/sbin/sysversion ] ; then
- echo ${UNAME_MACHINE}-unknown-osf1mk
- else
- echo ${UNAME_MACHINE}-unknown-osf1
- fi
- exit 0 ;;
- parisc*:Lites*:*:*)
- echo hppa1.1-hp-lites
- exit 0 ;;
- C1*:ConvexOS:*:* | convex:ConvexOS:C1*:*)
- echo c1-convex-bsd
- exit 0 ;;
- C2*:ConvexOS:*:* | convex:ConvexOS:C2*:*)
- if getsysinfo -f scalar_acc
- then echo c32-convex-bsd
- else echo c2-convex-bsd
- fi
- exit 0 ;;
- C34*:ConvexOS:*:* | convex:ConvexOS:C34*:*)
- echo c34-convex-bsd
- exit 0 ;;
- C38*:ConvexOS:*:* | convex:ConvexOS:C38*:*)
- echo c38-convex-bsd
- exit 0 ;;
- C4*:ConvexOS:*:* | convex:ConvexOS:C4*:*)
- echo c4-convex-bsd
- exit 0 ;;
- CRAY*Y-MP:*:*:*)
- echo ymp-cray-unicos${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/'
- exit 0 ;;
- CRAY*[A-Z]90:*:*:*)
- echo ${UNAME_MACHINE}-cray-unicos${UNAME_RELEASE} \
- | sed -e 's/CRAY.*\([A-Z]90\)/\1/' \
- -e y/ABCDEFGHIJKLMNOPQRSTUVWXYZ/abcdefghijklmnopqrstuvwxyz/ \
- -e 's/\.[^.]*$/.X/'
- exit 0 ;;
- CRAY*TS:*:*:*)
- echo t90-cray-unicos${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/'
- exit 0 ;;
- CRAY*T3E:*:*:*)
- echo alphaev5-cray-unicosmk${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/'
- exit 0 ;;
- CRAY*SV1:*:*:*)
- echo sv1-cray-unicos${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/'
- exit 0 ;;
- *:UNICOS/mp:*:*)
- echo craynv-cray-unicosmp${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/'
- exit 0 ;;
- F30[01]:UNIX_System_V:*:* | F700:UNIX_System_V:*:*)
- FUJITSU_PROC=`uname -m | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'`
- FUJITSU_SYS=`uname -p | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz' | sed -e 's/\///'`
- FUJITSU_REL=`echo ${UNAME_RELEASE} | sed -e 's/ /_/'`
- echo "${FUJITSU_PROC}-fujitsu-${FUJITSU_SYS}${FUJITSU_REL}"
- exit 0 ;;
- 5000:UNIX_System_V:4.*:*)
- FUJITSU_SYS=`uname -p | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz' | sed -e 's/\///'`
- FUJITSU_REL=`echo ${UNAME_RELEASE} | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz' | sed -e 's/ /_/'`
- echo "sparc-fujitsu-${FUJITSU_SYS}${FUJITSU_REL}"
- exit 0 ;;
- i*86:BSD/386:*:* | i*86:BSD/OS:*:* | *:Ascend\ Embedded/OS:*:*)
- echo ${UNAME_MACHINE}-pc-bsdi${UNAME_RELEASE}
- exit 0 ;;
- sparc*:BSD/OS:*:*)
- echo sparc-unknown-bsdi${UNAME_RELEASE}
- exit 0 ;;
- *:BSD/OS:*:*)
- echo ${UNAME_MACHINE}-unknown-bsdi${UNAME_RELEASE}
- exit 0 ;;
- *:FreeBSD:*:*)
- echo ${UNAME_MACHINE}-unknown-freebsd`echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'`
- exit 0 ;;
- i*:CYGWIN*:*)
- echo ${UNAME_MACHINE}-pc-cygwin
- exit 0 ;;
- i*:MINGW*:*)
- echo ${UNAME_MACHINE}-pc-mingw32
- exit 0 ;;
- i*:PW*:*)
- echo ${UNAME_MACHINE}-pc-pw32
- exit 0 ;;
- x86:Interix*:[34]*)
- echo i586-pc-interix${UNAME_RELEASE}|sed -e 's/\..*//'
- exit 0 ;;
- [345]86:Windows_95:* | [345]86:Windows_98:* | [345]86:Windows_NT:*)
- echo i${UNAME_MACHINE}-pc-mks
- exit 0 ;;
- i*:Windows_NT*:* | Pentium*:Windows_NT*:*)
- # How do we know it's Interix rather than the generic POSIX subsystem?
- # It also conflicts with pre-2.0 versions of AT&T UWIN. Should we
- # UNAME_MACHINE based on the output of uname instead of i386?
- echo i586-pc-interix
- exit 0 ;;
- i*:UWIN*:*)
- echo ${UNAME_MACHINE}-pc-uwin
- exit 0 ;;
- p*:CYGWIN*:*)
- echo powerpcle-unknown-cygwin
- exit 0 ;;
- prep*:SunOS:5.*:*)
- echo powerpcle-unknown-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'`
- exit 0 ;;
- *:GNU:*:*)
- # the GNU system
- echo `echo ${UNAME_MACHINE}|sed -e 's,[-/].*$,,'`-unknown-gnu`echo ${UNAME_RELEASE}|sed -e 's,/.*$,,'`
- exit 0 ;;
- *:GNU/*:*:*)
- # other systems with GNU libc and userland
- echo ${UNAME_MACHINE}-unknown-`echo ${UNAME_SYSTEM} | sed 's,^[^/]*/,,' | tr '[A-Z]' '[a-z]'``echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'`-gnu
- exit 0 ;;
- i*86:Minix:*:*)
- echo ${UNAME_MACHINE}-pc-minix
- exit 0 ;;
- arm*:Linux:*:*)
- echo ${UNAME_MACHINE}-unknown-linux-gnu
- exit 0 ;;
- cris:Linux:*:*)
- echo cris-axis-linux-gnu
- exit 0 ;;
- crisv32:Linux:*:*)
- echo crisv32-axis-linux-gnu
- exit 0 ;;
- frv:Linux:*:*)
- echo frv-unknown-linux-gnu
- exit 0 ;;
- ia64:Linux:*:*)
- echo ${UNAME_MACHINE}-unknown-linux-gnu
- exit 0 ;;
- m32r*:Linux:*:*)
- echo ${UNAME_MACHINE}-unknown-linux-gnu
- exit 0 ;;
- m68*:Linux:*:*)
- echo ${UNAME_MACHINE}-unknown-linux-gnu
- exit 0 ;;
- mips:Linux:*:*)
- eval $set_cc_for_build
- sed 's/^ //' << EOF >$dummy.c
- #undef CPU
- #undef mips
- #undef mipsel
- #if defined(__MIPSEL__) || defined(__MIPSEL) || defined(_MIPSEL) || defined(MIPSEL)
- CPU=mipsel
- #else
- #if defined(__MIPSEB__) || defined(__MIPSEB) || defined(_MIPSEB) || defined(MIPSEB)
- CPU=mips
- #else
- CPU=
- #endif
- #endif
-EOF
- eval `$CC_FOR_BUILD -E $dummy.c 2>/dev/null | grep ^CPU=`
- test x"${CPU}" != x && echo "${CPU}-unknown-linux-gnu" && exit 0
- ;;
- mips64:Linux:*:*)
- eval $set_cc_for_build
- sed 's/^ //' << EOF >$dummy.c
- #undef CPU
- #undef mips64
- #undef mips64el
- #if defined(__MIPSEL__) || defined(__MIPSEL) || defined(_MIPSEL) || defined(MIPSEL)
- CPU=mips64el
- #else
- #if defined(__MIPSEB__) || defined(__MIPSEB) || defined(_MIPSEB) || defined(MIPSEB)
- CPU=mips64
- #else
- CPU=
- #endif
- #endif
-EOF
- eval `$CC_FOR_BUILD -E $dummy.c 2>/dev/null | grep ^CPU=`
- test x"${CPU}" != x && echo "${CPU}-unknown-linux-gnu" && exit 0
- ;;
- ppc:Linux:*:*)
- echo powerpc-unknown-linux-gnu
- exit 0 ;;
- ppc64:Linux:*:*)
- echo powerpc64-unknown-linux-gnu
- exit 0 ;;
- alpha:Linux:*:*)
- case `sed -n '/^cpu model/s/^.*: \(.*\)/\1/p' < /proc/cpuinfo` in
- EV5) UNAME_MACHINE=alphaev5 ;;
- EV56) UNAME_MACHINE=alphaev56 ;;
- PCA56) UNAME_MACHINE=alphapca56 ;;
- PCA57) UNAME_MACHINE=alphapca56 ;;
- EV6) UNAME_MACHINE=alphaev6 ;;
- EV67) UNAME_MACHINE=alphaev67 ;;
- EV68*) UNAME_MACHINE=alphaev68 ;;
- esac
- objdump --private-headers /bin/sh | grep ld.so.1 >/dev/null
- if test "$?" = 0 ; then LIBC="libc1" ; else LIBC="" ; fi
- echo ${UNAME_MACHINE}-unknown-linux-gnu${LIBC}
- exit 0 ;;
- parisc:Linux:*:* | hppa:Linux:*:*)
- # Look for CPU level
- case `grep '^cpu[^a-z]*:' /proc/cpuinfo 2>/dev/null | cut -d' ' -f2` in
- PA7*) echo hppa1.1-unknown-linux-gnu ;;
- PA8*) echo hppa2.0-unknown-linux-gnu ;;
- *) echo hppa-unknown-linux-gnu ;;
- esac
- exit 0 ;;
- parisc64:Linux:*:* | hppa64:Linux:*:*)
- echo hppa64-unknown-linux-gnu
- exit 0 ;;
- s390:Linux:*:* | s390x:Linux:*:*)
- echo ${UNAME_MACHINE}-ibm-linux
- exit 0 ;;
- sh64*:Linux:*:*)
- echo ${UNAME_MACHINE}-unknown-linux-gnu
- exit 0 ;;
- sh*:Linux:*:*)
- echo ${UNAME_MACHINE}-unknown-linux-gnu
- exit 0 ;;
- sparc:Linux:*:* | sparc64:Linux:*:*)
- echo ${UNAME_MACHINE}-unknown-linux-gnu
- exit 0 ;;
- x86_64:Linux:*:*)
- echo x86_64-unknown-linux-gnu
- exit 0 ;;
- i*86:Linux:*:*)
- # The BFD linker knows what the default object file format is, so
- # first see if it will tell us. cd to the root directory to prevent
- # problems with other programs or directories called `ld' in the path.
- # Set LC_ALL=C to ensure ld outputs messages in English.
- ld_supported_targets=`cd /; LC_ALL=C ld --help 2>&1 \
- | sed -ne '/supported targets:/!d
- s/[ ][ ]*/ /g
- s/.*supported targets: *//
- s/ .*//
- p'`
- case "$ld_supported_targets" in
- elf32-i386)
- TENTATIVE="${UNAME_MACHINE}-pc-linux-gnu"
- ;;
- a.out-i386-linux)
- echo "${UNAME_MACHINE}-pc-linux-gnuaout"
- exit 0 ;;
- coff-i386)
- echo "${UNAME_MACHINE}-pc-linux-gnucoff"
- exit 0 ;;
- "")
- # Either a pre-BFD a.out linker (linux-gnuoldld) or
- # one that does not give us useful --help.
- echo "${UNAME_MACHINE}-pc-linux-gnuoldld"
- exit 0 ;;
- esac
- # Determine whether the default compiler is a.out or elf
- eval $set_cc_for_build
- sed 's/^ //' << EOF >$dummy.c
- #include <features.h>
- #ifdef __ELF__
- # ifdef __GLIBC__
- # if __GLIBC__ >= 2
- LIBC=gnu
- # else
- LIBC=gnulibc1
- # endif
- # else
- LIBC=gnulibc1
- # endif
- #else
- #ifdef __INTEL_COMPILER
- LIBC=gnu
- #else
- LIBC=gnuaout
- #endif
- #endif
- #ifdef __dietlibc__
- LIBC=dietlibc
- #endif
-EOF
- eval `$CC_FOR_BUILD -E $dummy.c 2>/dev/null | grep ^LIBC=`
- test x"${LIBC}" != x && echo "${UNAME_MACHINE}-pc-linux-${LIBC}" && exit 0
- test x"${TENTATIVE}" != x && echo "${TENTATIVE}" && exit 0
- ;;
- i*86:DYNIX/ptx:4*:*)
- # ptx 4.0 does uname -s correctly, with DYNIX/ptx in there.
- # earlier versions are messed up and put the nodename in both
- # sysname and nodename.
- echo i386-sequent-sysv4
- exit 0 ;;
- i*86:UNIX_SV:4.2MP:2.*)
- # Unixware is an offshoot of SVR4, but it has its own version
- # number series starting with 2...
- # I am not positive that other SVR4 systems won't match this,
- # I just have to hope. -- rms.
- # Use sysv4.2uw... so that sysv4* matches it.
- echo ${UNAME_MACHINE}-pc-sysv4.2uw${UNAME_VERSION}
- exit 0 ;;
- i*86:OS/2:*:*)
- # If we were able to find `uname', then EMX Unix compatibility
- # is probably installed.
- echo ${UNAME_MACHINE}-pc-os2-emx
- exit 0 ;;
- i*86:XTS-300:*:STOP)
- echo ${UNAME_MACHINE}-unknown-stop
- exit 0 ;;
- i*86:atheos:*:*)
- echo ${UNAME_MACHINE}-unknown-atheos
- exit 0 ;;
- i*86:syllable:*:*)
- echo ${UNAME_MACHINE}-pc-syllable
- exit 0 ;;
- i*86:LynxOS:2.*:* | i*86:LynxOS:3.[01]*:* | i*86:LynxOS:4.0*:*)
- echo i386-unknown-lynxos${UNAME_RELEASE}
- exit 0 ;;
- i*86:*DOS:*:*)
- echo ${UNAME_MACHINE}-pc-msdosdjgpp
- exit 0 ;;
- i*86:*:4.*:* | i*86:SYSTEM_V:4.*:*)
- UNAME_REL=`echo ${UNAME_RELEASE} | sed 's/\/MP$//'`
- if grep Novell /usr/include/link.h >/dev/null 2>/dev/null; then
- echo ${UNAME_MACHINE}-univel-sysv${UNAME_REL}
- else
- echo ${UNAME_MACHINE}-pc-sysv${UNAME_REL}
- fi
- exit 0 ;;
- i*86:*:5:[78]*)
- case `/bin/uname -X | grep "^Machine"` in
- *486*) UNAME_MACHINE=i486 ;;
- *Pentium) UNAME_MACHINE=i586 ;;
- *Pent*|*Celeron) UNAME_MACHINE=i686 ;;
- esac
- echo ${UNAME_MACHINE}-unknown-sysv${UNAME_RELEASE}${UNAME_SYSTEM}${UNAME_VERSION}
- exit 0 ;;
- i*86:*:3.2:*)
- if test -f /usr/options/cb.name; then
- UNAME_REL=`sed -n 's/.*Version //p' </usr/options/cb.name`
- echo ${UNAME_MACHINE}-pc-isc$UNAME_REL
- elif /bin/uname -X 2>/dev/null >/dev/null ; then
- UNAME_REL=`(/bin/uname -X|grep Release|sed -e 's/.*= //')`
- (/bin/uname -X|grep i80486 >/dev/null) && UNAME_MACHINE=i486
- (/bin/uname -X|grep '^Machine.*Pentium' >/dev/null) \
- && UNAME_MACHINE=i586
- (/bin/uname -X|grep '^Machine.*Pent *II' >/dev/null) \
- && UNAME_MACHINE=i686
- (/bin/uname -X|grep '^Machine.*Pentium Pro' >/dev/null) \
- && UNAME_MACHINE=i686
- echo ${UNAME_MACHINE}-pc-sco$UNAME_REL
- else
- echo ${UNAME_MACHINE}-pc-sysv32
- fi
- exit 0 ;;
- pc:*:*:*)
- # Left here for compatibility:
- # uname -m prints for DJGPP always 'pc', but it prints nothing about
- # the processor, so we play safe by assuming i386.
- echo i386-pc-msdosdjgpp
- exit 0 ;;
- Intel:Mach:3*:*)
- echo i386-pc-mach3
- exit 0 ;;
- paragon:*:*:*)
- echo i860-intel-osf1
- exit 0 ;;
- i860:*:4.*:*) # i860-SVR4
- if grep Stardent /usr/include/sys/uadmin.h >/dev/null 2>&1 ; then
- echo i860-stardent-sysv${UNAME_RELEASE} # Stardent Vistra i860-SVR4
- else # Add other i860-SVR4 vendors below as they are discovered.
- echo i860-unknown-sysv${UNAME_RELEASE} # Unknown i860-SVR4
- fi
- exit 0 ;;
- mini*:CTIX:SYS*5:*)
- # "miniframe"
- echo m68010-convergent-sysv
- exit 0 ;;
- mc68k:UNIX:SYSTEM5:3.51m)
- echo m68k-convergent-sysv
- exit 0 ;;
- M680?0:D-NIX:5.3:*)
- echo m68k-diab-dnix
- exit 0 ;;
- M68*:*:R3V[5678]*:*)
- test -r /sysV68 && echo 'm68k-motorola-sysv' && exit 0 ;;
- 3[345]??:*:4.0:3.0 | 3[34]??A:*:4.0:3.0 | 3[34]??,*:*:4.0:3.0 | 3[34]??/*:*:4.0:3.0 | 4400:*:4.0:3.0 | 4850:*:4.0:3.0 | SKA40:*:4.0:3.0 | SDS2:*:4.0:3.0 | SHG2:*:4.0:3.0 | S7501*:*:4.0:3.0)
- OS_REL=''
- test -r /etc/.relid \
- && OS_REL=.`sed -n 's/[^ ]* [^ ]* \([0-9][0-9]\).*/\1/p' < /etc/.relid`
- /bin/uname -p 2>/dev/null | grep 86 >/dev/null \
- && echo i486-ncr-sysv4.3${OS_REL} && exit 0
- /bin/uname -p 2>/dev/null | /bin/grep entium >/dev/null \
- && echo i586-ncr-sysv4.3${OS_REL} && exit 0 ;;
- 3[34]??:*:4.0:* | 3[34]??,*:*:4.0:*)
- /bin/uname -p 2>/dev/null | grep 86 >/dev/null \
- && echo i486-ncr-sysv4 && exit 0 ;;
- m68*:LynxOS:2.*:* | m68*:LynxOS:3.0*:*)
- echo m68k-unknown-lynxos${UNAME_RELEASE}
- exit 0 ;;
- mc68030:UNIX_System_V:4.*:*)
- echo m68k-atari-sysv4
- exit 0 ;;
- TSUNAMI:LynxOS:2.*:*)
- echo sparc-unknown-lynxos${UNAME_RELEASE}
- exit 0 ;;
- rs6000:LynxOS:2.*:*)
- echo rs6000-unknown-lynxos${UNAME_RELEASE}
- exit 0 ;;
- PowerPC:LynxOS:2.*:* | PowerPC:LynxOS:3.[01]*:* | PowerPC:LynxOS:4.0*:*)
- echo powerpc-unknown-lynxos${UNAME_RELEASE}
- exit 0 ;;
- SM[BE]S:UNIX_SV:*:*)
- echo mips-dde-sysv${UNAME_RELEASE}
- exit 0 ;;
- RM*:ReliantUNIX-*:*:*)
- echo mips-sni-sysv4
- exit 0 ;;
- RM*:SINIX-*:*:*)
- echo mips-sni-sysv4
- exit 0 ;;
- *:SINIX-*:*:*)
- if uname -p 2>/dev/null >/dev/null ; then
- UNAME_MACHINE=`(uname -p) 2>/dev/null`
- echo ${UNAME_MACHINE}-sni-sysv4
- else
- echo ns32k-sni-sysv
- fi
- exit 0 ;;
- PENTIUM:*:4.0*:*) # Unisys `ClearPath HMP IX 4000' SVR4/MP effort
- # says <Richard.M.Bartel@ccMail.Census.GOV>
- echo i586-unisys-sysv4
- exit 0 ;;
- *:UNIX_System_V:4*:FTX*)
- # From Gerald Hewes <hewes@openmarket.com>.
- # How about differentiating between stratus architectures? -djm
- echo hppa1.1-stratus-sysv4
- exit 0 ;;
- *:*:*:FTX*)
- # From seanf@swdc.stratus.com.
- echo i860-stratus-sysv4
- exit 0 ;;
- *:VOS:*:*)
- # From Paul.Green@stratus.com.
- echo hppa1.1-stratus-vos
- exit 0 ;;
- mc68*:A/UX:*:*)
- echo m68k-apple-aux${UNAME_RELEASE}
- exit 0 ;;
- news*:NEWS-OS:6*:*)
- echo mips-sony-newsos6
- exit 0 ;;
- R[34]000:*System_V*:*:* | R4000:UNIX_SYSV:*:* | R*000:UNIX_SV:*:*)
- if [ -d /usr/nec ]; then
- echo mips-nec-sysv${UNAME_RELEASE}
- else
- echo mips-unknown-sysv${UNAME_RELEASE}
- fi
- exit 0 ;;
- BeBox:BeOS:*:*) # BeOS running on hardware made by Be, PPC only.
- echo powerpc-be-beos
- exit 0 ;;
- BeMac:BeOS:*:*) # BeOS running on Mac or Mac clone, PPC only.
- echo powerpc-apple-beos
- exit 0 ;;
- BePC:BeOS:*:*) # BeOS running on Intel PC compatible.
- echo i586-pc-beos
- exit 0 ;;
- SX-4:SUPER-UX:*:*)
- echo sx4-nec-superux${UNAME_RELEASE}
- exit 0 ;;
- SX-5:SUPER-UX:*:*)
- echo sx5-nec-superux${UNAME_RELEASE}
- exit 0 ;;
- SX-6:SUPER-UX:*:*)
- echo sx6-nec-superux${UNAME_RELEASE}
- exit 0 ;;
- Power*:Rhapsody:*:*)
- echo powerpc-apple-rhapsody${UNAME_RELEASE}
- exit 0 ;;
- *:Rhapsody:*:*)
- echo ${UNAME_MACHINE}-apple-rhapsody${UNAME_RELEASE}
- exit 0 ;;
- *:Darwin:*:*)
- UNAME_PROCESSOR=`uname -p` || UNAME_PROCESSOR=unknown
- case $UNAME_PROCESSOR in
- *86) UNAME_PROCESSOR=i686 ;;
- unknown) UNAME_PROCESSOR=powerpc ;;
- esac
- echo ${UNAME_PROCESSOR}-apple-darwin${UNAME_RELEASE}
- exit 0 ;;
- *:procnto*:*:* | *:QNX:[0123456789]*:*)
- UNAME_PROCESSOR=`uname -p`
- if test "$UNAME_PROCESSOR" = "x86"; then
- UNAME_PROCESSOR=i386
- UNAME_MACHINE=pc
- fi
- echo ${UNAME_PROCESSOR}-${UNAME_MACHINE}-nto-qnx${UNAME_RELEASE}
- exit 0 ;;
- *:QNX:*:4*)
- echo i386-pc-qnx
- exit 0 ;;
- NSR-?:NONSTOP_KERNEL:*:*)
- echo nsr-tandem-nsk${UNAME_RELEASE}
- exit 0 ;;
- *:NonStop-UX:*:*)
- echo mips-compaq-nonstopux
- exit 0 ;;
- BS2000:POSIX*:*:*)
- echo bs2000-siemens-sysv
- exit 0 ;;
- DS/*:UNIX_System_V:*:*)
- echo ${UNAME_MACHINE}-${UNAME_SYSTEM}-${UNAME_RELEASE}
- exit 0 ;;
- *:Plan9:*:*)
- # "uname -m" is not consistent, so use $cputype instead. 386
- # is converted to i386 for consistency with other x86
- # operating systems.
- if test "$cputype" = "386"; then
- UNAME_MACHINE=i386
- else
- UNAME_MACHINE="$cputype"
- fi
- echo ${UNAME_MACHINE}-unknown-plan9
- exit 0 ;;
- *:TOPS-10:*:*)
- echo pdp10-unknown-tops10
- exit 0 ;;
- *:TENEX:*:*)
- echo pdp10-unknown-tenex
- exit 0 ;;
- KS10:TOPS-20:*:* | KL10:TOPS-20:*:* | TYPE4:TOPS-20:*:*)
- echo pdp10-dec-tops20
- exit 0 ;;
- XKL-1:TOPS-20:*:* | TYPE5:TOPS-20:*:*)
- echo pdp10-xkl-tops20
- exit 0 ;;
- *:TOPS-20:*:*)
- echo pdp10-unknown-tops20
- exit 0 ;;
- *:ITS:*:*)
- echo pdp10-unknown-its
- exit 0 ;;
- SEI:*:*:SEIUX)
- echo mips-sei-seiux${UNAME_RELEASE}
- exit 0 ;;
- *:DragonFly:*:*)
- echo ${UNAME_MACHINE}-unknown-dragonfly`echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'`
- exit 0 ;;
- *:*VMS:*:*)
- UNAME_MACHINE=`(uname -p) 2>/dev/null`
- case "${UNAME_MACHINE}" in
- A*) echo alpha-dec-vms && exit 0 ;;
- I*) echo ia64-dec-vms && exit 0 ;;
- V*) echo vax-dec-vms && exit 0 ;;
- esac
-esac
-
-#echo '(No uname command or uname output not recognized.)' 1>&2
-#echo "${UNAME_MACHINE}:${UNAME_SYSTEM}:${UNAME_RELEASE}:${UNAME_VERSION}" 1>&2
-
-eval $set_cc_for_build
-cat >$dummy.c <<EOF
-#ifdef _SEQUENT_
-# include <sys/types.h>
-# include <sys/utsname.h>
-#endif
-main ()
-{
-#if defined (sony)
-#if defined (MIPSEB)
- /* BFD wants "bsd" instead of "newsos". Perhaps BFD should be changed,
- I don't know.... */
- printf ("mips-sony-bsd\n"); exit (0);
-#else
-#include <sys/param.h>
- printf ("m68k-sony-newsos%s\n",
-#ifdef NEWSOS4
- "4"
-#else
- ""
-#endif
- ); exit (0);
-#endif
-#endif
-
-#if defined (__arm) && defined (__acorn) && defined (__unix)
- printf ("arm-acorn-riscix"); exit (0);
-#endif
-
-#if defined (hp300) && !defined (hpux)
- printf ("m68k-hp-bsd\n"); exit (0);
-#endif
-
-#if defined (NeXT)
-#if !defined (__ARCHITECTURE__)
-#define __ARCHITECTURE__ "m68k"
-#endif
- int version;
- version=`(hostinfo | sed -n 's/.*NeXT Mach \([0-9]*\).*/\1/p') 2>/dev/null`;
- if (version < 4)
- printf ("%s-next-nextstep%d\n", __ARCHITECTURE__, version);
- else
- printf ("%s-next-openstep%d\n", __ARCHITECTURE__, version);
- exit (0);
-#endif
-
-#if defined (MULTIMAX) || defined (n16)
-#if defined (UMAXV)
- printf ("ns32k-encore-sysv\n"); exit (0);
-#else
-#if defined (CMU)
- printf ("ns32k-encore-mach\n"); exit (0);
-#else
- printf ("ns32k-encore-bsd\n"); exit (0);
-#endif
-#endif
-#endif
-
-#if defined (__386BSD__)
- printf ("i386-pc-bsd\n"); exit (0);
-#endif
-
-#if defined (sequent)
-#if defined (i386)
- printf ("i386-sequent-dynix\n"); exit (0);
-#endif
-#if defined (ns32000)
- printf ("ns32k-sequent-dynix\n"); exit (0);
-#endif
-#endif
-
-#if defined (_SEQUENT_)
- struct utsname un;
-
- uname(&un);
-
- if (strncmp(un.version, "V2", 2) == 0) {
- printf ("i386-sequent-ptx2\n"); exit (0);
- }
- if (strncmp(un.version, "V1", 2) == 0) { /* XXX is V1 correct? */
- printf ("i386-sequent-ptx1\n"); exit (0);
- }
- printf ("i386-sequent-ptx\n"); exit (0);
-
-#endif
-
-#if defined (vax)
-# if !defined (ultrix)
-# include <sys/param.h>
-# if defined (BSD)
-# if BSD == 43
- printf ("vax-dec-bsd4.3\n"); exit (0);
-# else
-# if BSD == 199006
- printf ("vax-dec-bsd4.3reno\n"); exit (0);
-# else
- printf ("vax-dec-bsd\n"); exit (0);
-# endif
-# endif
-# else
- printf ("vax-dec-bsd\n"); exit (0);
-# endif
-# else
- printf ("vax-dec-ultrix\n"); exit (0);
-# endif
-#endif
-
-#if defined (alliant) && defined (i860)
- printf ("i860-alliant-bsd\n"); exit (0);
-#endif
-
- exit (1);
-}
-EOF
-
-$CC_FOR_BUILD -o $dummy $dummy.c 2>/dev/null && $dummy && exit 0
-
-# Apollos put the system type in the environment.
-
-test -d /usr/apollo && { echo ${ISP}-apollo-${SYSTYPE}; exit 0; }
-
-# Convex versions that predate uname can use getsysinfo(1)
-
-if [ -x /usr/convex/getsysinfo ]
-then
- case `getsysinfo -f cpu_type` in
- c1*)
- echo c1-convex-bsd
- exit 0 ;;
- c2*)
- if getsysinfo -f scalar_acc
- then echo c32-convex-bsd
- else echo c2-convex-bsd
- fi
- exit 0 ;;
- c34*)
- echo c34-convex-bsd
- exit 0 ;;
- c38*)
- echo c38-convex-bsd
- exit 0 ;;
- c4*)
- echo c4-convex-bsd
- exit 0 ;;
- esac
-fi
-
-cat >&2 <<EOF
-$0: unable to guess system type
-
-This script, last modified $timestamp, has failed to recognize
-the operating system you are using. It is advised that you
-download the most up to date version of the config scripts from
-
- ftp://ftp.gnu.org/pub/gnu/config/
-
-If the version you run ($0) is already up to date, please
-send the following data and any information you think might be
-pertinent to <config-patches@gnu.org> in order to provide the needed
-information to handle your system.
-
-config.guess timestamp = $timestamp
-
-uname -m = `(uname -m) 2>/dev/null || echo unknown`
-uname -r = `(uname -r) 2>/dev/null || echo unknown`
-uname -s = `(uname -s) 2>/dev/null || echo unknown`
-uname -v = `(uname -v) 2>/dev/null || echo unknown`
-
-/usr/bin/uname -p = `(/usr/bin/uname -p) 2>/dev/null`
-/bin/uname -X = `(/bin/uname -X) 2>/dev/null`
-
-hostinfo = `(hostinfo) 2>/dev/null`
-/bin/universe = `(/bin/universe) 2>/dev/null`
-/usr/bin/arch -k = `(/usr/bin/arch -k) 2>/dev/null`
-/bin/arch = `(/bin/arch) 2>/dev/null`
-/usr/bin/oslevel = `(/usr/bin/oslevel) 2>/dev/null`
-/usr/convex/getsysinfo = `(/usr/convex/getsysinfo) 2>/dev/null`
-
-UNAME_MACHINE = ${UNAME_MACHINE}
-UNAME_RELEASE = ${UNAME_RELEASE}
-UNAME_SYSTEM = ${UNAME_SYSTEM}
-UNAME_VERSION = ${UNAME_VERSION}
-EOF
-
-exit 1
-
-# Local variables:
-# eval: (add-hook 'write-file-hooks 'time-stamp)
-# time-stamp-start: "timestamp='"
-# time-stamp-format: "%:y-%02m-%02d"
-# time-stamp-end: "'"
-# End:
diff --git a/vmkit/autoconf/config.sub b/vmkit/autoconf/config.sub
deleted file mode 100755
index edb6b66..0000000
--- a/vmkit/autoconf/config.sub
+++ /dev/null
@@ -1,1555 +0,0 @@
-#! /bin/sh
-# Configuration validation subroutine script.
-# Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999,
-# 2000, 2001, 2002, 2003, 2004 Free Software Foundation, Inc.
-
-timestamp='2004-08-29'
-
-# This file is (in principle) common to ALL GNU software.
-# The presence of a machine in this file suggests that SOME GNU software
-# can handle that machine. It does not imply ALL GNU software can.
-#
-# This file is free software; you can redistribute it and/or modify
-# it under the terms of the GNU General Public License as published by
-# the Free Software Foundation; either version 2 of the License, or
-# (at your option) any later version.
-#
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-# GNU General Public License for more details.
-#
-# You should have received a copy of the GNU General Public License
-# along with this program; if not, write to the Free Software
-# Foundation, Inc., 59 Temple Place - Suite 330,
-# Boston, MA 02111-1307, USA.
-
-# As a special exception to the GNU General Public License, if you
-# distribute this file as part of a program that contains a
-# configuration script generated by Autoconf, you may include it under
-# the same distribution terms that you use for the rest of that program.
-
-# Please send patches to <config-patches@gnu.org>. Submit a context
-# diff and a properly formatted ChangeLog entry.
-#
-# Configuration subroutine to validate and canonicalize a configuration type.
-# Supply the specified configuration type as an argument.
-# If it is invalid, we print an error message on stderr and exit with code 1.
-# Otherwise, we print the canonical config type on stdout and succeed.
-
-# This file is supposed to be the same for all GNU packages
-# and recognize all the CPU types, system types and aliases
-# that are meaningful with *any* GNU software.
-# Each package is responsible for reporting which valid configurations
-# it does not support. The user should be able to distinguish
-# a failure to support a valid configuration from a meaningless
-# configuration.
-
-# The goal of this file is to map all the various variations of a given
-# machine specification into a single specification in the form:
-# CPU_TYPE-MANUFACTURER-OPERATING_SYSTEM
-# or in some cases, the newer four-part form:
-# CPU_TYPE-MANUFACTURER-KERNEL-OPERATING_SYSTEM
-# It is wrong to echo any other type of specification.
-
-me=`echo "$0" | sed -e 's,.*/,,'`
-
-usage="\
-Usage: $0 [OPTION] CPU-MFR-OPSYS
- $0 [OPTION] ALIAS
-
-Canonicalize a configuration name.
-
-Operation modes:
- -h, --help print this help, then exit
- -t, --time-stamp print date of last modification, then exit
- -v, --version print version number, then exit
-
-Report bugs and patches to <config-patches@gnu.org>."
-
-version="\
-GNU config.sub ($timestamp)
-
-Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004
-Free Software Foundation, Inc.
-
-This is free software; see the source for copying conditions. There is NO
-warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE."
-
-help="
-Try \`$me --help' for more information."
-
-# Parse command line
-while test $# -gt 0 ; do
- case $1 in
- --time-stamp | --time* | -t )
- echo "$timestamp" ; exit 0 ;;
- --version | -v )
- echo "$version" ; exit 0 ;;
- --help | --h* | -h )
- echo "$usage"; exit 0 ;;
- -- ) # Stop option processing
- shift; break ;;
- - ) # Use stdin as input.
- break ;;
- -* )
- echo "$me: invalid option $1$help"
- exit 1 ;;
-
- *local*)
- # First pass through any local machine types.
- echo $1
- exit 0;;
-
- * )
- break ;;
- esac
-done
-
-case $# in
- 0) echo "$me: missing argument$help" >&2
- exit 1;;
- 1) ;;
- *) echo "$me: too many arguments$help" >&2
- exit 1;;
-esac
-
-# Separate what the user gave into CPU-COMPANY and OS or KERNEL-OS (if any).
-# Here we must recognize all the valid KERNEL-OS combinations.
-maybe_os=`echo $1 | sed 's/^\(.*\)-\([^-]*-[^-]*\)$/\2/'`
-case $maybe_os in
- nto-qnx* | linux-gnu* | linux-dietlibc | linux-uclibc* | uclinux-uclibc* | uclinux-gnu* | \
- kfreebsd*-gnu* | knetbsd*-gnu* | netbsd*-gnu* | storm-chaos* | os2-emx* | rtmk-nova*)
- os=-$maybe_os
- basic_machine=`echo $1 | sed 's/^\(.*\)-\([^-]*-[^-]*\)$/\1/'`
- ;;
- *)
- basic_machine=`echo $1 | sed 's/-[^-]*$//'`
- if [ $basic_machine != $1 ]
- then os=`echo $1 | sed 's/.*-/-/'`
- else os=; fi
- ;;
-esac
-
-### Let's recognize common machines as not being operating systems so
-### that things like config.sub decstation-3100 work. We also
-### recognize some manufacturers as not being operating systems, so we
-### can provide default operating systems below.
-case $os in
- -sun*os*)
- # Prevent following clause from handling this invalid input.
- ;;
- -dec* | -mips* | -sequent* | -encore* | -pc532* | -sgi* | -sony* | \
- -att* | -7300* | -3300* | -delta* | -motorola* | -sun[234]* | \
- -unicom* | -ibm* | -next | -hp | -isi* | -apollo | -altos* | \
- -convergent* | -ncr* | -news | -32* | -3600* | -3100* | -hitachi* |\
- -c[123]* | -convex* | -sun | -crds | -omron* | -dg | -ultra | -tti* | \
- -harris | -dolphin | -highlevel | -gould | -cbm | -ns | -masscomp | \
- -apple | -axis | -knuth | -cray)
- os=
- basic_machine=$1
- ;;
- -sim | -cisco | -oki | -wec | -winbond)
- os=
- basic_machine=$1
- ;;
- -scout)
- ;;
- -wrs)
- os=-vxworks
- basic_machine=$1
- ;;
- -chorusos*)
- os=-chorusos
- basic_machine=$1
- ;;
- -chorusrdb)
- os=-chorusrdb
- basic_machine=$1
- ;;
- -hiux*)
- os=-hiuxwe2
- ;;
- -sco5)
- os=-sco3.2v5
- basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
- ;;
- -sco4)
- os=-sco3.2v4
- basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
- ;;
- -sco3.2.[4-9]*)
- os=`echo $os | sed -e 's/sco3.2./sco3.2v/'`
- basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
- ;;
- -sco3.2v[4-9]*)
- # Don't forget version if it is 3.2v4 or newer.
- basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
- ;;
- -sco*)
- os=-sco3.2v2
- basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
- ;;
- -udk*)
- basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
- ;;
- -isc)
- os=-isc2.2
- basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
- ;;
- -clix*)
- basic_machine=clipper-intergraph
- ;;
- -isc*)
- basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
- ;;
- -lynx*)
- os=-lynxos
- ;;
- -ptx*)
- basic_machine=`echo $1 | sed -e 's/86-.*/86-sequent/'`
- ;;
- -windowsnt*)
- os=`echo $os | sed -e 's/windowsnt/winnt/'`
- ;;
- -psos*)
- os=-psos
- ;;
- -mint | -mint[0-9]*)
- basic_machine=m68k-atari
- os=-mint
- ;;
-esac
-
-# Decode aliases for certain CPU-COMPANY combinations.
-case $basic_machine in
- # Recognize the basic CPU types without company name.
- # Some are omitted here because they have special meanings below.
- 1750a | 580 \
- | a29k \
- | alpha | alphaev[4-8] | alphaev56 | alphaev6[78] | alphapca5[67] \
- | alpha64 | alpha64ev[4-8] | alpha64ev56 | alpha64ev6[78] | alpha64pca5[67] \
- | am33_2.0 \
- | arc | arm | arm[bl]e | arme[lb] | armv[2345] | armv[345][lb] | avr \
- | c4x | clipper \
- | d10v | d30v | dlx | dsp16xx \
- | fr30 | frv \
- | h8300 | h8500 | hppa | hppa1.[01] | hppa2.0 | hppa2.0[nw] | hppa64 \
- | i370 | i860 | i960 | ia64 \
- | ip2k | iq2000 \
- | m32r | m32rle | m68000 | m68k | m88k | mcore \
- | mips | mipsbe | mipseb | mipsel | mipsle \
- | mips16 \
- | mips64 | mips64el \
- | mips64vr | mips64vrel \
- | mips64orion | mips64orionel \
- | mips64vr4100 | mips64vr4100el \
- | mips64vr4300 | mips64vr4300el \
- | mips64vr5000 | mips64vr5000el \
- | mipsisa32 | mipsisa32el \
- | mipsisa32r2 | mipsisa32r2el \
- | mipsisa64 | mipsisa64el \
- | mipsisa64r2 | mipsisa64r2el \
- | mipsisa64sb1 | mipsisa64sb1el \
- | mipsisa64sr71k | mipsisa64sr71kel \
- | mipstx39 | mipstx39el \
- | mn10200 | mn10300 \
- | msp430 \
- | ns16k | ns32k \
- | openrisc | or32 \
- | pdp10 | pdp11 | pj | pjl \
- | powerpc | powerpc64 | powerpc64le | powerpcle | ppcbe \
- | pyramid \
- | sh | sh[1234] | sh[23]e | sh[34]eb | shbe | shle | sh[1234]le | sh3ele \
- | sh64 | sh64le \
- | sparc | sparc64 | sparc86x | sparclet | sparclite | sparcv8 | sparcv9 | sparcv9b \
- | strongarm \
- | tahoe | thumb | tic4x | tic80 | tron \
- | v850 | v850e \
- | we32k \
- | x86 | xscale | xstormy16 | xtensa \
- | z8k)
- basic_machine=$basic_machine-unknown
- ;;
- m6811 | m68hc11 | m6812 | m68hc12)
- # Motorola 68HC11/12.
- basic_machine=$basic_machine-unknown
- os=-none
- ;;
- m88110 | m680[12346]0 | m683?2 | m68360 | m5200 | v70 | w65 | z8k)
- ;;
-
- # We use `pc' rather than `unknown'
- # because (1) that's what they normally are, and
- # (2) the word "unknown" tends to confuse beginning users.
- i*86 | x86_64)
- basic_machine=$basic_machine-pc
- ;;
- # Object if more than one company name word.
- *-*-*)
- echo Invalid configuration \`$1\': machine \`$basic_machine\' not recognized 1>&2
- exit 1
- ;;
- # Recognize the basic CPU types with company name.
- 580-* \
- | a29k-* \
- | alpha-* | alphaev[4-8]-* | alphaev56-* | alphaev6[78]-* \
- | alpha64-* | alpha64ev[4-8]-* | alpha64ev56-* | alpha64ev6[78]-* \
- | alphapca5[67]-* | alpha64pca5[67]-* | arc-* \
- | arm-* | armbe-* | armle-* | armeb-* | armv*-* \
- | avr-* \
- | bs2000-* \
- | c[123]* | c30-* | [cjt]90-* | c4x-* | c54x-* | c55x-* | c6x-* \
- | clipper-* | craynv-* | cydra-* \
- | d10v-* | d30v-* | dlx-* \
- | elxsi-* \
- | f30[01]-* | f700-* | fr30-* | frv-* | fx80-* \
- | h8300-* | h8500-* \
- | hppa-* | hppa1.[01]-* | hppa2.0-* | hppa2.0[nw]-* | hppa64-* \
- | i*86-* | i860-* | i960-* | ia64-* \
- | ip2k-* | iq2000-* \
- | m32r-* | m32rle-* \
- | m68000-* | m680[012346]0-* | m68360-* | m683?2-* | m68k-* \
- | m88110-* | m88k-* | mcore-* \
- | mips-* | mipsbe-* | mipseb-* | mipsel-* | mipsle-* \
- | mips16-* \
- | mips64-* | mips64el-* \
- | mips64vr-* | mips64vrel-* \
- | mips64orion-* | mips64orionel-* \
- | mips64vr4100-* | mips64vr4100el-* \
- | mips64vr4300-* | mips64vr4300el-* \
- | mips64vr5000-* | mips64vr5000el-* \
- | mipsisa32-* | mipsisa32el-* \
- | mipsisa32r2-* | mipsisa32r2el-* \
- | mipsisa64-* | mipsisa64el-* \
- | mipsisa64r2-* | mipsisa64r2el-* \
- | mipsisa64sb1-* | mipsisa64sb1el-* \
- | mipsisa64sr71k-* | mipsisa64sr71kel-* \
- | mipstx39-* | mipstx39el-* \
- | mmix-* \
- | msp430-* \
- | none-* | np1-* | ns16k-* | ns32k-* \
- | orion-* \
- | pdp10-* | pdp11-* | pj-* | pjl-* | pn-* | power-* \
- | powerpc-* | powerpc64-* | powerpc64le-* | powerpcle-* | ppcbe-* \
- | pyramid-* \
- | romp-* | rs6000-* \
- | sh-* | sh[1234]-* | sh[23]e-* | sh[34]eb-* | shbe-* \
- | shle-* | sh[1234]le-* | sh3ele-* | sh64-* | sh64le-* \
- | sparc-* | sparc64-* | sparc86x-* | sparclet-* | sparclite-* \
- | sparcv8-* | sparcv9-* | sparcv9b-* | strongarm-* | sv1-* | sx?-* \
- | tahoe-* | thumb-* \
- | tic30-* | tic4x-* | tic54x-* | tic55x-* | tic6x-* | tic80-* \
- | tron-* \
- | v850-* | v850e-* | vax-* \
- | we32k-* \
- | x86-* | x86_64-* | xps100-* | xscale-* | xstormy16-* \
- | xtensa-* \
- | ymp-* \
- | z8k-*)
- ;;
- # Recognize the various machine names and aliases which stand
- # for a CPU type and a company and sometimes even an OS.
- 386bsd)
- basic_machine=i386-unknown
- os=-bsd
- ;;
- 3b1 | 7300 | 7300-att | att-7300 | pc7300 | safari | unixpc)
- basic_machine=m68000-att
- ;;
- 3b*)
- basic_machine=we32k-att
- ;;
- a29khif)
- basic_machine=a29k-amd
- os=-udi
- ;;
- abacus)
- basic_machine=abacus-unknown
- ;;
- adobe68k)
- basic_machine=m68010-adobe
- os=-scout
- ;;
- alliant | fx80)
- basic_machine=fx80-alliant
- ;;
- altos | altos3068)
- basic_machine=m68k-altos
- ;;
- am29k)
- basic_machine=a29k-none
- os=-bsd
- ;;
- amd64)
- basic_machine=x86_64-pc
- ;;
- amd64-*)
- basic_machine=x86_64-`echo $basic_machine | sed 's/^[^-]*-//'`
- ;;
- amdahl)
- basic_machine=580-amdahl
- os=-sysv
- ;;
- amiga | amiga-*)
- basic_machine=m68k-unknown
- ;;
- amigaos | amigados)
- basic_machine=m68k-unknown
- os=-amigaos
- ;;
- amigaunix | amix)
- basic_machine=m68k-unknown
- os=-sysv4
- ;;
- apollo68)
- basic_machine=m68k-apollo
- os=-sysv
- ;;
- apollo68bsd)
- basic_machine=m68k-apollo
- os=-bsd
- ;;
- aux)
- basic_machine=m68k-apple
- os=-aux
- ;;
- balance)
- basic_machine=ns32k-sequent
- os=-dynix
- ;;
- c90)
- basic_machine=c90-cray
- os=-unicos
- ;;
- convex-c1)
- basic_machine=c1-convex
- os=-bsd
- ;;
- convex-c2)
- basic_machine=c2-convex
- os=-bsd
- ;;
- convex-c32)
- basic_machine=c32-convex
- os=-bsd
- ;;
- convex-c34)
- basic_machine=c34-convex
- os=-bsd
- ;;
- convex-c38)
- basic_machine=c38-convex
- os=-bsd
- ;;
- cray | j90)
- basic_machine=j90-cray
- os=-unicos
- ;;
- craynv)
- basic_machine=craynv-cray
- os=-unicosmp
- ;;
- cr16c)
- basic_machine=cr16c-unknown
- os=-elf
- ;;
- crds | unos)
- basic_machine=m68k-crds
- ;;
- crisv32 | crisv32-* | etraxfs*)
- basic_machine=crisv32-axis
- ;;
- cris | cris-* | etrax*)
- basic_machine=cris-axis
- ;;
- crx)
- basic_machine=crx-unknown
- os=-elf
- ;;
- da30 | da30-*)
- basic_machine=m68k-da30
- ;;
- decstation | decstation-3100 | pmax | pmax-* | pmin | dec3100 | decstatn)
- basic_machine=mips-dec
- ;;
- decsystem10* | dec10*)
- basic_machine=pdp10-dec
- os=-tops10
- ;;
- decsystem20* | dec20*)
- basic_machine=pdp10-dec
- os=-tops20
- ;;
- delta | 3300 | motorola-3300 | motorola-delta \
- | 3300-motorola | delta-motorola)
- basic_machine=m68k-motorola
- ;;
- delta88)
- basic_machine=m88k-motorola
- os=-sysv3
- ;;
- dpx20 | dpx20-*)
- basic_machine=rs6000-bull
- os=-bosx
- ;;
- dpx2* | dpx2*-bull)
- basic_machine=m68k-bull
- os=-sysv3
- ;;
- ebmon29k)
- basic_machine=a29k-amd
- os=-ebmon
- ;;
- elxsi)
- basic_machine=elxsi-elxsi
- os=-bsd
- ;;
- encore | umax | mmax)
- basic_machine=ns32k-encore
- ;;
- es1800 | OSE68k | ose68k | ose | OSE)
- basic_machine=m68k-ericsson
- os=-ose
- ;;
- fx2800)
- basic_machine=i860-alliant
- ;;
- genix)
- basic_machine=ns32k-ns
- ;;
- gmicro)
- basic_machine=tron-gmicro
- os=-sysv
- ;;
- go32)
- basic_machine=i386-pc
- os=-go32
- ;;
- h3050r* | hiux*)
- basic_machine=hppa1.1-hitachi
- os=-hiuxwe2
- ;;
- h8300hms)
- basic_machine=h8300-hitachi
- os=-hms
- ;;
- h8300xray)
- basic_machine=h8300-hitachi
- os=-xray
- ;;
- h8500hms)
- basic_machine=h8500-hitachi
- os=-hms
- ;;
- harris)
- basic_machine=m88k-harris
- os=-sysv3
- ;;
- hp300-*)
- basic_machine=m68k-hp
- ;;
- hp300bsd)
- basic_machine=m68k-hp
- os=-bsd
- ;;
- hp300hpux)
- basic_machine=m68k-hp
- os=-hpux
- ;;
- hp3k9[0-9][0-9] | hp9[0-9][0-9])
- basic_machine=hppa1.0-hp
- ;;
- hp9k2[0-9][0-9] | hp9k31[0-9])
- basic_machine=m68000-hp
- ;;
- hp9k3[2-9][0-9])
- basic_machine=m68k-hp
- ;;
- hp9k6[0-9][0-9] | hp6[0-9][0-9])
- basic_machine=hppa1.0-hp
- ;;
- hp9k7[0-79][0-9] | hp7[0-79][0-9])
- basic_machine=hppa1.1-hp
- ;;
- hp9k78[0-9] | hp78[0-9])
- # FIXME: really hppa2.0-hp
- basic_machine=hppa1.1-hp
- ;;
- hp9k8[67]1 | hp8[67]1 | hp9k80[24] | hp80[24] | hp9k8[78]9 | hp8[78]9 | hp9k893 | hp893)
- # FIXME: really hppa2.0-hp
- basic_machine=hppa1.1-hp
- ;;
- hp9k8[0-9][13679] | hp8[0-9][13679])
- basic_machine=hppa1.1-hp
- ;;
- hp9k8[0-9][0-9] | hp8[0-9][0-9])
- basic_machine=hppa1.0-hp
- ;;
- hppa-next)
- os=-nextstep3
- ;;
- hppaosf)
- basic_machine=hppa1.1-hp
- os=-osf
- ;;
- hppro)
- basic_machine=hppa1.1-hp
- os=-proelf
- ;;
- i370-ibm* | ibm*)
- basic_machine=i370-ibm
- ;;
-# I'm not sure what "Sysv32" means. Should this be sysv3.2?
- i*86v32)
- basic_machine=`echo $1 | sed -e 's/86.*/86-pc/'`
- os=-sysv32
- ;;
- i*86v4*)
- basic_machine=`echo $1 | sed -e 's/86.*/86-pc/'`
- os=-sysv4
- ;;
- i*86v)
- basic_machine=`echo $1 | sed -e 's/86.*/86-pc/'`
- os=-sysv
- ;;
- i*86sol2)
- basic_machine=`echo $1 | sed -e 's/86.*/86-pc/'`
- os=-solaris2
- ;;
- i386mach)
- basic_machine=i386-mach
- os=-mach
- ;;
- i386-vsta | vsta)
- basic_machine=i386-unknown
- os=-vsta
- ;;
- iris | iris4d)
- basic_machine=mips-sgi
- case $os in
- -irix*)
- ;;
- *)
- os=-irix4
- ;;
- esac
- ;;
- isi68 | isi)
- basic_machine=m68k-isi
- os=-sysv
- ;;
- m88k-omron*)
- basic_machine=m88k-omron
- ;;
- magnum | m3230)
- basic_machine=mips-mips
- os=-sysv
- ;;
- merlin)
- basic_machine=ns32k-utek
- os=-sysv
- ;;
- mingw32)
- basic_machine=i386-pc
- os=-mingw32
- ;;
- miniframe)
- basic_machine=m68000-convergent
- ;;
- *mint | -mint[0-9]* | *MiNT | *MiNT[0-9]*)
- basic_machine=m68k-atari
- os=-mint
- ;;
- mips3*-*)
- basic_machine=`echo $basic_machine | sed -e 's/mips3/mips64/'`
- ;;
- mips3*)
- basic_machine=`echo $basic_machine | sed -e 's/mips3/mips64/'`-unknown
- ;;
- monitor)
- basic_machine=m68k-rom68k
- os=-coff
- ;;
- morphos)
- basic_machine=powerpc-unknown
- os=-morphos
- ;;
- msdos)
- basic_machine=i386-pc
- os=-msdos
- ;;
- mvs)
- basic_machine=i370-ibm
- os=-mvs
- ;;
- ncr3000)
- basic_machine=i486-ncr
- os=-sysv4
- ;;
- netbsd386)
- basic_machine=i386-unknown
- os=-netbsd
- ;;
- netwinder)
- basic_machine=armv4l-rebel
- os=-linux
- ;;
- news | news700 | news800 | news900)
- basic_machine=m68k-sony
- os=-newsos
- ;;
- news1000)
- basic_machine=m68030-sony
- os=-newsos
- ;;
- news-3600 | risc-news)
- basic_machine=mips-sony
- os=-newsos
- ;;
- necv70)
- basic_machine=v70-nec
- os=-sysv
- ;;
- next | m*-next )
- basic_machine=m68k-next
- case $os in
- -nextstep* )
- ;;
- -ns2*)
- os=-nextstep2
- ;;
- *)
- os=-nextstep3
- ;;
- esac
- ;;
- nh3000)
- basic_machine=m68k-harris
- os=-cxux
- ;;
- nh[45]000)
- basic_machine=m88k-harris
- os=-cxux
- ;;
- nindy960)
- basic_machine=i960-intel
- os=-nindy
- ;;
- mon960)
- basic_machine=i960-intel
- os=-mon960
- ;;
- nonstopux)
- basic_machine=mips-compaq
- os=-nonstopux
- ;;
- np1)
- basic_machine=np1-gould
- ;;
- nsr-tandem)
- basic_machine=nsr-tandem
- ;;
- op50n-* | op60c-*)
- basic_machine=hppa1.1-oki
- os=-proelf
- ;;
- or32 | or32-*)
- basic_machine=or32-unknown
- os=-coff
- ;;
- os400)
- basic_machine=powerpc-ibm
- os=-os400
- ;;
- OSE68000 | ose68000)
- basic_machine=m68000-ericsson
- os=-ose
- ;;
- os68k)
- basic_machine=m68k-none
- os=-os68k
- ;;
- pa-hitachi)
- basic_machine=hppa1.1-hitachi
- os=-hiuxwe2
- ;;
- paragon)
- basic_machine=i860-intel
- os=-osf
- ;;
- pbd)
- basic_machine=sparc-tti
- ;;
- pbb)
- basic_machine=m68k-tti
- ;;
- pc532 | pc532-*)
- basic_machine=ns32k-pc532
- ;;
- pentium | p5 | k5 | k6 | nexgen | viac3)
- basic_machine=i586-pc
- ;;
- pentiumpro | p6 | 6x86 | athlon | athlon_*)
- basic_machine=i686-pc
- ;;
- pentiumii | pentium2 | pentiumiii | pentium3)
- basic_machine=i686-pc
- ;;
- pentium4)
- basic_machine=i786-pc
- ;;
- pentium-* | p5-* | k5-* | k6-* | nexgen-* | viac3-*)
- basic_machine=i586-`echo $basic_machine | sed 's/^[^-]*-//'`
- ;;
- pentiumpro-* | p6-* | 6x86-* | athlon-*)
- basic_machine=i686-`echo $basic_machine | sed 's/^[^-]*-//'`
- ;;
- pentiumii-* | pentium2-* | pentiumiii-* | pentium3-*)
- basic_machine=i686-`echo $basic_machine | sed 's/^[^-]*-//'`
- ;;
- pentium4-*)
- basic_machine=i786-`echo $basic_machine | sed 's/^[^-]*-//'`
- ;;
- pn)
- basic_machine=pn-gould
- ;;
- power) basic_machine=power-ibm
- ;;
- ppc) basic_machine=powerpc-unknown
- ;;
- ppc-*) basic_machine=powerpc-`echo $basic_machine | sed 's/^[^-]*-//'`
- ;;
- ppcle | powerpclittle | ppc-le | powerpc-little)
- basic_machine=powerpcle-unknown
- ;;
- ppcle-* | powerpclittle-*)
- basic_machine=powerpcle-`echo $basic_machine | sed 's/^[^-]*-//'`
- ;;
- ppc64) basic_machine=powerpc64-unknown
- ;;
- ppc64-*) basic_machine=powerpc64-`echo $basic_machine | sed 's/^[^-]*-//'`
- ;;
- ppc64le | powerpc64little | ppc64-le | powerpc64-little)
- basic_machine=powerpc64le-unknown
- ;;
- ppc64le-* | powerpc64little-*)
- basic_machine=powerpc64le-`echo $basic_machine | sed 's/^[^-]*-//'`
- ;;
- ps2)
- basic_machine=i386-ibm
- ;;
- pw32)
- basic_machine=i586-unknown
- os=-pw32
- ;;
- rom68k)
- basic_machine=m68k-rom68k
- os=-coff
- ;;
- rm[46]00)
- basic_machine=mips-siemens
- ;;
- rtpc | rtpc-*)
- basic_machine=romp-ibm
- ;;
- s390 | s390-*)
- basic_machine=s390-ibm
- ;;
- s390x | s390x-*)
- basic_machine=s390x-ibm
- ;;
- sa29200)
- basic_machine=a29k-amd
- os=-udi
- ;;
- sb1)
- basic_machine=mipsisa64sb1-unknown
- ;;
- sb1el)
- basic_machine=mipsisa64sb1el-unknown
- ;;
- sei)
- basic_machine=mips-sei
- os=-seiux
- ;;
- sequent)
- basic_machine=i386-sequent
- ;;
- sh)
- basic_machine=sh-hitachi
- os=-hms
- ;;
- sh64)
- basic_machine=sh64-unknown
- ;;
- sparclite-wrs | simso-wrs)
- basic_machine=sparclite-wrs
- os=-vxworks
- ;;
- sps7)
- basic_machine=m68k-bull
- os=-sysv2
- ;;
- spur)
- basic_machine=spur-unknown
- ;;
- st2000)
- basic_machine=m68k-tandem
- ;;
- stratus)
- basic_machine=i860-stratus
- os=-sysv4
- ;;
- sun2)
- basic_machine=m68000-sun
- ;;
- sun2os3)
- basic_machine=m68000-sun
- os=-sunos3
- ;;
- sun2os4)
- basic_machine=m68000-sun
- os=-sunos4
- ;;
- sun3os3)
- basic_machine=m68k-sun
- os=-sunos3
- ;;
- sun3os4)
- basic_machine=m68k-sun
- os=-sunos4
- ;;
- sun4os3)
- basic_machine=sparc-sun
- os=-sunos3
- ;;
- sun4os4)
- basic_machine=sparc-sun
- os=-sunos4
- ;;
- sun4sol2)
- basic_machine=sparc-sun
- os=-solaris2
- ;;
- sun3 | sun3-*)
- basic_machine=m68k-sun
- ;;
- sun4)
- basic_machine=sparc-sun
- ;;
- sun386 | sun386i | roadrunner)
- basic_machine=i386-sun
- ;;
- sv1)
- basic_machine=sv1-cray
- os=-unicos
- ;;
- symmetry)
- basic_machine=i386-sequent
- os=-dynix
- ;;
- t3e)
- basic_machine=alphaev5-cray
- os=-unicos
- ;;
- t90)
- basic_machine=t90-cray
- os=-unicos
- ;;
- tic54x | c54x*)
- basic_machine=tic54x-unknown
- os=-coff
- ;;
- tic55x | c55x*)
- basic_machine=tic55x-unknown
- os=-coff
- ;;
- tic6x | c6x*)
- basic_machine=tic6x-unknown
- os=-coff
- ;;
- tx39)
- basic_machine=mipstx39-unknown
- ;;
- tx39el)
- basic_machine=mipstx39el-unknown
- ;;
- toad1)
- basic_machine=pdp10-xkl
- os=-tops20
- ;;
- tower | tower-32)
- basic_machine=m68k-ncr
- ;;
- tpf)
- basic_machine=s390x-ibm
- os=-tpf
- ;;
- udi29k)
- basic_machine=a29k-amd
- os=-udi
- ;;
- ultra3)
- basic_machine=a29k-nyu
- os=-sym1
- ;;
- v810 | necv810)
- basic_machine=v810-nec
- os=-none
- ;;
- vaxv)
- basic_machine=vax-dec
- os=-sysv
- ;;
- vms)
- basic_machine=vax-dec
- os=-vms
- ;;
- vpp*|vx|vx-*)
- basic_machine=f301-fujitsu
- ;;
- vxworks960)
- basic_machine=i960-wrs
- os=-vxworks
- ;;
- vxworks68)
- basic_machine=m68k-wrs
- os=-vxworks
- ;;
- vxworks29k)
- basic_machine=a29k-wrs
- os=-vxworks
- ;;
- w65*)
- basic_machine=w65-wdc
- os=-none
- ;;
- w89k-*)
- basic_machine=hppa1.1-winbond
- os=-proelf
- ;;
- xps | xps100)
- basic_machine=xps100-honeywell
- ;;
- ymp)
- basic_machine=ymp-cray
- os=-unicos
- ;;
- z8k-*-coff)
- basic_machine=z8k-unknown
- os=-sim
- ;;
- none)
- basic_machine=none-none
- os=-none
- ;;
-
-# Here we handle the default manufacturer of certain CPU types. It is in
-# some cases the only manufacturer, in others, it is the most popular.
- w89k)
- basic_machine=hppa1.1-winbond
- ;;
- op50n)
- basic_machine=hppa1.1-oki
- ;;
- op60c)
- basic_machine=hppa1.1-oki
- ;;
- romp)
- basic_machine=romp-ibm
- ;;
- mmix)
- basic_machine=mmix-knuth
- ;;
- rs6000)
- basic_machine=rs6000-ibm
- ;;
- vax)
- basic_machine=vax-dec
- ;;
- pdp10)
- # there are many clones, so DEC is not a safe bet
- basic_machine=pdp10-unknown
- ;;
- pdp11)
- basic_machine=pdp11-dec
- ;;
- we32k)
- basic_machine=we32k-att
- ;;
- sh3 | sh4 | sh[34]eb | sh[1234]le | sh[23]ele)
- basic_machine=sh-unknown
- ;;
- sh64)
- basic_machine=sh64-unknown
- ;;
- sparc | sparcv8 | sparcv9 | sparcv9b)
- basic_machine=sparc-sun
- ;;
- cydra)
- basic_machine=cydra-cydrome
- ;;
- orion)
- basic_machine=orion-highlevel
- ;;
- orion105)
- basic_machine=clipper-highlevel
- ;;
- mac | mpw | mac-mpw)
- basic_machine=m68k-apple
- ;;
- pmac | pmac-mpw)
- basic_machine=powerpc-apple
- ;;
- *-unknown)
- # Make sure to match an already-canonicalized machine name.
- ;;
- *)
- echo Invalid configuration \`$1\': machine \`$basic_machine\' not recognized 1>&2
- exit 1
- ;;
-esac
-
-# Here we canonicalize certain aliases for manufacturers.
-case $basic_machine in
- *-digital*)
- basic_machine=`echo $basic_machine | sed 's/digital.*/dec/'`
- ;;
- *-commodore*)
- basic_machine=`echo $basic_machine | sed 's/commodore.*/cbm/'`
- ;;
- *)
- ;;
-esac
-
-# Decode manufacturer-specific aliases for certain operating systems.
-
-if [ x"$os" != x"" ]
-then
-case $os in
- # First match some system type aliases
- # that might get confused with valid system types.
- # -solaris* is a basic system type, with this one exception.
- -solaris1 | -solaris1.*)
- os=`echo $os | sed -e 's|solaris1|sunos4|'`
- ;;
- -solaris)
- os=-solaris2
- ;;
- -svr4*)
- os=-sysv4
- ;;
- -unixware*)
- os=-sysv4.2uw
- ;;
- -gnu/linux*)
- os=`echo $os | sed -e 's|gnu/linux|linux-gnu|'`
- ;;
- # First accept the basic system types.
- # The portable systems comes first.
- # Each alternative MUST END IN A *, to match a version number.
- # -sysv* is not here because it comes later, after sysvr4.
- -gnu* | -bsd* | -mach* | -minix* | -genix* | -ultrix* | -irix* \
- | -*vms* | -sco* | -esix* | -isc* | -aix* | -sunos | -sunos[34]*\
- | -hpux* | -unos* | -osf* | -luna* | -dgux* | -solaris* | -sym* \
- | -amigaos* | -amigados* | -msdos* | -newsos* | -unicos* | -aof* \
- | -aos* \
- | -nindy* | -vxsim* | -vxworks* | -ebmon* | -hms* | -mvs* \
- | -clix* | -riscos* | -uniplus* | -iris* | -rtu* | -xenix* \
- | -hiux* | -386bsd* | -knetbsd* | -mirbsd* | -netbsd* | -openbsd* \
- | -ekkobsd* | -kfreebsd* | -freebsd* | -riscix* | -lynxos* \
- | -bosx* | -nextstep* | -cxux* | -aout* | -elf* | -oabi* \
- | -ptx* | -coff* | -ecoff* | -winnt* | -domain* | -vsta* \
- | -udi* | -eabi* | -lites* | -ieee* | -go32* | -aux* \
- | -chorusos* | -chorusrdb* \
- | -cygwin* | -pe* | -psos* | -moss* | -proelf* | -rtems* \
- | -mingw32* | -linux-gnu* | -linux-uclibc* | -uxpv* | -beos* | -mpeix* | -udk* \
- | -interix* | -uwin* | -mks* | -rhapsody* | -darwin* | -opened* \
- | -openstep* | -oskit* | -conix* | -pw32* | -nonstopux* \
- | -storm-chaos* | -tops10* | -tenex* | -tops20* | -its* \
- | -os2* | -vos* | -palmos* | -uclinux* | -nucleus* \
- | -morphos* | -superux* | -rtmk* | -rtmk-nova* | -windiss* \
- | -powermax* | -dnix* | -nx6 | -nx7 | -sei* | -dragonfly*)
- # Remember, each alternative MUST END IN *, to match a version number.
- ;;
- -qnx*)
- case $basic_machine in
- x86-* | i*86-*)
- ;;
- *)
- os=-nto$os
- ;;
- esac
- ;;
- -nto-qnx*)
- ;;
- -nto*)
- os=`echo $os | sed -e 's|nto|nto-qnx|'`
- ;;
- -sim | -es1800* | -hms* | -xray | -os68k* | -none* | -v88r* \
- | -windows* | -osx | -abug | -netware* | -os9* | -beos* \
- | -macos* | -mpw* | -magic* | -mmixware* | -mon960* | -lnews*)
- ;;
- -mac*)
- os=`echo $os | sed -e 's|mac|macos|'`
- ;;
- -linux-dietlibc)
- os=-linux-dietlibc
- ;;
- -linux*)
- os=`echo $os | sed -e 's|linux|linux-gnu|'`
- ;;
- -sunos5*)
- os=`echo $os | sed -e 's|sunos5|solaris2|'`
- ;;
- -sunos6*)
- os=`echo $os | sed -e 's|sunos6|solaris3|'`
- ;;
- -opened*)
- os=-openedition
- ;;
- -os400*)
- os=-os400
- ;;
- -wince*)
- os=-wince
- ;;
- -osfrose*)
- os=-osfrose
- ;;
- -osf*)
- os=-osf
- ;;
- -utek*)
- os=-bsd
- ;;
- -dynix*)
- os=-bsd
- ;;
- -acis*)
- os=-aos
- ;;
- -atheos*)
- os=-atheos
- ;;
- -syllable*)
- os=-syllable
- ;;
- -386bsd)
- os=-bsd
- ;;
- -ctix* | -uts*)
- os=-sysv
- ;;
- -nova*)
- os=-rtmk-nova
- ;;
- -ns2 )
- os=-nextstep2
- ;;
- -nsk*)
- os=-nsk
- ;;
- # Preserve the version number of sinix5.
- -sinix5.*)
- os=`echo $os | sed -e 's|sinix|sysv|'`
- ;;
- -sinix*)
- os=-sysv4
- ;;
- -tpf*)
- os=-tpf
- ;;
- -triton*)
- os=-sysv3
- ;;
- -oss*)
- os=-sysv3
- ;;
- -svr4)
- os=-sysv4
- ;;
- -svr3)
- os=-sysv3
- ;;
- -sysvr4)
- os=-sysv4
- ;;
- # This must come after -sysvr4.
- -sysv*)
- ;;
- -ose*)
- os=-ose
- ;;
- -es1800*)
- os=-ose
- ;;
- -xenix)
- os=-xenix
- ;;
- -*mint | -mint[0-9]* | -*MiNT | -MiNT[0-9]*)
- os=-mint
- ;;
- -aros*)
- os=-aros
- ;;
- -kaos*)
- os=-kaos
- ;;
- -none)
- ;;
- *)
- # Get rid of the `-' at the beginning of $os.
- os=`echo $os | sed 's/[^-]*-//'`
- echo Invalid configuration \`$1\': system \`$os\' not recognized 1>&2
- exit 1
- ;;
-esac
-else
-
-# Here we handle the default operating systems that come with various machines.
-# The value should be what the vendor currently ships out the door with their
-# machine or put another way, the most popular os provided with the machine.
-
-# Note that if you're going to try to match "-MANUFACTURER" here (say,
-# "-sun"), then you have to tell the case statement up towards the top
-# that MANUFACTURER isn't an operating system. Otherwise, code above
-# will signal an error saying that MANUFACTURER isn't an operating
-# system, and we'll never get to this point.
-
-case $basic_machine in
- *-acorn)
- os=-riscix1.2
- ;;
- arm*-rebel)
- os=-linux
- ;;
- arm*-semi)
- os=-aout
- ;;
- c4x-* | tic4x-*)
- os=-coff
- ;;
- # This must come before the *-dec entry.
- pdp10-*)
- os=-tops20
- ;;
- pdp11-*)
- os=-none
- ;;
- *-dec | vax-*)
- os=-ultrix4.2
- ;;
- m68*-apollo)
- os=-domain
- ;;
- i386-sun)
- os=-sunos4.0.2
- ;;
- m68000-sun)
- os=-sunos3
- # This also exists in the configure program, but was not the
- # default.
- # os=-sunos4
- ;;
- m68*-cisco)
- os=-aout
- ;;
- mips*-cisco)
- os=-elf
- ;;
- mips*-*)
- os=-elf
- ;;
- or32-*)
- os=-coff
- ;;
- *-tti) # must be before sparc entry or we get the wrong os.
- os=-sysv3
- ;;
- sparc-* | *-sun)
- os=-sunos4.1.1
- ;;
- *-be)
- os=-beos
- ;;
- *-ibm)
- os=-aix
- ;;
- *-knuth)
- os=-mmixware
- ;;
- *-wec)
- os=-proelf
- ;;
- *-winbond)
- os=-proelf
- ;;
- *-oki)
- os=-proelf
- ;;
- *-hp)
- os=-hpux
- ;;
- *-hitachi)
- os=-hiux
- ;;
- i860-* | *-att | *-ncr | *-altos | *-motorola | *-convergent)
- os=-sysv
- ;;
- *-cbm)
- os=-amigaos
- ;;
- *-dg)
- os=-dgux
- ;;
- *-dolphin)
- os=-sysv3
- ;;
- m68k-ccur)
- os=-rtu
- ;;
- m88k-omron*)
- os=-luna
- ;;
- *-next )
- os=-nextstep
- ;;
- *-sequent)
- os=-ptx
- ;;
- *-crds)
- os=-unos
- ;;
- *-ns)
- os=-genix
- ;;
- i370-*)
- os=-mvs
- ;;
- *-next)
- os=-nextstep3
- ;;
- *-gould)
- os=-sysv
- ;;
- *-highlevel)
- os=-bsd
- ;;
- *-encore)
- os=-bsd
- ;;
- *-sgi)
- os=-irix
- ;;
- *-siemens)
- os=-sysv4
- ;;
- *-masscomp)
- os=-rtu
- ;;
- f30[01]-fujitsu | f700-fujitsu)
- os=-uxpv
- ;;
- *-rom68k)
- os=-coff
- ;;
- *-*bug)
- os=-coff
- ;;
- *-apple)
- os=-macos
- ;;
- *-atari*)
- os=-mint
- ;;
- *)
- os=-none
- ;;
-esac
-fi
-
-# Here we handle the case where we know the os, and the CPU type, but not the
-# manufacturer. We pick the logical manufacturer.
-vendor=unknown
-case $basic_machine in
- *-unknown)
- case $os in
- -riscix*)
- vendor=acorn
- ;;
- -sunos*)
- vendor=sun
- ;;
- -aix*)
- vendor=ibm
- ;;
- -beos*)
- vendor=be
- ;;
- -hpux*)
- vendor=hp
- ;;
- -mpeix*)
- vendor=hp
- ;;
- -hiux*)
- vendor=hitachi
- ;;
- -unos*)
- vendor=crds
- ;;
- -dgux*)
- vendor=dg
- ;;
- -luna*)
- vendor=omron
- ;;
- -genix*)
- vendor=ns
- ;;
- -mvs* | -opened*)
- vendor=ibm
- ;;
- -os400*)
- vendor=ibm
- ;;
- -ptx*)
- vendor=sequent
- ;;
- -tpf*)
- vendor=ibm
- ;;
- -vxsim* | -vxworks* | -windiss*)
- vendor=wrs
- ;;
- -aux*)
- vendor=apple
- ;;
- -hms*)
- vendor=hitachi
- ;;
- -mpw* | -macos*)
- vendor=apple
- ;;
- -*mint | -mint[0-9]* | -*MiNT | -MiNT[0-9]*)
- vendor=atari
- ;;
- -vos*)
- vendor=stratus
- ;;
- esac
- basic_machine=`echo $basic_machine | sed "s/unknown/$vendor/"`
- ;;
-esac
-
-echo $basic_machine$os
-exit 0
-
-# Local variables:
-# eval: (add-hook 'write-file-hooks 'time-stamp)
-# time-stamp-start: "timestamp='"
-# time-stamp-format: "%:y-%02m-%02d"
-# time-stamp-end: "'"
-# End:
diff --git a/vmkit/autoconf/configure.ac b/vmkit/autoconf/configure.ac
deleted file mode 100644
index abef671..0000000
--- a/vmkit/autoconf/configure.ac
+++ /dev/null
@@ -1,616 +0,0 @@
-dnl === configure.ac --------------------------------------------------------===
-dnl The vmkit project
-dnl
-dnl This file is distributed under the University of Illinois Open Source
-dnl License. See LICENSE.TXT for details.
-dnl
-dnl===-----------------------------------------------------------------------===
-dnl This is the VMKit configuration script. It is processed by the autoconf
-dnl program to produce a script named configure. This script contains the
-dnl configuration checks that VMKit needs in order to support multiple platforms.
-dnl This file is composed of 10 sections per the recommended organization of
-dnl autoconf input defined in the autoconf documentation. As this file evolves,
-dnl please keep the various types of checks within their sections. The sections
-dnl are as follows:
-dnl
-dnl SECTION 1: Initialization & Setup
-dnl SECTION 2: Architecture, target, and host checks
-dnl SECTION 3: Command line arguments for the configure script.
-dnl SECTION 4: Check for programs we need and that they are the right version
-dnl SECTION 5: Check for libraries
-dnl SECTION 6: Check for header files
-dnl SECTION 7: Check for types and structures
-dnl SECTION 8: Check for specific functions needed
-dnl SECTION 9: Additional checks, variables, etc.
-dnl SECTION 10: Specify the output files and generate it
-dnl
-dnl===-----------------------------------------------------------------------===
-dnl===
-dnl=== SECTION 1: Initialization & Setup
-dnl===
-dnl===-----------------------------------------------------------------------===
-dnl Initialize autoconf and define the package name, version number and
-dnl email address for reporting bugs.
-AC_INIT([vmkit],[0.29svn],[nicolas.geoffray@gmail.com])
-
-dnl Provide a copyright substitution and ensure the copyright notice is included
-dnl in the output of --version option of the generated configure script.
-AC_SUBST(VMKIT_COPYRIGHT,["Copyright (c) 2003-2010 Universite Pierre et Marie Curie."])
-AC_COPYRIGHT([Copyright (c) 2003-2010 Universite Pierre et Marie Curie.])
-
-dnl Indicate that we require autoconf 2.59 or later. Ths is needed because we
-dnl use some autoconf macros only available in 2.59.
-AC_PREREQ(2.59)
-
-dnl Verify that the source directory is valid. This makes sure that we are
-dnl configuring VMKit and not some other package (it validates --srcdir argument)
-AC_CONFIG_SRCDIR([lib/Mvm/Runtime/Object.cpp])
-
-
-dnl Quit if the source directory has already been configured.
-dnl NOTE: This relies upon undocumented autoconf behavior.
-if test ${srcdir} != "." ; then
- if test -f ${srcdir}/include/mvm/Config/config.h ; then
- AC_MSG_ERROR([Already configured in ${srcdir}])
- fi
-fi
-
-dnl Place all of the extra autoconf files into the config subdirectory. Tell
-dnl various tools where the m4 autoconf macros are.
-AC_CONFIG_AUX_DIR([$LLVM_SRC_ROOT/autoconf])
-
-dnl Tell autoconf that this is an LLVM project being configured
-dnl This provides the --with-llvmsrc and --with-llvmobj options
-LLVM_CONFIG_PROJECT($LLVM_SRC_ROOT,$LLVM_OBJ_ROOT)
-
-
-dnl===-----------------------------------------------------------------------===
-dnl===
-dnl=== SECTION 2: Architecture, target, and host checks
-dnl===
-dnl===-----------------------------------------------------------------------===
-
-dnl Check the target for which we're compiling and the host that will do the
-dnl compilations. This will tell us which LLVM compiler will be used for
-dnl compiling SSA into object code. This needs to be done early because
-dnl following tests depend on it.
-AC_CANONICAL_TARGET
-
-dnl Determine the platform type and cache its value. This helps us configure
-dnl the System library to the correct build platform.
-AC_CACHE_CHECK([type of operating system we're going to host on],
- [vmkit_cv_os_type],
-[case $host in
- *-*-aix*)
- AC_MSG_ERROR([Good luck porting vmkit to your host!])
- vmkit_cv_os_type="AIX"
- vmkit_cv_platform_type="Unix" ;;
- *-*-irix*)
- AC_MSG_ERROR([Good luck porting vmkit to your host!])
- vmkit_cv_os_type="IRIX"
- vmkit_cv_platform_type="Unix" ;;
- *-*-cygwin*)
- AC_MSG_ERROR([Good luck porting vmkit to your host!])
- vmkit_cv_os_type="Cygwin"
- vmkit_cv_platform_type="Unix" ;;
- *-*-darwin*)
- DYLIB_EXTENSION="dylib"
- vmkit_cv_os_type="Darwin"
- vmkit_cv_platform_type="Unix" ;;
- *-*-freebsd*)
- AC_MSG_ERROR([Good luck porting vmkit to your host!])
- vmkit_cv_os_type="FreeBSD"
- vmkit_cv_platform_type="Unix" ;;
- *-*-openbsd*)
- AC_MSG_ERROR([Good luck porting vmkit to your host!])
- vmkit_cv_os_type="OpenBSD"
- vmkit_cv_platform_type="Unix" ;;
- *-*-netbsd*)
- AC_MSG_ERROR([Good luck porting vmkit to your host!])
- vmkit_cv_os_type="NetBSD"
- vmkit_cv_platform_type="Unix" ;;
- *-*-hpux*)
- AC_MSG_ERROR([Good luck porting vmkit to your host!])
- vmkit_cv_os_type="HP-UX"
- vmkit_cv_platform_type="Unix" ;;
- *-*-interix*)
- AC_MSG_ERROR([Good luck porting vmkit to your host!])
- vmkit_cv_os_type="Interix"
- vmkit_cv_platform_type="Unix" ;;
- *-*-linux*)
- DYLIB_EXTENSION="so"
- vmkit_cv_os_type="Linux"
- vmkit_cv_platform_type="Unix" ;;
- *-*-solaris*)
- AC_MSG_ERROR([Good luck porting vmkit to your host!])
- vmkit_cv_os_type="SunOS"
- vmkit_cv_platform_type="Unix" ;;
- *-*-win32*)
- AC_MSG_ERROR([Good luck porting vmkit to your host!])
- vmkit_cv_os_type="Win32"
- vmkit_cv_platform_type="Win32" ;;
- *-*-mingw*)
- AC_MSG_ERROR([Good luck porting vmkit to your host!])
- vmkit_cv_os_type="MingW"
- vmkit_cv_platform_type="Win32" ;;
- *)
- AC_MSG_ERROR([Good luck porting vmkit to your host!])
- vmkit_cv_os_type="Unknown"
- vmkit_cv_platform_type="Unknown" ;;
-esac])
-
-dnl Make sure we aren't attempting to configure for an unknown system
-
-AC_SUBST([DYLIB_EXTENSION])
-
-dnl===-----------------------------------------------------------------------===
-dnl===
-dnl=== SECTION 3: Command line arguments for the configure script.
-dnl===
-dnl===-----------------------------------------------------------------------===
-
-AC_ARG_WITH(llvmgcc,
- [AS_HELP_STRING(--with-llvmgcc,
- [Compile with llvm-gcc])],
- [[withllvm=yes]],
- [[withllvm=no]],
-)
-
-if test "x$withllvm" = "xyes"; then
- WITH_LLVM_GCC=1
- LLVM_FLAGS=-DWITH_LLVM_GCC
-fi
-
-AC_SUBST([WITH_LLVM_GCC])
-AC_SUBST([LLVM_FLAGS])
-
-AC_ARG_WITH(thread,
- [AS_HELP_STRING(--with-thread=something,
- [Thread type ('common' or 'no')])],
- [thread=$withval],[thread=common]
-)
-
-AS_IF([test "x$thread" != "xno"],
- [AC_CHECK_HEADER([pthread.h],,
- [AC_MSG_WARN(phtread include NOT found)])
- AC_CHECK_LIB(pthread, pthread_create, [],
- [AC_MSG_ERROR([pthread library not found])])
- ]
-)
-
-if test "x$thread" = xcommon; then
- AC_DEFINE([HAVE_PTHREAD], [1], [Using pthread library])
-fi
-
-AC_ARG_WITH(finalizer,
- [AS_HELP_STRING(--with-finalizer,
- [Compile with finalizer (default yes)])],
- [[withfinalizer=$withfinalizer]],
- [[withfinalizer=yes]],
-)
-
-if test ! "x$withfinalizer" = "xyes"; then
- VM_FLAGS="$VM_FLAGS -DWITHOUT_FINALIZER"
-fi
-
-AC_SUBST([VM_FLAGS])
-
-dnl **************************************************************************
-dnl Architecture
-dnl **************************************************************************
-
-case $target_cpu in
- powerpc)
- AC_DEFINE([WITH_64], [0], [Building on a platform without 64bit cas])
- AC_SUBST([WITH_64], [0]);;
- *)
- AC_DEFINE([WITH_64], [1], [Building on a platform with 64bit cas])
- AC_SUBST([WITH_64], [1]);;
-esac
-
-
-
-dnl **************************************************************************
-dnl GC type
-dnl **************************************************************************
-AC_ARG_WITH(gc,
- [AS_HELP_STRING(--with-gc=something,
- [GC type ('mmtk' (requires llvm-gcc) 'single-mmap' 'multi-mmap' or 'boehm')])],
- [[gc=$withval]],
- [[ echo Using mmap2 as vvm gc type.
- gc=single-mmap
- ]]
-)
-
-AC_ARG_WITH(mmtk-plan,
- [AS_HELP_STRING(--with-mmtk-plan=something,
- [MMTk plan type ('marksweep')])],
- [[MMTK_PLAN_HEADER=$withval]],
- [[MMTK_PLAN_HEADER=marksweep]]
-)
-
-if test "x$gc" = "xboehm"; then
- GC_FLAGS="-I\$(PROJ_SRC_ROOT)/lib/Mvm/BoehmGC -DGC_THREADS"
- AC_DEFINE([USE_GC_BOEHM], [1], [Using the boehm gc])
- AC_SUBST(GC_MMAP2, [0])
- AC_SUBST(GC_BOEHM, [1])
- AC_SUBST(GC_MMTK, [0])
- GC_LIBS=BoehmGC
- case $target_os in
- *linux*)
- GC_FLAGS="-I\$(PROJ_SRC_ROOT)/lib/Mvm/BoehmGC -DUSE_GC_BOEHM -DGC_THREADS -DGC_LINUX_THREADS"
- ;;
- esac
-else
- if test "x$gc" = "xmmtk"; then
- AC_SUBST([GC_MULTI_MMAP], [0])
- AC_SUBST([GC_SINGLE_MMAP], [1])
- AC_SUBST(GC_MMAP2, [0])
- AC_SUBST(GC_BOEHM, [0])
- AC_SUBST(GC_MMTK, [1])
- GC_LIBS=MMTk
- GC_FLAGS="-I\$(PROJ_SRC_ROOT)/lib/Mvm/MMTk -DWITH_MMTK -I\$(PROJ_SRC_ROOT)/mmtk/config/\$(MMTK_PLAN_HEADER)"
- else
- GC_LIBS=GCMmap2
- if test "x$gc" = "xmulti-mmap"; then
- GC_FLAGS="-I\$(PROJ_SRC_ROOT)/lib/Mvm/GCMmap2 -DWITH_TRACER -DMULTIPLE_GC -I\$(PROJ_SRC_ROOT)/lib/Mvm/Allocator"
- AC_SUBST([GC_MULTI_MMAP], [1])
- AC_SUBST([GC_SINGLE_MMAP], [0])
- else
- GC_FLAGS="-I\$(PROJ_SRC_ROOT)/lib/Mvm/GCMmap2 -DWITH_TRACER -I\$(PROJ_SRC_ROOT)/lib/Mvm/Allocator"
- AC_SUBST([GC_MULTI_MMAP], [0])
- AC_SUBST([GC_SINGLE_MMAP], [1])
- fi
- AC_DEFINE([USE_GC_MMAP2], [1], [Using the gcmmap2])
- AC_SUBST(GC_MMAP2, [1])
- AC_SUBST(GC_BOEHM, [0])
- AC_SUBST(GC_MMTK, [0])
- fi
-fi
-
-
-if test "x$MMTK_PLAN_HEADER" = "xmarksweep"; then
- MMTK_PLAN=org.mmtk.plan.marksweep.MS
-else
- if test "x$MMTK_PLAN_HEADER" = "xcopyms"; then
- MMTK_PLAN=org.mmtk.plan.copyms.CopyMS
- else
- if test "x$MMTK_PLAN_HEADER" != "x"; then
- error Unknown or unsupported MMTK plan
- fi
- fi
-fi
-
-AC_SUBST([GC_FLAGS])
-AC_SUBST([GC_LIBS])
-AC_SUBST([MMTK_PLAN])
-AC_SUBST([MMTK_PLAN_HEADER])
-
-dnl **************************************************************************
-dnl Exception type
-dnl **************************************************************************
-AC_ARG_WITH(exception-type,
- [AS_HELP_STRING(--with-exception-type=something,
- [Exception type ('check' or 'dwarf')])],
- [[exceptiontype=$withval]],
- [[ echo Using check as exception type.
- exceptiontype=check
- ]]
-)
-
-AC_ARG_WITH(runtime-exception-type,
- [AS_HELP_STRING(--with-runtime-exception-type=something,
- [Runtime exception type ('setjmp' or 'dwarf')])],
- [[runtimeexceptiontype=$withval]],
- [[ echo Using setjmp as exception type.
- exceptiontype=setjmp
- ]]
-)
-
-if test "x$exceptiontype" = "xdwarf"; then
- EXCEPTION_FLAGS="-DDWARF_EXCEPTIONS -fexceptions"
-fi
-
-if test "x$runtimeexceptiontype" = "xdwarf"; then
- EXCEPTION_FLAGS+="-DRUNTIME_DWARF_EXCEPTIONS -fexceptions"
-fi
-
-if test "x$runtimeexceptiontype" != "xdwarf"; then
- if test "x$exceptiontype" != "xdwarf"; then
- EXCEPTION_FLAGS="-fno-exceptions"
- fi
-fi
-
-AC_SUBST([EXCEPTION_FLAGS])
-
-dnl **************************************************************************
-dnl GNU CLASSPATH installation prefix
-dnl **************************************************************************
-
-classpathversion=0.97.2;
-
-AC_ARG_WITH(gnu-classpath-libs,
- [AS_HELP_STRING(--with-gnu-classpath-libs=something,
- [GNU CLASSPATH libraries (default is /usr/lib/classpath)])],
- [[classpathlibs=$withval]],
- [[classpathlibs=/usr/lib/classpath]]
-)
-
-AC_ARG_WITH(gnu-classpath-glibj,
- [AS_HELP_STRING(--with-gnu-classpath-glibj,
- [Build J3 with GNU Classpath install (default is '/usr/share/classpath/glibj.zip')])],
- [[classpathglibj=$withval]],
- [[classpathglibj=/usr/share/classpath/glibj.zip]]
-)
-
-AC_ARG_WITH(j3,
- [AS_HELP_STRING(--with-j3=yes|no,
- [Build J3 (default is yes)])],
- [[WITH_J3=$withval]],
- [[WITH_J3=yes]]
-)
-
-classpathinclude="-I${classpathlibs}/../include -I/usr/include/classpath";
-
-if test "x${WITH_J3}" = "xyes"; then
- WITH_J3=1;
- AC_DEFINE([WITH_J3], [1], [With J3])
-else
- WITH_J3=0;
-fi
-
-AC_SUBST([classpathglibj])
-AC_SUBST([classpathlibs])
-AC_SUBST([classpathinclude])
-AC_SUBST([classpathversion])
-AC_SUBST([WITH_J3])
-
-dnl **************************************************************************
-dnl Local PNet directory
-dnl **************************************************************************
-AC_ARG_WITH(pnet-local-prefix,
- [AS_HELP_STRING(--with-pnet-local-prefix=something,
- [PNET local prefix (no default)])],
- [[pnetlocalprefix=$withval]],
- [[ echo Not using PNETlocal prefix.
- pnetlocalprefix=''
- ]]
-)
-
-AC_ARG_WITH(pnetlib,
- [AS_HELP_STRING(--with-pnetlib=something,
- [Pnetlib's mscorlib.dll location (default is /usr/lib/cscc/lib/)])],
- [[pnetlibpath=$withval]],
- [[pnetlibpath=/usr/lib/cscc/lib/]]
-)
-
-WITH_N3=0
-
-if test "x$pnetlocalprefix" != x; then
- echo Using ${pnetlocalprefix} as PNET local prefix;
- WITH_N3_PNETLIB=1;
- WITH_N3=1;
- AC_DEFINE([WITH_N3], [1], [With N3])
-else
- WITH_N3_PNETLIB=0;
-fi
-
-AC_SUBST([pnetlocalprefix])
-AC_SUBST([WITH_N3_PNETLIB])
-
-N3_LIB=PNetLib
-AC_SUBST([N3_LIB])
-AC_SUBST([pnetlibpath])
-
-AC_ARG_WITH(mono,
- [AS_HELP_STRING(--with-mono=something,
- [Mono's mscorlib.dll location (no default)])],
- [[monopath=$withval]],
- [[echo Not using Mono]]
-)
-
-if test "x$monopath" != x; then
- echo Building N3 with Mono;
- WITH_N3_MONO=1;
- WITH_N3=1;
-else
- WITH_N3_MONO=0;
-fi
-
-AC_SUBST([WITH_N3_MONO])
-AC_SUBST([monopath])
-
-AC_SUBST([WITH_N3])
-
-dnl===-----------------------------------------------------------------------===
-dnl===
-dnl=== SECTION 4: Check for programs we need and that they are the right version
-dnl===
-dnl===-----------------------------------------------------------------------===
-
-dnl Check for compilation tools
-AC_PROG_CPP
-AC_PROG_CC(gcc)
-AC_PROG_CXX(g++)
-
-AC_PROG_NM
-AC_SUBST(NM)
-
-dnl Check for the tools that the makefiles require
-AC_PROG_LN_S
-AC_PATH_PROG(CMP, [cmp], [cmp])
-AC_PATH_PROG(CP, [cp], [cp])
-AC_PATH_PROG(DATE, [date], [date])
-AC_PATH_PROG(FIND, [find], [find])
-AC_PATH_PROG(GREP, [grep], [grep])
-AC_PATH_PROG(MKDIR,[mkdir],[mkdir])
-AC_PATH_PROG(MV, [mv], [mv])
-AC_PROG_RANLIB
-AC_PATH_PROG(RM, [rm], [rm])
-AC_PATH_PROG(SED, [sed], [sed])
-AC_PATH_PROG(TAR, [tar], [gtar])
-AC_PATH_PROG(BINPWD,[pwd], [pwd])
-AC_PATH_PROG(CAT,[cat], [cat])
-
-AC_PATH_PROG(LLVMAS, [llvm-as], [llvm-as])
-AC_PATH_PROG(LLC, [llc], [llc])
-
-if test "x$gc" = "xmmtk"; then
- AC_PATH_PROG(ANT, [ant])
- if test -z "$ANT"; then
- AC_MSG_ERROR([Apache ANT required for MMTk, but not found])
- fi
-fi
-
-dnl Find the install program
-AC_PROG_INSTALL
-
-if test "$WITH_LLVMGCCDIR" = "default" ; then
- LLVMGCC="llvm-gcc${EXEEXT}"
- LLVMGXX="llvm-g++${EXEEXT}"
- AC_PATH_PROG(LLVMGCC, $LLVMGCC, [])
- AC_PATH_PROG(LLVMGXX, $LLVMGXX, [])
-else
- if test -z "$LLVMGCC"; then
- LLVMGCC="$WITH_LLVMGCCDIR/bin/llvm-gcc${EXEEXT}"
- fi
- if test -z "$LLVMGXX"; then
- LLVMGXX="$WITH_LLVMGCCDIR/bin/llvm-g++${EXEEXT}"
- fi
- AC_SUBST(LLVMGCC,$LLVMGCC)
- AC_SUBST(LLVMGXX,$LLVMGXX)
-fi
-
-AC_MSG_CHECKING([tool compatibility])
-
-dnl Ensure that compilation tools are GCC or a GNU compatible compiler such as
-dnl ICC; we use GCC specific options in the makefiles so the compiler needs
-dnl to support those options.
-dnl "icc" emits gcc signatures
-dnl "icc -no-gcc" emits no gcc signature BUT is still compatible
-ICC=no
-IXX=no
-case $CC in
- icc*|icpc*)
- ICC=yes
- IXX=yes
- ;;
- *)
- ;;
-esac
-
-if test "$GCC" != "yes" && test "$ICC" != "yes"
-then
- AC_MSG_ERROR([gcc|icc required but not found])
-fi
-
-dnl Ensure that compilation tools are GCC; we use GCC specific extensions
-if test "$GXX" != "yes" && test "$IXX" != "yes"
-then
- AC_MSG_ERROR([g++|icc required but not found])
-fi
-
-dnl Verify that GCC is version 3.0 or higher
-if test "$GCC" = "yes"
-then
- AC_COMPILE_IFELSE([[#if !defined(__GNUC__) || __GNUC__ < 3
-#error Unsupported GCC version
-#endif
-]], [], [AC_MSG_ERROR([gcc 3.x required, but you have a lower version])])
-fi
-
-dnl Tool compatibility is okay if we make it here.
-AC_MSG_RESULT([ok])
-
-
-dnl===-----------------------------------------------------------------------===
-dnl===
-dnl=== SECTION 5: Check for libraries
-dnl===
-dnl===-----------------------------------------------------------------------===
-
-AC_CHECK_LIB(z, inflate, [], \
- [AC_MSG_ERROR([You need to install the zlib package (z).])]
-)
-
-if test "x$gc" = "xboehm"; then
-AC_CHECK_LIB(gc, GC_malloc, [], \
- [AC_MSG_ERROR([You need to install the boehm-gc package (gc).])]
-)
-fi
-
-dnl===-----------------------------------------------------------------------===
-dnl===
-dnl=== SECTION 6: Check for header files
-dnl===
-dnl===-----------------------------------------------------------------------===
-
-AC_CHECK_HEADER([zlib.h], [], \
- AC_MSG_ERROR([You need to install the zlib devel package (zlib.h).])
-)
-
-if test "x$gc" = "xboehm"; then
- AC_CHECK_HEADER([gc/gc.h], [], \
- AC_MSG_ERROR([You need to install the boehm-gc devel package (gc/gc.h).])
- )
-fi
-
-
-nl===-----------------------------------------------------------------------===
-dnl===
-dnl=== SECTION 7: Check for types and structures
-dnl===
-dnl===-----------------------------------------------------------------------===
-
-AC_TYPE_PID_T
-AC_TYPE_SIZE_T
-AC_STRUCT_TM
-AC_CHECK_TYPES([int64_t],,AC_MSG_ERROR([Type int64_t required but not found]))
-AC_CHECK_TYPES([uint64_t],,
- AC_CHECK_TYPES([u_int64_t],,
- AC_MSG_ERROR([Type uint64_t or u_int64_t required but not found])))
-
-dnl===-----------------------------------------------------------------------===
-dnl===
-dnl=== SECTION 8: Check for specific functions needed
-dnl===
-dnl===-----------------------------------------------------------------------===
-
-AC_CHECK_FUNCS([setjmp longjmp])
-
-
-dnl===-----------------------------------------------------------------------===
-dnl===
-dnl=== SECTION 9: Additional checks, variables, etc.
-dnl===
-dnl===-----------------------------------------------------------------------===
-
-dnl===-----------------------------------------------------------------------===
-dnl===
-dnl=== SECTION 10: Specify the output files and generate it
-dnl===
-dnl===-----------------------------------------------------------------------===
-
-dnl Configure header files
-dnl WARNING: dnl If you add or remove any of the following config headers, then
-dnl you MUST also update Makefile.rules so that the variable FilesToConfig
-dnl contains the same list of files as AC_CONFIG_HEADERS below. This ensures the
-dnl files can be updated automatically when their *.in sources change.
-AC_CONFIG_HEADERS([include/mvm/Config/config.h])
-
-dnl Verify that the source directory is valid
-AC_CONFIG_SRCDIR(["Makefile.common.in"])
-
-dnl Configure a common Makefile
-AC_CONFIG_FILES(Makefile.common)
-AC_CONFIG_FILES(Makefile.config)
-AC_CONFIG_FILES([lib/J3/Classpath/Classpath.h])
-AC_CONFIG_FILES([tools/llcj/LinkPaths.h])
-AC_CONFIG_FILES([mmtk/java/src/org/j3/config/Selected.java])
-
-dnl Do special configuration of Makefiles
-AC_CONFIG_MAKEFILE(Makefile)
-AC_CONFIG_MAKEFILE(lib/Makefile)
-
-
-AC_OUTPUT
diff --git a/vmkit/autoconf/install-sh b/vmkit/autoconf/install-sh
deleted file mode 100644
index dd97db7..0000000
--- a/vmkit/autoconf/install-sh
+++ /dev/null
@@ -1,322 +0,0 @@
-#!/bin/sh
-# install - install a program, script, or datafile
-
-scriptversion=2004-09-10.20
-
-# This originates from X11R5 (mit/util/scripts/install.sh), which was
-# later released in X11R6 (xc/config/util/install.sh) with the
-# following copyright and license.
-#
-# Copyright (C) 1994 X Consortium
-#
-# Permission is hereby granted, free of charge, to any person obtaining a copy
-# of this software and associated documentation files (the "Software"), to
-# deal in the Software without restriction, including without limitation the
-# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
-# sell copies of the Software, and to permit persons to whom the Software is
-# furnished to do so, subject to the following conditions:
-#
-# The above copyright notice and this permission notice shall be included in
-# all copies or substantial portions of the Software.
-#
-# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-# X CONSORTIUM BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
-# AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNEC-
-# TION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-#
-# Except as contained in this notice, the name of the X Consortium shall not
-# be used in advertising or otherwise to promote the sale, use or other deal-
-# ings in this Software without prior written authorization from the X Consor-
-# tium.
-#
-#
-# FSF changes to this file are in the public domain.
-#
-# Calling this script install-sh is preferred over install.sh, to prevent
-# `make' implicit rules from creating a file called install from it
-# when there is no Makefile.
-#
-# This script is compatible with the BSD install script, but was written
-# from scratch. It can only install one file at a time, a restriction
-# shared with many OS's install programs.
-
-# set DOITPROG to echo to test this script
-
-# Don't use :- since 4.3BSD and earlier shells don't like it.
-doit="${DOITPROG-}"
-
-# put in absolute paths if you don't have them in your path; or use env. vars.
-
-mvprog="${MVPROG-mv}"
-cpprog="${CPPROG-cp}"
-chmodprog="${CHMODPROG-chmod}"
-chownprog="${CHOWNPROG-chown}"
-chgrpprog="${CHGRPPROG-chgrp}"
-stripprog="${STRIPPROG-strip}"
-rmprog="${RMPROG-rm}"
-mkdirprog="${MKDIRPROG-mkdir}"
-
-chmodcmd="$chmodprog 0755"
-chowncmd=
-chgrpcmd=
-stripcmd=
-rmcmd="$rmprog -f"
-mvcmd="$mvprog"
-src=
-dst=
-dir_arg=
-dstarg=
-no_target_directory=
-
-usage="Usage: $0 [OPTION]... [-T] SRCFILE DSTFILE
- or: $0 [OPTION]... SRCFILES... DIRECTORY
- or: $0 [OPTION]... -t DIRECTORY SRCFILES...
- or: $0 [OPTION]... -d DIRECTORIES...
-
-In the 1st form, copy SRCFILE to DSTFILE.
-In the 2nd and 3rd, copy all SRCFILES to DIRECTORY.
-In the 4th, create DIRECTORIES.
-
-Options:
--c (ignored)
--d create directories instead of installing files.
--g GROUP $chgrpprog installed files to GROUP.
--m MODE $chmodprog installed files to MODE.
--o USER $chownprog installed files to USER.
--s $stripprog installed files.
--t DIRECTORY install into DIRECTORY.
--T report an error if DSTFILE is a directory.
---help display this help and exit.
---version display version info and exit.
-
-Environment variables override the default commands:
- CHGRPPROG CHMODPROG CHOWNPROG CPPROG MKDIRPROG MVPROG RMPROG STRIPPROG
-"
-
-while test -n "$1"; do
- case $1 in
- -c) shift
- continue;;
-
- -d) dir_arg=true
- shift
- continue;;
-
- -g) chgrpcmd="$chgrpprog $2"
- shift
- shift
- continue;;
-
- --help) echo "$usage"; exit 0;;
-
- -m) chmodcmd="$chmodprog $2"
- shift
- shift
- continue;;
-
- -o) chowncmd="$chownprog $2"
- shift
- shift
- continue;;
-
- -s) stripcmd=$stripprog
- shift
- continue;;
-
- -t) dstarg=$2
- shift
- shift
- continue;;
-
- -T) no_target_directory=true
- shift
- continue;;
-
- --version) echo "$0 $scriptversion"; exit 0;;
-
- *) # When -d is used, all remaining arguments are directories to create.
- # When -t is used, the destination is already specified.
- test -n "$dir_arg$dstarg" && break
- # Otherwise, the last argument is the destination. Remove it from $@.
- for arg
- do
- if test -n "$dstarg"; then
- # $@ is not empty: it contains at least $arg.
- set fnord "$@" "$dstarg"
- shift # fnord
- fi
- shift # arg
- dstarg=$arg
- done
- break;;
- esac
-done
-
-if test -z "$1"; then
- if test -z "$dir_arg"; then
- echo "$0: no input file specified." >&2
- exit 1
- fi
- # It's OK to call `install-sh -d' without argument.
- # This can happen when creating conditional directories.
- exit 0
-fi
-
-for src
-do
- # Protect names starting with `-'.
- case $src in
- -*) src=./$src ;;
- esac
-
- if test -n "$dir_arg"; then
- dst=$src
- src=
-
- if test -d "$dst"; then
- mkdircmd=:
- chmodcmd=
- else
- mkdircmd=$mkdirprog
- fi
- else
- # Waiting for this to be detected by the "$cpprog $src $dsttmp" command
- # might cause directories to be created, which would be especially bad
- # if $src (and thus $dsttmp) contains '*'.
- if test ! -f "$src" && test ! -d "$src"; then
- echo "$0: $src does not exist." >&2
- exit 1
- fi
-
- if test -z "$dstarg"; then
- echo "$0: no destination specified." >&2
- exit 1
- fi
-
- dst=$dstarg
- # Protect names starting with `-'.
- case $dst in
- -*) dst=./$dst ;;
- esac
-
- # If destination is a directory, append the input filename; won't work
- # if double slashes aren't ignored.
- if test -d "$dst"; then
- if test -n "$no_target_directory"; then
- echo "$0: $dstarg: Is a directory" >&2
- exit 1
- fi
- dst=$dst/`basename "$src"`
- fi
- fi
-
- # This sed command emulates the dirname command.
- dstdir=`echo "$dst" | sed -e 's,[^/]*$,,;s,/$,,;s,^$,.,'`
-
- # Make sure that the destination directory exists.
-
- # Skip lots of stat calls in the usual case.
- if test ! -d "$dstdir"; then
- defaultIFS='
- '
- IFS="${IFS-$defaultIFS}"
-
- oIFS=$IFS
- # Some sh's can't handle IFS=/ for some reason.
- IFS='%'
- set - `echo "$dstdir" | sed -e 's@/@%@g' -e 's@^%@/@'`
- IFS=$oIFS
-
- pathcomp=
-
- while test $# -ne 0 ; do
- pathcomp=$pathcomp$1
- shift
- if test ! -d "$pathcomp"; then
- $mkdirprog "$pathcomp"
- # mkdir can fail with a `File exist' error in case several
- # install-sh are creating the directory concurrently. This
- # is OK.
- test -d "$pathcomp" || exit
- fi
- pathcomp=$pathcomp/
- done
- fi
-
- if test -n "$dir_arg"; then
- $doit $mkdircmd "$dst" \
- && { test -z "$chowncmd" || $doit $chowncmd "$dst"; } \
- && { test -z "$chgrpcmd" || $doit $chgrpcmd "$dst"; } \
- && { test -z "$stripcmd" || $doit $stripcmd "$dst"; } \
- && { test -z "$chmodcmd" || $doit $chmodcmd "$dst"; }
-
- else
- dstfile=`basename "$dst"`
-
- # Make a couple of temp file names in the proper directory.
- dsttmp=$dstdir/_inst.$$_
- rmtmp=$dstdir/_rm.$$_
-
- # Trap to clean up those temp files at exit.
- trap 'ret=$?; rm -f "$dsttmp" "$rmtmp" && exit $ret' 0
- trap '(exit $?); exit' 1 2 13 15
-
- # Copy the file name to the temp name.
- $doit $cpprog "$src" "$dsttmp" &&
-
- # and set any options; do chmod last to preserve setuid bits.
- #
- # If any of these fail, we abort the whole thing. If we want to
- # ignore errors from any of these, just make sure not to ignore
- # errors from the above "$doit $cpprog $src $dsttmp" command.
- #
- { test -z "$chowncmd" || $doit $chowncmd "$dsttmp"; } \
- && { test -z "$chgrpcmd" || $doit $chgrpcmd "$dsttmp"; } \
- && { test -z "$stripcmd" || $doit $stripcmd "$dsttmp"; } \
- && { test -z "$chmodcmd" || $doit $chmodcmd "$dsttmp"; } &&
-
- # Now rename the file to the real destination.
- { $doit $mvcmd -f "$dsttmp" "$dstdir/$dstfile" 2>/dev/null \
- || {
- # The rename failed, perhaps because mv can't rename something else
- # to itself, or perhaps because mv is so ancient that it does not
- # support -f.
-
- # Now remove or move aside any old file at destination location.
- # We try this two ways since rm can't unlink itself on some
- # systems and the destination file might be busy for other
- # reasons. In this case, the final cleanup might fail but the new
- # file should still install successfully.
- {
- if test -f "$dstdir/$dstfile"; then
- $doit $rmcmd -f "$dstdir/$dstfile" 2>/dev/null \
- || $doit $mvcmd -f "$dstdir/$dstfile" "$rmtmp" 2>/dev/null \
- || {
- echo "$0: cannot unlink or rename $dstdir/$dstfile" >&2
- (exit 1); exit
- }
- else
- :
- fi
- } &&
-
- # Now rename the file to the real destination.
- $doit $mvcmd "$dsttmp" "$dstdir/$dstfile"
- }
- }
- fi || { (exit 1); exit; }
-done
-
-# The final little trick to "correctly" pass the exit status to the exit trap.
-{
- (exit 0); exit
-}
-
-# Local variables:
-# eval: (add-hook 'write-file-hooks 'time-stamp)
-# time-stamp-start: "scriptversion="
-# time-stamp-format: "%:y-%02m-%02d.%02H"
-# time-stamp-end: "$"
-# End:
diff --git a/vmkit/configure b/vmkit/configure
deleted file mode 100755
index 06ebd02..0000000
--- a/vmkit/configure
+++ /dev/null
Binary files differ
diff --git a/vmkit/docs/index.html b/vmkit/docs/index.html
deleted file mode 100644
index 3f29c77..0000000
--- a/vmkit/docs/index.html
+++ /dev/null
@@ -1 +0,0 @@
-vmkit dox go here.
diff --git a/vmkit/find-it.sh b/vmkit/find-it.sh
deleted file mode 100755
index 83adbee..0000000
--- a/vmkit/find-it.sh
+++ /dev/null
@@ -1,11 +0,0 @@
-#!/bin/bash
-
-if [ -z "$1" ]; then
-
- echo $0 pattern
-
-else
-
- grep --exclude find-it.sh --exclude-dir IJvm --exclude-dir Isolate --exclude *.txt --exclude-dir autoconf --exclude config.status --exclude config.log --exclude configure --exclude *.xml --exclude *.html --exclude *.jar --exclude *.bc --exclude MMTkInline.inc --exclude-dir patches --exclude-dir N3 --exclude *.java --exclude *.class -R --exclude-dir .svn --exclude-dir Release --exclude *.s "$1" .
-
-fi
\ No newline at end of file
diff --git a/vmkit/include/debug.h b/vmkit/include/debug.h
deleted file mode 100644
index cbac536..0000000
--- a/vmkit/include/debug.h
+++ /dev/null
@@ -1,87 +0,0 @@
-//===----------------- debug.h - Debug facilities -------------------------===//
-//
-// The VMKit project
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#ifndef DEBUG_H
-#define DEBUG_H
-
-#define ESC "\033["
-#define COLOR_NORMAL ""
-#define END "m"
-
-#define _BLACK "00"
-#define _RED "01"
-#define _GREEN "02"
-#define _YELLOW "03"
-#define _BLUE "04"
-#define _MAGENTA "05"
-#define _CYAN "06"
-#define _WHITE "07"
-
-#define _NORMAL "00"
-#define _BOLD "01"
-#define _SOULIGNE "04"
-
-#define MK_COLOR(type, bg, fg) type";"bg";"fg
-
-#define WHITE MK_COLOR(_NORMAL, _BLACK, _BLACK)
-
-#define DARK_MAGENTA MK_COLOR(_NORMAL, _BLACK, _MAGENTA)
-#define DARK_YELLOW MK_COLOR(_NORMAL, _BLACK, _YELLOW)
-#define DARK_CYAN MK_COLOR(_NORMAL, _BLACK, _CYAN)
-#define DARK_BLUE MK_COLOR(_NORMAL, _BLACK, _BLUE)
-#define DARK_GREEN MK_COLOR(_NORMAL, _BLACK, _GREEN)
-
-#define LIGHT_MAGENTA MK_COLOR(_BOLD, _BLACK, _MAGENTA)
-#define LIGHT_YELLOW MK_COLOR(_BOLD, _BLACK, _YELLOW)
-#define LIGHT_CYAN MK_COLOR(_BOLD, _BLACK, _CYAN)
-#define LIGHT_BLUE MK_COLOR(_BOLD, _BLACK, _BLUE)
-#define LIGHT_GREEN MK_COLOR(_BOLD, _BLACK, _GREEN)
-#define LIGHT_RED MK_COLOR(_BOLD, _BLACK, _RED)
-
-#if DEBUG > 0
-
- #ifdef WITH_COLOR
- #define PRINT_DEBUG(symb, level, color, ...) \
- if (symb > level) { \
- fprintf(stderr, "%s%s%s", ESC, color, END); \
- fprintf(stderr, __VA_ARGS__); \
- fprintf(stderr, "%s%s%s", ESC, COLOR_NORMAL, END); \
- }
- #else
- #define PRINT_DEBUG(symb, level, color, ...) \
- if (symb > level) { \
- fprintf(stderr, __VA_ARGS__); \
- }
- #endif
-
-#else
-#define PRINT_DEBUG(symb, level, color, args...) do {} while(0);
-#endif
-
-#define UNIMPLEMENTED() { \
- mvm::Thread::get()->printBacktrace(); \
- fprintf(stderr, "%s:%d\n", __FILE__, __LINE__); \
- abort(); } \
-
-#define ABORT() UNIMPLEMENTED()
-#define UNREACHABLE() ABORT()
-
-#define ASSERT(cond) { \
- if (!cond) { fprintf(stderr, "fatal: assert("#cond")\n"); ABORT(); } } \
-
-#undef ALWAYS_INLINE
-#define ALWAYS_INLINE __attribute__ ((always_inline))
-
-#ifndef DEBUG
-#ifdef _DEBUG
-#define DEBUG
-#endif
-#endif
-
-#endif
diff --git a/vmkit/include/j3/J3Intrinsics.h b/vmkit/include/j3/J3Intrinsics.h
deleted file mode 100644
index 932d125..0000000
--- a/vmkit/include/j3/J3Intrinsics.h
+++ /dev/null
@@ -1,155 +0,0 @@
-//===-------------- J3Intrinsics.h - Intrinsics of J3 ---------------------===//
-//
-// The VMKit project
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#ifndef J3_INTRINSICS_H
-#define J3_INTRINSICS_H
-
-#include "mvm/JIT.h"
-
-namespace j3 {
-
-class J3Intrinsics : public mvm::BaseIntrinsics {
-
-public:
- const llvm::Type* JavaArrayUInt8Type;
- const llvm::Type* JavaArraySInt8Type;
- const llvm::Type* JavaArrayUInt16Type;
- const llvm::Type* JavaArraySInt16Type;
- const llvm::Type* JavaArrayUInt32Type;
- const llvm::Type* JavaArraySInt32Type;
- const llvm::Type* JavaArrayLongType;
- const llvm::Type* JavaArrayFloatType;
- const llvm::Type* JavaArrayDoubleType;
- const llvm::Type* JavaArrayObjectType;
-
- const llvm::Type* JavaObjectType;
- const llvm::Type* JavaObjectPtrType;
- const llvm::Type* JavaArrayType;
- const llvm::Type* JavaCommonClassType;
- const llvm::Type* JavaClassType;
- const llvm::Type* JavaClassArrayType;
- const llvm::Type* JavaClassPrimitiveType;
- const llvm::Type* ConstantPoolType;
- const llvm::Type* CodeLineInfoType;
- const llvm::Type* UTF8Type;
- const llvm::Type* JavaMethodType;
- const llvm::Type* JavaFieldType;
- const llvm::Type* AttributType;
- const llvm::Type* JavaThreadType;
-
- llvm::Function* StartJNIFunction;
- llvm::Function* EndJNIFunction;
- llvm::Function* InterfaceLookupFunction;
- llvm::Function* VirtualFieldLookupFunction;
- llvm::Function* StaticFieldLookupFunction;
- llvm::Function* PrintExecutionFunction;
- llvm::Function* PrintMethodStartFunction;
- llvm::Function* PrintMethodEndFunction;
- llvm::Function* InitialiseClassFunction;
- llvm::Function* InitialisationCheckFunction;
- llvm::Function* ForceInitialisationCheckFunction;
- llvm::Function* ForceLoadedCheckFunction;
- llvm::Function* ClassLookupFunction;
- llvm::Function* StringLookupFunction;
-
- llvm::Function* ResolveVirtualStubFunction;
- llvm::Function* ResolveSpecialStubFunction;
- llvm::Function* ResolveStaticStubFunction;
- llvm::Function* ResolveInterfaceFunction;
-
-#ifndef WITHOUT_VTABLE
- llvm::Function* VirtualLookupFunction;
-#endif
- llvm::Function* IsAssignableFromFunction;
- llvm::Function* IsSecondaryClassFunction;
- llvm::Function* GetDepthFunction;
- llvm::Function* GetDisplayFunction;
- llvm::Function* GetVTInDisplayFunction;
- llvm::Function* GetStaticInstanceFunction;
- llvm::Function* AquireObjectFunction;
- llvm::Function* ReleaseObjectFunction;
- llvm::Function* GetConstantPoolAtFunction;
- llvm::Function* MultiCallNewFunction;
- llvm::Function* GetArrayClassFunction;
-
- llvm::Function* GetClassDelegateeFunction;
- llvm::Function* RuntimeDelegateeFunction;
- llvm::Function* ArrayLengthFunction;
- llvm::Function* GetVTFunction;
- llvm::Function* GetIMTFunction;
- llvm::Function* GetClassFunction;
- llvm::Function* GetVTFromClassFunction;
- llvm::Function* GetVTFromClassArrayFunction;
- llvm::Function* GetVTFromCommonClassFunction;
- llvm::Function* GetObjectSizeFromClassFunction;
- llvm::Function* GetBaseClassVTFromVTFunction;
-
- llvm::Function* GetLockFunction;
-
- llvm::Function* GetFinalInt8FieldFunction;
- llvm::Function* GetFinalInt16FieldFunction;
- llvm::Function* GetFinalInt32FieldFunction;
- llvm::Function* GetFinalLongFieldFunction;
- llvm::Function* GetFinalFloatFieldFunction;
- llvm::Function* GetFinalDoubleFieldFunction;
-
- llvm::Constant* JavaArraySizeOffsetConstant;
- llvm::Constant* JavaArrayElementsOffsetConstant;
- llvm::Constant* JavaObjectLockOffsetConstant;
- llvm::Constant* JavaObjectVTOffsetConstant;
-
- llvm::Constant* OffsetAccessInCommonClassConstant;
- llvm::Constant* IsArrayConstant;
- llvm::Constant* IsPrimitiveConstant;
- llvm::Constant* OffsetObjectSizeInClassConstant;
- llvm::Constant* OffsetVTInClassConstant;
- llvm::Constant* OffsetTaskClassMirrorInClassConstant;
- llvm::Constant* OffsetStaticInstanceInTaskClassMirrorConstant;
- llvm::Constant* OffsetInitializedInTaskClassMirrorConstant;
- llvm::Constant* OffsetStatusInTaskClassMirrorConstant;
-
- llvm::Constant* OffsetJNIInJavaThreadConstant;
- llvm::Constant* OffsetJavaExceptionInJavaThreadConstant;
-
- llvm::Constant* OffsetClassInVTConstant;
- llvm::Constant* OffsetDepthInVTConstant;
- llvm::Constant* OffsetDisplayInVTConstant;
- llvm::Constant* OffsetBaseClassVTInVTConstant;
- llvm::Constant* OffsetIMTInVTConstant;
-
- llvm::Constant* OffsetBaseClassInArrayClassConstant;
- llvm::Constant* OffsetLogSizeInPrimitiveClassConstant;
-
- llvm::Constant* ClassReadyConstant;
-
- llvm::Constant* JavaObjectNullConstant;
- llvm::Constant* MaxArraySizeConstant;
- llvm::Constant* JavaArraySizeConstant;
-
- llvm::Function* ThrowExceptionFunction;
- llvm::Function* NullPointerExceptionFunction;
- llvm::Function* IndexOutOfBoundsExceptionFunction;
- llvm::Function* ClassCastExceptionFunction;
- llvm::Function* OutOfMemoryErrorFunction;
- llvm::Function* StackOverflowErrorFunction;
- llvm::Function* NegativeArraySizeExceptionFunction;
- llvm::Function* ArrayStoreExceptionFunction;
- llvm::Function* ArithmeticExceptionFunction;
- llvm::Function* ThrowExceptionFromJITFunction;
-
-
- J3Intrinsics(llvm::Module*);
-
- static void initialise();
-
-};
-
-}
-
-#endif
diff --git a/vmkit/include/j3/JavaAOTCompiler.h b/vmkit/include/j3/JavaAOTCompiler.h
deleted file mode 100644
index a006c32..0000000
--- a/vmkit/include/j3/JavaAOTCompiler.h
+++ /dev/null
@@ -1,188 +0,0 @@
-//===------ JavaAOTCompiler.h - The J3 ahead of time compiler -------------===//
-//
-// The VMKit project
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#ifndef J3_AOT_COMPILER_H
-#define J3_AOT_COMPILER_H
-
-#include "j3/JavaLLVMCompiler.h"
-
-namespace j3 {
-
-class ArrayObject;
-class Attribut;
-
-using mvm::UTF8;
-
-class JavaAOTCompiler : public JavaLLVMCompiler {
-
-public:
- JavaAOTCompiler(const std::string &ModuleID);
-
- virtual bool isStaticCompiling() {
- return true;
- }
-
- virtual bool emitFunctionName() {
- return true;
- }
-
- virtual JavaCompiler* Create(const std::string& ModuleID) {
- return new JavaAOTCompiler(ModuleID);
- }
-
- virtual void* materializeFunction(JavaMethod* meth) {
- fprintf(stderr, "Can not materiale a function in AOT mode.");
- abort();
- }
-
- virtual void* GenerateStub(llvm::Function* F) {
- // Do nothing in case of AOT.
- return NULL;
- }
-
- virtual llvm::Value* addCallback(Class* cl, uint16 index, Signdef* sign,
- bool stat, llvm::BasicBlock* insert);
-
- virtual void makeVT(Class* cl);
- virtual void makeIMT(Class* cl);
-
- llvm::Constant* HandleMagic(JavaObject* obj, CommonClass* cl);
- virtual llvm::Constant* getFinalObject(JavaObject* obj, CommonClass* cl);
- virtual JavaObject* getFinalObject(llvm::Value* C);
- virtual llvm::Constant* getNativeClass(CommonClass* cl);
- virtual llvm::Constant* getJavaClass(CommonClass* cl);
- virtual llvm::Constant* getJavaClassPtr(CommonClass* cl);
- virtual llvm::Constant* getStaticInstance(Class* cl);
- virtual llvm::Constant* getVirtualTable(JavaVirtualTable*);
- virtual llvm::Constant* getMethodInClass(JavaMethod* meth);
-
- virtual llvm::Constant* getString(JavaString* str);
- virtual llvm::Constant* getStringPtr(JavaString** str);
- virtual llvm::Constant* getConstantPool(JavaConstantPool* ctp);
- virtual llvm::Constant* getNativeFunction(JavaMethod* meth, void* natPtr);
-
- virtual void setMethod(llvm::Function* func, void* ptr, const char* name);
-
- virtual ~JavaAOTCompiler() {}
-
- virtual void* loadMethod(void* handle, const char* symbol);
-
- virtual CommonClass* getUniqueBaseClass(CommonClass* cl);
-
-private:
-
- //--------------- Static compiler specific functions -----------------------//
- llvm::Constant* CreateConstantFromVT(JavaVirtualTable* VT);
- llvm::Constant* CreateConstantFromUTF8(const UTF8* val);
- llvm::Constant* CreateConstantFromCommonClass(CommonClass* cl);
- llvm::Constant* CreateConstantFromClass(Class* cl);
- llvm::Constant* CreateConstantFromClassPrimitive(ClassPrimitive* cl);
- llvm::Constant* CreateConstantFromClassArray(ClassArray* cl);
- llvm::Constant* CreateConstantFromAttribut(Attribut& attribut);
- llvm::Constant* CreateConstantFromJavaField(JavaField& field);
- llvm::Constant* CreateConstantFromJavaMethod(JavaMethod& method);
- llvm::Constant* CreateConstantFromStaticInstance(Class* cl);
- llvm::Constant* CreateConstantFromJavaString(JavaString* str);
- llvm::Constant* CreateConstantFromJavaClass(CommonClass* cl);
- llvm::Constant* CreateConstantForBaseObject(CommonClass* cl);
- llvm::Constant* CreateConstantFromJavaObject(JavaObject* obj);
- llvm::Constant* getUTF8(const UTF8* val);
-
- template<typename T>
- llvm::Constant* CreateConstantFromIntArray(const T* val, const llvm::Type* Ty);
-
- template<typename T>
- llvm::Constant* CreateConstantFromFPArray(const T* val, const llvm::Type* Ty);
-
- llvm::Constant* CreateConstantFromObjectArray(const ArrayObject* val);
-
- std::map<const CommonClass*, llvm::Constant*> nativeClasses;
- std::map<const ClassArray*, llvm::GlobalVariable*> arrayClasses;
- std::map<const CommonClass*, llvm::Constant*> javaClasses;
- std::map<const JavaVirtualTable*, llvm::Constant*> virtualTables;
- std::map<const Class*, llvm::Constant*> staticInstances;
- std::map<const JavaConstantPool*, llvm::Constant*> constantPools;
- std::map<const JavaString*, llvm::Constant*> strings;
- std::map<const JavaMethod*, llvm::Constant*> nativeFunctions;
- std::map<const UTF8*, llvm::Constant*> utf8s;
- std::map<const Class*, llvm::Constant*> virtualMethods;
- std::map<const JavaObject*, llvm::Constant*> finalObjects;
- std::map<const llvm::Constant*, JavaObject*> reverseFinalObjects;
-
- typedef std::map<const JavaObject*, llvm::Constant*>::iterator
- final_object_iterator;
-
- typedef std::map<const llvm::Constant*, JavaObject*>::iterator
- reverse_final_object_iterator;
-
- typedef std::map<const Class*, llvm::Constant*>::iterator
- method_iterator;
-
- typedef std::map<const CommonClass*, llvm::Constant*>::iterator
- native_class_iterator;
-
- typedef std::map<const ClassArray*, llvm::GlobalVariable*>::iterator
- array_class_iterator;
-
- typedef std::map<const CommonClass*, llvm::Constant*>::iterator
- java_class_iterator;
-
- typedef std::map<const JavaVirtualTable*, llvm::Constant*>::iterator
- virtual_table_iterator;
-
- typedef std::map<const Class*, llvm::Constant*>::iterator
- static_instance_iterator;
-
- typedef std::map<const JavaConstantPool*, llvm::Constant*>::iterator
- constant_pool_iterator;
-
- typedef std::map<const JavaString*, llvm::Constant*>::iterator
- string_iterator;
-
- typedef std::map<const JavaMethod*, llvm::Constant*>::iterator
- native_function_iterator;
-
- typedef std::map<const UTF8*, llvm::Constant*>::iterator
- utf8_iterator;
-
- bool isCompiling(const CommonClass* cl) const;
-
-public:
- llvm::Function* StaticInitializer;
- llvm::Function* ObjectPrinter;
- llvm::Function* Callback;
- llvm::Function* ArrayObjectTracer;
- llvm::Function* RegularObjectTracer;
- llvm::Function* JavaObjectTracer;
- llvm::Function* ReferenceObjectTracer;
-
- bool generateStubs;
- bool assumeCompiled;
- bool compileRT;
-
- std::vector<std::string>* clinits;
-
-
- void CreateStaticInitializer();
-
- void setNoInline(Class* cl);
-
- void printStats();
-
- void compileFile(Jnjvm* vm, const char* name);
- void compileClass(Class* cl);
- void generateMain(const char* name, bool jit);
-
-private:
- void compileAllStubs(Signdef* sign);
-};
-
-} // end namespace j3
-
-#endif
diff --git a/vmkit/include/j3/JavaCompiler.h b/vmkit/include/j3/JavaCompiler.h
deleted file mode 100644
index 6a18383..0000000
--- a/vmkit/include/j3/JavaCompiler.h
+++ /dev/null
@@ -1,119 +0,0 @@
-//===---------- JavaCompiler.h - J3 interface for the compiler ------------===//
-//
-// The VMKit project
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#ifndef JAVA_COMPILER_H
-#define JAVA_COMPILER_H
-
-#include <cstdio>
-#include <cstdlib>
-#include <string>
-#include <dlfcn.h>
-
-#include "mvm/GC.h"
-#include "mvm/Allocator.h"
-
-namespace mvm {
- class UTF8;
-}
-
-namespace j3 {
-
-class Class;
-class CommonClass;
-class JavaMethod;
-class JavaVirtualTable;
-class JnjvmClassLoader;
-class Signdef;
-
-class JavaCompiler {
-public:
-
- mvm::BumpPtrAllocator allocator;
-
- virtual JavaCompiler* Create(const std::string&) {
- return this;
- }
-
- virtual void* materializeFunction(JavaMethod* meth) {
- fprintf(stderr, "Materializing a function in an empty compiler");
- abort();
- return 0;
- }
-
- virtual bool isStaticCompiling() {
- return false;
- }
-
- virtual bool emitFunctionName() {
- return false;
- }
-
- virtual void resolveVirtualClass(Class* cl) {
- fprintf(stderr, "Resolving a class in an empty compiler");
- abort();
- }
-
- virtual void resolveStaticClass(Class* cl) {
- fprintf(stderr, "Resolving a class in an empty compiler");
- abort();
- }
-
-
- virtual void staticCallBuf(Signdef* sign) {
- fprintf(stderr, "Asking for a callback in an empty compiler");
- abort();
- }
-
- virtual void virtualCallBuf(Signdef* sign) {
- fprintf(stderr, "Asking for a callback in an empty compiler");
- abort();
- }
-
- virtual void staticCallAP(Signdef* sign) {
- fprintf(stderr, "Asking for a callback in an empty compiler");
- abort();
- }
-
- virtual void virtualCallAP(Signdef* sign) {
- fprintf(stderr, "Asking for a callback in an empty compiler");
- abort();
- }
-
- virtual void virtualCallStub(Signdef* sign) {
- fprintf(stderr, "Asking for a callback in an empty compiler");
- abort();
- }
-
- virtual void specialCallStub(Signdef* sign) {
- fprintf(stderr, "Asking for a callback in an empty compiler");
- abort();
- }
-
- virtual void staticCallStub(Signdef* sign) {
- fprintf(stderr, "Asking for a callback in an empty compiler");
- abort();
- }
-
- virtual ~JavaCompiler() {}
-
- virtual void* loadMethod(void* handle, const char* symbol) {
- return dlsym(handle, symbol);
- }
-
- static const mvm::UTF8* InlinePragma;
- static const mvm::UTF8* NoInlinePragma;
-
- virtual CommonClass* getUniqueBaseClass(CommonClass* cl) {
- return 0;
- }
-};
-
-}
-
-#endif
diff --git a/vmkit/include/j3/JavaJITCompiler.h b/vmkit/include/j3/JavaJITCompiler.h
deleted file mode 100644
index d5e4eb1..0000000
--- a/vmkit/include/j3/JavaJITCompiler.h
+++ /dev/null
@@ -1,101 +0,0 @@
-//===------- JavaJITCompiler.h - The J3 just in time compiler -------------===//
-//
-// The VMKit project
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#ifndef J3_JIT_COMPILER_H
-#define J3_JIT_COMPILER_H
-
-#include "llvm/CodeGen/GCMetadata.h"
-#include "llvm/ExecutionEngine/ExecutionEngine.h"
-#include "llvm/ExecutionEngine/JITEventListener.h"
-#include "j3/JavaLLVMCompiler.h"
-
-namespace j3 {
-
-class JavaJITCompiler;
-
-class JavaJITListener : public llvm::JITEventListener {
- JavaJITCompiler* TheCompiler;
-public:
- JavaJITListener(JavaJITCompiler* Compiler) {
- TheCompiler = Compiler;
- }
-
- virtual void NotifyFunctionEmitted(
- const llvm::Function &F,
- void *Code,
- size_t Size,
- const llvm::JITEventListener::EmittedFunctionDetails &Details);
-};
-
-class JavaJITCompiler : public JavaLLVMCompiler {
-public:
-
- bool EmitFunctionName;
- JavaJITListener listener;
- llvm::ExecutionEngine* executionEngine;
- llvm::GCModuleInfo* GCInfo;
-
- JavaJITCompiler(const std::string &ModuleID);
- ~JavaJITCompiler();
-
- virtual bool isStaticCompiling() {
- return false;
- }
-
- virtual void* GenerateStub(llvm::Function* F);
-
- virtual bool emitFunctionName() {
- return EmitFunctionName;
- }
-
- virtual void makeVT(Class* cl);
- virtual void makeIMT(Class* cl);
-
- virtual void* materializeFunction(JavaMethod* meth);
-
- virtual llvm::Constant* getFinalObject(JavaObject* obj, CommonClass* cl);
- virtual JavaObject* getFinalObject(llvm::Value* C);
- virtual llvm::Constant* getNativeClass(CommonClass* cl);
- virtual llvm::Constant* getJavaClass(CommonClass* cl);
- virtual llvm::Constant* getJavaClassPtr(CommonClass* cl);
- virtual llvm::Constant* getStaticInstance(Class* cl);
- virtual llvm::Constant* getVirtualTable(JavaVirtualTable*);
- virtual llvm::Constant* getMethodInClass(JavaMethod* meth);
-
- virtual llvm::Constant* getString(JavaString* str);
- virtual llvm::Constant* getStringPtr(JavaString** str);
- virtual llvm::Constant* getConstantPool(JavaConstantPool* ctp);
- virtual llvm::Constant* getNativeFunction(JavaMethod* meth, void* natPtr);
-
- virtual void setMethod(llvm::Function* func, void* ptr, const char* name);
-
- virtual llvm::Value* addCallback(Class* cl, uint16 index, Signdef* sign,
- bool stat, llvm::BasicBlock* insert) = 0;
- virtual uintptr_t getPointerOrStub(JavaMethod& meth, int type) = 0;
-
- static JavaJITCompiler* CreateCompiler(const std::string& ModuleID);
-};
-
-class JavaJ3LazyJITCompiler : public JavaJITCompiler {
-public:
- virtual bool needsCallback(JavaMethod* meth, bool* needsInit);
- virtual llvm::Value* addCallback(Class* cl, uint16 index, Signdef* sign,
- bool stat, llvm::BasicBlock* insert);
- virtual uintptr_t getPointerOrStub(JavaMethod& meth, int side);
-
- virtual JavaCompiler* Create(const std::string& ModuleID) {
- return new JavaJ3LazyJITCompiler(ModuleID);
- }
-
- JavaJ3LazyJITCompiler(const std::string& ModuleID);
-};
-
-} // end namespace j3
-
-#endif
diff --git a/vmkit/include/j3/JavaLLVMCompiler.h b/vmkit/include/j3/JavaLLVMCompiler.h
deleted file mode 100644
index 69ce7b3..0000000
--- a/vmkit/include/j3/JavaLLVMCompiler.h
+++ /dev/null
@@ -1,246 +0,0 @@
-//===---==---- JavaLLVMCompiler.h - A LLVM Compiler for J3 ----------------===//
-//
-// The VMKit project
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#ifndef J3_LLVM_COMPILER_H
-#define J3_LLVM_COMPILER_H
-
-#include "j3/JavaCompiler.h"
-#include "j3/J3Intrinsics.h"
-#include "j3/LLVMInfo.h"
-
-#include "llvm/LLVMContext.h"
-#include "llvm/Module.h"
-
-#include <map>
-
-namespace llvm {
- class BasicBlock;
- class DIFactory;
-}
-
-namespace j3 {
-
-class CommonClass;
-class Class;
-class ClassArray;
-class ClassPrimitive;
-class JavaConstantPool;
-class JavaField;
-class JavaMethod;
-class JavaObject;
-class JavaString;
-class JavaVirtualTable;
-class Jnjvm;
-class Typedef;
-class Signdef;
-
-class JavaLLVMCompiler : public JavaCompiler {
- friend class LLVMClassInfo;
- friend class LLVMMethodInfo;
-
-protected:
- llvm::Module* TheModule;
- llvm::DIFactory* DebugFactory;
- J3Intrinsics JavaIntrinsics;
-
-private:
- bool enabledException;
- bool cooperativeGC;
-
- virtual void makeVT(Class* cl) = 0;
- virtual void makeIMT(Class* cl) = 0;
-
- std::map<const llvm::Function*, JavaMethod*> functions;
- typedef std::map<const llvm::Function*, JavaMethod*>::iterator function_iterator;
-
- std::map<JavaMethod*, LLVMMethodInfo*> method_infos;
- typedef std::map<JavaMethod*, LLVMMethodInfo*>::iterator method_info_iterator;
-
- std::map<JavaField*, LLVMFieldInfo*> field_infos;
- typedef std::map<JavaField*, LLVMFieldInfo*>::iterator field_info_iterator;
-
- std::map<Signdef*, LLVMSignatureInfo*> signature_infos;
- typedef std::map<Signdef*, LLVMSignatureInfo*>::iterator signature_info_iterator;
-
- std::map<Class*, LLVMClassInfo*> class_infos;
- typedef std::map<Class*, LLVMClassInfo*>::iterator class_info_iterator;
-
- std::map<llvm::MDNode*, JavaMethod*> DbgInfos;
- typedef std::map<llvm::MDNode*, JavaMethod*>::iterator dbg_iterator;
-
-public:
- JavaLLVMCompiler(const std::string &ModuleID);
-
- virtual bool isStaticCompiling() = 0;
- virtual bool emitFunctionName() = 0;
- virtual void* GenerateStub(llvm::Function* F) = 0;
- void addJavaPasses();
-
- llvm::DIFactory* getDebugFactory() {
- return DebugFactory;
- }
-
- llvm::Module* getLLVMModule() {
- return TheModule;
- }
-
- llvm::LLVMContext& getLLVMContext() {
- return TheModule->getContext();
- }
-
- J3Intrinsics* getIntrinsics() {
- return &JavaIntrinsics;
- }
-
- bool hasExceptionsEnabled() {
- return enabledException;
- }
-
- bool useCooperativeGC() {
- return cooperativeGC;
- }
-
- void disableExceptions() {
- enabledException = false;
- }
-
- void disableCooperativeGC() {
- cooperativeGC = false;
- }
-
- virtual JavaCompiler* Create(const std::string& ModuleID) = 0;
-
- virtual ~JavaLLVMCompiler();
-
- JavaMethod* getJavaMethod(const llvm::Function&);
- llvm::MDNode* GetDbgSubprogram(JavaMethod* meth);
-
- void resolveVirtualClass(Class* cl);
- void resolveStaticClass(Class* cl);
- llvm::Function* getMethod(JavaMethod* meth);
-
- void initialiseAssessorInfo();
- std::map<const char, LLVMAssessorInfo> AssessorInfo;
- LLVMAssessorInfo& getTypedefInfo(const Typedef* type);
-
- LLVMSignatureInfo* getSignatureInfo(Signdef* sign) {
- signature_info_iterator E = signature_infos.end();
- signature_info_iterator I = signature_infos.find(sign);
- if (I == E) {
- LLVMSignatureInfo* signInfo =
- new(allocator, "LLVMSignatureInfo") LLVMSignatureInfo(sign, this);
- signature_infos.insert(std::make_pair(sign, signInfo));
- return signInfo;
- } else {
- return I->second;
- }
- }
-
- LLVMFieldInfo* getFieldInfo(JavaField* field) {
- field_info_iterator E = field_infos.end();
- field_info_iterator I = field_infos.find(field);
- if (I == E) {
- LLVMFieldInfo* fieldInfo =
- new(allocator, "LLVMFieldInfo") LLVMFieldInfo(field, this);
- field_infos.insert(std::make_pair(field, fieldInfo));
- return fieldInfo;
- } else {
- return I->second;
- }
- }
-
- LLVMClassInfo* getClassInfo(Class* klass) {
- class_info_iterator E = class_infos.end();
- class_info_iterator I = class_infos.find(klass);
- if (I == E) {
- LLVMClassInfo* classInfo =
- new(allocator, "LLVMClassInfo") LLVMClassInfo(klass, this);
- class_infos.insert(std::make_pair(klass, classInfo));
- return classInfo;
- } else {
- return I->second;
- }
- }
-
- LLVMMethodInfo* getMethodInfo(JavaMethod* method) {
- method_info_iterator E = method_infos.end();
- method_info_iterator I = method_infos.find(method);
- if (I == E) {
- LLVMMethodInfo* methodInfo =
- new(allocator, "LLVMMethodInfo") LLVMMethodInfo(method, this);
- method_infos.insert(std::make_pair(method, methodInfo));
- return methodInfo;
- } else {
- return I->second;
- }
- }
-
- virtual llvm::Constant* getFinalObject(JavaObject* obj, CommonClass* cl) = 0;
- virtual JavaObject* getFinalObject(llvm::Value* C) = 0;
- virtual llvm::Constant* getNativeClass(CommonClass* cl) = 0;
- virtual llvm::Constant* getJavaClass(CommonClass* cl) = 0;
- virtual llvm::Constant* getJavaClassPtr(CommonClass* cl) = 0;
- virtual llvm::Constant* getStaticInstance(Class* cl) = 0;
- virtual llvm::Constant* getVirtualTable(JavaVirtualTable*) = 0;
- virtual llvm::Constant* getMethodInClass(JavaMethod* meth) = 0;
-
- virtual llvm::Constant* getString(JavaString* str) = 0;
- virtual llvm::Constant* getStringPtr(JavaString** str) = 0;
- virtual llvm::Constant* getConstantPool(JavaConstantPool* ctp) = 0;
- virtual llvm::Constant* getNativeFunction(JavaMethod* meth, void* natPtr) = 0;
-
- virtual void setMethod(llvm::Function* func, void* ptr, const char* name) = 0;
-
- virtual void* materializeFunction(JavaMethod* meth) = 0;
- llvm::Function* parseFunction(JavaMethod* meth);
-
- llvm::FunctionPassManager* JavaFunctionPasses;
- llvm::FunctionPassManager* JavaNativeFunctionPasses;
-
- virtual bool needsCallback(JavaMethod* meth, bool* needsInit) {
- *needsInit = true;
- return meth == NULL;
- }
- virtual llvm::Value* addCallback(Class* cl, uint16 index, Signdef* sign,
- bool stat, llvm::BasicBlock* insert) = 0;
-
- virtual void staticCallBuf(Signdef* sign) {
- getSignatureInfo(sign)->getStaticBuf();
- }
-
- virtual void virtualCallBuf(Signdef* sign) {
- getSignatureInfo(sign)->getVirtualBuf();
- }
-
- virtual void staticCallAP(Signdef* sign) {
- getSignatureInfo(sign)->getStaticAP();
- }
-
- virtual void virtualCallAP(Signdef* sign) {
- getSignatureInfo(sign)->getVirtualAP();
- }
-
- virtual void virtualCallStub(Signdef* sign) {
- getSignatureInfo(sign)->getVirtualStub();
- }
-
- virtual void specialCallStub(Signdef* sign) {
- getSignatureInfo(sign)->getSpecialStub();
- }
-
- virtual void staticCallStub(Signdef* sign) {
- getSignatureInfo(sign)->getStaticStub();
- }
-
- llvm::Function* NativeLoader;
-};
-
-} // end namespace j3
-
-#endif
diff --git a/vmkit/include/j3/LLVMInfo.h b/vmkit/include/j3/LLVMInfo.h
deleted file mode 100644
index ba45f9b..0000000
--- a/vmkit/include/j3/LLVMInfo.h
+++ /dev/null
@@ -1,209 +0,0 @@
-//===------------- LLVMInfo.h - Compiler info for LLVM --------------------===//
-//
-// The VMKit project
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#ifndef J3_LLVM_INFO_H
-#define J3_LLVM_INFO_H
-
-namespace llvm {
- class Constant;
- class Function;
- class FunctionType;
- class GCFunctionInfo;
- class MDNode;
- class Module;
- class Type;
- class Value;
-}
-
-namespace j3 {
-
-class Class;
-class JavaField;
-class JavaLLVMCompiler;
-class JavaMethod;
-class Signdef;
-
-class LLVMAssessorInfo {
-public:
- const llvm::Type* llvmType;
- const llvm::Type* llvmTypePtr;
- uint8_t logSizeInBytesConstant;
-};
-
-class LLVMClassInfo : public mvm::JITInfo {
- friend class JavaAOTCompiler;
- friend class JavaJITCompiler;
- friend class JavaLLVMCompiler;
-private:
- /// Compiler - The compiler for this class info.
- JavaLLVMCompiler* Compiler;
-
- Class* classDef;
-
- /// virtualSizeLLVM - The LLVM constant size of instances of this class.
- llvm::Constant* virtualSizeConstant;
-
- /// virtualType - The LLVM type of instance of this class.
- const llvm::Type * virtualType;
-
- /// staticType - The LLVM type of the static instance of this class.
- const llvm::Type * staticType;
-
-public:
-
- llvm::Value* getVirtualSize();
- const llvm::Type* getVirtualType();
- const llvm::Type* getStaticType();
-
- LLVMClassInfo(Class* cl, JavaLLVMCompiler* comp) :
- Compiler(comp),
- classDef(cl),
- virtualSizeConstant(0),
- virtualType(0),
- staticType(0) {}
-
- virtual void clear() {
- virtualType = 0;
- staticType = 0;
- virtualSizeConstant = 0;
- }
-};
-
-class LLVMMethodInfo : public mvm::JITInfo {
-private:
- /// Compiler - The compiler for this method info.
- JavaLLVMCompiler* Compiler;
-
- JavaMethod* methodDef;
-
- llvm::Function* methodFunction;
- llvm::Constant* offsetConstant;
- const llvm::FunctionType* functionType;
- llvm::MDNode* DbgSubprogram;
-
-public:
- llvm::Function* getMethod();
- llvm::Constant* getOffset();
- const llvm::FunctionType* getFunctionType();
-
- LLVMMethodInfo(JavaMethod* M, JavaLLVMCompiler* comp) : Compiler(comp),
- methodDef(M), methodFunction(0), offsetConstant(0), functionType(0),
- DbgSubprogram(0) {}
-
- void setDbgSubprogram(llvm::MDNode* node) { DbgSubprogram = node; }
- llvm::MDNode* getDbgSubprogram() { return DbgSubprogram; }
-
- virtual void clear() {
- methodFunction = 0;
- offsetConstant = 0;
- functionType = 0;
- DbgSubprogram = 0;
- }
-};
-
-
-class LLVMFieldInfo : public mvm::JITInfo {
-private:
- /// Compiler - The compiler for this field info.
- JavaLLVMCompiler* Compiler;
-
- JavaField* fieldDef;
-
- llvm::Constant* offsetConstant;
-
-public:
- llvm::Constant* getOffset();
-
- LLVMFieldInfo(JavaField* F, JavaLLVMCompiler* comp) :
- Compiler(comp),
- fieldDef(F),
- offsetConstant(0) {}
-
- virtual void clear() {
- offsetConstant = 0;
- }
-};
-
-class LLVMSignatureInfo : public mvm::JITInfo {
-private:
- /// Compiler - The compiler for this signature info.
- JavaLLVMCompiler* Compiler;
-
- const llvm::FunctionType* staticType;
- const llvm::FunctionType* virtualType;
- const llvm::FunctionType* nativeType;
-
- const llvm::FunctionType* virtualBufType;
- const llvm::FunctionType* staticBufType;
-
- const llvm::PointerType* staticPtrType;
- const llvm::PointerType* virtualPtrType;
- const llvm::PointerType* nativePtrType;
-
- llvm::Function* virtualBufFunction;
- llvm::Function* virtualAPFunction;
- llvm::Function* staticBufFunction;
- llvm::Function* staticAPFunction;
-
- llvm::Function* staticStubFunction;
- llvm::Function* specialStubFunction;
- llvm::Function* virtualStubFunction;
-
- Signdef* signature;
-
- llvm::Function* createFunctionCallBuf(bool virt);
- llvm::Function* createFunctionCallAP(bool virt);
- llvm::Function* createFunctionStub(bool special, bool virt);
-
-
-public:
- const llvm::FunctionType* getVirtualType();
- const llvm::FunctionType* getStaticType();
- const llvm::FunctionType* getNativeType();
-
- const llvm::FunctionType* getVirtualBufType();
- const llvm::FunctionType* getStaticBufType();
-
- const llvm::PointerType* getStaticPtrType();
- const llvm::PointerType* getNativePtrType();
- const llvm::PointerType* getVirtualPtrType();
-
- llvm::Function* getVirtualBuf();
- llvm::Function* getVirtualAP();
- llvm::Function* getStaticBuf();
- llvm::Function* getStaticAP();
-
- llvm::Function* getStaticStub();
- llvm::Function* getSpecialStub();
- llvm::Function* getVirtualStub();
-
- LLVMSignatureInfo(Signdef* sign, JavaLLVMCompiler* comp) :
- Compiler(comp),
- staticType(0),
- virtualType(0),
- nativeType(0),
- virtualBufType(0),
- staticBufType(0),
- staticPtrType(0),
- virtualPtrType(0),
- nativePtrType(0),
- virtualBufFunction(0),
- virtualAPFunction(0),
- staticBufFunction(0),
- staticAPFunction(0),
- staticStubFunction(0),
- specialStubFunction(0),
- virtualStubFunction(0),
- signature(sign) {}
-
-};
-
-} // end namespace j3
-
-#endif
diff --git a/vmkit/include/j3/LLVMMaterializer.h b/vmkit/include/j3/LLVMMaterializer.h
deleted file mode 100644
index fa4bbd6..0000000
--- a/vmkit/include/j3/LLVMMaterializer.h
+++ /dev/null
@@ -1,74 +0,0 @@
-//===---------- LLVMMaterializer.h - LLVM Materializer for J3 -------------===//
-//
-// The VMKit project
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#ifndef J3_LLVM_MATERIALIZER_H
-#define J3_LLVM_MATERIALIZER_H
-
-#include <llvm/GVMaterializer.h>
-
-#include "j3/JavaJITCompiler.h"
-
-namespace j3 {
-
-class LLVMMaterializer;
-
-struct CallbackInfo {
- Class* cl;
- uint16 index;
- bool stat;
-
- CallbackInfo(Class* c, uint32 i, bool s) :
- cl(c), index(i), stat(s) {}
-
-};
-
-class JavaLLVMLazyJITCompiler : public JavaJITCompiler {
-private:
- std::map<llvm::Function*, CallbackInfo> callbacks;
- typedef std::map<llvm::Function*, CallbackInfo>::iterator callback_iterator;
-
-public:
- llvm::GVMaterializer* TheMaterializer;
-
- virtual llvm::Value* addCallback(Class* cl, uint16 index, Signdef* sign,
- bool stat, llvm::BasicBlock* insert);
- virtual uintptr_t getPointerOrStub(JavaMethod& meth, int side);
-
- virtual JavaCompiler* Create(const std::string& ModuleID) {
- return new JavaLLVMLazyJITCompiler(ModuleID);
- }
-
- JavaLLVMLazyJITCompiler(const std::string& ModuleID);
-
- virtual ~JavaLLVMLazyJITCompiler();
-
- virtual void* loadMethod(void* handle, const char* symbol);
-
- friend class LLVMMaterializer;
-};
-
-class LLVMMaterializer : public llvm::GVMaterializer {
-public:
-
- JavaLLVMLazyJITCompiler* Comp;
- llvm::Module* TheModule;
-
- LLVMMaterializer(llvm::Module* M, JavaLLVMLazyJITCompiler* C);
-
- virtual bool Materialize(llvm::GlobalValue *GV, std::string *ErrInfo = 0);
- virtual bool isMaterializable(const llvm::GlobalValue*) const;
- virtual bool isDematerializable(const llvm::GlobalValue*) const {
- return false;
- }
- virtual bool MaterializeModule(llvm::Module*, std::string*) { return true; }
-};
-
-} // End j3 namespace
-
-#endif
diff --git a/vmkit/include/j3/OpcodeNames.def b/vmkit/include/j3/OpcodeNames.def
deleted file mode 100644
index 0228d1c..0000000
--- a/vmkit/include/j3/OpcodeNames.def
+++ /dev/null
@@ -1,221 +0,0 @@
-//===-------------- OpcodeNames.def - Name of opcodes ---------------------===//
-//
-// The VMKit project
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#ifndef OPCODE_NAMES_DEF
-#define OPCODE_NAMES_DEF
-
-static const char* OpcodeNames[256] = {
- "NOP",
- "ACONST_NULL",
- "ICONST_M1",
- "ICONST_0",
- "ICONST_1",
- "ICONST_2",
- "ICONST_3",
- "ICONST_4",
- "ICONST_5",
- "LCONST_0",
- "LCONST_1",
- "FCONST_0",
- "FCONST_1",
- "FCONST_2",
- "DCONST_0",
- "DCONST_1",
- "BIPUSH",
- "SIPUSH",
- "LDC",
- "LDC_W",
- "LDC2_W",
- "ILOAD",
- "LLOAD",
- "FLOAD",
- "DLOAD",
- "ALOAD",
- "ILOAD_0",
- "ILOAD_1",
- "ILOAD_2",
- "ILOAD_3",
- "LLOAD_0",
- "LLOAD_1",
- "LLOAD_2",
- "LLOAD_3",
- "FLOAD_0",
- "FLOAD_1",
- "FLOAD_2",
- "FLOAD_3",
- "DLOAD_0",
- "DLOAD_1",
- "DLOAD_2",
- "DLOAD_3",
- "ALOAD_0",
- "ALOAD_1",
- "ALOAD_2",
- "ALOAD_3",
- "IALOAD",
- "LALOAD",
- "FALOAD",
- "DALOAD",
- "AALOAD",
- "BALOAD",
- "CALOAD",
- "SALOAD",
- "ISTORE",
- "LSTORE",
- "FSTORE",
- "DSTORE",
- "ASTORE",
- "ISTORE_0",
- "ISTORE_1",
- "ISTORE_2",
- "ISTORE_3",
- "LSTORE_0",
- "LSTORE_1",
- "LSTORE_2",
- "LSTORE_3",
- "FSTORE_0",
- "FSTORE_1",
- "FSTORE_2",
- "FSTORE_3",
- "DSTORE_0",
- "DSTORE_1",
- "DSTORE_2",
- "DSTORE_3",
- "ASTORE_0",
- "ASTORE_1",
- "ASTORE_2",
- "ASTORE_3",
- "IASTORE",
- "LASTORE",
- "FASTORE",
- "DASTORE",
- "AASTORE",
- "BASTORE",
- "CASTORE",
- "SASTORE",
- "POP",
- "POP2",
- "DUP",
- "DUP_X1",
- "DUP_X2",
- "DUP2",
- "DUP2_X1",
- "DUP2_X2",
- "SWAP",
- "IADD",
- "LADD",
- "FADD",
- "DADD",
- "ISUB",
- "LSUB",
- "FSUB",
- "DSUB",
- "IMUL",
- "LMUL",
- "FMUL",
- "DMUL",
- "IDIV",
- "LDIV",
- "FDIV",
- "DDIV",
- "IREM",
- "LREM",
- "FREM",
- "DREM",
- "INEG",
- "LNEG",
- "FNEG",
- "DNEG",
- "ISHL",
- "LSHL",
- "ISHR",
- "LSHR",
- "IUSHR",
- "LUSHR",
- "IAND",
- "LAND",
- "IOR",
- "LOR",
- "IXOR",
- "LXOR",
- "IINC",
- "I2L",
- "I2F",
- "I2D",
- "L2I",
- "L2F",
- "L2D",
- "F2I",
- "F2L",
- "F2D",
- "D2I",
- "D2L",
- "D2F",
- "I2B",
- "I2C",
- "I2S",
- "LCMP",
- "FCMPL",
- "FCMPG",
- "DCMPL",
- "DCMPG",
- "IFEQ",
- "IFNE",
- "IFLT",
- "IFGE",
- "IFGT",
- "IFLE",
- "IF_ICMPEQ",
- "IF_ICMPNE",
- "IF_ICMPLT",
- "IF_ICMPGE",
- "IF_ICMPGT",
- "IF_ICMPLE",
- "IF_ACMPEQ",
- "IF_ACMPNE",
- "GOTO",
- "JSR",
- "RET",
- "TABLESWITCH",
- "LOOKUPSWITCH",
- "IRETURN",
- "LRETURN",
- "FRETURN",
- "DRETURN",
- "ARETURN",
- "RETURN",
- "GETSTATIC",
- "PUTSTATIC",
- "GETFIELD",
- "PUTFIELD",
- "INVOKEVIRTUAL",
- "INVOKESPECIAL",
- "INVOKESTATIC",
- "INVOKEINTERFACE",
- "UNUSED",
- "NEW",
- "NEWARRAY",
- "ANEWARRAY",
- "ARRAYLENGTH",
- "ATHROW",
- "CHECKCAST",
- "INSTANCEOF",
- "MONITORENTER",
- "MONITOREXIT",
- "WIDE",
- "MULTIANEWARRAY",
- "IFNULL",
- "IFNONNULL",
- "GOTO_W",
- "JSR_W",
- "BREAKPOINT",
- "IMPDEP1",
- "IMPDEP2"
-};
-
-#endif
diff --git a/vmkit/include/mvm/Allocator.h b/vmkit/include/mvm/Allocator.h
deleted file mode 100644
index 1083c47..0000000
--- a/vmkit/include/mvm/Allocator.h
+++ /dev/null
@@ -1,99 +0,0 @@
-//===----------- Allocator.h - A memory allocator ------------------------===//
-//
-// The VMKit project
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#ifndef MVM_ALLOCATOR_H
-#define MVM_ALLOCATOR_H
-
-#include <cstdlib>
-#include <cstring>
-#include <limits>
-
-#include "llvm/Support/Allocator.h"
-
-#include "mvm/Threads/Locks.h"
-
-#define declare_gcroot(type, name) type name; llvm_gcroot(name, 0); name
-
-namespace mvm {
-
-class BumpPtrAllocator {
-private:
- SpinLock TheLock;
- llvm::BumpPtrAllocator Allocator;
-public:
- void* Allocate(size_t sz, const char* name) {
-#ifdef USE_GC_BOEHM
- return GC_MALLOC(sz);
-#else
- TheLock.acquire();
- void* res = Allocator.Allocate(sz, sizeof(void*));
- TheLock.release();
- memset(res, 0, sz);
- return res;
-#endif
- }
-
- void Deallocate(void* obj) {}
-
-};
-
-class ThreadAllocator {
-private:
- llvm::BumpPtrAllocator Allocator;
-public:
- void* Allocate(size_t sz) {
-#ifdef USE_GC_BOEHM
- return GC_MALLOC(sz);
-#else
- void* res = Allocator.Allocate(sz, sizeof(void*));
- memset(res, 0, sz);
- return res;
-#endif
- }
-
- void Deallocate(void* obj) {}
-
-};
-
-class PermanentObject {
-public:
- void* operator new(size_t sz, BumpPtrAllocator& allocator,
- const char* name) {
- return allocator.Allocate(sz, name);
- }
-
- void operator delete(void* ptr) {
- free(ptr);
- }
-
- void* operator new [](size_t sz, BumpPtrAllocator& allocator,
- const char* name) {
- return allocator.Allocate(sz, name);
- }
-
- void* operator new[](size_t sz) {
- return malloc(sz);
- }
-
- void operator delete[](void* ptr) {
- return free(ptr);
- }
-};
-
-/// JITInfo - This class can be derived from to hold private JIT-specific
-/// information. Objects of type are accessed/created with
-/// <Class>::getInfo and destroyed when the <Class> object is destroyed.
-struct JITInfo : public mvm::PermanentObject {
- virtual ~JITInfo() {}
- virtual void clear() {}
-};
-
-} // end namespace mvm
-
-#endif // MVM_ALLOCATOR_H
diff --git a/vmkit/include/mvm/Config/config.h.in b/vmkit/include/mvm/Config/config.h.in
deleted file mode 100644
index d5d4b76..0000000
--- a/vmkit/include/mvm/Config/config.h.in
+++ /dev/null
@@ -1,97 +0,0 @@
-/* include/mvm/Config/config.h.in. Generated from autoconf/configure.ac by autoheader. */
-
-/* Define to 1 if the system has the type `int64_t'. */
-#undef HAVE_INT64_T
-
-/* Define to 1 if you have the <inttypes.h> header file. */
-#undef HAVE_INTTYPES_H
-
-/* Define to 1 if you have the `gc' library (-lgc). */
-#undef HAVE_LIBGC
-
-/* Define to 1 if you have the `pthread' library (-lpthread). */
-#undef HAVE_LIBPTHREAD
-
-/* Define to 1 if you have the `z' library (-lz). */
-#undef HAVE_LIBZ
-
-/* Define to 1 if you have the `longjmp' function. */
-#undef HAVE_LONGJMP
-
-/* Define to 1 if you have the <memory.h> header file. */
-#undef HAVE_MEMORY_H
-
-/* Using pthread library */
-#undef HAVE_PTHREAD
-
-/* Define to 1 if you have the `setjmp' function. */
-#undef HAVE_SETJMP
-
-/* Define to 1 if you have the <stdint.h> header file. */
-#undef HAVE_STDINT_H
-
-/* Define to 1 if you have the <stdlib.h> header file. */
-#undef HAVE_STDLIB_H
-
-/* Define to 1 if you have the <strings.h> header file. */
-#undef HAVE_STRINGS_H
-
-/* Define to 1 if you have the <string.h> header file. */
-#undef HAVE_STRING_H
-
-/* Define to 1 if you have the <sys/stat.h> header file. */
-#undef HAVE_SYS_STAT_H
-
-/* Define to 1 if you have the <sys/types.h> header file. */
-#undef HAVE_SYS_TYPES_H
-
-/* Define to 1 if the system has the type `uint64_t'. */
-#undef HAVE_UINT64_T
-
-/* Define to 1 if you have the <unistd.h> header file. */
-#undef HAVE_UNISTD_H
-
-/* Define to 1 if the system has the type `u_int64_t'. */
-#undef HAVE_U_INT64_T
-
-/* Define to the address where bug reports for this package should be sent. */
-#undef PACKAGE_BUGREPORT
-
-/* Define to the full name of this package. */
-#undef PACKAGE_NAME
-
-/* Define to the full name and version of this package. */
-#undef PACKAGE_STRING
-
-/* Define to the one symbol short name of this package. */
-#undef PACKAGE_TARNAME
-
-/* Define to the version of this package. */
-#undef PACKAGE_VERSION
-
-/* Define as the return type of signal handlers (`int' or `void'). */
-#undef RETSIGTYPE
-
-/* Define to 1 if you have the ANSI C header files. */
-#undef STDC_HEADERS
-
-/* Define to 1 if your <sys/time.h> declares `struct tm'. */
-#undef TM_IN_SYS_TIME
-
-/* Using the boehm gc */
-#undef USE_GC_BOEHM
-
-/* Using the gcmmap2 */
-#undef USE_GC_MMAP2
-
-/* Compiling N3 */
-#undef WITH_N3
-
-/* Compiling JNJVM */
-#undef WITH_J3
-
-/* Define to `int' if <sys/types.h> does not define. */
-#undef pid_t
-
-/* Define to `unsigned int' if <sys/types.h> does not define. */
-#undef size_t
diff --git a/vmkit/include/mvm/GC.h b/vmkit/include/mvm/GC.h
deleted file mode 100644
index 5e4b1ed..0000000
--- a/vmkit/include/mvm/GC.h
+++ /dev/null
@@ -1,80 +0,0 @@
-//===----------- GC.h - Garbage Collection Interface -----------------------===//
-//
-// The Micro Virtual Machine
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-
-#ifndef _GC_H_
-#define _GC_H_
-
-#include <stdint.h>
-#include "ObjectHeader.h"
-
-#ifdef WITH_LLVM_GCC
-extern "C" void __llvm_gcroot(void**, void*) __attribute__((nothrow));
-#define llvm_gcroot(a, b) __llvm_gcroot((void**)&a, b)
-#else
-#define llvm_gcroot(a, b)
-#endif
-
-namespace mvm {
-
- class VirtualMachine;
- class VirtualTable;
- class gc;
-
- class gcRoot {
- public:
- virtual ~gcRoot() {}
- virtual void tracer(uintptr_t closure) {}
- uintptr_t header;
-
- /// getVirtualTable - Returns the virtual table of this object.
- ///
- VirtualTable* getVirtualTable() const {
- return ((VirtualTable**)(this))[0];
- }
-
- /// setVirtualTable - Sets the virtual table of this object.
- ///
- void setVirtualTable(VirtualTable* VT) {
- ((VirtualTable**)(this))[0] = VT;
- }
- };
-
- // WARNING: if you modify this class, you must also change the generation of VT in JavaAOTCompiler
- class CommonVirtualTable {
- public:
- uintptr_t destructor;
- uintptr_t operatorDelete;
- uintptr_t tracer;
- VirtualMachine* vm;
-
- uintptr_t* getFunctions() {
- return &destructor;
- }
-
- static int numberOfCommonEntries() { return 4; }
-
- static void emptyTracer(void*) {}
- };
-
-} // namespace mvm
-
-#include "MvmGC.h"
-
-namespace mvm {
- class gc : public collectable {
- };
-
- class VirtualTable : public GCVirtualTable {};
-
- static const uint32_t HashBits = 8;
- static const uint64_t GCBitMask = ((1 << GCBits) - 1);
-} // namespace mvm
-
-#endif
diff --git a/vmkit/include/mvm/JIT.h b/vmkit/include/mvm/JIT.h
deleted file mode 100644
index f526443..0000000
--- a/vmkit/include/mvm/JIT.h
+++ /dev/null
@@ -1,238 +0,0 @@
-//===------------------ JIT.h - JIT facilities ----------------------------===//
-//
-// The Micro Virtual Machine
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#ifndef MVM_JIT_H
-#define MVM_JIT_H
-
-#include <cfloat>
-#include <cmath>
-#include <string>
-
-#include "types.h"
-
-#include "llvm/Target/TargetMachine.h"
-
-#include "mvm/MethodInfo.h"
-#include "mvm/GC.h"
-
-namespace llvm {
- class Constant;
- class ConstantFP;
- class ConstantInt;
- class ExecutionEngine;
- class Function;
- class FunctionPassManager;
- class GCFunctionInfo;
- class GCStrategy;
- class JIT;
- class Module;
- class PointerType;
- class TargetData;
- class TargetMachine;
- class Type;
-}
-
-namespace mvm {
-
-class LockRecursive;
-
-const double MaxDouble = +INFINITY; //1.0 / 0.0;
-const double MinDouble = -INFINITY;//-1.0 / 0.0;
-const double MaxLongDouble = 9223372036854775807.0;
-const double MinLongDouble = -9223372036854775808.0;
-const double MaxIntDouble = 2147483647.0;
-const double MinIntDouble = -2147483648.0;
-const uint64 MaxLong = 9223372036854775807LL;
-const uint64 MinLong = -9223372036854775808ULL;
-const uint32 MaxInt = 2147483647;
-const uint32 MinInt = -2147483648U;
-const float MaxFloat = +INFINITY; //(float)(((float)1.0) / (float)0.0);
-const float MinFloat = -INFINITY; //(float)(((float)-1.0) / (float)0.0);
-const float MaxLongFloat = (float)9223372036854775807.0;
-const float MinLongFloat = (float)-9223372036854775808.0;
-const float MaxIntFloat = (float)2147483647.0;
-const float MinIntFloat = (float)-2147483648.0;
-const float NaNFloat = NAN; //(float)(((float)0.0) / (float)0.0);
-const double NaNDouble = NAN; //0.0 / 0.0;
-
-class BaseIntrinsics {
-
-public:
-
- explicit BaseIntrinsics(llvm::Module*);
-
- llvm::Function* exceptionEndCatch;
- llvm::Function* exceptionBeginCatch;
- llvm::Function* unwindResume;
- llvm::Function* exceptionSelector;
- llvm::Function* personality;
- llvm::Function* llvmGetException;
-
- llvm::Function* printFloatLLVM;
- llvm::Function* printDoubleLLVM;
- llvm::Function* printLongLLVM;
- llvm::Function* printIntLLVM;
- llvm::Function* printObjectLLVM;
-
- llvm::Function* setjmpLLVM;
-
- llvm::Function* func_llvm_fabs_f32;
- llvm::Function* func_llvm_fabs_f64;
- llvm::Function* func_llvm_sqrt_f64;
- llvm::Function* func_llvm_sin_f64;
- llvm::Function* func_llvm_cos_f64;
- llvm::Function* func_llvm_tan_f64;
- llvm::Function* func_llvm_asin_f64;
- llvm::Function* func_llvm_acos_f64;
- llvm::Function* func_llvm_atan_f64;
- llvm::Function* func_llvm_atan2_f64;
- llvm::Function* func_llvm_exp_f64;
- llvm::Function* func_llvm_log_f64;
- llvm::Function* func_llvm_pow_f64;
- llvm::Function* func_llvm_ceil_f64;
- llvm::Function* func_llvm_floor_f64;
- llvm::Function* func_llvm_rint_f64;
- llvm::Function* func_llvm_cbrt_f64;
- llvm::Function* func_llvm_cosh_f64;
- llvm::Function* func_llvm_expm1_f64;
- llvm::Function* func_llvm_hypot_f64;
- llvm::Function* func_llvm_log10_f64;
- llvm::Function* func_llvm_log1p_f64;
- llvm::Function* func_llvm_sinh_f64;
- llvm::Function* func_llvm_tanh_f64;
-
- llvm::Function* llvm_memcpy_i32;
- llvm::Function* llvm_memset_i32;
- llvm::Function* llvm_frameaddress;
- llvm::Function* llvm_atomic_lcs_i8;
- llvm::Function* llvm_atomic_lcs_i16;
- llvm::Function* llvm_atomic_lcs_i32;
- llvm::Function* llvm_atomic_lcs_i64;
- llvm::Function* llvm_atomic_lcs_ptr;
- llvm::Function* llvm_gc_gcroot;
-
- llvm::Function* conditionalSafePoint;
- llvm::Function* unconditionalSafePoint;
- llvm::Function* AllocateFunction;
- llvm::Function* AllocateUnresolvedFunction;
- llvm::Function* AddFinalizationCandidate;
-
- llvm::Constant* constantInt8Zero;
- llvm::Constant* constantZero;
- llvm::Constant* constantOne;
- llvm::Constant* constantTwo;
- llvm::Constant* constantThree;
- llvm::Constant* constantFour;
- llvm::Constant* constantFive;
- llvm::Constant* constantSix;
- llvm::Constant* constantSeven;
- llvm::Constant* constantEight;
- llvm::Constant* constantMinusOne;
- llvm::Constant* constantLongMinusOne;
- llvm::Constant* constantLongZero;
- llvm::Constant* constantLongOne;
- llvm::Constant* constantMinInt;
- llvm::Constant* constantMaxInt;
- llvm::Constant* constantMinLong;
- llvm::Constant* constantMaxLong;
- llvm::Constant* constantFloatZero;
- llvm::Constant* constantFloatOne;
- llvm::Constant* constantFloatTwo;
- llvm::Constant* constantDoubleZero;
- llvm::Constant* constantDoubleOne;
- llvm::Constant* constantMaxIntFloat;
- llvm::Constant* constantMinIntFloat;
- llvm::Constant* constantMinLongFloat;
- llvm::Constant* constantMinLongDouble;
- llvm::Constant* constantMaxLongFloat;
- llvm::Constant* constantMaxIntDouble;
- llvm::Constant* constantMinIntDouble;
- llvm::Constant* constantMaxLongDouble;
- llvm::Constant* constantDoubleInfinity;
- llvm::Constant* constantDoubleMinusInfinity;
- llvm::Constant* constantFloatInfinity;
- llvm::Constant* constantFloatMinusInfinity;
- llvm::Constant* constantFloatMinusZero;
- llvm::Constant* constantDoubleMinusZero;
- llvm::Constant* constantPtrNull;
- llvm::Constant* constantPtrLogSize;
- llvm::Constant* constantThreadIDMask;
- llvm::Constant* constantStackOverflowMask;
- llvm::Constant* constantFatMask;
- llvm::Constant* constantPtrOne;
- llvm::Constant* constantPtrZero;
-
- const llvm::PointerType* ptrType;
- const llvm::PointerType* ptr32Type;
- const llvm::PointerType* ptrPtrType;
- const llvm::Type* arrayPtrType;
- const llvm::Type* pointerSizeType;
-
- const llvm::Type* MutatorThreadType;
- const llvm::Type* VTType;
-
- llvm::Constant* OffsetDoYieldInThreadConstant;
- llvm::Constant* OffsetCXXExceptionInThreadConstant;
- llvm::Constant* OffsetVMDataInThreadConstant;
- llvm::Constant* OffsetPendingExceptionInThreadConstant;
-
- llvm::Constant* OffsetThreadInMutatorThreadConstant;
-};
-
-
-class MvmModule {
-public:
- static llvm::GCStrategy* TheGCStrategy;
- static mvm::LockRecursive protectEngine;
- static llvm::Module *globalModule;
- static const llvm::TargetData* TheTargetData;
- static mvm::BumpPtrAllocator* Allocator;
- static llvm::ExecutionEngine* executionEngine;
- //static unsigned MetadataTypeKind;
-
- static uint64 getTypeSize(const llvm::Type* type);
- static void runPasses(llvm::Function* func, llvm::FunctionPassManager*);
- static void initialise(llvm::CodeGenOpt::Level = llvm::CodeGenOpt::Default,
- llvm::Module* TheModule = 0,
- llvm::TargetMachine* TheTarget = 0);
- static void loadBytecodeFile(const std::string& str);
-
- static int disassemble(unsigned int* addr);
-
- static void protectIR();
- static void unprotectIR();
-
- static void addCommandLinePasses(llvm::FunctionPassManager* PM);
-
- static const char* getHostTriple();
-};
-
-class JITMethodInfo : public MethodInfo {
- llvm::GCFunctionInfo* GCInfo;
-public:
- virtual void scan(uintptr_t closure, void* ip, void* addr);
- JITMethodInfo(llvm::GCFunctionInfo* GFI) : GCInfo(GFI) {}
- void addToVMKit(VMKit* vmkit, llvm::JIT* jit);
-};
-
-class MvmJITMethodInfo : public JITMethodInfo {
-public:
- virtual void print(void* ip, void* addr);
- MvmJITMethodInfo(llvm::GCFunctionInfo* GFI,
- const llvm::Function* F,
- void* owner) :
- JITMethodInfo(GFI) {
- MetaInfo = const_cast<llvm::Function*>(F);
- Owner = owner;
- }
-};
-
-} // end namespace mvm
-
-#endif // MVM_JIT_H
diff --git a/vmkit/include/mvm/MethodInfo.h b/vmkit/include/mvm/MethodInfo.h
deleted file mode 100644
index 1a66505..0000000
--- a/vmkit/include/mvm/MethodInfo.h
+++ /dev/null
@@ -1,80 +0,0 @@
-//===---------- MethodInfo.h - Meta information for methods ---------------===//
-//
-// The VMKit project
-//
-// This file is distributed under the University of Pierre et Marie Curie
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#ifndef MVM_METHODINFO_H
-#define MVM_METHODINFO_H
-
-#include "mvm/Allocator.h"
-#include "mvm/GC.h"
-
-namespace mvm {
-
-class MethodInfo : public PermanentObject {
-public:
- virtual void print(void* ip, void* addr) = 0;
- virtual void scan(uintptr_t closure, void* ip, void* addr) = 0;
- virtual bool isHighLevelMethod() {
- return false;
- }
-
- static void* isStub(void* ip, void* addr) {
- bool isStub = ((unsigned char*)ip)[0] == 0xCE;
- if (isStub) ip = ((void**)addr)[2];
- return ip;
- }
-
- void* MetaInfo;
- void* Owner;
-};
-
-class CamlFrame {
-public:
- void* ReturnAddress;
- uint16_t FrameSize;
- uint16_t NumLiveOffsets;
- int16_t LiveOffsets[1];
-};
-
-class CamlMethodInfo : public MethodInfo {
-public:
- CamlFrame* CF;
- virtual void scan(uintptr_t closure, void* ip, void* addr);
- CamlMethodInfo(CamlFrame* C) : CF(C) {
- Owner = NULL;
- MetaInfo = NULL;
- }
-};
-
-class StaticCamlMethodInfo : public CamlMethodInfo {
- const char* name;
-public:
- virtual void print(void* ip, void* addr);
- StaticCamlMethodInfo(CamlFrame* CF, const char* n) :
- CamlMethodInfo(CF) {
- Owner = NULL;
- MetaInfo = NULL;
- name = n;
- }
-};
-
-class DefaultMethodInfo : public MethodInfo {
-public:
- virtual void print(void* ip, void* addr);
- virtual void scan(uintptr_t closure, void* ip, void* addr);
- static DefaultMethodInfo DM;
-
- DefaultMethodInfo() {
- Owner = NULL;
- MetaInfo = NULL;
- }
-};
-
-
-} // end namespace mvm
-#endif // MVM_METHODINFO_H
diff --git a/vmkit/include/mvm/PrintBuffer.h b/vmkit/include/mvm/PrintBuffer.h
deleted file mode 100644
index 9c59333..0000000
--- a/vmkit/include/mvm/PrintBuffer.h
+++ /dev/null
@@ -1,211 +0,0 @@
-//===--------------- PrintBuffer.h - Printing objects ----------------------===//
-//
-// The Micro Virtual Machine
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#ifndef MVM_PRINTBUFFER_H
-#define MVM_PRINTBUFFER_H
-
-#include <cstdio> // sprintf
-#include <cstring> // memcpy
-
-#include "types.h"
-#include "mvm/UTF8.h"
-
-namespace mvm {
-
-// #define VT_DESTRUCTOR_OFFSET 0
-// #define VT_OPERATOR_DELETE_OFFSET 1
-// #define VT_TRACER_OFFSET 2
-// #define VT_PRINT_OFFSET 3
-// #define VT_HASHCODE_OFFSET 4
-// #define VT_NB_FUNCS 5
-// #define VT_SIZE 5 * sizeof(void*)
-
-class PrintBuffer;
-
-/// OldObject - Root of all objects. Define default implementations of virtual
-/// methods and some commodity functions.
-/// ************ Technically this class is not used anywhere, to be removed? ************
-///
-class OldObject : public gc {
-public:
- static void default_tracer(gc *o, uintptr_t closure) {}
- static intptr_t default_hashCode(const gc *o) { return (intptr_t)o; }
- static void default_print(const gc *o, PrintBuffer *buf);
-
- /// tracer - Default implementation of tracer. Does nothing.
- ///
- virtual void tracer(uintptr_t closure) { default_tracer(this, closure); }
-
- /// print - Default implementation of print.
- ///
- virtual void print(PrintBuffer *buf) const { default_print(this, buf); }
-
- /// hashCode - Default implementation of hashCode. Returns the address
- /// of this object.
- ///
- virtual intptr_t hashCode() const { return default_hashCode(this);}
-
-};
-
-/// PrintBuffer - This class is a buffered string.
-///
-class PrintBuffer {
-public:
-
- /// contents - The buffer.
- ///
- char* contents;
-
- /// capacity - The capacity of the current buffer.
- ///
- uint32 capacity;
-
- /// writePosition - The position in the buffer where the next write will
- /// happen.
- ///
- uint32 writePosition;
-
- void init() {
- capacity = 256;
- contents = new char[capacity];
- writePosition = 0;
- }
-
-public:
- PrintBuffer() {
- init();
- }
-
- PrintBuffer(const OldObject *obj) {
- llvm_gcroot(obj, 0);
- init();
- writeObj(obj);
- }
-
- PrintBuffer(const UTF8 *utf8) {
- init();
- writeUTF8(utf8);
- }
-
- virtual ~PrintBuffer() {
- delete[] contents;
- }
-
- char *cString() {
- return contents;
- }
-
- void ensureCapacity(uint32 len) {
- uint32 size = writePosition + len + 1;
- if (size >= capacity) {
- while (size >= capacity)
- capacity*= 4;
- char *newContents = new char[capacity];
- memcpy(newContents, contents, writePosition);
- delete[] contents;
- contents = newContents;
- }
- }
-
- /// write - Writes to this PrintBuffer.
- ///
- virtual PrintBuffer *write(const char *string) {
- uint32 len= strlen(string);
- ensureCapacity(len);
- strcpy(cString() + writePosition, string);
- writePosition+= len;
- return this;
- }
-
- /// writeChar - Writes a char.
- inline PrintBuffer *writeUTF8(const UTF8 *utf8) {
- uint32 len = utf8->size;
- ensureCapacity(len);
- for(uint32 i=0; i<len; i++) {
- // printf("%d/%d: '%c (%d)'\n", i, len, utf8->elements[i], utf8->elements[i]);
- contents[writePosition + i] = utf8->elements[i];
- }
- contents[writePosition += len] = 0;
- return this;
- }
-
- /// writeChar - Writes a char.
- inline PrintBuffer *writeBool(bool v) {
- return write(v ? "true" : "false");
- }
-
- /// writeChar - Writes a char.
- inline PrintBuffer *writeChar(char v) {
- char buf[32];
- sprintf(buf, "%c", v);
- return write(buf);
- }
-
- /// writeChar - Writes a int32.
- inline PrintBuffer *writeS4(int v) {
- char buf[32];
- sprintf(buf, "%d", v);
- return write(buf);
- }
-
- /// writes8 - Writes a int64.
- inline PrintBuffer *writeS8(sint64 v) {
- char buf[32];
- sprintf(buf, "%lld", (long long int)v);
- return write(buf);
- }
-
- /// writeFP - Writes a double.
- inline PrintBuffer *writeFP(double v) {
- char buf[32];
- sprintf(buf, "%f", v);
- return write(buf);
- }
-
- /// writePtr - Writes a pointer.
- inline PrintBuffer *writePtr(void *p) {
- char buf[32];
- sprintf(buf, "%p", p);
- return write(buf);
- }
-
- /// writeBytes - Writes len bytes in the buffer bytes.
- inline PrintBuffer *writeBytes(unsigned char *bytes, size_t len) {
- write("[");
- for (size_t idx= 0; idx < len; ++idx) {
- if (idx > 0)
- write(" ");
- char buf[32];
- sprintf(buf, "%d", bytes[idx]);
- write(buf);
- }
- write("]");
- return this;
- }
-
- /// writeObj - Writes a gc Object to the buffer.
- ///
- inline PrintBuffer *writeObj(const OldObject *obj) {
- llvm_gcroot(obj, 0);
- obj->print(this);
- return this;
- }
-
-
- /// replaceWith - replace the content of the buffer and free the old buffer
- ///
- void replaceWith(char *buffer) {
- delete[] this->contents;
- this->contents = buffer;
- }
-};
-
-} // end namespace mvm
-
-#endif // MVM_PRINTBUFFER_H
diff --git a/vmkit/include/mvm/SystemThreads.h b/vmkit/include/mvm/SystemThreads.h
deleted file mode 100644
index df6e148..0000000
--- a/vmkit/include/mvm/SystemThreads.h
+++ /dev/null
@@ -1,181 +0,0 @@
-#ifndef _SYSTEM_THREADS_H_
-#define _SYSTEM_THREADS_H_
-
-#include "MutatorThread.h"
-#include "mvm/Threads/Cond.h"
-
-// Same values than JikesRVM
-#define INITIAL_QUEUE_SIZE 256
-#define GROW_FACTOR 2
-
-namespace mvm {
-class VirtualMachine;
-
-class ReferenceThread;
-class Jnjvm;
-
-class ReferenceQueue {
-private:
- mvm::gc** References;
- uint32 QueueLength;
- uint32 CurrentIndex;
- mvm::SpinLock QueueLock;
- uint8_t semantics;
-
- mvm::gc* processReference(mvm::gc*, ReferenceThread*, uintptr_t closure);
-public:
-
- static const uint8_t WEAK = 1;
- static const uint8_t SOFT = 2;
- static const uint8_t PHANTOM = 3;
-
-
- ReferenceQueue(uint8_t s) {
- References = new mvm::gc*[INITIAL_QUEUE_SIZE];
- memset(References, 0, INITIAL_QUEUE_SIZE * sizeof(mvm::gc*));
- QueueLength = INITIAL_QUEUE_SIZE;
- CurrentIndex = 0;
- semantics = s;
- }
-
- ~ReferenceQueue() {
- delete[] References;
- }
-
- void addReference(mvm::gc* ref);
-
- void acquire() {
- QueueLock.acquire();
- }
-
- void release() {
- QueueLock.release();
- }
-
- void scan(ReferenceThread* thread, uintptr_t closure);
-};
-
-class ReferenceThread : public mvm::MutatorThread {
-public:
- /// WeakReferencesQueue - The queue of weak references.
- ///
- ReferenceQueue WeakReferencesQueue;
-
- /// SoftReferencesQueue - The queue of soft references.
- ///
- ReferenceQueue SoftReferencesQueue;
-
- /// PhantomReferencesQueue - The queue of phantom references.
- ///
- ReferenceQueue PhantomReferencesQueue;
-
- mvm::gc** ToEnqueue;
- uint32 ToEnqueueLength;
- uint32 ToEnqueueIndex;
-
- /// ToEnqueueLock - A lock to protect access to the queue.
- ///
- mvm::LockNormal EnqueueLock;
- mvm::Cond EnqueueCond;
- mvm::SpinLock ToEnqueueLock;
-
- void addToEnqueue(mvm::gc* obj);
-
- static void enqueueStart(ReferenceThread*);
-
- /// addWeakReference - Add a weak reference to the queue.
- ///
- void addWeakReference(mvm::gc* ref);
-
- /// addSoftReference - Add a weak reference to the queue.
- ///
- void addSoftReference(mvm::gc* ref);
-
- /// addPhantomReference - Add a weak reference to the queue.
- ///
- void addPhantomReference(mvm::gc* ref);
-
- ReferenceThread(mvm::VMKit* vmkit);
-
- virtual ~ReferenceThread() {
- delete[] ToEnqueue;
- }
-
- virtual void tracer(uintptr_t closure);
-};
-
-class FinalizerThread : public mvm::MutatorThread {
-public:
- /// FinalizationQueueLock - A lock to protect access to the queue.
- ///
- mvm::SpinLock FinalizationQueueLock;
-
- /// finalizationQueue - A list of allocated objets that contain a finalize
- /// method.
- ///
- mvm::gc** FinalizationQueue;
-
- /// CurrentIndex - Current index in the queue of finalizable objects.
- ///
- uint32 CurrentIndex;
-
- /// QueueLength - Current length of the queue of finalizable objects.
- ///
- uint32 QueueLength;
-
- /// growFinalizationQueue - Grow the queue of finalizable objects.
- ///
- void growFinalizationQueue();
-
- /// ToBeFinalized - List of objects that are scheduled to be finalized.
- ///
- mvm::gc** ToBeFinalized;
-
- /// ToBeFinalizedLength - Current length of the queue of objects scheduled
- /// for finalization.
- ///
- uint32 ToBeFinalizedLength;
-
- /// CurrentFinalizedIndex - The current index in the ToBeFinalized queue
- /// that will be sceduled for finalization.
- ///
- uint32 CurrentFinalizedIndex;
-
- /// growToBeFinalizedQueue - Grow the queue of the to-be finalized objects.
- ///
- void growToBeFinalizedQueue();
-
- /// finalizationCond - Condition variable to wake up finalization threads.
- ///
- mvm::Cond FinalizationCond;
-
- /// finalizationLock - Lock for the condition variable.
- ///
- mvm::LockNormal FinalizationLock;
-
- static void finalizerStart(FinalizerThread*);
-
- /// addFinalizationCandidate - Add an object to the queue of objects with
- /// a finalization method.
- ///
- void addFinalizationCandidate(mvm::gc*);
-
- /// scanFinalizationQueue - Scan objets with a finalized method and schedule
- /// them for finalization if they are not live.
- ///
- void scanFinalizationQueue(uintptr_t closure);
-
- FinalizerThread(VMKit* vmkit);
-
- ~FinalizerThread() {
- delete[] FinalizationQueue;
- delete[] ToBeFinalized;
- }
-
- virtual void tracer(uintptr_t closure);
-};
-
-} // namespace mvm
-
-
-#endif
diff --git a/vmkit/include/mvm/Threads/CollectionRV.h b/vmkit/include/mvm/Threads/CollectionRV.h
deleted file mode 100644
index 3dc7758..0000000
--- a/vmkit/include/mvm/Threads/CollectionRV.h
+++ /dev/null
@@ -1,92 +0,0 @@
-//===---------- CollectionRV.h - Rendez-vous for garbage collection -------===//
-//
-// The VMKit project
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#ifndef _MVM_COLLECTIONRV_H_
-#define _MVM_COLLECTIONRV_H_
-
-#include "mvm/Threads/Cond.h"
-#include "mvm/Threads/Locks.h"
-#include "mvm/Threads/Thread.h"
-
-namespace mvm {
-
-class CollectionRV {
-public:
- /// _lockRV - Lock for synchronization.
- LockNormal _lockRV;
-
- /// condEndRV - Condition for unlocking other tasks (write protect).
- Cond condEndRV;
-
- /// collectionCond - Condition for unblocking the initator.
- Cond condInitiator;
-
- /// nbJoined - Number of threads that joined the rendezvous.
- unsigned nbJoined;
-
-public:
- CollectionRV() {
- nbJoined = 0;
- }
-
- void lockRV() { _lockRV.lock(); }
- void unlockRV() { _lockRV.unlock(); }
-
- void waitEndOfRV();
- void waitRV();
-
- void startRV() {
- mvm::Thread::get()->inRV = true;
- lockRV();
- }
-
- void cancelRV() {
- unlockRV();
- mvm::Thread::get()->inRV = false;
- }
-
- void another_mark();
-
- virtual void finishRV() = 0;
- virtual void synchronize() = 0;
-
- virtual void join() = 0;
- virtual void joinAfterUncooperative(void* SP) = 0;
- virtual void joinBeforeUncooperative() = 0;
-
- /// prepareForJoin - for uncooperative gc, prepare the SIGGC handler
- virtual void prepareForJoin() = 0;
-};
-
-class CooperativeCollectionRV : public CollectionRV {
-public:
- void finishRV();
- void synchronize();
-
- void join();
- void joinAfterUncooperative(void* SP);
- void joinBeforeUncooperative();
- void prepareForJoin();
-};
-
-class UncooperativeCollectionRV : public CollectionRV {
-public:
- void finishRV();
- void synchronize();
-
- void join();
- void joinAfterUncooperative(void* SP);
- void joinBeforeUncooperative();
- void prepareForJoin();
-};
-
-
-}
-
-#endif
diff --git a/vmkit/include/mvm/Threads/Cond.h b/vmkit/include/mvm/Threads/Cond.h
deleted file mode 100644
index 5bcd74b..0000000
--- a/vmkit/include/mvm/Threads/Cond.h
+++ /dev/null
@@ -1,34 +0,0 @@
-//===---------------- Cond.h - Threads conditions -------------------------===//
-//
-// The Micro Virtual Machine
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#ifndef MVM_COND_H
-#define MVM_COND_H
-
-#include <cstdlib>
-#include <pthread.h>
-
-namespace mvm {
-
-class Lock;
-
-class Cond {
- pthread_cond_t internalCond;
-public:
-
- Cond();
- ~Cond();
- void broadcast(void) __attribute__ ((noinline));
- void wait(Lock *l) __attribute__ ((noinline));
- int timedWait(Lock *l, timeval *tv) __attribute__ ((noinline));
- void signal(void) __attribute__ ((noinline));
-};
-
-} // end namespace mvm
-
-#endif // MVM_COND_H
diff --git a/vmkit/include/mvm/Threads/Locks.h b/vmkit/include/mvm/Threads/Locks.h
deleted file mode 100644
index 7d07a39..0000000
--- a/vmkit/include/mvm/Threads/Locks.h
+++ /dev/null
@@ -1,224 +0,0 @@
-//===------------------ Locks.h - Thread locks ----------------------------===//
-//
-// The Micro Virtual Machine
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#ifndef MVM_LOCKS_H
-#define MVM_LOCKS_H
-
-#include <pthread.h>
-#include <cassert>
-#include <cstdio>
-
-#include "ObjectHeader.h"
-#include "mvm/Threads/Thread.h"
-
-namespace mvm {
-
-class gc;
-
-extern "C" uint8 llvm_atomic_cmp_swap_i8(uint8* ptr, uint8 cmp,
- uint8 val);
-extern "C" uint16 llvm_atomic_cmp_swap_i16(uint16* ptr, uint16 cmp,
- uint16 val);
-extern "C" uint32 llvm_atomic_cmp_swap_i32(uint32* ptr, uint32 cmp,
- uint32 val);
-extern "C" uint64 llvm_atomic_cmp_swap_i64(uint64* ptr, uint64 cmp,
- uint64 val);
-
-#ifndef WITH_LLVM_GCC
-
-// TODO: find what macro for gcc < 4.2
-
-#define __sync_bool_compare_and_swap_32(ptr, cmp, val) \
- mvm::llvm_atomic_cmp_swap_i32((uint32*)(ptr), (uint32)(cmp), \
- (uint32)(val)) == (uint32)(cmp)
-
-#if (__WORDSIZE == 64)
-
-#define __sync_bool_compare_and_swap(ptr, cmp, val) \
- mvm::llvm_atomic_cmp_swap_i64((uint64*)(ptr), (uint64)(cmp), \
- (uint64)(val)) == (uint64)(cmp)
-
-#define __sync_val_compare_and_swap(ptr, cmp,val) \
- mvm::llvm_atomic_cmp_swap_i64((uint64*)(ptr), (uint64)(cmp), \
- (uint64)(val))
-
-
-#else
-
-
-
-#define __sync_bool_compare_and_swap(ptr, cmp, val) \
- mvm::llvm_atomic_cmp_swap_i32((uint32*)(ptr), (uint32)(cmp), \
- (uint32)(val)) == (uint32)(cmp)
-
-#define __sync_val_compare_and_swap(ptr, cmp,val) \
- mvm::llvm_atomic_cmp_swap_i32((uint32*)(ptr), (uint32)(cmp), \
- (uint32)(val))
-#endif
-
-
-#endif
-
-class Cond;
-class FatLock;
-class LockNormal;
-class LockRecursive;
-class Thread;
-
-/// Lock - This class is an abstract class for declaring recursive and normal
-/// locks.
-///
-class Lock {
- friend class Cond;
-
-private:
- virtual void unsafeLock(int n) = 0;
- virtual int unsafeUnlock() = 0;
-
-protected:
- /// owner - Which thread is currently holding the lock?
- ///
- mvm::Thread* owner;
-
- /// internalLock - The lock implementation of the platform.
- ///
- pthread_mutex_t internalLock;
-
-
-public:
-
- /// Lock - Creates a lock, recursive if rec is true.
- ///
- Lock();
-
- /// ~Lock - Give it a home.
- ///
- virtual ~Lock();
-
- /// lock - Acquire the lock.
- ///
- virtual void lock() __attribute__ ((noinline)) = 0;
-
- /// unlock - Release the lock.
- ///
- virtual void unlock() = 0;
-
- /// selfOwner - Is the current thread holding the lock?
- ///
- bool selfOwner();
-
- /// getOwner - Get the thread that is holding the lock.
- ///
- mvm::Thread* getOwner();
-
-};
-
-/// LockNormal - A non-recursive lock.
-class LockNormal : public Lock {
- friend class Cond;
-private:
- virtual void unsafeLock(int n) {
- owner = mvm::Thread::get();
- }
-
- virtual int unsafeUnlock() {
- owner = 0;
- return 0;
- }
-public:
- LockNormal() : Lock() {}
-
- virtual void lock() __attribute__ ((noinline));
- virtual void unlock();
-
-};
-
-/// LockRecursive - A recursive lock.
-class LockRecursive : public Lock {
- friend class Cond;
-private:
-
- /// n - Number of times the lock has been locked.
- ///
- int n;
-
- virtual void unsafeLock(int a) {
- n = a;
- owner = mvm::Thread::get();
- }
-
- virtual int unsafeUnlock() {
- int ret = n;
- n = 0;
- owner = 0;
- return ret;
- }
-
-public:
- LockRecursive() : Lock() { n = 0; }
-
- virtual void lock() __attribute__ ((noinline));
- virtual void unlock();
- virtual int tryLock();
-
- /// recursionCount - Get the number of times the lock has been locked.
- ///
- int recursionCount() { return n; }
-
- /// unlockAll - Unlock the lock, releasing it the number of times it is held.
- /// Return the number of times the lock has been locked.
- ///
- int unlockAll();
-
- /// lockAll - Acquire the lock count times.
- ///
- void lockAll(int count) __attribute__ ((noinline));
-};
-
-/// SpinLock - This class implements a spin lock. A spin lock is OK to use
-/// when it is held during short period of times. It is CPU expensive
-/// otherwise.
-class SpinLock {
-public:
-
- /// locked - Is the spin lock locked?
- ///
- uint32 locked;
-
- /// SpinLock - Initialize the lock as not being held.
- ///
- SpinLock() { locked = 0; }
-
-
- /// acquire - Acquire the spin lock, doing an active loop.
- ///
- void acquire() {
- for (uint32 count = 0; count < 1000; ++count) {
- uint32 res = __sync_val_compare_and_swap(&locked, 0, 1);
- if (!res) return;
- }
-
- while (__sync_val_compare_and_swap(&locked, 0, 1))
- mvm::Thread::yield();
- }
-
- void lock() { acquire(); }
-
- /// release - Release the spin lock. This must be called by the thread
- /// holding it.
- ///
- void release() { locked = 0; }
-
- void unlock() { release(); }
-};
-
-
-} // end namespace mvm
-
-#endif // MVM_LOCKS_H
diff --git a/vmkit/include/mvm/Threads/ObjectLocks.h b/vmkit/include/mvm/Threads/ObjectLocks.h
deleted file mode 100644
index 67d0f96..0000000
--- a/vmkit/include/mvm/Threads/ObjectLocks.h
+++ /dev/null
@@ -1,202 +0,0 @@
-//===----------- ObjectLocks.h - Object based locks -----------------------===//
-//
-// The VMKit project
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#ifndef MVM_OBJECT_LOCKS_H
-#define MVM_OBJECT_LOCKS_H
-
-#include "ObjectHeader.h"
-#include "mvm/Allocator.h"
-#include "mvm/GC.h"
-#include "mvm/Threads/Cond.h"
-#include "mvm/Threads/Locks.h"
-#include "mvm/Threads/Thread.h"
-
-namespace mvm {
-
-class FatLock;
-class LockSystem;
-
-class LockingThread {
-public:
- /// varcond - Condition variable when the thread needs to be awaken from
- /// a wait.
- ///
- mvm::Cond varcond;
-
- /// interruptFlag - Has this thread been interrupted?
- ///
- uint32 interruptFlag;
-
- /// nextWaiting - Next thread waiting on the same monitor.
- ///
- LockingThread* nextWaiting;
-
- /// prevWaiting - Previous thread waiting on the same monitor.
- ///
- LockingThread* prevWaiting;
-
- /// waitsOn - The lock on which the thread is waiting on.
- ///
- FatLock* waitsOn;
-
- static const unsigned int StateRunning = 0;
- static const unsigned int StateWaiting = 1;
- static const unsigned int StateInterrupted = 2;
-
- /// state - The current state of this thread: Running, Waiting or Interrupted.
- uint32 state;
-
- LockingThread() {
- interruptFlag = 0;
- nextWaiting = NULL;
- prevWaiting = NULL;
- waitsOn = NULL;
- state = StateRunning;
- }
-
- bool wait(gc* object, LockSystem& table, struct timeval* info, bool timed);
- void notify(gc* object, LockSystem& table);
- void notifyAll(gc* object, LockSystem& table);
-};
-
-
-class FatLock : public mvm::PermanentObject {
-private:
- mvm::LockRecursive internalLock;
- mvm::SpinLock spinLock;
- uint32_t waitingThreads;
- uint32_t lockingThreads;
- LockingThread* firstThread;
- gc* associatedObject;
- uint32_t index;
- FatLock* nextFreeLock;
-public:
- FatLock(uint32_t index, gc* object);
- uintptr_t getID();
- int tryAcquire() { return internalLock.tryLock(); }
- bool acquire(gc* object);
- void acquireAll(gc* object, uint32_t count);
- void release(gc* object, LockSystem& table);
- mvm::Thread* getOwner();
- bool owner();
- gc* getAssociatedObject() { return associatedObject; }
- gc** getAssociatedObjectPtr() { return &associatedObject; }
-
- friend class LockSystem;
- friend class LockingThread;
- friend class ThinLock;
-};
-
-
-/// LockSystem - This class manages all Java locks used by the applications.
-/// Each JVM must own an instance of this class and allocate Java locks
-/// with it.
-///
-class LockSystem {
- friend class FatLock;
-public:
-
- // Fixed values. With these values, an index is on 18 bits.
- static const uint32_t GlobalSize = 128;
- static const uint32_t BitIndex = 11;
- static const uint32_t IndexSize = 1 << BitIndex;
- static const uint32_t BitMask = IndexSize - 1;
- static const uint32_t MaxLocks = GlobalSize * IndexSize;
-
- mvm::BumpPtrAllocator& allocator;
-
- /// LockTable - The global table that will hold the locks. The table is
- /// a two-dimensional array, and only one entry is created, so that
- /// the lock system does not eat up all memory on startup.
- ///
- FatLock* ** LockTable;
-
- /// currentIndex - The current index in the tables. Always incremented,
- /// never decremented.
- ///
- uint32_t currentIndex;
-
- /// freeLock - The list of locks that are allocated and available.
- ///
- FatLock* freeLock;
-
- /// threadLock - Spin lock to protect the currentIndex field.
- ///
- mvm::SpinLock threadLock;
-
- /// allocate - Allocate a FatLock.
- ///
- FatLock* allocate(gc* obj);
-
- /// deallocate - Put a lock in the free list lock.
- ///
- void deallocate(FatLock* lock);
-
- /// LockSystem - Default constructor. Initialize the table.
- ///
- LockSystem(mvm::BumpPtrAllocator& allocator);
-
- /// getLock - Get a lock from an index in the table.
- ///
- FatLock* getLock(uint32_t index) {
- return LockTable[index >> BitIndex][index & BitMask];
- }
-
- FatLock* getFatLockFromID(uintptr_t ID);
-};
-
-class ThinLock {
-public:
-
- // The header of an object that has a thin lock implementation is like the
- // following:
- //
- // x xxx xxxx xxxx xxxx xxxx xxxx xxxx xxxx
- // ^ ^^^ ^^^^ ^^^^ ^^^^ ^^^^ ^^^^ ^^^^ ^^^^
- // 1 11 12 8
- // fat lock thread id thin lock count + hash GC bits
-
- static const uint64_t FatMask = 1 << ((sizeof(size_t) << 3) - 1);
-
- static const uint32_t NonLockBits = HashBits + GCBits;
- static const uint64_t NonLockBitsMask = ((1 << NonLockBits) - 1);
-
- static const uint64_t ThinCountMask = ~(FatMask + Thread::IDMask + NonLockBitsMask);
- static const uint64_t ThinCountShift = NonLockBits;
- static const uint64_t ThinCountAdd = 1 << NonLockBits;
-
- /// initialise - Initialise the value of the lock.
- ///
- static void removeFatLock(FatLock* fatLock, LockSystem& table);
-
- /// overflowThinlock - Change the lock of this object to a fat lock because
- /// we have reached the maximum number of locks.
- static void overflowThinLock(gc* object, LockSystem& table);
-
- /// changeToFatlock - Change the lock of this object to a fat lock. The lock
- /// may be in a thin lock or fat lock state.
- static FatLock* changeToFatlock(gc* object, LockSystem& table);
-
- /// acquire - Acquire the lock.
- static void acquire(gc* object, LockSystem& table);
-
- /// release - Release the lock.
- static void release(gc* object, LockSystem& table);
-
- /// owner - Returns true if the curren thread is the owner of this object's
- /// lock.
- static bool owner(gc* object, LockSystem& table);
-
- /// getFatLock - Get the fat lock is the lock is a fat lock, 0 otherwise.
- static FatLock* getFatLock(gc* object, LockSystem& table);
-};
-
-} // end namespace mvm
-
-#endif // MVM_OBJECT_LOCKS_H
diff --git a/vmkit/include/mvm/Threads/Thread.h b/vmkit/include/mvm/Threads/Thread.h
deleted file mode 100644
index e0e5797..0000000
--- a/vmkit/include/mvm/Threads/Thread.h
+++ /dev/null
@@ -1,413 +0,0 @@
-//===---------------- Threads.h - Micro-vm threads ------------------------===//
-//
-// The VMKit project
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#ifndef MVM_THREAD_H
-#define MVM_THREAD_H
-
-#include <cassert>
-#include <cstdio>
-#include <stdlib.h>
-
-#include "debug.h"
-#include "types.h"
-
-#ifdef RUNTIME_DWARF_EXCEPTIONS
- #define TRY try
- #define CATCH catch(...)
- #define IGNORE catch(...) { mvm::Thread::get()->clearPendingException(); }
- #define END_CATCH
-#else
- #include <csetjmp>
- #if defined(__MACH__)
- #define TRY { mvm::ExceptionBuffer __buffer__; if (!_setjmp(__buffer__.buffer))
- #else
- #define TRY { mvm::ExceptionBuffer __buffer__; if (!setjmp(__buffer__.buffer))
- #endif
- #define CATCH else
- #define IGNORE else { mvm::Thread::get()->clearPendingException(); }}
- #define END_CATCH }
-#endif
-
-namespace mvm {
-
-class gc;
-class MethodInfo;
-class VirtualMachine;
-
-/// CircularBase - This class represents a circular list. Classes that extend
-/// this class automatically place their instances in a circular list.
-///
-// WARNING: if you modify this class, you must also change mvm-runtime.ll
-template<typename T>
-class CircularBase {
- /// _next - The next object in the list.
- ///
- T *_next;
-
- /// _prev - The previous object in the list.
- ///
- T *_prev;
-public:
- /// ~CircularBase - Give the class a home.
- ///
- virtual ~CircularBase() {}
-
- /// next - Get the next object in the list.
- ///
- inline T *next() { return _next; }
-
- /// prev - Get the previous object in the list.
- ///
- inline T *prev() { return _prev; }
-
- /// CricularBase - Creates the object as a single element in the list.
- ///
- inline CircularBase() { _prev = _next = (T*)this; }
-
- /// CircularBase - Creates the object and place it in the given list.
- ///
- inline explicit CircularBase(CircularBase<T> *p) { appendTo(p); }
-
- /// remove - Remove the object from its list.
- ///
- inline void remove() {
- _prev->_next = _next;
- _next->_prev = _prev;
- _prev = _next = (T*)this;
- }
-
- /// append - Add the object in the list.
- ///
- inline void appendTo(CircularBase<T> *p) {
- _prev = (T*)p;
- _next = p->_next;
- _next->_prev = (T*)this;
- _prev->_next = (T*)this;
- }
-
- /// print - Print the list for debug purposes.
- void print() {
- T* temp = (T*)this;
- do {
- fprintf(stderr, "%p -> ", (void*)temp);
- temp = temp->next0();
- } while (temp != this);
- fprintf(stderr, "\n");
- }
-};
-
-
-
-#if defined(__MACH__) && (defined(__PPC__) || defined(__ppc__))
-#define FRAME_IP(fp) (fp[2])
-#else
-#define FRAME_IP(fp) (fp[1])
-#endif
-
-// Apparently gcc for i386 and family considers __builtin_frame_address(0) to
-// return the caller, not the current function.
-#if defined(__i386__) || defined(i386) || defined(_M_IX86) || \
- defined(__x86_64__) || defined(_M_AMD64)
-#define FRAME_PTR() __builtin_frame_address(0)
-#else
-#define FRAME_PTR() (((void**)__builtin_frame_address(0))[0])
-#endif
-
-
-class KnownFrame {
-public:
- void* currentFP;
- void* currentIP;
- KnownFrame* previousFrame;
-};
-
-
-class ExceptionBuffer;
-class Thread;
-class VMKit;
-
-// WARNING: if you modify this class, you must also change mvm-runtime.ll
-// WARNING: when a VMThreadData is in a thread (in allVmsData), you must never delete it yourself.
-class VMThreadData {
-public:
- /// mut - The associated thread mutator
- Thread* mut;
-
- /// vm - The associated virtual machine
- VirtualMachine* vm;
-
- VMThreadData(VirtualMachine *v, Thread* m) {
- this->mut = m;
- this->vm = v;
- }
-
- virtual void tracer(uintptr_t closure) {};
-
- virtual ~VMThreadData() {} // force the construction of a VT
-};
-
-#define THREAD_RUNNING 1
-#define THREAD_DAEMON 2
-
-/// Thread - This class is the base of custom virtual machines' Thread classes.
-/// It provides static functions to manage threads. An instance of this class
-/// contains all thread-specific informations.
-// WARNING: if you modify this class, you must also change mvm-runtime.ll
-class Thread : public CircularBase<Thread> {
-public:
- /// doYield - Flag to tell the thread to yield for GC reasons.
- bool doYield; // 1 - intrinsic
-
-#ifdef RUNTIME_DWARF_EXCEPTIONS
- void* internalPendingException;
-#else
- /// lastExceptionBuffer - The last exception buffer on this thread's stack.
- ExceptionBuffer* lastExceptionBuffer; // 2 - intrinsic
-#endif
-
- /// vmData - vm specific data - notice that vmkit do not consider that this field has a value
- VMThreadData* vmData; // 3 - intrinsic
-
- /// pendingException - the pending exception
- gc* pendingException; // 4 - intrinsic
-
- /// vmkit - a (shortcut) pointer to vmkit that contains information on all the vms
- mvm::VMKit* vmkit; // 5
-
- /// baseSP - The base stack pointer.
- void* baseSP; // 6
-
- /// inRV - Flag to tell that the thread is being part of a rendezvous.
- bool inRV; // 7
-
- /// joinedRV - Flag to tell that the thread has joined a rendezvous.
- bool joinedRV; // 8
-
-private:
- /// lastSP - If the thread is running native code that can not be
- /// interrupted, lastSP is not null and contains the value of the
- /// stack pointer before entering native.
- void* lastSP; // 9
-
- /// internalThreadID - The implementation specific thread id.
- void* internalThreadID; // 10
-
-public:
- /// routine - The function to invoke when the thread starts.
- void (*routine)(mvm::Thread*); // 11
-
- /// lastKnownFrame - The last frame that we know of, before resuming to JNI.
- KnownFrame* lastKnownFrame; // 12
-
- /// allVmsData - the array of thread specific data.
- VMThreadData** allVmsData; // 13
-
-private:
- /// state - daemon, running
- uint32 state; // 14
-
-private:
- friend class MutatorThread;
- Thread(VMKit* vmk);
-
-public:
-
- /// setDaemon - the thread is a daemon
- void setDaemon();
-
- /// setDaemon - the thread is not a daemon
- void setNonDaemon();
-
- /// getDaemon - get the daemon flag of the thread
- uint32 getState() { return state; }
-
- /// yield - Yield the processor to another thread.
- ///
- static void yield(void);
-
- /// kill - Kill the thread with the given pid by sending it a signal.
- ///
- static int kill(void* tid, int signo);
-
- /// kill - Kill the given thread by sending it a signal.
- ///
- int kill(int signo);
-
- /// exit - Exit the current thread.
- ///
- static void exit(int value);
-
- /// start - Start the execution of a thread.
- ///
- virtual int start(void (*fct)(mvm::Thread*));
-
- uint64_t getThreadID() {
- return (uint64_t)this;
- }
-
- /// get - Get the thread specific data of the current thread.
- ///
- static Thread* get() {
- return (Thread*)((uintptr_t)__builtin_frame_address(0) & IDMask);
- }
-
-private:
-
- /// internalThreadStart - The implementation sepcific thread starter
- /// function.
- ///
- static void internalThreadStart(mvm::Thread* th);
-
-public:
-
- /// tracer - trace the pendingException and the vmData
- ///
- virtual void tracer(uintptr_t closure);
-
- void scanStack(uintptr_t closure);
-
- void* getLastSP() { return lastSP; }
- void setLastSP(void* V) { lastSP = V; }
-
- void joinRVBeforeEnter();
- void joinRVAfterLeave(void* savedSP);
-
- void enterUncooperativeCode(unsigned level = 0) __attribute__ ((noinline));
- void enterUncooperativeCode(void* SP);
- void leaveUncooperativeCode();
- void* waitOnSP();
-
-
- /// clearPendingException - Clear any pending exception of the current thread.
- void clearPendingException() {
- pendingException = 0;
-#ifdef RUNTIME_DWARF_EXCEPTIONS
- internalPendingException = 0;
-#endif
- }
-
- /// setException - only set the pending exception
- ///
- Thread* setPendingException(gc *obj);
-
- /// throwIt - Throw a pending exception.
- ///
- void throwIt();
-
- /// getPendingException - Return the pending exception.
- ///
- gc* getPendingException() {
- return pendingException;
- }
-
- bool isMvmThread() {
- if (!baseAddr) return false;
- else return (((uintptr_t)this) & MvmThreadMask) == baseAddr;
- }
-
- /// baseAddr - The base address for all threads.
- static uintptr_t baseAddr;
-
- /// IDMask - Apply this mask to the stack pointer to get the Thread object.
- ///
-#if (__WORDSIZE == 64)
- static const uint64_t IDMask = 0xF7FF00000;
-#else
- static const uint64_t IDMask = 0x7FF00000;
-#endif
- /// MvmThreadMask - Apply this mask to verify that the current thread was
- /// created by Mvm.
- ///
- static const uint64_t MvmThreadMask = 0xF0000000;
-
- /// OverflowMask - Apply this mask to implement overflow checks. For
- /// efficiency, we lower the available size of the stack: it can never go
- /// under 0xC0000
- ///
- static const uint64_t StackOverflowMask = 0xC0000;
-
- /// stackOverflow - Returns if there is a stack overflow in Java land.
- ///
- bool stackOverflow() {
- return ((uintptr_t)__builtin_frame_address(0) & StackOverflowMask) == 0;
- }
-
- /// operator new - Allocate the Thread object as well as the stack for this
- /// Thread. The thread object is inlined in the stack.
- ///
- void* operator new(size_t sz);
- void operator delete(void* th);
- virtual ~Thread();
-
- /// printBacktrace - Print the backtrace.
- ///
- void printBacktrace();
-
- /// getFrameContext - Fill the buffer with frames currently on the stack.
- ///
- void getFrameContext(void** buffer);
-
- /// getFrameContextLength - Get the length of the frame context.
- ///
- uint32_t getFrameContextLength();
-
- void startKnownFrame(KnownFrame& F) __attribute__ ((noinline));
- void endKnownFrame();
- void startUnknownFrame(KnownFrame& F) __attribute__ ((noinline));
- void endUnknownFrame();
-
- /// reallocAllVmsData - realloc the allVmsData from old to n or 0 to n if allVmsData=0
- /// must be protected by rendezvous.threadLock
- ///
- void reallocAllVmsData(int old, int n);
-
- /// attach - attach the vm specific data of the given virtual machine
- ///
- void attach(VirtualMachine* vm);
-};
-
-#ifndef RUNTIME_DWARF_EXCEPTIONS
-class ExceptionBuffer {
-public:
- ExceptionBuffer() {
- Thread* th = Thread::get();
- previousBuffer = th->lastExceptionBuffer;
- th->lastExceptionBuffer = this;
- }
-
- ~ExceptionBuffer() {
- Thread* th = Thread::get();
- assert(th->lastExceptionBuffer == this && "Wrong exception buffer");
- th->lastExceptionBuffer = previousBuffer;
- }
- ExceptionBuffer* previousBuffer;
- jmp_buf buffer;
-};
-#endif
-
-/// StackWalker - This class walks the stack of threads, returning a MethodInfo
-/// object at each iteration.
-///
-class StackWalker {
-public:
- void** addr;
- void* ip;
- KnownFrame* frame;
- mvm::Thread* thread;
-
- StackWalker(mvm::Thread* th) __attribute__ ((noinline));
- void operator++();
- void* operator*();
- MethodInfo* get();
-
-};
-
-
-} // end namespace mvm
-#endif // MVM_THREAD_H
diff --git a/vmkit/include/mvm/UTF8.h b/vmkit/include/mvm/UTF8.h
deleted file mode 100644
index 6c92ba3..0000000
--- a/vmkit/include/mvm/UTF8.h
+++ /dev/null
@@ -1,102 +0,0 @@
-#ifndef _UTF8_INTERNAL_H_
-#define _UTF8_INTERNAL_H_
-
-#include <map>
-#include "mvm/Allocator.h"
-
-namespace mvm {
-
-class PrintBuffer;
-class UTF8Map;
-
-class UTF8 {
- friend class UTF8Map;
-private:
-
- /// operator new - Redefines the new operator of this class to allocate
- /// its objects in permanent memory, not with the garbage collector.
- void* operator new(size_t sz, mvm::BumpPtrAllocator& allocator, sint32 n) {
- return allocator.Allocate(sizeof(UTF8) + (n - 1) * sizeof(uint16), "UTF8");
- }
-
- UTF8(sint32 n) {
- size = n;
- }
-
-public:
- /// size - The (constant) size of the array.
- ssize_t size;
-
- /// elements - Elements of this array. The size here is different than the
- /// actual size of the Java array. This is to facilitate Java array accesses
- /// in JnJVM code. The size should be set to zero, but this is invalid C99.
- uint16 elements[1];
-
- /// extract - Similar, but creates it in the map.
- const UTF8* extract(UTF8Map* map, uint32 start, uint32 len) const;
-
- /// equals - Are the two UTF8s equal?
- bool equals(const UTF8* other) const {
- if (other == this) return true;
- else if (size != other->size) return false;
- else return !memcmp(elements, other->elements, size * sizeof(uint16));
- }
-
- /// equals - Does the UTF8 equal to the buffer?
- bool equals(const uint16* buf, sint32 len) const {
- if (size != len) return false;
- else return !memcmp(elements, buf, size * sizeof(uint16));
- }
-
- /// lessThan - strcmp-like function for UTF8s, used by hash tables.
- bool lessThan(const UTF8* other) const {
- if (size < other->size) return true;
- else if (size > other->size) return false;
- else return memcmp((const char*)elements, (const char*)other->elements,
- size * sizeof(uint16)) < 0;
- }
-
- static uint32_t readerHasher(const uint16* buf, sint32 size);
-
- uint32_t hash() const {
- return readerHasher(elements, size);
- }
-
-};
-
-
-class UTF8Map : public mvm::PermanentObject {
-private:
- typedef std::multimap<const uint32, const UTF8*>::iterator iterator;
-
- mvm::LockNormal lock;
- mvm::BumpPtrAllocator& allocator;
- std::multimap<const uint32, const UTF8*> map;
-public:
-
- const UTF8* lookupOrCreateAsciiz(const char* asciiz);
- const UTF8* lookupOrCreateReader(const uint16* buf, uint32 size);
- const UTF8* lookupAsciiz(const char* asciiz);
- const UTF8* lookupReader(const uint16* buf, uint32 size);
-
- UTF8Map(mvm::BumpPtrAllocator& A) : allocator(A) {}
-
- ~UTF8Map() {
- for (iterator i = map.begin(), e = map.end(); i!= e; ++i) {
- allocator.Deallocate((void*)i->second);
- }
- }
-
- void copy(UTF8Map* newMap) {
- for (iterator i = map.begin(), e = map.end(); i!= e; ++i) {
- newMap->map.insert(*i);
- }
- }
-
- void replace(const UTF8* oldUTF8, const UTF8* newUTF8);
- void insert(const UTF8* val);
-};
-
-} // end namespace mvm
-
-#endif
diff --git a/vmkit/include/mvm/VMKit.h b/vmkit/include/mvm/VMKit.h
deleted file mode 100644
index 2392600..0000000
--- a/vmkit/include/mvm/VMKit.h
+++ /dev/null
@@ -1,229 +0,0 @@
-#ifndef _VMKIT_H_
-#define _VMKIT_H_
-
-#include "mvm/Allocator.h"
-#include "mvm/Threads/CollectionRV.h"
-#include "mvm/VirtualMachine.h"
-
-#include "llvm/Target/TargetMachine.h"
-
-namespace llvm {
- class Module;
- class TargetMachine;
-}
-
-namespace mvm {
-class MethodInfo;
-class VMKit;
-class gc;
-class FinalizerThread;
-class ReferenceThread;
-
-class FunctionMap {
-public:
- /// Functions - Map of applicative methods to function pointers. This map is
- /// used when walking the stack so that VMKit knows which applicative method
- /// is executing on the stack.
- ///
- std::map<void*, MethodInfo*> Functions;
-
- /// FunctionMapLock - Spin lock to protect the Functions map.
- ///
- mvm::SpinLock FunctionMapLock;
-
- /// IPToMethodInfo - Map a code start instruction instruction to the MethodInfo.
- ///
- MethodInfo* IPToMethodInfo(void* ip);
-
- /// addMethodInfo - A new instruction pointer in the function map.
- ///
- void addMethodInfo(MethodInfo* meth, void* ip);
-
- /// removeMethodInfos - Remove all MethodInfo owned by the given owner.
- void removeMethodInfos(void* owner);
-
- FunctionMap();
-};
-
-
-class NonDaemonThreadManager {
- friend class Thread;
-public:
- NonDaemonThreadManager() { nonDaemonThreads = 0; }
-
-private:
- /// nonDaemonThreads - Number of threads in the system that are not daemon
- /// threads.
- //
- uint16 nonDaemonThreads;
-
- /// nonDaemonLock - Protection lock for the nonDaemonThreads variable.
- ///
- mvm::LockNormal nonDaemonLock;
-
- /// nonDaemonVar - Condition variable to wake up the initial thread when it
- /// waits for other non-daemon threads to end. The non-daemon thread that
- /// decrements the nonDaemonThreads variable to zero wakes up the initial
- /// thread.
- ///
- mvm::Cond nonDaemonVar;
-
- /// leave - A thread calls this function when it leaves the thread system.
- ///
- void leaveNonDaemonMode();
-
- /// enter - A thread calls this function when it enters the thread system.
- ///
- void enterNonDaemonMode();
-
-public:
- void waitNonDaemonThreads();
-};
-
-class VMKit : public mvm::PermanentObject {
-public:
- /// allocator - Bump pointer allocator to allocate permanent memory of VMKit
- mvm::BumpPtrAllocator& allocator;
-
- // initialise - initialise vmkit. If never called, will be called by the first constructor of vmkit
- static void initialise(llvm::CodeGenOpt::Level = llvm::CodeGenOpt::Default,
- llvm::Module* TheModule = 0,
- llvm::TargetMachine* TheTarget = 0);
-
- VMKit(mvm::BumpPtrAllocator &Alloc);
-
- LockRecursive _vmkitLock;
-
- void vmkitLock() { _vmkitLock.lock(); }
- void vmkitUnlock() { _vmkitLock.unlock(); }
-
- /// ------------------------------------------------- ///
- /// --- vm managment --- ///
- /// ------------------------------------------------- ///
- // vms - the list of vms.
- // synchronized with vmkitLock
- VirtualMachine** vms;
- size_t vmsArraySize;
-
- size_t addVM(VirtualMachine* vm);
- void removeVM(size_t id);
-
- /// ------------------------------------------------- ///
- /// --- thread managment --- ///
- /// ------------------------------------------------- ///
- /// preparedThreads - the list of prepared threads, they are not yet running.
- /// synchronized with vmkitLock
- ///
- CircularBase<Thread> preparedThreads;
-
- /// runningThreads - the list of running threads
- /// synchronize with vmkitLock
- ///
- CircularBase<Thread> runningThreads;
-
- /// numberOfRunningThreads - The number of threads that currently run under this VM.
- /// synchronized with vmkitLock
- ///
- size_t numberOfRunningThreads;
-
- // nonDaemonThreadsManager - manager of the non daemon threads
- NonDaemonThreadManager nonDaemonThreadsManager;
-
- void registerPreparedThread(mvm::Thread* th);
- void unregisterPreparedThread(mvm::Thread* th);
-
- void registerRunningThread(mvm::Thread* th);
- void unregisterRunningThread(mvm::Thread* th);
-
- void waitNonDaemonThreads();
-
- /// ------------------------------------------------- ///
- /// --- memory managment --- ///
- /// ------------------------------------------------- ///
- /// rendezvous - The rendezvous implementation for garbage collection.
- ///
-#ifdef WITH_LLVM_GCC
- CooperativeCollectionRV rendezvous;
-#else
- UncooperativeCollectionRV rendezvous;
-#endif
-
-private:
- /// enqueueThread - The thread that finalizes references.
- ///
- FinalizerThread* finalizerThread;
-
- /// enqueueThread - The thread that enqueues references.
- ///
- ReferenceThread* referenceThread;
-
- /// getAndAllocateFinalizerThread - get the finalizer thread and allocate it if it does not exist
- ///
- FinalizerThread* getAndAllocateFinalizerThread();
-
- /// getAndAllocateReferenceThread - get the reference thread and allocate it if it does not exist
- ///
- ReferenceThread* getAndAllocateReferenceThread();
-
-public:
- /// addWeakReference - Add a weak reference to the queue.
- ///
- void addWeakReference(mvm::gc* ref);
-
- /// addSoftReference - Add a weak reference to the queue.
- ///
- void addSoftReference(mvm::gc* ref);
-
- /// addPhantomReference - Add a weak reference to the queue.
- ///
- void addPhantomReference(mvm::gc* ref);
-
- /// addFinalizationCandidate - Add an object to the queue of objects with
- /// a finalization method.
- ///
- void addFinalizationCandidate(gc* object);
-
- /// scanFinalizationQueue - Scan objets with a finalized method and schedule
- /// them for finalization if they are not live.
- ///
- void scanFinalizationQueue(uintptr_t closure);
-
- /// scanWeakReferencesQueue - Scan all weak references. Called by the GC
- /// before scanning the finalization queue.
- ///
- void scanWeakReferencesQueue(uintptr_t closure);
-
- /// scanSoftReferencesQueue - Scan all soft references. Called by the GC
- /// before scanning the finalization queue.
- ///
- void scanSoftReferencesQueue(uintptr_t closure);
-
- /// scanPhantomReferencesQueue - Scan all phantom references. Called by the GC
- /// after the finalization queue.
- ///
- void scanPhantomReferencesQueue(uintptr_t closure);
-
- bool startCollection(); // 1 ok, begin collection, 0 do not start collection
- void endCollection();
-
- void tracer(uintptr_t closure);
-
- /// ------------------------------------------------- ///
- /// --- backtrace related methods --- ///
- /// ------------------------------------------------- ///
- /// FunctionsCache - cache of compiled functions
- //
- FunctionMap FunctionsCache;
-
- MethodInfo* IPToMethodInfo(void* ip) {
- return FunctionsCache.IPToMethodInfo(ip);
- }
-
- void removeMethodInfos(void* owner) {
- FunctionsCache.removeMethodInfos(owner);
- }
-};
-
-}
-
-#endif
diff --git a/vmkit/include/mvm/VirtualMachine.h b/vmkit/include/mvm/VirtualMachine.h
deleted file mode 100644
index 20dc6b8..0000000
--- a/vmkit/include/mvm/VirtualMachine.h
+++ /dev/null
@@ -1,114 +0,0 @@
-//===--------- VirtualMachine.h - Registering a VM ------------------------===//
-//
-// The VMKit project
-//
-// This file is distributed under the University of Pierre et Marie Curie
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#ifndef MVM_VIRTUALMACHINE_H
-#define MVM_VIRTUALMACHINE_H
-
-#include "mvm/Allocator.h"
-#include "mvm/Threads/CollectionRV.h"
-#include "mvm/Threads/Locks.h"
-
-#include <cassert>
-#include <map>
-
-namespace mvm {
-
-/// VirtualMachine - This class is the root of virtual machine classes. It
-/// defines what a VM should be.
-///
-class VirtualMachine : public mvm::PermanentObject {
-private:
- friend class VMKit;
- VirtualMachine(mvm::BumpPtrAllocator &Alloc) : allocator(Alloc) {}
-
-protected:
- VirtualMachine(mvm::BumpPtrAllocator &Alloc, mvm::VMKit* vmk);
-
-public:
- virtual ~VirtualMachine();
-
- /// allocator - Bump pointer allocator to allocate permanent memory
- /// related to this VM.
- ///
- mvm::BumpPtrAllocator& allocator;
-
- /// vmkit - a pointer to vmkit that contains information on all the vms
- ///
- mvm::VMKit* vmkit;
-
- /// vmID - id of the vm
- size_t vmID;
-
-//===----------------------------------------------------------------------===//
-// (1) thread-related methods.
-//===----------------------------------------------------------------------===//
- /// buildVMThreadData - allocate a java thread for the underlying mutator. Called when the java thread is a foreign thread.
- ///
- virtual VMThreadData* buildVMThreadData(Thread* mut) { return new VMThreadData(this, mut); }
-
- /// runApplicationImpl - code executed after a runApplication in a vmkit thread
- ///
- virtual void runApplicationImpl(int argc, char** argv) {}
-
- /// runApplication - launch runApplicationImpl in a vmkit thread. The vmData is not allocated.
- ///
- void runApplication(int argc, char** argv);
-
- /// runApplication - launch starter in a vmkit thread. The vmData is not allocated.
- ///
- void runApplication(void (*starter)(VirtualMachine* vm, int argc, char** argv), int argc, char** argv);
-
-//===----------------------------------------------------------------------===//
-// (2) GC-related methods.
-//===----------------------------------------------------------------------===//
- /// startCollection - Preliminary code before starting a GC.
- ///
- virtual void startCollection() {}
-
- /// endCollection - Code after running a GC.
- ///
- virtual void endCollection() {}
-
- /// finalizeObject - invoke the finalizer of a java object
- ///
- virtual void finalizeObject(mvm::gc* obj) = 0;
-
- /// getReferentPtr - return the referent of a reference
- ///
- virtual mvm::gc** getReferent(mvm::gc* ref) = 0;
-
- /// setReferentPtr - set the referent of a reference
- ///
- virtual void setReferent(mvm::gc* ref, mvm::gc* val) = 0;
-
- /// enqueueReference - enqueue the reference
- ///
- virtual bool enqueueReference(mvm::gc* _obj) = 0;
-
- /// tracer - Trace this virtual machine's GC-objects.
- /// Called once by vm. If you have GC-objects in a thread specific data, redefine the tracer of your VMThreadData.
- ///
- virtual void tracer(uintptr_t closure) {}
-
- /// getObjectSize - Get the size of this object. Used by copying collectors.
- ///
- virtual size_t getObjectSize(gc* object) = 0;
-
- /// getObjectTypeName - Get the type of this object. Used by the GC for
- /// debugging purposes.
- ///
- virtual const char* getObjectTypeName(gc* object) { return "An object"; }
-
-//===----------------------------------------------------------------------===//
-// (4) Launch-related methods.
-//===----------------------------------------------------------------------===//
-};
-
-} // end namespace mvm
-#endif // MVM_VIRTUALMACHINE_H
diff --git a/vmkit/include/types.h b/vmkit/include/types.h
deleted file mode 100644
index b3ef05b..0000000
--- a/vmkit/include/types.h
+++ /dev/null
@@ -1,24 +0,0 @@
-//===------------------- types.h - bitsized types -------------------------===//
-//
-// MVM
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#ifndef TYPES_H
-#define TYPES_H
-
-#include <stdint.h>
-
-typedef uint8_t uint8;
-typedef int8_t sint8;
-typedef uint16_t uint16;
-typedef int16_t sint16;
-typedef uint32_t uint32;
-typedef int32_t sint32;
-typedef uint64_t uint64;
-typedef int64_t sint64;
-
-#endif
diff --git a/vmkit/lib/J3/Classpath/Classpath.h.in b/vmkit/lib/J3/Classpath/Classpath.h.in
deleted file mode 100644
index 107510d..0000000
--- a/vmkit/lib/J3/Classpath/Classpath.h.in
+++ /dev/null
@@ -1,19 +0,0 @@
-//===-------- Classpath.h - Configuration for classpath -------------------===//
-//
-// The VMKit project
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-
-#define GNUClasspathLibs "@classpathlibs@";
-#define GNUClasspathGlibj "@classpathglibj@";
-#define GNUClasspathVersion "@classpathversion@";
-
-#ifdef NATIVE_JNI
-#define JNIEXPORT
-#else
-#include <jni.h>
-#endif
diff --git a/vmkit/lib/J3/Classpath/Classpath.inc b/vmkit/lib/J3/Classpath/Classpath.inc
deleted file mode 100644
index 8d6174c..0000000
--- a/vmkit/lib/J3/Classpath/Classpath.inc
+++ /dev/null
@@ -1,359 +0,0 @@
-//===-------- Classpath.cpp - Configuration for classpath -------------------===//
-//
-// The VMKit project
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-
-
-#include "Classpath.h"
-#include "ClasspathReflect.h"
-#include "JavaClass.h"
-#include "JavaThread.h"
-#include "JavaUpcalls.h"
-#include "Jnjvm.h"
-
-
-using namespace j3;
-
-extern "C" {
-
-// Define hasClassInitializer because of a buggy implementation in Classpath.
-JNIEXPORT bool JNICALL Java_java_io_VMObjectStreamClass_hasClassInitializer(
-#ifdef NATIVE_JNI
-JNIEnv *env,
-jclass clazz,
-#endif
-JavaObject* Cl) {
-
- llvm_gcroot(Cl, 0);
- bool res = false;
- BEGIN_NATIVE_EXCEPTION(0)
-
- verifyNull(Cl);
- Jnjvm* vm = JavaThread::get()->getJVM();
- UserCommonClass* cl = UserCommonClass::resolvedImplClass(Cl, true);
-
- if (cl->isClass() &&
- cl->asClass()->lookupMethodDontThrow(vm->upcalls->clinitName,
- vm->upcalls->clinitType,
- true, false, 0))
- res = true;
-
- END_NATIVE_EXCEPTION
-
- return res;
-}
-
-
-// Redefine some VMObjectStreamClass functions because of a slow implementation
-// in Classpath.
-
-JNIEXPORT void JNICALL Java_java_io_VMObjectStreamClass_setBooleanNative(
-#ifdef NATIVE_JNI
-JNIEnv *env,
-jclass clazz,
-#endif
-JavaObjectField* Field, JavaObject* obj, jboolean val) {
-
- llvm_gcroot(Field, 0);
- llvm_gcroot(obj, 0);
- BEGIN_NATIVE_EXCEPTION(0)
-
- verifyNull(obj);
- JavaField* field = JavaObjectField::getInternalField(Field);
- field->setInstanceInt8Field(obj, (uint8)val);
-
- END_NATIVE_EXCEPTION
-}
-
-JNIEXPORT void JNICALL Java_java_io_VMObjectStreamClass_setByteNative(
-#ifdef NATIVE_JNI
-JNIEnv *env,
-jclass clazz,
-#endif
-JavaObjectField* Field, JavaObject* obj, jbyte val) {
-
- llvm_gcroot(Field, 0);
- llvm_gcroot(obj, 0);
- BEGIN_NATIVE_EXCEPTION(0)
-
- verifyNull(obj);
- JavaField* field = JavaObjectField::getInternalField(Field);
- field->setInstanceInt8Field(obj, (uint8)val);
-
- END_NATIVE_EXCEPTION
-}
-
-JNIEXPORT void JNICALL Java_java_io_VMObjectStreamClass_setCharNative(
-#ifdef NATIVE_JNI
-JNIEnv *env,
-jclass clazz,
-#endif
-JavaObjectField* Field, JavaObject* obj, jchar val) {
-
- llvm_gcroot(Field, 0);
- llvm_gcroot(obj, 0);
- BEGIN_NATIVE_EXCEPTION(0)
-
- verifyNull(obj);
- JavaField* field = JavaObjectField::getInternalField(Field);
- field->setInstanceInt16Field((JavaObject*)obj, (uint16)val);
-
- END_NATIVE_EXCEPTION
-}
-
-JNIEXPORT void JNICALL Java_java_io_VMObjectStreamClass_setShortNative(
-#ifdef NATIVE_JNI
-JNIEnv *env,
-jclass clazz,
-#endif
-JavaObjectField* Field, JavaObject* obj, jshort val) {
-
- llvm_gcroot(Field, 0);
- llvm_gcroot(obj, 0);
- BEGIN_NATIVE_EXCEPTION(0)
-
- verifyNull(obj);
- JavaField* field = JavaObjectField::getInternalField(Field);
- field->setInstanceInt16Field(obj, (sint16)val);
-
- END_NATIVE_EXCEPTION
-}
-
-JNIEXPORT void JNICALL Java_java_io_VMObjectStreamClass_setIntNative(
-#ifdef NATIVE_JNI
-JNIEnv *env,
-jclass clazz,
-#endif
-JavaObjectField* Field, JavaObject* obj, jint val) {
-
- llvm_gcroot(Field, 0);
- llvm_gcroot(obj, 0);
- BEGIN_NATIVE_EXCEPTION(0)
-
- verifyNull(obj);
- JavaField* field = JavaObjectField::getInternalField(Field);
- field->setInstanceInt32Field(obj, (sint32)val);
-
- END_NATIVE_EXCEPTION
-}
-
-JNIEXPORT void JNICALL Java_java_io_VMObjectStreamClass_setLongNative(
-#ifdef NATIVE_JNI
-JNIEnv *env,
-jclass clazz,
-#endif
-JavaObjectField* Field, JavaObject* obj, jlong val) {
-
- llvm_gcroot(Field, 0);
- llvm_gcroot(obj, 0);
- BEGIN_NATIVE_EXCEPTION(0)
-
- verifyNull(obj);
- JavaField* field = JavaObjectField::getInternalField(Field);
- field->setInstanceLongField(obj, (sint64)val);
-
- END_NATIVE_EXCEPTION
-}
-
-JNIEXPORT void JNICALL Java_java_io_VMObjectStreamClass_setFloatNative(
-#ifdef NATIVE_JNI
-JNIEnv *env,
-jclass clazz,
-#endif
-JavaObjectField* Field, JavaObject* obj, jfloat val) {
-
- llvm_gcroot(Field, 0);
- llvm_gcroot(obj, 0);
- BEGIN_NATIVE_EXCEPTION(0)
-
- verifyNull(obj);
- JavaField* field = JavaObjectField::getInternalField(Field);
- field->setInstanceFloatField(obj, (float)val);
-
- END_NATIVE_EXCEPTION
-}
-
-JNIEXPORT void JNICALL Java_java_io_VMObjectStreamClass_setDoubleNative(
-#ifdef NATIVE_JNI
-JNIEnv *env,
-jclass clazz,
-#endif
-JavaObjectField* Field, JavaObject* obj, jdouble val) {
-
- llvm_gcroot(Field, 0);
- llvm_gcroot(obj, 0);
- BEGIN_NATIVE_EXCEPTION(0)
-
- verifyNull(obj);
- JavaField* field = JavaObjectField::getInternalField(Field);
- field->setInstanceDoubleField(obj, (double)val);
-
- END_NATIVE_EXCEPTION
-}
-
-JNIEXPORT void JNICALL Java_java_io_VMObjectStreamClass_setObjectNative(
-#ifdef NATIVE_JNI
-JNIEnv *env,
-jclass clazz,
-#endif
-JavaObjectField* Field, JavaObject* obj, JavaObject* val) {
-
- llvm_gcroot(Field, 0);
- llvm_gcroot(obj, 0);
- llvm_gcroot(val, 0);
- BEGIN_NATIVE_EXCEPTION(0)
-
- verifyNull(obj);
- JavaField* field = JavaObjectField::getInternalField(Field);
- field->setInstanceObjectField(obj, val);
-
- END_NATIVE_EXCEPTION
-}
-
-JNIEXPORT JavaObject* JNICALL Java_java_io_VMObjectInputStream_allocateObject(
-#ifdef NATIVE_JNI
-JNIEnv *env,
-jclass clazz,
-#endif
-JavaObject* target, JavaObject* constr, JavaObjectConstructor* cons) {
-
- JavaObject* res = 0;
- llvm_gcroot(res, 0);
- llvm_gcroot(target, 0);
- llvm_gcroot(constr, 0);
- llvm_gcroot(cons, 0);
-
- BEGIN_NATIVE_EXCEPTION(0)
-
- UserClass* cl =
- (UserClass*)UserCommonClass::resolvedImplClass(target, true);
- res = cl->doNew();
- JavaMethod* meth = JavaObjectConstructor::getInternalMethod(cons);
- meth->invokeIntSpecial(cl, res);
-
- END_NATIVE_EXCEPTION
-
- return res;
-}
-
-JNIEXPORT JavaObject* JNICALL Java_java_lang_reflect_VMArray_createObjectArray(
-#ifdef NATIVE_JNI
-JNIEnv * env,
-jclass thisClass,
-#endif
-JavaObject* arrayType, jint arrayLength) {
-
- JavaObject* res = 0;
- llvm_gcroot(arrayType, 0);
- llvm_gcroot(res, 0);
-
- BEGIN_NATIVE_EXCEPTION(0)
-
- UserCommonClass* base =
- UserCommonClass::resolvedImplClass(arrayType, true);
- JnjvmClassLoader* loader = base->classLoader;
- const UTF8* name = base->getName();
- const UTF8* arrayName = loader->constructArrayName(1, name);
- UserClassArray* array = loader->constructArray(arrayName, base);
- res = array->doNew(arrayLength);
-
- END_NATIVE_EXCEPTION
-
- return res;
-}
-
-
-// Never throws.
-JNIEXPORT
-bool JNICALL Java_java_util_concurrent_atomic_AtomicLong_VMSupportsCS8(
-#ifdef NATIVE_JNI
-JNIEnv *env,
-jclass clazz,
-#endif
-) {
- return false;
-}
-
-// Never throws.
-JNIEXPORT bool JNICALL Java_sun_misc_Unsafe_compareAndSwapLong(
-#ifdef NATIVE_JNI
-JNIEnv *env,
-#endif
-JavaObject* unsafe, JavaObject* obj, jlong offset, jlong expect, jlong update) {
-
- llvm_gcroot(unsafe, 0);
- llvm_gcroot(obj, 0);
- jlong *ptr;
- jlong value;
-
- ptr = (jlong *) (((uint8 *) obj) + offset);
-
- value = *ptr;
-
- if (value == expect) {
- *ptr = update;
- return true;
- } else {
- return false;
- }
-
-}
-
-// Never throws.
-JNIEXPORT bool JNICALL Java_sun_misc_Unsafe_compareAndSwapInt(
-#ifdef NATIVE_JNI
-JNIEnv *env,
-#endif
-JavaObject* unsafe, JavaObject* obj, jlong offset, jint expect, jint update) {
-
- llvm_gcroot(unsafe, 0);
- llvm_gcroot(obj, 0);
- jint *ptr;
-
- ptr = (jint *) (((uint8 *) obj) + offset);
-
- return __sync_bool_compare_and_swap(ptr, expect, update);
-}
-
-// Never throws.
-JNIEXPORT bool JNICALL Java_sun_misc_Unsafe_compareAndSwapObject(
-#ifdef NATIVE_JNI
-JNIEnv *env,
-#endif
-JavaObject* unsafe, JavaObject* obj, jlong offset, JavaObject* expect,
-JavaObject* update) {
- llvm_gcroot(unsafe, 0);
- llvm_gcroot(obj, 0);
- llvm_gcroot(expect, 0);
- llvm_gcroot(update, 0);
-
- jobject *ptr;
-
- ptr = (jobject *) (((uint8 *) obj) + offset);
-
- return __sync_bool_compare_and_swap(ptr, expect, update);
-}
-
-// Never throws.
-JNIEXPORT void JNICALL Java_sun_misc_Unsafe_putObjectVolatile(
-#ifdef NATIVE_JNI
-JNIEnv *env,
-#endif
-JavaObject* unsafe, JavaObject* obj, jlong offset, JavaObject* value) {
- llvm_gcroot(unsafe, 0);
- llvm_gcroot(obj, 0);
- llvm_gcroot(value, 0);
-
- JavaObject** ptr;
-
- ptr = (JavaObject**) (((uint8 *) obj) + offset);
-
- *ptr = value;
-
-}
-}
diff --git a/vmkit/lib/J3/Classpath/ClasspathConstructor.inc b/vmkit/lib/J3/Classpath/ClasspathConstructor.inc
deleted file mode 100644
index 808cb8d..0000000
--- a/vmkit/lib/J3/Classpath/ClasspathConstructor.inc
+++ /dev/null
@@ -1,225 +0,0 @@
-//===- ClasspathConstructor.cpp -------------------------------------------===//
-//===----------- GNU classpath java/lang/reflect/Constructor --------------===//
-//
-// The VMKit project
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#include "types.h"
-
-#include "Classpath.h"
-#include "ClasspathReflect.h"
-#include "JavaArray.h"
-#include "JavaClass.h"
-#include "JavaObject.h"
-#include "JavaThread.h"
-#include "JavaTypes.h"
-#include "JavaUpcalls.h"
-#include "Jnjvm.h"
-#include "JnjvmClassLoader.h"
-
-using namespace j3;
-
-extern "C" {
-
-JNIEXPORT jobject JNICALL Java_java_lang_reflect_Constructor_getParameterTypes(
-#ifdef NATIVE_JNI
-JNIEnv *env,
-#endif
-JavaObjectConstructor* cons) {
-
- JavaObject* res = 0;
-
- llvm_gcroot(cons, 0);
- llvm_gcroot(res, 0);
-
- BEGIN_NATIVE_EXCEPTION(0)
-
- verifyNull(cons);
- UserClass* cl = JavaObjectConstructor::getClass(cons);
- JavaMethod* meth = JavaObjectConstructor::getInternalMethod(cons);
- JnjvmClassLoader* loader = cl->classLoader;
-
- res = meth->getParameterTypes(loader);
- END_NATIVE_EXCEPTION
-
- return (jobject)res;
-}
-
-JNIEXPORT jint JNICALL Java_java_lang_reflect_Constructor_getModifiersInternal(
-#ifdef NATIVE_JNI
-JNIEnv *env,
-#endif
-JavaObjectConstructor* cons) {
-
- llvm_gcroot(cons, 0);
- jint res = 0;
-
- BEGIN_NATIVE_EXCEPTION(0)
-
- verifyNull(cons);
- JavaMethod* meth = JavaObjectConstructor::getInternalMethod(cons);
- res = meth->access;
-
- END_NATIVE_EXCEPTION
-
- return res;
-}
-
-JavaObject* proceedConstructor(JavaObjectConstructor* cons,
- ArrayObject* args,
- JavaObject* Clazz, jint index)
- __attribute__ ((noinline));
-
-JavaObject* proceedConstructor(JavaObjectConstructor* cons,
- ArrayObject* args,
- JavaObject* Clazz, jint index) {
- JavaObject* res = 0;
- mvm::gc* excp = 0;
- JavaObject* jexcp;
-
- llvm_gcroot(cons, 0);
- llvm_gcroot(args, 0);
- llvm_gcroot(Clazz, 0);
- llvm_gcroot(res, 0);
- llvm_gcroot(excp, 0);
- llvm_gcroot(jexcp, 0);
-
- JavaMethod* meth = JavaObjectConstructor::getInternalMethod(cons);
- UserClass* cl = JavaObjectConstructor::getClass(cons);
- Jnjvm* vm = cl->classLoader->vm;
- sint32 nbArgs = args ? ArrayObject::getSize(args) : 0;
- Signdef* sign = meth->getSignature();
- sint32 size = sign->nbArguments;
-
- if (isAbstract(cl->access)) vm->instantiationException(cl);
-
- mvm::ThreadAllocator allocator;
- // Allocate a buffer to store the arguments.
- jvalue* buf = size ?
- (jvalue*)allocator.Allocate(size * sizeof(jvalue)) : NULL;
-
- if (nbArgs == size) {
- UserCommonClass* _cl = UserCommonClass::resolvedImplClass(Clazz, false);
- UserClass* cl = _cl->asClass();
- if (cl) {
- cl->initialiseClass();
- res = cl->doNew();
- JavaObject** ptr = (JavaObject**)ArrayObject::getElements(args);
-
- Typedef* const* arguments = sign->getArgumentsType();
- // Store the arguments, unboxing primitives if necessary.
- for (sint32 i = 0; i < size; ++i) {
- JavaObject::decapsulePrimitive(ptr[i], &buf[i], arguments[i]);
- if (!arguments[i]->isPrimitive()) {
- buf[i].l = reinterpret_cast<jobject>(&ptr[i]);
- }
- }
-
- TRY {
- meth->invokeIntSpecialBuf(cl, res, buf);
- } CATCH {
- excp = mvm::Thread::get()->getPendingException();
- } END_CATCH;
- mvm::Thread* mut = mvm::Thread::get();
- if (excp) {
- jexcp = Jnjvm::asJavaException(excp);
- if (jexcp && JavaObject::getClass(jexcp)->isAssignableFrom(vm->upcalls->newException)) {
- mut->clearPendingException();
- // If it's an exception, we encapsule it in an
- // invocationTargetException
- vm->invocationTargetException(jexcp);
- } else {
- // If it's an error, throw it again.
- mut->throwIt();
- }
- return NULL;
- }
- } else {
- vm->illegalArgumentException("class is not a regular class");
- return NULL;
- }
- } else {
- vm->illegalArgumentException("wrong number of arguments");
- return NULL;
- }
-
- return res;
-}
-
-JNIEXPORT JavaObject* JNICALL Java_java_lang_reflect_Constructor_constructNative(
-#ifdef NATIVE_JNI
-JNIEnv *env,
-#endif
-JavaObjectConstructor* cons, ArrayObject* args, JavaObject* Clazz, jint index) {
-
- JavaObject* res = 0;
-
- llvm_gcroot(res, 0);
- llvm_gcroot(cons, 0);
- llvm_gcroot(args, 0);
- llvm_gcroot(Clazz, 0);
-
- BEGIN_NATIVE_EXCEPTION(0)
-
- res = proceedConstructor(cons, args, Clazz, index);
-
- END_NATIVE_EXCEPTION
-
- return res;
-}
-
-JNIEXPORT
-ArrayObject* JNICALL Java_java_lang_reflect_Constructor_getExceptionTypes(
-#ifdef NATIVE_JNI
-JNIEnv *env,
-#endif
-JavaObjectConstructor* cons) {
-
- ArrayObject* res = 0;
-
- llvm_gcroot(res, 0);
- llvm_gcroot(cons, 0);
-
- BEGIN_NATIVE_EXCEPTION(0)
-
- verifyNull(cons);
- UserClass* cl = JavaObjectConstructor::getClass(cons);
- JavaMethod* meth = JavaObjectConstructor::getInternalMethod(cons);
- JnjvmClassLoader* loader = cl->classLoader;
-
- res = (ArrayObject*)meth->getExceptionTypes(loader);
-
- END_NATIVE_EXCEPTION
-
- return res;
-}
-
-JNIEXPORT JavaObject* JNICALL Java_java_lang_reflect_Constructor_getSignature(
-#ifdef NATIVE_JNI
-JNIEnv *env,
-#endif
-JavaObjectConstructor* Meth) {
-
- JavaObject* result = 0;
-
- llvm_gcroot(result, 0);
- llvm_gcroot(Meth, 0);
-
- BEGIN_NATIVE_EXCEPTION(0)
-
- verifyNull(Meth);
- JavaMethod* meth = JavaObjectConstructor::getInternalMethod(Meth);
- Jnjvm* vm = meth->classDef->classLoader->vm;
- result = vm->internalUTF8ToStr(meth->type);
-
- END_NATIVE_EXCEPTION
-
- return result;
-}
-
-
-}
diff --git a/vmkit/lib/J3/Classpath/ClasspathField.inc b/vmkit/lib/J3/Classpath/ClasspathField.inc
deleted file mode 100644
index 74a56d0..0000000
--- a/vmkit/lib/J3/Classpath/ClasspathField.inc
+++ /dev/null
@@ -1,1169 +0,0 @@
-//===- ClasspathVMField.cpp - GNU classpath java/lang/reflect/Field -------===//
-//
-// The VMKit project
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#include "Classpath.h"
-#include "ClasspathReflect.h"
-#include "JavaClass.h"
-#include "JavaThread.h"
-#include "JavaTypes.h"
-#include "JavaUpcalls.h"
-#include "Jnjvm.h"
-
-using namespace j3;
-
-extern "C" {
-
-
-JNIEXPORT jint JNICALL Java_java_lang_reflect_Field_getModifiersInternal(
-#ifdef NATIVE_JNI
-JNIEnv *env,
-#endif
-JavaObjectField* Field) {
- jint res = 0;
-
- llvm_gcroot(Field, 0);
-
- BEGIN_NATIVE_EXCEPTION(0)
-
- JavaField* field = JavaObjectField::getInternalField(Field);
- res = field->access;
-
- END_NATIVE_EXCEPTION
-
- return res;
-}
-
-JNIEXPORT JavaObject* JNICALL Java_java_lang_reflect_Field_getType(
-#ifdef NATIVE_JNI
-JNIEnv *env,
-#endif
-JavaObjectField* Field) {
-
- JavaObject* res = 0;
-
- llvm_gcroot(Field, 0);
- llvm_gcroot(res, 0);
-
- BEGIN_NATIVE_EXCEPTION(0)
-
- UserClass* cl = JavaObjectField::getClass(Field);
- JavaField* field = JavaObjectField::getInternalField(Field);
- JnjvmClassLoader* loader = cl->classLoader;
- UserCommonClass* fieldCl = field->getSignature()->assocClass(loader);
- res = fieldCl->getClassDelegatee();
-
- END_NATIVE_EXCEPTION
-
- return res;
-}
-
-JNIEXPORT jint JNICALL Java_java_lang_reflect_Field_getInt(
-#ifdef NATIVE_JNI
-JNIEnv *env,
-#endif
-JavaObjectField* Field, JavaObject* obj) {
-
- jint res = 0;
-
- llvm_gcroot(Field, 0);
- llvm_gcroot(obj, 0);
-
- BEGIN_NATIVE_EXCEPTION(0)
-
- UserClass* cl = JavaObjectField::getClass(Field);
- Jnjvm* vm = cl->classLoader->vm;
- JavaField* field = JavaObjectField::getInternalField(Field);
- const Typedef* type = field->getSignature();
- bool stat = isStatic(field->access);
-
- if (stat) {
- cl->initialiseClass();
- } else {
- verifyNull(obj);
- }
-
- if (type->isPrimitive()) {
- const PrimitiveTypedef* prim = (const PrimitiveTypedef*)type;
-
- if (prim->isInt()) {
- if (stat) {
- res = (sint32)field->getStaticInt32Field();
- } else {
- res = (sint32)field->getInstanceInt32Field(obj);
- }
- } else if (prim->isChar()) {
- if (stat) {
- res = (uint32)field->getStaticInt16Field();
- } else {
- res = (uint32)field->getInstanceInt16Field(obj);
- }
- } else if (prim->isByte()) {
- if (stat) {
- res = (sint32)field->getStaticInt8Field();
- } else {
- res = (sint32)field->getInstanceInt8Field(obj);
- }
- } else if (prim->isShort()) {
- if (stat) {
- res = (sint32)field->getStaticInt16Field();
- } else {
- res = (sint32)field->getInstanceInt16Field(obj);
- }
- } else {
- vm->illegalArgumentException("wrong type");
- }
- } else {
- vm->illegalArgumentException("wrong type");
- }
-
- END_NATIVE_EXCEPTION
-
- return res;
-
-}
-
-JNIEXPORT jlong JNICALL Java_java_lang_reflect_Field_getLong(
-#ifdef NATIVE_JNI
-JNIEnv *env,
-#endif
-JavaObjectField* Field, JavaObject* obj) {
-
- jlong res = 0;
-
- llvm_gcroot(Field, 0);
- llvm_gcroot(obj, 0);
-
- BEGIN_NATIVE_EXCEPTION(0)
-
- UserClass* cl = JavaObjectField::getClass(Field);
- Jnjvm* vm = cl->classLoader->vm;
- JavaField* field = JavaObjectField::getInternalField(Field);
- bool stat = isStatic(field->access);
-
- if (stat) {
- cl->initialiseClass();
- } else {
- verifyNull(obj);
- }
-
- const Typedef* type = field->getSignature();
- if (type->isPrimitive()) {
- const PrimitiveTypedef* prim = (const PrimitiveTypedef*)type;
-
- if (prim->isInt()) {
- if (stat) {
- res = (sint64)field->getStaticInt32Field();
- } else {
- res = (sint64)field->getInstanceInt32Field(obj);
- }
- } else if (prim->isChar()) {
- if (stat) {
- res = (uint64)field->getStaticInt16Field();
- } else {
- res = (uint64)field->getInstanceInt16Field(obj);
- }
- } else if (prim->isByte()) {
- if (stat) {
- res = (sint64)field->getStaticInt8Field();
- } else {
- res = (sint64)field->getInstanceInt8Field(obj);
- }
- } else if (prim->isShort()) {
- if (stat) {
- res = (sint64)field->getStaticInt16Field();
- } else {
- res = (sint64)field->getInstanceInt16Field(obj);
- }
- } else if (prim->isLong()) {
- if (stat) {
- res = (sint64)field->getStaticLongField();
- } else {
- res = (sint64)field->getInstanceLongField(obj);
- }
- } else {
- vm->illegalArgumentException("wrong type");
- }
- } else {
- vm->illegalArgumentException("wrong type");
- }
-
- END_NATIVE_EXCEPTION
-
- return res;
-}
-
-JNIEXPORT jboolean JNICALL Java_java_lang_reflect_Field_getBoolean(
-#ifdef NATIVE_JNI
-JNIEnv *env,
-#endif
-JavaObjectField* Field, JavaObject* obj) {
-
- jboolean res = 0;
-
- llvm_gcroot(Field, 0);
- llvm_gcroot(obj, 0);
-
- BEGIN_NATIVE_EXCEPTION(0)
-
- UserClass* cl = JavaObjectField::getClass(Field);
- Jnjvm* vm = cl->classLoader->vm;
- JavaField* field = JavaObjectField::getInternalField(Field);
- bool stat = isStatic(field->access);
-
- if (stat) {
- cl->initialiseClass();
- } else {
- verifyNull(obj);
- }
-
- const Typedef* type = field->getSignature();
- if (type->isPrimitive()) {
- const PrimitiveTypedef* prim = (const PrimitiveTypedef*)type;
- if (prim->isBool()) {
- if (stat) {
- res = (uint8)field->getStaticInt8Field();
- } else {
- res = (uint8)field->getInstanceInt8Field(obj);
- }
- } else {
- vm->illegalArgumentException("wrong type");
- }
- } else {
- vm->illegalArgumentException("wrong type");
- }
-
- END_NATIVE_EXCEPTION
-
- return res;
-
-}
-
-JNIEXPORT jfloat JNICALL Java_java_lang_reflect_Field_getFloat(
-#ifdef NATIVE_JNI
-JNIEnv *env,
-#endif
-JavaObjectField* Field, JavaObject* obj) {
-
- jfloat res = 0;
- llvm_gcroot(Field, 0);
- llvm_gcroot(obj, 0);
-
- BEGIN_NATIVE_EXCEPTION(0)
-
- UserClass* cl = JavaObjectField::getClass(Field);
- Jnjvm* vm = cl->classLoader->vm;
- JavaField* field = JavaObjectField::getInternalField(Field);
- bool stat = isStatic(field->access);
-
- if (stat) {
- cl->initialiseClass();
- } else {
- verifyNull(obj);
- }
-
- const Typedef* type = field->getSignature();
- if (type->isPrimitive()) {
- const PrimitiveTypedef* prim = (const PrimitiveTypedef*)type;
- if (prim->isByte()) {
- if (stat) {
- res = (jfloat)field->getStaticInt8Field();
- } else {
- res = (jfloat)field->getInstanceInt8Field(obj);
- }
- } else if (prim->isInt()) {
- if (stat) {
- res = (jfloat)field->getStaticInt32Field();
- } else {
- res = (jfloat)field->getInstanceInt32Field(obj);
- }
- } else if (prim->isShort()) {
- if (stat) {
- res = (jfloat)field->getStaticInt16Field();
- } else {
- res = (jfloat)field->getInstanceInt16Field(obj);
- }
- } else if (prim->isLong()) {
- if (stat) {
- res = (jfloat)field->getStaticLongField();
- } else {
- res = (jfloat)field->getInstanceLongField(obj);
- }
- } else if (prim->isChar()) {
- // Cast to uint32 because char is unsigned.
- if (stat) {
- res = (jfloat)(uint32)field->getStaticInt16Field();
- } else {
- res = (jfloat)(uint32)field->getInstanceInt16Field(obj);
- }
- } else if (prim->isFloat()) {
- if (stat) {
- res = (jfloat)field->getStaticFloatField();
- } else {
- res = (jfloat)field->getInstanceFloatField(obj);
- }
- } else {
- vm->illegalArgumentException("wrong type");
- }
- } else {
- vm->illegalArgumentException("wrong type");
- }
-
- END_NATIVE_EXCEPTION
-
- return res;
-}
-
-JNIEXPORT jbyte JNICALL Java_java_lang_reflect_Field_getByte(
-#ifdef NATIVE_JNI
-JNIEnv *env,
-#endif
-JavaObjectField* Field, JavaObject* obj) {
-
- jbyte res = 0;
- llvm_gcroot(Field, 0);
- llvm_gcroot(obj, 0);
-
- BEGIN_NATIVE_EXCEPTION(0)
-
- UserClass* cl = JavaObjectField::getClass(Field);
- Jnjvm* vm = cl->classLoader->vm;
- JavaField* field = JavaObjectField::getInternalField(Field);
- bool stat = isStatic(field->access);
-
- if (stat) {
- cl->initialiseClass();
- } else {
- verifyNull(obj);
- }
-
- const Typedef* type = field->getSignature();
- if (type->isPrimitive()) {
- const PrimitiveTypedef* prim = (const PrimitiveTypedef*)type;
- if (prim->isByte()) {
- if (stat) {
- res = (sint8)field->getStaticInt8Field();
- } else {
- res = (sint8)field->getInstanceInt8Field(obj);
- }
- } else {
- vm->illegalArgumentException("wrong type");
- }
- } else {
- vm->illegalArgumentException("wrong type");
- }
-
- END_NATIVE_EXCEPTION
-
- return res;
-}
-
-JNIEXPORT jchar JNICALL Java_java_lang_reflect_Field_getChar(
-#ifdef NATIVE_JNI
-JNIEnv *env,
-#endif
-JavaObjectField* Field, JavaObject* obj) {
-
- jchar res = 0;
- llvm_gcroot(Field, 0);
- llvm_gcroot(obj, 0);
-
- BEGIN_NATIVE_EXCEPTION(0)
-
- UserClass* cl = JavaObjectField::getClass(Field);
- Jnjvm* vm = cl->classLoader->vm;
- JavaField* field = JavaObjectField::getInternalField(Field);
- bool stat = isStatic(field->access);
-
- if (stat) {
- cl->initialiseClass();
- } else {
- verifyNull(obj);
- }
-
- const Typedef* type = field->getSignature();
- if (type->isPrimitive()) {
- const PrimitiveTypedef* prim = (const PrimitiveTypedef*)type;
- if (prim->isChar()) {
- if (stat) {
- res = (uint16)field->getStaticInt16Field();
- } else {
- res = (uint16)field->getInstanceInt16Field(obj);
- }
- } else {
- vm->illegalArgumentException("wrong type");
- }
- } else {
- vm->illegalArgumentException("wrong type");
- }
-
- END_NATIVE_EXCEPTION
-
- return res;
-
-}
-
-JNIEXPORT jshort JNICALL Java_java_lang_reflect_Field_getShort(
-#ifdef NATIVE_JNI
-JNIEnv *env,
-#endif
-JavaObjectField* Field, JavaObject* obj) {
-
-
- jshort res = 0;
- llvm_gcroot(Field, 0);
- llvm_gcroot(obj, 0);
-
- BEGIN_NATIVE_EXCEPTION(0)
-
- UserClass* cl = JavaObjectField::getClass(Field);
- Jnjvm* vm = cl->classLoader->vm;
- JavaField* field = JavaObjectField::getInternalField(Field);
- bool stat = isStatic(field->access);
-
- if (stat) {
- cl->initialiseClass();
- } else {
- verifyNull(obj);
- }
-
- const Typedef* type = field->getSignature();
- if (type->isPrimitive()) {
- const PrimitiveTypedef* prim = (const PrimitiveTypedef*)type;
- if (prim->isShort()) {
- if (stat) {
- res = (sint16)field->getStaticInt16Field();
- } else {
- res = (sint16)field->getInstanceInt16Field(obj);
- }
- } else if (prim->isByte()) {
- if (stat) {
- res = (sint16)field->getStaticInt8Field();
- } else {
- res = (sint16)field->getInstanceInt8Field(obj);
- }
- } else {
- vm->illegalArgumentException("wrong type");
- }
- } else {
- vm->illegalArgumentException("wrong type");
- }
-
- END_NATIVE_EXCEPTION
-
- return res;
-}
-
-JNIEXPORT jdouble JNICALL Java_java_lang_reflect_Field_getDouble(
-#ifdef NATIVE_JNI
-JNIEnv *env,
-#endif
-JavaObjectField* Field, JavaObject* obj) {
-
- jdouble res = 0;
- llvm_gcroot(Field, 0);
- llvm_gcroot(obj, 0);
-
- BEGIN_NATIVE_EXCEPTION(0)
-
- UserClass* cl = JavaObjectField::getClass(Field);
- Jnjvm* vm = cl->classLoader->vm;
- JavaField* field = JavaObjectField::getInternalField(Field);
- bool stat = isStatic(field->access);
-
- if (stat) {
- cl->initialiseClass();
- } else {
- verifyNull(obj);
- }
-
- const Typedef* type = field->getSignature();
- if (type->isPrimitive()) {
- const PrimitiveTypedef* prim = (const PrimitiveTypedef*)type;
- if (prim->isByte()) {
- if (stat) {
- res = (jdouble)(sint64)field->getStaticInt8Field();
- } else {
- res = (jdouble)(sint64)field->getInstanceInt8Field(obj);
- }
- } else if (prim->isInt()) {
- if (stat) {
- res = (jdouble)(sint64)field->getStaticInt32Field();
- } else {
- res = (jdouble)(sint64)field->getInstanceInt32Field(obj);
- }
- } else if (prim->isShort()) {
- if (stat) {
- res = (jdouble)(sint64)field->getStaticInt16Field();
- } else {
- res = (jdouble)(sint64)field->getInstanceInt16Field(obj);
- }
- } else if (prim->isLong()) {
- if (stat) {
- res = (jdouble)(sint64)field->getStaticLongField();
- } else {
- res = (jdouble)(sint64)field->getInstanceLongField(obj);
- }
- } else if (prim->isChar()) {
- if (stat) {
- res = (jdouble)(uint64)field->getStaticInt16Field();
- } else {
- res = (jdouble)(uint64)field->getInstanceInt16Field(obj);
- }
- } else if (prim->isFloat()) {
- if (stat) {
- res = (jdouble)field->getStaticFloatField();
- } else {
- res = (jdouble)field->getInstanceFloatField(obj);
- }
- } else if (prim->isDouble()) {
- if (stat) {
- res = (jdouble)field->getStaticDoubleField();
- } else {
- res = (jdouble)field->getInstanceDoubleField(obj);
- }
- } else {
- vm->illegalArgumentException("wrong type");
- }
- } else {
- vm->illegalArgumentException("wrong type");
- }
-
- END_NATIVE_EXCEPTION
-
- return res;
-}
-
-JNIEXPORT JavaObject* JNICALL Java_java_lang_reflect_Field_get(
-#ifdef NATIVE_JNI
-JNIEnv *env,
-#endif
-JavaObjectField* Field, JavaObject* obj) {
-
-
- JavaObject* res = 0;
- llvm_gcroot(Field, 0);
- llvm_gcroot(obj, 0);
- llvm_gcroot(res, 0);
-
- BEGIN_NATIVE_EXCEPTION(0)
-
- UserClass* cl = JavaObjectField::getClass(Field);
- Jnjvm* vm = cl->classLoader->vm;
- JavaField* field = JavaObjectField::getInternalField(Field);
- bool stat = isStatic(field->access);
-
- if (stat) {
- cl->initialiseClass();
- } else {
- verifyNull(obj);
- }
-
- const Typedef* type = field->getSignature();
- if (type->isPrimitive()) {
- const PrimitiveTypedef* prim = (const PrimitiveTypedef*)type;
- if (prim->isBool()) {
- uint8 val = stat ? field->getStaticInt8Field() :
- field->getInstanceInt8Field(obj);
- res = vm->upcalls->boolClass->doNew();
- vm->upcalls->boolValue->setInstanceInt8Field(res, val);
- } else if (prim->isByte()) {
- sint8 val = stat ? field->getStaticInt8Field() :
- field->getInstanceInt8Field(obj);
- res = vm->upcalls->byteClass->doNew();
- vm->upcalls->byteValue->setInstanceInt8Field(res, val);
- } else if (prim->isChar()) {
- uint16 val = stat ? field->getStaticInt16Field() :
- field->getInstanceInt16Field(obj);
- res = vm->upcalls->charClass->doNew();
- vm->upcalls->charValue->setInstanceInt16Field(res, val);
- } else if (prim->isShort()) {
- sint16 val = stat ? field->getStaticInt16Field() :
- field->getInstanceInt16Field(obj);
- res = vm->upcalls->shortClass->doNew();
- vm->upcalls->shortValue->setInstanceInt16Field(res, val);
- } else if (prim->isInt()) {
- sint64 val = stat ? field->getStaticInt32Field() :
- field->getInstanceInt32Field(obj);
- res = vm->upcalls->intClass->doNew();
- vm->upcalls->intValue->setInstanceInt32Field(res, val);
- } else if (prim->isLong()) {
- sint64 val = stat ? field->getStaticLongField() :
- field->getInstanceLongField(obj);
- res = vm->upcalls->longClass->doNew();
- vm->upcalls->longValue->setInstanceLongField(res, val);
- } else if (prim->isFloat()) {
- float val = stat ? field->getStaticFloatField() :
- field->getInstanceFloatField(obj);
- res = vm->upcalls->floatClass->doNew();
- vm->upcalls->floatValue->setInstanceFloatField(res, val);
- } else if (prim->isDouble()) {
- double val = stat ? field->getStaticDoubleField() :
- field->getInstanceDoubleField(obj);
- res = vm->upcalls->doubleClass->doNew();
- vm->upcalls->doubleValue->setInstanceDoubleField(res, val);
- }
- } else {
- if (stat) {
- res = field->getStaticObjectField();
- } else {
- res = field->getInstanceObjectField(obj);
- }
- }
-
- END_NATIVE_EXCEPTION
-
- return res;
-}
-
-JNIEXPORT void JNICALL Java_java_lang_reflect_Field_set(
-#ifdef NATIVE_JNI
-JNIEnv *env,
-#endif
-JavaObjectField* Field, JavaObject* obj, JavaObject* val) {
-
- llvm_gcroot(Field, 0);
- llvm_gcroot(obj, 0);
- llvm_gcroot(val, 0);
-
- BEGIN_NATIVE_EXCEPTION(0)
-
- UserClass* cl = JavaObjectField::getClass(Field);
- JavaField* field = JavaObjectField::getInternalField(Field);
- jvalue buf;
- bool stat = isStatic(field->access);
-
-
- if (stat) {
- cl->initialiseClass();
- } else {
- verifyNull(obj);
- }
-
- const Typedef* type = field->getSignature();
- JavaObject::decapsulePrimitive(val, &buf, type);
-
-
- if (type->isPrimitive()) {
- const PrimitiveTypedef* prim = (const PrimitiveTypedef*)type;
- if (prim->isBool()) {
- if (stat) {
- field->setStaticInt8Field(buf.z);
- } else {
- field->setInstanceInt8Field(obj, buf.z);
- }
- } else if (prim->isByte()) {
- if (stat) {
- field->setStaticInt8Field(buf.b);
- } else {
- field->setInstanceInt8Field(obj, buf.b);
- }
- } else if (prim->isChar()) {
- if (stat) {
- field->setStaticInt16Field(buf.c);
- } else {
- field->setInstanceInt16Field(obj, buf.c);
- }
- } else if (prim->isShort()) {
- if (stat) {
- field->setStaticInt16Field(buf.s);
- } else {
- field->setInstanceInt16Field(obj, buf.s);
- }
- } else if (prim->isInt()) {
- if (stat) {
- field->setStaticInt32Field(buf.i);
- } else {
- field->setInstanceInt32Field(obj, buf.i);
- }
- } else if (prim->isLong()) {
- if (stat) {
- field->setStaticLongField(buf.j);
- } else {
- field->setInstanceLongField(obj, buf.j);
- }
- } else if (prim->isFloat()) {
- if (stat) {
- field->setStaticFloatField(buf.f);
- } else {
- field->setInstanceFloatField(obj, buf.f);
- }
- } else if (prim->isDouble()) {
- if (stat) {
- field->setStaticDoubleField(buf.d);
- } else {
- field->setInstanceDoubleField(obj, buf.d);
- }
- }
- } else {
- if (stat) {
- field->setStaticObjectField(val);
- } else {
- field->setInstanceObjectField(obj, val);
- }
- }
-
- END_NATIVE_EXCEPTION
-}
-
-JNIEXPORT void JNICALL Java_java_lang_reflect_Field_setBoolean(
-#ifdef NATIVE_JNI
-JNIEnv *env,
-#endif
-JavaObjectField* Field, JavaObject* obj, jboolean val) {
-
- llvm_gcroot(Field, 0);
- llvm_gcroot(obj, 0);
-
- BEGIN_NATIVE_EXCEPTION(0)
-
- UserClass* cl = JavaObjectField::getClass(Field);
- Jnjvm* vm = cl->classLoader->vm;
- JavaField* field = JavaObjectField::getInternalField(Field);
- bool stat = isStatic(field->access);
-
- if (stat) {
- cl->initialiseClass();
- } else {
- verifyNull(obj);
- }
-
- const Typedef* type = field->getSignature();
- if (type->isPrimitive()) {
- const PrimitiveTypedef* prim = (const PrimitiveTypedef*)type;
- if (prim->isBool()) {
- if (stat) {
- field->setStaticInt8Field((uint8)val);
- } else {
- field->setInstanceInt8Field(obj, (uint8)val);
- }
- } else {
- vm->illegalArgumentException("wrong type");
- }
- } else {
- vm->illegalArgumentException("wrong type");
- }
-
- END_NATIVE_EXCEPTION
-
-}
-
-JNIEXPORT void JNICALL Java_java_lang_reflect_Field_setByte(
-#ifdef NATIVE_JNI
-JNIEnv *env,
-#endif
-JavaObjectField* Field, JavaObject* obj, jbyte val) {
-
- llvm_gcroot(Field, 0);
- llvm_gcroot(obj, 0);
-
- BEGIN_NATIVE_EXCEPTION(0)
-
- UserClass* cl = JavaObjectField::getClass(Field);
- Jnjvm* vm = cl->classLoader->vm;
- JavaField* field = JavaObjectField::getInternalField(Field);
- bool stat = isStatic(field->access);
-
- if (stat) {
- cl->initialiseClass();
- } else {
- verifyNull(obj);
- }
-
- const Typedef* type = field->getSignature();
- if (type->isPrimitive()) {
- const PrimitiveTypedef* prim = (const PrimitiveTypedef*)type;
- if (prim->isByte()) {
- if (stat) {
- field->setStaticInt8Field((sint8)val);
- } else {
- field->setInstanceInt8Field(obj, (sint8)val);
- }
- } else if (prim->isShort()) {
- if (stat) {
- field->setStaticInt16Field((sint16)val);
- } else {
- field->setInstanceInt16Field(obj, (sint16)val);
- }
- } else if (prim->isInt()) {
- if (stat) {
- field->setStaticInt32Field((sint32)val);
- } else {
- field->setInstanceInt32Field(obj, (sint32)val);
- }
- } else if (prim->isLong()) {
- if (stat) {
- field->setStaticLongField((sint64)val);
- } else {
- field->setInstanceLongField(obj, (sint64)val);
- }
- } else if (prim->isFloat()) {
- if (stat) {
- field->setStaticFloatField((float)val);
- } else {
- field->setInstanceFloatField(obj, (float)val);
- }
- } else if (prim->isDouble()) {
- if (stat) {
- field->setStaticDoubleField((double)val);
- } else {
- field->setInstanceDoubleField(obj, (double)val);
- }
- } else {
- vm->illegalArgumentException("wrong type");
- }
- } else {
- vm->illegalArgumentException("wrong type");
- }
-
- END_NATIVE_EXCEPTION
-}
-
-JNIEXPORT void JNICALL Java_java_lang_reflect_Field_setChar(
-#ifdef NATIVE_JNI
-JNIEnv *env,
-#endif
-JavaObjectField* Field, JavaObject* obj, jchar val) {
-
- llvm_gcroot(Field, 0);
- llvm_gcroot(obj, 0);
-
- BEGIN_NATIVE_EXCEPTION(0)
-
- UserClass* cl = JavaObjectField::getClass(Field);
- Jnjvm* vm = cl->classLoader->vm;
- JavaField* field = JavaObjectField::getInternalField(Field);
- bool stat = isStatic(field->access);
-
- if (stat) {
- cl->initialiseClass();
- } else {
- verifyNull(obj);
- }
- const Typedef* type = field->getSignature();
- if (type->isPrimitive()) {
- const PrimitiveTypedef* prim = (const PrimitiveTypedef*)type;
- if (prim->isChar()) {
- if (stat) {
- field->setStaticInt16Field((uint16)val);
- } else {
- field->setInstanceInt16Field(obj, (uint16)val);
- }
- } else if (prim->isInt()) {
- if (stat) {
- field->setStaticInt32Field((uint32)val);
- } else {
- field->setInstanceInt32Field(obj, (uint32)val);
- }
- } else if (prim->isLong()) {
- if (stat) {
- field->setStaticLongField((uint64)val);
- } else {
- field->setInstanceLongField(obj, (uint64)val);
- }
- } else if (prim->isFloat()) {
- if (stat) {
- field->setStaticFloatField((float)(uint32)val);
- } else {
- field->setInstanceFloatField(obj, (float)(uint32)val);
- }
- } else if (prim->isDouble()) {
- if (stat) {
- field->setStaticDoubleField((double)(uint64)val);
- } else {
- field->setInstanceDoubleField(obj, (double)(uint64)val);
- }
- } else {
- vm->illegalArgumentException("wrong type");
- }
- } else {
- vm->illegalArgumentException("wrong type");
- }
-
- END_NATIVE_EXCEPTION
-}
-
-JNIEXPORT void JNICALL Java_java_lang_reflect_Field_setShort(
-#ifdef NATIVE_JNI
-JNIEnv *env,
-#endif
-JavaObjectField* Field, JavaObject* obj, jshort val) {
-
- llvm_gcroot(Field, 0);
- llvm_gcroot(obj, 0);
-
- BEGIN_NATIVE_EXCEPTION(0)
-
- UserClass* cl = JavaObjectField::getClass(Field);
- Jnjvm* vm = cl->classLoader->vm;
- JavaField* field = JavaObjectField::getInternalField(Field);
- bool stat = isStatic(field->access);
-
- if (stat) {
- cl->initialiseClass();
- } else {
- verifyNull(obj);
- }
-
- const Typedef* type = field->getSignature();
- if (type->isPrimitive()) {
- const PrimitiveTypedef* prim = (const PrimitiveTypedef*)type;
- if (prim->isShort()) {
- if (stat) {
- field->setStaticInt16Field((sint16)val);
- } else {
- field->setInstanceInt16Field(obj, (sint16)val);
- }
- } else if (prim->isInt()) {
- if (stat) {
- field->setStaticInt32Field((sint32)val);
- } else {
- field->setInstanceInt32Field(obj, (sint32)val);
- }
- } else if (prim->isLong()) {
- if (stat) {
- field->setStaticLongField((sint64)val);
- } else {
- }
- } else if (prim->isFloat()) {
- if (stat) {
- field->setStaticFloatField((float)val);
- } else {
- field->setInstanceFloatField(obj, (float)val);
- }
- } else if (prim->isDouble()) {
- if (stat) {
- field->setStaticDoubleField((double)val);
- } else {
- field->setInstanceDoubleField(obj, (double)val);
- }
- } else {
- vm->illegalArgumentException("wrong type");
- }
- } else {
- vm->illegalArgumentException("wrong type");
- }
-
- END_NATIVE_EXCEPTION
-}
-
-JNIEXPORT void JNICALL Java_java_lang_reflect_Field_setInt(
-#ifdef NATIVE_JNI
-JNIEnv *env,
-#endif
-JavaObjectField* Field, JavaObject* obj, jint val) {
-
- llvm_gcroot(Field, 0);
- llvm_gcroot(obj, 0);
-
- BEGIN_NATIVE_EXCEPTION(0)
-
- UserClass* cl = JavaObjectField::getClass(Field);
- Jnjvm* vm = cl->classLoader->vm;
- JavaField* field = JavaObjectField::getInternalField(Field);
- bool stat = isStatic(field->access);
-
- if (stat) {
- cl->initialiseClass();
- } else {
- verifyNull(obj);
- }
-
- const Typedef* type = field->getSignature();
- if (type->isPrimitive()) {
- const PrimitiveTypedef* prim = (const PrimitiveTypedef*)type;
- if (prim->isInt()) {
- if (stat) {
- field->setStaticInt32Field((sint32)val);
- } else {
- field->setInstanceInt32Field(obj, (sint32)val);
- }
- } else if (prim->isLong()) {
- if (stat) {
- field->setStaticLongField((sint64)val);
- } else {
- field->setInstanceLongField(obj, (sint64)val);
- }
- } else if (prim->isFloat()) {
- if (stat) {
- field->setStaticFloatField((float)val);
- } else {
- field->setInstanceFloatField(obj, (float)val);
- }
- } else if (prim->isDouble()) {
- if (stat) {
- field->setStaticDoubleField((double)val);
- } else {
- field->setInstanceDoubleField(obj, (double)val);
- }
- } else {
- vm->illegalArgumentException("wrong type");
- }
- } else {
- vm->illegalArgumentException("wrong type");
- }
-
- END_NATIVE_EXCEPTION
-}
-
-JNIEXPORT void JNICALL Java_java_lang_reflect_Field_setLong(
-#ifdef NATIVE_JNI
-JNIEnv *env,
-#endif
-JavaObjectField* Field, JavaObject* obj, jlong val) {
-
- llvm_gcroot(Field, 0);
- llvm_gcroot(obj, 0);
-
- BEGIN_NATIVE_EXCEPTION(0)
-
- UserClass* cl = JavaObjectField::getClass(Field);
- Jnjvm* vm = cl->classLoader->vm;
- JavaField* field = JavaObjectField::getInternalField(Field);
- bool stat = isStatic(field->access);
-
- if (stat) {
- cl->initialiseClass();
- } else {
- verifyNull(obj);
- }
-
- const Typedef* type = field->getSignature();
- if (type->isPrimitive()) {
- const PrimitiveTypedef* prim = (const PrimitiveTypedef*)type;
- if (prim->isLong()) {
- if (stat) {
- field->setStaticLongField((sint64)val);
- } else {
- field->setInstanceLongField(obj, (sint64)val);
- }
- } else if (prim->isFloat()) {
- if (stat) {
- field->setStaticFloatField((float)val);
- } else {
- field->setInstanceFloatField(obj, (float)val);
- }
- } else if (prim->isDouble()) {
- if (stat) {
- field->setStaticDoubleField((double)val);
- } else {
- field->setInstanceDoubleField(obj, (double)val);
- }
- } else {
- vm->illegalArgumentException("wrong type");
- }
- } else {
- vm->illegalArgumentException("wrong type");
- }
-
- END_NATIVE_EXCEPTION
-}
-
-JNIEXPORT void JNICALL Java_java_lang_reflect_Field_setFloat(
-#ifdef NATIVE_JNI
-JNIEnv *env,
-#endif
-JavaObjectField* Field, JavaObject* obj, jfloat val) {
-
- llvm_gcroot(Field, 0);
- llvm_gcroot(obj, 0);
-
- BEGIN_NATIVE_EXCEPTION(0)
-
- UserClass* cl = JavaObjectField::getClass(Field);
- Jnjvm* vm = cl->classLoader->vm;
- JavaField* field = JavaObjectField::getInternalField(Field);
- bool stat = isStatic(field->access);
-
- if (stat) {
- cl->initialiseClass();
- } else {
- verifyNull(obj);
- }
-
- const Typedef* type = field->getSignature();
- if (type->isPrimitive()) {
- const PrimitiveTypedef* prim = (const PrimitiveTypedef*)type;
- if (prim->isFloat()) {
- if (stat) {
- field->setStaticFloatField((float)val);
- } else {
- field->setInstanceFloatField(obj, (float)val);
- }
- } else if (prim->isDouble()) {
- if (stat) {
- field->setStaticDoubleField((double)val);
- } else {
- field->setInstanceDoubleField(obj, (double)val);
- }
- } else {
- vm->illegalArgumentException("wrong type");
- }
- } else {
- vm->illegalArgumentException("wrong type");
- }
-
- END_NATIVE_EXCEPTION
-}
-
-JNIEXPORT void JNICALL Java_java_lang_reflect_Field_setDouble(
-#ifdef NATIVE_JNI
-JNIEnv *env,
-#endif
-JavaObjectField* Field, JavaObject* obj, jdouble val) {
-
- llvm_gcroot(Field, 0);
- llvm_gcroot(obj, 0);
-
- BEGIN_NATIVE_EXCEPTION(0)
-
- UserClass* cl = JavaObjectField::getClass(Field);
- Jnjvm* vm = cl->classLoader->vm;
- JavaField* field = JavaObjectField::getInternalField(Field);
- bool stat = isStatic(field->access);
-
- if (stat) {
- cl->initialiseClass();
- } else {
- verifyNull(obj);
- }
-
- const Typedef* type = field->getSignature();
- if (type->isPrimitive()) {
- const PrimitiveTypedef* prim = (const PrimitiveTypedef*)type;
- if (prim->isDouble()) {
- if (stat) {
- field->setStaticDoubleField((double)val);
- } else {
- field->setInstanceDoubleField(obj, (double)val);
- }
- } else {
- vm->illegalArgumentException("wrong type");
- }
- } else {
- vm->illegalArgumentException("wrong type");
- }
-
- END_NATIVE_EXCEPTION
-}
-
-// Never throws.
-JNIEXPORT jlong JNICALL Java_sun_misc_Unsafe_objectFieldOffset(
-#ifdef NATIVE_JNI
-JNIEnv *env,
-#endif
-JavaObject* Unsafe, JavaObjectField* Field) {
-
- llvm_gcroot(Field, 0);
- llvm_gcroot(Unsafe, 0);
-
- JavaField* field = JavaObjectField::getInternalField(Field);
- return (jlong)field->ptrOffset;
-}
-
-}
diff --git a/vmkit/lib/J3/Classpath/ClasspathMethod.inc b/vmkit/lib/J3/Classpath/ClasspathMethod.inc
deleted file mode 100644
index e5fc55b..0000000
--- a/vmkit/lib/J3/Classpath/ClasspathMethod.inc
+++ /dev/null
@@ -1,313 +0,0 @@
-//===- ClasspathMethod.cpp ------------------------------------------------===//
-//===------------- GNU classpath java/lang/reflect/Method -----------------===//
-//
-// The VMKit project
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#include "types.h"
-
-#include "Classpath.h"
-#include "ClasspathReflect.h"
-#include "JavaArray.h"
-#include "JavaClass.h"
-#include "JavaObject.h"
-#include "JavaTypes.h"
-#include "JavaThread.h"
-#include "JavaUpcalls.h"
-#include "Jnjvm.h"
-#include "JnjvmClassLoader.h"
-
-using namespace j3;
-
-extern "C" {
-
-JNIEXPORT jint JNICALL Java_java_lang_reflect_Method_getModifiersInternal(
-#ifdef NATIVE_JNI
-JNIEnv *env,
-#endif
-JavaObjectMethod* Meth) {
-
- jint res = 0;
- llvm_gcroot(Meth, 0);
-
- BEGIN_NATIVE_EXCEPTION(0)
-
- JavaMethod* meth = JavaObjectMethod::getInternalMethod(Meth);
- res = meth->access;
-
- END_NATIVE_EXCEPTION
-
- return res;
-}
-
-JNIEXPORT JavaObject* JNICALL Java_java_lang_reflect_Method_getReturnType(
-#ifdef NATIVE_JNI
-JNIEnv *env,
-#endif
-JavaObjectMethod* Meth) {
-
- JavaObject* res = 0;
- llvm_gcroot(Meth, 0);
- llvm_gcroot(res, 0);
-
- BEGIN_NATIVE_EXCEPTION(0)
-
- UserClass* cl = JavaObjectMethod::getClass(Meth);
- JavaMethod* meth = JavaObjectMethod::getInternalMethod(Meth);
- JnjvmClassLoader* loader = cl->classLoader;
- res = meth->getReturnType(loader);
-
- END_NATIVE_EXCEPTION
-
- return res;
-}
-
-
-JNIEXPORT JavaObject* JNICALL Java_java_lang_reflect_Method_getParameterTypes(
-#ifdef NATIVE_JNI
-JNIEnv *env,
-#endif
-JavaObjectMethod* Meth) {
-
- JavaObject* res = 0;
- llvm_gcroot(Meth, 0);
- llvm_gcroot(res, 0);
-
- BEGIN_NATIVE_EXCEPTION(0)
-
- UserClass* cl = JavaObjectMethod::getClass(Meth);
- JavaMethod* meth = JavaObjectMethod::getInternalMethod(Meth);
- JnjvmClassLoader* loader = cl->classLoader;
-
- res = meth->getParameterTypes(loader);
-
- END_NATIVE_EXCEPTION
-
- return res;
-}
-
-JavaObject* proceedMethod(JavaObjectMethod* Meth, JavaObject* obj,
- ArrayObject* args, JavaObject* Cl, jint index)
- __attribute__((noinline));
-
-JavaObject* proceedMethod(JavaObjectMethod* Meth, JavaObject* obj,
- ArrayObject* args, JavaObject* Cl, jint index) {
-
- JavaObject* res = 0;
- JavaObject* jexc = 0;
- mvm::gc* exc = 0;
-
- llvm_gcroot(res, 0);
- llvm_gcroot(Meth, 0);
- llvm_gcroot(obj, 0);
- llvm_gcroot(args, 0);
- llvm_gcroot(Cl, 0);
- llvm_gcroot(exc, 0);
- llvm_gcroot(jexc, 0);
-
- Jnjvm* vm = JavaThread::get()->getJVM();
-
- JavaMethod* meth = JavaObjectMethod::getInternalMethod(Meth);
-
- sint32 nbArgs = args ? ArrayObject::getSize(args) : 0;
- Signdef* sign = meth->getSignature();
- sint32 size = sign->nbArguments;
-
- mvm::ThreadAllocator allocator;
- jvalue* buf = size ?
- (jvalue*)allocator.Allocate(size * sizeof(jvalue)) : NULL;
-
- if (nbArgs == size) {
- UserCommonClass* _cl = UserCommonClass::resolvedImplClass(Cl, false);
- UserClass* cl = (UserClass*)_cl;
-
- if (isVirtual(meth->access)) {
- verifyNull(obj);
- UserCommonClass* objCl = JavaObject::getClass(obj);
- if (!(objCl->isAssignableFrom(cl))) {
- vm->illegalArgumentException("<this> is not a valid type");
- }
-
- if (isInterface(cl->access)) {
- cl->initialiseClass();
- UserClass* methodCl = 0;
- UserClass* lookup = objCl->isArray() ? objCl->super : objCl->asClass();
- meth = lookup->lookupMethod(meth->name, meth->type, false, true,
- &methodCl);
- }
- } else {
- cl->initialiseClass();
- }
-
- JavaObject** ptr = ArrayObject::getElements(args);
- Typedef* const* arguments = sign->getArgumentsType();
- for (sint32 i = 0; i < size; ++i) {
- JavaObject::decapsulePrimitive(ptr[i], &buf[i], arguments[i]);
- if (!arguments[i]->isPrimitive()) {
- buf[i].l = reinterpret_cast<jobject>(&ptr[i]);
- }
- }
-
-
-#define RUN_METH(TYPE, VAR) \
- TRY { \
- if (isVirtual(meth->access)) { \
- if (isPublic(meth->access) && !isFinal(meth->access) && \
- !isFinal(meth->classDef->access)) { \
- VAR = meth->invoke##TYPE##VirtualBuf(cl, obj, buf); \
- } else { \
- VAR = meth->invoke##TYPE##SpecialBuf(cl, obj, buf); \
- } \
- } else { \
- VAR = meth->invoke##TYPE##StaticBuf(cl, buf); \
- } \
- } CATCH { \
- exc = mvm::Thread::get()->getPendingException(); \
- } END_CATCH; \
- \
- if (exc) { \
- mvm::Thread* mut = mvm::Thread::get(); \
- jexc = Jnjvm::asJavaException(exc); \
- if (jexc && JavaObject::getClass(jexc)->isAssignableFrom( \
- vm->upcalls->newException)) { \
- mut->clearPendingException(); \
- JavaThread::j3Thread(mut)->getJVM()->invocationTargetException(jexc); \
- } else { \
- mut->throwIt(); \
- } \
- return NULL; \
- }
-
- Typedef* retType = sign->getReturnType();
- if (retType->isPrimitive()) {
- PrimitiveTypedef* prim = (PrimitiveTypedef*)retType;
- if (prim->isVoid()) {
- res = 0;
- uint32 val = 0;
- RUN_METH(Int, val);
- } else if (prim->isBool()) {
- uint32 val = 0;
- RUN_METH(Int, val);
- res = vm->upcalls->boolClass->doNew();
- vm->upcalls->boolValue->setInstanceInt8Field(res, val);
- } else if (prim->isByte()) {
- uint32 val = 0;
- RUN_METH(Int, val);
- res = vm->upcalls->byteClass->doNew();
- vm->upcalls->byteValue->setInstanceInt8Field(res, val);
- } else if (prim->isChar()) {
- uint32 val = 0;
- RUN_METH(Int, val);
- res = vm->upcalls->charClass->doNew();
- vm->upcalls->charValue->setInstanceInt16Field(res, val);
- } else if (prim->isShort()) {
- uint32 val = 0;
- RUN_METH(Int, val);
- res = vm->upcalls->shortClass->doNew();
- vm->upcalls->shortValue->setInstanceInt16Field(res, val);
- } else if (prim->isInt()) {
- uint32 val = 0;
- RUN_METH(Int, val);
- res = vm->upcalls->intClass->doNew();
- vm->upcalls->intValue->setInstanceInt32Field(res, val);
- } else if (prim->isLong()) {
- sint64 val = 0;
- RUN_METH(Long, val);
- res = vm->upcalls->longClass->doNew();
- vm->upcalls->longValue->setInstanceLongField(res, val);
- } else if (prim->isFloat()) {
- float val = 0;
- RUN_METH(Float, val);
- res = vm->upcalls->floatClass->doNew();
- vm->upcalls->floatValue->setInstanceFloatField(res, val);
- } else if (prim->isDouble()) {
- double val = 0;
- RUN_METH(Double, val);
- res = vm->upcalls->doubleClass->doNew();
- vm->upcalls->doubleValue->setInstanceDoubleField(res, val);
- }
- } else {
- RUN_METH(JavaObject, res);
- }
- } else {
- vm->illegalArgumentException("wrong number of arguments");
- return NULL;
- }
-
- return res;
-}
-
-#undef RUN_METH
-
-JNIEXPORT JavaObject* JNICALL Java_java_lang_reflect_Method_invokeNative(
-#ifdef NATIVE_JNI
-JNIEnv *env,
-#endif
-JavaObjectMethod* Meth, JavaObject* obj, ArrayObject* args, JavaObject* Cl, jint index) {
-
- JavaObject* res = 0;
- llvm_gcroot(res, 0);
- llvm_gcroot(Meth, 0);
- llvm_gcroot(obj, 0);
- llvm_gcroot(args, 0);
- llvm_gcroot(Cl, 0);
-
- BEGIN_NATIVE_EXCEPTION(0)
-
- res = proceedMethod(Meth, obj, args, Cl, index);
-
- END_NATIVE_EXCEPTION
-
- return res;
-}
-
-JNIEXPORT ArrayObject* JNICALL Java_java_lang_reflect_Method_getExceptionTypes(
-#ifdef NATIVE_JNI
-JNIEnv *env,
-#endif
-JavaObjectMethod* Meth) {
-
- ArrayObject* res = 0;
- llvm_gcroot(Meth, 0);
- llvm_gcroot(res, 0);
-
- BEGIN_NATIVE_EXCEPTION(0)
-
- verifyNull(Meth);
- UserClass* cl = JavaObjectMethod::getClass(Meth);
- JavaMethod* meth = JavaObjectMethod::getInternalMethod(Meth);
- JnjvmClassLoader* loader = cl->classLoader;
- res = meth->getExceptionTypes(loader);
-
- END_NATIVE_EXCEPTION
-
- return res;
-}
-
-JNIEXPORT JavaObject* JNICALL Java_java_lang_reflect_Method_getSignature(
-#ifdef NATIVE_JNI
-JNIEnv *env,
-#endif
-JavaObjectMethod* Meth) {
-
- JavaObject* result = 0;
- llvm_gcroot(Meth, 0);
- llvm_gcroot(result, 0);
-
- BEGIN_NATIVE_EXCEPTION(0)
-
- verifyNull(Meth);
- JavaMethod* meth = JavaObjectMethod::getInternalMethod(Meth);
- Jnjvm* vm = JavaThread::get()->getJVM();
- result = vm->internalUTF8ToStr(meth->type);
-
- END_NATIVE_EXCEPTION
-
- return result;
-}
-
-}
diff --git a/vmkit/lib/J3/Classpath/ClasspathReflect.h b/vmkit/lib/J3/Classpath/ClasspathReflect.h
deleted file mode 100644
index c8537b1..0000000
--- a/vmkit/lib/J3/Classpath/ClasspathReflect.h
+++ /dev/null
@@ -1,222 +0,0 @@
-//===-- ClasspathReflect.h - Internal representation of core system classes --//
-//
-// The VMKit project
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#ifndef JNJVM_CLASSPATH_REFLECT_H
-#define JNJVM_CLASSPATH_REFLECT_H
-
-#include "mvm/GC.h"
-
-#include "JavaClass.h"
-#include "JavaObject.h"
-#include <JavaThread.h>
-
-extern "C" j3::JavaObject* internalFillInStackTrace(j3::JavaObject*);
-
-namespace j3 {
-
-class JavaObjectClass : public JavaObject {
-private:
- JavaObject* signers;
- JavaObject* pd;
- UserCommonClass* vmdata;
- JavaObject* constructor;
-
-public:
-
- static UserCommonClass* getClass(JavaObjectClass* cl) {
- llvm_gcroot(cl, 0);
- return cl->vmdata;
- }
-
- static void setClass(JavaObjectClass* cl, UserCommonClass* vmdata) {
- llvm_gcroot(cl, 0);
- cl->vmdata = vmdata;
- }
-
- static void setProtectionDomain(JavaObjectClass* cl, JavaObject* pd) {
- llvm_gcroot(cl, 0);
- llvm_gcroot(pd, 0);
- cl->pd = pd;
- }
-
- static JavaObject* getProtectionDomain(JavaObjectClass* cl) {
- llvm_gcroot(cl, 0);
- return cl->pd;
- }
-
- static void staticTracer(JavaObjectClass* obj, uintptr_t closure) {
- mvm::Collector::markAndTrace(obj, &obj->pd, closure);
- mvm::Collector::markAndTrace(obj, &obj->signers, closure);
- mvm::Collector::markAndTrace(obj, &obj->constructor, closure);
- if (obj->vmdata) {
- JavaObject** Obj = obj->vmdata->classLoader->getJavaClassLoaderPtr();
- if (*Obj) mvm::Collector::markAndTraceRoot(Obj, closure);
- }
- }
-};
-
-class JavaObjectField : public JavaObject {
-private:
- uint8 flag;
- JavaObjectClass* declaringClass;
- JavaObject* name;
- uint32 slot;
-
-public:
-
- static void staticTracer(JavaObjectField* obj, uintptr_t closure) {
- mvm::Collector::markAndTrace(obj, &obj->name, closure);
- mvm::Collector::markAndTrace(obj, &obj->declaringClass, closure);
- }
-
- static JavaField* getInternalField(JavaObjectField* self) {
- llvm_gcroot(self, 0);
- UserCommonClass* cls = JavaObjectClass::getClass(self->declaringClass);
- return &(cls->asClass()->virtualFields[self->slot]);
- }
-
- static UserClass* getClass(JavaObjectField* self) {
- llvm_gcroot(self, 0);
- UserCommonClass* cls = JavaObjectClass::getClass(self->declaringClass);
- return cls->asClass();
- }
-
-};
-
-class JavaObjectMethod : public JavaObject {
-private:
- uint8 flag;
- JavaObjectClass* declaringClass;
- JavaObject* name;
- uint32 slot;
-
-public:
-
- static void staticTracer(JavaObjectMethod* obj, uintptr_t closure) {
- mvm::Collector::markAndTrace(obj, &obj->name, closure);
- mvm::Collector::markAndTrace(obj, &obj->declaringClass, closure);
- }
-
- static JavaMethod* getInternalMethod(JavaObjectMethod* self) {
- llvm_gcroot(self, 0);
- UserCommonClass* cls = JavaObjectClass::getClass(self->declaringClass);
- return &(cls->asClass()->virtualMethods[self->slot]);
- }
-
- static UserClass* getClass(JavaObjectMethod* self) {
- llvm_gcroot(self, 0);
- UserCommonClass* cls = JavaObjectClass::getClass(self->declaringClass);
- return cls->asClass();
- }
-
-};
-
-class JavaObjectConstructor : public JavaObject {
-private:
- uint8 flag;
- JavaObjectClass* declaringClass;
- uint32 slot;
-
-public:
- static void staticTracer(JavaObjectConstructor* obj, uintptr_t closure) {
- mvm::Collector::markAndTrace(obj, &obj->declaringClass, closure);
- }
-
- static JavaMethod* getInternalMethod(JavaObjectConstructor* self) {
- llvm_gcroot(self, 0);
- UserCommonClass* cls = JavaObjectClass::getClass(self->declaringClass);
- return &(cls->asClass()->virtualMethods[self->slot]);
- }
-
- static UserClass* getClass(JavaObjectConstructor* self) {
- llvm_gcroot(self, 0);
- UserCommonClass* cls = JavaObjectClass::getClass(self->declaringClass);
- return cls->asClass();
- }
-
-};
-
-class JavaObjectVMThread : public JavaObject {
-private:
- JavaObject* thread;
- bool running;
- JavaThread* vmdata;
-
-public:
- static void staticDestructor(JavaObjectVMThread* obj) {
- llvm_gcroot(obj, 0);
- delete obj->vmdata->mut;
- }
-
- static void staticTracer(JavaObjectVMThread* obj, uintptr_t closure) {
- mvm::Collector::markAndTrace(obj, &obj->thread, closure);
- }
-
- static void setVmdata(JavaObjectVMThread* vmthread,
- JavaThread* internal_thread) {
- llvm_gcroot(vmthread, 0);
- vmthread->vmdata = internal_thread;
- }
-
-};
-
-
-class JavaObjectThrowable : public JavaObject {
-private:
- JavaObject* detailedMessage;
- JavaObject* cause;
- JavaObject* stackTrace;
- JavaObject* vmState;
-
-public:
-
- static void setDetailedMessage(JavaObjectThrowable* self, JavaObject* obj) {
- llvm_gcroot(self, 0);
- llvm_gcroot(obj, 0);
- self->detailedMessage = obj;
- }
-
- static void fillInStackTrace(JavaObjectThrowable* self) {
- llvm_gcroot(self, 0);
- self->cause = self;
- self->vmState = internalFillInStackTrace(self);
- self->stackTrace = NULL;
- }
-};
-
-class JavaObjectReference : public JavaObject {
-private:
- JavaObject* referent;
- JavaObject* queue;
- JavaObject* nextOnQueue;
-
-public:
- static void init(JavaObjectReference* self, JavaObject* r, JavaObject* q) {
- llvm_gcroot(self, 0);
- llvm_gcroot(r, 0);
- llvm_gcroot(q, 0);
- self->referent = r;
- self->queue = q;
- }
-
- static JavaObject** getReferentPtr(JavaObjectReference* self) {
- llvm_gcroot(self, 0);
- return &(self->referent);
- }
-
- static void setReferent(JavaObjectReference* self, JavaObject* r) {
- llvm_gcroot(self, 0);
- llvm_gcroot(r, 0);
- self->referent = r;
- }
-};
-
-}
-
-#endif
diff --git a/vmkit/lib/J3/Classpath/ClasspathVMClass.inc b/vmkit/lib/J3/Classpath/ClasspathVMClass.inc
deleted file mode 100644
index 834c6b4..0000000
--- a/vmkit/lib/J3/Classpath/ClasspathVMClass.inc
+++ /dev/null
@@ -1,625 +0,0 @@
-//===---- ClasspathVMClass.cpp - GNU classpath java/lang/VMClass ----------===//
-//
-// The VMKit project
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#include "types.h"
-
-#include "Classpath.h"
-#include "ClasspathReflect.h"
-#include "JavaAccess.h"
-#include "JavaArray.h"
-#include "JavaClass.h"
-#include "JavaObject.h"
-#include "JavaString.h"
-#include "JavaTypes.h"
-#include "JavaThread.h"
-#include "JavaUpcalls.h"
-#include "Jnjvm.h"
-
-using namespace j3;
-
-extern "C" {
-
-// Never throws
-JNIEXPORT jboolean JNICALL Java_java_lang_VMClass_isArray(
-#ifdef NATIVE_JNI
-JNIEnv *env,
-jclass clazz,
-#endif
-JavaObjectClass* klass) {
-
- llvm_gcroot(klass, 0);
-
- UserCommonClass* cl = JavaObjectClass::getClass(klass);
-
- return cl->isArray();
-
-}
-
-JNIEXPORT JavaObject* JNICALL Java_java_lang_VMClass_forName(
-#ifdef NATIVE_JNI
-JNIEnv *env,
-jclass clazz,
-#endif
-JavaString* str,
-jboolean clinit,
-JavaObject* loader) {
-
- JavaObject* res = 0;
- llvm_gcroot(loader, 0);
- llvm_gcroot(str, 0);
- llvm_gcroot(res, 0);
-
- BEGIN_NATIVE_EXCEPTION(0)
-
- verifyNull(str);
- Jnjvm* vm = JavaThread::get()->getJVM();
- JnjvmClassLoader* JCL =
- JnjvmClassLoader::getJnjvmLoaderFromJavaObject(loader, vm);
- UserCommonClass* cl = JCL->loadClassFromJavaString(str, true, false);
-
- if (cl != 0) {
- if (clinit && cl->asClass()) {
- cl->asClass()->initialiseClass();
- }
- res = cl->getClassDelegatee();
- } else {
- vm->classNotFoundException(str);
- }
-
- END_NATIVE_EXCEPTION
-
- return res;
-}
-
-JNIEXPORT JavaObject* JNICALL Java_java_lang_VMClass_getDeclaredConstructors(
-#ifdef NATIVE_JNI
-JNIEnv *env,
-jclass clazz,
-#endif
-JavaObject* Cl,
-jboolean publicOnly) {
-
- ArrayObject* ret = 0;
- JavaObject* tmp = 0;
- llvm_gcroot(Cl, 0);
- llvm_gcroot(ret, 0);
- llvm_gcroot(tmp, 0);
-
- BEGIN_NATIVE_EXCEPTION(0)
-
- Jnjvm* vm = JavaThread::get()->getJVM();
- UserCommonClass* cl = UserCommonClass::resolvedImplClass(Cl, false);
-
- if (cl->isArray() || cl->isInterface() || cl->isPrimitive()) {
- ret = (ArrayObject*)vm->upcalls->constructorArrayClass->doNew(0);
- } else {
- UserClass* realCl = cl->asClass();;
- uint32 size = 0;
-
- for (uint32 i = 0; i < realCl->nbVirtualMethods; ++i) {
- JavaMethod* meth = &realCl->virtualMethods[i];
- bool pub = isPublic(meth->access);
- if (meth->name->equals(vm->upcalls->initName) &&
- (!publicOnly || pub)) {
- ++size;
- }
- }
-
- ret = (ArrayObject*)vm->upcalls->constructorArrayClass->doNew(size);
-
- sint32 index = 0;
- for (uint32 i = 0; i < realCl->nbVirtualMethods; ++i) {
- JavaMethod* meth = &realCl->virtualMethods[i];
- bool pub = isPublic(meth->access);
- if (meth->name->equals(vm->upcalls->initName) &&
- (!publicOnly || pub)) {
- UserClass* Cons = vm->upcalls->newConstructor;
- tmp = Cons->doNew();
- vm->upcalls->initConstructor->invokeIntSpecial(Cons, tmp, &Cl, i);
- ArrayObject::setElement(ret, tmp, index);
- index++;
- }
- }
- }
-
- END_NATIVE_EXCEPTION
-
- return ret;
-}
-
-JNIEXPORT JavaObject* JNICALL Java_java_lang_VMClass_getDeclaredMethods(
-#ifdef NATIVE_JNI
-JNIEnv *env,
-jclass clazz,
-#endif
-JavaObject* Cl,
-jboolean publicOnly) {
-
- ArrayObject* ret = 0;
- JavaObject* tmp = 0;
- JavaString* str = 0;
- llvm_gcroot(Cl, 0);
- llvm_gcroot(ret, 0);
- llvm_gcroot(tmp, 0);
- llvm_gcroot(str, 0);
-
- BEGIN_NATIVE_EXCEPTION(0)
-
- Jnjvm* vm = JavaThread::get()->getJVM();
- UserCommonClass* cl = UserCommonClass::resolvedImplClass(Cl, false);
- Classpath* upcalls = vm->upcalls;
-
- if (cl->isArray() || cl->isPrimitive()) {
- ret = (ArrayObject*)upcalls->methodArrayClass->doNew(0);
- } else {
- UserClass* realCl = cl->asClass();
- uint32 size = 0;
-
- for (uint32 i = 0; i < realCl->nbVirtualMethods + realCl->nbStaticMethods;
- ++i) {
- JavaMethod* meth = &realCl->virtualMethods[i];
- bool pub = isPublic(meth->access);
- if (!(meth->name->equals(vm->upcalls->initName)) &&
- (!publicOnly || pub)) {
- ++size;
- }
- }
-
-
- ret = (ArrayObject*)upcalls->methodArrayClass->doNew(size);
-
- sint32 index = 0;
- for (uint32 i = 0; i < realCl->nbVirtualMethods + realCl->nbStaticMethods;
- ++i) {
- JavaMethod* meth = &realCl->virtualMethods[i];
- bool pub = isPublic(meth->access);
- if (!(meth->name->equals(vm->upcalls->initName)) &&
- (!publicOnly || pub)) {
- // TODO: check parameter types
- UserClass* Meth = vm->upcalls->newMethod;
- tmp = Meth->doNew();
- str = vm->internalUTF8ToStr(meth->name);
- upcalls->initMethod->invokeIntSpecial(Meth, tmp, &Cl, &str, i);
- ArrayObject::setElement(ret, tmp, index);
- index++;
- }
- }
- }
-
- END_NATIVE_EXCEPTION
-
- return ret;
-}
-
-JNIEXPORT jint JNICALL Java_java_lang_VMClass_getModifiers(
-#ifdef NATIVE_JNI
-JNIEnv *env,
-jclass clazz,
-#endif
-JavaObject* Cl,
-jboolean ignore) {
-
- jint res = 0;
- llvm_gcroot(Cl, 0);
-
- BEGIN_NATIVE_EXCEPTION(0)
-
- UserCommonClass* cl = UserCommonClass::resolvedImplClass(Cl, false);
- res = cl->getAccess();
-
- END_NATIVE_EXCEPTION
- return res;
-}
-
-JNIEXPORT JavaObject* JNICALL Java_java_lang_VMClass_getName(
-#ifdef NATIVE_JNI
-JNIEnv *env,
-jclass clazz,
-#endif
-JavaObject* Cl) {
-
- JavaObject* result = 0;
- llvm_gcroot(Cl, 0);
- llvm_gcroot(result, 0);
-
- BEGIN_NATIVE_EXCEPTION(0)
-
- Jnjvm* vm = JavaThread::get()->getJVM();
- UserCommonClass* cl = UserCommonClass::resolvedImplClass(Cl, false);
-
- const UTF8* iname = cl->getName();
- result = JavaString::internalToJava(iname, vm);
-
- END_NATIVE_EXCEPTION
-
- return result;
-}
-
-JNIEXPORT jboolean JNICALL Java_java_lang_VMClass_isPrimitive(
-#ifdef NATIVE_JNI
-JNIEnv *env,
-jclass clazz,
-#endif
-JavaObject* Cl) {
-
- jboolean res = 0;
- llvm_gcroot(Cl, 0);
-
- BEGIN_NATIVE_EXCEPTION(0)
-
- UserCommonClass* cl = UserCommonClass::resolvedImplClass(Cl, false);
-
- res = cl->isPrimitive();
-
- END_NATIVE_EXCEPTION
-
- return res;
-}
-
-JNIEXPORT jboolean JNICALL Java_java_lang_VMClass_isInterface(
-#ifdef NATIVE_JNI
-JNIEnv *env,
-jclass clazz,
-#endif
-JavaObject* Cl) {
-
- jboolean res = 0;
- llvm_gcroot(Cl, 0);
-
- BEGIN_NATIVE_EXCEPTION(0)
-
- UserCommonClass* cl = UserCommonClass::resolvedImplClass(Cl, false);
-
- res = cl->isInterface();
-
- END_NATIVE_EXCEPTION
-
- return res;
-}
-
-JNIEXPORT JavaObject* JNICALL Java_java_lang_VMClass_getComponentType(
-#ifdef NATIVE_JNI
-JNIEnv *env,
-jclass clazz,
-#endif
-JavaObject* Cl) {
-
- JavaObject* res = 0;
- llvm_gcroot(res, 0);
- llvm_gcroot(Cl, 0);
-
-
- BEGIN_NATIVE_EXCEPTION(0)
-
- UserCommonClass* cl = UserCommonClass::resolvedImplClass(Cl, false);
-
- if (cl->isArray()) {
- UserCommonClass* bc = cl->asArrayClass()->baseClass();
- res = bc->getClassDelegatee();
- } else {
- res = 0;
- }
-
- END_NATIVE_EXCEPTION
- return res;
-}
-
-JNIEXPORT JavaObject* JNICALL Java_java_lang_VMClass_getClassLoader(
-#ifdef NATIVE_JNI
-JNIEnv *env,
-jclass clazz,
-#endif
-JavaObject* Cl) {
-
- JavaObject* res = 0;
- llvm_gcroot(res, 0);
- llvm_gcroot(Cl, 0);
-
- BEGIN_NATIVE_EXCEPTION(0)
-
- UserCommonClass* cl = UserCommonClass::resolvedImplClass(Cl, false);
- res = cl->classLoader->getJavaClassLoader();
-
- END_NATIVE_EXCEPTION
-
- return res;
-}
-
-JNIEXPORT jboolean JNICALL Java_java_lang_VMClass_isAssignableFrom(
-#ifdef NATIVE_JNI
-JNIEnv *env,
-jclass clazz,
-#endif
-JavaObject* Cl1, JavaObject* Cl2) {
-
- jboolean res = 0;
- llvm_gcroot(Cl1, 0);
- llvm_gcroot(Cl2, 0);
-
- BEGIN_NATIVE_EXCEPTION(0)
-
- Jnjvm* vm = JavaThread::get()->getJVM();
- if (!Cl2) vm->nullPointerException();
-
- UserCommonClass* cl1 = UserCommonClass::resolvedImplClass(Cl1, false);
- UserCommonClass* cl2 = UserCommonClass::resolvedImplClass(Cl2, false);
-
- res = cl2->isAssignableFrom(cl1);
-
- END_NATIVE_EXCEPTION
-
- return res;
-
-}
-
-JNIEXPORT JavaObject* JNICALL Java_java_lang_VMClass_getSuperclass(
-#ifdef NATIVE_JNI
-JNIEnv *env,
-jclass clazz,
-#endif
-JavaObject* Cl) {
-
- JavaObject* res = 0;
- llvm_gcroot(Cl, 0);
- llvm_gcroot(res, 0);
-
- BEGIN_NATIVE_EXCEPTION(0)
-
- UserCommonClass* cl = UserCommonClass::resolvedImplClass(Cl, false);
- if (cl->isInterface()) res = 0;
- else {
- if (cl->getSuper()) res = cl->getSuper()->getClassDelegatee();
- else res = 0;
- }
-
- END_NATIVE_EXCEPTION
-
- return res;
-}
-
-JNIEXPORT bool JNICALL Java_java_lang_VMClass_isInstance(
-#ifdef NATIVE_JNI
-JNIEnv *env,
-jclass clazz,
-#endif
-JavaObject* Cl, JavaObject* obj) {
-
- bool res = false;
- llvm_gcroot(Cl, 0);
- llvm_gcroot(obj, 0);
-
- BEGIN_NATIVE_EXCEPTION(0)
-
- UserCommonClass* cl = UserCommonClass::resolvedImplClass(Cl, false);
- res = JavaObject::instanceOf(obj, cl);
-
- END_NATIVE_EXCEPTION
-
- return res;
-}
-
-JNIEXPORT JavaObject* JNICALL Java_java_lang_VMClass_getDeclaredFields(
-#ifdef NATIVE_JNI
-JNIEnv *env,
-jclass clazz,
-#endif
-JavaObject* Cl, jboolean publicOnly) {
-
- ArrayObject* ret = 0;
- JavaObject* tmp = 0;
- JavaString* name = 0;
- llvm_gcroot(Cl, 0);
- llvm_gcroot(ret, 0);
- llvm_gcroot(tmp, 0);
- llvm_gcroot(name, 0);
-
- BEGIN_NATIVE_EXCEPTION(0)
-
- Jnjvm* vm = JavaThread::get()->getJVM();
- UserCommonClass* cl = UserCommonClass::resolvedImplClass(Cl, false);
-
- if (!cl->isClass()) {
- ret = (ArrayObject*)vm->upcalls->fieldArrayClass->doNew(0);
- } else {
- UserClass* realCl = cl->asClass();
- uint32 size = 0;
- for (uint32 i = 0; i < realCl->nbVirtualFields + realCl->nbStaticFields;
- ++i) {
- JavaField* field = &realCl->virtualFields[i];
- if (!publicOnly || isPublic(field->access)) {
- ++size;
- }
- }
-
-
- ret = (ArrayObject*)vm->upcalls->fieldArrayClass->doNew(size);
-
- sint32 index = 0;
- for (uint32 i = 0; i < realCl->nbVirtualFields + realCl->nbStaticFields;
- ++i) {
- JavaField* field = &realCl->virtualFields[i];
- if (!publicOnly || isPublic(field->access)) {
- // TODO: check parameter types
- UserClass* Field = vm->upcalls->newField;
- tmp = Field->doNew();
- name = vm->internalUTF8ToStr(field->name);
- vm->upcalls->initField->invokeIntSpecial(Field, tmp, &Cl, &name, i);
- ArrayObject::setElement(ret, tmp, index);
- index++;
- }
- }
- }
-
- END_NATIVE_EXCEPTION
-
- return ret;
-}
-
-JNIEXPORT JavaObject* JNICALL Java_java_lang_VMClass_getInterfaces(
-#ifdef NATIVE_JNI
-JNIEnv *env,
-jclass clazz,
-#endif
-JavaObject* Cl) {
-
- ArrayObject* res = 0;
- llvm_gcroot(res, 0);
- llvm_gcroot(Cl, 0);
-
- BEGIN_NATIVE_EXCEPTION(0)
-
- Jnjvm* vm = JavaThread::get()->getJVM();
- UserCommonClass* cl = UserCommonClass::resolvedImplClass(Cl, false);
- res = (ArrayObject*)vm->upcalls->classArrayClass->doNew(cl->nbInterfaces);
-
- for (uint16 i = 0; i < cl->nbInterfaces; ++i) {
- UserClass* klass = cl->interfaces[i];
- ArrayObject::setElement(res, klass->getClassDelegatee(), i);
- }
-
- END_NATIVE_EXCEPTION
-
- return res;
-}
-
-
-JNIEXPORT JavaObject* JNICALL Java_java_lang_VMClass_getDeclaringClass(
-#ifdef NATIVE_JNI
-JNIEnv *env,
-jclass clazz,
-#endif
-JavaObject* Cl) {
- JavaObject* res = 0;
-
- llvm_gcroot(res, 0);
- llvm_gcroot(Cl, 0);
-
- BEGIN_NATIVE_EXCEPTION(0)
-
- UserClass* cl = UserCommonClass::resolvedImplClass(Cl, false)->asClass();
-
- if (cl) {
- cl->resolveInnerOuterClasses();
- UserClass* outer = cl->getOuterClass();
- if (outer) {
- res = outer->getClassDelegatee();
- }
- }
-
- END_NATIVE_EXCEPTION
-
- return res;
-
-}
-
-JNIEXPORT JavaObject* JNICALL Java_java_lang_VMClass_getDeclaredClasses(
-#ifdef NATIVE_JNI
-JNIEnv *env,
-jclass clazz,
-#endif
-JavaObject* Cl, bool publicOnly) {
-
- ArrayObject* result = 0;
- llvm_gcroot(result, 0);
- llvm_gcroot(Cl, 0);
-
- BEGIN_NATIVE_EXCEPTION(0)
-
- Jnjvm* vm = JavaThread::get()->getJVM();
- UserClass* cl = UserCommonClass::resolvedImplClass(Cl, false)->asClass();
- if (cl) {
- cl->resolveInnerOuterClasses();
- UserClassArray* array = vm->upcalls->constructorArrayClass;
-
- uint16 sizeArray = 0;
-
- if (publicOnly) {
- for (uint16 i = 0; i < cl->nbInnerClasses; ++i) {
- UserClass* klass = cl->innerClasses[i];
- if (isPublic(klass->innerAccess)) ++sizeArray;
- }
- } else {
- sizeArray = cl->nbInnerClasses;
- }
-
- result = (ArrayObject*)array->doNew(sizeArray);
- for (uint16 i = 0; i < cl->nbInnerClasses; ++i) {
- UserClass* klass = cl->innerClasses[i];
- if (!publicOnly || isPublic(klass->innerAccess))
- ArrayObject::setElement(result, klass->getClassDelegatee(), i);
- }
- }
-
-
- END_NATIVE_EXCEPTION
-
- return result;
-
-}
-
-// Only throws.
-JNIEXPORT void JNICALL Java_java_lang_VMClass_throwException(
-#ifdef NATIVE_JNI
-JNIEnv *env,
-jclass clazz,
-#endif
-JavaObject* throwable) {
-
- llvm_gcroot(throwable, 0);
-
- assert(throwable && "Using internal VM throw exception without exception");
- mvm::Thread::get()->setPendingException(throwable);
-}
-
-JNIEXPORT ArrayObject* Java_java_lang_VMClass_getDeclaredAnnotations(
-#ifdef NATIVE_JNI
-JNIEnv *env,
-jclass clazz,
-#endif
-JavaObject* Cl) {
- // TODO implement me
-
- ArrayObject* res = 0;
- llvm_gcroot(res, 0);
- llvm_gcroot(Cl, 0);
-
- BEGIN_NATIVE_EXCEPTION(0)
-
- Jnjvm* vm = JavaThread::get()->getJVM();
- UserClassArray* array = vm->upcalls->constructorArrayAnnotation;
- res = (ArrayObject*)array->doNew(0);
-
- END_NATIVE_EXCEPTION
-
- return res;
-}
-
-JNIEXPORT jboolean Java_java_lang_VMClass_isAnonymousClass(
-#ifdef NATIVE_JNI
-JNIEnv *env,
-jclass clazz,
-#endif
-JavaObject* Cl) {
-
- jboolean res = false;
- llvm_gcroot(Cl, 0);
-
- BEGIN_NATIVE_EXCEPTION(0)
-
- UserClass* cl = UserCommonClass::resolvedImplClass(Cl, false)->asClass();
-
- if (cl) res = cl->isAnonymous;
-
- END_NATIVE_EXCEPTION
-
- return res;
-}
-
-
-}
diff --git a/vmkit/lib/J3/Classpath/ClasspathVMClassLoader.inc b/vmkit/lib/J3/Classpath/ClasspathVMClassLoader.inc
deleted file mode 100644
index 828e480..0000000
--- a/vmkit/lib/J3/Classpath/ClasspathVMClassLoader.inc
+++ /dev/null
@@ -1,376 +0,0 @@
-//===- ClasspathVMClassLoader.cpp - GNU classpath java/lang/VMClassLoader -===//
-//
-// The VMKit project
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#include "types.h"
-
-#include "Classpath.h"
-#include "JavaArray.h"
-#include "JavaClass.h"
-#include "JavaObject.h"
-#include "JavaString.h"
-#include "JavaThread.h"
-#include "JavaUpcalls.h"
-#include "Jnjvm.h"
-#include "Reader.h"
-
-using namespace j3;
-
-extern "C" {
-
-JNIEXPORT JavaObject* JNICALL Java_java_lang_VMClassLoader_getPrimitiveClass(
-#ifdef NATIVE_JNI
-JNIEnv *env,
-jclass clazz,
-#endif
-jchar byteId) {
-
- JavaObject* res = 0;
- llvm_gcroot(res, 0);
-
- BEGIN_NATIVE_EXCEPTION(0)
-
- Jnjvm* vm = JavaThread::get()->getJVM();
- UserClassPrimitive* prim =
- UserClassPrimitive::byteIdToPrimitive(byteId, vm->upcalls);
-
- if (!prim) {
- fprintf(stderr, "unknown byte primitive %c", byteId);
- abort();
- }
-
- res = prim->getClassDelegatee();
-
- END_NATIVE_EXCEPTION
-
- return res;
-
-}
-
-JNIEXPORT JavaObject* JNICALL Java_java_lang_VMClassLoader_findLoadedClass(
-#ifdef NATIVE_JNI
-JNIEnv *env,
-jclass clazz,
-#endif
-JavaObject* loader,
-JavaString* name) {
-
- JavaObject* res = 0;
- llvm_gcroot(loader, 0);
- llvm_gcroot(name, 0);
- llvm_gcroot(res, 0);
-
- BEGIN_NATIVE_EXCEPTION(0)
-
- Jnjvm* vm = JavaThread::get()->getJVM();
- JnjvmClassLoader* JCL =
- JnjvmClassLoader::getJnjvmLoaderFromJavaObject(loader, vm);
- UserCommonClass* cl = JCL->lookupClassFromJavaString(name);
-
- if (cl) res = cl->getClassDelegatee();
-
- END_NATIVE_EXCEPTION
-
- return res;
-
- return 0;
-}
-
-JNIEXPORT JavaObject* JNICALL Java_java_lang_VMClassLoader_loadClass(
-#ifdef NATIVE_JNI
-JNIEnv *env,
-jclass clazz,
-#endif
-JavaString* str,
-jboolean doResolve) {
-
- JavaObject* res = 0;
- llvm_gcroot(res, 0);
- llvm_gcroot(str, 0);
-
- BEGIN_NATIVE_EXCEPTION(0)
-
- Jnjvm* vm = JavaThread::get()->getJVM();
-
- JnjvmClassLoader* JCL = vm->bootstrapLoader;
- UserCommonClass* cl = JCL->loadClassFromJavaString(str, doResolve, false);
-
- if (cl != 0) res = cl->getClassDelegatee();
-
- END_NATIVE_EXCEPTION
-
- return res;
-}
-
-JNIEXPORT JavaObject* JNICALL Java_java_lang_VMClassLoader_defineClass(
-#ifdef NATIVE_JNI
-JNIEnv *env,
-jclass clazz,
-#endif
-JavaObject* loader,
-JavaString* str,
-ArrayUInt8* bytes,
-jint off,
-jint len,
-JavaObject* pd) {
-
- JavaObject* res = 0;
- JavaObject* excp = 0;
- llvm_gcroot(loader, 0);
- llvm_gcroot(str, 0);
- llvm_gcroot(bytes, 0);
- llvm_gcroot(pd, 0);
- llvm_gcroot(res, 0);
- llvm_gcroot(excp, 0);
-
- BEGIN_NATIVE_EXCEPTION(0)
-
- Jnjvm* vm = JavaThread::get()->getJVM();
-
- JnjvmClassLoader* JCL =
- JnjvmClassLoader::getJnjvmLoaderFromJavaObject(loader, vm);
-
- int32_t size = JavaArray::getSize(bytes);
- ClassBytes* classBytes = new (JCL->allocator, size) ClassBytes(size);
- memcpy(classBytes->elements, JavaArray::getElements(bytes), size);
-
- // Before creating a class, do a check on the bytes.
- Reader reader(classBytes);
- uint32 magic = reader.readU4();
- if (magic != Jnjvm::Magic) {
- JavaThread::get()->getJVM()->classFormatError("bad magic number");
- }
-
-
- const UTF8* name = JavaString::javaToInternal(str, JCL->hashUTF8);
- UserCommonClass* cl = JCL->lookupClass(name);
-
- if (!cl) {
- UserClass* cl = JCL->constructClass(name, classBytes);
- cl->resolveClass();
-
- res = cl->getClassDelegatee(pd);
- } else {
- excp = vm->CreateLinkageError("duplicate class definition");
- mvm::Thread::get()->setPendingException(excp)->throwIt();
- }
-
- END_NATIVE_EXCEPTION
-
- return res;
-}
-
-JNIEXPORT void JNICALL Java_java_lang_VMClassLoader_resolveClass(
-#ifdef NATIVE_JNI
-JNIEnv *env,
-jclass clazz,
-#endif
-JavaObject* Cl) {
-
- llvm_gcroot(Cl, 0);
-
- BEGIN_NATIVE_EXCEPTION(0)
-
- verifyNull(Cl);
- UserCommonClass::resolvedImplClass(Cl, false);
-
- END_NATIVE_EXCEPTION
-}
-
-#define NUM_BOOT_PACKAGES 168
-
-static const char* bootPackages[NUM_BOOT_PACKAGES] = {
- "java.applet",
- "java.awt",
- "java.awt.color",
- "java.awt.datatransfer",
- "java.awt.dnd",
- "java.awt.dnd.peer",
- "java.awt.event",
- "java.awt.font",
- "java.awt.geom",
- "java.awt.im",
- "java.awt.im.spi",
- "java.awt.image",
- "java.awt.image.renderable",
- "java.awt.peer",
- "java.awt.print",
- "java.beans",
- "java.beans.beancontext",
- "java.io",
- "java.lang",
- "java.lang.annotation",
- "java.lang.instrument",
- "java.lang.management",
- "java.lang.ref",
- "java.lang.reflect",
- "java.math",
- "java.net",
- "java.nio",
- "java.nio.channels",
- "java.nio.channels.spi",
- "java.nio.charset",
- "java.nio.charset.spi",
- "java.rmi",
- "java.rmi.activation",
- "java.rmi.dgc",
- "java.rmi.registry",
- "java.rmi.server",
- "java.security",
- "java.security.acl",
- "java.security.cert",
- "java.security.interfaces",
- "java.security.spec",
- "java.sql",
- "java.text",
- "java.util",
- "java.util.concurrent",
- "java.util.concurrent.atomic",
- "java.util.concurrent.locks",
- "java.util.jar",
- "java.util.logging",
- "java.util.prefs",
- "java.util.regex",
- "java.util.zip",
- "javax.accessibility",
- "javax.activity",
- "javax.crypto",
- "javax.crypto.interfaces",
- "javax.crypto.spec",
- "javax.imageio",
- "javax.imageio.event",
- "javax.imageio.metadata",
- "javax.imageio.plugins.bmp",
- "javax.imageio.plugins.jpeg",
- "javax.imageio.spi",
- "javax.imageio.stream",
- "javax.management",
- "javax.management.loading",
- "javax.management.modelmbean",
- "javax.management.monitor",
- "javax.management.openmbean",
- "javax.management.relation",
- "javax.management.remote",
- "javax.management.remote.rmi",
- "javax.management.timer",
- "javax.naming",
- "javax.naming.directory",
- "javax.naming.event",
- "javax.naming.ldap",
- "javax.naming.spi",
- "javax.net",
- "javax.net.ssl",
- "javax.print",
- "javax.print.attribute",
- "javax.print.attribute.standard",
- "javax.print.event",
- "javax.rmi",
- "javax.rmi.CORBA",
- "javax.rmi.ssl",
- "javax.security.auth",
- "javax.security.auth.callback",
- "javax.security.auth.kerberos",
- "javax.security.auth.login",
- "javax.security.auth.spi",
- "javax.security.auth.x500",
- "javax.security.cert",
- "javax.security.sasl",
- "javax.sound.midi",
- "javax.sound.midi.spi",
- "javax.sound.sampled",
- "javax.sound.sampled.spi",
- "javax.sql",
- "javax.sql.rowset",
- "javax.sql.rowset.serial",
- "javax.sql.rowset.spi",
- "javax.swing",
- "javax.swing.border",
- "javax.swing.colorchooser",
- "javax.swing.event",
- "javax.swing.filechooser",
- "javax.swing.plaf",
- "javax.swing.plaf.basic",
- "javax.swing.plaf.metal",
- "javax.swing.plaf.multi",
- "javax.swing.plaf.synth",
- "javax.swing.table",
- "javax.swing.text",
- "javax.swing.text.html",
- "javax.swing.text.html.parser",
- "javax.swing.text.rtf",
- "javax.swing.tree",
- "javax.swing.undo",
- "javax.transaction",
- "javax.transaction.xa",
- "javax.xml",
- "javax.xml.datatype",
- "javax.xml.namespace",
- "javax.xml.parsers",
- "javax.xml.transform",
- "javax.xml.transform.dom",
- "javax.xml.transform.sax",
- "javax.xml.transform.stream",
- "javax.xml.validation",
- "javax.xml.xpath",
- "org.ietf.jgss",
- "org.omg.CORBA",
- "org.omg.CORBA_2_3",
- "org.omg.CORBA_2_3.portable",
- "org.omg.CORBA.DynAnyPackage",
- "org.omg.CORBA.ORBPackage",
- "org.omg.CORBA.portable",
- "org.omg.CORBA.TypeCodePackage",
- "org.omg.CosNaming",
- "org.omg.CosNaming.NamingContextExtPackage",
- "org.omg.CosNaming.NamingContextPackage",
- "org.omg.Dynamic",
- "org.omg.DynamicAny",
- "org.omg.DynamicAny.DynAnyFactoryPackage",
- "org.omg.DynamicAny.DynAnyPackage",
- "org.omg.IOP",
- "org.omg.IOP.CodecFactoryPackage",
- "org.omg.IOP.CodecPackage",
- "org.omg.Messaging",
- "org.omg.PortableInterceptor",
- "org.omg.PortableInterceptor.ORBInitInfoPackage",
- "org.omg.PortableServer",
- "org.omg.PortableServer.CurrentPackage",
- "org.omg.PortableServer.POAManagerPackage",
- "org.omg.PortableServer.POAPackage",
- "org.omg.PortableServer.portable",
- "org.omg.PortableServer.ServantLocatorPackage",
- "org.omg.SendingContext",
- "org.omg.stub.java.rmi",
- "org.w3c.dom",
- "org.w3c.dom.bootstrap",
- "org.w3c.dom.events",
- "org.w3c.dom.ls",
- "org.xml.sax",
- "org.xml.sax.ext",
- "org.xml.sax.helpers"
-};
-
-extern "C" ArrayObject* Java_java_lang_VMClassLoader_getBootPackages__() {
- ArrayObject* obj = 0;
- llvm_gcroot(obj, 0);
-
- BEGIN_NATIVE_EXCEPTION(0)
-
- Jnjvm* vm = JavaThread::get()->getJVM();
- obj = (ArrayObject*)vm->upcalls->ArrayOfString->doNew(NUM_BOOT_PACKAGES);
- for (uint32 i = 0; i < NUM_BOOT_PACKAGES; ++i) {
- ArrayObject::setElement(obj, vm->asciizToStr(bootPackages[i]), i);
- }
-
- END_NATIVE_EXCEPTION
-
- return obj;
-}
-
-
-}
diff --git a/vmkit/lib/J3/Classpath/ClasspathVMObject.inc b/vmkit/lib/J3/Classpath/ClasspathVMObject.inc
deleted file mode 100644
index a943cb4..0000000
--- a/vmkit/lib/J3/Classpath/ClasspathVMObject.inc
+++ /dev/null
@@ -1,139 +0,0 @@
-//===------ ClasspathVMObject.cpp - GNU classpath java/lang/VMObject ------===//
-//
-// The VMKit project
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#include "types.h"
-
-#include "Classpath.h"
-#include "JavaArray.h"
-#include "JavaClass.h"
-#include "JavaObject.h"
-#include "JavaThread.h"
-#include "Jnjvm.h"
-
-using namespace j3;
-
-extern "C" {
-
-JNIEXPORT JavaObject* JNICALL Java_java_lang_VMObject_clone(
-#ifdef NATIVE_JNI
-JNIEnv *env,
-jclass clazz,
-#endif
-JavaObject* src) {
-
- JavaObject* res = 0;
- llvm_gcroot(res, 0);
- llvm_gcroot(src, 0);
-
- BEGIN_NATIVE_EXCEPTION(0)
-
- UserCommonClass* cl = JavaObject::getClass(src);
- size_t size = 0;
- if (cl->isArray()) {
- UserClassArray* array = cl->asArrayClass();
- UserCommonClass* base = array->baseClass();
- uint32 logSize = base->isPrimitive() ?
- base->asPrimitiveClass()->logSize : (sizeof(JavaObject*) == 8 ? 3 : 2);
-
- size = sizeof(JavaObject) + sizeof(ssize_t) +
- (JavaArray::getSize(src) << logSize);
- } else {
- assert(cl->isClass() && "Not a class!");
- size = cl->asClass()->getVirtualSize();
- }
- res = (JavaObject*)mvm::gc::operator new(size, src->getVirtualTable());
- memcpy((void*)((uintptr_t)res + 2 * sizeof(void*)),
- (void*)((uintptr_t)src + 2 * sizeof(void*)),
- size - 2 * sizeof(void*));
-
- END_NATIVE_EXCEPTION
-
- return res;
-}
-
-JNIEXPORT JavaObject* JNICALL Java_java_lang_VMObject_getClass(
-#ifdef NATIVE_JNI
-JNIEnv *env,
-jclass clazz,
-#endif
-JavaObject* obj) {
-
- JavaObject* res = 0;
- llvm_gcroot(res, 0);
- llvm_gcroot(obj, 0);
-
- BEGIN_NATIVE_EXCEPTION(0)
-
- res = JavaObject::getClass(obj)->getClassDelegatee();
-
- END_NATIVE_EXCEPTION
-
- return res;
-}
-
-JNIEXPORT void JNICALL Java_java_lang_VMObject_notifyAll(
-#ifdef NATIVE_JNI
-JNIEnv *env,
-jclass clazz,
-#endif
-JavaObject* obj) {
-
- llvm_gcroot(obj, 0);
-
- BEGIN_NATIVE_EXCEPTION(0)
-
- JavaObject::notifyAll(obj);
-
- END_NATIVE_EXCEPTION
-}
-
-
-JNIEXPORT void JNICALL Java_java_lang_VMObject_wait(
-#ifdef NATIVE_JNI
-JNIEnv *env,
-jclass clazz,
-#endif
-JavaObject* obj, jlong ms, jint ns) {
-
- llvm_gcroot(obj, 0);
-
- BEGIN_NATIVE_EXCEPTION(0)
-
- uint32 sec = (uint32) (ms / 1000);
- uint32 usec = (ns / 1000) + 1000 * (ms % 1000);
- if (ns && !usec) usec = 1;
- if (sec || usec) {
- struct timeval t;
- t.tv_sec = sec;
- t.tv_usec = usec;
- JavaObject::timedWait(obj, t);
- } else {
- JavaObject::wait(obj);
- }
-
- END_NATIVE_EXCEPTION
-}
-
-JNIEXPORT void JNICALL Java_java_lang_VMObject_notify(
-#ifdef NATIVE_JNI
-JNIEnv *env,
-jclass clazz,
-#endif
-JavaObject* obj) {
-
- llvm_gcroot(obj, 0);
-
- BEGIN_NATIVE_EXCEPTION(0)
-
- JavaObject::notify(obj);
-
- END_NATIVE_EXCEPTION
-}
-
-}
diff --git a/vmkit/lib/J3/Classpath/ClasspathVMRuntime.inc b/vmkit/lib/J3/Classpath/ClasspathVMRuntime.inc
deleted file mode 100644
index 10749c9..0000000
--- a/vmkit/lib/J3/Classpath/ClasspathVMRuntime.inc
+++ /dev/null
@@ -1,222 +0,0 @@
-//===------ ClasspathVMRuntime.cpp - GNU classpath java/lang/VMRuntime ----===//
-//
-// The VMKit project
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-
-#include "mvm/GC.h"
-
-#include "types.h"
-
-#include "Classpath.h"
-#include "JavaArray.h"
-#include "JavaClass.h"
-#include "JavaObject.h"
-#include "JavaString.h"
-#include "JavaThread.h"
-#include "JavaUpcalls.h"
-#include "Jnjvm.h"
-
-#include <csetjmp>
-#include <cstring>
-#include <unistd.h>
-
-using namespace j3;
-
-extern "C" {
-
-
-JNIEXPORT JavaObject* JNICALL Java_java_lang_VMRuntime_mapLibraryName(
-#ifdef NATIVE_JNI
-JNIEnv *env,
-jclass clazz,
-#endif
-JavaString* strLib) {
-
- JavaObject* res = 0;
- ArrayUInt16* array = 0;
- const ArrayUInt16* utf8Lib = 0;
- llvm_gcroot(res, 0);
- llvm_gcroot(array, 0);
- llvm_gcroot(utf8Lib, 0);
- llvm_gcroot(strLib, 0);
-
- BEGIN_NATIVE_EXCEPTION(0)
-
- Jnjvm* vm = JavaThread::get()->getJVM();
-
- utf8Lib = JavaString::getValue(strLib);
- uint32 stLib = strLib->offset;
- sint32 lgLib = strLib->count;
- sint32 lgPre = vm->upcalls->prelib->size;
- sint32 lgPost = vm->upcalls->postlib->size;
-
- uint32 size = (uint32)(lgPre + lgLib + lgPost);
- array = (ArrayUInt16*)vm->upcalls->ArrayOfChar->doNew(size);
- uint16* elements = ArrayUInt16::getElements(array);
-
- memmove(elements, vm->upcalls->prelib->elements,
- lgPre * sizeof(uint16));
- memmove(&(elements[lgPre]), ArrayUInt16::getElements(utf8Lib) + stLib,
- lgLib * sizeof(uint16));
- memmove(&(elements[lgPre + lgLib]), vm->upcalls->postlib->elements,
- lgPost * sizeof(uint16));
-
- res = vm->constructString(array);
-
- END_NATIVE_EXCEPTION
-
- return res;
-
-}
-
-typedef int (*onLoad_t)(const void**, void*);
-extern "C" void j3EndJNI(uint32** old);
-extern "C" void j3StartJNI(uint32* num, uint32** old, mvm::KnownFrame* Frame);
-
-extern "C" void callOnLoad(void* res, JnjvmClassLoader* loader, Jnjvm* vm)
- __attribute__ ((noinline));
-
-// Calls the JNI_OnLoad function of a dynamic library.
-extern "C" void callOnLoad(void* res, JnjvmClassLoader* loader, Jnjvm* vm) {
-
- onLoad_t onLoad = (onLoad_t)loader->loadInLib("JNI_OnLoad", res);
-
- if (onLoad) {
- uint32 num = 0;
- uint32* old = 0;
- mvm::KnownFrame Frame;
-
- j3StartJNI(&num, &old, &Frame);
- onLoad(&vm->javavmEnv, res);
- j3EndJNI(&old);
- }
-}
-
-// Never throws.
-JNIEXPORT jint JNICALL Java_java_lang_VMRuntime_nativeLoad(
-#ifdef NATIVE_JNI
-JNIEnv *env,
-jclass clazz,
-#endif
-JavaString* str,
-JavaObject* javaLoader) {
-
-
- llvm_gcroot(str, 0);
- llvm_gcroot(javaLoader, 0);
-
- void* res = 0;
-
- BEGIN_NATIVE_EXCEPTION(0)
-
- Jnjvm* vm = JavaThread::get()->getJVM();
- JnjvmClassLoader* loader =
- JnjvmClassLoader::getJnjvmLoaderFromJavaObject(javaLoader, vm);
-
- mvm::ThreadAllocator allocator;
- char* buf = JavaString::strToAsciiz(str, &allocator);
-
- res = loader->loadLib(buf);
-
- if (res) callOnLoad(res, loader, vm);
-
- END_NATIVE_EXCEPTION
-
- return res != 0;
-}
-
-
-JNIEXPORT void JNICALL Java_java_lang_VMRuntime_gc(
-#ifdef NATIVE_JNI
-JNIEnv *env,
-jclass clazz,
-#endif
-) {
- BEGIN_NATIVE_EXCEPTION(0)
-
- mvm::Collector::collect();
-
- END_NATIVE_EXCEPTION
-}
-
-JNIEXPORT void JNICALL Java_java_lang_VMRuntime_runFinalization(
-#ifdef NATIVE_JNI
-JNIEnv *env,
-jclass clazz,
-#endif
-) {
- mvm::Collector::collect();
- // Sleep a bit.
- sleep(1);
- return;
-}
-
-JNIEXPORT void JNICALL Java_java_lang_VMRuntime_runFinalizationForExit(
-#ifdef NATIVE_JNI
-JNIEnv *env,
-jclass clazz,
-#endif
-) {
- return;
-}
-
-JNIEXPORT void JNICALL Java_java_lang_VMRuntime_runFinalizersOnExit(
-#ifdef NATIVE_JNI
-JNIEnv *env,
-jclass clazz,
-#endif
-uint8 value
-) {
- return;
-}
-
-JNIEXPORT void JNICALL Java_java_lang_VMRuntime_exit(
-#ifdef NATIVE_JNI
-JNIEnv *env,
-jclass clazz,
-#endif
-jint par1) {
- exit(par1);
-}
-
-JNIEXPORT jlong Java_java_lang_VMRuntime_freeMemory(
-#ifdef NATIVE_JNI
-JNIEnv *env,
-jclass clazz,
-#endif
-) {
- return (jlong)mvm::Collector::getFreeMemory();
-}
-
-JNIEXPORT jlong Java_java_lang_VMRuntime_totalMemory(
-#ifdef NATIVE_JNI
-JNIEnv *env,
-jclass clazz,
-#endif
-) {
- return (jlong)mvm::Collector::getTotalMemory();
-}
-
-JNIEXPORT jlong Java_java_lang_VMRuntime_maxMemory(
-#ifdef NATIVE_JNI
-JNIEnv *env,
-jclass clazz,
-#endif
-) {
- return (jlong)mvm::Collector::getMaxMemory();
-}
-
-JNIEXPORT jint Java_java_lang_VMRuntime_availableProcessors(){
-#ifdef NATIVE_JNI
-JNIEnv *env,
-jclass clazz,
-#endif
- return 1;
-}
-}
-
diff --git a/vmkit/lib/J3/Classpath/ClasspathVMStackWalker.inc b/vmkit/lib/J3/Classpath/ClasspathVMStackWalker.inc
deleted file mode 100644
index 8494f4d..0000000
--- a/vmkit/lib/J3/Classpath/ClasspathVMStackWalker.inc
+++ /dev/null
@@ -1,86 +0,0 @@
-//===- ClasspathVMStackWalker.cpp -----------------------------------------===//
-//===------------ GNU classpath gnu/classpath/VMStackWalker ---------------===//
-//
-// The VMKit project
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#include "types.h"
-
-#include "Classpath.h"
-#include "ClasspathReflect.h"
-#include "JavaArray.h"
-#include "JavaClass.h"
-#include "JavaObject.h"
-#include "JavaThread.h"
-#include "JavaUpcalls.h"
-#include "Jnjvm.h"
-
-using namespace j3;
-
-extern "C" {
-
-JNIEXPORT JavaObject* JNICALL Java_gnu_classpath_VMStackWalker_getClassContext(
-#ifdef NATIVE_JNI
-JNIEnv *env,
-jclass clazz,
-#endif
-) {
-
- ArrayObject* result = NULL;
- JavaObject* delegatee = NULL;
- llvm_gcroot(result, 0);
- llvm_gcroot(delegatee, 0);
-
- BEGIN_NATIVE_EXCEPTION(0)
-
- mvm::Thread* mut = mvm::Thread::get();
- JavaThread* th = JavaThread::j3Thread(mut);
- Jnjvm* vm = th->getJVM();
- uint32 length = mut->getFrameContextLength();
-
- mvm::ThreadAllocator allocator;
- uintptr_t* buffer = (uintptr_t*)allocator.Allocate(length * sizeof(uintptr_t));
-
- uint32 finalSize = th->getJavaFrameContext((void**)buffer);
-
- result = (ArrayObject*)
- vm->upcalls->stackTraceArray->doNew(finalSize);
-
- for (uint32 i = 0; i != finalSize; ++i) {
- JavaMethod* meth = ((JavaMethod**)buffer)[i];
- assert(meth && "Wrong stack trace");
- delegatee = meth->classDef->getClassDelegatee();;
- ArrayObject::setElement(result, delegatee, i);
- }
-
- END_NATIVE_EXCEPTION
-
- return result;
-}
-
-JNIEXPORT JavaObject* JNICALL Java_gnu_classpath_VMStackWalker_getClassLoader(
-#ifdef NATIVE_JNI
-JNIEnv *env,
-jclass clazz,
-#endif
-JavaObject* Cl) {
-
- JavaObject* res = 0;
- llvm_gcroot(res, 0);
- llvm_gcroot(Cl, 0);
-
- BEGIN_NATIVE_EXCEPTION(0)
-
- UserCommonClass* cl = UserCommonClass::resolvedImplClass(Cl, false);
- res = cl->classLoader->getJavaClassLoader();
-
- END_NATIVE_EXCEPTION
-
- return res;
-}
-
-}
diff --git a/vmkit/lib/J3/Classpath/ClasspathVMSystem.inc b/vmkit/lib/J3/Classpath/ClasspathVMSystem.inc
deleted file mode 100644
index 1441ccd..0000000
--- a/vmkit/lib/J3/Classpath/ClasspathVMSystem.inc
+++ /dev/null
@@ -1,123 +0,0 @@
-//===-- ClasspathVMSystem.cpp - GNU classpath java/lang/VMSystem ----------===//
-//
-// The VMKit project
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#include "types.h"
-
-#include "Classpath.h"
-#include "JavaArray.h"
-#include "JavaClass.h"
-#include "JavaObject.h"
-#include "JavaThread.h"
-#include "Jnjvm.h"
-
-using namespace j3;
-
-extern "C" {
-
-JNIEXPORT void JNICALL Java_java_lang_VMSystem_arraycopy(
-#ifdef NATIVE_JNI
-JNIEnv *env,
-jclass _cl,
-#endif
-JavaObject* src,
-jint sstart,
-JavaObject* dst,
-jint dstart,
-jint len) {
-
- JavaObject* cur = 0;
- llvm_gcroot(src, 0);
- llvm_gcroot(dst, 0);
- llvm_gcroot(cur, 0);
- assert(src->getVirtualTable());
- assert(dst->getVirtualTable());
-
- mvm::Thread* mut = mvm::Thread::get();
- Jnjvm *vm = JavaThread::j3Thread(mut)->getJVM();
-
- if (src == NULL || dst == NULL) {
- mut->setPendingException(vm->CreateNullPointerException());
- return;
- }
-
- if (!(JavaObject::getClass(src)->isArray() &&
- JavaObject::getClass(dst)->isArray())) {
- mut->setPendingException(vm->CreateArrayStoreException((JavaVirtualTable*)dst->getVirtualTable()));
- return;
- }
-
- UserClassArray* ts = (UserClassArray*)JavaObject::getClass(src);
- UserClassArray* td = (UserClassArray*)JavaObject::getClass(dst);
- UserCommonClass* dstType = td->baseClass();
- UserCommonClass* srcType = ts->baseClass();
-
- sint32 srcSize = JavaArray::getSize(src);
- sint32 dstSize = JavaArray::getSize(dst);
-
- if (len > srcSize) {
- mut->setPendingException(vm->CreateIndexOutOfBoundsException(len));
- } else if (len > dstSize) {
- mut->setPendingException(vm->CreateIndexOutOfBoundsException(len));
- } else if (len + sstart > srcSize) {
- mut->setPendingException(vm->CreateIndexOutOfBoundsException(len + sstart));
- } else if (len + dstart > dstSize) {
- mut->setPendingException(vm->CreateIndexOutOfBoundsException(len + dstart));
- } else if (dstart < 0) {
- mut->setPendingException(vm->CreateIndexOutOfBoundsException(dstart));
- } else if (sstart < 0) {
- mut->setPendingException(vm->CreateIndexOutOfBoundsException(sstart));
- } else if (len < 0) {
- mut->setPendingException(vm->CreateIndexOutOfBoundsException(len));
- } else if ((dstType->isPrimitive() || srcType->isPrimitive()) &&
- srcType != dstType) {
- mut->setPendingException(vm->CreateArrayStoreException((JavaVirtualTable*)dst->getVirtualTable()));
- }
- if (mut->getPendingException() != NULL) return;
-
- jint i = sstart;
- jint length = len;
- bool doThrow = false;
- if (!(dstType->isPrimitive())) {
- while (i < sstart + len && !doThrow) {
- cur = ArrayObject::getElement((ArrayObject*)src, i);
- if (cur) {
- if (!(JavaObject::getClass(cur)->isAssignableFrom(dstType))) {
- doThrow = true;
- length = i;
- }
- }
- ++i;
- }
- }
-
- uint32 logSize = dstType->isPrimitive() ?
- dstType->asPrimitiveClass()->logSize : (sizeof(JavaObject*) == 8 ? 3 : 2);
-
- void* ptrDst = (void*)((int64_t)JavaArray::getElements(dst) + (dstart << logSize));
- void* ptrSrc = (void*)((int64_t)JavaArray::getElements(src) + (sstart << logSize));
- memmove(ptrDst, ptrSrc, length << logSize);
-
- if (doThrow) {
- mut->setPendingException(vm->CreateArrayStoreException((JavaVirtualTable*)dst->getVirtualTable()));
- }
-}
-
-JNIEXPORT jint JNICALL Java_java_lang_VMSystem_identityHashCode(
-#ifdef NATIVE_JNI
-JNIEnv *env,
-jclass clazz,
-#endif
-JavaObject* obj) {
-
- llvm_gcroot(obj, 0);
- if (obj == NULL) return 0;
- return JavaObject::hashCode(obj);
-}
-
-}
diff --git a/vmkit/lib/J3/Classpath/ClasspathVMSystemProperties.inc b/vmkit/lib/J3/Classpath/ClasspathVMSystemProperties.inc
deleted file mode 100644
index 002b018..0000000
--- a/vmkit/lib/J3/Classpath/ClasspathVMSystemProperties.inc
+++ /dev/null
@@ -1,153 +0,0 @@
-//===- ClasspathVMSystem/Properties.cpp -----------------------------------===//
-//===--------------------- GNU classpath gnu/classpath/VMSystemProperties -===//
-//
-// The VMKit project
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#include <sys/utsname.h>
-
-#include "types.h"
-
-#include "Classpath.h"
-#include "JavaArray.h"
-#include "JavaClass.h"
-#include "JavaObject.h"
-#include "JavaThread.h"
-#include "JavaUpcalls.h"
-#include "Jnjvm.h"
-
-using namespace j3;
-
-extern "C" {
-
-void setProperty(Jnjvm* vm, JavaObject* prop, const char* key,
- const char* val) {
-
- JavaString* Val = 0;
- JavaString* Key = 0;
- llvm_gcroot(prop, 0);
- llvm_gcroot(Val, 0);
- llvm_gcroot(Key, 0);
-
- Val = vm->asciizToStr(val);
- Key = vm->asciizToStr(key);
-
- vm->upcalls->setProperty->invokeIntSpecial((UserClass*)JavaObject::getClass(prop), prop, &Key, &Val);
-}
-
-void setUnameProp(Jnjvm* vm, JavaObject* prop) {
-
- llvm_gcroot(prop, 0);
-
- struct utsname infos;
- uname(&infos);
- setProperty(vm, prop, "os.name", infos.sysname);
- setProperty(vm, prop, "os.arch", infos.machine);
- setProperty(vm, prop, "os.version", infos.release);
- if (!strcmp(infos.machine, "ppc")) {
- setProperty(vm, prop, "gnu.cpu.endian","big");
- } else {
- setProperty(vm, prop, "gnu.cpu.endian","little");
- }
-}
-
-JNIEXPORT void JNICALL Java_gnu_classpath_VMSystemProperties_preInit(
-#ifdef NATIVE_JNI
-JNIEnv *env,
-jclass clazz,
-#endif
-JavaObject* prop) {
-
- llvm_gcroot(prop, 0);
-
- BEGIN_NATIVE_EXCEPTION(0)
-
- Jnjvm* vm = JavaThread::get()->getJVM();
- const char* tmp;
- setProperty(vm, prop, "java.vm.specification.version", "1.0");
- setProperty(vm, prop, "java.vm.specification.vendor",
- "Sun Microsystems, Inc");
- setProperty(vm, prop, "java.vm.specification.name",
- "Java Virtual Machine Specification");
- setProperty(vm, prop, "java.specification.version", "1.5");
- setProperty(vm, prop, "java.specification.vendor", "Sun Microsystems, Inc");
- setProperty(vm, prop, "java.specification.name",
- "Java Platform API Specification");
- setProperty(vm, prop, "java.version", "1.5");
- setProperty(vm, prop, "java.runtime.version", "1.5");
- setProperty(vm, prop, "java.vendor", "The VMKit Project");
- setProperty(vm, prop, "java.vendor.url", "http://vmkit.llvm.org");
-
- tmp = getenv("JAVA_HOME");
- if (!tmp) tmp = "";
- setProperty(vm, prop, "java.home", tmp);
-
- JnjvmBootstrapLoader* JCL = vm->bootstrapLoader;
- setProperty(vm, prop, "java.class.version", "49.0");
- setProperty(vm, prop, "java.class.path", vm->classpath);
- setProperty(vm, prop, "java.boot.class.path", JCL->bootClasspathEnv);
- setProperty(vm, prop, "sun.boot.class.path", JCL->bootClasspathEnv);
- setProperty(vm, prop, "java.vm.version", "0.28");
- setProperty(vm, prop, "java.vm.vendor", "The VMKit Project");
- setProperty(vm, prop, "java.vm.name", "J3");
- setProperty(vm, prop, "java.specification.version", "1.5");
- setProperty(vm, prop, "java.io.tmpdir", "/tmp");
-
- tmp = getenv("JAVA_COMPILER");
- if (!tmp) tmp = "gcj";
- setProperty(vm, prop, "java.compiler", tmp);
-
- setProperty(vm, prop, "build.compiler", "gcj");
- setProperty(vm, prop, "gcj.class.path", JCL->bootClasspathEnv);
- setProperty(vm, prop, "gnu.classpath.boot.library.path",
- JCL->libClasspathEnv);
-
- setUnameProp(vm, prop);
-
- setProperty(vm, prop, "file.separator", vm->dirSeparator);
- setProperty(vm, prop, "path.separator", vm->envSeparator);
- setProperty(vm, prop, "line.separator", "\n");
-
- tmp = getenv("USERNAME");
- if (!tmp) tmp = getenv("LOGNAME");
- else if (!tmp) tmp = getenv("NAME");
- else if (!tmp) tmp = "";
- setProperty(vm, prop, "user.name", tmp);
-
- tmp = getenv("HOME");
- if (!tmp) tmp = "";
- setProperty(vm, prop, "user.home", tmp);
-
- tmp = getenv("PWD");
- if (!tmp) tmp = "";
- setProperty(vm, prop, "user.dir", tmp);
-
- // Disable this property. The Classpath iconv implementation is really
- // not optimized (it over-abuses JNI calls).
- //setProperty(vm, prop, "gnu.classpath.nio.charset.provider.iconv", "true");
- setProperty(vm, prop, "file.encoding", "ISO8859_1");
- setProperty(vm, prop, "gnu.java.util.zoneinfo.dir", "/usr/share/zoneinfo");
-
- END_NATIVE_EXCEPTION
-}
-
-extern "C" void Java_gnu_classpath_VMSystemProperties_postInit__Ljava_util_Properties_2(JavaObject* prop) {
-
- llvm_gcroot(prop, 0);
-
- BEGIN_NATIVE_EXCEPTION(0)
-
- Jnjvm* vm = JavaThread::get()->getJVM();
- for (std::vector<std::pair<char*, char*> >::iterator i =
- vm->postProperties.begin(), e = vm->postProperties.end(); i!= e; i++) {
- setProperty(vm, prop, i->first, i->second);
- }
-
- END_NATIVE_EXCEPTION
-}
-
-}
diff --git a/vmkit/lib/J3/Classpath/ClasspathVMThread.inc b/vmkit/lib/J3/Classpath/ClasspathVMThread.inc
deleted file mode 100644
index 5340d54..0000000
--- a/vmkit/lib/J3/Classpath/ClasspathVMThread.inc
+++ /dev/null
@@ -1,213 +0,0 @@
-//===- ClasspathVMThread.cpp - GNU classpath java/lang/VMThread -----------===//
-//
-// The VMKit project
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#include "types.h"
-
-#include "Classpath.h"
-#include "JavaArray.h"
-#include "JavaClass.h"
-#include "JavaObject.h"
-#include "JavaThread.h"
-#include "JavaUpcalls.h"
-#include "Jnjvm.h"
-
-using namespace j3;
-
-extern "C" {
-
-// Never throws.
-// Never calls Java code.
-JNIEXPORT JavaObject* JNICALL Java_java_lang_VMThread_currentThread(
-#ifdef NATIVE_JNI
-JNIEnv *env,
-jclass clazz
-#endif
-) {
- return JavaThread::get()->currentThread();
-}
-
-void start(mvm::Thread* mut) {
- JavaObjectVMThread* vmThread = NULL;
- JavaObject* javaThread = NULL;
- llvm_gcroot(vmThread, 0);
- llvm_gcroot(javaThread, 0);
-
- JavaThread* thread = JavaThread::j3Thread(mut);
- Jnjvm* vm = thread->getJVM();
- // Wait some time to let the creator initialise these fields.
- while ((thread->javaThread == NULL) || (thread->vmThread == NULL)) {
- mvm::Thread::yield();
- }
-
- // Ok, now that the thread is created we can set the the value of vmdata,
- // which is the JavaThread object.
- vmThread = (JavaObjectVMThread*)thread->vmThread;
- assert(vmThread && "Didn't fix the vmThread of a j3 thread");
- assert(vmThread->getVirtualTable());
- JavaObjectVMThread::setVmdata(vmThread, thread);
-
- UserClass* vmthClass = (UserClass*)JavaObject::getClass(vmThread);
-
- javaThread = thread->javaThread;
- assert(javaThread && "Didn't fix the javaThread of a j3 thread");
- // If the thread is not a daemon, it is added to the list of threads to
- // wait until exit.
- bool isDaemon = vm->upcalls->daemon->getInstanceInt8Field(javaThread);
-
- if (isDaemon)
- mut->setDaemon();
-
- assert(vmThread->getVirtualTable());
- assert(javaThread->getVirtualTable());
- // Run the VMThread::run function
- vm->upcalls->runVMThread->invokeIntSpecial(vmthClass, vmThread);
-}
-
-JNIEXPORT void JNICALL Java_java_lang_VMThread_start(
-#ifdef NATIVE_JNI
-JNIEnv *env,
-#endif
-JavaObject* vmThread, sint64 stackSize) {
-
- JavaObject* javaThread = 0;
- llvm_gcroot(vmThread, 0);
- llvm_gcroot(javaThread, 0);
-
- BEGIN_NATIVE_EXCEPTION(0)
-
- Jnjvm* vm = JavaThread::get()->getJVM();
-
- // Classpath has set this field.
- javaThread = vm->upcalls->assocThread->getInstanceObjectField(vmThread);
- assert(javaThread && "VMThread with no Java equivalent");
-
- JavaThread* th = JavaThread::associate(vm, new mvm::MutatorThread(vm->vmkit));
-
- if (!th) vm->outOfMemoryError();
- th->mut->start((void (*)(mvm::Thread*))start);
- // Now that the thread has been created, initialise its object fields.
-
- th->initialise(javaThread, vmThread);
-
- END_NATIVE_EXCEPTION
-}
-
-JNIEXPORT void JNICALL Java_java_lang_VMThread_interrupt(
-#ifdef NATIVE_JNI
-JNIEnv *env,
-#endif
-JavaObject* vmthread) {
-
- llvm_gcroot(vmthread, 0);
-
- BEGIN_NATIVE_EXCEPTION(0)
-
- Jnjvm* vm = JavaThread::get()->getJVM();
- JavaField* field = vm->upcalls->vmdataVMThread;
-
- // It's possible that the thread to be interrupted has not finished
- // its initialization. Wait until the initialization is done.
- while (field->getInstanceObjectField(vmthread) == 0)
- mvm::Thread::yield();
-
- JavaThread* th = (JavaThread*)field->getInstanceObjectField(vmthread);
- th->lockingThread.interruptFlag = 1;
- mvm::FatLock* lock = th->lockingThread.waitsOn;
-
- // If the thread is blocked on a wait. We also verify nextWaiting in case
- // the thread has been notified.
- if (lock && th->lockingThread.nextWaiting) {
- th->lockingThread.state = mvm::LockingThread::StateInterrupted;
-
- // Make sure the thread is waiting.
- uint32 locked = 0;
- while (true) {
- locked = (lock->tryAcquire() == 0);
- if (locked || (lock->getOwner() != th->mut && lock->getOwner() != 0))
- break;
- else mvm::Thread::yield();
- }
-
- // Interrupt the thread.
- th->lockingThread.varcond.signal();
-
- // Release the lock if we acquired it.
- if (locked) lock->release(lock->getAssociatedObject(), vm->lockSystem);
- }
-
- // Here we could also raise a signal for interrupting I/O
-
- END_NATIVE_EXCEPTION
-}
-
-// Never throws.
-// Never calls Java code.
-JNIEXPORT jboolean JNICALL Java_java_lang_VMThread_interrupted(
-#ifdef NATIVE_JNI
-JNIEnv *env,
-jclass clazz,
-#endif
-) {
- JavaThread* th = JavaThread::get();
- uint32 interrupt = th->lockingThread.interruptFlag;
- th->lockingThread.interruptFlag = 0;
- return (jboolean)interrupt;
-}
-
-// Never throws.
-// Never calls Java code.
-JNIEXPORT jboolean JNICALL Java_java_lang_VMThread_isInterrupted(
-#ifdef NATIVE_JNI
-JNIEnv *env,
-#endif
-JavaObject* vmthread) {
-
- llvm_gcroot(vmthread, 0);
-
- Jnjvm* vm = JavaThread::get()->getJVM();
- JavaField* field = vm->upcalls->vmdataVMThread;
- JavaThread* th = (JavaThread*)field->getInstanceObjectField(vmthread);
- return (jboolean)th->lockingThread.interruptFlag;
-}
-
-// Never throws.
-// Never calls Java code.
-JNIEXPORT void JNICALL Java_java_lang_VMThread_nativeSetPriority(
-#ifdef NATIVE_JNI
-JNIEnv *env,
-#endif
-JavaObject* vmthread, jint prio) {
- // Currently not implemented
- llvm_gcroot(vmthread, 0);
-}
-
-// Never throws.
-// Never calls Java code.
-JNIEXPORT void JNICALL Java_java_lang_VMThread_nativeStop(
-#ifdef NATIVE_JNI
-JNIEnv *env,
-#endif
-JavaObject* vmthread, JavaObject* exc) {
- // Currently not implemented
- llvm_gcroot(vmthread, 0);
- llvm_gcroot(exc, 0);
-}
-
-// Never throws.
-// Never calls Java code.
-JNIEXPORT void JNICALL Java_java_lang_VMThread_yield(
-#ifdef NATIVE_JNI
-JNIEnv *env,
-jclass clazz,
-#endif
-) {
- mvm::Thread::yield();
-}
-
-}
diff --git a/vmkit/lib/J3/Classpath/ClasspathVMThrowable.inc b/vmkit/lib/J3/Classpath/ClasspathVMThrowable.inc
deleted file mode 100644
index 649d42c..0000000
--- a/vmkit/lib/J3/Classpath/ClasspathVMThrowable.inc
+++ /dev/null
@@ -1,188 +0,0 @@
-//===- ClasspathVMClassLoader.cpp - GNU classpath java/lang/VMClassLoader -===//
-//
-// The VMKit project
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#include "mvm/VMKit.h"
-
-#include "types.h"
-
-#include "Classpath.h"
-#include "JavaAccess.h"
-#include "JavaArray.h"
-#include "JavaClass.h"
-#include "JavaConstantPool.h"
-#include "JavaObject.h"
-#include "JavaString.h"
-#include "JavaThread.h"
-#include "JavaUpcalls.h"
-#include "Jnjvm.h"
-#include "Reader.h"
-
-using namespace j3;
-
-extern "C" {
-
-JavaObject* internalFillInStackTrace(JavaObject* throwable) {
-
- JavaObject* vmThrowable = 0;
- ArrayPtr* result = 0;
- llvm_gcroot(throwable, 0);
- llvm_gcroot(vmThrowable, 0);
- llvm_gcroot(result, 0);
-
- mvm::Thread* mut = mvm::Thread::get();
- uint32 length = mut->getFrameContextLength();
-
- Jnjvm* vm = JavaThread::j3Thread(mut)->getJVM();
-
- if (sizeof(void*) == 4) {
- ClassArray* cl = vm->upcalls->ArrayOfInt;
- result = (ArrayPtr*) cl->doNew(length);
- } else {
- ClassArray* cl = vm->upcalls->ArrayOfLong;
- result = (ArrayPtr*) cl->doNew(length);
- }
-
- // Don't call th->getFrameContext because it is not GC-safe.
- mvm::StackWalker Walker(mut);
- uint32_t i = 0;
-
- while (void* ip = *Walker) {
- ArrayPtr::setElement(result, ip, i);
- ++i;
- ++Walker;
- }
-
- // Set the tempory data in the new VMThrowable object.
- vmThrowable = vm->upcalls->newVMThrowable->doNew();
- vm->upcalls->vmDataVMThrowable->setInstanceObjectField(vmThrowable, result);
- return vmThrowable;
-}
-
-JNIEXPORT JavaObject* JNICALL Java_java_lang_VMThrowable_fillInStackTrace(
-#ifdef NATIVE_JNI
-JNIEnv *env,
-jclass clazz,
-#endif
-JavaObject* throwable) {
-
- JavaObject* res = 0;
- llvm_gcroot(res, 0);
- llvm_gcroot(throwable, 0);
-
- BEGIN_NATIVE_EXCEPTION(0)
-
- res = internalFillInStackTrace(throwable);
-
- END_NATIVE_EXCEPTION
-
- return res;
-}
-
-
-JavaObject* consStackElement(JavaMethod* meth, void* ip) {
-
- JavaString* methodName = 0;
- JavaString* className = 0;
- JavaString* sourceName = 0;
- JavaObject* res = 0;
- llvm_gcroot(methodName, 0);
- llvm_gcroot(className, 0);
- llvm_gcroot(sourceName, 0);
- llvm_gcroot(res, 0);
-
- Jnjvm* vm = meth->classDef->classLoader->vm;
- methodName = vm->internalUTF8ToStr(meth->name);
- Class* cl = meth->classDef;
- className = JavaString::internalToJava(cl->name, vm);
-
- Attribut* sourceAtt = cl->lookupAttribut(Attribut::sourceFileAttribut);
-
- // We don't have the bytes if the class was vmjc'ed.
- if (sourceAtt && cl->getBytes()) {
- Reader reader(sourceAtt, cl->bytes);
- uint16 index = reader.readU2();
- sourceName = vm->internalUTF8ToStr(cl->getConstantPool()->UTF8At(index));
- }
-
- bool native = isNative(meth->access);
- uint16 lineNumber = meth->lookupLineNumber(reinterpret_cast<uintptr_t>(ip));
-
- UserClass* newS = vm->upcalls->newStackTraceElement;
- res = newS->doNew();
- vm->upcalls->initStackTraceElement->invokeIntSpecial(newS, res,
- &sourceName,
- lineNumber,
- &className,
- &methodName, native);
- return res;
-}
-
-JNIEXPORT JavaObject* JNICALL Java_java_lang_VMThrowable_getStackTrace(
-#ifdef NATIVE_JNI
-JNIEnv *env,
-#endif
-JavaObject* vmthrow, JavaObject* throwable) {
-
- ArrayObject* result = NULL;
- JavaObject* stack = NULL;
- llvm_gcroot(vmthrow, 0);
- llvm_gcroot(throwable, 0);
- llvm_gcroot(result, 0);
- llvm_gcroot(stack, 0);
-
- BEGIN_NATIVE_EXCEPTION(0)
-
- Jnjvm* vm = JavaThread::get()->getJVM();
- mvm::VMKit* vmkit = vm->vmkit;
- JavaField* field = vm->upcalls->vmDataVMThrowable;
-
- stack = field->getInstanceObjectField(vmthrow);
-
- // remove the VMThrowable.fillInStackTrace method and the last method
- // on the stack.
- sint32 index = 2;;
- while (index != JavaArray::getSize(stack)) {
- mvm::MethodInfo* MI = vmkit->IPToMethodInfo(ArrayPtr::getElement((ArrayPtr*)stack, index));
- if (!MI->isHighLevelMethod()) ++index;
- else {
- JavaMethod* meth = (JavaMethod*)MI->MetaInfo;
- assert(meth && "Wrong stack trace");
- if (meth->classDef->isAssignableFrom(vm->upcalls->newThrowable)) {
- ++index;
- } else break;
- }
- }
-
- sint32 size = 0;
- sint32 cur = index;
- while (cur < JavaArray::getSize(stack)) {
- mvm::MethodInfo* MI = vmkit->IPToMethodInfo(ArrayPtr::getElement((ArrayPtr*)stack, cur));
- ++cur;
- if (MI->isHighLevelMethod()) ++size;
- }
-
- result = (ArrayObject*)
- vm->upcalls->stackTraceArray->doNew(size);
-
- cur = 0;
- for (sint32 i = index; i < JavaArray::getSize(stack); ++i) {
- mvm::MethodInfo* MI = vmkit->IPToMethodInfo(ArrayPtr::getElement((ArrayPtr*)stack, i));
- if (MI->isHighLevelMethod()) {
- JavaMethod* meth = (JavaMethod*)MI->MetaInfo;
- ArrayObject::setElement(result, consStackElement(meth, ArrayPtr::getElement((ArrayPtr*)stack, i)), cur);
- cur++;
- }
- }
-
- END_NATIVE_EXCEPTION
-
- return result;
-}
-
-}
diff --git a/vmkit/lib/J3/Classpath/JavaUpcalls.cpp b/vmkit/lib/J3/Classpath/JavaUpcalls.cpp
deleted file mode 100644
index 2223cc5..0000000
--- a/vmkit/lib/J3/Classpath/JavaUpcalls.cpp
+++ /dev/null
@@ -1,1044 +0,0 @@
-//===-------- JavaUpcalls.cpp - Upcalls to Java entities ------------------===//
-//
-// The VMKit project
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#include "ClasspathReflect.h"
-#include "JavaAccess.h"
-#include "JavaClass.h"
-#include "JavaObject.h"
-#include "JavaString.h"
-#include "JavaThread.h"
-#include "JavaUpcalls.h"
-#include "Jnjvm.h"
-#include "mvm/SystemThreads.h"
-#include "mvm/VMKit.h"
-#include "j3/JavaCompiler.h"
-#include "JavaTypes.h"
-
-// for dlopen and dlsym
-#include <dlfcn.h>
-
-using namespace j3;
-
-typedef void (*static_init_t)(JnjvmClassLoader*);
-
-const UTF8* JavaCompiler::InlinePragma = 0;
-const UTF8* JavaCompiler::NoInlinePragma = 0;
-
-#define COMPILE_METHODS(cl) \
- for (CommonClass::method_iterator i = cl->virtualMethods.begin(), \
- e = cl->virtualMethods.end(); i!= e; ++i) { \
- i->second->compiledPtr(); \
- } \
- \
- for (CommonClass::method_iterator i = cl->staticMethods.begin(), \
- e = cl->staticMethods.end(); i!= e; ++i) { \
- i->second->compiledPtr(); \
- }
-
-void Classpath::CreateJavaThread(Jnjvm* vm, JavaThread* myth,
- const char* thName, JavaObject* Group) {
- JavaObjectVMThread* vmth = NULL;
- JavaObject* th = NULL;
- JavaObject* name = NULL;
- llvm_gcroot(Group, 0);
- llvm_gcroot(vmth, 0);
- llvm_gcroot(th, 0);
- llvm_gcroot(name, 0);
-
- th = newThread->doNew();
- myth->javaThread = th;
- vmth = (JavaObjectVMThread*)newVMThread->doNew();
- name = vm->asciizToStr(thName);
-
- threadName->setInstanceObjectField(th, name);
- priority->setInstanceInt32Field(th, (uint32)1);
- daemon->setInstanceInt8Field(th, (uint32)0);
- vmThread->setInstanceObjectField(th, vmth);
- assocThread->setInstanceObjectField(vmth, th);
- running->setInstanceInt8Field(vmth, (uint32)1);
- JavaObjectVMThread::setVmdata(vmth, myth);
-
- group->setInstanceObjectField(th, Group);
- groupAddThread->invokeIntSpecial(threadGroup, Group, &th);
-
- finaliseCreateInitialThread->invokeIntStatic(inheritableThreadLocal, &th);
-}
-
-
-void Classpath::CreateForeignJavaThread(Jnjvm* vm, JavaThread* myth) {
- JavaObject* RG = 0;
- llvm_gcroot(RG, 0);
-
- RG = rootGroup->getStaticObjectField(); // should be system group or a special group for foreign threads
- CreateJavaThread(vm, myth, "foreign thread", RG);
-}
-
-
-void Classpath::InitializeThreading(Jnjvm* vm) {
-
- JavaObject* RG = 0;
- JavaObject* SystemGroup = 0;
- JavaObject* systemName = 0;
- llvm_gcroot(RG, 0);
- llvm_gcroot(SystemGroup, 0);
- llvm_gcroot(systemName, 0);
-
- // Resolve and initialize classes first.
- newThread->resolveClass();
- newThread->initialiseClass();
-
- newVMThread->resolveClass();
- newVMThread->initialiseClass();
-
- threadGroup->resolveClass();
- threadGroup->initialiseClass();
-
- // Create the main thread
- RG = rootGroup->getStaticObjectField();
- assert(RG && "No root group");
- assert(vm->getMainThread() && "VM did not set its main thread");
- CreateJavaThread(vm, JavaThread::get(), "main", RG);
-
- // Create the "system" group.
- SystemGroup = threadGroup->doNew();
- initGroup->invokeIntSpecial(threadGroup, SystemGroup);
- systemName = vm->asciizToStr("system");
- groupName->setInstanceObjectField(SystemGroup, systemName);
-}
-
-extern "C" void Java_java_lang_ref_WeakReference__0003Cinit_0003E__Ljava_lang_Object_2(
- JavaObjectReference* reference, JavaObject* referent) {
- llvm_gcroot(reference, 0);
- llvm_gcroot(referent, 0);
-
- BEGIN_NATIVE_EXCEPTION(0)
-
- JavaObjectReference::init(reference, referent, 0);
- mvm::Thread::get()->vmkit->addWeakReference(reference);
-
- END_NATIVE_EXCEPTION
-
-}
-
-extern "C" void Java_java_lang_ref_WeakReference__0003Cinit_0003E__Ljava_lang_Object_2Ljava_lang_ref_ReferenceQueue_2(
- JavaObjectReference* reference,
- JavaObject* referent,
- JavaObject* queue) {
- llvm_gcroot(reference, 0);
- llvm_gcroot(referent, 0);
- llvm_gcroot(queue, 0);
-
- BEGIN_NATIVE_EXCEPTION(0)
-
- JavaObjectReference::init(reference, referent, queue);
- mvm::Thread::get()->vmkit->addWeakReference(reference);
-
- END_NATIVE_EXCEPTION
-
-}
-
-extern "C" void Java_java_lang_ref_SoftReference__0003Cinit_0003E__Ljava_lang_Object_2(
- JavaObjectReference* reference, JavaObject* referent) {
- llvm_gcroot(reference, 0);
- llvm_gcroot(referent, 0);
-
- BEGIN_NATIVE_EXCEPTION(0)
-
- JavaObjectReference::init(reference, referent, 0);
- mvm::Thread::get()->vmkit->addSoftReference(reference);
-
- END_NATIVE_EXCEPTION
-
-}
-
-extern "C" void Java_java_lang_ref_SoftReference__0003Cinit_0003E__Ljava_lang_Object_2Ljava_lang_ref_ReferenceQueue_2(
- JavaObjectReference* reference,
- JavaObject* referent,
- JavaObject* queue) {
- llvm_gcroot(reference, 0);
- llvm_gcroot(referent, 0);
- llvm_gcroot(queue, 0);
-
- BEGIN_NATIVE_EXCEPTION(0)
-
- JavaObjectReference::init(reference, referent, queue);
- mvm::Thread::get()->vmkit->addSoftReference(reference);
-
- END_NATIVE_EXCEPTION
-
-}
-
-extern "C" void Java_java_lang_ref_PhantomReference__0003Cinit_0003E__Ljava_lang_Object_2Ljava_lang_ref_ReferenceQueue_2(
- JavaObjectReference* reference,
- JavaObject* referent,
- JavaObject* queue) {
- llvm_gcroot(reference, 0);
- llvm_gcroot(referent, 0);
- llvm_gcroot(queue, 0);
-
- BEGIN_NATIVE_EXCEPTION(0)
-
- JavaObjectReference::init(reference, referent, queue);
- mvm::Thread::get()->vmkit->addPhantomReference(reference);
-
- END_NATIVE_EXCEPTION
-}
-
-extern "C" JavaString* Java_java_lang_VMString_intern__Ljava_lang_String_2(
- JavaString* obj) {
- const ArrayUInt16* array = 0;
- JavaString* res = 0;
- llvm_gcroot(obj, 0);
- llvm_gcroot(array, 0);
- llvm_gcroot(res, 0);
- // If the string is already interned, just return.
- if (obj->getVirtualTable() == JavaString::internStringVT) return obj;
-
- BEGIN_NATIVE_EXCEPTION(0)
-
- Jnjvm* vm = obj->getJVM();
- array = JavaString::strToArray(obj, vm);
- res = vm->constructString(array);
-
- END_NATIVE_EXCEPTION
-
- return res;
-}
-
-extern "C" uint8 Java_java_lang_Class_isArray__(JavaObjectClass* klass) {
- llvm_gcroot(klass, 0);
- UserCommonClass* cl = 0;
-
- BEGIN_NATIVE_EXCEPTION(0)
-
- cl = JavaObjectClass::getClass(klass);
-
- END_NATIVE_EXCEPTION
-
- return (uint8)cl->isArray();
-}
-
-extern "C" JavaObject* Java_gnu_classpath_VMStackWalker_getCallingClass__() {
-
- JavaObject* res = 0;
- llvm_gcroot(res, 0);
-
- BEGIN_NATIVE_EXCEPTION(0)
-
- JavaThread* th = JavaThread::get();
- UserClass* cl = th->getCallingClassLevel(2);
- if (cl != NULL) res = cl->getClassDelegatee();
-
- END_NATIVE_EXCEPTION
-
- return res;
-}
-
-extern "C" JavaObject* Java_gnu_classpath_VMStackWalker_getCallingClassLoader__() {
-
- JavaObject* res = 0;
- llvm_gcroot(res, 0);
-
- BEGIN_NATIVE_EXCEPTION(0)
-
- JavaThread* th = JavaThread::get();
- UserClass* cl = th->getCallingClassLevel(2);
- res = cl->classLoader->getJavaClassLoader();
-
- END_NATIVE_EXCEPTION
-
- return res;
-}
-
-extern "C" JavaObject* Java_gnu_classpath_VMStackWalker_firstNonNullClassLoader__() {
- JavaObject* res = 0;
- llvm_gcroot(res, 0);
-
- BEGIN_NATIVE_EXCEPTION(0)
-
- JavaThread* th = JavaThread::get();
- res = th->getNonNullClassLoader();
-
- END_NATIVE_EXCEPTION
-
- return res;
-}
-
-extern "C" JavaObject* Java_sun_reflect_Reflection_getCallerClass__I(uint32 index) {
-
- JavaObject* res = 0;
- llvm_gcroot(res, 0);
-
- BEGIN_NATIVE_EXCEPTION(0)
-
- JavaThread* th = JavaThread::get();
- UserClass* cl = th->getCallingClassLevel(index);
- if (cl) res = cl->getClassDelegatee();
-
- END_NATIVE_EXCEPTION
-
- return res;
-}
-
-extern "C" JavaObject* Java_java_lang_reflect_AccessibleObject_getAnnotation__Ljava_lang_Class_2(
- JavaObject* obj) {
- llvm_gcroot(obj, 0);
- return 0;
-}
-
-extern "C" JavaObject* Java_java_lang_reflect_AccessibleObject_getDeclaredAnnotations__() {
- JavaObject* res = 0;
- llvm_gcroot(res, 0);
-
- BEGIN_NATIVE_EXCEPTION(0)
-
- Jnjvm* vm = JavaThread::get()->getJVM();
- UserClassArray* array = vm->upcalls->constructorArrayAnnotation;
- res = array->doNew(0);
-
- END_NATIVE_EXCEPTION
-
- return res;
-}
-
-extern "C" void nativeJavaObjectClassTracer(
- JavaObjectClass* obj, uintptr_t closure) {
- JavaObjectClass::staticTracer(obj, closure);
-}
-
-extern "C" void nativeJavaObjectFieldTracer(
- JavaObjectField* obj, uintptr_t closure) {
- JavaObjectField::staticTracer(obj, closure);
-}
-
-extern "C" void nativeJavaObjectMethodTracer(
- JavaObjectMethod* obj, uintptr_t closure) {
- JavaObjectMethod::staticTracer(obj, closure);
-}
-
-extern "C" void nativeJavaObjectConstructorTracer(
- JavaObjectConstructor* obj, uintptr_t closure) {
- JavaObjectConstructor::staticTracer(obj, closure);
-}
-
-extern "C" void nativeJavaObjectVMThreadTracer(
- JavaObjectVMThread* obj, uintptr_t closure) {
- JavaObjectVMThread::staticTracer(obj, closure);
-}
-
-extern "C" void nativeJavaObjectVMThreadDestructor(JavaObjectVMThread* obj) {
- llvm_gcroot(obj, 0);
- JavaObjectVMThread::staticDestructor(obj);
-}
-
-extern "C" JavaString* Java_java_lang_VMSystem_getenv__Ljava_lang_String_2(JavaString* str) {
- JavaString* ret = 0;
- llvm_gcroot(str, 0);
- llvm_gcroot(ret, 0);
-
- BEGIN_NATIVE_EXCEPTION(0)
-
- mvm::ThreadAllocator allocator;
- char* buf = JavaString::strToAsciiz(str, &allocator);
- char* res = getenv(buf);
- if (res) {
- Jnjvm* vm = JavaThread::get()->getJVM();
- ret = vm->asciizToStr(res);
- }
-
- END_NATIVE_EXCEPTION
-
- return ret;
-}
-
-
-Classpath::Classpath(JnjvmBootstrapLoader* loader, bool dlLoad) {
-
- // Try to find if we have a pre-compiled rt.jar
- if (dlLoad) {
- SuperArray = (Class*)dlsym(SELF_HANDLE, "java_lang_Object");
- if (!SuperArray) {
- loader->nativeHandle = dlopen("libvmjc"DYLD_EXTENSION, RTLD_LAZY | RTLD_GLOBAL);
- if (loader->nativeHandle) {
- // Found it!
- SuperArray = (Class*)dlsym(loader->nativeHandle, "java_lang_Object");
- }
- }
-
- if (SuperArray) {
- assert(TheCompiler &&
- "Loading libvmjc"DYLD_EXTENSION" requires a compiler");
- ClassArray::SuperArray = (Class*)SuperArray->getInternal();
-
- // Get the native classes.
- OfVoid = (ClassPrimitive*)dlsym(loader->nativeHandle, "void");
- OfBool = (ClassPrimitive*)dlsym(loader->nativeHandle, "boolean");
- OfByte = (ClassPrimitive*)dlsym(loader->nativeHandle, "byte");
- OfChar = (ClassPrimitive*)dlsym(loader->nativeHandle, "char");
- OfShort = (ClassPrimitive*)dlsym(loader->nativeHandle, "short");
- OfInt = (ClassPrimitive*)dlsym(loader->nativeHandle, "int");
- OfFloat = (ClassPrimitive*)dlsym(loader->nativeHandle, "float");
- OfLong = (ClassPrimitive*)dlsym(loader->nativeHandle, "long");
- OfDouble = (ClassPrimitive*)dlsym(loader->nativeHandle, "double");
-
-
- // We have the java/lang/Object class, execute the static initializer.
- static_init_t init = (static_init_t)(uintptr_t)SuperArray->classLoader;
- assert(init && "Loaded the wrong boot library");
- init(loader);
-
- // Get the base object arrays after the init, because init puts arrays
- // in the class loader map.
- ArrayOfString =
- loader->constructArray(loader->asciizConstructUTF8("[Ljava/lang/String;"));
-
- ArrayOfObject =
- loader->constructArray(loader->asciizConstructUTF8("[Ljava/lang/Object;"));
-
- InterfacesArray = ArrayOfObject->interfaces;
- ClassArray::InterfacesArray = InterfacesArray;
-
- }
- }
-
- if (!OfChar) {
- // Allocate interfaces.
- InterfacesArray = (Class**)loader->allocator.Allocate(2 * sizeof(UserClass*),
- "Interface array");
- ClassArray::InterfacesArray = InterfacesArray;
-
- // Create the primitive classes.
- OfChar = UPCALL_PRIMITIVE_CLASS(loader, "char", 1);
- OfBool = UPCALL_PRIMITIVE_CLASS(loader, "boolean", 0);
- OfShort = UPCALL_PRIMITIVE_CLASS(loader, "short", 1);
- OfInt = UPCALL_PRIMITIVE_CLASS(loader, "int", 2);
- OfLong = UPCALL_PRIMITIVE_CLASS(loader, "long", 3);
- OfFloat = UPCALL_PRIMITIVE_CLASS(loader, "float", 2);
- OfDouble = UPCALL_PRIMITIVE_CLASS(loader, "double", 3);
- OfVoid = UPCALL_PRIMITIVE_CLASS(loader, "void", 0);
- OfByte = UPCALL_PRIMITIVE_CLASS(loader, "byte", 0);
- }
-
- // Create the primitive arrays.
- ArrayOfChar = loader->constructArray(loader->asciizConstructUTF8("[C"), OfChar);
- ArrayOfByte = loader->constructArray(loader->asciizConstructUTF8("[B"), OfByte);
- ArrayOfInt = loader->constructArray(loader->asciizConstructUTF8("[I"), OfInt);
- ArrayOfBool = loader->constructArray(loader->asciizConstructUTF8("[Z"), OfBool);
- ArrayOfLong = loader->constructArray(loader->asciizConstructUTF8("[J"), OfLong);
- ArrayOfFloat = loader->constructArray(loader->asciizConstructUTF8("[F"), OfFloat);
- ArrayOfDouble = loader->constructArray(loader->asciizConstructUTF8("[D"), OfDouble);
- ArrayOfShort = loader->constructArray(loader->asciizConstructUTF8("[S"), OfShort);
-
- // Fill the maps.
- primitiveMap[I_VOID] = OfVoid;
- primitiveMap[I_BOOL] = OfBool;
- primitiveMap[I_BYTE] = OfByte;
- primitiveMap[I_CHAR] = OfChar;
- primitiveMap[I_SHORT] = OfShort;
- primitiveMap[I_INT] = OfInt;
- primitiveMap[I_FLOAT] = OfFloat;
- primitiveMap[I_LONG] = OfLong;
- primitiveMap[I_DOUBLE] = OfDouble;
-
- arrayTable[JavaArray::T_BOOLEAN - 4] = ArrayOfBool;
- arrayTable[JavaArray::T_BYTE - 4] = ArrayOfByte;
- arrayTable[JavaArray::T_CHAR - 4] = ArrayOfChar;
- arrayTable[JavaArray::T_SHORT - 4] = ArrayOfShort;
- arrayTable[JavaArray::T_INT - 4] = ArrayOfInt;
- arrayTable[JavaArray::T_FLOAT - 4] = ArrayOfFloat;
- arrayTable[JavaArray::T_LONG - 4] = ArrayOfLong;
- arrayTable[JavaArray::T_DOUBLE - 4] = ArrayOfDouble;
-
- Attribut::annotationsAttribut = loader->asciizConstructUTF8("RuntimeVisibleAnnotations");
- Attribut::codeAttribut = loader->asciizConstructUTF8("Code");
- Attribut::exceptionsAttribut = loader->asciizConstructUTF8("Exceptions");
- Attribut::constantAttribut = loader->asciizConstructUTF8("ConstantValue");
- Attribut::lineNumberTableAttribut = loader->asciizConstructUTF8("LineNumberTable");
- Attribut::innerClassesAttribut = loader->asciizConstructUTF8("InnerClasses");
- Attribut::sourceFileAttribut = loader->asciizConstructUTF8("SourceFile");
-
- JavaCompiler::InlinePragma = loader->asciizConstructUTF8("Lorg/vmmagic/pragma/Inline;");
- JavaCompiler::NoInlinePragma = loader->asciizConstructUTF8("Lorg/vmmagic/pragma/NoInline;");
-
- initName = loader->asciizConstructUTF8("<init>");
- initExceptionSig = loader->asciizConstructUTF8("(Ljava/lang/String;)V");
- clinitName = loader->asciizConstructUTF8("<clinit>");
- clinitType = loader->asciizConstructUTF8("()V");
- runName = loader->asciizConstructUTF8("run");
- prelib = loader->asciizConstructUTF8("lib");
-#if defined(__MACH__)
- postlib = loader->asciizConstructUTF8(".dylib");
-#else
- postlib = loader->asciizConstructUTF8(".so");
-#endif
- mathName = loader->asciizConstructUTF8("java/lang/Math");
- stackWalkerName = loader->asciizConstructUTF8("gnu/classpath/VMStackWalker");
- NoClassDefFoundErrorName = loader->asciizConstructUTF8("java/lang/NoClassDefFoundError");
-
-#define DEF_UTF8(var) \
- var = loader->asciizConstructUTF8(#var)
-
- DEF_UTF8(abs);
- DEF_UTF8(sqrt);
- DEF_UTF8(sin);
- DEF_UTF8(cos);
- DEF_UTF8(tan);
- DEF_UTF8(asin);
- DEF_UTF8(acos);
- DEF_UTF8(atan);
- DEF_UTF8(atan2);
- DEF_UTF8(exp);
- DEF_UTF8(log);
- DEF_UTF8(pow);
- DEF_UTF8(ceil);
- DEF_UTF8(floor);
- DEF_UTF8(rint);
- DEF_UTF8(cbrt);
- DEF_UTF8(cosh);
- DEF_UTF8(expm1);
- DEF_UTF8(hypot);
- DEF_UTF8(log10);
- DEF_UTF8(log1p);
- DEF_UTF8(sinh);
- DEF_UTF8(tanh);
- DEF_UTF8(finalize);
-
-#undef DEF_UTF8
-}
-
-void Classpath::postInitialiseClasspath(JnjvmClassLoader* loader) {
-
- newClassLoader =
- UPCALL_CLASS(loader, "java/lang/ClassLoader");
-
- getSystemClassLoader =
- UPCALL_METHOD(loader, "java/lang/ClassLoader", "getSystemClassLoader",
- "()Ljava/lang/ClassLoader;", ACC_STATIC);
-
- setContextClassLoader =
- UPCALL_METHOD(loader, "java/lang/Thread", "setContextClassLoader",
- "(Ljava/lang/ClassLoader;)V", ACC_VIRTUAL);
-
- newString =
- UPCALL_CLASS(loader, "java/lang/String");
-
- newClass =
- UPCALL_CLASS(loader, "java/lang/Class");
-
- newThrowable =
- UPCALL_CLASS(loader, "java/lang/Throwable");
-
- newException =
- UPCALL_CLASS(loader, "java/lang/Exception");
-
- newPointer32 =
- UPCALL_CLASS(loader, "gnu/classpath/Pointer32");
-
- newPointer64 =
- UPCALL_CLASS(loader, "gnu/classpath/Pointer64");
-
- newDirectByteBuffer =
- UPCALL_CLASS(loader, "java/nio/DirectByteBufferImpl$ReadWrite");
-
- InitDirectByteBuffer =
- UPCALL_METHOD(loader, "java/nio/DirectByteBufferImpl$ReadWrite", "<init>",
- "(Ljava/lang/Object;Lgnu/classpath/Pointer;III)V",
- ACC_VIRTUAL);
-
- initClass =
- UPCALL_METHOD(loader, "java/lang/Class", "<init>", "(Ljava/lang/Object;)V",
- ACC_VIRTUAL);
-
- initClassWithProtectionDomain =
- UPCALL_METHOD(loader, "java/lang/Class", "<init>",
- "(Ljava/lang/Object;Ljava/security/ProtectionDomain;)V",
- ACC_VIRTUAL);
-
- vmdataClass =
- UPCALL_FIELD(loader, "java/lang/Class", "vmdata", "Ljava/lang/Object;",
- ACC_VIRTUAL);
-
- setProperty =
- UPCALL_METHOD(loader, "java/util/Properties", "setProperty",
- "(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/Object;",
- ACC_VIRTUAL);
-
- initString =
- UPCALL_METHOD(loader, "java/lang/String", "<init>", "([CIIZ)V", ACC_VIRTUAL);
-
- initConstructor =
- UPCALL_METHOD(loader, "java/lang/reflect/Constructor", "<init>",
- "(Ljava/lang/Class;I)V", ACC_VIRTUAL);
-
- newConstructor =
- UPCALL_CLASS(loader, "java/lang/reflect/Constructor");
-
- constructorArrayClass =
- UPCALL_ARRAY_CLASS(loader, "java/lang/reflect/Constructor", 1);
-
- constructorArrayAnnotation =
- UPCALL_ARRAY_CLASS(loader, "java/lang/annotation/Annotation", 1);
-
- constructorSlot =
- UPCALL_FIELD(loader, "java/lang/reflect/Constructor", "slot", "I", ACC_VIRTUAL);
-
- initMethod =
- UPCALL_METHOD(loader, "java/lang/reflect/Method", "<init>",
- "(Ljava/lang/Class;Ljava/lang/String;I)V", ACC_VIRTUAL);
-
- newMethod =
- UPCALL_CLASS(loader, "java/lang/reflect/Method");
-
- methodArrayClass =
- UPCALL_ARRAY_CLASS(loader, "java/lang/reflect/Method", 1);
-
- methodSlot =
- UPCALL_FIELD(loader, "java/lang/reflect/Method", "slot", "I", ACC_VIRTUAL);
-
- initField =
- UPCALL_METHOD(loader, "java/lang/reflect/Field", "<init>",
- "(Ljava/lang/Class;Ljava/lang/String;I)V", ACC_VIRTUAL);
-
- newField =
- UPCALL_CLASS(loader, "java/lang/reflect/Field");
-
- fieldArrayClass =
- UPCALL_ARRAY_CLASS(loader, "java/lang/reflect/Field", 1);
-
- fieldSlot =
- UPCALL_FIELD(loader, "java/lang/reflect/Field", "slot", "I", ACC_VIRTUAL);
-
-
- classArrayClass =
- UPCALL_ARRAY_CLASS(loader, "java/lang/Class", 1);
-
- newVMThrowable =
- UPCALL_CLASS(loader, "java/lang/VMThrowable");
-
- initVMThrowable =
- UPCALL_METHOD(loader, "java/lang/VMThrowable", "<init>", "()V", ACC_VIRTUAL);
-
- vmDataVMThrowable =
- UPCALL_FIELD(loader, "java/lang/VMThrowable", "vmdata", "Ljava/lang/Object;",
- ACC_VIRTUAL);
-
- bufferAddress =
- UPCALL_FIELD(loader, "java/nio/Buffer", "address", "Lgnu/classpath/Pointer;",
- ACC_VIRTUAL);
-
- dataPointer32 =
- UPCALL_FIELD(loader, "gnu/classpath/Pointer32", "data", "I", ACC_VIRTUAL);
-
- dataPointer64 =
- UPCALL_FIELD(loader, "gnu/classpath/Pointer64", "data", "J", ACC_VIRTUAL);
-
- vmdataClassLoader =
- UPCALL_FIELD(loader, "java/lang/ClassLoader", "vmdata", "Ljava/lang/Object;",
- ACC_VIRTUAL);
-
- newStackTraceElement =
- UPCALL_CLASS(loader, "java/lang/StackTraceElement");
-
- stackTraceArray =
- UPCALL_ARRAY_CLASS(loader, "java/lang/StackTraceElement", 1);
-
- initStackTraceElement =
- UPCALL_METHOD(loader, "java/lang/StackTraceElement", "<init>",
- "(Ljava/lang/String;ILjava/lang/String;Ljava/lang/String;Z)V",
- ACC_VIRTUAL);
-
- boolValue =
- UPCALL_FIELD(loader, "java/lang/Boolean", "value", "Z", ACC_VIRTUAL);
-
- byteValue =
- UPCALL_FIELD(loader, "java/lang/Byte", "value", "B", ACC_VIRTUAL);
-
- shortValue =
- UPCALL_FIELD(loader, "java/lang/Short", "value", "S", ACC_VIRTUAL);
-
- charValue =
- UPCALL_FIELD(loader, "java/lang/Character", "value", "C", ACC_VIRTUAL);
-
- intValue =
- UPCALL_FIELD(loader, "java/lang/Integer", "value", "I", ACC_VIRTUAL);
-
- longValue =
- UPCALL_FIELD(loader, "java/lang/Long", "value", "J", ACC_VIRTUAL);
-
- floatValue =
- UPCALL_FIELD(loader, "java/lang/Float", "value", "F", ACC_VIRTUAL);
-
- doubleValue =
- UPCALL_FIELD(loader, "java/lang/Double", "value", "D", ACC_VIRTUAL);
-
- Classpath::voidClass =
- UPCALL_CLASS(loader, "java/lang/Void");
-
- Classpath::boolClass =
- UPCALL_CLASS(loader, "java/lang/Boolean");
-
- Classpath::byteClass =
- UPCALL_CLASS(loader, "java/lang/Byte");
-
- Classpath::shortClass =
- UPCALL_CLASS(loader, "java/lang/Short");
-
- Classpath::charClass =
- UPCALL_CLASS(loader, "java/lang/Character");
-
- Classpath::intClass =
- UPCALL_CLASS(loader, "java/lang/Integer");
-
- Classpath::floatClass =
- UPCALL_CLASS(loader, "java/lang/Float");
-
- Classpath::doubleClass =
- UPCALL_CLASS(loader, "java/lang/Double");
-
- Classpath::longClass =
- UPCALL_CLASS(loader, "java/lang/Long");
-
- Classpath::OfObject =
- UPCALL_CLASS(loader, "java/lang/Object");
-
- vmStackWalker =
- UPCALL_CLASS(loader, "gnu/classpath/VMStackWalker");
-
- loadInClassLoader =
- UPCALL_METHOD(loader, "java/lang/ClassLoader", "loadClass",
- "(Ljava/lang/String;)Ljava/lang/Class;", ACC_VIRTUAL);
-
- JavaMethod* internString =
- UPCALL_METHOD(loader, "java/lang/VMString", "intern",
- "(Ljava/lang/String;)Ljava/lang/String;", ACC_STATIC);
- internString->setNative();
-
- JavaMethod* isArray =
- UPCALL_METHOD(loader, "java/lang/Class", "isArray", "()Z", ACC_VIRTUAL);
- isArray->setNative();
-
-
- UPCALL_REFLECT_CLASS_EXCEPTION(loader, InvocationTargetException);
- UPCALL_CLASS_EXCEPTION(loader, ArrayStoreException);
- UPCALL_CLASS_EXCEPTION(loader, ClassCastException);
- UPCALL_CLASS_EXCEPTION(loader, IllegalMonitorStateException);
- UPCALL_CLASS_EXCEPTION(loader, IllegalArgumentException);
- UPCALL_CLASS_EXCEPTION(loader, InterruptedException);
- UPCALL_CLASS_EXCEPTION(loader, IndexOutOfBoundsException);
- UPCALL_CLASS_EXCEPTION(loader, ArrayIndexOutOfBoundsException);
- UPCALL_CLASS_EXCEPTION(loader, NegativeArraySizeException);
- UPCALL_CLASS_EXCEPTION(loader, NullPointerException);
- UPCALL_CLASS_EXCEPTION(loader, SecurityException);
- UPCALL_CLASS_EXCEPTION(loader, ClassFormatError);
- UPCALL_CLASS_EXCEPTION(loader, ClassCircularityError);
- UPCALL_CLASS_EXCEPTION(loader, NoClassDefFoundError);
- UPCALL_CLASS_EXCEPTION(loader, UnsupportedClassVersionError);
- UPCALL_CLASS_EXCEPTION(loader, NoSuchFieldError);
- UPCALL_CLASS_EXCEPTION(loader, NoSuchMethodError);
- UPCALL_CLASS_EXCEPTION(loader, InstantiationError);
- UPCALL_CLASS_EXCEPTION(loader, InstantiationException);
- UPCALL_CLASS_EXCEPTION(loader, IllegalAccessError);
- UPCALL_CLASS_EXCEPTION(loader, IllegalAccessException);
- UPCALL_CLASS_EXCEPTION(loader, VerifyError);
- UPCALL_CLASS_EXCEPTION(loader, ExceptionInInitializerError);
- UPCALL_CLASS_EXCEPTION(loader, LinkageError);
- UPCALL_CLASS_EXCEPTION(loader, AbstractMethodError);
- UPCALL_CLASS_EXCEPTION(loader, UnsatisfiedLinkError);
- UPCALL_CLASS_EXCEPTION(loader, InternalError);
- UPCALL_CLASS_EXCEPTION(loader, OutOfMemoryError);
- UPCALL_CLASS_EXCEPTION(loader, StackOverflowError);
- UPCALL_CLASS_EXCEPTION(loader, UnknownError);
- UPCALL_CLASS_EXCEPTION(loader, ClassNotFoundException);
- UPCALL_CLASS_EXCEPTION(loader, ArithmeticException);
-
- UPCALL_METHOD_EXCEPTION(loader, InvocationTargetException);
- UPCALL_METHOD_EXCEPTION(loader, ArrayStoreException);
- UPCALL_METHOD_EXCEPTION(loader, ClassCastException);
- UPCALL_METHOD_EXCEPTION(loader, IllegalMonitorStateException);
- UPCALL_METHOD_EXCEPTION(loader, IllegalArgumentException);
- UPCALL_METHOD_EXCEPTION(loader, InterruptedException);
- UPCALL_METHOD_EXCEPTION(loader, IndexOutOfBoundsException);
- UPCALL_METHOD_EXCEPTION(loader, ArrayIndexOutOfBoundsException);
- UPCALL_METHOD_EXCEPTION(loader, NegativeArraySizeException);
- UPCALL_METHOD_EXCEPTION(loader, NullPointerException);
- UPCALL_METHOD_EXCEPTION(loader, SecurityException);
- UPCALL_METHOD_EXCEPTION(loader, ClassFormatError);
- UPCALL_METHOD_EXCEPTION(loader, ClassCircularityError);
- UPCALL_METHOD_EXCEPTION(loader, NoClassDefFoundError);
- UPCALL_METHOD_EXCEPTION(loader, UnsupportedClassVersionError);
- UPCALL_METHOD_EXCEPTION(loader, NoSuchFieldError);
- UPCALL_METHOD_EXCEPTION(loader, NoSuchMethodError);
- UPCALL_METHOD_EXCEPTION(loader, InstantiationError);
- UPCALL_METHOD_EXCEPTION(loader, InstantiationException);
- UPCALL_METHOD_EXCEPTION(loader, IllegalAccessError);
- UPCALL_METHOD_EXCEPTION(loader, IllegalAccessException);
- UPCALL_METHOD_EXCEPTION(loader, VerifyError);
- UPCALL_METHOD_EXCEPTION(loader, ExceptionInInitializerError);
- UPCALL_METHOD_EXCEPTION(loader, LinkageError);
- UPCALL_METHOD_EXCEPTION(loader, AbstractMethodError);
- UPCALL_METHOD_EXCEPTION(loader, UnsatisfiedLinkError);
- UPCALL_METHOD_EXCEPTION(loader, InternalError);
- UPCALL_METHOD_EXCEPTION(loader, OutOfMemoryError);
- UPCALL_METHOD_EXCEPTION(loader, StackOverflowError);
- UPCALL_METHOD_EXCEPTION(loader, UnknownError);
- UPCALL_METHOD_EXCEPTION(loader, ClassNotFoundException);
- UPCALL_METHOD_EXCEPTION(loader, ArithmeticException);
-
- UPCALL_METHOD_WITH_EXCEPTION(loader, NoClassDefFoundError);
- UPCALL_METHOD_WITH_EXCEPTION(loader, ExceptionInInitializerError);
- UPCALL_METHOD_WITH_EXCEPTION(loader, InvocationTargetException);
-
- InitObject = UPCALL_METHOD(loader, "java/lang/Object", "<init>", "()V",
- ACC_VIRTUAL);
-
- FinalizeObject = UPCALL_METHOD(loader, "java/lang/Object", "finalize", "()V",
- ACC_VIRTUAL);
-
- IntToString = UPCALL_METHOD(loader, "java/lang/Integer", "toString",
- "(II)Ljava/lang/String;", ACC_STATIC);
-
- SystemArraycopy = UPCALL_METHOD(loader, "java/lang/System", "arraycopy",
- "(Ljava/lang/Object;ILjava/lang/Object;II)V",
- ACC_STATIC);
-
- VMSystemArraycopy = UPCALL_METHOD(loader, "java/lang/VMSystem", "arraycopy",
- "(Ljava/lang/Object;ILjava/lang/Object;II)V",
- ACC_STATIC);
-
- SystemClass = UPCALL_CLASS(loader, "java/lang/System");
-
- newThread =
- UPCALL_CLASS(loader, "java/lang/Thread");
-
- newVMThread =
- UPCALL_CLASS(loader, "java/lang/VMThread");
-
- assocThread =
- UPCALL_FIELD(loader, "java/lang/VMThread", "thread", "Ljava/lang/Thread;",
- ACC_VIRTUAL);
-
- vmdataVMThread =
- UPCALL_FIELD(loader, "java/lang/VMThread", "vmdata", "Ljava/lang/Object;",
- ACC_VIRTUAL);
-
- inheritableThreadLocal =
- UPCALL_CLASS(loader, "java/lang/InheritableThreadLocal");
-
- finaliseCreateInitialThread =
- UPCALL_METHOD(loader, "java/lang/InheritableThreadLocal", "newChildThread",
- "(Ljava/lang/Thread;)V", ACC_STATIC);
-
- initVMThread =
- UPCALL_METHOD(loader, "java/lang/VMThread", "<init>",
- "(Ljava/lang/Thread;)V", ACC_VIRTUAL);
-
- runVMThread =
- UPCALL_METHOD(loader, "java/lang/VMThread", "run", "()V", ACC_VIRTUAL);
-
-
- groupAddThread =
- UPCALL_METHOD(loader, "java/lang/ThreadGroup", "addThread",
- "(Ljava/lang/Thread;)V", ACC_VIRTUAL);
-
- initGroup =
- UPCALL_METHOD(loader, "java/lang/ThreadGroup", "<init>",
- "()V", ACC_VIRTUAL);
-
- groupName =
- UPCALL_FIELD(loader, "java/lang/ThreadGroup", "name", "Ljava/lang/String;",
- ACC_VIRTUAL);
-
- threadName =
- UPCALL_FIELD(loader, "java/lang/Thread", "name", "Ljava/lang/String;",
- ACC_VIRTUAL);
-
-
- priority =
- UPCALL_FIELD(loader, "java/lang/Thread", "priority", "I", ACC_VIRTUAL);
-
- daemon =
- UPCALL_FIELD(loader, "java/lang/Thread", "daemon", "Z", ACC_VIRTUAL);
-
- group =
- UPCALL_FIELD(loader, "java/lang/Thread", "group",
- "Ljava/lang/ThreadGroup;", ACC_VIRTUAL);
-
- running =
- UPCALL_FIELD(loader, "java/lang/VMThread", "running", "Z", ACC_VIRTUAL);
-
- threadGroup =
- UPCALL_CLASS(loader, "java/lang/ThreadGroup");
-
- rootGroup =
- UPCALL_FIELD(loader, "java/lang/ThreadGroup", "root",
- "Ljava/lang/ThreadGroup;", ACC_STATIC);
-
- vmThread =
- UPCALL_FIELD(loader, "java/lang/Thread", "vmThread",
- "Ljava/lang/VMThread;", ACC_VIRTUAL);
-
- uncaughtException =
- UPCALL_METHOD(loader, "java/lang/ThreadGroup", "uncaughtException",
- "(Ljava/lang/Thread;Ljava/lang/Throwable;)V", ACC_VIRTUAL);
-
-
- methodClass =
- UPCALL_FIELD(loader, "java/lang/reflect/Method", "declaringClass",
- "Ljava/lang/Class;", ACC_VIRTUAL);
-
- fieldClass =
- UPCALL_FIELD(loader, "java/lang/reflect/Field", "declaringClass",
- "Ljava/lang/Class;", ACC_VIRTUAL);
-
- constructorClass =
- UPCALL_FIELD(loader, "java/lang/reflect/Constructor", "clazz",
- "Ljava/lang/Class;", ACC_VIRTUAL);
-
- loader->loadName(loader->asciizConstructUTF8("java/lang/String"),
- true, false, NULL);
-
- loader->loadName(loader->asciizConstructUTF8("java/lang/Object"),
- true, false, NULL);
-
- // Don't compile methods here, we still don't know where to allocate Java
- // strings.
-
- JavaMethod* getEnv =
- UPCALL_METHOD(loader, "java/lang/VMSystem", "getenv",
- "(Ljava/lang/String;)Ljava/lang/String;", ACC_STATIC);
- getEnv->setNative();
-
- JavaMethod* getCallingClass =
- UPCALL_METHOD(loader, "gnu/classpath/VMStackWalker", "getCallingClass",
- "()Ljava/lang/Class;", ACC_STATIC);
- getCallingClass->setNative();
-
- JavaMethod* getCallingClassLoader =
- UPCALL_METHOD(loader, "gnu/classpath/VMStackWalker", "getCallingClassLoader",
- "()Ljava/lang/ClassLoader;", ACC_STATIC);
- getCallingClassLoader->setNative();
-
- JavaMethod* firstNonNullClassLoader =
- UPCALL_METHOD(loader, "gnu/classpath/VMStackWalker", "firstNonNullClassLoader",
- "()Ljava/lang/ClassLoader;", ACC_STATIC);
- firstNonNullClassLoader->setNative();
-
- JavaMethod* getCallerClass =
- UPCALL_METHOD(loader, "sun/reflect/Reflection", "getCallerClass",
- "(I)Ljava/lang/Class;", ACC_STATIC);
- getCallerClass->setNative();
-
- JavaMethod* postProperties =
- UPCALL_METHOD(loader, "gnu/classpath/VMSystemProperties", "postInit",
- "(Ljava/util/Properties;)V", ACC_STATIC);
- postProperties->setNative();
-
- // Also implement these twos, implementation in GNU Classpath 0.97.2 is buggy.
- JavaMethod* getAnnotation =
- UPCALL_METHOD(loader, "java/lang/reflect/AccessibleObject", "getAnnotation",
- "(Ljava/lang/Class;)Ljava/lang/annotation/Annotation;",
- ACC_VIRTUAL);
- getAnnotation->setNative();
-
- JavaMethod* getAnnotations =
- UPCALL_METHOD(loader, "java/lang/reflect/AccessibleObject",
- "getDeclaredAnnotations",
- "()[Ljava/lang/annotation/Annotation;",
- ACC_VIRTUAL);
- getAnnotations->setNative();
-
- JavaMethod* getBootPackages =
- UPCALL_METHOD(loader, "java/lang/VMClassLoader", "getBootPackages",
- "()[Ljava/lang/String;", ACC_STATIC);
- getBootPackages->setNative();
-
- //===----------------------------------------------------------------------===//
- //
- // To make classes non GC-allocated, we have to bypass the tracer functions of
- // java.lang.Class, java.lang.reflect.Field, java.lang.reflect.Method and
- // java.lang.reflect.constructor. The new tracer functions trace the classloader
- // instead of the class/field/method.
- //
- //===----------------------------------------------------------------------===//
-
- newClass->getVirtualVT()->setNativeTracer(
- (uintptr_t)nativeJavaObjectClassTracer,
- "nativeJavaObjectClassTracer");
-
- newConstructor->getVirtualVT()->setNativeTracer(
- (uintptr_t)nativeJavaObjectConstructorTracer,
- "nativeJavaObjectConstructorTracer");
-
- newMethod->getVirtualVT()->setNativeTracer(
- (uintptr_t)nativeJavaObjectMethodTracer,
- "nativeJavaObjectMethodTracer");
-
- newField->getVirtualVT()->setNativeTracer(
- (uintptr_t)nativeJavaObjectFieldTracer,
- "nativeJavaObjectFieldTracer");
-
- newVMThread->getVirtualVT()->setNativeTracer(
- (uintptr_t)nativeJavaObjectVMThreadTracer,
- "nativeJavaObjectVMThreadTracer");
-
- newVMThread->getVirtualVT()->setNativeDestructor(
- (uintptr_t)nativeJavaObjectVMThreadDestructor,
- "nativeJavaObjectVMThreadDestructor");
-
-
- newReference = UPCALL_CLASS(loader, "java/lang/ref/Reference");
-
- EnqueueReference =
- UPCALL_METHOD(loader, "java/lang/ref/Reference", "enqueue", "()Z",
- ACC_VIRTUAL);
-
- JavaMethod* initWeakReference =
- UPCALL_METHOD(loader, "java/lang/ref/WeakReference", "<init>",
- "(Ljava/lang/Object;)V",
- ACC_VIRTUAL);
- initWeakReference->setNative();
-
- initWeakReference =
- UPCALL_METHOD(loader, "java/lang/ref/WeakReference", "<init>",
- "(Ljava/lang/Object;Ljava/lang/ref/ReferenceQueue;)V",
- ACC_VIRTUAL);
- initWeakReference->setNative();
-
- JavaMethod* initSoftReference =
- UPCALL_METHOD(loader, "java/lang/ref/SoftReference", "<init>",
- "(Ljava/lang/Object;)V",
- ACC_VIRTUAL);
- initSoftReference->setNative();
-
- initSoftReference =
- UPCALL_METHOD(loader, "java/lang/ref/SoftReference", "<init>",
- "(Ljava/lang/Object;Ljava/lang/ref/ReferenceQueue;)V",
- ACC_VIRTUAL);
- initSoftReference->setNative();
-
- JavaMethod* initPhantomReference =
- UPCALL_METHOD(loader, "java/lang/ref/PhantomReference", "<init>",
- "(Ljava/lang/Object;Ljava/lang/ref/ReferenceQueue;)V",
- ACC_VIRTUAL);
- initPhantomReference->setNative();
-}
-
-#include "ClasspathConstructor.inc"
-#include "Classpath.inc"
-#include "ClasspathField.inc"
-#include "ClasspathMethod.inc"
-#include "ClasspathVMClass.inc"
-#include "ClasspathVMClassLoader.inc"
-#include "ClasspathVMObject.inc"
-#include "ClasspathVMRuntime.inc"
-#include "ClasspathVMStackWalker.inc"
-#include "ClasspathVMSystem.inc"
-#include "ClasspathVMSystemProperties.inc"
-#include "ClasspathVMThread.inc"
-#include "ClasspathVMThrowable.inc"
diff --git a/vmkit/lib/J3/Classpath/JavaUpcalls.h b/vmkit/lib/J3/Classpath/JavaUpcalls.h
deleted file mode 100644
index 04b646e..0000000
--- a/vmkit/lib/J3/Classpath/JavaUpcalls.h
+++ /dev/null
@@ -1,349 +0,0 @@
-//===---------- JavaUpcalls.h - Upcalls to Java entities ------------------===//
-//
-// The VMKit project
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#ifndef JNJVM_JAVA_UPCALLS_H
-#define JNJVM_JAVA_UPCALLS_H
-
-#include "mvm/Allocator.h"
-
-#include "JnjvmConfig.h"
-
-#define UPCALL_CLASS(vm, name) \
- vm->loadName(vm->asciizConstructUTF8(name), true, false, NULL)
-
-#define UPCALL_PRIMITIVE_CLASS(loader, name, nb) \
- new(loader->allocator, "Primitive class") \
- UserClassPrimitive(loader, loader->asciizConstructUTF8(name), nb) \
-
-#define UPCALL_FIELD(vm, cl, name, type, acc) \
- UPCALL_CLASS(vm, cl)->lookupFieldDontThrow(vm->asciizConstructUTF8(name), \
- vm->asciizConstructUTF8(type), \
- isStatic(acc), false, 0)
-
-#define UPCALL_METHOD(vm, cl, name, type, acc) \
- UPCALL_CLASS(vm, cl)->lookupMethodDontThrow(vm->asciizConstructUTF8(name), \
- vm->asciizConstructUTF8(type), \
- isStatic(acc), false, 0)
-
-#define UPCALL_ARRAY_CLASS(loader, name, depth) \
- loader->constructArray( \
- loader->constructArrayName(depth, loader->asciizConstructUTF8(name)))
-
-#define UPCALL_CLASS_EXCEPTION(loader, name) \
- name = UPCALL_CLASS(loader, "java/lang/"#name)
-
-#define UPCALL_REFLECT_CLASS_EXCEPTION(loader, name) \
- name = UPCALL_CLASS(loader, "java/lang/reflect/"#name)
-
-#define UPCALL_METHOD_EXCEPTION(loader, name) \
- Init##name = name->lookupMethodDontThrow(loader->asciizConstructUTF8("<init>"), \
- loader->asciizConstructUTF8("(Ljava/lang/String;)V"), \
- false, false, 0);
-
-#define UPCALL_METHOD_WITH_EXCEPTION(loader, name) \
- ErrorWithExcp##name = name->lookupMethodDontThrow(loader->asciizConstructUTF8("<init>"), \
- loader->asciizConstructUTF8("(Ljava/lang/Throwable;)V"), \
- false, false, 0);
-
-namespace j3 {
-
-class Jnjvm;
-class JavaField;
-class JavaMethod;
-class Class;
-class ClassArray;
-
-#if defined(__MACH__)
-#define SELF_HANDLE RTLD_DEFAULT
-#define DYLD_EXTENSION ".dylib"
-#else
-#define SELF_HANDLE 0
-#define DYLD_EXTENSION ".so"
-#endif
-
-class Classpath : public mvm::PermanentObject {
-public:
- Classpath(JnjvmBootstrapLoader* loader, bool dlLoad);
-
- void postInitialiseClasspath(JnjvmClassLoader* loader);
-
- UserClass* newClassLoader;
- JavaMethod* getSystemClassLoader;
- JavaMethod* setContextClassLoader;
- UserClass* newString;
- UserClass* newClass;
- UserClass* newThrowable;
- UserClass* newException;
- JavaMethod* initClass;
- JavaMethod* initClassWithProtectionDomain;
- JavaField* vmdataClass;
- JavaMethod* setProperty;
- JavaMethod* initString;
- JavaMethod* getCallingClassLoader;
- JavaMethod* initConstructor;
- UserClassArray* constructorArrayClass;
- UserClassArray* constructorArrayAnnotation;
- UserClass* newConstructor;
- JavaField* constructorSlot;
- JavaMethod* initMethod;
- JavaMethod* initField;
- UserClassArray* methodArrayClass;
- UserClassArray* fieldArrayClass;
- UserClass* newMethod;
- UserClass* newField;
- JavaField* methodSlot;
- JavaField* fieldSlot;
- UserClassArray* classArrayClass;
- JavaMethod* loadInClassLoader;
- JavaMethod* initVMThrowable;
- JavaField* vmDataVMThrowable;
- UserClass* newVMThrowable;
- JavaField* bufferAddress;
- JavaField* dataPointer32;
- JavaField* dataPointer64;
- UserClass* newPointer32;
- UserClass* newPointer64;
- UserClass* newDirectByteBuffer;
- JavaMethod* InitDirectByteBuffer;
- JavaField* vmdataClassLoader;
-
- JavaField* boolValue;
- JavaField* byteValue;
- JavaField* shortValue;
- JavaField* charValue;
- JavaField* intValue;
- JavaField* longValue;
- JavaField* floatValue;
- JavaField* doubleValue;
-
- UserClass* newStackTraceElement;
- UserClassArray* stackTraceArray;
- JavaMethod* initStackTraceElement;
-
- UserClass* voidClass;
- UserClass* boolClass;
- UserClass* byteClass;
- UserClass* shortClass;
- UserClass* charClass;
- UserClass* intClass;
- UserClass* floatClass;
- UserClass* doubleClass;
- UserClass* longClass;
-
- UserClass* vmStackWalker;
-
- UserClass* newThread;
- UserClass* newVMThread;
- JavaField* assocThread;
- JavaField* vmdataVMThread;
- JavaMethod* finaliseCreateInitialThread;
- JavaMethod* initVMThread;
- JavaMethod* runVMThread;
- JavaMethod* groupAddThread;
- JavaField* threadName;
- JavaField* groupName;
- JavaMethod* initGroup;
- JavaField* priority;
- JavaField* daemon;
- JavaField* group;
- JavaField* running;
- UserClass* threadGroup;
- JavaField* rootGroup;
- JavaField* vmThread;
- JavaMethod* uncaughtException;
- UserClass* inheritableThreadLocal;
-
-
- UserClass* InvocationTargetException;
- UserClass* ArrayStoreException;
- UserClass* ClassCastException;
- UserClass* IllegalMonitorStateException;
- UserClass* IllegalArgumentException;
- UserClass* InterruptedException;
- UserClass* IndexOutOfBoundsException;
- UserClass* ArrayIndexOutOfBoundsException;
- UserClass* NegativeArraySizeException;
- UserClass* NullPointerException;
- UserClass* SecurityException;
- UserClass* ClassFormatError;
- UserClass* ClassCircularityError;
- UserClass* NoClassDefFoundError;
- UserClass* UnsupportedClassVersionError;
- UserClass* NoSuchFieldError;
- UserClass* NoSuchMethodError;
- UserClass* InstantiationError;
- UserClass* InstantiationException;
- UserClass* IllegalAccessError;
- UserClass* IllegalAccessException;
- UserClass* VerifyError;
- UserClass* ExceptionInInitializerError;
- UserClass* LinkageError;
- UserClass* AbstractMethodError;
- UserClass* UnsatisfiedLinkError;
- UserClass* InternalError;
- UserClass* OutOfMemoryError;
- UserClass* StackOverflowError;
- UserClass* UnknownError;
- UserClass* ClassNotFoundException;
- UserClass* ArithmeticException;
-
- JavaMethod* InitInvocationTargetException;
- JavaMethod* InitArrayStoreException;
- JavaMethod* InitClassCastException;
- JavaMethod* InitIllegalMonitorStateException;
- JavaMethod* InitIllegalArgumentException;
- JavaMethod* InitInterruptedException;
- JavaMethod* InitIndexOutOfBoundsException;
- JavaMethod* InitArrayIndexOutOfBoundsException;
- JavaMethod* InitNegativeArraySizeException;
- JavaMethod* InitNullPointerException;
- JavaMethod* InitSecurityException;
- JavaMethod* InitClassFormatError;
- JavaMethod* InitClassCircularityError;
- JavaMethod* InitNoClassDefFoundError;
- JavaMethod* InitUnsupportedClassVersionError;
- JavaMethod* InitNoSuchFieldError;
- JavaMethod* InitNoSuchMethodError;
- JavaMethod* InitInstantiationError;
- JavaMethod* InitInstantiationException;
- JavaMethod* InitIllegalAccessError;
- JavaMethod* InitIllegalAccessException;
- JavaMethod* InitVerifyError;
- JavaMethod* InitExceptionInInitializerError;
- JavaMethod* InitLinkageError;
- JavaMethod* InitAbstractMethodError;
- JavaMethod* InitUnsatisfiedLinkError;
- JavaMethod* InitInternalError;
- JavaMethod* InitOutOfMemoryError;
- JavaMethod* InitStackOverflowError;
- JavaMethod* InitUnknownError;
- JavaMethod* InitClassNotFoundException;
- JavaMethod* InitArithmeticException;
-
- JavaMethod* SystemArraycopy;
- JavaMethod* VMSystemArraycopy;
- Class* SystemClass;
-
- JavaMethod* IntToString;
-
- JavaMethod* InitObject;
- JavaMethod* FinalizeObject;
-
- JavaMethod* ErrorWithExcpNoClassDefFoundError;
- JavaMethod* ErrorWithExcpExceptionInInitializerError;
- JavaMethod* ErrorWithExcpInvocationTargetException;
-
-
-
- UserClassArray* ArrayOfByte;
- UserClassArray* ArrayOfChar;
- UserClassArray* ArrayOfInt;
- UserClassArray* ArrayOfShort;
- UserClassArray* ArrayOfBool;
- UserClassArray* ArrayOfLong;
- UserClassArray* ArrayOfFloat;
- UserClassArray* ArrayOfDouble;
- UserClassArray* ArrayOfObject;
- UserClassArray* ArrayOfString;
-
- UserClassPrimitive* OfByte;
- UserClassPrimitive* OfChar;
- UserClassPrimitive* OfInt;
- UserClassPrimitive* OfShort;
- UserClassPrimitive* OfBool;
- UserClassPrimitive* OfLong;
- UserClassPrimitive* OfFloat;
- UserClassPrimitive* OfDouble;
- UserClassPrimitive* OfVoid;
-
- UserClass* OfObject;
-
- JavaField* methodClass;
- JavaField* fieldClass;
- JavaField* constructorClass;
-
- JavaMethod* EnqueueReference;
- Class* newReference;
-
- /// upcalls - Upcall classes, fields and methods so that C++ code can call
- /// Java code.
- ///
- Classpath* upcalls;
-
- /// InterfacesArray - The interfaces that array classes implement.
- ///
- UserClass** InterfacesArray;
-
- /// SuperArray - The super of array classes.
- UserClass* SuperArray;
-
- /// Lists of UTF8s used internaly in VMKit.
- const UTF8* NoClassDefFoundErrorName;
- const UTF8* initName;
- const UTF8* clinitName;
- const UTF8* clinitType;
- const UTF8* initExceptionSig;
- const UTF8* runName;
- const UTF8* prelib;
- const UTF8* postlib;
- const UTF8* mathName;
- const UTF8* stackWalkerName;
- const UTF8* abs;
- const UTF8* sqrt;
- const UTF8* sin;
- const UTF8* cos;
- const UTF8* tan;
- const UTF8* asin;
- const UTF8* acos;
- const UTF8* atan;
- const UTF8* atan2;
- const UTF8* exp;
- const UTF8* log;
- const UTF8* pow;
- const UTF8* ceil;
- const UTF8* floor;
- const UTF8* rint;
- const UTF8* cbrt;
- const UTF8* cosh;
- const UTF8* expm1;
- const UTF8* hypot;
- const UTF8* log10;
- const UTF8* log1p;
- const UTF8* sinh;
- const UTF8* tanh;
- const UTF8* finalize;
-
- /// primitiveMap - Map of primitive classes, hashed by id.
- std::map<const char, UserClassPrimitive*> primitiveMap;
-
- UserClassPrimitive* getPrimitiveClass(char id) {
- return primitiveMap[id];
- }
-
- /// arrayTable - Table of array classes.
- UserClassArray* arrayTable[8];
-
- UserClassArray* getArrayClass(unsigned id) {
- return arrayTable[id - 4];
- }
-
-private:
- void CreateJavaThread(Jnjvm* vm, JavaThread* myth,
- const char* name, JavaObject* Group);
-
-public:
- void InitializeThreading(Jnjvm* vm);
-
- void CreateForeignJavaThread(Jnjvm* vm, JavaThread* myth);
-};
-
-
-} // end namespace j3
-
-#endif
diff --git a/vmkit/lib/J3/Classpath/Makefile b/vmkit/lib/J3/Classpath/Makefile
deleted file mode 100644
index 24fd0d8..0000000
--- a/vmkit/lib/J3/Classpath/Makefile
+++ /dev/null
@@ -1,28 +0,0 @@
-##===- lib/JnJVM/Classpath/Makefile ------------------------*- Makefile -*-===##
-#
-# The vmkit project
-#
-# This file is distributed under the University of Illinois Open Source
-# License. See LICENSE.TXT for details.
-#
-##===----------------------------------------------------------------------===##
-LEVEL = ../../..
-
-
-EXTRA_DIST = ClasspathConstructor.inc ClasspathField.inc Classpath.inc ClasspathMethod.inc \
- ClasspathVMClass.inc ClasspathVMClassLoader.inc ClasspathVMObject.inc \
- ClasspathVMRuntime.inc ClasspathVMStackWalker.inc ClasspathVMSystem.inc \
- ClasspathVMSystemProperties.inc ClasspathVMThread.inc ClasspathVMThrowable.inc
-
-include $(LEVEL)/Makefile.config
-
-ifeq ($(WITH_LLVM_GCC), 1)
- MODULE_NAME = Classpath
-else
- LIBRARYNAME = Classpath
-endif
-
-include $(LEVEL)/Makefile.common
-
-CXX.Flags += -I$(PROJ_SRC_DIR)/../VMCore $(CLASSPATH_FLAGS)
-
diff --git a/vmkit/lib/J3/Compiler/ExceptionsCheck.inc b/vmkit/lib/J3/Compiler/ExceptionsCheck.inc
deleted file mode 100644
index 4338067..0000000
--- a/vmkit/lib/J3/Compiler/ExceptionsCheck.inc
+++ /dev/null
@@ -1,480 +0,0 @@
-Instruction* JavaJIT::invoke(Value *F, std::vector<llvm::Value*>& args,
- const char* Name,
- BasicBlock *InsertAtEnd) {
-
- Instruction* res = CallInst::Create(F, args.begin(), args.end(), Name,
- InsertAtEnd);
- DebugLoc DL = CreateLocation();
- res->setDebugLoc(DL);
-
- if (TheCompiler->hasExceptionsEnabled()) {
- Value* exceptionPtr = getPendingExceptionPtr(getMutatorThreadPtr());
-
- // Get the Java exception.
- Value* obj = 0;
-
- BasicBlock* ifNormal = createBasicBlock("no exception block");
-
- Value* test = 0;
- Constant* zero = intrinsics->JavaObjectNullConstant;
-
- // If F is a runtime intrinsic that does not access memory, use a hack
- // that will prevent LLVM from moving the exception check: runtime
- // intrinsics return the exception if an exception was raised.
- if (F == intrinsics->InitialisationCheckFunction ||
- F == intrinsics->GetConstantPoolAtFunction ||
- F == intrinsics->GetArrayClassFunction ||
- F == intrinsics->GetClassDelegateeFunction) {
- // Make the load volatile to force the instruction after the call.
- // Otherwise, LLVM will merge the load with a previous load because
- // the function is readnone.
- obj = new LoadInst(exceptionPtr, "", TheCompiler->useCooperativeGC(), currentBlock);
- test = new BitCastInst(res, intrinsics->JavaObjectType, "", currentBlock);
- test = new ICmpInst(*currentBlock, ICmpInst::ICMP_EQ, test, obj, "");
- Value* T = new ICmpInst(*currentBlock, ICmpInst::ICMP_NE, obj, zero, "");
- test = BinaryOperator::CreateAnd(test, T, "", currentBlock);
- } else {
- obj = new LoadInst(exceptionPtr, "", currentBlock);
- test = new ICmpInst(*currentBlock, ICmpInst::ICMP_NE, obj, zero, "");
- }
-
- BranchInst::Create(currentExceptionBlock, ifNormal, test, currentBlock);
-
-
- if (!currentExceptionBlock->empty()) {
- Instruction* insn = currentExceptionBlock->begin();
- PHINode* node = dyn_cast<PHINode>(insn);
- if (node) node->addIncoming(obj, currentBlock);
- }
-
- currentBlock = ifNormal;
- }
-
- return res;
-}
-
-Instruction* JavaJIT::invoke(Value *F, Value* arg1, const char* Name,
- BasicBlock *InsertAtEnd) {
-
- Instruction* res = CallInst::Create(F, arg1, Name, InsertAtEnd);
- DebugLoc DL = CreateLocation();
- res->setDebugLoc(DL);
-
- if (TheCompiler->hasExceptionsEnabled()) {
- Value* exceptionPtr = getPendingExceptionPtr(getMutatorThreadPtr());
-
- // Get the Java exception.
- Value* obj = 0;
-
- BasicBlock* ifNormal = createBasicBlock("no exception block");
-
- Value* test = 0;
- Constant* zero = intrinsics->JavaObjectNullConstant;
- if (F == intrinsics->InitialisationCheckFunction ||
- F == intrinsics->GetConstantPoolAtFunction ||
- F == intrinsics->GetArrayClassFunction ||
- F == intrinsics->GetClassDelegateeFunction) {
- obj = new LoadInst(exceptionPtr, "", TheCompiler->useCooperativeGC(), currentBlock);
- test = new BitCastInst(res, intrinsics->JavaObjectType, "", currentBlock);
- test = new ICmpInst(*currentBlock, ICmpInst::ICMP_EQ, test, obj, "");
- Value* T = new ICmpInst(*currentBlock, ICmpInst::ICMP_NE, obj, zero, "");
- test = BinaryOperator::CreateAnd(test, T, "", currentBlock);
- } else {
- obj = new LoadInst(exceptionPtr, "", currentBlock);
- test = new ICmpInst(*currentBlock, ICmpInst::ICMP_NE, obj, zero, "");
- }
-
- BranchInst::Create(currentExceptionBlock, ifNormal, test, currentBlock);
-
- if (!currentExceptionBlock->empty()) {
- Instruction* insn = currentExceptionBlock->begin();
- PHINode* node = dyn_cast<PHINode>(insn);
- if (node) node->addIncoming(obj, currentBlock);
- }
-
- currentBlock = ifNormal;
- }
-
- return res;
-}
-
-Instruction* JavaJIT::invoke(Value *F, Value* arg1, Value* arg2,
- const char* Name, BasicBlock *InsertAtEnd) {
-
- Value* args[2] = { arg1, arg2 };
-
- Instruction* res = CallInst::Create(F, args, args + 2, Name, InsertAtEnd);
- DebugLoc DL = CreateLocation();
- res->setDebugLoc(DL);
-
- if (TheCompiler->hasExceptionsEnabled()) {
- Value* exceptionPtr = getPendingExceptionPtr(getMutatorThreadPtr());
-
- // Get the Java exception.
- Value* obj = 0;
-
- BasicBlock* ifNormal = createBasicBlock("no exception block");
-
- Value* test = 0;
- Constant* zero = intrinsics->JavaObjectNullConstant;
- if (F == intrinsics->InitialisationCheckFunction ||
- F == intrinsics->GetConstantPoolAtFunction ||
- F == intrinsics->GetArrayClassFunction ||
- F == intrinsics->GetClassDelegateeFunction) {
- obj = new LoadInst(exceptionPtr, "", TheCompiler->useCooperativeGC(), currentBlock);
- test = new BitCastInst(res, intrinsics->JavaObjectType, "", currentBlock);
- test = new ICmpInst(*currentBlock, ICmpInst::ICMP_EQ, test, obj, "");
- Value* T = new ICmpInst(*currentBlock, ICmpInst::ICMP_NE, obj, zero, "");
- test = BinaryOperator::CreateAnd(test, T, "", currentBlock);
- } else {
- obj = new LoadInst(exceptionPtr, "", currentBlock);
- test = new ICmpInst(*currentBlock, ICmpInst::ICMP_NE, obj, zero, "");
- }
-
- BranchInst::Create(currentExceptionBlock, ifNormal, test, currentBlock);
-
- if (!currentExceptionBlock->empty()) {
- Instruction* insn = currentExceptionBlock->begin();
- PHINode* node = dyn_cast<PHINode>(insn);
- if (node) node->addIncoming(obj, currentBlock);
- }
-
- currentBlock = ifNormal;
- }
-
- return res;
-}
-
-Instruction* JavaJIT::invoke(Value *F, const char* Name,
- BasicBlock *InsertAtEnd) {
- Instruction* res = llvm::CallInst::Create(F, Name, InsertAtEnd);
- DebugLoc DL = CreateLocation();
- res->setDebugLoc(DL);
-
- if (TheCompiler->hasExceptionsEnabled()) {
- Value* exceptionPtr = getPendingExceptionPtr(getMutatorThreadPtr());
-
- // Get the Java exception.
- Value* obj = 0;
-
- BasicBlock* ifNormal = createBasicBlock("no exception block");
-
- Value* test = 0;
- Constant* zero = intrinsics->JavaObjectNullConstant;
- if (F == intrinsics->InitialisationCheckFunction ||
- F == intrinsics->GetConstantPoolAtFunction ||
- F == intrinsics->GetArrayClassFunction ||
- F == intrinsics->GetClassDelegateeFunction) {
- obj = new LoadInst(exceptionPtr, "", TheCompiler->useCooperativeGC(), currentBlock);
- test = new BitCastInst(res, intrinsics->JavaObjectType, "", currentBlock);
- test = new ICmpInst(*currentBlock, ICmpInst::ICMP_EQ, test, obj, "");
- Value* T = new ICmpInst(*currentBlock, ICmpInst::ICMP_NE, obj, zero, "");
- test = BinaryOperator::CreateAnd(test, T, "", currentBlock);
- } else {
- obj = new LoadInst(exceptionPtr, "", currentBlock);
- test = new ICmpInst(*currentBlock, ICmpInst::ICMP_NE, obj, zero, "");
- }
-
- BranchInst::Create(currentExceptionBlock, ifNormal, test, currentBlock);
-
- if (!currentExceptionBlock->empty()) {
- Instruction* insn = currentExceptionBlock->begin();
- PHINode* node = dyn_cast<PHINode>(insn);
- if (node) node->addIncoming(obj, currentBlock);
- }
-
- currentBlock = ifNormal;
- }
-
- return res;
-}
-
-void JavaJIT::throwException(llvm::Function* F, Value* arg1) {
- Instruction* obj = CallInst::Create(F, arg1, "", currentBlock);
- DebugLoc DL = CreateLocation();
- obj->setDebugLoc(DL);
-
- if (currentExceptionBlock != endExceptionBlock) {
- Instruction* insn = currentExceptionBlock->begin();
- PHINode* node = dyn_cast<PHINode>(insn);
- if (node) node->addIncoming(obj, currentBlock);
- BranchInst::Create(currentExceptionBlock, currentBlock);
- } else {
- if (endNode) {
- endNode->addIncoming(Constant::getNullValue(endNode->getType()),
- currentBlock);
- }
- BranchInst::Create(endBlock, currentBlock);
- }
-}
-
-void JavaJIT::throwException(Value* obj) {
- JITVerifyNull(obj);
- Value* exceptionPtr = getPendingExceptionPtr(getMutatorThreadPtr());
-
- new StoreInst(obj, exceptionPtr, currentBlock);
- if (currentExceptionBlock != endExceptionBlock) {
- Instruction* insn = currentExceptionBlock->begin();
- PHINode* node = dyn_cast<PHINode>(insn);
- if (node) node->addIncoming(obj, currentBlock);
- BranchInst::Create(currentExceptionBlock, currentBlock);
- } else {
- if (endNode) {
- endNode->addIncoming(Constant::getNullValue(endNode->getType()),
- currentBlock);
- }
- BranchInst::Create(endBlock, currentBlock);
- }
-}
-
-void JavaJIT::throwException(llvm::Function* F, Value** args,
- uint32 nbArgs) {
- Instruction* obj = CallInst::Create(F, args, args + nbArgs, "", currentBlock);
- DebugLoc DL = CreateLocation();
- obj->setDebugLoc(DL);
-
- if (currentExceptionBlock != endExceptionBlock) {
- Instruction* insn = currentExceptionBlock->begin();
- PHINode* node = dyn_cast<PHINode>(insn);
- if (node) node->addIncoming(obj, currentBlock);
- BranchInst::Create(currentExceptionBlock, currentBlock);
- } else {
- if (endNode) {
- endNode->addIncoming(Constant::getNullValue(endNode->getType()),
- currentBlock);
- }
- BranchInst::Create(endBlock, currentBlock);
- }
-}
-
-/// Handler - This class represents an exception handler. It is only needed
-/// when parsing the .class file in the JIT, therefore it is only defined
-/// here. The readExceptionTable function is the only function that makes
-/// use of this class.
-struct Handler {
-
- /// startpc - The bytecode number that begins the try clause.
- uint32 startpc;
-
- /// endpc - The bytecode number that ends the try clause.
- uint32 endpc;
-
- /// handlerpc - The bytecode number where the handler code starts.
- uint32 handlerpc;
-
- /// catche - Index in the constant pool of the exception class.
- uint16 catche;
-
- /// catchClass - The class of the exception: it must always be loaded before
- /// reading the exception table so that we do not throw an exception
- /// when compiling.
- UserClass* catchClass;
-
- /// tester - The basic block that tests if the exception is handled by this
- /// handler. If the handler is not the first of a list of handlers with the
- /// same range, than this block is the catcher block. Otherwise, it is the
- /// destination of the catcher block and of the handlers that do not handler
- /// the exception.
- llvm::BasicBlock* tester;
-
- /// javaHandler - The Java code that handles the exception. At this point, we
- /// know we have caught and are handling the exception. The Java exception
- /// object is the PHI node that begins this block.
- llvm::BasicBlock* javaHandler;
-
-};
-
-unsigned JavaJIT::readExceptionTable(Reader& reader, uint32 codeLen) {
-
- // This function uses currentBlock to simplify things. We save the current
- // value of currentBlock to restore it at the end of the function
- BasicBlock* temp = currentBlock;
-
- sint16 nbe = reader.readU2();
- sint16 sync = isSynchro(compilingMethod->access) ? 1 : 0;
- nbe += sync;
-
- mvm::ThreadAllocator allocator;
- // Loop over all handlers in the bytecode to initialize their values.
- Handler* handlers =
- (Handler*)allocator.Allocate(sizeof(Handler) * (nbe - sync));
- for (uint16 i = 0; i < nbe - sync; ++i) {
- Handler* ex = &handlers[i];
- ex->startpc = reader.readU2();
- ex->endpc = reader.readU2();
- ex->handlerpc = reader.readU2();
-
- ex->catche = reader.readU2();
-
- if (ex->catche) {
- UserClass* cl =
- (UserClass*)(compilingClass->ctpInfo->isClassLoaded(ex->catche));
- // When loading the class, we made sure that all exception classes
- // were loaded, so cl must have a value.
- assert(cl && "exception class has not been loaded");
- ex->catchClass = cl;
- } else {
- ex->catchClass = upcalls->newThrowable;
- }
-
- ex->tester = createBasicBlock("testException");
-
- // PHI Node for the exception object
- PHINode::Create(intrinsics->JavaObjectType, "", ex->tester);
-
- // Set the unwind destination of the instructions in the range of this
- // handler to the test block of the handler. If an instruction already has
- // a handler and thus is not the synchronize or regular end handler block,
- // leave it as-is.
- for (uint16 i = ex->startpc; i < ex->endpc; ++i) {
- if (opcodeInfos[i].exceptionBlock == endExceptionBlock) {
- opcodeInfos[i].exceptionBlock = ex->tester;
- }
- }
-
- // If the handler pc does not already have a block, create a new one.
- if (!(opcodeInfos[ex->handlerpc].newBlock)) {
- opcodeInfos[ex->handlerpc].newBlock = createBasicBlock("javaHandler");
- }
-
- // Set the Java handler for this exception.
- ex->javaHandler = opcodeInfos[ex->handlerpc].newBlock;
- opcodeInfos[ex->handlerpc].handler = true;
-
- if (ex->javaHandler->empty()) {
- PHINode::Create(intrinsics->JavaObjectType, "", ex->javaHandler);
- }
-
- }
-
- // Loop over all handlers to implement their tester.
- for (sint16 i = 0; i < nbe - sync; ++i) {
- Handler* cur = &handlers[i];
- BasicBlock* bbNext = 0;
- PHINode* javaNode = 0;
- currentExceptionBlock = opcodeInfos[cur->handlerpc].exceptionBlock;
-
- // Look out where we go if we're not the handler for the exception.
- if (i + 1 != nbe - sync) {
- Handler* next = &handlers[i + 1];
- if (!(cur->startpc >= next->startpc && cur->endpc <= next->endpc)) {
- // If there is no handler to go to (either one that has the same range
- // or one that contains the range), then we jump to the end handler.
- bbNext = endExceptionBlock;
- } else {
- // If there's a handler to goto, we jump to its tester block and record
- // the exception PHI node to give our exception to the tester.
- bbNext = next->tester;
- javaNode = dyn_cast<PHINode>(bbNext->begin());
- assert(javaNode);
- }
- } else {
- // If there's no handler after us, we jump to the end handler.
- bbNext = endExceptionBlock;
- }
-
- currentBlock = cur->tester;
-
- assert(cur->catchClass &&
- "Class not loaded when reading the exception table");
-
- Value* VTVar = TheCompiler->getVirtualTable(cur->catchClass->virtualVT);
-
- // Get the Java exception.
- Value* obj = currentBlock->begin();
-
- Value* objVT = CallInst::Create(intrinsics->GetVTFunction, obj, "",
- currentBlock);
-
- uint32 depth = cur->catchClass->virtualVT->depth;
- Value* depthCl = ConstantInt::get(Type::getInt32Ty(*llvmContext), depth);
- Value* cmp = 0;
-
- if (depth >= JavaVirtualTable::getDisplayLength()) {
- Value* classArgs[2] = { objVT, VTVar };
-
- cmp = CallInst::Create(intrinsics->IsSecondaryClassFunction,
- classArgs, classArgs + 2, "",
- currentBlock);
-
- } else {
-
- Value* inDisplay = CallInst::Create(intrinsics->GetDisplayFunction,
- objVT, "", currentBlock);
-
- Value* displayArgs[2] = { inDisplay, depthCl };
- Value* VTInDisplay = CallInst::Create(intrinsics->GetVTInDisplayFunction,
- displayArgs, displayArgs + 2, "",
- currentBlock);
-
- cmp = new ICmpInst(*currentBlock, ICmpInst::ICMP_EQ, VTInDisplay, VTVar,
- "");
- }
-
- // Add the Java exception in the phi node of the handler.
- Instruction* insn = cur->javaHandler->begin();
- PHINode* node = dyn_cast<PHINode>(insn);
- assert(node && "malformed exceptions");
- node->addIncoming(obj, currentBlock);
-
- // Add the Java exception in the phi node of the next block.
- if (javaNode)
- javaNode->addIncoming(obj, currentBlock);
-
- // If we are catching this exception, then jump to the Java Handler,
- // otherwise jump to our next handler.
- BranchInst::Create(cur->javaHandler, bbNext, cmp, currentBlock);
-
- currentBlock = cur->javaHandler;
-
- // First thing in the handler: clear the exception.
- Value* exceptionPtr = getPendingExceptionPtr(getMutatorThreadPtr());
-
- // Clear exceptions.
- new StoreInst(intrinsics->JavaObjectNullConstant, exceptionPtr,
- currentBlock);
-
- }
-
- // Restore currentBlock.
- currentBlock = temp;
- return nbe;
-}
-
-void JavaJIT::finishExceptions() {
- pred_iterator PI = pred_begin(endExceptionBlock);
- pred_iterator PE = pred_end(endExceptionBlock);
- if (PI == PE) {
- endExceptionBlock->eraseFromParent();
- } else {
- if (endNode) {
- endNode->addIncoming(Constant::getNullValue(endNode->getType()),
- endExceptionBlock);
- }
- BranchInst::Create(endBlock, endExceptionBlock);
- }
-
-
- PI = pred_begin(unifiedUnreachable);
- PE = pred_end(unifiedUnreachable);
- if (PI == PE) {
- unifiedUnreachable->eraseFromParent();
- } else {
- new UnreachableInst(*llvmContext, unifiedUnreachable);
- }
-
- for (Function::iterator BI = llvmFunction->begin(), BE = llvmFunction->end();
- BI != BE; BI++) {
- PI = pred_begin(BI);
- PE = pred_end(BI);
- if (PI == PE) {
- Instruction* insn = BI->begin();
- PHINode* node = dyn_cast<PHINode>(insn);
- if (node) {
- node->replaceAllUsesWith(Constant::getNullValue(node->getType()));
- node->eraseFromParent();
- }
- }
- }
-
-}
diff --git a/vmkit/lib/J3/Compiler/ExceptionsDwarf.inc b/vmkit/lib/J3/Compiler/ExceptionsDwarf.inc
deleted file mode 100644
index 0cbbb4c..0000000
--- a/vmkit/lib/J3/Compiler/ExceptionsDwarf.inc
+++ /dev/null
@@ -1,492 +0,0 @@
-Instruction* JavaJIT::invoke(Value *F, std::vector<llvm::Value*>& args,
- const char* Name,
- BasicBlock *InsertAtEnd) {
-
- // means: is there a handler for me?
- if (currentExceptionBlock != endExceptionBlock) {
- BasicBlock* ifNormal = createBasicBlock("no exception block");
- currentBlock = ifNormal;
- return llvm::InvokeInst::Create(F, ifNormal, currentExceptionBlock,
- args.begin(),
- args.end(), Name, InsertAtEnd);
- } else {
- return llvm::CallInst::Create(F, args.begin(), args.end(), Name, InsertAtEnd);
- }
-}
-
-Instruction* JavaJIT::invoke(Value *F, Value* arg1, const char* Name,
- BasicBlock *InsertAtEnd) {
-
- // means: is there a handler for me?
- if (currentExceptionBlock != endExceptionBlock) {
- BasicBlock* ifNormal = createBasicBlock("no exception block");
- currentBlock = ifNormal;
- Value* arg[1] = { arg1 };
- return InvokeInst::Create(F, ifNormal, currentExceptionBlock,
- arg, arg + 1, Name, InsertAtEnd);
- } else {
- return CallInst::Create(F, arg1, Name, InsertAtEnd);
- }
-}
-
-Instruction* JavaJIT::invoke(Value *F, Value* arg1, Value* arg2,
- const char* Name, BasicBlock *InsertAtEnd) {
-
- Value* args[2] = { arg1, arg2 };
-
- // means: is there a handler for me?
- if (currentExceptionBlock != endExceptionBlock) {
- BasicBlock* ifNormal = createBasicBlock("no exception block");
- currentBlock = ifNormal;
- return InvokeInst::Create(F, ifNormal, currentExceptionBlock,
- args, args + 2, Name, InsertAtEnd);
- } else {
- return CallInst::Create(F, args, args + 2, Name, InsertAtEnd);
- }
-}
-
-Instruction* JavaJIT::invoke(Value *F, const char* Name,
- BasicBlock *InsertAtEnd) {
- // means: is there a handler for me?
- if (currentExceptionBlock != endExceptionBlock) {
- BasicBlock* ifNormal = createBasicBlock("no exception block");
- currentBlock = ifNormal;
- Value* args[1];
- return llvm::InvokeInst::Create(F, ifNormal, currentExceptionBlock,
- args, args, Name,
- InsertAtEnd);
- } else {
- return llvm::CallInst::Create(F, Name, InsertAtEnd);
- }
-}
-
-void JavaJIT::throwException(llvm::Function* F, Value* arg1) {
- if (currentExceptionBlock != endExceptionBlock) {
- Value* exArgs[1] = { arg1 };
- InvokeInst::Create(F, unifiedUnreachable,
- currentExceptionBlock, exArgs, exArgs + 1,
- "", currentBlock);
- } else {
- CallInst::Create(F, arg1, "", currentBlock);
- new UnreachableInst(currentBlock);
- }
-}
-
-void JavaJIT::throwException(Value* obj) {
- Function* F = module->ThrowExceptionFunction;
- if (currentExceptionBlock != endExceptionBlock) {
- Value* exArgs[1] = { obj };
- InvokeInst::Create(F, unifiedUnreachable,
- currentExceptionBlock, exArgs, exArgs + 1,
- "", currentBlock);
- } else {
- CallInst::Create(F, obj, "", currentBlock);
- new UnreachableInst(currentBlock);
- }
-}
-
-void JavaJIT::throwException(llvm::Function* F, Value** args,
- uint32 nbArgs) {
- if (currentExceptionBlock != endExceptionBlock) {
- InvokeInst::Create(F, unifiedUnreachable,
- currentExceptionBlock, args, args + nbArgs,
- "", currentBlock);
- } else {
- CallInst::Create(F, args, args + nbArgs, "", currentBlock);
- new UnreachableInst(currentBlock);
- }
-}
-
-/// Handler - This class represents an exception handler. It is only needed
-/// when parsing the .class file in the JIT, therefore it is only defined
-/// here. The readExceptionTable function is the only function that makes
-/// use of this class.
-struct Handler {
-
- /// startpc - The bytecode number that begins the try clause.
- uint32 startpc;
-
- /// endpc - The bytecode number that ends the try clause.
- uint32 endpc;
-
- /// handlerpc - The bytecode number where the handler code starts.
- uint32 handlerpc;
-
- /// catche - Index in the constant pool of the exception class.
- uint16 catche;
-
- /// catchClass - The class of the exception: it must always be loaded before
- /// reading the exception table so that we do not throw an exception
- /// when compiling.
- UserClass* catchClass;
-
- /// catcher - The basic block that catches the exception. The catcher deals
- /// with LLVM codegen and declares the llvm.select method. This block is the
- /// destination of invoke instructions that are in the try clause.
- llvm::BasicBlock* catcher;
-
- /// tester - The basic block that tests if the exception is handled by this
- /// handler. If the handler is not the first of a list of handlers with the
- /// same range, than this block is the catcher block. Otherwise, it is the
- /// destination of the catcher block and of the handlers that do not handler
- /// the exception.
- llvm::BasicBlock* tester;
-
- /// javaHandler - The Java code that handles the exception. At this point, we
- /// know we have caught and are handling the exception. The Java exception
- /// object is the PHI node that begins this block.
- llvm::BasicBlock* javaHandler;
-
- /// nativeHandler - The CXX exception-related code that handles the exception.
- /// The block clears the exception from the execution environment, calls
- /// the CXX begin and end catch methods and jumps to the Java handler.
- llvm::BasicBlock* nativeHandler;
-
- /// exceptionPHI - The CXX exception object for the tester block. The
- /// tester has incoming blocks, either from the catcher or from other
- /// handlers that don't handle the exception. Therefore each incoming block
- /// specifies the CXX exception object that was caught.
- llvm::PHINode* exceptionPHI;
-};
-
-unsigned JavaJIT::readExceptionTable(Reader& reader, uint32 codeLen) {
-
- // This function uses currentBlock to simplify things. We save the current
- // value of currentBlock to restore it at the end of the function
- BasicBlock* temp = currentBlock;
-
- sint16 nbe = reader.readU2();
- sint16 sync = isSynchro(compilingMethod->access) ? 1 : 0;
- nbe += sync;
-
- // realEndExceptionBlock is the block where handlers will resume if
- // they don't treat the exception. realEndExceptionBlock does not
- // have to catch the exception.
- BasicBlock* realEndExceptionBlock = endExceptionBlock;
-
- // endExceptionBlockCatcher is the block where every instruction will
- // unwind.
- BasicBlock* endExceptionBlockCatcher = endExceptionBlock;
-
- if (sync) {
- // synchronizeExceptionBlock is the the block which will release the lock
- // on the object. trySynchronizeExceptionBlock is the block which will
- // catch the exception if one is thrown.
- BasicBlock* synchronizeExceptionBlock =
- createBasicBlock("synchronizeExceptionBlock");
- BasicBlock* trySynchronizeExceptionBlock =
- createBasicBlock("trySynchronizeExceptionBlock");
-
- // So synchronizeExceptionBlock becomes the block where every instructions
- // will unwind.
- realEndExceptionBlock = synchronizeExceptionBlock;
- endExceptionBlockCatcher = trySynchronizeExceptionBlock;
- Value* argsSync = 0;
- if (isVirtual(compilingMethod->access)) {
- argsSync = llvmFunction->arg_begin();
- } else {
- Value* cl = module->getJavaClass(compilingClass);
- argsSync = cl;
- }
-
- // In the synchronizeExceptionBlock: release the object and go to
- // endExceptionBlock, which will unwind the function.
-
- CallInst::Create(module->ReleaseObjectFunction, argsSync, "",
- synchronizeExceptionBlock);
-
- BranchInst::Create(endExceptionBlock, synchronizeExceptionBlock);
-
-
- // In the trySynchronizeExceptionBlock: catch the exception and move
- // to synchronizeExceptionBlock.
-
- const PointerType* PointerTy_0 = module->ptrType;
- Instruction* ptr_eh_ptr = CallInst::Create(module->llvmGetException,
- "eh_ptr",
- trySynchronizeExceptionBlock);
- Constant* C = ConstantExpr::getCast(Instruction::BitCast,
- module->personality, PointerTy_0);
- Value* int32_eh_select_params[3] =
- { ptr_eh_ptr, C, module->constantPtrNull };
- CallInst::Create(module->exceptionSelector, int32_eh_select_params,
- int32_eh_select_params + 3, "eh_select",
- trySynchronizeExceptionBlock);
-
- BranchInst::Create(synchronizeExceptionBlock,
- trySynchronizeExceptionBlock);
-
- // Now we can set the unwind destination of all instructions to
- // the exception catcher.
- for (uint16 i = 0; i < codeLen; ++i) {
- if (opcodeInfos[i].exceptionBlock == endExceptionBlock) {
- opcodeInfos[i].exceptionBlock = trySynchronizeExceptionBlock;
- }
- }
- }
-
- mvm::ThreadAllocator allocator;
- // Loop over all handlers in the bytecode to initialize their values.
- Handler* handlers = (Handler*)
- allocator.Allocate(sizeof(Handler) * (nbe - sync));
- for (uint16 i = 0; i < nbe - sync; ++i) {
- Handler* ex = &handlers[i];
- ex->startpc = reader.readU2();
- ex->endpc = reader.readU2();
- ex->handlerpc = reader.readU2();
-
- ex->catche = reader.readU2();
-
- if (ex->catche) {
- UserClass* cl =
- (UserClass*)(compilingClass->ctpInfo->isClassLoaded(ex->catche));
- // When loading the class, we made sure that all exception classes
- // were loaded, so cl must have a value.
- assert(cl && "exception class has not been loaded");
- ex->catchClass = cl;
- } else {
- ex->catchClass = upcalls->newThrowable;
- }
-
- ex->catcher = createBasicBlock("testException");
-
- // Set the unwind destination of the instructions in the range of this
- // handler to the test block of the handler. If an instruction already has
- // a handler and thus is not the synchronize or regular end handler block,
- // leave it as-is.
- for (uint16 i = ex->startpc; i < ex->endpc; ++i) {
- if (opcodeInfos[i].exceptionBlock == endExceptionBlockCatcher) {
- opcodeInfos[i].exceptionBlock = ex->catcher;
- }
- }
-
- // If the handler pc does not already have a block, create a new one.
- if (!(opcodeInfos[ex->handlerpc].newBlock)) {
- opcodeInfos[ex->handlerpc].newBlock = createBasicBlock("javaHandler");
- }
-
- // Set the Java handler for this exception.
- ex->javaHandler = opcodeInfos[ex->handlerpc].newBlock;
- opcodeInfos[ex->handlerpc].handler = true;
-
- // Set the native handler of this exception, which will catch the exception
- // object.
- ex->nativeHandler = createBasicBlock("nativeHandler");
- }
-
- // Loop over all handlers to know which ones have the same range. Handlers
- // with a same range all verify the exception's class, but only one catches
- // the exception. This is the reason why we have a tester block
- // and a catcher block: the first one tests the exception's class, and the
- // second one catches the exception.
- bool first = true;
- for (sint16 i = 0; i < nbe - sync; ++i) {
- Handler* cur = &handlers[i];
-
- // If we are the first handler, we must have one block for catching
- // the exception, and one block for comparing the exception. The former
- // is catcher and the latter is tester. Handlers that live in
- // the range of this handler will jump to tester because they
- // have already catched the exception. The other instructions in the range
- // of this handler will jump to catcher because the
- // exception still has to be catched.
- if (first) {
- cur->tester = createBasicBlock("realTestException");
- } else {
- cur->tester = cur->catcher;
- }
-
- // Set the exception as a phi node. This PHI has two types of incoming
- // nodes:
- // - Handlers within the range: they have already catched the exception
- // and verified its type. They are not the right handler for the
- // exception, so they jump to this handler
- // - The testException block of this handler (which is unique). It has
- // catched the exception and is now jumping to perform the test.
- cur->exceptionPHI = PHINode::Create(module->ptrType, "", cur->tester);
-
- // Look if the next handler has the same range or has a different range.
- // If it's in the same range, then no need to catch the exception.
- // Otherwise, it's a new range and we need to catch the exception.
- if (i + 1 != nbe - sync) {
- Handler* next = &handlers[i + 1];
-
- if (cur->startpc == next->startpc && cur->endpc == next->endpc) {
- first = false;
- } else {
- first = true;
- }
- }
- }
-
-
- // Loop over all handlers to implement their catcher and tester.
- for (sint16 i = 0; i < nbe - sync; ++i) {
- Handler* cur = &handlers[i];
- BasicBlock* bbNext = 0;
- PHINode* nodeNext = 0;
- currentExceptionBlock = opcodeInfos[cur->handlerpc].exceptionBlock;
-
- // Look out where we go if we're not the handler for the exception.
- if (i + 1 != nbe - sync) {
- Handler* next = &handlers[i + 1];
- if (!(cur->startpc >= next->startpc && cur->endpc <= next->endpc)) {
- // If there is no handler to go to (either one that has the same range
- // or one that contains the range), then we jump to the end handler.
- bbNext = realEndExceptionBlock;
- } else {
- // If there's a handler to goto, we jump to its tester block and record
- // the exception PHI node to give our exception to the tester.
- bbNext = next->tester;
- nodeNext = next->exceptionPHI;
- }
- } else {
- // If there's no handler after us, we jump to the end handler.
- bbNext = realEndExceptionBlock;
- }
-
- // If the tester and the catcher is not the same, then we must implement
- // the catcher. The catcher catches the exception, jumps to the tester
- // and gives the exception as an incoming node the the exceptionPHI.
- if (cur->tester != cur->catcher) {
- const PointerType* PointerTy_0 = module->ptrType;
- Instruction* ptr_eh_ptr =
- CallInst::Create(module->llvmGetException, "eh_ptr", cur->catcher);
- Constant* C = ConstantExpr::getCast(Instruction::BitCast,
- module->personality, PointerTy_0);
- Value* int32_eh_select_params[3] =
- { ptr_eh_ptr, C, module->constantPtrNull };
- llvm::CallInst::Create(module->exceptionSelector,
- int32_eh_select_params,
- int32_eh_select_params + 3, "eh_select",
- cur->catcher);
- llvm::BranchInst::Create(cur->tester, cur->catcher);
- cur->exceptionPHI->addIncoming(ptr_eh_ptr, cur->catcher);
- }
-
- currentBlock = cur->tester;
-
- Value* clVar = 0;
-
- // We know catchClass exists because we have loaded all exceptions catched
- // by the method when we loaded the class that defined this method.
- clVar = module->getNativeClass(cur->catchClass);
-
- if (clVar->getType() != module->JavaCommonClassType)
- clVar = new BitCastInst(clVar, module->JavaCommonClassType, "",
- currentBlock);
-
- Value* mutatorThreadId = getMutatorThreadPtr();
- Value* javaThreadId = getJavaThreadPtr(mutatorThreadId);
- Value* javaExceptionPtr = getGetJavaExceptionPtr(javaThreadId);
-
- // Get the Java exception.
- Value* obj = new LoadInst(javaExceptionPtr, "", currentBlock);
-
- Value* objCl = CallInst::Create(module->GetClassFunction, obj, "",
- currentBlock);
-
- Value* depthCl = ConstantInt::get(Type::Int32Ty, cur->catchClass->depth);
- Value* depthClObj = CallInst::Create(module->GetDepthFunction, objCl, "",
- currentBlock);
-
- // Compare the exception with the exception class we catch.
- Value* cmp = new ICmpInst(*currentBlock, ICmpInst::ICMP_ULE, depthCl,
- depthClObj, "");
-
- BasicBlock* supDepth = createBasicBlock("superior depth");
-
- BranchInst::Create(supDepth, bbNext, cmp, currentBlock);
-
- if (nodeNext)
- nodeNext->addIncoming(cur->exceptionPHI, currentBlock);
-
- currentBlock = supDepth;
- Value* inDisplay = CallInst::Create(module->GetDisplayFunction,
- objCl, "", currentBlock);
-
- Value* displayArgs[2] = { inDisplay, depthCl };
- Value* clInDisplay = CallInst::Create(module->GetClassInDisplayFunction,
- displayArgs, displayArgs + 2, "",
- currentBlock);
-
- cmp = new ICmpInst(*currentBlock, ICmpInst::ICMP_EQ, clInDisplay, clVar,
- "");
-
- // If we are catching this exception, then jump to the nativeHandler,
- // otherwise jump to our next handler.
- BranchInst::Create(cur->nativeHandler, bbNext, cmp, currentBlock);
-
- // Add the incoming value to the next handler, which is the exception we
- // just catched.
- if (nodeNext)
- nodeNext->addIncoming(cur->exceptionPHI, currentBlock);
-
- currentBlock = cur->nativeHandler;
-
- mutatorThreadId = getMutatorThreadPtr();
- javaThreadId = getJavaThreadPtr(mutatorThreadId);
- javaExceptionPtr = getGetJavaExceptionPtr(javaThreadId);
-
- // Get the Java exception.
- Value* exc = new LoadInst(javaExceptionPtr, "", currentBlock);
- Value* cxxExceptionPtr = getCXXExceptionPtr(mutatorThreadId);
-
- // Clear exceptions.
- new StoreInst(module->constantPtrNull, cxxExceptionPtr, currentBlock);
- new StoreInst(module->JavaObjectNullConstant, javaExceptionPtr,
- currentBlock);
-
- // Call the CXX begin and end catcher.
- CallInst::Create(module->exceptionBeginCatch, cur->exceptionPHI,
- "tmp8", cur->nativeHandler);
- CallInst::Create(module->exceptionEndCatch, "", cur->nativeHandler);
-
- // We can now jump to the Java handler!
- BranchInst::Create(cur->javaHandler, cur->nativeHandler);
-
- // If the Java handler is empty, create a PHI node that will contain the
- // exception and give our own.
- if (cur->javaHandler->empty()) {
- PHINode* node = PHINode::Create(JnjvmModule::JavaObjectType, "",
- cur->javaHandler);
- node->addIncoming(exc, cur->nativeHandler);
-
- } else {
- // If the Java handler is not empty, then the first instruction is the
- // PHI node. Give it our own.
- Instruction* insn = cur->javaHandler->begin();
- PHINode* node = dyn_cast<PHINode>(insn);
- assert(node && "malformed exceptions");
- node->addIncoming(exc, cur->nativeHandler);
- }
-
- }
-
- // Restore currentBlock.
- currentBlock = temp;
- return nbe;
-
-}
-
-void JavaJIT::finishExceptions() {
- pred_iterator PI = pred_begin(endExceptionBlock);
- pred_iterator PE = pred_end(endExceptionBlock);
- if (PI == PE) {
- endExceptionBlock->eraseFromParent();
- } else {
- Value* cxxExceptionPtr = getCXXExceptionPtr(getMutatorThreadPtr());
- Value* cxxException = new LoadInst(cxxExceptionPtr, "", currentBlock);
- llvm::CallInst::Create(module->unwindResume, cxxException, "", currentBlock);
- new UnreachableInst(currentBlock);
- }
-
- PI = pred_begin(unifiedUnreachable);
- PE = pred_end(unifiedUnreachable);
- if (PI == PE) {
- unifiedUnreachable->eraseFromParent();
- } else {
- new UnreachableInst(unifiedUnreachable);
- }
-
-}
diff --git a/vmkit/lib/J3/Compiler/J3Intrinsics.cpp b/vmkit/lib/J3/Compiler/J3Intrinsics.cpp
deleted file mode 100644
index 055033e..0000000
--- a/vmkit/lib/J3/Compiler/J3Intrinsics.cpp
+++ /dev/null
@@ -1,222 +0,0 @@
-//===------------- J3Intrinsics.cpp - Intrinsics for J3 -------------------===//
-//
-// The VMKit project
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#include "llvm/Constants.h"
-#include "llvm/DerivedTypes.h"
-#include "llvm/LLVMContext.h"
-#include "llvm/Module.h"
-
-#include "mvm/JIT.h"
-
-#include "JavaAccess.h"
-#include "JavaArray.h"
-#include "JavaClass.h"
-#include "JavaTypes.h"
-
-#include "j3/J3Intrinsics.h"
-#include "j3/LLVMInfo.h"
-
-using namespace j3;
-using namespace llvm;
-
-namespace j3 {
- namespace llvm_runtime {
- #include "LLVMRuntime.inc"
- }
-}
-
-J3Intrinsics::J3Intrinsics(llvm::Module* module) :
- BaseIntrinsics(module) {
- j3::llvm_runtime::makeLLVMModuleContents(module);
-
- LLVMContext& Context = module->getContext();
-
- ConstantPoolType = ptrPtrType;
-
- JavaObjectType =
- PointerType::getUnqual(module->getTypeByName("JavaObject"));
-
- JavaObjectPtrType = PointerType::getUnqual(JavaObjectType);
-
- JavaArrayType =
- PointerType::getUnqual(module->getTypeByName("JavaArray"));
-
- JavaCommonClassType =
- PointerType::getUnqual(module->getTypeByName("JavaCommonClass"));
- JavaClassPrimitiveType =
- PointerType::getUnqual(module->getTypeByName("JavaClassPrimitive"));
- JavaClassArrayType =
- PointerType::getUnqual(module->getTypeByName("JavaClassArray"));
- JavaClassType =
- PointerType::getUnqual(module->getTypeByName("JavaClass"));
-
- JavaArrayUInt8Type =
- PointerType::getUnqual(module->getTypeByName("ArrayUInt8"));
- JavaArraySInt8Type =
- PointerType::getUnqual(module->getTypeByName("ArraySInt8"));
- JavaArrayUInt16Type =
- PointerType::getUnqual(module->getTypeByName("ArrayUInt16"));
- JavaArraySInt16Type =
- PointerType::getUnqual(module->getTypeByName("ArraySInt16"));
- JavaArrayUInt32Type =
- PointerType::getUnqual(module->getTypeByName("ArrayUInt32"));
- JavaArraySInt32Type =
- PointerType::getUnqual(module->getTypeByName("ArraySInt32"));
- JavaArrayLongType =
- PointerType::getUnqual(module->getTypeByName("ArrayLong"));
- JavaArrayFloatType =
- PointerType::getUnqual(module->getTypeByName("ArrayFloat"));
- JavaArrayDoubleType =
- PointerType::getUnqual(module->getTypeByName("ArrayDouble"));
- JavaArrayObjectType =
- PointerType::getUnqual(module->getTypeByName("ArrayObject"));
-
- JavaFieldType =
- PointerType::getUnqual(module->getTypeByName("JavaField"));
- JavaMethodType =
- PointerType::getUnqual(module->getTypeByName("JavaMethod"));
- UTF8Type =
- PointerType::getUnqual(module->getTypeByName("UTF8"));
- AttributType =
- PointerType::getUnqual(module->getTypeByName("Attribut"));
- JavaThreadType =
- PointerType::getUnqual(module->getTypeByName("JavaThread"));
-
- CodeLineInfoType =
- PointerType::getUnqual(module->getTypeByName("CodeLineInfo"));
-
- JavaObjectNullConstant =
- Constant::getNullValue(J3Intrinsics::JavaObjectType);
- MaxArraySizeConstant = ConstantInt::get(Type::getInt32Ty(Context),
- JavaArray::MaxArraySize);
- JavaArraySizeConstant = ConstantInt::get(Type::getInt32Ty(Context),
- sizeof(JavaObject) + sizeof(ssize_t));
-
-
- JavaArrayElementsOffsetConstant = constantTwo;
- JavaArraySizeOffsetConstant = constantOne;
- JavaObjectLockOffsetConstant = constantOne;
- JavaObjectVTOffsetConstant = constantZero;
-
- OffsetClassInVTConstant =
- ConstantInt::get(Type::getInt32Ty(Context),
- JavaVirtualTable::getClassIndex());
- OffsetDepthInVTConstant =
- ConstantInt::get(Type::getInt32Ty(Context),
- JavaVirtualTable::getDepthIndex());
- OffsetDisplayInVTConstant =
- ConstantInt::get(Type::getInt32Ty(Context),
- JavaVirtualTable::getDisplayIndex());
- OffsetBaseClassVTInVTConstant =
- ConstantInt::get(Type::getInt32Ty(Context),
- JavaVirtualTable::getBaseClassIndex());
- OffsetIMTInVTConstant =
- ConstantInt::get(Type::getInt32Ty(Context),
- JavaVirtualTable::getIMTIndex());
-
- OffsetAccessInCommonClassConstant = constantOne;
- IsArrayConstant = ConstantInt::get(Type::getInt16Ty(Context),
- JNJVM_ARRAY);
-
- IsPrimitiveConstant = ConstantInt::get(Type::getInt16Ty(Context),
- JNJVM_PRIMITIVE);
-
- OffsetBaseClassInArrayClassConstant = constantOne;
- OffsetLogSizeInPrimitiveClassConstant = constantOne;
-
- OffsetObjectSizeInClassConstant = constantOne;
- OffsetVTInClassConstant = ConstantInt::get(Type::getInt32Ty(Context), 7);
- OffsetTaskClassMirrorInClassConstant = constantThree;
- OffsetStaticInstanceInTaskClassMirrorConstant = constantThree;
- OffsetStatusInTaskClassMirrorConstant = constantZero;
- OffsetInitializedInTaskClassMirrorConstant = constantOne;
-
- OffsetJNIInJavaThreadConstant = ConstantInt::get(Type::getInt32Ty(Context), 1);
-
- ClassReadyConstant = ConstantInt::get(Type::getInt8Ty(Context), ready);
-
- InterfaceLookupFunction = module->getFunction("j3InterfaceLookup");
- MultiCallNewFunction = module->getFunction("j3MultiCallNew");
- ForceLoadedCheckFunction = module->getFunction("forceLoadedCheck");
- InitialisationCheckFunction = module->getFunction("initialisationCheck");
- ForceInitialisationCheckFunction =
- module->getFunction("forceInitialisationCheck");
- InitialiseClassFunction = module->getFunction("j3RuntimeInitialiseClass");
-
- GetConstantPoolAtFunction = module->getFunction("getConstantPoolAt");
- ArrayLengthFunction = module->getFunction("arrayLength");
- GetVTFunction = module->getFunction("getVT");
- GetIMTFunction = module->getFunction("getIMT");
- GetClassFunction = module->getFunction("getClass");
- ClassLookupFunction = module->getFunction("j3ClassLookup");
- GetVTFromClassFunction = module->getFunction("getVTFromClass");
- GetVTFromClassArrayFunction = module->getFunction("getVTFromClassArray");
- GetVTFromCommonClassFunction = module->getFunction("getVTFromCommonClass");
- GetBaseClassVTFromVTFunction = module->getFunction("getBaseClassVTFromVT");
- GetObjectSizeFromClassFunction =
- module->getFunction("getObjectSizeFromClass");
-
- GetClassDelegateeFunction = module->getFunction("getClassDelegatee");
- RuntimeDelegateeFunction = module->getFunction("j3RuntimeDelegatee");
- IsAssignableFromFunction = module->getFunction("isAssignableFrom");
- IsSecondaryClassFunction = module->getFunction("isSecondaryClass");
- GetDepthFunction = module->getFunction("getDepth");
- GetStaticInstanceFunction = module->getFunction("getStaticInstance");
- GetDisplayFunction = module->getFunction("getDisplay");
- GetVTInDisplayFunction = module->getFunction("getVTInDisplay");
- AquireObjectFunction = module->getFunction("j3JavaObjectAquire");
- ReleaseObjectFunction = module->getFunction("j3JavaObjectRelease");
-
- VirtualFieldLookupFunction = module->getFunction("j3VirtualFieldLookup");
- StaticFieldLookupFunction = module->getFunction("j3StaticFieldLookup");
- StringLookupFunction = module->getFunction("j3StringLookup");
- StartJNIFunction = module->getFunction("j3StartJNI");
- EndJNIFunction = module->getFunction("j3EndJNI");
-
- ResolveVirtualStubFunction = module->getFunction("j3ResolveVirtualStub");
- ResolveStaticStubFunction = module->getFunction("j3ResolveStaticStub");
- ResolveSpecialStubFunction = module->getFunction("j3ResolveSpecialStub");
- ResolveInterfaceFunction = module->getFunction("j3ResolveInterface");
-
- NullPointerExceptionFunction =
- module->getFunction("j3NullPointerException");
- ClassCastExceptionFunction = module->getFunction("j3ClassCastException");
- IndexOutOfBoundsExceptionFunction =
- module->getFunction("j3IndexOutOfBoundsException");
- NegativeArraySizeExceptionFunction =
- module->getFunction("j3NegativeArraySizeException");
- OutOfMemoryErrorFunction = module->getFunction("j3OutOfMemoryError");
- StackOverflowErrorFunction = module->getFunction("j3StackOverflowError");
- ArrayStoreExceptionFunction = module->getFunction("j3ArrayStoreException");
- ArithmeticExceptionFunction = module->getFunction("j3ArithmeticException");
-
- PrintExecutionFunction = module->getFunction("j3PrintExecution");
- PrintMethodStartFunction = module->getFunction("j3PrintMethodStart");
- PrintMethodEndFunction = module->getFunction("j3PrintMethodEnd");
-
- ThrowExceptionFunction = module->getFunction("j3ThrowException");
-
- GetArrayClassFunction = module->getFunction("j3GetArrayClass");
-
- GetFinalInt8FieldFunction = module->getFunction("getFinalInt8Field");
- GetFinalInt16FieldFunction = module->getFunction("getFinalInt16Field");
- GetFinalInt32FieldFunction = module->getFunction("getFinalInt32Field");
- GetFinalLongFieldFunction = module->getFunction("getFinalLongField");
- GetFinalFloatFieldFunction = module->getFunction("getFinalFloatField");
- GetFinalDoubleFieldFunction = module->getFunction("getFinalDoubleField");
-
-#ifndef WITHOUT_VTABLE
- VirtualLookupFunction = module->getFunction("j3VirtualTableLookup");
-#endif
-
- GetLockFunction = module->getFunction("getLock");
- ThrowExceptionFromJITFunction =
- module->getFunction("j3ThrowExceptionFromJIT");
-
-}
diff --git a/vmkit/lib/J3/Compiler/JavaAOTCompiler.cpp b/vmkit/lib/J3/Compiler/JavaAOTCompiler.cpp
deleted file mode 100644
index ba20ddb..0000000
--- a/vmkit/lib/J3/Compiler/JavaAOTCompiler.cpp
+++ /dev/null
@@ -1,2199 +0,0 @@
-//===----- JavaAOTCompiler.cpp - Support for Ahead of Time Compiler --------===//
-//
-// The VMKit project
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#include "llvm/BasicBlock.h"
-#include "llvm/Constants.h"
-#include "llvm/Instructions.h"
-#include "llvm/LLVMContext.h"
-#include "llvm/Module.h"
-#include "llvm/PassManager.h"
-#include "llvm/Support/raw_ostream.h"
-
-#include "mvm/Threads/Thread.h"
-#include "mvm/VMKit.h"
-
-#include "j3/J3Intrinsics.h"
-#include "j3/JavaAOTCompiler.h"
-#include "j3/JavaJITCompiler.h"
-
-#include "JavaArray.h"
-#include "JavaConstantPool.h"
-#include "JavaString.h"
-#include "JavaThread.h"
-#include "JavaTypes.h"
-#include "JavaUpcalls.h"
-#include "Jnjvm.h"
-#include "Reader.h"
-#include "Zip.h"
-
-#include <cstdio>
-
-using namespace j3;
-using namespace llvm;
-
-bool JavaAOTCompiler::isCompiling(const CommonClass* cl) const {
- if (cl->isClass()) {
- // A class is being static compiled if owner class is not null.
- return cl->asClass()->getOwnerClass() != 0;
- } else if (cl->isArray()) {
- // Only compile an aray if we are compiling rt.jar.
- return compileRT;
- } else if (cl->isPrimitive() && compileRT) {
- return true;
- } else {
- return false;
- }
-}
-
-Constant* JavaAOTCompiler::getNativeClass(CommonClass* classDef) {
-
- if (classDef->isClass() || isCompiling(classDef) || assumeCompiled) {
-
- native_class_iterator End = nativeClasses.end();
- native_class_iterator I = nativeClasses.find(classDef);
- if (I == End) {
- const llvm::Type* Ty = 0;
-
- if (classDef->isArray()) {
- Ty = JavaIntrinsics.JavaClassArrayType->getContainedType(0);
- } else if (classDef->isPrimitive()) {
- Ty = JavaIntrinsics.JavaClassPrimitiveType->getContainedType(0);
- } else {
- Ty = JavaIntrinsics.JavaClassType->getContainedType(0);
- }
-
- GlobalVariable* varGV =
- new GlobalVariable(*getLLVMModule(), Ty, false,
- GlobalValue::ExternalLinkage, 0,
- UTF8Buffer(classDef->name).toCompileName()->cString());
-
- nativeClasses.insert(std::make_pair(classDef, varGV));
-
- if (classDef->isClass() && isCompiling(classDef)) {
- Constant* C = CreateConstantFromClass(classDef->asClass());
- varGV->setInitializer(C);
- } else if (classDef->isArray()) {
- Constant* C = CreateConstantFromClassArray(classDef->asArrayClass());
- varGV->setInitializer(C);
- } else if (classDef->isPrimitive()) {
- Constant* C =
- CreateConstantFromClassPrimitive(classDef->asPrimitiveClass());
- varGV->setInitializer(C);
- }
-
- return varGV;
-
- } else {
- return I->second;
- }
- } else if (classDef->isArray()) {
- array_class_iterator End = arrayClasses.end();
- array_class_iterator I = arrayClasses.find(classDef->asArrayClass());
- if (I == End) {
- const llvm::Type* Ty = JavaIntrinsics.JavaClassArrayType;
- Module& Mod = *getLLVMModule();
-
- GlobalVariable* varGV =
- new GlobalVariable(Mod, Ty, false, GlobalValue::InternalLinkage,
- Constant::getNullValue(Ty),
- UTF8Buffer(classDef->name).toCompileName()->cString());
-
- arrayClasses.insert(std::make_pair(classDef->asArrayClass(), varGV));
- return varGV;
- } else {
- return I->second;
- }
- } else {
- assert(0 && "Implement me");
- }
- return 0;
-}
-
-Constant* JavaAOTCompiler::getConstantPool(JavaConstantPool* ctp) {
- llvm::Constant* varGV = 0;
- constant_pool_iterator End = constantPools.end();
- constant_pool_iterator I = constantPools.find(ctp);
- if (I == End) {
- const Type* Ty = JavaIntrinsics.ConstantPoolType->getContainedType(0);
- Module& Mod = *getLLVMModule();
-
- varGV = new GlobalVariable(Mod, Ty, false,
- GlobalValue::InternalLinkage,
- Constant::getNullValue(Ty), "");
- constantPools.insert(std::make_pair(ctp, varGV));
- return varGV;
- } else {
- return I->second;
- }
-}
-
-Constant* JavaAOTCompiler::getMethodInClass(JavaMethod* meth) {
- Class* cl = meth->classDef;
- Constant* MOffset = 0;
- Constant* Array = 0;
-
- for (uint32 i = 0; i < cl->nbVirtualMethods + cl->nbStaticMethods; ++i) {
- if (&cl->virtualMethods[i] == meth) {
- MOffset = ConstantInt::get(Type::getInt32Ty(getLLVMContext()), i);
- break;
- }
- }
- assert(MOffset && "No offset for method");
-
- method_iterator SI = virtualMethods.find(cl);
- if (SI != virtualMethods.end()) {
- Array = SI->second;
- assert(Array && "No array in class");
- } else {
- std::string name(UTF8Buffer(cl->name).toCompileName()->cString());
- name += "_VirtualMethods";
- Module& Mod = *getLLVMModule();
- const Type* ATy =
- ArrayType::get(JavaIntrinsics.JavaMethodType->getContainedType(0),
- cl->nbVirtualMethods + cl->nbStaticMethods);
-
- Array = new GlobalVariable(Mod, ATy, false, GlobalValue::ExternalLinkage,
- 0, name);
- virtualMethods.insert(std::make_pair(cl, Array));
- }
-
- Constant* GEPs[2] = { getIntrinsics()->constantZero, MOffset };
- return ConstantExpr::getGetElementPtr(Array, GEPs, 2);
-}
-
-Constant* JavaAOTCompiler::getString(JavaString* str) {
- assert(!useCooperativeGC());
- string_iterator SI = strings.find(str);
- if (SI != strings.end()) {
- return SI->second;
- } else {
- assert(str && "No string given");
- LLVMClassInfo* LCI = getClassInfo(JavaObject::getClass(str)->asClass());
- const llvm::Type* Ty = LCI->getVirtualType();
- Module& Mod = *getLLVMModule();
-
- const char* name = JavaString::strToAsciiz(str);
- GlobalVariable* varGV =
- new GlobalVariable(Mod, Ty->getContainedType(0), false,
- GlobalValue::ExternalLinkage, 0, "str");
- delete[] name;
- Constant* res = ConstantExpr::getCast(Instruction::BitCast, varGV,
- JavaIntrinsics.JavaObjectType);
- strings.insert(std::make_pair(str, res));
- Constant* C = CreateConstantFromJavaString(str);
- varGV->setInitializer(C);
- return res;
- }
-}
-
-Constant* JavaAOTCompiler::getStringPtr(JavaString** str) {
- fprintf(stderr, "Implement me");
- abort();
-}
-
-Constant* JavaAOTCompiler::getJavaClass(CommonClass* cl) {
- java_class_iterator End = javaClasses.end();
- java_class_iterator I = javaClasses.find(cl);
- if (I == End) {
- final_object_iterator End = finalObjects.end();
- final_object_iterator I = finalObjects.find(cl->delegatee[0]);
- if (I == End) {
-
- Class* javaClass = cl->classLoader->vm->upcalls->newClass;
- LLVMClassInfo* LCI = getClassInfo(javaClass);
- const llvm::Type* Ty = LCI->getVirtualType();
- Module& Mod = *getLLVMModule();
-
- GlobalVariable* varGV =
- new GlobalVariable(Mod, Ty->getContainedType(0), false,
- GlobalValue::InternalLinkage, 0, "");
-
- Constant* res = ConstantExpr::getCast(Instruction::BitCast, varGV,
- JavaIntrinsics.JavaObjectType);
-
- javaClasses.insert(std::make_pair(cl, res));
- varGV->setInitializer(CreateConstantFromJavaClass(cl));
- return res;
- } else {
- return I->second;
- }
- } else {
- return I->second;
- }
-}
-
-Constant* JavaAOTCompiler::getJavaClassPtr(CommonClass* cl) {
- // Make sure it's emitted.
- getJavaClass(cl);
-
- Constant* Cl = getNativeClass(cl);
- Cl = ConstantExpr::getBitCast(Cl, JavaIntrinsics.JavaCommonClassType);
-
- Constant* GEP[2] = { getIntrinsics()->constantZero,
- getIntrinsics()->constantZero };
-
- Constant* TCMArray = ConstantExpr::getGetElementPtr(Cl, GEP, 2);
-
- Constant* GEP2[2] = { getIntrinsics()->constantZero,
- getIntrinsics()->constantZero };
-
- Constant* Ptr = ConstantExpr::getGetElementPtr(TCMArray, GEP2, 2);
- return Ptr;
-}
-
-JavaObject* JavaAOTCompiler::getFinalObject(llvm::Value* obj) {
- if (Constant* CI = dyn_cast<Constant>(obj)) {
- reverse_final_object_iterator End = reverseFinalObjects.end();
- reverse_final_object_iterator I = reverseFinalObjects.find(CI);
- if (I != End) return I->second;
- }
-
- return 0;
-}
-
-Constant* JavaAOTCompiler::HandleMagic(JavaObject* obj, CommonClass* objCl) {
-
- static const UTF8* AddressArray = objCl->classLoader->asciizConstructUTF8("org/vmmagic/unboxed/AddressArray");
- static const UTF8* WordArray = objCl->classLoader->asciizConstructUTF8("org/vmmagic/unboxed/WordArray");
- static const UTF8* ExtentArray = objCl->classLoader->asciizConstructUTF8("org/vmmagic/unboxed/ExtentArray");
- static const UTF8* ObjectReferenceArray = objCl->classLoader->asciizConstructUTF8("org/vmmagic/unboxed/ObjectReferenceArray");
- static const UTF8* OffsetArray = objCl->classLoader->asciizConstructUTF8("org/vmmagic/unboxed/OffsetArray");
- const UTF8* name = objCl->name;
-
- if (name->equals(AddressArray) || name->equals(WordArray) ||
- name->equals(ExtentArray) || name->equals(ObjectReferenceArray) ||
- name->equals(OffsetArray)) {
-
- intptr_t* realObj = (intptr_t*)obj;
- intptr_t size = realObj[0];
-
- const ArrayType* ATy = ArrayType::get(JavaIntrinsics.JavaObjectType,
- size + 1);
-
- std::vector<Constant*> Vals;
- for (sint32 i = 0; i < size + 1; ++i) {
- Constant* CI = ConstantInt::get(Type::getInt64Ty(getLLVMContext()),
- uint64_t(realObj[i]));
- CI = ConstantExpr::getIntToPtr(CI, JavaIntrinsics.JavaObjectType);
- Vals.push_back(CI);
- }
-
- Constant* CA = ConstantArray::get(ATy, Vals);
-
- GlobalVariable* varGV = new GlobalVariable(*getLLVMModule(), CA->getType(),
- false,
- GlobalValue::InternalLinkage,
- CA, "");
-
- return ConstantExpr::getBitCast(varGV, JavaIntrinsics.JavaObjectType);
-
- } else {
- Constant* CI = ConstantInt::get(Type::getInt64Ty(getLLVMContext()),
- uint64_t(obj));
- CI = ConstantExpr::getIntToPtr(CI, JavaIntrinsics.JavaObjectType);
- return CI;
- }
-}
-
-
-Constant* JavaAOTCompiler::getFinalObject(JavaObject* obj, CommonClass* objCl) {
- assert(!useCooperativeGC());
- llvm::GlobalVariable* varGV = 0;
- final_object_iterator End = finalObjects.end();
- final_object_iterator I = finalObjects.find(obj);
- if (I == End) {
-
- if (mvm::Collector::begOf(obj)) {
- const Type* Ty = 0;
- CommonClass* cl = JavaObject::getClass(obj);
-
- if (cl->isArray()) {
- Classpath* upcalls = cl->classLoader->vm->upcalls;
- CommonClass* subClass = cl->asArrayClass()->baseClass();
- if (subClass->isPrimitive()) {
- if (subClass == upcalls->OfBool) {
- Ty = Type::getInt8Ty(getLLVMContext());
- } else if (subClass == upcalls->OfByte) {
- Ty = Type::getInt8Ty(getLLVMContext());
- } else if (subClass == upcalls->OfShort) {
- Ty = Type::getInt16Ty(getLLVMContext());
- } else if (subClass == upcalls->OfChar) {
- Ty = Type::getInt16Ty(getLLVMContext());
- } else if (subClass == upcalls->OfInt) {
- Ty = Type::getInt32Ty(getLLVMContext());
- } else if (subClass == upcalls->OfFloat) {
- Ty = Type::getFloatTy(getLLVMContext());
- } else if (subClass == upcalls->OfLong) {
- Ty = Type::getInt64Ty(getLLVMContext());
- } else if (subClass == upcalls->OfDouble) {
- Ty = Type::getDoubleTy(getLLVMContext());
- } else {
- abort();
- }
- } else {
- Ty = JavaIntrinsics.JavaObjectType;
- }
-
- std::vector<const Type*> Elemts;
- const ArrayType* ATy = ArrayType::get(Ty, JavaArray::getSize(obj));
- Elemts.push_back(JavaIntrinsics.JavaObjectType->getContainedType(0));
- Elemts.push_back(JavaIntrinsics.pointerSizeType);
- Elemts.push_back(ATy);
- Ty = StructType::get(getLLVMModule()->getContext(), Elemts);
-
- } else {
- LLVMClassInfo* LCI = getClassInfo(cl->asClass());
- Ty = LCI->getVirtualType()->getContainedType(0);
- }
-
- Module& Mod = *getLLVMModule();
- // Set as External, so that inlining MMTk code works.
- varGV = new GlobalVariable(Mod, Ty, false, GlobalValue::ExternalLinkage,
- 0, "finalObject");
-
- Constant* C = ConstantExpr::getBitCast(varGV,
- JavaIntrinsics.JavaObjectType);
-
- finalObjects.insert(std::make_pair(obj, C));
- reverseFinalObjects.insert(std::make_pair(C, obj));
-
- varGV->setInitializer(CreateConstantFromJavaObject(obj));
- return C;
- } else {
- Constant* CI = HandleMagic(obj, objCl);
- finalObjects.insert(std::make_pair(obj, CI));
- return CI;
- }
- } else {
- return I->second;
- }
-}
-
-Constant* JavaAOTCompiler::CreateConstantFromStaticInstance(Class* cl) {
- LLVMClassInfo* LCI = getClassInfo(cl);
- const Type* Ty = LCI->getStaticType();
- const StructType* STy = dyn_cast<StructType>(Ty->getContainedType(0));
-
- std::vector<Constant*> Elts;
-
- for (uint32 i = 0; i < cl->nbStaticFields; ++i) {
- JavaField& field = cl->staticFields[i];
- const Typedef* type = field.getSignature();
- LLVMAssessorInfo& LAI = getTypedefInfo(type);
- const Type* Ty = LAI.llvmType;
-
- Attribut* attribut = field.lookupAttribut(Attribut::constantAttribut);
-
- if (!attribut) {
- if (cl->getStaticInstance() != NULL) {
- if (type->isPrimitive()) {
- const PrimitiveTypedef* prim = (const PrimitiveTypedef*)type;
- if (prim->isBool() || prim->isByte()) {
- ConstantInt* CI = ConstantInt::get(
- Type::getInt8Ty(getLLVMContext()),
- field.getStaticInt8Field());
- Elts.push_back(CI);
- } else if (prim->isShort() || prim->isChar()) {
- ConstantInt* CI = ConstantInt::get(
- Type::getInt16Ty(getLLVMContext()),
- field.getStaticInt16Field());
- Elts.push_back(CI);
- } else if (prim->isInt()) {
- ConstantInt* CI = ConstantInt::get(
- Type::getInt32Ty(getLLVMContext()),
- field.getStaticInt32Field());
- Elts.push_back(CI);
- } else if (prim->isLong()) {
- ConstantInt* CI = ConstantInt::get(
- Type::getInt64Ty(getLLVMContext()),
- field.getStaticLongField());
- Elts.push_back(CI);
- } else if (prim->isFloat()) {
- Constant* CF = ConstantFP::get(
- Type::getFloatTy(getLLVMContext()),
- field.getStaticFloatField());
- Elts.push_back(CF);
- } else if (prim->isDouble()) {
- Constant* CF = ConstantFP::get(
- Type::getDoubleTy(getLLVMContext()),
- field.getStaticDoubleField());
- Elts.push_back(CF);
- } else {
- abort();
- }
- } else {
- JavaObject* val = field.getStaticObjectField();
- if (val) {
- JnjvmClassLoader* JCL = cl->classLoader;
- CommonClass* FieldCl = field.getSignature()->assocClass(JCL);
- Constant* CO = getFinalObject(val, FieldCl);
- Elts.push_back(CO);
- } else {
- Elts.push_back(Constant::getNullValue(Ty));
- }
- }
- } else {
- Elts.push_back(Constant::getNullValue(Ty));
- }
- } else {
- Reader reader(attribut, cl->bytes);
- JavaConstantPool * ctpInfo = cl->ctpInfo;
- uint16 idx = reader.readU2();
- if (type->isPrimitive()) {
- if (Ty == Type::getInt64Ty(getLLVMContext())) {
- Elts.push_back(ConstantInt::get(Ty, (uint64)ctpInfo->LongAt(idx)));
- } else if (Ty == Type::getDoubleTy(getLLVMContext())) {
- Elts.push_back(ConstantFP::get(Ty, ctpInfo->DoubleAt(idx)));
- } else if (Ty == Type::getFloatTy(getLLVMContext())) {
- Elts.push_back(ConstantFP::get(Ty, ctpInfo->FloatAt(idx)));
- } else {
- Elts.push_back(ConstantInt::get(Ty, (uint64)ctpInfo->IntegerAt(idx)));
- }
- } else if (type->isReference()){
- const UTF8* utf8 = ctpInfo->UTF8At(ctpInfo->ctpDef[idx]);
- JavaString* obj = ctpInfo->resolveString(utf8, idx);
- Constant* C = getString(obj);
- C = ConstantExpr::getBitCast(C, JavaIntrinsics.JavaObjectType);
- Elts.push_back(C);
- } else {
- fprintf(stderr, "Implement me");
- abort();
- }
- }
- }
-
- return ConstantStruct::get(STy, Elts);
-}
-
-Constant* JavaAOTCompiler::getStaticInstance(Class* classDef) {
- static_instance_iterator End = staticInstances.end();
- static_instance_iterator I = staticInstances.find(classDef);
- if (I == End) {
-
- LLVMClassInfo* LCI = getClassInfo(classDef);
- const Type* Ty = LCI->getStaticType();
- Ty = Ty->getContainedType(0);
- std::string name(UTF8Buffer(classDef->name).toCompileName()->cString());
- name += "_static";
- Module& Mod = *getLLVMModule();
- GlobalVariable* varGV =
- new GlobalVariable(Mod, Ty, false, GlobalValue::ExternalLinkage,
- 0, name);
-
- Constant* res = ConstantExpr::getCast(Instruction::BitCast, varGV,
- JavaIntrinsics.ptrType);
- staticInstances.insert(std::make_pair(classDef, res));
-
- if (isCompiling(classDef)) {
- Constant* C = CreateConstantFromStaticInstance(classDef);
- varGV->setInitializer(C);
- }
-
- return res;
- } else {
- return I->second;
- }
-}
-
-Constant* JavaAOTCompiler::getVirtualTable(JavaVirtualTable* VT) {
- CommonClass* classDef = VT->cl;
- uint32 size = 0;
- if (classDef->isClass()) {
- LLVMClassInfo* LCI = getClassInfo(classDef->asClass());
- LCI->getVirtualType();
- size = classDef->asClass()->virtualTableSize;
- } else {
- size = JavaVirtualTable::getBaseSize();
- }
- llvm::Constant* res = 0;
- virtual_table_iterator End = virtualTables.end();
- virtual_table_iterator I = virtualTables.find(VT);
- if (I == End) {
-
- const ArrayType* ATy =
- dyn_cast<ArrayType>(JavaIntrinsics.VTType->getContainedType(0));
- const PointerType* PTy = dyn_cast<PointerType>(ATy->getContainedType(0));
- ATy = ArrayType::get(PTy, size);
- std::string name(UTF8Buffer(classDef->name).toCompileName()->cString());
- name += "_VT";
- // Do not set a virtual table as a constant, because the runtime may
- // modify it.
- Module& Mod = *getLLVMModule();
- GlobalVariable* varGV = new GlobalVariable(Mod, ATy, false,
- GlobalValue::ExternalLinkage,
- 0, name);
-
- res = ConstantExpr::getCast(Instruction::BitCast, varGV,
- JavaIntrinsics.VTType);
- virtualTables.insert(std::make_pair(VT, res));
-
- if (isCompiling(classDef) || assumeCompiled) {
- Constant* C = CreateConstantFromVT(VT);
- varGV->setInitializer(C);
- }
-
- return res;
- } else {
- return I->second;
- }
-}
-
-Constant* JavaAOTCompiler::getNativeFunction(JavaMethod* meth, void* ptr) {
- llvm::Constant* varGV = 0;
- native_function_iterator End = nativeFunctions.end();
- native_function_iterator I = nativeFunctions.find(meth);
- if (I == End) {
-
- LLVMSignatureInfo* LSI = getSignatureInfo(meth->getSignature());
- const llvm::Type* valPtrType = LSI->getNativePtrType();
-
- Module& Mod = *getLLVMModule();
- varGV = new GlobalVariable(Mod, valPtrType, false,
- GlobalValue::InternalLinkage,
- Constant::getNullValue(valPtrType), "");
-
- nativeFunctions.insert(std::make_pair(meth, varGV));
- return varGV;
- } else {
- return I->second;
- }
-}
-
-Constant* JavaAOTCompiler::CreateConstantForBaseObject(CommonClass* cl) {
- const StructType* STy =
- dyn_cast<StructType>(JavaIntrinsics.JavaObjectType->getContainedType(0));
-
- std::vector<Constant*> Elmts;
-
- // VT
- Elmts.push_back(getVirtualTable(cl->virtualVT));
-
- // lock
- Constant* L = ConstantInt::get(Type::getInt64Ty(getLLVMContext()), 0);
- Elmts.push_back(ConstantExpr::getIntToPtr(L, JavaIntrinsics.ptrType));
-
- return ConstantStruct::get(STy, Elmts);
-}
-
-Constant* JavaAOTCompiler::CreateConstantFromJavaClass(CommonClass* cl) {
- Class* javaClass = cl->classLoader->vm->upcalls->newClass;
- LLVMClassInfo* LCI = getClassInfo(javaClass);
- const StructType* STy =
- dyn_cast<StructType>(LCI->getVirtualType()->getContainedType(0));
-
- std::vector<Constant*> Elmts;
-
- // JavaObject
- Elmts.push_back(CreateConstantForBaseObject(javaClass));
-
- // signers
- Elmts.push_back(Constant::getNullValue(JavaIntrinsics.JavaObjectType));
-
- // pd
- Elmts.push_back(Constant::getNullValue(JavaIntrinsics.JavaObjectType));
-
- // vmdata
- Constant* Cl = getNativeClass(cl);
- Cl = ConstantExpr::getCast(Instruction::BitCast, Cl,
- JavaIntrinsics.JavaObjectType);
- Elmts.push_back(Cl);
-
- // constructor
- Elmts.push_back(Constant::getNullValue(JavaIntrinsics.JavaObjectType));
-
- return ConstantStruct::get(STy, Elmts);
-}
-
-Constant* JavaAOTCompiler::CreateConstantFromJavaObject(JavaObject* obj) {
- CommonClass* cl = JavaObject::getClass(obj);
-
- if (cl->isArray()) {
- Classpath* upcalls = cl->classLoader->vm->upcalls;
- CommonClass* subClass = cl->asArrayClass()->baseClass();
- if (subClass->isPrimitive()) {
- if (subClass == upcalls->OfBool) {
- return CreateConstantFromIntArray<ArrayUInt8>((ArrayUInt8*)obj,
- Type::getInt8Ty(getLLVMContext()));
- } else if (subClass == upcalls->OfByte) {
- return CreateConstantFromIntArray<ArraySInt8>((ArraySInt8*)obj,
- Type::getInt8Ty(getLLVMContext()));
- } else if (subClass == upcalls->OfShort) {
- return CreateConstantFromIntArray<ArraySInt16>((ArraySInt16*)obj,
- Type::getInt16Ty(getLLVMContext()));
- } else if (subClass == upcalls->OfChar) {
- return CreateConstantFromIntArray<ArrayUInt16>((ArrayUInt16*)obj,
- Type::getInt16Ty(getLLVMContext()));
- } else if (subClass == upcalls->OfInt) {
- return CreateConstantFromIntArray<ArraySInt32>((ArraySInt32*)obj,
- Type::getInt32Ty(getLLVMContext()));
- } else if (subClass == upcalls->OfFloat) {
- return CreateConstantFromFPArray<ArrayFloat>((ArrayFloat*)obj,
- Type::getFloatTy(getLLVMContext()));
- } else if (subClass == upcalls->OfLong) {
- return CreateConstantFromIntArray<ArrayLong>((ArrayLong*)obj,
- Type::getInt64Ty(getLLVMContext()));
- } else if (subClass == upcalls->OfDouble) {
- return CreateConstantFromFPArray<ArrayDouble>((ArrayDouble*)obj,
- Type::getDoubleTy(getLLVMContext()));
- } else {
- abort();
- }
- } else {
- return CreateConstantFromObjectArray((ArrayObject*)obj);
- }
- } else {
-
- std::vector<Constant*> Elmts;
-
- // JavaObject
- Constant* CurConstant =
- CreateConstantForBaseObject(JavaObject::getClass(obj));
-
- for (uint32 j = 1; j <= cl->virtualVT->depth; ++j) {
- std::vector<Constant*> TempElts;
- Elmts.push_back(CurConstant);
- TempElts.push_back(CurConstant);
- Class* curCl = cl->virtualVT->display[j]->cl->asClass();
- LLVMClassInfo* LCI = getClassInfo(curCl);
- const StructType* STy =
- dyn_cast<StructType>(LCI->getVirtualType()->getContainedType(0));
-
- for (uint32 i = 0; i < curCl->nbVirtualFields; ++i) {
- JavaField& field = curCl->virtualFields[i];
- const Typedef* type = field.getSignature();
- if (type->isPrimitive()) {
- const PrimitiveTypedef* prim = (const PrimitiveTypedef*)type;
- if (prim->isBool() || prim->isByte()) {
- ConstantInt* CI = ConstantInt::get(Type::getInt8Ty(getLLVMContext()),
- field.getInstanceInt8Field(obj));
- TempElts.push_back(CI);
- } else if (prim->isShort() || prim->isChar()) {
- ConstantInt* CI = ConstantInt::get(Type::getInt16Ty(getLLVMContext()),
- field.getInstanceInt16Field(obj));
- TempElts.push_back(CI);
- } else if (prim->isInt()) {
- ConstantInt* CI = ConstantInt::get(Type::getInt32Ty(getLLVMContext()),
- field.getInstanceInt32Field(obj));
- TempElts.push_back(CI);
- } else if (prim->isLong()) {
- ConstantInt* CI = ConstantInt::get(Type::getInt64Ty(getLLVMContext()),
- field.getInstanceLongField(obj));
- TempElts.push_back(CI);
- } else if (prim->isFloat()) {
- Constant* CF = ConstantFP::get(Type::getFloatTy(getLLVMContext()),
- field.getInstanceFloatField(obj));
- TempElts.push_back(CF);
- } else if (prim->isDouble()) {
- Constant* CF = ConstantFP::get(Type::getDoubleTy(getLLVMContext()),
- field.getInstanceDoubleField(obj));
- TempElts.push_back(CF);
- } else {
- abort();
- }
- } else {
- JavaObject* val = field.getInstanceObjectField(obj);
- if (val) {
- JnjvmClassLoader* JCL = cl->classLoader;
- CommonClass* FieldCl = field.getSignature()->assocClass(JCL);
- Constant* C = getFinalObject(val, FieldCl);
- TempElts.push_back(C);
- } else {
- const llvm::Type* Ty = JavaIntrinsics.JavaObjectType;
- TempElts.push_back(Constant::getNullValue(Ty));
- }
- }
- }
- CurConstant = ConstantStruct::get(STy, TempElts);
- }
-
- return CurConstant;
- }
-}
-
-Constant* JavaAOTCompiler::CreateConstantFromJavaString(JavaString* str) {
- Class* cl = JavaObject::getClass(str)->asClass();
- LLVMClassInfo* LCI = getClassInfo(cl);
- const StructType* STy =
- dyn_cast<StructType>(LCI->getVirtualType()->getContainedType(0));
-
- std::vector<Constant*> Elmts;
-
- Elmts.push_back(CreateConstantForBaseObject(cl));
-
- Constant* Array =
- CreateConstantFromIntArray<ArrayUInt16>(JavaString::getValue(str),
- Type::getInt16Ty(getLLVMContext()));
-
-
- Module& Mod = *getLLVMModule();
- GlobalVariable* varGV = new GlobalVariable(Mod, Array->getType(), false,
- GlobalValue::InternalLinkage,
- Array, "");
-
- Array = ConstantExpr::getBitCast(varGV, JavaIntrinsics.JavaObjectType);
-
- Elmts.push_back(Array);
- Elmts.push_back(ConstantInt::get(Type::getInt32Ty(getLLVMContext()),
- str->count));
- Elmts.push_back(ConstantInt::get(Type::getInt32Ty(getLLVMContext()),
- str->cachedHashCode));
- Elmts.push_back(ConstantInt::get(Type::getInt32Ty(getLLVMContext()),
- str->offset));
-
- return ConstantStruct::get(STy, Elmts);
-}
-
-
-Constant* JavaAOTCompiler::CreateConstantFromAttribut(Attribut& attribut) {
- const StructType* STy =
- dyn_cast<StructType>(JavaIntrinsics.AttributType->getContainedType(0));
-
-
- std::vector<Constant*> Elmts;
-
- // name
- Elmts.push_back(getUTF8(attribut.name));
-
- // start
- Elmts.push_back(ConstantInt::get(Type::getInt32Ty(getLLVMContext()), attribut.start));
-
- // nbb
- Elmts.push_back(ConstantInt::get(Type::getInt32Ty(getLLVMContext()), attribut.nbb));
-
- return ConstantStruct::get(STy, Elmts);
-}
-
-Constant* JavaAOTCompiler::CreateConstantFromCommonClass(CommonClass* cl) {
- const StructType* STy =
- dyn_cast<StructType>(JavaIntrinsics.JavaCommonClassType->getContainedType(0));
- Module& Mod = *getLLVMModule();
-
- const llvm::Type* TempTy = 0;
-
- std::vector<Constant*> CommonClassElts;
- std::vector<Constant*> TempElmts;
-
- // delegatee
- const ArrayType* ATy = dyn_cast<ArrayType>(STy->getContainedType(0));
- assert(ATy && "Malformed type");
-
- Constant* TCM[1] = { getJavaClass(cl) };
- CommonClassElts.push_back(ConstantArray::get(ATy, TCM, 1));
-
- // access
- CommonClassElts.push_back(ConstantInt::get(Type::getInt16Ty(getLLVMContext()), cl->access));
-
- // interfaces
- if (cl->nbInterfaces) {
- for (uint32 i = 0; i < cl->nbInterfaces; ++i) {
- TempElmts.push_back(getNativeClass(cl->interfaces[i]));
- }
-
- ATy = ArrayType::get(JavaIntrinsics.JavaClassType, cl->nbInterfaces);
- Constant* interfaces = ConstantArray::get(ATy, TempElmts);
- interfaces = new GlobalVariable(Mod, ATy, true,
- GlobalValue::InternalLinkage,
- interfaces, "");
- interfaces = ConstantExpr::getCast(Instruction::BitCast, interfaces,
- PointerType::getUnqual(JavaIntrinsics.JavaClassType));
-
- CommonClassElts.push_back(interfaces);
- } else {
- const Type* Ty = PointerType::getUnqual(JavaIntrinsics.JavaClassType);
- CommonClassElts.push_back(Constant::getNullValue(Ty));
- }
-
- // nbInterfaces
- CommonClassElts.push_back(ConstantInt::get(Type::getInt16Ty(getLLVMContext()), cl->nbInterfaces));
-
- // name
- CommonClassElts.push_back(getUTF8(cl->name));
-
- // super
- if (cl->super) {
- CommonClassElts.push_back(getNativeClass(cl->super));
- } else {
- TempTy = JavaIntrinsics.JavaClassType;
- CommonClassElts.push_back(Constant::getNullValue(TempTy));
- }
-
- // classLoader: store the static initializer, it will be overriden once
- // the class is loaded.
- Constant* loader = ConstantExpr::getBitCast(StaticInitializer,
- JavaIntrinsics.ptrType);
- CommonClassElts.push_back(loader);
-
- // virtualTable
- if (cl->virtualVT) {
- CommonClassElts.push_back(getVirtualTable(cl->virtualVT));
- } else {
- TempTy = JavaIntrinsics.VTType;
- CommonClassElts.push_back(Constant::getNullValue(TempTy));
- }
- return ConstantStruct::get(STy, CommonClassElts);
-}
-
-Constant* JavaAOTCompiler::CreateConstantFromJavaField(JavaField& field) {
- const StructType* STy =
- dyn_cast<StructType>(JavaIntrinsics.JavaFieldType->getContainedType(0));
-
- std::vector<Constant*> FieldElts;
- std::vector<Constant*> TempElts;
-
- // signature
- FieldElts.push_back(Constant::getNullValue(JavaIntrinsics.ptrType));
-
- // access
- FieldElts.push_back(ConstantInt::get(Type::getInt16Ty(getLLVMContext()), field.access));
-
- // name
- FieldElts.push_back(getUTF8(field.name));
-
- // type
- FieldElts.push_back(getUTF8(field.type));
-
- // attributs
- if (field.nbAttributs) {
- const llvm::Type* AttrTy = JavaIntrinsics.AttributType->getContainedType(0);
- const ArrayType* ATy = ArrayType::get(AttrTy, field.nbAttributs);
- for (uint32 i = 0; i < field.nbAttributs; ++i) {
- TempElts.push_back(CreateConstantFromAttribut(field.attributs[i]));
- }
-
- Constant* attributs = ConstantArray::get(ATy, TempElts);
- TempElts.clear();
- attributs = new GlobalVariable(*getLLVMModule(), ATy, true,
- GlobalValue::InternalLinkage,
- attributs, "");
- attributs = ConstantExpr::getCast(Instruction::BitCast, attributs,
- JavaIntrinsics.AttributType);
-
- FieldElts.push_back(attributs);
- } else {
- FieldElts.push_back(Constant::getNullValue(JavaIntrinsics.AttributType));
- }
-
- // nbAttributs
- FieldElts.push_back(ConstantInt::get(Type::getInt16Ty(getLLVMContext()), field.nbAttributs));
-
- // classDef
- FieldElts.push_back(getNativeClass(field.classDef));
-
- // ptrOffset
- FieldElts.push_back(ConstantInt::get(Type::getInt32Ty(getLLVMContext()), field.ptrOffset));
-
- // num
- FieldElts.push_back(ConstantInt::get(Type::getInt16Ty(getLLVMContext()), field.num));
-
- return ConstantStruct::get(STy, FieldElts);
-}
-
-Constant* JavaAOTCompiler::CreateConstantFromJavaMethod(JavaMethod& method) {
- const StructType* STy =
- dyn_cast<StructType>(JavaIntrinsics.JavaMethodType->getContainedType(0));
- Module& Mod = *getLLVMModule();
-
- std::vector<Constant*> MethodElts;
- std::vector<Constant*> TempElts;
-
- // signature
- MethodElts.push_back(Constant::getNullValue(JavaIntrinsics.ptrType));
-
- // access
- MethodElts.push_back(ConstantInt::get(Type::getInt16Ty(getLLVMContext()), method.access));
-
- // attributs
- if (method.nbAttributs) {
- const llvm::Type* AttrTy = JavaIntrinsics.AttributType->getContainedType(0);
- const ArrayType* ATy = ArrayType::get(AttrTy, method.nbAttributs);
- for (uint32 i = 0; i < method.nbAttributs; ++i) {
- TempElts.push_back(CreateConstantFromAttribut(method.attributs[i]));
- }
-
- Constant* attributs = ConstantArray::get(ATy, TempElts);
- TempElts.clear();
- attributs = new GlobalVariable(Mod, ATy, true,
- GlobalValue::InternalLinkage,
- attributs, "");
- attributs = ConstantExpr::getCast(Instruction::BitCast, attributs,
- JavaIntrinsics.AttributType);
-
- MethodElts.push_back(attributs);
- } else {
- MethodElts.push_back(Constant::getNullValue(JavaIntrinsics.AttributType));
- }
-
- // nbAttributs
- MethodElts.push_back(ConstantInt::get(Type::getInt16Ty(getLLVMContext()), method.nbAttributs));
-
- // classDef
- MethodElts.push_back(getNativeClass(method.classDef));
-
- // name
- MethodElts.push_back(getUTF8(method.name));
-
- // type
- MethodElts.push_back(getUTF8(method.type));
-
- // canBeInlined
- MethodElts.push_back(ConstantInt::get(Type::getInt8Ty(getLLVMContext()), method.canBeInlined));
-
- // code
- if (isAbstract(method.access)) {
- MethodElts.push_back(Constant::getNullValue(JavaIntrinsics.ptrType));
- } else {
- LLVMMethodInfo* LMI = getMethodInfo(&method);
- Function* func = LMI->getMethod();
- MethodElts.push_back(ConstantExpr::getCast(Instruction::BitCast, func,
- JavaIntrinsics.ptrType));
- }
-
- // codeInfo
- MethodElts.push_back(Constant::getNullValue(JavaIntrinsics.CodeLineInfoType));
-
- // codeInfoLength
- MethodElts.push_back(ConstantInt::get(Type::getInt16Ty(getLLVMContext()), 0));
-
- // offset
- MethodElts.push_back(ConstantInt::get(Type::getInt32Ty(getLLVMContext()), method.offset));
-
- return ConstantStruct::get(STy, MethodElts);
-}
-
-Constant* JavaAOTCompiler::CreateConstantFromClassPrimitive(ClassPrimitive* cl) {
- const llvm::Type* JCPTy =
- JavaIntrinsics.JavaClassPrimitiveType->getContainedType(0);
- const StructType* STy = dyn_cast<StructType>(JCPTy);
-
- std::vector<Constant*> ClassElts;
-
- // common class
- ClassElts.push_back(CreateConstantFromCommonClass(cl));
-
- // primSize
- ClassElts.push_back(ConstantInt::get(Type::getInt32Ty(getLLVMContext()), cl->logSize));
-
- return ConstantStruct::get(STy, ClassElts);
-}
-
-Constant* JavaAOTCompiler::CreateConstantFromClassArray(ClassArray* cl) {
- const StructType* STy =
- dyn_cast<StructType>(JavaIntrinsics.JavaClassArrayType->getContainedType(0));
-
- std::vector<Constant*> ClassElts;
- Constant* ClGEPs[2] = { getIntrinsics()->constantZero,
- getIntrinsics()->constantZero };
-
- // common class
- ClassElts.push_back(CreateConstantFromCommonClass(cl));
-
- // baseClass
- Constant* Cl = getNativeClass(cl->baseClass());
- if (Cl->getType() != JavaIntrinsics.JavaCommonClassType)
- Cl = ConstantExpr::getGetElementPtr(Cl, ClGEPs, 2);
-
- ClassElts.push_back(Cl);
-
- return ConstantStruct::get(STy, ClassElts);
-}
-
-Constant* JavaAOTCompiler::CreateConstantFromClass(Class* cl) {
- const StructType* STy =
- dyn_cast<StructType>(JavaIntrinsics.JavaClassType->getContainedType(0));
- Module& Mod = *getLLVMModule();
-
- std::vector<Constant*> ClassElts;
- std::vector<Constant*> TempElts;
-
- // common class
- ClassElts.push_back(CreateConstantFromCommonClass(cl));
-
- // virtualSize
- ClassElts.push_back(ConstantInt::get(Type::getInt32Ty(getLLVMContext()),
- cl->virtualSize));
-
- // alginment
- ClassElts.push_back(ConstantInt::get(Type::getInt32Ty(getLLVMContext()),
- cl->alignment));
-
- // IsolateInfo
- const ArrayType* ATy = dyn_cast<ArrayType>(STy->getContainedType(3));
- assert(ATy && "Malformed type");
-
- const StructType* TCMTy = dyn_cast<StructType>(ATy->getContainedType(0));
- assert(TCMTy && "Malformed type");
-
- uint32 status = cl->needsInitialisationCheck() ? vmjc : ready;
- TempElts.push_back(ConstantInt::get(Type::getInt8Ty(getLLVMContext()),
- status));
- TempElts.push_back(ConstantInt::get(Type::getInt1Ty(getLLVMContext()),
- status == ready ? 1 : 0));
- TempElts.push_back(getStaticInstance(cl));
- Constant* CStr[1] = { ConstantStruct::get(TCMTy, TempElts) };
- TempElts.clear();
- ClassElts.push_back(ConstantArray::get(ATy, CStr, 1));
-
- if (cl->nbVirtualFields + cl->nbStaticFields) {
- ATy = ArrayType::get(JavaIntrinsics.JavaFieldType->getContainedType(0),
- cl->nbVirtualFields + cl->nbStaticFields);
- }
-
- // virtualFields
- if (cl->nbVirtualFields) {
-
- for (uint32 i = 0; i < cl->nbVirtualFields; ++i) {
- TempElts.push_back(CreateConstantFromJavaField(cl->virtualFields[i]));
- }
-
- }
-
- // staticFields
- if (cl->nbStaticFields) {
-
- for (uint32 i = 0; i < cl->nbStaticFields; ++i) {
- TempElts.push_back(CreateConstantFromJavaField(cl->staticFields[i]));
- }
-
- }
-
- Constant* fields = 0;
- if (cl->nbStaticFields + cl->nbVirtualFields) {
-
- fields = ConstantArray::get(ATy, TempElts);
- TempElts.clear();
- fields = new GlobalVariable(Mod, ATy, false,
- GlobalValue::InternalLinkage,
- fields, "");
- fields = ConstantExpr::getCast(Instruction::BitCast, fields,
- JavaIntrinsics.JavaFieldType);
- } else {
- fields = Constant::getNullValue(JavaIntrinsics.JavaFieldType);
- }
-
- // virtualFields
- ClassElts.push_back(fields);
-
- ConstantInt* nbVirtualFields =
- ConstantInt::get(Type::getInt16Ty(getLLVMContext()), cl->nbVirtualFields);
- // nbVirtualFields
- ClassElts.push_back(nbVirtualFields);
-
- // staticFields
- // Output null, getLLVMModule() will be set in the initializer. Otherwise, the
- // assembly emitter of LLVM will try to align the data.
- ClassElts.push_back(Constant::getNullValue(JavaIntrinsics.JavaFieldType));
-
- // nbStaticFields
- ClassElts.push_back(ConstantInt::get(Type::getInt16Ty(getLLVMContext()), cl->nbStaticFields));
-
- // virtualMethods
- if (cl->nbVirtualMethods + cl->nbStaticMethods) {
- ATy = ArrayType::get(JavaIntrinsics.JavaMethodType->getContainedType(0),
- cl->nbVirtualMethods + cl->nbStaticMethods);
- }
-
- if (cl->nbVirtualMethods) {
- for (uint32 i = 0; i < cl->nbVirtualMethods; ++i) {
- TempElts.push_back(CreateConstantFromJavaMethod(cl->virtualMethods[i]));
- }
- }
-
- if (cl->nbStaticMethods) {
- for (uint32 i = 0; i < cl->nbStaticMethods; ++i) {
- TempElts.push_back(CreateConstantFromJavaMethod(cl->staticMethods[i]));
- }
- }
-
- Constant* methods = 0;
- if (cl->nbVirtualMethods + cl->nbStaticMethods) {
- methods = ConstantArray::get(ATy, TempElts);
- TempElts.clear();
-
- GlobalVariable* GV = NULL;
- method_iterator SI = virtualMethods.find(cl);
- if (SI != virtualMethods.end()) {
- GV = dyn_cast<GlobalVariable>(SI->second);
- GV->setInitializer(methods);
- } else {
- std::string name(UTF8Buffer(cl->name).toCompileName()->cString());
- name += "_VirtualMethods";
- GV = new GlobalVariable(Mod, ATy, false, GlobalValue::ExternalLinkage,
- methods, name);
- virtualMethods.insert(std::make_pair(cl, GV));
- }
- methods = ConstantExpr::getCast(Instruction::BitCast, GV,
- JavaIntrinsics.JavaMethodType);
- } else {
- methods = Constant::getNullValue(JavaIntrinsics.JavaMethodType);
- }
-
- // virtualMethods
- ClassElts.push_back(methods);
-
- ConstantInt* nbVirtualMethods =
- ConstantInt::get(Type::getInt16Ty(getLLVMContext()), cl->nbVirtualMethods);
- // nbVirtualMethods
- ClassElts.push_back(nbVirtualMethods);
-
- // staticMethods
- // Output null, getLLVMModule() will be set in the initializer.
- ClassElts.push_back(Constant::getNullValue(JavaIntrinsics.JavaMethodType));
-
- // nbStaticMethods
- ClassElts.push_back(ConstantInt::get(Type::getInt16Ty(getLLVMContext()), cl->nbStaticMethods));
-
- // ownerClass
- ClassElts.push_back(Constant::getNullValue(JavaIntrinsics.ptrType));
-
- // bytes
- ClassElts.push_back(Constant::getNullValue(JavaIntrinsics.JavaArrayUInt8Type));
-
- // ctpInfo
- ClassElts.push_back(Constant::getNullValue(JavaIntrinsics.ptrType));
-
- // attributs
- if (cl->nbAttributs) {
- ATy = ArrayType::get(JavaIntrinsics.AttributType->getContainedType(0),
- cl->nbAttributs);
-
- for (uint32 i = 0; i < cl->nbAttributs; ++i) {
- TempElts.push_back(CreateConstantFromAttribut(cl->attributs[i]));
- }
-
- Constant* attributs = ConstantArray::get(ATy, TempElts);
- TempElts.clear();
- attributs = new GlobalVariable(*getLLVMModule(), ATy, true,
- GlobalValue::InternalLinkage,
- attributs, "");
- attributs = ConstantExpr::getCast(Instruction::BitCast, attributs,
- JavaIntrinsics.AttributType);
- ClassElts.push_back(attributs);
- } else {
- ClassElts.push_back(Constant::getNullValue(JavaIntrinsics.AttributType));
- }
-
- // nbAttributs
- ClassElts.push_back(ConstantInt::get(Type::getInt16Ty(getLLVMContext()), cl->nbAttributs));
-
- // innerClasses
- if (cl->nbInnerClasses) {
- for (uint32 i = 0; i < cl->nbInnerClasses; ++i) {
- TempElts.push_back(getNativeClass(cl->innerClasses[i]));
- }
-
- const llvm::Type* TempTy = JavaIntrinsics.JavaClassType;
- ATy = ArrayType::get(TempTy, cl->nbInnerClasses);
- Constant* innerClasses = ConstantArray::get(ATy, TempElts);
- innerClasses = new GlobalVariable(*getLLVMModule(), ATy, true,
- GlobalValue::InternalLinkage,
- innerClasses, "");
- innerClasses = ConstantExpr::getCast(Instruction::BitCast, innerClasses,
- PointerType::getUnqual(TempTy));
-
- ClassElts.push_back(innerClasses);
- } else {
- const Type* Ty = PointerType::getUnqual(JavaIntrinsics.JavaClassType);
- ClassElts.push_back(Constant::getNullValue(Ty));
- }
-
- // nbInnerClasses
- ClassElts.push_back(ConstantInt::get(Type::getInt16Ty(getLLVMContext()), cl->nbInnerClasses));
-
- // outerClass
- if (cl->outerClass) {
- ClassElts.push_back(getNativeClass(cl->outerClass));
- } else {
- ClassElts.push_back(Constant::getNullValue(JavaIntrinsics.JavaClassType));
- }
-
- // innerAccess
- ClassElts.push_back(ConstantInt::get(Type::getInt16Ty(getLLVMContext()), cl->innerAccess));
-
- // innerOuterResolved
- ClassElts.push_back(ConstantInt::get(Type::getInt8Ty(getLLVMContext()), cl->innerOuterResolved));
-
- // isAnonymous
- ClassElts.push_back(ConstantInt::get(Type::getInt8Ty(getLLVMContext()), cl->isAnonymous));
-
- // virtualTableSize
- ClassElts.push_back(ConstantInt::get(Type::getInt32Ty(getLLVMContext()), cl->virtualTableSize));
-
- // staticSize
- ClassElts.push_back(ConstantInt::get(Type::getInt32Ty(getLLVMContext()), cl->staticSize));
-
- return ConstantStruct::get(STy, ClassElts);
-}
-
-template<typename T>
-Constant* JavaAOTCompiler::CreateConstantFromIntArray(const T* val, const Type* Ty) {
- std::vector<const Type*> Elemts;
- const ArrayType* ATy = ArrayType::get(Ty, T::getSize(val));
- Elemts.push_back(JavaIntrinsics.JavaObjectType->getContainedType(0));
- Elemts.push_back(JavaIntrinsics.pointerSizeType);
-
-
- Elemts.push_back(ATy);
-
- const StructType* STy = StructType::get(getLLVMModule()->getContext(), Elemts);
-
- std::vector<Constant*> Cts;
- Cts.push_back(CreateConstantForBaseObject(JavaObject::getClass(val)));
- Cts.push_back(ConstantInt::get(JavaIntrinsics.pointerSizeType, T::getSize(val)));
-
- std::vector<Constant*> Vals;
- for (sint32 i = 0; i < T::getSize(val); ++i) {
- Vals.push_back(ConstantInt::get(Ty, (uint64)T::getElement(val, i)));
- }
-
- Cts.push_back(ConstantArray::get(ATy, Vals));
-
- return ConstantStruct::get(STy, Cts);
-}
-
-template<typename T>
-Constant* JavaAOTCompiler::CreateConstantFromFPArray(const T* val, const Type* Ty) {
- std::vector<const Type*> Elemts;
- const ArrayType* ATy = ArrayType::get(Ty, T::getSize(val));
- Elemts.push_back(JavaIntrinsics.JavaObjectType->getContainedType(0));
- Elemts.push_back(JavaIntrinsics.pointerSizeType);
-
-
- Elemts.push_back(ATy);
-
- const StructType* STy = StructType::get(getLLVMModule()->getContext(), Elemts);
-
- std::vector<Constant*> Cts;
- Cts.push_back(CreateConstantForBaseObject(JavaObject::getClass(val)));
- Cts.push_back(ConstantInt::get(JavaIntrinsics.pointerSizeType, T::getSize(val)));
-
- std::vector<Constant*> Vals;
- for (sint32 i = 0; i < T::getSize(val); ++i) {
- Vals.push_back(ConstantFP::get(Ty, (double)T::getElement(val, i)));
- }
-
- Cts.push_back(ConstantArray::get(ATy, Vals));
-
- return ConstantStruct::get(STy, Cts);
-}
-
-Constant* JavaAOTCompiler::CreateConstantFromObjectArray(const ArrayObject* val) {
- std::vector<const Type*> Elemts;
- const llvm::Type* Ty = JavaIntrinsics.JavaObjectType;
- const ArrayType* ATy = ArrayType::get(Ty, ArrayObject::getSize(val));
- Elemts.push_back(JavaIntrinsics.JavaObjectType->getContainedType(0));
- Elemts.push_back(JavaIntrinsics.pointerSizeType);
-
-
- Elemts.push_back(ATy);
-
- const StructType* STy = StructType::get(getLLVMModule()->getContext(), Elemts);
-
- std::vector<Constant*> Cts;
- Cts.push_back(CreateConstantForBaseObject(JavaObject::getClass(val)));
- Cts.push_back(ConstantInt::get(JavaIntrinsics.pointerSizeType,
- ArrayObject::getSize(val)));
-
- std::vector<Constant*> Vals;
- for (sint32 i = 0; i < ArrayObject::getSize(val); ++i) {
- if (ArrayObject::getElement(val, i)) {
- Vals.push_back(getFinalObject(ArrayObject::getElement(val, i),
- JavaObject::getClass(val)->asArrayClass()->baseClass()));
- } else {
- Vals.push_back(Constant::getNullValue(JavaIntrinsics.JavaObjectType));
- }
- }
-
- Cts.push_back(ConstantArray::get(ATy, Vals));
-
- return ConstantStruct::get(STy, Cts);
-}
-
-Constant* JavaAOTCompiler::CreateConstantFromUTF8(const UTF8* val) {
- std::vector<const Type*> Elemts;
- const ArrayType* ATy = ArrayType::get(Type::getInt16Ty(getLLVMContext()), val->size);
- Elemts.push_back(JavaIntrinsics.pointerSizeType);
-
- Elemts.push_back(ATy);
-
- const StructType* STy = StructType::get(getLLVMModule()->getContext(),
- Elemts);
-
- std::vector<Constant*> Cts;
- Cts.push_back(ConstantInt::get(JavaIntrinsics.pointerSizeType, val->size));
-
- std::vector<Constant*> Vals;
- for (sint32 i = 0; i < val->size; ++i) {
- Vals.push_back(ConstantInt::get(Type::getInt16Ty(getLLVMContext()), val->elements[i]));
- }
-
- Cts.push_back(ConstantArray::get(ATy, Vals));
-
- return ConstantStruct::get(STy, Cts);
-
-}
-
-Constant* JavaAOTCompiler::getUTF8(const UTF8* val) {
- utf8_iterator End = utf8s.end();
- utf8_iterator I = utf8s.find(val);
- if (I == End) {
- Constant* C = CreateConstantFromUTF8(val);
- Module& Mod = *getLLVMModule();
- GlobalVariable* varGV = new GlobalVariable(Mod, C->getType(), true,
- GlobalValue::InternalLinkage,
- C, "");
-
- Constant* res = ConstantExpr::getCast(Instruction::BitCast, varGV,
- JavaIntrinsics.UTF8Type);
- utf8s.insert(std::make_pair(val, res));
-
- return res;
- } else {
- return I->second;
- }
-}
-
-Constant* JavaAOTCompiler::CreateConstantFromVT(JavaVirtualTable* VT) {
- CommonClass* classDef = VT->cl;
- uint32 size = classDef->isClass() ? classDef->asClass()->virtualTableSize :
- JavaVirtualTable::getBaseSize();
- JavaVirtualTable* RealVT = classDef->isClass() ?
- VT : ClassArray::SuperArray->virtualVT;
-
- const ArrayType* ATy =
- dyn_cast<ArrayType>(JavaIntrinsics.VTType->getContainedType(0));
- const PointerType* PTy = dyn_cast<PointerType>(ATy->getContainedType(0));
- ATy = ArrayType::get(PTy, size);
-
- ConstantPointerNull* N = ConstantPointerNull::get(PTy);
- std::vector<Constant*> Elemts;
-
- // Destructor
- Function* Finalizer = 0;
- JavaMethod* meth = (JavaMethod*)(RealVT->destructor);
- if (meth) {
- LLVMMethodInfo* LMI = getMethodInfo(meth);
- Finalizer = LMI->getMethod();
- }
-
- Elemts.push_back(Finalizer ?
- ConstantExpr::getCast(Instruction::BitCast, Finalizer, PTy) : N);
-
- // Delete
- Elemts.push_back(N);
-
- // Tracer
- Function* Tracer = 0;
- if (classDef->isArray()) {
- if (classDef->asArrayClass()->baseClass()->isPrimitive()) {
- Tracer = JavaObjectTracer;
- } else {
- Tracer = ArrayObjectTracer;
- }
- } else if (classDef->isClass()) {
- if (classDef->isAssignableFrom(classDef->classLoader->vm->upcalls->newReference)) {
- Tracer = ReferenceObjectTracer;
- } else {
- Tracer = RegularObjectTracer;
- }
- }
-
- Elemts.push_back(Tracer ?
- ConstantExpr::getCast(Instruction::BitCast, Tracer, PTy) : N);
-
- // vm
- Elemts.push_back(N);
-
- // specialized tracers
- for (uint32_t i = 0; i < mvm::VirtualTable::numberOfSpecializedTracers(); i++) {
- // Push null for now.
- Elemts.push_back(N);
- }
-
- // Class
- Elemts.push_back(ConstantExpr::getCast(Instruction::BitCast,
- getNativeClass(classDef), PTy));
-
- // depth
- Elemts.push_back(ConstantExpr::getIntToPtr(
- ConstantInt::get(Type::getInt64Ty(getLLVMContext()), VT->depth), PTy));
-
- // offset
- Elemts.push_back(ConstantExpr::getIntToPtr(
- ConstantInt::get(Type::getInt64Ty(getLLVMContext()), VT->offset), PTy));
-
- // cache
- Elemts.push_back(N);
-
- // display
- for (uint32 i = 0; i < JavaVirtualTable::getDisplayLength(); ++i) {
- if (VT->display[i]) {
- Constant* Temp = getVirtualTable(VT->display[i]);
- Temp = ConstantExpr::getBitCast(Temp, PTy);
- Elemts.push_back(Temp);
- } else {
- Elemts.push_back(Constant::getNullValue(PTy));
- }
- }
-
- // nbSecondaryTypes
- Elemts.push_back(ConstantExpr::getIntToPtr(
- ConstantInt::get(Type::getInt64Ty(getLLVMContext()), VT->nbSecondaryTypes), PTy));
-
- // secondaryTypes
- const ArrayType* DTy = ArrayType::get(JavaIntrinsics.VTType,
- VT->nbSecondaryTypes);
-
- std::vector<Constant*> TempElmts;
- for (uint32 i = 0; i < VT->nbSecondaryTypes; ++i) {
- assert(VT->secondaryTypes[i] && "No secondary type");
- Constant* Cl = getVirtualTable(VT->secondaryTypes[i]);
- TempElmts.push_back(Cl);
- }
- Constant* display = ConstantArray::get(DTy, TempElmts);
- TempElmts.clear();
-
- display = new GlobalVariable(*getLLVMModule(), DTy, true,
- GlobalValue::InternalLinkage,
- display, "");
-
- display = ConstantExpr::getCast(Instruction::BitCast, display, PTy);
-
- Elemts.push_back(display);
-
- // baseClassVT
- if (VT->baseClassVT) {
- Constant* Temp = getVirtualTable(VT->baseClassVT);
- Temp = ConstantExpr::getBitCast(Temp, PTy);
- Elemts.push_back(Temp);
- } else {
- Elemts.push_back(Constant::getNullValue(PTy));
- }
-
- // IMT
- if (!VT->IMT) {
- Elemts.push_back(Constant::getNullValue(PTy));
- } else {
- // TODO: add a null element at the end to diagnose errors.
- Class* cl = classDef->asClass();
- assert(cl && "Not a class");
- std::set<JavaMethod*> contents[InterfaceMethodTable::NumIndexes];
- classDef->asClass()->fillIMT(contents);
-
-
- const ArrayType* ATy =
- dyn_cast<ArrayType>(JavaIntrinsics.VTType->getContainedType(0));
- const PointerType* PTy = dyn_cast<PointerType>(ATy->getContainedType(0));
- ATy = ArrayType::get(PTy, InterfaceMethodTable::NumIndexes);
-
- ConstantPointerNull* N = ConstantPointerNull::get(PTy);
- std::vector<Constant*> IElemts;
-
- for (uint32_t i = 0; i < InterfaceMethodTable::NumIndexes; ++i) {
- std::set<JavaMethod*>& atIndex = contents[i];
- uint32_t size = atIndex.size();
- if (size == 1) {
- JavaMethod* Imeth = *(atIndex.begin());
- JavaMethod* meth = cl->lookupMethodDontThrow(Imeth->name,
- Imeth->type,
- false, true, 0);
- assert(meth && "No method found");
- LLVMMethodInfo* LMI = getMethodInfo(meth);
- Function* func = LMI->getMethod();
- IElemts.push_back(ConstantExpr::getBitCast(func, PTy));
- } else if (size > 1) {
- std::vector<JavaMethod*> methods;
- bool SameMethod = true;
- JavaMethod* OldMethod = 0;
-
- for (std::set<JavaMethod*>::iterator it = atIndex.begin(),
- et = atIndex.end(); it != et; ++it) {
- JavaMethod* Imeth = *it;
- JavaMethod* Cmeth = cl->lookupMethodDontThrow(Imeth->name, Imeth->type,
- false, true, 0);
-
- if (OldMethod && OldMethod != Cmeth) SameMethod = false;
- else OldMethod = Cmeth;
-
- methods.push_back(Cmeth);
- }
-
- if (SameMethod) {
- assert(methods[0] && "No method found");
- LLVMMethodInfo* LMI = getMethodInfo(methods[0]);
- Function* func = LMI->getMethod();
- IElemts.push_back(ConstantExpr::getBitCast(func, PTy));
- } else {
-
- uint32_t length = 2 * size;
-
- const ArrayType* ATy =
- dyn_cast<ArrayType>(JavaIntrinsics.VTType->getContainedType(0));
- ATy = ArrayType::get(PTy, length);
- std::vector<Constant*> InternalElemts;
-
-
- std::set<JavaMethod*>::iterator Interf = atIndex.begin();
- for (std::vector<JavaMethod*>::iterator it = methods.begin(),
- et = methods.end(); it != et; ++it, ++Interf) {
- JavaMethod* Imeth = *Interf;
- JavaMethod* Cmeth = *it;
- assert(Cmeth && "No method found");
-
- LLVMMethodInfo* LMI = getMethodInfo(Cmeth);
- Function* func = LMI->getMethod();
- InternalElemts.push_back(
- ConstantExpr::getBitCast(getMethodInClass(Imeth), PTy));
- InternalElemts.push_back(ConstantExpr::getBitCast(func, PTy));
- }
- Constant* Array = ConstantArray::get(ATy, InternalElemts);
-
- GlobalVariable* GV = new GlobalVariable(*getLLVMModule(), ATy, false,
- GlobalValue::InternalLinkage,
- Array, "");
-
- Constant* CI =
- ConstantExpr::getPtrToInt(GV, JavaIntrinsics.pointerSizeType);
- CI = ConstantExpr::getAdd(CI,
- ConstantExpr::getIntegerCast(JavaIntrinsics.constantOne,
- JavaIntrinsics.pointerSizeType,
- false));
- CI = ConstantExpr::getIntToPtr(CI, PTy);
- IElemts.push_back(CI);
- }
- } else {
- IElemts.push_back(N);
- }
- }
-
- Constant* Array = ConstantArray::get(ATy, IElemts);
- GlobalVariable* GV = new GlobalVariable(*getLLVMModule(), ATy, false,
- GlobalValue::InternalLinkage,
- Array, "");
- Elemts.push_back(ConstantExpr::getBitCast(GV, PTy));
- }
-
- // methods
- for (uint32 i = JavaVirtualTable::getFirstJavaMethodIndex(); i < size; ++i) {
- JavaMethod* meth = ((JavaMethod**)RealVT)[i];
- LLVMMethodInfo* LMI = getMethodInfo(meth);
- Function* F = LMI->getMethod();
- if (isAbstract(meth->access)) {
- Elemts.push_back(Constant::getNullValue(PTy));
- } else {
- Elemts.push_back(ConstantExpr::getCast(Instruction::BitCast, F, PTy));
- }
- }
-
- Constant* Array = ConstantArray::get(ATy, Elemts);
-
- return Array;
-}
-
-namespace mvm {
- llvm::FunctionPass* createEscapeAnalysisPass(llvm::Function*);
-}
-
-namespace j3 {
- llvm::FunctionPass* createLowerConstantCallsPass();
-}
-
-JavaAOTCompiler::JavaAOTCompiler(const std::string& ModuleID) :
- JavaLLVMCompiler(ModuleID) {
-
- generateStubs = true;
- assumeCompiled = false;
- compileRT = false;
-
- std::vector<const llvm::Type*> llvmArgs;
- llvmArgs.push_back(JavaIntrinsics.ptrType); // class loader.
- const FunctionType* FTy = FunctionType::get(Type::getVoidTy(getLLVMContext()),
- llvmArgs, false);
-
- StaticInitializer = Function::Create(FTy, GlobalValue::InternalLinkage,
- "Init", getLLVMModule());
-
- llvmArgs.clear();
- FTy = FunctionType::get(Type::getVoidTy(getLLVMContext()), llvmArgs, false);
- Callback = Function::Create(FTy, GlobalValue::ExternalLinkage,
- "staticCallback", getLLVMModule());
-
- llvmArgs.clear();
- llvmArgs.push_back(JavaIntrinsics.JavaMethodType);
-
- FTy = FunctionType::get(JavaIntrinsics.ptrType, llvmArgs, false);
-
- NativeLoader = Function::Create(FTy, GlobalValue::ExternalLinkage,
- "vmjcNativeLoader", getLLVMModule());
-
- llvmArgs.clear();
- FTy = FunctionType::get(Type::getVoidTy(getLLVMContext()), llvmArgs, false);
- ObjectPrinter = Function::Create(FTy, GlobalValue::ExternalLinkage,
- "printJavaObject", getLLVMModule());
-
- ArrayObjectTracer = Function::Create(FTy, GlobalValue::ExternalLinkage,
- "ArrayObjectTracer", getLLVMModule());
-
- RegularObjectTracer = Function::Create(FTy,
- GlobalValue::ExternalLinkage,
- "RegularObjectTracer",
- getLLVMModule());
-
- JavaObjectTracer = Function::Create(FTy, GlobalValue::ExternalLinkage,
- "JavaObjectTracer", getLLVMModule());
-
- ReferenceObjectTracer = Function::Create(FTy,
- GlobalValue::ExternalLinkage,
- "ReferenceObjectTracer",
- getLLVMModule());
-}
-
-void JavaAOTCompiler::printStats() {
- fprintf(stderr, "----------------- Info from the module -----------------\n");
- fprintf(stderr, "Number of native classes : %llu\n",
- (unsigned long long int) nativeClasses.size());
- fprintf(stderr, "Number of Java classes : %llu\n",
- (unsigned long long int) javaClasses.size());
- fprintf(stderr, "Number of external array classes : %llu\n",
- (unsigned long long int) arrayClasses.size());
- fprintf(stderr, "Number of virtual tables : %llu\n",
- (unsigned long long int) virtualTables.size());
- fprintf(stderr, "Number of static instances : %llu\n",
- (unsigned long long int) staticInstances.size());
- fprintf(stderr, "Number of constant pools : %llu\n",
- (unsigned long long int) constantPools.size());
- fprintf(stderr, "Number of strings : %llu\n",
- (unsigned long long int) strings.size());
- fprintf(stderr, "Number of native functions : %llu\n",
- (unsigned long long int) nativeFunctions.size());
- fprintf(stderr, "----------------- Total size in .data ------------------\n");
- uint64 size = 0;
- Module* Mod = getLLVMModule();
- for (Module::const_global_iterator i = Mod->global_begin(),
- e = Mod->global_end(); i != e; ++i) {
- size += mvm::MvmModule::getTypeSize(i->getType());
- }
- fprintf(stderr, "%lluB\n", (unsigned long long int)size);
-}
-
-void JavaAOTCompiler::CreateStaticInitializer() {
-
- std::vector<const llvm::Type*> llvmArgs;
- llvmArgs.push_back(JavaIntrinsics.ptrType); // class loader
- llvmArgs.push_back(JavaIntrinsics.JavaCommonClassType); // cl
- const FunctionType* FTy =
- FunctionType::get(Type::getVoidTy(getLLVMContext()), llvmArgs, false);
-
- Function* AddClass = Function::Create(FTy, GlobalValue::ExternalLinkage,
- "vmjcAddPreCompiledClass",
- getLLVMModule());
-
- llvmArgs.clear();
- // class loader
- llvmArgs.push_back(JavaIntrinsics.ptrType);
- // array ptr
- llvmArgs.push_back(PointerType::getUnqual(JavaIntrinsics.JavaClassArrayType));
- // name
- llvmArgs.push_back(JavaIntrinsics.UTF8Type);
- FTy = FunctionType::get(Type::getVoidTy(getLLVMContext()), llvmArgs, false);
-
- Function* GetClassArray = Function::Create(FTy, GlobalValue::ExternalLinkage,
- "vmjcGetClassArray", getLLVMModule());
-
- BasicBlock* currentBlock = BasicBlock::Create(getLLVMContext(), "enter",
- StaticInitializer);
- Function::arg_iterator loader = StaticInitializer->arg_begin();
-
- Value* Args[3];
- // If we have defined some strings.
- if (strings.begin() != strings.end()) {
- llvmArgs.clear();
- llvmArgs.push_back(JavaIntrinsics.ptrType); // class loader
- llvmArgs.push_back(strings.begin()->second->getType()); // val
- FTy = FunctionType::get(Type::getVoidTy(getLLVMContext()), llvmArgs, false);
-
- Function* AddString = Function::Create(FTy, GlobalValue::ExternalLinkage,
- "vmjcAddString", getLLVMModule());
-
-
-
- for (string_iterator i = strings.begin(), e = strings.end(); i != e; ++i) {
- Args[0] = loader;
- Args[1] = i->second;
- CallInst::Create(AddString, Args, Args + 2, "", currentBlock);
- }
- }
-
-#if 0
- // Disable initialization of UTF8s, it makes the Init method too big.
- // If we have defined some UTF8s.
- if (utf8s.begin() != utf8s.end()) {
- llvmArgs.clear();
- llvmArgs.push_back(JavaIntrinsics.ptrType); // class loader
- llvmArgs.push_back(utf8s.begin()->second->getType()); // val
- FTy = FunctionType::get(Type::getVoidTy(getLLVMContext()), llvmArgs, false);
-
- Function* AddUTF8 = Function::Create(FTy, GlobalValue::ExternalLinkage,
- "vmjcAddUTF8", getLLVMModule());
-
-
-
- for (utf8_iterator i = utf8s.begin(), e = utf8s.end(); i != e; ++i) {
- Args[0] = loader;
- Args[1] = i->second;
- CallInst::Create(AddUTF8, Args, Args + 2, "", currentBlock);
- }
- }
-#endif
-
- for (native_class_iterator i = nativeClasses.begin(),
- e = nativeClasses.end(); i != e; ++i) {
- if (isCompiling(i->first)) {
- Args[0] = loader;
- Args[1] = ConstantExpr::getBitCast(i->second,
- JavaIntrinsics.JavaCommonClassType);
- CallInst::Create(AddClass, Args, Args + 2, "", currentBlock);
- }
- }
-
- for (array_class_iterator i = arrayClasses.begin(),
- e = arrayClasses.end(); i != e; ++i) {
- Args[0] = loader;
- Args[1] = i->second;
- Args[2] = getUTF8(i->first->name);
- CallInst::Create(GetClassArray, Args, Args + 3, "", currentBlock);
- }
-
-
- ReturnInst::Create(getLLVMContext(), currentBlock);
-}
-
-void JavaAOTCompiler::setNoInline(Class* cl) {
- for (uint32 i = 0; i < cl->nbVirtualMethods; ++i) {
- JavaMethod& meth = cl->virtualMethods[i];
- if (!isAbstract(meth.access)) {
- LLVMMethodInfo* LMI = getMethodInfo(&meth);
- Function* func = LMI->getMethod();
- func->addFnAttr(Attribute::NoInline);
- }
- }
-
- for (uint32 i = 0; i < cl->nbStaticMethods; ++i) {
- JavaMethod& meth = cl->staticMethods[i];
- if (!isAbstract(meth.access)) {
- LLVMMethodInfo* LMI = getMethodInfo(&meth);
- Function* func = LMI->getMethod();
- func->addFnAttr(Attribute::NoInline);
- }
- }
-}
-
-void JavaAOTCompiler::makeVT(Class* cl) {
- JavaVirtualTable* VT = cl->virtualVT;
-
- if (cl->super) {
- // Copy the super VT into the current VT.
- uint32 size = cl->super->virtualTableSize -
- JavaVirtualTable::getFirstJavaMethodIndex();
- memcpy(VT->getFirstJavaMethod(), cl->super->virtualVT->getFirstJavaMethod(),
- size * sizeof(uintptr_t));
- VT->destructor = cl->super->virtualVT->destructor;
- }
-
- for (uint32 i = 0; i < cl->nbVirtualMethods; ++i) {
- JavaMethod& meth = cl->virtualMethods[i];
- ((void**)VT)[meth.offset] = &meth;
- }
-
- if (!cl->super) VT->destructor = 0;
-
-}
-
-void JavaAOTCompiler::makeIMT(Class* cl) {
-}
-
-void JavaAOTCompiler::setMethod(Function* func, void* ptr, const char* name) {
- func->setName(name);
- func->setLinkage(GlobalValue::ExternalLinkage);
-}
-
-Value* JavaAOTCompiler::addCallback(Class* cl, uint16 index,
- Signdef* sign, bool stat,
- BasicBlock* insert) {
-
- JavaConstantPool* ctpInfo = cl->ctpInfo;
- Signdef* signature = 0;
- const UTF8* name = 0;
- const UTF8* methCl = 0;
- ctpInfo->nameOfStaticOrSpecialMethod(index, methCl, name, signature);
-
-
- fprintf(stderr, "Warning: emitting a callback from %s (%s.%s)\n",
- UTF8Buffer(cl->name).cString(), UTF8Buffer(methCl).cString(),
- UTF8Buffer(name).cString());
-
- LLVMSignatureInfo* LSI = getSignatureInfo(sign);
-
- const FunctionType* type = stat ? LSI->getStaticType() :
- LSI->getVirtualType();
-
- Value* func = ConstantExpr::getBitCast(Callback,
- PointerType::getUnqual(type));
-
- return func;
-}
-
-void JavaAOTCompiler::compileClass(Class* cl) {
-
- // Make sure the class is emitted.
- getNativeClass(cl);
-
- for (uint32 i = 0; i < cl->nbVirtualMethods; ++i) {
- JavaMethod& meth = cl->virtualMethods[i];
- if (!isAbstract(meth.access)) parseFunction(&meth);
- if (generateStubs) compileAllStubs(meth.getSignature());
- }
-
- for (uint32 i = 0; i < cl->nbStaticMethods; ++i) {
- JavaMethod& meth = cl->staticMethods[i];
- if (!isAbstract(meth.access)) parseFunction(&meth);
- if (generateStubs) compileAllStubs(meth.getSignature());
- }
-}
-
-
-
-void extractFiles(ClassBytes* bytes,
- JavaAOTCompiler* M,
- JnjvmBootstrapLoader* bootstrapLoader,
- std::vector<Class*>& classes) {
- ZipArchive archive(bytes, bootstrapLoader->allocator);
-
- mvm::BumpPtrAllocator allocator;
- char* realName = (char*)allocator.Allocate(4096, "temp");
- for (ZipArchive::table_iterator i = archive.filetable.begin(),
- e = archive.filetable.end(); i != e; ++i) {
- ZipFile* file = i->second;
-
- char* name = file->filename;
- uint32 size = strlen(name);
- if (size > 6 && !strcmp(&(name[size - 6]), ".class")) {
- memcpy(realName, name, size);
- realName[size - 6] = 0;
- const UTF8* utf8 = bootstrapLoader->asciizConstructUTF8(realName);
- Class* cl = bootstrapLoader->loadName(utf8, true, false, NULL);
- assert(cl && "Class not created");
- if (cl == ClassArray::SuperArray) M->compileRT = true;
- classes.push_back(cl);
- } else if (size > 4 && (!strcmp(&name[size - 4], ".jar") ||
- !strcmp(&name[size - 4], ".zip"))) {
- ClassBytes* res = new (allocator, file->ucsize) ClassBytes(file->ucsize);
- int ok = archive.readFile(res, file);
- if (!ok) return;
-
- extractFiles(res, M, bootstrapLoader, classes);
- }
- }
-}
-
-
-static const char* name;
-
-
-void mainCompilerStart(mvm::VirtualMachine* _vm, int argc, char** argv) {
- Jnjvm* vm = (Jnjvm*)_vm;
-
- JavaThread::associate(vm, mvm::Thread::get());
-
- JnjvmBootstrapLoader* bootstrapLoader = vm->bootstrapLoader;
- JavaAOTCompiler* M = (JavaAOTCompiler*)bootstrapLoader->getCompiler();
- JavaJITCompiler* Comp = 0;
- mvm::ThreadAllocator allocator;
- bootstrapLoader->analyseClasspathEnv(vm->bootstrapLoader->bootClasspathEnv);
- uint32 size = strlen(name);
- if (size > 4 &&
- (!strcmp(&name[size - 4], ".jar") || !strcmp(&name[size - 4], ".zip"))) {
- bootstrapLoader->analyseClasspathEnv(name);
- }
-
- if (!M->clinits->empty()) {
- Comp = JavaJITCompiler::CreateCompiler("JIT");
- Comp->EmitFunctionName = true;
- if (!M->useCooperativeGC()) {
- Comp->disableCooperativeGC();
- }
- bootstrapLoader->setCompiler(Comp);
- bootstrapLoader->analyseClasspathEnv(vm->classpath);
- } else {
- bootstrapLoader->analyseClasspathEnv(vm->classpath);
- vm->upcalls->postInitialiseClasspath(bootstrapLoader);
- }
-
-
- if (size > 4 &&
- (!strcmp(&name[size - 4], ".jar") || !strcmp(&name[size - 4], ".zip"))) {
-
- std::vector<Class*> classes;
- ClassBytes* bytes = Reader::openFile(bootstrapLoader, name);
-
- if (!bytes) {
- fprintf(stderr, "Can't find zip file.\n");
- goto end;
- }
-
- extractFiles(bytes, M, bootstrapLoader, classes);
- // Now that we know if we can trust this compiler, add the Java passes.
- M->addJavaPasses();
-
-
- // First resolve everyone so that there can not be unknown references in
- // constant pools.
- for (std::vector<Class*>::iterator i = classes.begin(),
- e = classes.end(); i != e; ++i) {
- Class* cl = *i;
- cl->resolveClass();
- cl->setOwnerClass(mvm::Thread::get());
-
- for (uint32 i = 0; i < cl->nbVirtualMethods; ++i) {
- LLVMMethodInfo* LMI = M->getMethodInfo(&cl->virtualMethods[i]);
- LMI->getMethod();
- }
-
- for (uint32 i = 0; i < cl->nbStaticMethods; ++i) {
- LLVMMethodInfo* LMI = M->getMethodInfo(&cl->staticMethods[i]);
- LMI->getMethod();
- }
-
- }
-
- if (!M->clinits->empty()) {
- vm->loadBootstrap();
-
- for (std::vector<std::string>::iterator i = M->clinits->begin(),
- e = M->clinits->end(); i != e; ++i) {
-
- if (i->at(i->length() - 1) == '*') {
- for (std::vector<Class*>::iterator ii = classes.begin(),
- ee = classes.end(); ii != ee; ++ii) {
- Class* cl = *ii;
- if (!strncmp(UTF8Buffer(cl->name).cString(), i->c_str(),
- i->length() - 1)) {
- TRY {
- cl->asClass()->initialiseClass();
- } CATCH {
- fprintf(stderr, "Error when initializing %s\n",
- UTF8Buffer(cl->name).cString());
- abort();
- } END_CATCH;
- }
- }
- } else {
-
- const UTF8* name = bootstrapLoader->asciizConstructUTF8(i->c_str());
- CommonClass* cl = bootstrapLoader->lookupClass(name);
- if (cl && cl->isClass()) {
- TRY {
- cl->asClass()->initialiseClass();
- } CATCH {
- fprintf(stderr, "Error when initializing %s\n",
- UTF8Buffer(cl->name).cString());
- abort();
- } END_CATCH;
- } else {
- fprintf(stderr, "Class %s does not exist or is an array class.\n",
- i->c_str());
- }
- }
- }
- bootstrapLoader->setCompiler(M);
- }
-
- for (std::vector<Class*>::iterator i = classes.begin(), e = classes.end();
- i != e; ++i) {
- Class* cl = *i;
- cl->setOwnerClass(mvm::Thread::get());
- }
-
- for (std::vector<Class*>::iterator i = classes.begin(), e = classes.end();
- i != e; ++i) {
- Class* cl = *i;
- M->compileClass(cl);
- }
-
- } else {
- M->addJavaPasses();
- char* realName = (char*)allocator.Allocate(size + 1);
- if (size > 6 && !strcmp(&name[size - 6], ".class")) {
- memcpy(realName, name, size - 6);
- realName[size - 6] = 0;
- } else {
- memcpy(realName, name, size + 1);
- }
-
- const UTF8* utf8 = bootstrapLoader->asciizConstructUTF8(realName);
- UserClass* cl = bootstrapLoader->loadName(utf8, true, true, NULL);
-
- if (!M->clinits->empty()) {
- vm->loadBootstrap();
- cl->initialiseClass();
- bootstrapLoader->setCompiler(M);
- }
-
- cl->setOwnerClass(mvm::Thread::get());
- cl->resolveInnerOuterClasses();
- for (uint32 i = 0; i < cl->nbInnerClasses; ++i) {
- cl->innerClasses[i]->setOwnerClass(mvm::Thread::get());
- M->compileClass(cl->innerClasses[i]);
- }
- M->compileClass(cl);
- }
-
- if (M->compileRT) {
- // Make sure that if we compile RT, the native classes are emitted.
- M->getNativeClass(vm->upcalls->OfVoid);
- M->getNativeClass(vm->upcalls->OfBool);
- M->getNativeClass(vm->upcalls->OfByte);
- M->getNativeClass(vm->upcalls->OfChar);
- M->getNativeClass(vm->upcalls->OfShort);
- M->getNativeClass(vm->upcalls->OfInt);
- M->getNativeClass(vm->upcalls->OfFloat);
- M->getNativeClass(vm->upcalls->OfLong);
- M->getNativeClass(vm->upcalls->OfDouble);
-
- // Also do not allow inling of some functions.
-#define SET_INLINE(NAME) { \
- const UTF8* name = bootstrapLoader->asciizConstructUTF8(NAME); \
- Class* cl = (Class*)bootstrapLoader->lookupClass(name); \
- if (cl) M->setNoInline(cl); }
-
- SET_INLINE("java/util/concurrent/atomic/AtomicReferenceFieldUpdater")
- SET_INLINE("java/util/concurrent/atomic/AtomicReferenceFieldUpdater"
- "$AtomicReferenceFieldUpdaterImpl")
- SET_INLINE("java/util/concurrent/atomic/AtomicIntegerFieldUpdater")
- SET_INLINE("java/util/concurrent/atomic/AtomicIntegerFieldUpdater"
- "$AtomicIntegerFieldUpdaterImpl")
- SET_INLINE("java/util/concurrent/atomic/AtomicLongFieldUpdater")
- SET_INLINE("java/util/concurrent/atomic/AtomicLongFieldUpdater"
- "$CASUpdater")
- SET_INLINE("java/util/concurrent/atomic/AtomicLongFieldUpdater"
- "$LockedUpdater")
-#undef SET_INLINE
- }
-
- M->CreateStaticInitializer();
-
-end:
- return;
-}
-
-void JavaAOTCompiler::compileFile(Jnjvm* vm, const char* n) {
- name = n;
- vm->runApplication(mainCompilerStart, 0, 0);
- vm->vmkit->waitNonDaemonThreads();
-}
-
-/// compileAllStubs - Compile all the native -> Java stubs.
-/// TODO: Once LLVM supports va_arg, enable AP.
-///
-void JavaAOTCompiler::compileAllStubs(Signdef* sign) {
- sign->getStaticCallBuf();
- // getStaticCallAP();
- sign->getVirtualCallBuf();
- // getVirtualCallAP();
-}
-
-void JavaAOTCompiler::generateMain(const char* name, bool jit) {
-
- // Type Definitions
- std::vector<const Type*> FuncArgs;
- FuncArgs.push_back(Type::getInt32Ty(getLLVMContext()));
- FuncArgs.push_back(PointerType::getUnqual(JavaIntrinsics.ptrType));
-
- FunctionType* FuncTy = FunctionType::get(Type::getInt32Ty(getLLVMContext()),
- FuncArgs, false);
-
- Function* MainFunc = Function::Create(FuncTy, GlobalValue::ExternalLinkage,
- "main", TheModule);
- BasicBlock* currentBlock = BasicBlock::Create(getLLVMContext(), "enter",
- MainFunc);
-
- GlobalVariable* GvarArrayStr = new GlobalVariable(
- *TheModule, ArrayType::get(Type::getInt8Ty(getLLVMContext()),
- strlen(name) + 1),
- true, GlobalValue::InternalLinkage, 0, "mainClass");
-
-
- Constant* NameArray = ConstantArray::get(getLLVMContext(), name, true);
- GvarArrayStr->setInitializer(NameArray);
- Value* Indices[2] = { JavaIntrinsics.constantZero,
- JavaIntrinsics.constantZero };
- Value* ArgName = ConstantExpr::getGetElementPtr(GvarArrayStr, Indices, 2);
-
- Function::arg_iterator FuncVals = MainFunc->arg_begin();
- Value* Argc = FuncVals++;
- Value* Argv = FuncVals++;
- Value* Args[3] = { Argc, Argv, ArgName };
-
- FuncArgs.push_back(Args[2]->getType());
-
- FuncTy = FunctionType::get(Type::getInt32Ty(getLLVMContext()), FuncArgs, false);
-
- Function* CalledFunc =
- Function::Create(FuncTy, GlobalValue::ExternalLinkage,
- jit ? "StartJnjvmWithJIT" : "StartJnjvmWithoutJIT",
- TheModule);
-
- Value* res = CallInst::Create(CalledFunc, Args, Args + 3, "", currentBlock);
- ReturnInst::Create(getLLVMContext(), res, currentBlock);
-
-}
-
-
-// Use a FakeFunction to return from loadMethod, so that the compiler thinks
-// the method is defined by J3.
-extern "C" void __JavaAOTFakeFunction__() {}
-
-void* JavaAOTCompiler::loadMethod(void* handle, const char* symbol) {
- Function* F = mvm::MvmModule::globalModule->getFunction(symbol);
- if (F) {
- return (void*)(uintptr_t)__JavaAOTFakeFunction__;
- }
-
- return JavaCompiler::loadMethod(handle, symbol);
-}
-
-#ifdef WITH_MMTK
-
-#include <set>
-extern std::set<mvm::gc*> __InternalSet__;
-
-CommonClass* JavaAOTCompiler::getUniqueBaseClass(CommonClass* cl) {
- std::set<mvm::gc*>::iterator I = __InternalSet__.begin();
- std::set<mvm::gc*>::iterator E = __InternalSet__.end();
- CommonClass* currentClass = 0;
-
- for (; I != E; ++I) {
- JavaObject* obj = (JavaObject*)(*I);
- if (!VMClassLoader::isVMClassLoader(cl->classLoader->vm, obj) && JavaObject::instanceOf(obj, cl)) {
- if (currentClass != NULL) {
- if (JavaObject::getClass(obj) != currentClass) {
- return 0;
- }
- } else {
- currentClass = JavaObject::getClass(obj);
- }
- }
- }
- return currentClass;
-}
-
-#else
-CommonClass* JavaAOTCompiler::getUniqueBaseClass(CommonClass* cl) {
- return 0;
-}
-#endif
diff --git a/vmkit/lib/J3/Compiler/JavaJIT.cpp b/vmkit/lib/J3/Compiler/JavaJIT.cpp
deleted file mode 100644
index 0c6bba9..0000000
--- a/vmkit/lib/J3/Compiler/JavaJIT.cpp
+++ /dev/null
@@ -1,2417 +0,0 @@
-//===----------- JavaJIT.cpp - Java just in time compiler -----------------===//
-//
-// The VMKit project
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-
-#define DEBUG 0
-#define JNJVM_COMPILE 0
-#define JNJVM_EXECUTE 0
-
-#include <cstring>
-
-#include <llvm/Constants.h>
-#include <llvm/DerivedTypes.h>
-#include <llvm/Function.h>
-#include <llvm/Instructions.h>
-#include <llvm/Module.h>
-#include <llvm/Type.h>
-#include <llvm/Analysis/DebugInfo.h>
-#include <llvm/Support/CFG.h>
-
-#include "mvm/JIT.h"
-
-#include "debug.h"
-#include "JavaArray.h"
-#include "JavaClass.h"
-#include "JavaConstantPool.h"
-#include "JavaObject.h"
-#include "JavaJIT.h"
-#include "JavaString.h"
-#include "JavaThread.h"
-#include "JavaTypes.h"
-#include "JavaUpcalls.h"
-#include "Jnjvm.h"
-#include "Reader.h"
-
-#include "j3/JavaLLVMCompiler.h"
-#include "j3/J3Intrinsics.h"
-
-using namespace j3;
-using namespace llvm;
-
-static bool needsInitialisationCheck(Class* cl, Class* compilingClass) {
- if (cl->isReadyForCompilation() ||
- (!cl->isInterface() && compilingClass->isAssignableFrom(cl))) {
- return false;
- }
-
- if (!cl->needsInitialisationCheck()) {
- if (!cl->isReady()) {
- cl->setInitializationState(ready);
- }
- return false;
- }
-
- return true;
-}
-
-bool JavaJIT::canBeInlined(JavaMethod* meth) {
- JnjvmClassLoader* loader = meth->classDef->classLoader;
- return (meth->canBeInlined &&
- meth != compilingMethod && inlineMethods[meth] == 0 &&
- (loader == compilingClass->classLoader ||
- loader == compilingClass->classLoader->vm->bootstrapLoader));
-}
-
-void JavaJIT::invokeVirtual(uint16 index) {
-
- JavaConstantPool* ctpInfo = compilingClass->ctpInfo;
- CommonClass* cl = 0;
- JavaMethod* meth = 0;
- ctpInfo->infoOfMethod(index, ACC_VIRTUAL, cl, meth);
- bool canBeDirect = false;
- Value* val = NULL; // The return from the method.
-
- if ((cl && isFinal(cl->access)) ||
- (meth && (isFinal(meth->access) || isPrivate(meth->access)))) {
- canBeDirect = true;
- }
-
- if (meth && isInterface(meth->classDef->access)) {
- // This can happen because we compute miranda methods before resolving
- // interfaces.
- return invokeInterface(index);
- }
-
- const UTF8* name = 0;
- Signdef* signature = ctpInfo->infoOfInterfaceOrVirtualMethod(index, name);
-
- if (TheCompiler->isStaticCompiling()) {
- Value* obj = objectStack[stack.size() - signature->nbArguments - 1];
- JavaObject* source = TheCompiler->getFinalObject(obj);
- if (source) {
- canBeDirect = true;
- CommonClass* sourceClass = JavaObject::getClass(source);
- Class* lookup = sourceClass->isArray() ? sourceClass->super :
- sourceClass->asClass();
- meth = lookup->lookupMethodDontThrow(name, signature->keyName, false,
- true, 0);
- }
- CommonClass* unique = TheCompiler->getUniqueBaseClass(cl);
- if (unique) {
- canBeDirect = true;
- Class* lookup = unique->isArray() ? unique->super : unique->asClass();
- meth = lookup->lookupMethodDontThrow(name, signature->keyName, false,
- true, 0);
- }
- }
-
- Typedef* retTypedef = signature->getReturnType();
- std::vector<Value*> args; // size = [signature->nbIn + 3];
- LLVMSignatureInfo* LSI = TheCompiler->getSignatureInfo(signature);
- const llvm::FunctionType* virtualType = LSI->getVirtualType();
- FunctionType::param_iterator it = virtualType->param_end();
- const llvm::Type* retType = virtualType->getReturnType();
-
- bool needsInit = false;
- if (canBeDirect && meth && !TheCompiler->needsCallback(meth, &needsInit)) {
- makeArgs(it, index, args, signature->nbArguments + 1);
- JITVerifyNull(args[0]);
- val = invoke(TheCompiler->getMethod(meth), args, "", currentBlock);
- } else {
-
- BasicBlock* endBlock = 0;
- PHINode* node = 0;
-#if 0
- // TODO: enable this only when inlining?
- if (meth && !isAbstract(meth->access)) {
- Value* cl = CallInst::Create(intrinsics->GetClassFunction, args[0], "",
- currentBlock);
- Value* cl2 = intrinsics->getNativeClass(meth->classDef);
- if (cl2->getType() != intrinsics->JavaCommonClassType) {
- cl2 = new BitCastInst(cl2, intrinsics->JavaCommonClassType, "", currentBlock);
- }
-
- Value* test = new ICmpInst(*currentBlock, ICmpInst::ICMP_EQ, cl, cl2, "");
-
- BasicBlock* trueBlock = createBasicBlock("true virtual invoke");
- BasicBlock* falseBlock = createBasicBlock("false virtual invoke");
- endBlock = createBasicBlock("end virtual invoke");
- BranchInst::Create(trueBlock, falseBlock, test, currentBlock);
- currentBlock = trueBlock;
- Value* res = 0;
- if (canBeInlined(meth)) {
- res = invokeInline(meth, args);
- } else {
- Function* func = intrinsics->getMethod(meth);
- res = invoke(func, args, "", currentBlock);
- }
- BranchInst::Create(endBlock, currentBlock);
- if (retType != Type::getVoidTy(*llvmContext)) {
- node = PHINode::Create(virtualType->getReturnType(), "", endBlock);
- node->addIncoming(res, currentBlock);
- }
- currentBlock = falseBlock;
- }
-#endif
-
- Value* indexes2[2];
- indexes2[0] = intrinsics->constantZero;
-
- if (meth) {
- LLVMMethodInfo* LMI = TheCompiler->getMethodInfo(meth);
- Constant* Offset = LMI->getOffset();
- indexes2[1] = Offset;
- } else {
-
- GlobalVariable* GV = new GlobalVariable(*llvmFunction->getParent(),
- Type::getInt32Ty(*llvmContext),
- false,
- GlobalValue::ExternalLinkage,
- intrinsics->constantZero, "");
-
- BasicBlock* resolveVirtual = createBasicBlock("resolveVirtual");
- BasicBlock* endResolveVirtual = createBasicBlock("endResolveVirtual");
- PHINode* node = PHINode::Create(Type::getInt32Ty(*llvmContext), "",
- endResolveVirtual);
-
- Value* load = new LoadInst(GV, "", false, currentBlock);
- Value* test = new ICmpInst(*currentBlock, ICmpInst::ICMP_EQ, load,
- intrinsics->constantZero, "");
- BranchInst::Create(resolveVirtual, endResolveVirtual, test, currentBlock);
- node->addIncoming(load, currentBlock);
- currentBlock = resolveVirtual;
- std::vector<Value*> Args;
- Args.push_back(TheCompiler->getNativeClass(compilingClass));
- Args.push_back(ConstantInt::get(Type::getInt32Ty(*llvmContext), index));
- Args.push_back(GV);
- Value* targetObject = getTarget(signature);
- Args.push_back(new LoadInst(
- targetObject, "", TheCompiler->useCooperativeGC(), currentBlock));
- load = invoke(intrinsics->VirtualLookupFunction, Args, "", currentBlock);
- node->addIncoming(load, currentBlock);
- BranchInst::Create(endResolveVirtual, currentBlock);
- currentBlock = endResolveVirtual;
-
- indexes2[1] = node;
- }
-
- makeArgs(it, index, args, signature->nbArguments + 1);
- JITVerifyNull(args[0]);
- Value* VT = CallInst::Create(intrinsics->GetVTFunction, args[0], "",
- currentBlock);
-
- Value* FuncPtr = GetElementPtrInst::Create(VT, indexes2, indexes2 + 2, "",
- currentBlock);
-
- Value* Func = new LoadInst(FuncPtr, "", currentBlock);
-
- Func = new BitCastInst(Func, LSI->getVirtualPtrType(), "", currentBlock);
- val = invoke(Func, args, "", currentBlock);
-
- if (endBlock) {
- if (node) {
- node->addIncoming(val, currentBlock);
- val = node;
- }
- BranchInst::Create(endBlock, currentBlock);
- currentBlock = endBlock;
- }
- }
-
- if (retType != Type::getVoidTy(*llvmContext)) {
- if (retType == intrinsics->JavaObjectType) {
- JnjvmClassLoader* JCL = compilingClass->classLoader;
- push(val, false, signature->getReturnType()->findAssocClass(JCL));
- } else {
- push(val, retTypedef->isUnsigned());
- if (retType == Type::getDoubleTy(*llvmContext) || retType == Type::getInt64Ty(*llvmContext)) {
- push(intrinsics->constantZero, false);
- }
- }
- }
-}
-
-llvm::Value* JavaJIT::getMutatorThreadPtr() {
- Value* FrameAddr = CallInst::Create(intrinsics->llvm_frameaddress,
- intrinsics->constantZero, "", currentBlock);
- Value* threadId = new PtrToIntInst(FrameAddr, intrinsics->pointerSizeType, "",
- currentBlock);
- threadId = BinaryOperator::CreateAnd(threadId, intrinsics->constantThreadIDMask,
- "", currentBlock);
- threadId = new IntToPtrInst(threadId, intrinsics->MutatorThreadType, "", currentBlock);
-
- return threadId;
-}
-
-llvm::Value* JavaJIT::getDoYieldPtr(llvm::Value* mutatorThreadPtr) {
- Value* GEP[3] = { intrinsics->constantZero,
- intrinsics->OffsetThreadInMutatorThreadConstant,
- intrinsics->OffsetDoYieldInThreadConstant };
-
- return GetElementPtrInst::Create(mutatorThreadPtr, GEP, GEP + 3, "", currentBlock);
-}
-
-llvm::Value* JavaJIT::getCXXExceptionPtr(llvm::Value* mutatorThreadPtr) {
- Value* GEP[3] = { intrinsics->constantZero,
- intrinsics->OffsetThreadInMutatorThreadConstant,
- intrinsics->OffsetCXXExceptionInThreadConstant };
-
- return GetElementPtrInst::Create(mutatorThreadPtr, GEP, GEP + 3, "", currentBlock);
-}
-
-llvm::Value* JavaJIT::getPendingExceptionPtr(llvm::Value* mutatorThreadPtr) {
- Value* GEP[3] = { intrinsics->constantZero,
- intrinsics->OffsetThreadInMutatorThreadConstant,
- intrinsics->OffsetPendingExceptionInThreadConstant };
-
- Value* res = GetElementPtrInst::Create(mutatorThreadPtr, GEP, GEP + 3, "", currentBlock);
- return new BitCastInst(res, intrinsics->JavaObjectPtrType, "", currentBlock);
-}
-
-llvm::Value* JavaJIT::getJavaThreadPtr(llvm::Value* mutatorThreadPtr) {
- Value* GEP[3] = { intrinsics->constantZero,
- intrinsics->OffsetThreadInMutatorThreadConstant,
- intrinsics->OffsetVMDataInThreadConstant };
-
- Value *res = GetElementPtrInst::Create(mutatorThreadPtr, GEP, GEP + 3, "", currentBlock);
- res = new LoadInst(res, "", currentBlock);
- return new BitCastInst(res, intrinsics->JavaThreadType, "", currentBlock);
-}
-
-llvm::Value* JavaJIT::getJNIEnvPtr(llvm::Value* javaThreadPtr) {
- Value* GEP[2] = { intrinsics->constantZero,
- intrinsics->OffsetJNIInJavaThreadConstant };
-
- Value* res = GetElementPtrInst::Create(javaThreadPtr, GEP, GEP + 2, "", currentBlock);
- return new BitCastInst(res, intrinsics->ptrType, "", currentBlock);
-}
-
-
-extern "C" void j3ThrowExceptionFromJIT();
-
-llvm::Function* JavaJIT::nativeCompile(intptr_t natPtr) {
-
- PRINT_DEBUG(JNJVM_COMPILE, 1, COLOR_NORMAL, "native compile %s.%s\n",
- UTF8Buffer(compilingClass->name).cString(),
- UTF8Buffer(compilingMethod->name).cString());
-
- bool stat = isStatic(compilingMethod->access);
-
- const FunctionType *funcType = llvmFunction->getFunctionType();
- const llvm::Type* returnType = funcType->getReturnType();
-
- bool j3 = false;
-
- const UTF8* jniConsClName = compilingClass->name;
- const UTF8* jniConsName = compilingMethod->name;
- const UTF8* jniConsType = compilingMethod->type;
- sint32 clen = jniConsClName->size;
- sint32 mnlen = jniConsName->size;
- sint32 mtlen = jniConsType->size;
-
- mvm::ThreadAllocator allocator;
- char* functionName = (char*)allocator.Allocate(
- 3 + JNI_NAME_PRE_LEN + ((mnlen + clen + mtlen) << 3));
-
- if (!natPtr) {
- natPtr = compilingClass->classLoader->nativeLookup(compilingMethod, j3,
- functionName);
- }
-
- if (!natPtr && !TheCompiler->isStaticCompiling()) {
- currentBlock = createBasicBlock("start");
- CallInst::Create(intrinsics->ThrowExceptionFromJITFunction, "", currentBlock);
- if (returnType != Type::getVoidTy(*llvmContext)) {
- ReturnInst::Create(*llvmContext, Constant::getNullValue(returnType), currentBlock);
- } else {
- ReturnInst::Create(*llvmContext, currentBlock);
- }
-
- PRINT_DEBUG(JNJVM_COMPILE, 1, COLOR_NORMAL, "end native compile %s.%s\n",
- UTF8Buffer(compilingClass->name).cString(),
- UTF8Buffer(compilingMethod->name).cString());
-
- return llvmFunction;
- }
-
-
- Function* func = llvmFunction;
- if (j3) {
- Function* callee = Function::Create(llvmFunction->getFunctionType(),
- GlobalValue::ExternalLinkage,
- functionName,
- llvmFunction->getParent());
- TheCompiler->setMethod(callee, (void*)natPtr, functionName);
- currentBlock = createBasicBlock("start");
- std::vector<Value*> args;
- for (Function::arg_iterator i = func->arg_begin(), e = func->arg_end();
- i != e;
- i++) {
- args.push_back(i);
- }
- Value* res = CallInst::Create(
- callee, args.begin(), args.end(), "", currentBlock);
- if (returnType != Type::getVoidTy(*llvmContext)) {
- ReturnInst::Create(*llvmContext, res, currentBlock);
- } else {
- ReturnInst::Create(*llvmContext, currentBlock);
- }
- return llvmFunction;
- }
-
-
- currentExceptionBlock = endExceptionBlock = 0;
- currentBlock = createBasicBlock("start");
- endBlock = createBasicBlock("end block");
-
- if (returnType != Type::getVoidTy(*llvmContext)) {
- endNode = PHINode::Create(returnType, "", endBlock);
- }
-
- // Allocate currentLocalIndexNumber pointer
- Value* temp = new AllocaInst(Type::getInt32Ty(*llvmContext), "",
- currentBlock);
- new StoreInst(intrinsics->constantZero, temp, false, currentBlock);
-
- // Allocate oldCurrentLocalIndexNumber pointer
- Value* oldCLIN = new AllocaInst(PointerType::getUnqual(Type::getInt32Ty(*llvmContext)), "",
- currentBlock);
-
- Constant* sizeF = ConstantInt::get(Type::getInt32Ty(*llvmContext), sizeof(mvm::KnownFrame));
- Value* Frame = new AllocaInst(Type::getInt8Ty(*llvmContext), sizeF, "", currentBlock);
-
- uint32 nargs = func->arg_size() + 1 + (stat ? 1 : 0);
- std::vector<Value*> nativeArgs;
-
-
- Value* jniEnv = getJNIEnvPtr(getJavaThreadPtr(getMutatorThreadPtr()));
-
- nativeArgs.push_back(jniEnv);
-
- uint32 index = 0;
- if (stat) {
- Value* cl = TheCompiler->getJavaClassPtr(compilingClass);
- nativeArgs.push_back(cl);
- index = 2;
- } else {
- index = 1;
- }
- for (Function::arg_iterator i = func->arg_begin();
- index < nargs; ++i, ++index) {
-
- if (i->getType() == intrinsics->JavaObjectType) {
- BasicBlock* BB = createBasicBlock("");
- BasicBlock* NotZero = createBasicBlock("");
- const Type* Ty = PointerType::getUnqual(intrinsics->JavaObjectType);
- PHINode* node = PHINode::Create(Ty, "", BB);
-
- Value* test = new ICmpInst(*currentBlock, ICmpInst::ICMP_EQ, i,
- intrinsics->JavaObjectNullConstant, "");
-
- node->addIncoming(Constant::getNullValue(Ty), currentBlock);
- BranchInst::Create(BB, NotZero, test, currentBlock);
-
- currentBlock = NotZero;
-
- Instruction* temp = new AllocaInst(intrinsics->JavaObjectType, "",
- func->begin()->getTerminator());
- if (i == func->arg_begin() && !stat) {
- this->thisObject = temp;
- }
-
- if (TheCompiler->useCooperativeGC()) {
- Value* GCArgs[2] = {
- new BitCastInst(temp, intrinsics->ptrPtrType, "",
- func->begin()->getTerminator()),
- intrinsics->constantPtrNull
- };
-
- CallInst::Create(intrinsics->llvm_gc_gcroot, GCArgs, GCArgs + 2, "",
- func->begin()->getTerminator());
- }
-
- new StoreInst(i, temp, false, currentBlock);
- node->addIncoming(temp, currentBlock);
- BranchInst::Create(BB, currentBlock);
-
- currentBlock = BB;
-
- nativeArgs.push_back(node);
- } else {
- nativeArgs.push_back(i);
- }
- }
-
-
- Instruction* ResultObject = 0;
- if (returnType == intrinsics->JavaObjectType) {
- ResultObject = new AllocaInst(intrinsics->JavaObjectType, "",
- func->begin()->begin());
-
- if (TheCompiler->useCooperativeGC()) {
-
- Value* GCArgs[2] = {
- new BitCastInst(ResultObject, intrinsics->ptrPtrType, "", currentBlock),
- intrinsics->constantPtrNull
- };
-
- CallInst::Create(intrinsics->llvm_gc_gcroot, GCArgs, GCArgs + 2, "",
- currentBlock);
- } else {
- new StoreInst(intrinsics->JavaObjectNullConstant, ResultObject, "",
- currentBlock);
- }
- }
-
- Value* nativeFunc = TheCompiler->getNativeFunction(compilingMethod,
- (void*)natPtr);
-
- if (TheCompiler->isStaticCompiling()) {
- Value* Arg = TheCompiler->getMethodInClass(compilingMethod);
-
- // If the global variable is null, then load it.
- BasicBlock* unloadedBlock = createBasicBlock("");
- BasicBlock* endBlock = createBasicBlock("");
- Value* test = new LoadInst(nativeFunc, "", currentBlock);
- const llvm::Type* Ty = test->getType();
- PHINode* node = PHINode::Create(Ty, "", endBlock);
- node->addIncoming(test, currentBlock);
- Value* cmp = new ICmpInst(*currentBlock, ICmpInst::ICMP_EQ, test,
- Constant::getNullValue(Ty), "");
- BranchInst::Create(unloadedBlock, endBlock, cmp, currentBlock);
- currentBlock = unloadedBlock;
-
- Value* res = CallInst::Create(TheCompiler->NativeLoader, Arg, "",
- currentBlock);
-
- res = new BitCastInst(res, Ty, "", currentBlock);
- new StoreInst(res, nativeFunc, currentBlock);
- node->addIncoming(res, currentBlock);
- BranchInst::Create(endBlock, currentBlock);
- currentBlock = endBlock;
- nativeFunc = node;
- }
-
- // Synchronize before saying we're entering native
- if (isSynchro(compilingMethod->access))
- beginSynchronize();
-
- Value* Args4[3] = { temp, oldCLIN, Frame };
-
- CallInst::Create(intrinsics->StartJNIFunction, Args4, Args4 + 3, "",
- currentBlock);
-
- Value* result = llvm::CallInst::Create(nativeFunc, nativeArgs.begin(),
- nativeArgs.end(), "", currentBlock);
-
- if (returnType == intrinsics->JavaObjectType) {
- const Type* Ty = PointerType::getUnqual(intrinsics->JavaObjectType);
- Constant* C = Constant::getNullValue(Ty);
- Value* cmp = new ICmpInst(*currentBlock, ICmpInst::ICMP_EQ, result, C, "");
- BasicBlock* loadBlock = createBasicBlock("");
-
- endNode->addIncoming(intrinsics->JavaObjectNullConstant, currentBlock);
- BranchInst::Create(endBlock, loadBlock, cmp, currentBlock);
-
- currentBlock = loadBlock;
- result = new LoadInst(
- result, "", TheCompiler->useCooperativeGC(), currentBlock);
- new StoreInst(result, ResultObject, "", currentBlock);
- endNode->addIncoming(result, currentBlock);
-
- } else if (returnType != Type::getVoidTy(*llvmContext)) {
- endNode->addIncoming(result, currentBlock);
- }
-
- BranchInst::Create(endBlock, currentBlock);
-
-
- currentBlock = endBlock;
-
- Value* Args2[1] = { oldCLIN };
-
- CallInst::Create(intrinsics->EndJNIFunction, Args2, Args2 + 1, "", currentBlock);
-
- // Synchronize after leaving native.
- if (isSynchro(compilingMethod->access))
- endSynchronize();
-
- if (returnType != Type::getVoidTy(*llvmContext))
- ReturnInst::Create(*llvmContext, endNode, currentBlock);
- else
- ReturnInst::Create(*llvmContext, currentBlock);
-
- PRINT_DEBUG(JNJVM_COMPILE, 1, COLOR_NORMAL, "end native compile %s.%s\n",
- UTF8Buffer(compilingClass->name).cString(),
- UTF8Buffer(compilingMethod->name).cString());
-
- return llvmFunction;
-}
-
-void JavaJIT::monitorEnter(Value* obj) {
- std::vector<Value*> gep;
- gep.push_back(intrinsics->constantZero);
- gep.push_back(intrinsics->JavaObjectLockOffsetConstant);
- Value* lockPtr = GetElementPtrInst::Create(obj, gep.begin(), gep.end(), "",
- currentBlock);
-
- Value* lock = new LoadInst(lockPtr, "", currentBlock);
- lock = new PtrToIntInst(lock, intrinsics->pointerSizeType, "", currentBlock);
- Value* NonLockBitsMask = ConstantInt::get(intrinsics->pointerSizeType,
- mvm::ThinLock::NonLockBitsMask);
-
- lock = BinaryOperator::CreateAnd(lock, NonLockBitsMask, "", currentBlock);
-
- lockPtr = new BitCastInst(lockPtr,
- PointerType::getUnqual(intrinsics->pointerSizeType),
- "", currentBlock);
- Value* threadId = getMutatorThreadPtr();
- threadId = new PtrToIntInst(threadId, intrinsics->pointerSizeType, "",
- currentBlock);
- Value* newValMask = BinaryOperator::CreateOr(threadId, lock, "",
- currentBlock);
-
- std::vector<Value*> atomicArgs;
- atomicArgs.push_back(lockPtr);
- atomicArgs.push_back(lock);
- atomicArgs.push_back(newValMask);
-
- // Do the atomic compare and swap.
- Value* atomic = CallInst::Create(intrinsics->llvm_atomic_lcs_ptr,
- atomicArgs.begin(), atomicArgs.end(), "",
- currentBlock);
-
- Value* cmp = new ICmpInst(*currentBlock, ICmpInst::ICMP_EQ, atomic,
- lock, "");
-
- BasicBlock* OK = createBasicBlock("synchronize passed");
- BasicBlock* NotOK = createBasicBlock("synchronize did not pass");
-
- BranchInst::Create(OK, NotOK, cmp, currentBlock);
-
- // The atomic cas did not work.
- currentBlock = NotOK;
- CallInst::Create(intrinsics->AquireObjectFunction, obj, "", currentBlock);
- BranchInst::Create(OK, currentBlock);
-
- currentBlock = OK;
-}
-
-void JavaJIT::monitorExit(Value* obj) {
- std::vector<Value*> gep;
- gep.push_back(intrinsics->constantZero);
- gep.push_back(intrinsics->JavaObjectLockOffsetConstant);
- Value* lockPtr = GetElementPtrInst::Create(obj, gep.begin(), gep.end(), "",
- currentBlock);
- lockPtr = new BitCastInst(lockPtr,
- PointerType::getUnqual(intrinsics->pointerSizeType),
- "", currentBlock);
- Value* lock = new LoadInst(lockPtr, "", currentBlock);
- Value* NonLockBitsMask = ConstantInt::get(
- intrinsics->pointerSizeType, mvm::ThinLock::NonLockBitsMask);
-
- Value* lockedMask = BinaryOperator::CreateAnd(
- lock, NonLockBitsMask, "", currentBlock);
-
- Value* threadId = getMutatorThreadPtr();
- threadId = new PtrToIntInst(threadId, intrinsics->pointerSizeType, "",
- currentBlock);
-
- Value* oldValMask = BinaryOperator::CreateOr(threadId, lockedMask, "",
- currentBlock);
-
- std::vector<Value*> atomicArgs;
- atomicArgs.push_back(lockPtr);
- atomicArgs.push_back(oldValMask);
- atomicArgs.push_back(lockedMask);
-
- // Do the atomic compare and swap.
- Value* atomic = CallInst::Create(intrinsics->llvm_atomic_lcs_ptr,
- atomicArgs.begin(), atomicArgs.end(), "",
- currentBlock);
-
- Value* cmp = new ICmpInst(*currentBlock, ICmpInst::ICMP_EQ, atomic,
- oldValMask, "");
-
- BasicBlock* OK = createBasicBlock("unsynchronize passed");
- BasicBlock* NotOK = createBasicBlock("unsynchronize did not pass");
-
- BranchInst::Create(OK, NotOK, cmp, currentBlock);
-
- // The atomic cas did not work.
- currentBlock = NotOK;
- CallInst::Create(intrinsics->ReleaseObjectFunction, obj, "", currentBlock);
- BranchInst::Create(OK, currentBlock);
-
- currentBlock = OK;
-}
-
-void JavaJIT::beginSynchronize() {
- Value* obj = 0;
- if (isVirtual(compilingMethod->access)) {
- assert(thisObject != NULL && "beginSynchronize without this");
- obj = new LoadInst(
- thisObject, "", TheCompiler->useCooperativeGC(), currentBlock);
- } else {
- obj = TheCompiler->getJavaClassPtr(compilingClass);
- obj = new LoadInst(obj, "", false, currentBlock);
- }
- monitorEnter(obj);
-}
-
-void JavaJIT::endSynchronize() {
- Value* obj = 0;
- if (isVirtual(compilingMethod->access)) {
- assert(thisObject != NULL && "endSynchronize without this");
- obj = new LoadInst(
- thisObject, "", TheCompiler->useCooperativeGC(), currentBlock);
- } else {
- obj = TheCompiler->getJavaClassPtr(compilingClass);
- obj = new LoadInst(obj, "", false, currentBlock);
- }
- monitorExit(obj);
-}
-
-
-static void removeUnusedLocals(std::vector<AllocaInst*>& locals) {
- for (std::vector<AllocaInst*>::iterator i = locals.begin(),
- e = locals.end(); i != e; ++i) {
- AllocaInst* temp = *i;
- unsigned uses = temp->getNumUses();
- if (!uses) {
- temp->eraseFromParent();
- } else if (uses == 1 && dyn_cast<StoreInst>(*(temp->use_begin()))) {
- dyn_cast<StoreInst>(*(temp->use_begin()))->eraseFromParent();
- temp->eraseFromParent();
- }
- }
-}
-
-static void removeUnusedObjects(std::vector<AllocaInst*>& objects,
- J3Intrinsics* intrinsics, bool coop) {
- for (std::vector<AllocaInst*>::iterator i = objects.begin(),
- e = objects.end(); i != e; ++i) {
- AllocaInst* temp = *i;
- unsigned uses = temp->getNumUses();
- if (!uses) {
- temp->eraseFromParent();
- } else if (uses == 1 && dyn_cast<StoreInst>(*(temp->use_begin()))) {
- dyn_cast<StoreInst>(*(temp->use_begin()))->eraseFromParent();
- temp->eraseFromParent();
- } else {
- if (coop) {
- Instruction* I = new BitCastInst(temp, intrinsics->ptrPtrType, "");
- I->insertAfter(temp);
- Value* GCArgs[2] = { I, intrinsics->constantPtrNull };
- Instruction* C = CallInst::Create(intrinsics->llvm_gc_gcroot, GCArgs,
- GCArgs + 2, "");
- C->insertAfter(I);
- }
- }
- }
-}
-
-Instruction* JavaJIT::inlineCompile(BasicBlock*& curBB,
- BasicBlock* endExBlock,
- std::vector<Value*>& args) {
- DbgSubprogram = TheCompiler->GetDbgSubprogram(compilingMethod);
-
- PRINT_DEBUG(JNJVM_COMPILE, 1, COLOR_NORMAL, "inline compile %s.%s\n",
- UTF8Buffer(compilingClass->name).cString(),
- UTF8Buffer(compilingMethod->name).cString());
-
- Attribut* codeAtt = compilingMethod->lookupAttribut(Attribut::codeAttribut);
-
- if (!codeAtt) {
- fprintf(stderr, "I haven't verified your class file and it's malformed:"
- " no code attribut found for %s.%s!\n",
- UTF8Buffer(compilingClass->name).cString(),
- UTF8Buffer(compilingMethod->name).cString());
- abort();
- }
-
- Reader reader(codeAtt, compilingClass->bytes);
- uint16 maxStack = reader.readU2();
- uint16 maxLocals = reader.readU2();
- uint32 codeLen = reader.readU4();
- uint32 start = reader.cursor;
-
- reader.seek(codeLen, Reader::SeekCur);
-
- LLVMMethodInfo* LMI = TheCompiler->getMethodInfo(compilingMethod);
- assert(LMI);
- Function* func = LMI->getMethod();
-
- const Type* returnType = func->getReturnType();
- endBlock = createBasicBlock("end");
-
- currentBlock = curBB;
- endExceptionBlock = endExBlock;
-
- opcodeInfos = new Opinfo[codeLen];
- memset(opcodeInfos, 0, codeLen * sizeof(Opinfo));
- for (uint32 i = 0; i < codeLen; ++i) {
- opcodeInfos[i].exceptionBlock = endExBlock;
- }
-
- BasicBlock* firstBB = llvmFunction->begin();
-
- if (firstBB->begin() != firstBB->end()) {
- Instruction* firstInstruction = firstBB->begin();
-
- for (int i = 0; i < maxLocals; i++) {
- intLocals.push_back(new AllocaInst(Type::getInt32Ty(*llvmContext), "", firstInstruction));
- new StoreInst(Constant::getNullValue(Type::getInt32Ty(*llvmContext)), intLocals.back(), false, firstInstruction);
- doubleLocals.push_back(new AllocaInst(Type::getDoubleTy(*llvmContext), "",
- firstInstruction));
- new StoreInst(Constant::getNullValue(Type::getDoubleTy(*llvmContext)), doubleLocals.back(), false, firstInstruction);
- longLocals.push_back(new AllocaInst(Type::getInt64Ty(*llvmContext), "", firstInstruction));
- new StoreInst(Constant::getNullValue(Type::getInt64Ty(*llvmContext)), longLocals.back(), false, firstInstruction);
- floatLocals.push_back(new AllocaInst(Type::getFloatTy(*llvmContext), "", firstInstruction));
- new StoreInst(Constant::getNullValue(Type::getFloatTy(*llvmContext)), floatLocals.back(), false, firstInstruction);
- objectLocals.push_back(new AllocaInst(intrinsics->JavaObjectType, "",
- firstInstruction));
-
- // The GCStrategy will already initialize the value.
- if (!TheCompiler->useCooperativeGC())
- new StoreInst(Constant::getNullValue(intrinsics->JavaObjectType), objectLocals.back(), false, firstInstruction);
- }
- for (int i = 0; i < maxStack; i++) {
- objectStack.push_back(new AllocaInst(intrinsics->JavaObjectType, "",
- firstInstruction));
- addHighLevelType(objectStack.back(), upcalls->OfObject);
- intStack.push_back(new AllocaInst(Type::getInt32Ty(*llvmContext), "", firstInstruction));
- doubleStack.push_back(new AllocaInst(Type::getDoubleTy(*llvmContext), "",
- firstInstruction));
- longStack.push_back(new AllocaInst(Type::getInt64Ty(*llvmContext), "", firstInstruction));
- floatStack.push_back(new AllocaInst(Type::getFloatTy(*llvmContext), "", firstInstruction));
- }
-
- } else {
- for (int i = 0; i < maxLocals; i++) {
- intLocals.push_back(new AllocaInst(Type::getInt32Ty(*llvmContext), "", firstBB));
- new StoreInst(Constant::getNullValue(Type::getInt32Ty(*llvmContext)), intLocals.back(), false, firstBB);
- doubleLocals.push_back(new AllocaInst(Type::getDoubleTy(*llvmContext), "", firstBB));
- new StoreInst(Constant::getNullValue(Type::getDoubleTy(*llvmContext)), doubleLocals.back(), false, firstBB);
- longLocals.push_back(new AllocaInst(Type::getInt64Ty(*llvmContext), "", firstBB));
- new StoreInst(Constant::getNullValue(Type::getInt64Ty(*llvmContext)), longLocals.back(), false, firstBB);
- floatLocals.push_back(new AllocaInst(Type::getFloatTy(*llvmContext), "", firstBB));
- new StoreInst(Constant::getNullValue(Type::getFloatTy(*llvmContext)), floatLocals.back(), false, firstBB);
- objectLocals.push_back(new AllocaInst(intrinsics->JavaObjectType, "",
- firstBB));
- // The GCStrategy will already initialize the value.
- if (!TheCompiler->useCooperativeGC())
- new StoreInst(Constant::getNullValue(intrinsics->JavaObjectType), objectLocals.back(), false, firstBB);
- }
-
- for (int i = 0; i < maxStack; i++) {
- objectStack.push_back(new AllocaInst(intrinsics->JavaObjectType, "",
- firstBB));
- addHighLevelType(objectStack.back(), upcalls->OfObject);
- intStack.push_back(new AllocaInst(Type::getInt32Ty(*llvmContext), "", firstBB));
- doubleStack.push_back(new AllocaInst(Type::getDoubleTy(*llvmContext), "", firstBB));
- longStack.push_back(new AllocaInst(Type::getInt64Ty(*llvmContext), "", firstBB));
- floatStack.push_back(new AllocaInst(Type::getFloatTy(*llvmContext), "", firstBB));
- }
- }
-
-
- uint32 index = 0;
- uint32 count = 0;
- uint32 max = args.size();
- Signdef* sign = compilingMethod->getSignature();
- Typedef* const* arguments = sign->getArgumentsType();
- uint32 type = 0;
- std::vector<Value*>::iterator i = args.begin();
-
- if (isVirtual(compilingMethod->access)) {
- Instruction* V = new StoreInst(*i, objectLocals[0], false, currentBlock);
- addHighLevelType(V, compilingClass);
- ++i;
- ++index;
- ++count;
- thisObject = objectLocals[0];
- }
-
-
- for (;count < max; ++i, ++index, ++count, ++type) {
-
- const Typedef* cur = arguments[type];
- const Type* curType = (*i)->getType();
-
- if (curType == Type::getInt64Ty(*llvmContext)){
- new StoreInst(*i, longLocals[index], false, currentBlock);
- ++index;
- } else if (cur->isUnsigned()) {
- new StoreInst(new ZExtInst(*i, Type::getInt32Ty(*llvmContext), "", currentBlock),
- intLocals[index], false, currentBlock);
- } else if (curType == Type::getInt8Ty(*llvmContext) || curType == Type::getInt16Ty(*llvmContext)) {
- new StoreInst(new SExtInst(*i, Type::getInt32Ty(*llvmContext), "", currentBlock),
- intLocals[index], false, currentBlock);
- } else if (curType == Type::getInt32Ty(*llvmContext)) {
- new StoreInst(*i, intLocals[index], false, currentBlock);
- } else if (curType == Type::getDoubleTy(*llvmContext)) {
- new StoreInst(*i, doubleLocals[index], false, currentBlock);
- ++index;
- } else if (curType == Type::getFloatTy(*llvmContext)) {
- new StoreInst(*i, floatLocals[index], false, currentBlock);
- } else {
- Instruction* V = new StoreInst(*i, objectLocals[index], false, currentBlock);
- addHighLevelType(V, cur->findAssocClass(compilingClass->classLoader));
- }
- }
-
- readExceptionTable(reader, codeLen);
-
- reader.cursor = start;
- exploreOpcodes(reader, codeLen);
-
- if (returnType != Type::getVoidTy(*llvmContext)) {
- endNode = PHINode::Create(returnType, "", endBlock);
- }
-
- reader.cursor = start;
- compileOpcodes(reader, codeLen);
-
- PRINT_DEBUG(JNJVM_COMPILE, 1, COLOR_NORMAL,
- "--> end inline compiling %s.%s\n",
- UTF8Buffer(compilingClass->name).cString(),
- UTF8Buffer(compilingMethod->name).cString());
-
- curBB = endBlock;
-
-
- removeUnusedLocals(intLocals);
- removeUnusedLocals(doubleLocals);
- removeUnusedLocals(floatLocals);
- removeUnusedLocals(longLocals);
- removeUnusedLocals(intStack);
- removeUnusedLocals(doubleStack);
- removeUnusedLocals(floatStack);
- removeUnusedLocals(longStack);
-
- removeUnusedObjects(objectLocals, intrinsics, TheCompiler->useCooperativeGC());
- removeUnusedObjects(objectStack, intrinsics, TheCompiler->useCooperativeGC());
-
-
- delete[] opcodeInfos;
- return endNode;
-
-}
-
-llvm::Function* JavaJIT::javaCompile() {
- PRINT_DEBUG(JNJVM_COMPILE, 1, COLOR_NORMAL, "compiling %s.%s\n",
- UTF8Buffer(compilingClass->name).cString(),
- UTF8Buffer(compilingMethod->name).cString());
-
- DbgSubprogram = TheCompiler->GetDbgSubprogram(compilingMethod);
-
- Attribut* codeAtt = compilingMethod->lookupAttribut(Attribut::codeAttribut);
-
- if (!codeAtt) {
- fprintf(stderr, "I haven't verified your class file and it's malformed:"
- " no code attribute found for %s.%s!\n",
- UTF8Buffer(compilingClass->name).cString(),
- UTF8Buffer(compilingMethod->name).cString());
- abort();
- }
-
- Reader reader(codeAtt, compilingClass->bytes);
- uint16 maxStack = reader.readU2();
- uint16 maxLocals = reader.readU2();
- uint32 codeLen = reader.readU4();
- uint32 start = reader.cursor;
-
- reader.seek(codeLen, Reader::SeekCur);
-
- const FunctionType *funcType = llvmFunction->getFunctionType();
- const Type* returnType = funcType->getReturnType();
-
- Function* func = llvmFunction;
-
- currentBlock = createBasicBlock("start");
- endExceptionBlock = createBasicBlock("endExceptionBlock");
- unifiedUnreachable = createBasicBlock("unifiedUnreachable");
-
- opcodeInfos = new Opinfo[codeLen];
- memset(opcodeInfos, 0, codeLen * sizeof(Opinfo));
- for (uint32 i = 0; i < codeLen; ++i) {
- opcodeInfos[i].exceptionBlock = endExceptionBlock;
- }
-
- Instruction* returnValue = NULL;
- if (returnType == intrinsics->JavaObjectType &&
- TheCompiler->useCooperativeGC()) {
- returnValue = new AllocaInst(intrinsics->JavaObjectType, "",
- currentBlock);
- Instruction* cast =
- new BitCastInst(returnValue, intrinsics->ptrPtrType, "", currentBlock);
- Value* GCArgs[2] = { cast, intrinsics->constantPtrNull };
-
- CallInst::Create(intrinsics->llvm_gc_gcroot, GCArgs, GCArgs + 2, "",
- currentBlock);
- }
-
- for (int i = 0; i < maxLocals; i++) {
- intLocals.push_back(new AllocaInst(Type::getInt32Ty(*llvmContext), "", currentBlock));
- new StoreInst(Constant::getNullValue(Type::getInt32Ty(*llvmContext)), intLocals.back(), false, currentBlock);
- doubleLocals.push_back(new AllocaInst(Type::getDoubleTy(*llvmContext), "", currentBlock));
- new StoreInst(Constant::getNullValue(Type::getDoubleTy(*llvmContext)), doubleLocals.back(), false, currentBlock);
- longLocals.push_back(new AllocaInst(Type::getInt64Ty(*llvmContext), "", currentBlock));
- new StoreInst(Constant::getNullValue(Type::getInt64Ty(*llvmContext)), longLocals.back(), false, currentBlock);
- floatLocals.push_back(new AllocaInst(Type::getFloatTy(*llvmContext), "", currentBlock));
- new StoreInst(Constant::getNullValue(Type::getFloatTy(*llvmContext)), floatLocals.back(), false, currentBlock);
- objectLocals.push_back(new AllocaInst(intrinsics->JavaObjectType, "",
- currentBlock));
- // The GCStrategy will already initialize the value.
- if (!TheCompiler->useCooperativeGC())
- new StoreInst(Constant::getNullValue(intrinsics->JavaObjectType), objectLocals.back(), false, currentBlock);
- }
-
- for (int i = 0; i < maxStack; i++) {
- objectStack.push_back(new AllocaInst(intrinsics->JavaObjectType, "",
- currentBlock));
- addHighLevelType(objectStack.back(), upcalls->OfObject);
- intStack.push_back(new AllocaInst(Type::getInt32Ty(*llvmContext), "", currentBlock));
- doubleStack.push_back(new AllocaInst(Type::getDoubleTy(*llvmContext), "", currentBlock));
- longStack.push_back(new AllocaInst(Type::getInt64Ty(*llvmContext), "", currentBlock));
- floatStack.push_back(new AllocaInst(Type::getFloatTy(*llvmContext), "", currentBlock));
- }
-
- uint32 index = 0;
- uint32 count = 0;
- uint32 max = func->arg_size();
- Function::arg_iterator i = func->arg_begin();
- Signdef* sign = compilingMethod->getSignature();
- Typedef* const* arguments = sign->getArgumentsType();
- uint32 type = 0;
-
- if (isVirtual(compilingMethod->access)) {
- Instruction* V = new StoreInst(i, objectLocals[0], false, currentBlock);
- addHighLevelType(V, compilingClass);
- ++i;
- ++index;
- ++count;
- thisObject = objectLocals[0];
- }
-
- for (;count < max; ++i, ++index, ++count, ++type) {
-
- const Typedef* cur = arguments[type];
- const llvm::Type* curType = i->getType();
-
- if (curType == Type::getInt64Ty(*llvmContext)){
- new StoreInst(i, longLocals[index], false, currentBlock);
- ++index;
- } else if (cur->isUnsigned()) {
- new StoreInst(new ZExtInst(i, Type::getInt32Ty(*llvmContext), "", currentBlock),
- intLocals[index], false, currentBlock);
- } else if (curType == Type::getInt8Ty(*llvmContext) || curType == Type::getInt16Ty(*llvmContext)) {
- new StoreInst(new SExtInst(i, Type::getInt32Ty(*llvmContext), "", currentBlock),
- intLocals[index], false, currentBlock);
- } else if (curType == Type::getInt32Ty(*llvmContext)) {
- new StoreInst(i, intLocals[index], false, currentBlock);
- } else if (curType == Type::getDoubleTy(*llvmContext)) {
- new StoreInst(i, doubleLocals[index], false, currentBlock);
- ++index;
- } else if (curType == Type::getFloatTy(*llvmContext)) {
- new StoreInst(i, floatLocals[index], false, currentBlock);
- } else {
- Instruction* V = new StoreInst(i, objectLocals[index], false, currentBlock);
- addHighLevelType(V, cur->findAssocClass(compilingClass->classLoader));
- }
- }
-
- // Now that arguments have been setup, we can proceed with runtime calls.
-#if JNJVM_EXECUTE > 0
- {
- Value* arg = TheCompiler->getMethodInClass(compilingMethod);
-
- llvm::CallInst::Create(intrinsics->PrintMethodStartFunction, arg, "",
- currentBlock);
- }
-#endif
-
- readExceptionTable(reader, codeLen);
-
- reader.cursor = start;
- exploreOpcodes(reader, codeLen);
-
- endBlock = createBasicBlock("end");
-
- if (returnType != Type::getVoidTy(*llvmContext)) {
- endNode = llvm::PHINode::Create(returnType, "", endBlock);
- }
-
- if (isSynchro(compilingMethod->access)) {
- beginSynchronize();
- }
-
- if (TheCompiler->useCooperativeGC()) {
- Value* YieldPtr = getDoYieldPtr(getMutatorThreadPtr());
-
- Value* Yield = new LoadInst(YieldPtr, "", currentBlock);
-
- BasicBlock* continueBlock = createBasicBlock("After safe point");
- BasicBlock* yieldBlock = createBasicBlock("In safe point");
- BranchInst::Create(yieldBlock, continueBlock, Yield, currentBlock);
-
- currentBlock = yieldBlock;
- CallInst::Create(intrinsics->conditionalSafePoint, "", currentBlock);
- BranchInst::Create(continueBlock, currentBlock);
-
- currentBlock = continueBlock;
- }
-
- if (TheCompiler->hasExceptionsEnabled()) {
- // Variables have been allocated and the lock has been taken. Do the stack
- // check now: if there is an exception, we will go to the lock release code.
- currentExceptionBlock = opcodeInfos[0].exceptionBlock;
- Value* FrameAddr = CallInst::Create(intrinsics->llvm_frameaddress,
- intrinsics->constantZero, "", currentBlock);
- FrameAddr = new PtrToIntInst(FrameAddr, intrinsics->pointerSizeType, "",
- currentBlock);
- Value* stackCheck =
- BinaryOperator::CreateAnd(FrameAddr, intrinsics->constantStackOverflowMask,
- "", currentBlock);
-
- stackCheck = new ICmpInst(*currentBlock, ICmpInst::ICMP_EQ, stackCheck,
- intrinsics->constantPtrZero, "");
- BasicBlock* stackOverflow = createBasicBlock("stack overflow");
- BasicBlock* noStackOverflow = createBasicBlock("no stack overflow");
- BranchInst::Create(stackOverflow, noStackOverflow, stackCheck,
- currentBlock);
- currentBlock = stackOverflow;
- throwException(intrinsics->StackOverflowErrorFunction, 0, 0);
- currentBlock = noStackOverflow;
- }
-
- reader.cursor = start;
- compileOpcodes(reader, codeLen);
-
- assert(stack.size() == 0 && "Stack not empty after compiling bytecode");
- // Fix a javac(?) bug where a method only throws an exception and does
- // not return.
- pred_iterator PI = pred_begin(endBlock);
- pred_iterator PE = pred_end(endBlock);
- if (PI == PE && returnType != Type::getVoidTy(*llvmContext)) {
- Instruction* I = currentBlock->getTerminator();
-
- if (isa<UnreachableInst>(I)) {
- I->eraseFromParent();
- BranchInst::Create(endBlock, currentBlock);
- endNode->addIncoming(Constant::getNullValue(returnType),
- currentBlock);
- } else if (InvokeInst* II = dyn_cast<InvokeInst>(I)) {
- II->setNormalDest(endBlock);
- endNode->addIncoming(Constant::getNullValue(returnType),
- currentBlock);
- }
-
- }
- currentBlock = endBlock;
-
- if (returnValue != NULL) {
- new StoreInst(endNode, returnValue, currentBlock);
- }
-
- if (isSynchro(compilingMethod->access)) {
- endSynchronize();
- }
-
-#if JNJVM_EXECUTE > 0
- {
- Value* arg = TheCompiler->getMethodInClass(compilingMethod);
- CallInst::Create(intrinsics->PrintMethodEndFunction, arg, "", currentBlock);
- }
-#endif
-
- PI = pred_begin(currentBlock);
- PE = pred_end(currentBlock);
- if (PI == PE) {
- currentBlock->eraseFromParent();
- } else {
- if (returnType != Type::getVoidTy(*llvmContext)) {
- if (returnValue != NULL) {
- Value* obj = new LoadInst(
- returnValue, "", TheCompiler->useCooperativeGC(), currentBlock);
- ReturnInst::Create(*llvmContext, obj, currentBlock);
- } else {
- ReturnInst::Create(*llvmContext, endNode, currentBlock);
- }
- } else {
- ReturnInst::Create(*llvmContext, currentBlock);
- }
- }
-
- currentBlock = endExceptionBlock;
-
- finishExceptions();
-
- removeUnusedLocals(intLocals);
- removeUnusedLocals(doubleLocals);
- removeUnusedLocals(floatLocals);
- removeUnusedLocals(longLocals);
- removeUnusedLocals(intStack);
- removeUnusedLocals(doubleStack);
- removeUnusedLocals(floatStack);
- removeUnusedLocals(longStack);
-
- removeUnusedObjects(objectLocals, intrinsics, TheCompiler->useCooperativeGC());
- removeUnusedObjects(objectStack, intrinsics, TheCompiler->useCooperativeGC());
-
- delete[] opcodeInfos;
-
- PRINT_DEBUG(JNJVM_COMPILE, 1, COLOR_NORMAL, "--> end compiling %s.%s\n",
- UTF8Buffer(compilingClass->name).cString(),
- UTF8Buffer(compilingMethod->name).cString());
-
-#ifndef DWARF_EXCEPTIONS
- if (codeLen < 5 && !callsStackWalker && !TheCompiler->isStaticCompiling())
- compilingMethod->canBeInlined = false;
-#endif
-
- Attribut* annotationsAtt =
- compilingMethod->lookupAttribut(Attribut::annotationsAttribut);
-
- if (annotationsAtt) {
- Reader reader(annotationsAtt, compilingClass->bytes);
- AnnotationReader AR(reader, compilingClass);
- uint16 numAnnotations = reader.readU2();
- for (uint16 i = 0; i < numAnnotations; ++i) {
- AR.readAnnotation();
- const UTF8* name =
- compilingClass->ctpInfo->UTF8At(AR.AnnotationNameIndex);
- if (name->equals(TheCompiler->InlinePragma)) {
- llvmFunction->addFnAttr(Attribute::AlwaysInline);
- } else if (name->equals(TheCompiler->NoInlinePragma)) {
- llvmFunction->addFnAttr(Attribute::NoInline);
- }
- }
- }
-
- return llvmFunction;
-}
-
-void JavaJIT::compareFP(Value* val1, Value* val2, const Type* ty, bool l) {
- Value* one = intrinsics->constantOne;
- Value* zero = intrinsics->constantZero;
- Value* minus = intrinsics->constantMinusOne;
-
- Value* c = new FCmpInst(*currentBlock, FCmpInst::FCMP_UGT, val1, val2, "");
- Value* r = llvm::SelectInst::Create(c, one, zero, "", currentBlock);
- c = new FCmpInst(*currentBlock, FCmpInst::FCMP_ULT, val1, val2, "");
- r = llvm::SelectInst::Create(c, minus, r, "", currentBlock);
- c = new FCmpInst(*currentBlock, FCmpInst::FCMP_UNO, val1, val2, "");
- r = llvm::SelectInst::Create(c, l ? one : minus, r, "", currentBlock);
-
- push(r, false);
-
-}
-
-void JavaJIT::loadConstant(uint16 index) {
- JavaConstantPool* ctpInfo = compilingClass->ctpInfo;
- uint8 type = ctpInfo->typeAt(index);
-
- if (type == JavaConstantPool::ConstantString) {
-
- if (TheCompiler->isStaticCompiling()) {
- const UTF8* utf8 = ctpInfo->UTF8At(ctpInfo->ctpDef[index]);
- JavaString* str = *(compilingClass->classLoader->UTF8ToStr(utf8));
- Value* val = TheCompiler->getString(str);
- push(val, false, upcalls->newString);
- } else {
- JavaString** str = (JavaString**)ctpInfo->ctpRes[index];
- if (str) {
- Value* val = TheCompiler->getStringPtr(str);
- val = new LoadInst(val, "", currentBlock);
- push(val, false, upcalls->newString);
- } else {
- // Lookup the constant pool cache
- const llvm::Type* Ty = PointerType::getUnqual(intrinsics->JavaObjectType);
- Value* val = getConstantPoolAt(index, intrinsics->StringLookupFunction,
- Ty, 0, false);
- val = new LoadInst(val, "", currentBlock);
- push(val, false, upcalls->newString);
- }
- }
-
- } else if (type == JavaConstantPool::ConstantLong) {
- push(ConstantInt::get(Type::getInt64Ty(*llvmContext), ctpInfo->LongAt(index)),
- false);
- } else if (type == JavaConstantPool::ConstantDouble) {
- push(ConstantFP::get(Type::getDoubleTy(*llvmContext), ctpInfo->DoubleAt(index)),
- false);
- } else if (type == JavaConstantPool::ConstantInteger) {
- push(ConstantInt::get(Type::getInt32Ty(*llvmContext), ctpInfo->IntegerAt(index)),
- false);
- } else if (type == JavaConstantPool::ConstantFloat) {
- push(ConstantFP::get(Type::getFloatTy(*llvmContext), ctpInfo->FloatAt(index)),
- false);
- } else if (type == JavaConstantPool::ConstantClass) {
- UserCommonClass* cl = 0;
- Value* res = getResolvedCommonClass(index, false, &cl);
-
- res = CallInst::Create(intrinsics->GetClassDelegateeFunction, res, "",
- currentBlock);
- push(res, false, upcalls->newClass);
- } else {
- fprintf(stderr, "I haven't verified your class file and it's malformed:"
- " unknown ldc %d in %s.%s!\n", type,
- UTF8Buffer(compilingClass->name).cString(),
- UTF8Buffer(compilingMethod->name).cString());
- abort();
- }
-}
-
-void JavaJIT::JITVerifyNull(Value* obj) {
-
- if (TheCompiler->hasExceptionsEnabled()) {
- Constant* zero = intrinsics->JavaObjectNullConstant;
- Value* test = new ICmpInst(*currentBlock, ICmpInst::ICMP_EQ, obj, zero, "");
-
- BasicBlock* exit = createBasicBlock("verifyNullExit");
- BasicBlock* cont = createBasicBlock("verifyNullCont");
-
- BranchInst::Create(exit, cont, test, currentBlock);
- currentBlock = exit;
- throwException(intrinsics->NullPointerExceptionFunction, 0, 0);
- currentBlock = cont;
- }
-
-}
-
-Value* JavaJIT::verifyAndComputePtr(Value* obj, Value* index,
- const Type* arrayType, bool verif) {
- JITVerifyNull(obj);
-
- if (index->getType() != Type::getInt32Ty(*llvmContext)) {
- index = new SExtInst(index, Type::getInt32Ty(*llvmContext), "", currentBlock);
- }
-
- if (TheCompiler->hasExceptionsEnabled()) {
- Value* size = arraySize(obj);
-
- Value* cmp = new ICmpInst(*currentBlock, ICmpInst::ICMP_ULT, index, size,
- "");
-
- BasicBlock* ifTrue = createBasicBlock("true verifyAndComputePtr");
- BasicBlock* ifFalse = createBasicBlock("false verifyAndComputePtr");
-
- BranchInst::Create(ifTrue, ifFalse, cmp, currentBlock);
-
- currentBlock = ifFalse;
- Value* args[2] = { obj, index };
- throwException(intrinsics->IndexOutOfBoundsExceptionFunction, args, 2);
- currentBlock = ifTrue;
- }
-
- Constant* zero = intrinsics->constantZero;
- Value* val = new BitCastInst(obj, arrayType, "", currentBlock);
-
- Value* indexes[3] = { zero, intrinsics->JavaArrayElementsOffsetConstant, index };
- Value* ptr = GetElementPtrInst::Create(val, indexes, indexes + 3, "",
- currentBlock);
-
- return ptr;
-
-}
-
-void JavaJIT::makeArgs(FunctionType::param_iterator it,
- uint32 index, std::vector<Value*>& Args, uint32 nb) {
- Args.reserve(nb + 2);
- mvm::ThreadAllocator threadAllocator;
- Value** args = (Value**)threadAllocator.Allocate(nb*sizeof(Value*));
- sint32 start = nb - 1;
- for (sint32 i = start; i >= 0; --i) {
- it--;
- if (it->get() == Type::getInt64Ty(*llvmContext) || it->get() == Type::getDoubleTy(*llvmContext)) {
- pop();
- }
- Value* tmp = pop();
-
- const Type* type = it->get();
- if (tmp->getType() != type) { // int8 or int16
- convertValue(tmp, type, currentBlock, false);
- }
- args[i] = tmp;
-
- }
-
- for (uint32 i = 0; i < nb; ++i) {
- Args.push_back(args[i]);
- }
-}
-
-Value* JavaJIT::getTarget(Signdef* signature) {
- int offset = 0;
- Typedef* const* arguments = signature->getArgumentsType();
- for (uint32 i = 0; i < signature->nbArguments; i++) {
- if (arguments[i]->isDouble() || arguments[i]->isLong()) {
- offset++;
- }
- offset++;
- }
- return objectStack[currentStackIndex - 1 - offset];
-}
-
-Instruction* JavaJIT::lowerMathOps(const UTF8* name,
- std::vector<Value*>& args) {
- if (name->equals(upcalls->abs)) {
- const Type* Ty = args[0]->getType();
- if (Ty == Type::getInt32Ty(*llvmContext)) {
- Constant* const_int32_9 = intrinsics->constantZero;
- Constant* const_int32_10 = intrinsics->constantMinusOne;
- BinaryOperator* int32_tmpneg =
- BinaryOperator::Create(Instruction::Sub, const_int32_9, args[0],
- "tmpneg", currentBlock);
- ICmpInst* int1_abscond =
- new ICmpInst(*currentBlock, ICmpInst::ICMP_SGT, args[0], const_int32_10,
- "abscond");
- return llvm::SelectInst::Create(int1_abscond, args[0], int32_tmpneg,
- "abs", currentBlock);
- } else if (Ty == Type::getInt64Ty(*llvmContext)) {
- Constant* const_int64_9 = intrinsics->constantLongZero;
- Constant* const_int64_10 = intrinsics->constantLongMinusOne;
-
- BinaryOperator* int64_tmpneg =
- BinaryOperator::Create(Instruction::Sub, const_int64_9, args[0],
- "tmpneg", currentBlock);
-
- ICmpInst* int1_abscond = new ICmpInst(*currentBlock, ICmpInst::ICMP_SGT,
- args[0], const_int64_10, "abscond");
-
- return llvm::SelectInst::Create(int1_abscond, args[0], int64_tmpneg,
- "abs", currentBlock);
- } else if (Ty == Type::getFloatTy(*llvmContext)) {
- return llvm::CallInst::Create(intrinsics->func_llvm_fabs_f32, args[0],
- "tmp1", currentBlock);
- } else if (Ty == Type::getDoubleTy(*llvmContext)) {
- return llvm::CallInst::Create(intrinsics->func_llvm_fabs_f64, args[0],
- "tmp1", currentBlock);
- }
- } else if (name->equals(upcalls->sqrt)) {
- return llvm::CallInst::Create(intrinsics->func_llvm_sqrt_f64, args[0],
- "tmp1", currentBlock);
- } else if (name->equals(upcalls->sin)) {
- return llvm::CallInst::Create(intrinsics->func_llvm_sin_f64, args[0],
- "tmp1", currentBlock);
- } else if (name->equals(upcalls->cos)) {
- return llvm::CallInst::Create(intrinsics->func_llvm_cos_f64, args[0],
- "tmp1", currentBlock);
- } else if (name->equals(upcalls->tan)) {
- return llvm::CallInst::Create(intrinsics->func_llvm_tan_f64, args[0],
- "tmp1", currentBlock);
- } else if (name->equals(upcalls->asin)) {
- return llvm::CallInst::Create(intrinsics->func_llvm_asin_f64, args[0],
- "tmp1", currentBlock);
- } else if (name->equals(upcalls->acos)) {
- return llvm::CallInst::Create(intrinsics->func_llvm_acos_f64, args[0],
- "tmp1", currentBlock);
- } else if (name->equals(upcalls->atan)) {
- return llvm::CallInst::Create(intrinsics->func_llvm_atan_f64, args[0],
- "tmp1", currentBlock);
- } else if (name->equals(upcalls->atan2)) {
- return llvm::CallInst::Create(intrinsics->func_llvm_atan2_f64,
- args.begin(), args.end(), "tmp1",
- currentBlock);
- } else if (name->equals(upcalls->exp)) {
- return llvm::CallInst::Create(intrinsics->func_llvm_exp_f64, args[0],
- "tmp1", currentBlock);
- } else if (name->equals(upcalls->log)) {
- return llvm::CallInst::Create(intrinsics->func_llvm_log_f64, args[0],
- "tmp1", currentBlock);
- } else if (name->equals(upcalls->pow)) {
- return llvm::CallInst::Create(intrinsics->func_llvm_pow_f64, args.begin(),
- args.end(), "tmp1", currentBlock);
- } else if (name->equals(upcalls->ceil)) {
- return llvm::CallInst::Create(intrinsics->func_llvm_ceil_f64, args[0], "tmp1",
- currentBlock);
- } else if (name->equals(upcalls->floor)) {
- return llvm::CallInst::Create(intrinsics->func_llvm_floor_f64, args[0],
- "tmp1", currentBlock);
- } else if (name->equals(upcalls->rint)) {
- return llvm::CallInst::Create(intrinsics->func_llvm_rint_f64, args[0],
- "tmp1", currentBlock);
- } else if (name->equals(upcalls->cbrt)) {
- return llvm::CallInst::Create(intrinsics->func_llvm_cbrt_f64, args[0], "tmp1",
- currentBlock);
- } else if (name->equals(upcalls->cosh)) {
- return llvm::CallInst::Create(intrinsics->func_llvm_cosh_f64, args[0], "tmp1",
- currentBlock);
- } else if (name->equals(upcalls->expm1)) {
- return llvm::CallInst::Create(intrinsics->func_llvm_expm1_f64, args[0],
- "tmp1", currentBlock);
- } else if (name->equals(upcalls->hypot)) {
- return llvm::CallInst::Create(intrinsics->func_llvm_hypot_f64, args[0],
- "tmp1", currentBlock);
- } else if (name->equals(upcalls->log10)) {
- return llvm::CallInst::Create(intrinsics->func_llvm_log10_f64, args[0],
- "tmp1", currentBlock);
- } else if (name->equals(upcalls->log1p)) {
- return llvm::CallInst::Create(intrinsics->func_llvm_log1p_f64, args[0],
- "tmp1", currentBlock);
- } else if (name->equals(upcalls->sinh)) {
- return llvm::CallInst::Create(intrinsics->func_llvm_sinh_f64, args[0],
- "tmp1", currentBlock);
- } else if (name->equals(upcalls->tanh)) {
- return llvm::CallInst::Create(intrinsics->func_llvm_tanh_f64, args[0],
- "tmp1", currentBlock);
- }
-
- return 0;
-
-}
-
-
-Instruction* JavaJIT::invokeInline(JavaMethod* meth,
- std::vector<Value*>& args) {
- JavaJIT jit(TheCompiler, meth, llvmFunction);
- jit.unifiedUnreachable = unifiedUnreachable;
- jit.inlineMethods = inlineMethods;
- jit.inlineMethods[meth] = true;
- jit.inlining = true;
- Instruction* ret = jit.inlineCompile(currentBlock,
- currentExceptionBlock, args);
- inlineMethods[meth] = false;
- return ret;
-}
-
-void JavaJIT::invokeSpecial(uint16 index) {
- JavaConstantPool* ctpInfo = compilingClass->ctpInfo;
- JavaMethod* meth = 0;
- Signdef* signature = 0;
- const UTF8* name = 0;
- const UTF8* cl = 0;
-
- ctpInfo->nameOfStaticOrSpecialMethod(index, cl, name, signature);
- LLVMSignatureInfo* LSI = TheCompiler->getSignatureInfo(signature);
- const llvm::FunctionType* virtualType = LSI->getVirtualType();
- llvm::Instruction* val = 0;
-
- if (!meth) {
- meth = ctpInfo->infoOfStaticOrSpecialMethod(index, ACC_VIRTUAL, signature);
- }
-
- Value* func = 0;
- bool needsInit = false;
- if (TheCompiler->needsCallback(meth, &needsInit)) {
- if (needsInit) {
- // Make sure the class is loaded before materializing the method.
- uint32 clIndex = ctpInfo->getClassIndexFromMethod(index);
- UserCommonClass* cl = 0;
- Value* Cl = getResolvedCommonClass(clIndex, false, &cl);
- if (cl == NULL) {
- CallInst::Create(intrinsics->ForceLoadedCheckFunction, Cl, "",
- currentBlock);
- }
- }
- func = TheCompiler->addCallback(compilingClass, index, signature, false,
- currentBlock);
- } else {
- func = TheCompiler->getMethod(meth);
- }
-
- std::vector<Value*> args;
- FunctionType::param_iterator it = virtualType->param_end();
- makeArgs(it, index, args, signature->nbArguments + 1);
- JITVerifyNull(args[0]);
-
- if (meth == upcalls->InitObject) {
- return;
- }
-
- if (meth && canBeInlined(meth)) {
- val = invokeInline(meth, args);
- } else {
- val = invoke(func, args, "", currentBlock);
- }
-
- const llvm::Type* retType = virtualType->getReturnType();
- if (retType != Type::getVoidTy(*llvmContext)) {
- if (retType == intrinsics->JavaObjectType) {
- JnjvmClassLoader* JCL = compilingClass->classLoader;
- push(val, false, signature->getReturnType()->findAssocClass(JCL));
- } else {
- push(val, signature->getReturnType()->isUnsigned());
- if (retType == Type::getDoubleTy(*llvmContext) ||
- retType == Type::getInt64Ty(*llvmContext)) {
- push(intrinsics->constantZero, false);
- }
- }
- }
-}
-
-void JavaJIT::invokeStatic(uint16 index) {
- JavaConstantPool* ctpInfo = compilingClass->ctpInfo;
- Signdef* signature = 0;
- const UTF8* name = 0;
- const UTF8* className = 0;
- ctpInfo->nameOfStaticOrSpecialMethod(index, className, name, signature);
- LLVMSignatureInfo* LSI = TheCompiler->getSignatureInfo(signature);
- const llvm::FunctionType* staticType = LSI->getStaticType();
- ctpInfo->markAsStaticCall(index);
- llvm::Instruction* val = 0;
-
- if (className->equals(upcalls->stackWalkerName)) {
- callsStackWalker = true;
- }
-
- JavaMethod* meth = ctpInfo->infoOfStaticOrSpecialMethod(index, ACC_STATIC,
- signature);
-
-
- uint32 clIndex = ctpInfo->getClassIndexFromMethod(index);
- UserClass* cl = 0;
- Value* Cl = getResolvedClass(clIndex, true, true, &cl);
- if (!meth || (cl && needsInitialisationCheck(cl, compilingClass))) {
- CallInst::Create(intrinsics->ForceInitialisationCheckFunction, Cl, "",
- currentBlock);
- }
-
- Value* func = 0;
- bool needsInit = false;
- if (TheCompiler->needsCallback(meth, &needsInit)) {
- func = TheCompiler->addCallback(compilingClass, index, signature,
- true, currentBlock);
- } else {
- func = TheCompiler->getMethod(meth);
- }
-
- std::vector<Value*> args; // size = [signature->nbIn + 2];
- FunctionType::param_iterator it = staticType->param_end();
- makeArgs(it, index, args, signature->nbArguments);
-
- if (className->equals(upcalls->mathName)) {
- val = lowerMathOps(name, args);
- }
-
- if (val == NULL) {
- if (meth != NULL && canBeInlined(meth)) {
- val = invokeInline(meth, args);
- } else {
- val = invoke(func, args, "", currentBlock);
- }
- }
-
- const llvm::Type* retType = staticType->getReturnType();
- if (retType != Type::getVoidTy(*llvmContext)) {
- if (retType == intrinsics->JavaObjectType) {
- JnjvmClassLoader* JCL = compilingClass->classLoader;
- push(val, false, signature->getReturnType()->findAssocClass(JCL));
- } else {
- push(val, signature->getReturnType()->isUnsigned());
- if (retType == Type::getDoubleTy(*llvmContext) ||
- retType == Type::getInt64Ty(*llvmContext)) {
- push(intrinsics->constantZero, false);
- }
- }
- }
-}
-
-Value* JavaJIT::getConstantPoolAt(uint32 index, Function* resolver,
- const Type* returnType,
- Value* additionalArg, bool doThrow) {
-
-// This makes unswitch loop very unhappy time-wise, but makes GVN happy
-// number-wise. IMO, it's better to have this than Unswitch.
- JavaConstantPool* ctp = compilingClass->ctpInfo;
- Value* CTP = TheCompiler->getConstantPool(ctp);
- Value* Cl = TheCompiler->getNativeClass(compilingClass);
-
- std::vector<Value*> Args;
- Args.push_back(resolver);
- Args.push_back(CTP);
- Args.push_back(Cl);
- Args.push_back(ConstantInt::get(Type::getInt32Ty(*llvmContext), index));
- if (additionalArg) Args.push_back(additionalArg);
-
- Value* res = 0;
- if (doThrow) {
- res = invoke(intrinsics->GetConstantPoolAtFunction, Args, "",
- currentBlock);
- } else {
- res = CallInst::Create(intrinsics->GetConstantPoolAtFunction, Args.begin(),
- Args.end(), "", currentBlock);
- }
-
- const Type* realType =
- intrinsics->GetConstantPoolAtFunction->getReturnType();
- if (returnType == Type::getInt32Ty(*llvmContext)) {
- return new PtrToIntInst(res, Type::getInt32Ty(*llvmContext), "", currentBlock);
- } else if (returnType != realType) {
- return new BitCastInst(res, returnType, "", currentBlock);
- }
-
- return res;
-}
-
-Value* JavaJIT::getResolvedCommonClass(uint16 index, bool doThrow,
- UserCommonClass** alreadyResolved) {
-
- JavaConstantPool* ctpInfo = compilingClass->ctpInfo;
- CommonClass* cl = ctpInfo->getMethodClassIfLoaded(index);
- Value* node = 0;
- if (cl && (!cl->isClass() || cl->asClass()->isResolved())) {
- if (alreadyResolved) *alreadyResolved = cl;
- node = TheCompiler->getNativeClass(cl);
- // Since we only allocate for array classes that we own and
- // ony primitive arrays are already allocated, verify that the class
- // array is not external.
- if (TheCompiler->isStaticCompiling() && cl->isArray() &&
- node->getType() != intrinsics->JavaClassArrayType) {
- node = new LoadInst(node, "", currentBlock);
- }
- if (node->getType() != intrinsics->JavaCommonClassType) {
- node = new BitCastInst(node, intrinsics->JavaCommonClassType, "",
- currentBlock);
- }
- } else {
- node = getConstantPoolAt(index, intrinsics->ClassLookupFunction,
- intrinsics->JavaCommonClassType, 0, doThrow);
- }
-
- return node;
-}
-
-Value* JavaJIT::getResolvedClass(uint16 index, bool clinit, bool doThrow,
- Class** alreadyResolved) {
-
- JavaConstantPool* ctpInfo = compilingClass->ctpInfo;
- Class* cl = (Class*)(ctpInfo->getMethodClassIfLoaded(index));
- Value* node = 0;
- bool needsInit = true;
- if (cl && cl->isResolved()) {
- if (alreadyResolved) (*alreadyResolved) = cl;
- node = TheCompiler->getNativeClass(cl);
- needsInit = needsInitialisationCheck(cl, compilingClass);
- } else {
- node = getConstantPoolAt(index, intrinsics->ClassLookupFunction,
- intrinsics->JavaClassType, 0, doThrow);
- }
-
-
- if (clinit && needsInit) {
- if (node->getType() != intrinsics->JavaClassType) {
- node = new BitCastInst(node, intrinsics->JavaClassType, "", currentBlock);
- }
- return invoke(intrinsics->InitialisationCheckFunction, node, "",
- currentBlock);
- } else {
- return node;
- }
-}
-
-void JavaJIT::invokeNew(uint16 index) {
-
- Class* cl = 0;
- Value* Cl = getResolvedClass(index, true, true, &cl);
-
- Value* VT = 0;
- Value* Size = 0;
-
- if (cl) {
- VT = TheCompiler->getVirtualTable(cl->virtualVT);
- LLVMClassInfo* LCI = TheCompiler->getClassInfo(cl);
- Size = LCI->getVirtualSize();
-
- bool needsCheck = needsInitialisationCheck(cl, compilingClass);
- if (needsCheck) {
- Cl = invoke(intrinsics->ForceInitialisationCheckFunction, Cl, "",
- currentBlock);
- }
-
- } else {
- VT = CallInst::Create(intrinsics->GetVTFromClassFunction, Cl, "",
- currentBlock);
- Size = CallInst::Create(intrinsics->GetObjectSizeFromClassFunction, Cl,
- "", currentBlock);
- }
-
- VT = new BitCastInst(VT, intrinsics->ptrType, "", currentBlock);
- Instruction* val = invoke(cl ? intrinsics->AllocateFunction :
- intrinsics->AllocateUnresolvedFunction,
- Size, VT, "", currentBlock);
-
- addHighLevelType(val, cl ? cl : upcalls->OfObject);
- Instruction* res = new BitCastInst(val, intrinsics->JavaObjectType, "", currentBlock);
- push(res, false, cl ? cl : upcalls->OfObject);
-
- // Make sure to add the object to the finalization list after it has been
- // pushed.
- if (cl && cl->virtualVT->destructor) {
- CallInst::Create(intrinsics->AddFinalizationCandidate, val, "", currentBlock);
- }
-}
-
-Value* JavaJIT::ldResolved(uint16 index, bool stat, Value* object,
- const Type* fieldTypePtr) {
- JavaConstantPool* info = compilingClass->ctpInfo;
-
- JavaField* field = info->lookupField(index, stat);
- if (field && field->classDef->isResolved()) {
- LLVMClassInfo* LCI = TheCompiler->getClassInfo(field->classDef);
- LLVMFieldInfo* LFI = TheCompiler->getFieldInfo(field);
- const Type* type = 0;
- if (stat) {
- type = LCI->getStaticType();
- Value* Cl = TheCompiler->getNativeClass(field->classDef);
- bool needsCheck = needsInitialisationCheck(field->classDef,
- compilingClass);
- if (needsCheck) {
- Cl = invoke(intrinsics->InitialisationCheckFunction, Cl, "",
- currentBlock);
- }
- if (needsCheck) {
- CallInst::Create(intrinsics->ForceInitialisationCheckFunction, Cl, "",
- currentBlock);
- }
-
- object = TheCompiler->getStaticInstance(field->classDef);
- } else {
- object = new LoadInst(
- object, "", TheCompiler->useCooperativeGC(), currentBlock);
- JITVerifyNull(object);
- type = LCI->getVirtualType();
- }
-
- Value* objectConvert = new BitCastInst(object, type, "", currentBlock);
-
- Value* args[2] = { intrinsics->constantZero, LFI->getOffset() };
- Value* ptr = llvm::GetElementPtrInst::Create(objectConvert,
- args, args + 2, "",
- currentBlock);
- return ptr;
- }
-
- const Type* Pty = intrinsics->arrayPtrType;
- Constant* zero = intrinsics->constantZero;
-
- Function* func = stat ? intrinsics->StaticFieldLookupFunction :
- intrinsics->VirtualFieldLookupFunction;
-
- const Type* returnType = 0;
- if (stat) {
- returnType = intrinsics->ptrType;
- } else {
- returnType = Type::getInt32Ty(*llvmContext);
- }
-
- Value* ptr = getConstantPoolAt(index, func, returnType, 0, true);
- if (!stat) {
- object = new LoadInst(
- object, "", TheCompiler->useCooperativeGC(), currentBlock);
- Value* tmp = new BitCastInst(object, Pty, "", currentBlock);
- Value* args[2] = { zero, ptr };
- ptr = GetElementPtrInst::Create(tmp, args, args + 2, "", currentBlock);
- }
-
- return new BitCastInst(ptr, fieldTypePtr, "", currentBlock);
-}
-
-void JavaJIT::convertValue(Value*& val, const Type* t1, BasicBlock* currentBlock,
- bool usign) {
- const Type* t2 = val->getType();
- if (t1 != t2) {
- if (t1->isIntegerTy() && t2->isIntegerTy()) {
- if (t2->getPrimitiveSizeInBits() < t1->getPrimitiveSizeInBits()) {
- if (usign) {
- val = new ZExtInst(val, t1, "", currentBlock);
- } else {
- val = new SExtInst(val, t1, "", currentBlock);
- }
- } else {
- val = new TruncInst(val, t1, "", currentBlock);
- }
- } else if (t1->isFloatTy() && t2->isFloatTy()) {
- if (t2->getPrimitiveSizeInBits() < t1->getPrimitiveSizeInBits()) {
- val = new FPExtInst(val, t1, "", currentBlock);
- } else {
- val = new FPTruncInst(val, t1, "", currentBlock);
- }
- } else if (isa<PointerType>(t1) && isa<PointerType>(t2)) {
- val = new BitCastInst(val, t1, "", currentBlock);
- }
- }
-}
-
-
-void JavaJIT::setStaticField(uint16 index) {
- Typedef* sign = compilingClass->ctpInfo->infoOfField(index);
- LLVMAssessorInfo& LAI = TheCompiler->getTypedefInfo(sign);
- const Type* type = LAI.llvmType;
-
- Value* ptr = ldResolved(index, true, NULL, LAI.llvmTypePtr);
-
- Value* val = pop();
- if (type == Type::getInt64Ty(*llvmContext) ||
- type == Type::getDoubleTy(*llvmContext)) {
- val = pop();
- }
-
- if (type != val->getType()) { // int1, int8, int16
- convertValue(val, type, currentBlock, false);
- }
-
- new StoreInst(val, ptr, false, currentBlock);
-}
-
-void JavaJIT::getStaticField(uint16 index) {
- Typedef* sign = compilingClass->ctpInfo->infoOfField(index);
- LLVMAssessorInfo& LAI = TheCompiler->getTypedefInfo(sign);
- const Type* type = LAI.llvmType;
-
- Value* ptr = ldResolved(index, true, NULL, LAI.llvmTypePtr);
-
- bool final = false;
-
- if (!compilingMethod->name->equals(upcalls->clinitName)) {
- JavaField* field = compilingClass->ctpInfo->lookupField(index, true);
- if (field && field->classDef->isReady()) final = isFinal(field->access);
- if (final) {
- if (sign->isPrimitive()) {
- const PrimitiveTypedef* prim = (PrimitiveTypedef*)sign;
- if (prim->isInt()) {
- sint32 val = field->getStaticInt32Field();
- push(ConstantInt::get(Type::getInt32Ty(*llvmContext), val), false);
- } else if (prim->isByte()) {
- sint8 val = (sint8)field->getStaticInt8Field();
- push(ConstantInt::get(Type::getInt8Ty(*llvmContext), val), false);
- } else if (prim->isBool()) {
- uint8 val = (uint8)field->getStaticInt8Field();
- push(ConstantInt::get(Type::getInt8Ty(*llvmContext), val), true);
- } else if (prim->isShort()) {
- sint16 val = (sint16)field->getStaticInt16Field();
- push(ConstantInt::get(Type::getInt16Ty(*llvmContext), val), false);
- } else if (prim->isChar()) {
- uint16 val = (uint16)field->getStaticInt16Field();
- push(ConstantInt::get(Type::getInt16Ty(*llvmContext), val), true);
- } else if (prim->isLong()) {
- sint64 val = (sint64)field->getStaticLongField();
- push(ConstantInt::get(Type::getInt64Ty(*llvmContext), val), false);
- } else if (prim->isFloat()) {
- float val = (float)field->getStaticFloatField();
- push(ConstantFP::get(Type::getFloatTy(*llvmContext), val), false);
- } else if (prim->isDouble()) {
- double val = (double)field->getStaticDoubleField();
- push(ConstantFP::get(Type::getDoubleTy(*llvmContext), val), false);
- } else {
- abort();
- }
- } else {
- if (TheCompiler->isStaticCompiling() && !TheCompiler->useCooperativeGC()) {
- JavaObject* val = field->getStaticObjectField();
- JnjvmClassLoader* JCL = field->classDef->classLoader;
- Value* V = TheCompiler->getFinalObject(val, sign->assocClass(JCL));
- CommonClass* cl = mvm::Collector::begOf(val) ?
- JavaObject::getClass(val) : NULL;
- push(V, false, cl);
- } else {
- // Do not call getFinalObject, as the object may move in-between two
- // loads of this static.
- Value* V = new LoadInst(ptr, "", currentBlock);
- JnjvmClassLoader* JCL = compilingClass->classLoader;
- push(V, false, sign->findAssocClass(JCL));
- }
- }
- }
- }
-
- if (!final) {
- JnjvmClassLoader* JCL = compilingClass->classLoader;
- CommonClass* cl = sign->findAssocClass(JCL);
- push(new LoadInst(ptr, "", currentBlock), sign->isUnsigned(), cl);
- }
- if (type == Type::getInt64Ty(*llvmContext) ||
- type == Type::getDoubleTy(*llvmContext)) {
- push(intrinsics->constantZero, false);
- }
-}
-
-void JavaJIT::setVirtualField(uint16 index) {
- Typedef* sign = compilingClass->ctpInfo->infoOfField(index);
- LLVMAssessorInfo& LAI = TheCompiler->getTypedefInfo(sign);
- const Type* type = LAI.llvmType;
- int stackIndex = currentStackIndex - 2;
- if (type == Type::getInt64Ty(*llvmContext) ||
- type == Type::getDoubleTy(*llvmContext)) {
- stackIndex--;
- }
- Value* object = objectStack[stackIndex];
- Value* ptr = ldResolved(index, false, object, LAI.llvmTypePtr);
-
- Value* val = pop();
- if (type == Type::getInt64Ty(*llvmContext) ||
- type == Type::getDoubleTy(*llvmContext)) {
- val = pop();
- }
- pop(); // Pop the object
-
- if (type != val->getType()) { // int1, int8, int16
- convertValue(val, type, currentBlock, false);
- }
-
- new StoreInst(val, ptr, false, currentBlock);
-}
-
-void JavaJIT::getVirtualField(uint16 index) {
- Typedef* sign = compilingClass->ctpInfo->infoOfField(index);
- JnjvmClassLoader* JCL = compilingClass->classLoader;
- CommonClass* cl = sign->findAssocClass(JCL);
-
- LLVMAssessorInfo& LAI = TheCompiler->getTypedefInfo(sign);
- const Type* type = LAI.llvmType;
- Value* obj = objectStack[currentStackIndex - 1];
- pop(); // Pop the object
-
- Value* ptr = ldResolved(index, false, obj, LAI.llvmTypePtr);
-
- bool final = false;
-
- // In init methods, the fields have not been set yet.
- if (!compilingMethod->name->equals(upcalls->initName)) {
- JavaField* field = compilingClass->ctpInfo->lookupField(index, false);
- if (field) {
- final = isFinal(field->access) && sign->isPrimitive();
- }
- if (final) {
- Function* F = 0;
- assert(sign->isPrimitive());
- const PrimitiveTypedef* prim = (PrimitiveTypedef*)sign;
- if (prim->isInt()) {
- F = intrinsics->GetFinalInt32FieldFunction;
- } else if (prim->isByte()) {
- F = intrinsics->GetFinalInt8FieldFunction;
- } else if (prim->isBool()) {
- F = intrinsics->GetFinalInt8FieldFunction;
- } else if (prim->isShort()) {
- F = intrinsics->GetFinalInt16FieldFunction;
- } else if (prim->isChar()) {
- F = intrinsics->GetFinalInt16FieldFunction;
- } else if (prim->isLong()) {
- F = intrinsics->GetFinalLongFieldFunction;
- } else if (prim->isFloat()) {
- F = intrinsics->GetFinalFloatFieldFunction;
- } else if (prim->isDouble()) {
- F = intrinsics->GetFinalDoubleFieldFunction;
- } else {
- abort();
- }
- push(CallInst::Create(F, ptr, "", currentBlock), sign->isUnsigned(), cl);
- }
- }
-
- if (!final) push(new LoadInst(ptr, "", currentBlock), sign->isUnsigned(), cl);
- if (type == Type::getInt64Ty(*llvmContext) ||
- type == Type::getDoubleTy(*llvmContext)) {
- push(intrinsics->constantZero, false);
- }
-}
-
-
-void JavaJIT::invokeInterface(uint16 index) {
-
- // Do the usual
- JavaConstantPool* ctpInfo = compilingClass->ctpInfo;
- const UTF8* name = 0;
- Signdef* signature = ctpInfo->infoOfInterfaceOrVirtualMethod(index, name);
-
- LLVMSignatureInfo* LSI = TheCompiler->getSignatureInfo(signature);
- const llvm::FunctionType* virtualType = LSI->getVirtualType();
- const llvm::PointerType* virtualPtrType = LSI->getVirtualPtrType();
-
- const llvm::Type* retType = virtualType->getReturnType();
-
- CommonClass* cl = 0;
- JavaMethod* meth = 0;
- ctpInfo->infoOfMethod(index, ACC_VIRTUAL, cl, meth);
- Value* Meth = 0;
-
- if (meth) {
- Meth = TheCompiler->getMethodInClass(meth);
- } else {
- Meth = getConstantPoolAt(index, intrinsics->InterfaceLookupFunction,
- intrinsics->JavaMethodType, 0, true);
- }
-
- uint32_t tableIndex = InterfaceMethodTable::getIndex(name, signature->keyName);
- Constant* Index = ConstantInt::get(Type::getInt32Ty(*llvmContext),
- tableIndex);
- Value* targetObject = getTarget(signature);
- targetObject = new LoadInst(
- targetObject, "", TheCompiler->useCooperativeGC(), currentBlock);
- JITVerifyNull(targetObject);
- // TODO: The following code needs more testing.
-#if 0
- BasicBlock* endBlock = createBasicBlock("end interface invoke");
- PHINode * node = PHINode::Create(virtualPtrType, "", endBlock);
-
- BasicBlock* label_bb = createBasicBlock("bb");
- BasicBlock* label_bb4 = createBasicBlock("bb4");
- BasicBlock* label_bb6 = createBasicBlock("bb6");
- BasicBlock* label_bb7 = createBasicBlock("bb7");
-
- // Block entry (label_entry)
- Value* VT = CallInst::Create(intrinsics->GetVTFunction, targetObject, "",
- currentBlock);
- Value* IMT = CallInst::Create(intrinsics->GetIMTFunction, VT, "",
- currentBlock);
-
-
- Value* indices[2] = { intrinsics->constantZero, Index };
- Instruction* ptr_18 = GetElementPtrInst::Create(IMT, indices, indices + 2, "",
- currentBlock);
- Instruction* int32_19 = new LoadInst(ptr_18, "", false, currentBlock);
- int32_19 = new PtrToIntInst(int32_19, intrinsics->pointerSizeType, "",
- currentBlock);
- Value* one = ConstantInt::get(intrinsics->pointerSizeType, 1);
- Value* zero = ConstantInt::get(intrinsics->pointerSizeType, 0);
- BinaryOperator* int32_20 = BinaryOperator::Create(Instruction::And, int32_19,
- one, "", currentBlock);
- ICmpInst* int1_toBool = new ICmpInst(*currentBlock, ICmpInst::ICMP_EQ,
- int32_20, zero, "toBool");
- BranchInst::Create(label_bb, label_bb4, int1_toBool, currentBlock);
-
- // Block bb (label_bb)
- currentBlock = label_bb;
- CastInst* ptr_22 = new IntToPtrInst(int32_19, virtualPtrType, "", currentBlock);
-
- node->addIncoming(ptr_22, currentBlock);
- BranchInst::Create(endBlock, currentBlock);
-
- // Block bb4 (label_bb4)
- currentBlock = label_bb4;
- Constant* MinusTwo = ConstantInt::get(intrinsics->pointerSizeType, -2);
- BinaryOperator* int32_25 = BinaryOperator::Create(Instruction::And, int32_19,
- MinusTwo, "", currentBlock);
- const PointerType* Ty = PointerType::getUnqual(intrinsics->JavaMethodType);
- CastInst* ptr_26 = new IntToPtrInst(int32_25, Ty, "", currentBlock);
- LoadInst* int32_27 = new LoadInst(ptr_26, "", false, currentBlock);
- ICmpInst* int1_28 = new ICmpInst(*currentBlock, ICmpInst::ICMP_EQ, int32_27,
- Meth, "");
- BranchInst::Create(label_bb6, label_bb7, int1_28, currentBlock);
-
- // Block bb6 (label_bb6)
- currentBlock = label_bb6;
- PHINode* ptr_table_0_lcssa = PHINode::Create(Ty, "table.0.lcssa",
- currentBlock);
- ptr_table_0_lcssa->reserveOperandSpace(2);
- ptr_table_0_lcssa->addIncoming(ptr_26, label_bb4);
-
- GetElementPtrInst* ptr_31 = GetElementPtrInst::Create(ptr_table_0_lcssa,
- intrinsics->constantOne, "",
- currentBlock);
-
- LoadInst* int32_32 = new LoadInst(ptr_31, "", false, currentBlock);
- CastInst* ptr_33 = new BitCastInst(int32_32, virtualPtrType, "",
- currentBlock);
- node->addIncoming(ptr_33, currentBlock);
-
- BranchInst::Create(endBlock, currentBlock);
-
- // Block bb7 (label_bb7)
- currentBlock = label_bb7;
- PHINode* int32_indvar = PHINode::Create(Type::getInt32Ty(*llvmContext),
- "indvar", currentBlock);
- int32_indvar->reserveOperandSpace(2);
- int32_indvar->addIncoming(intrinsics->constantZero, label_bb4);
-
- BinaryOperator* int32_table_010_rec =
- BinaryOperator::Create(Instruction::Shl, int32_indvar, intrinsics->constantOne,
- "table.010.rec", currentBlock);
-
- BinaryOperator* int32__rec =
- BinaryOperator::Create(Instruction::Add, int32_table_010_rec,
- intrinsics->constantTwo, ".rec", currentBlock);
- GetElementPtrInst* ptr_37 = GetElementPtrInst::Create(ptr_26, int32__rec, "",
- currentBlock);
- LoadInst* int32_38 = new LoadInst(ptr_37, "", false, currentBlock);
- ICmpInst* int1_39 = new ICmpInst(*currentBlock, ICmpInst::ICMP_EQ, int32_38,
- Meth, "");
- BinaryOperator* int32_indvar_next =
- BinaryOperator::Create(Instruction::Add, int32_indvar, intrinsics->constantOne,
- "indvar.next", currentBlock);
- BranchInst::Create(label_bb6, label_bb7, int1_39, currentBlock);
-
- int32_indvar->addIncoming(int32_indvar_next, currentBlock);
- ptr_table_0_lcssa->addIncoming(ptr_37, currentBlock);
-
- currentBlock = endBlock;
-#else
- std::vector<Value*> Args;
- Args.push_back(targetObject);
- Args.push_back(Meth);
- Args.push_back(Index);
- Value* node =
- invoke(intrinsics->ResolveInterfaceFunction, Args, "", currentBlock);
- node = new BitCastInst(node, virtualPtrType, "", currentBlock);
-#endif
-
- std::vector<Value*> args; // size = [signature->nbIn + 3];
- FunctionType::param_iterator it = virtualType->param_end();
- makeArgs(it, index, args, signature->nbArguments + 1);
- JITVerifyNull(args[0]);
- Value* ret = invoke(node, args, "", currentBlock);
- if (retType != Type::getVoidTy(*llvmContext)) {
- if (ret->getType() == intrinsics->JavaObjectType) {
- JnjvmClassLoader* JCL = compilingClass->classLoader;
- push(ret, false, signature->getReturnType()->findAssocClass(JCL));
- } else {
- push(ret, signature->getReturnType()->isUnsigned());
- if (retType == Type::getDoubleTy(*llvmContext) ||
- retType == Type::getInt64Ty(*llvmContext)) {
- push(intrinsics->constantZero, false);
- }
- }
- }
-}
-
-void JavaJIT::lowerArraycopy(std::vector<Value*>& args) {
- Function* meth = TheCompiler->getMethod(upcalls->VMSystemArraycopy);
-
- Value* ptr_src = args[0];
- Value* int32_start = args[1];
- Value* ptr_dst = args[2];
- Value* int32_start2 = args[3];
- Value* int32_length = args[4];
-
- JITVerifyNull(ptr_src);
- JITVerifyNull(ptr_dst);
-
- BasicBlock* label_entry = currentBlock;
- BasicBlock* label_bb = createBasicBlock("bb");
- BasicBlock* label_bb2 = createBasicBlock("bb2");
- BasicBlock* label_bb4 = createBasicBlock("bb4");
- BasicBlock* label_bb5 = createBasicBlock("bb5");
- BasicBlock* label_bb12_preheader = createBasicBlock("bb12.preheader");
- BasicBlock* label_bb7 = createBasicBlock("bb7");
- BasicBlock* label_bb11 = createBasicBlock("bb11");
- BasicBlock* label_memmove = createBasicBlock("memmove");
- BasicBlock* label_backward = createBasicBlock("backward");
- BasicBlock* label_return = createBasicBlock("return");
-
- BasicBlock* log_label_entry = createBasicBlock("log_entry");
- BasicBlock* log_label_bb = createBasicBlock("log_bb");
-
- // Block entry (label_entry)
- CallInst* ptr_16 = CallInst::Create(intrinsics->GetVTFunction, ptr_src, "",
- label_entry);
- CallInst* ptr_17 = CallInst::Create(intrinsics->GetVTFunction, ptr_dst, "",
- label_entry);
-
- ICmpInst* int1_18 = new ICmpInst(*label_entry, ICmpInst::ICMP_EQ, ptr_16,
- ptr_17, "");
- BranchInst::Create(label_bb, label_bb2, int1_18, label_entry);
-
- // Block bb (label_bb)
- currentBlock = label_bb;
- CallInst* ptr_20 = CallInst::Create(intrinsics->GetClassFunction, ptr_src, "",
- label_bb);
- std::vector<Value*> ptr_21_indices;
- ptr_21_indices.push_back(intrinsics->constantZero);
- ptr_21_indices.push_back(intrinsics->OffsetAccessInCommonClassConstant);
- Instruction* ptr_21 =
- GetElementPtrInst::Create(ptr_20, ptr_21_indices.begin(),
- ptr_21_indices.end(), "", label_bb);
- LoadInst* int32_22 = new LoadInst(ptr_21, "", false, label_bb);
- Value* cmp = BinaryOperator::CreateAnd(int32_22, intrinsics->IsArrayConstant, "",
- label_bb);
- Value* zero = ConstantInt::get(Type::getInt16Ty(*llvmContext), 0);
- ICmpInst* int1_23 = new ICmpInst(*label_bb, ICmpInst::ICMP_NE, cmp, zero, "");
- BranchInst::Create(label_bb4, label_bb2, int1_23, label_bb);
-
-
- // Block bb2 (label_bb2)
- currentBlock = label_bb2;
- invoke(meth, args, "", label_bb2);
- BranchInst::Create(label_return, currentBlock);
-
-
- // Block bb4 (label_bb4)
- currentBlock = label_bb4;
- BinaryOperator* int32_27 = BinaryOperator::Create(Instruction::Add,
- int32_length, int32_start,
- "", label_bb4);
- Value* int32_28 = arraySize(ptr_src);
-
- ICmpInst* int1_29 = new ICmpInst(*label_bb4, ICmpInst::ICMP_ULE, int32_27,
- int32_28, "");
- BranchInst::Create(label_bb5, label_bb7, int1_29, label_bb4);
-
- // Block bb5 (label_bb5)
- currentBlock = label_bb5;
- BinaryOperator* int32_31 = BinaryOperator::Create(Instruction::Add,
- int32_length, int32_start2,
- "", label_bb5);
- Value* int32_32 = arraySize(ptr_dst);
-
- ICmpInst* int1_33 = new ICmpInst(*label_bb5, ICmpInst::ICMP_ULE, int32_31,
- int32_32, "");
- BranchInst::Create(label_bb12_preheader, label_bb7, int1_33, label_bb5);
-
- // Block bb12.preheader (label_bb12_preheader)
- currentBlock = label_bb12_preheader;
- ICmpInst* int1_35 = new ICmpInst(*label_bb12_preheader, ICmpInst::ICMP_UGT,
- int32_length, intrinsics->constantZero, "");
- BranchInst::Create(log_label_entry, label_return, int1_35, label_bb12_preheader);
-
- // Block bb7 (label_bb7)
- currentBlock = label_bb7;
- Value* VTArgs[1] = { Constant::getNullValue(intrinsics->VTType) };
- throwException(intrinsics->ArrayStoreExceptionFunction, VTArgs, 1);
-
-
-
- // Block entry (label_entry)
- currentBlock = log_label_entry;
- Value* ptr_10_indices[2] = { intrinsics->constantZero,
- intrinsics->OffsetBaseClassInArrayClassConstant };
- Instruction* temp = new BitCastInst(ptr_20, intrinsics->JavaClassArrayType, "",
- log_label_entry);
- Instruction* ptr_10 = GetElementPtrInst::Create(temp, ptr_10_indices,
- ptr_10_indices + 2, "",
- log_label_entry);
-
- LoadInst* ptr_11 = new LoadInst(ptr_10, "", false, log_label_entry);
-
- Value* ptr_12_indices[2] = { intrinsics->constantZero,
- intrinsics->OffsetAccessInCommonClassConstant };
- Instruction* ptr_12 = GetElementPtrInst::Create(ptr_11, ptr_12_indices,
- ptr_12_indices + 2, "",
- log_label_entry);
- LoadInst* int16_13 = new LoadInst(ptr_12, "", false, log_label_entry);
-
- BinaryOperator* int32_15 = BinaryOperator::Create(Instruction::And, int16_13,
- intrinsics->IsPrimitiveConstant,
- "", log_label_entry);
- ICmpInst* int1_16 = new ICmpInst(*log_label_entry, ICmpInst::ICMP_EQ,
- int32_15, zero, "");
- BranchInst::Create(label_bb2, log_label_bb, int1_16, log_label_entry);
-
- // Block bb (log_label_bb)
- currentBlock = log_label_bb;
- Value* ptr_11_indices[2] = { intrinsics->constantZero,
- intrinsics->OffsetLogSizeInPrimitiveClassConstant };
- temp = new BitCastInst(ptr_11, intrinsics->JavaClassPrimitiveType, "",
- log_label_bb);
- GetElementPtrInst* ptr_18 = GetElementPtrInst::Create(temp, ptr_11_indices,
- ptr_11_indices + 2, "",
- log_label_bb);
- LoadInst* int32_20 = new LoadInst(ptr_18, "", false, log_label_bb);
-
- int32_start = BinaryOperator::CreateShl(int32_start, int32_20, "",
- log_label_bb);
- int32_start2 = BinaryOperator::CreateShl(int32_start2, int32_20, "",
- log_label_bb);
- int32_length = BinaryOperator::CreateShl(int32_length, int32_20, "",
- log_label_bb);
-
- ptr_src = new BitCastInst(ptr_src, intrinsics->JavaArrayUInt8Type, "",
- log_label_bb);
-
- ptr_dst = new BitCastInst(ptr_dst, intrinsics->JavaArrayUInt8Type, "",
- log_label_bb);
-
- Value* indexes[3] = { intrinsics->constantZero,
- intrinsics->JavaArrayElementsOffsetConstant,
- int32_start };
- Instruction* ptr_42 = GetElementPtrInst::Create(ptr_src, indexes, indexes + 3,
- "", log_label_bb);
-
- indexes[2] = int32_start2;
- Instruction* ptr_44 = GetElementPtrInst::Create(ptr_dst, indexes, indexes + 3,
- "", log_label_bb);
-
- BranchInst::Create(label_memmove, log_label_bb);
-
- // Block memmove
- currentBlock = label_memmove;
- Value* src_int = new PtrToIntInst(ptr_42, intrinsics->pointerSizeType, "",
- currentBlock);
-
- Value* dst_int = new PtrToIntInst(ptr_44, intrinsics->pointerSizeType, "",
- currentBlock);
-
- cmp = new ICmpInst(*currentBlock, ICmpInst::ICMP_ULT, dst_int, src_int, "");
-
- Value* increment = SelectInst::Create(cmp, intrinsics->constantOne,
- intrinsics->constantMinusOne, "",
- currentBlock);
- BranchInst::Create(label_bb11, label_backward, cmp, currentBlock);
-
- PHINode* phi_dst_ptr = PHINode::Create(ptr_44->getType(), "", label_bb11);
- PHINode* phi_src_ptr = PHINode::Create(ptr_44->getType(), "", label_bb11);
- phi_dst_ptr->addIncoming(ptr_44, currentBlock);
- phi_src_ptr->addIncoming(ptr_42, currentBlock);
-
- // Block backward
- currentBlock = label_backward;
-
- ptr_42 = GetElementPtrInst::Create(ptr_42, int32_length, "",
- currentBlock);
-
- ptr_44 = GetElementPtrInst::Create(ptr_44, int32_length, "",
- currentBlock);
-
- ptr_42 = GetElementPtrInst::Create(ptr_42, intrinsics->constantMinusOne, "",
- currentBlock);
-
- ptr_44 = GetElementPtrInst::Create(ptr_44, intrinsics->constantMinusOne, "",
- currentBlock);
-
- phi_dst_ptr->addIncoming(ptr_44, currentBlock);
- phi_src_ptr->addIncoming(ptr_42, currentBlock);
-
- BranchInst::Create(label_bb11, currentBlock);
-
- // Block bb11 (label_bb11)
- currentBlock = label_bb11;
- Argument* fwdref_39 = new Argument(Type::getInt32Ty(*llvmContext));
- PHINode* int32_i_016 = PHINode::Create(Type::getInt32Ty(*llvmContext),
- "i.016", label_bb11);
- int32_i_016->reserveOperandSpace(2);
- int32_i_016->addIncoming(fwdref_39, label_bb11);
- int32_i_016->addIncoming(intrinsics->constantZero, log_label_bb);
-
- LoadInst* ptr_43 = new LoadInst(phi_src_ptr, "", false, label_bb11);
- new StoreInst(ptr_43, phi_dst_ptr, false, label_bb11);
-
-
- ptr_42 = GetElementPtrInst::Create(phi_src_ptr, increment, "",
- label_bb11);
-
- ptr_44 = GetElementPtrInst::Create(phi_dst_ptr, increment, "",
- label_bb11);
- phi_dst_ptr->addIncoming(ptr_44, label_bb11);
- phi_src_ptr->addIncoming(ptr_42, label_bb11);
-
- BinaryOperator* int32_indvar_next =
- BinaryOperator::Create(Instruction::Add, int32_i_016, intrinsics->constantOne,
- "indvar.next", label_bb11);
- ICmpInst* int1_exitcond = new ICmpInst(*label_bb11, ICmpInst::ICMP_EQ,
- int32_indvar_next, int32_length,
- "exitcond");
- BranchInst::Create(label_return, label_bb11, int1_exitcond, label_bb11);
-
- // Resolve Forward References
- fwdref_39->replaceAllUsesWith(int32_indvar_next); delete fwdref_39;
-
- currentBlock = label_return;
-}
-
-DebugLoc JavaJIT::CreateLocation() {
- DebugLoc DL = DebugLoc::get(currentBytecodeIndex, 0, DbgSubprogram);
- return DL;
-}
-
-#ifdef DWARF_EXCEPTIONS
-#include "ExceptionsDwarf.inc"
-#else
-#include "ExceptionsCheck.inc"
-#endif
diff --git a/vmkit/lib/J3/Compiler/JavaJIT.h b/vmkit/lib/J3/Compiler/JavaJIT.h
deleted file mode 100644
index 70eb20f..0000000
--- a/vmkit/lib/J3/Compiler/JavaJIT.h
+++ /dev/null
@@ -1,718 +0,0 @@
-//===----------- JavaJIT.h - Java just in time compiler -------------------===//
-//
-// The VMKit project
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#ifndef JNJVM_JAVA_JIT_H
-#define JNJVM_JAVA_JIT_H
-
-#include <vector>
-#include <map>
-
-#include "llvm/BasicBlock.h"
-#include "llvm/Function.h"
-#include "llvm/Instructions.h"
-#include "llvm/LLVMContext.h"
-#include "llvm/Metadata.h"
-#include "llvm/Type.h"
-#include "llvm/Value.h"
-#include "llvm/Support/DebugLoc.h"
-#include "llvm/Analysis/DebugInfo.h"
-
-#include "types.h"
-
-#include "j3/JavaLLVMCompiler.h"
-
-#include "JavaClass.h"
-#include "JavaUpcalls.h"
-#include "Jnjvm.h"
-
-namespace j3 {
-
-class Class;
-class JavaMethod;
-class Reader;
-
-/// Opinfo - This class gives for each opcode if it starts a new block and
-/// its exception destination.
-///
-struct Opinfo {
-
- /// newBlock - If it is non-null, the block that the instruction starts.
- ///
- llvm::BasicBlock* newBlock;
-
- /// exceptionBlock - Never null, the exception destination of the
- /// instruction.
- ///
- llvm::BasicBlock* exceptionBlock;
-
- /// handler - If the instruction is the first instruction of a Java exception
- /// handler.
- ///
- bool handler;
-
- /// stack - The stack at this location if there is a new block
- ///
- std::vector<CommonClass*> stack;
-};
-
-
-/// JavaJIT - The compilation engine of J3. Parses the bycode and returns
-/// its LLVM representation.
-///
-class JavaJIT {
-public:
-
- /// JavaJIT - Default constructor.
- JavaJIT(JavaLLVMCompiler* C, JavaMethod* meth, llvm::Function* func) {
- compilingMethod = meth;
- compilingClass = meth->classDef;
- upcalls = compilingClass->classLoader->vm->upcalls;
- TheCompiler = C;
- intrinsics = TheCompiler->getIntrinsics();
- llvmFunction = func;
- llvmContext = &func->getContext();
- inlining = false;
- callsStackWalker = false;
- endNode = 0;
- currentStackIndex = 0;
- currentBytecodeIndex = 0;
- thisObject = NULL;
- }
-
- /// javaCompile - Compile the Java method.
- llvm::Function* javaCompile();
-
- /// nativeCompile - Compile the native method.
- llvm::Function* nativeCompile(intptr_t natPtr = 0);
-
-private:
-
- /// compilingClass - The class that is defining the method being compiled.
- Class* compilingClass;
-
- /// compilingMethod - The method being compiled.
- JavaMethod* compilingMethod;
-
- /// upcalls - Upcalls used tp type the stack and locals.
- Classpath* upcalls;
-
- /// llvmFunction - The LLVM representation of the method.
- llvm::Function* llvmFunction;
-
- /// llvmContext - The current LLVM context of compilation.
- llvm::LLVMContext* llvmContext;
-
- /// intrinsics - The LLVM intrinsics where lives the compiling LLVM function.
- J3Intrinsics* intrinsics;
-
- /// TheCompiler - The LLVM Java compiler.
- ///
- JavaLLVMCompiler* TheCompiler;
-
- /// locals - The locals of the method.
- std::vector<llvm::AllocaInst*> intLocals;
- std::vector<llvm::AllocaInst*> longLocals;
- std::vector<llvm::AllocaInst*> floatLocals;
- std::vector<llvm::AllocaInst*> doubleLocals;
- std::vector<llvm::AllocaInst*> objectLocals;
-
- /// endBlock - The block that returns.
- llvm::BasicBlock* endBlock;
-
- /// endNode - The result of the method.
- llvm::PHINode* endNode;
-
- /// arraySize - Get the size of the array.
- llvm::Value* arraySize(llvm::Value* obj) {
- return llvm::CallInst::Create(intrinsics->ArrayLengthFunction, obj, "",
- currentBlock);
- }
-
- /// convertValue - Convert a value to a new type.
- void convertValue(llvm::Value*& val, const llvm::Type* t1,
- llvm::BasicBlock* currentBlock, bool usign);
-
- /// getMutatorThreadPtr - Emit code to get a pointer to the current MutatorThread.
- llvm::Value* getMutatorThreadPtr();
-
- /// getDoYieldPtr - Emit code to get a pointer to doYield.
- llvm::Value* getDoYieldPtr(llvm::Value* mutatorThreadPtr);
-
- /// getCXXExceptionPtr - Emit code to get a pointer to internalPendingException.
- llvm::Value* getCXXExceptionPtr(llvm::Value* mutatorThreadPtr);
-
- /// getPendingExceptionPtr - Emit code to get a pointer to the Java pending exception
- llvm::Value* getPendingExceptionPtr(llvm::Value* mutatorThreadPtr);
-
- /// getJavaThreadPtr - Emit code to get a pointer to the current JavaThread.
- llvm::Value* getJavaThreadPtr(llvm::Value* mutatorThreadPtr);
-
- /// getJNIEnvPtr - Emit code to get a pointer to JNIEnv
- llvm::Value* getJNIEnvPtr(llvm::Value* javaThreadPtr);
-
-
-//===------------------------- Debugging support --------------------------===//
-
- llvm::MDNode* DbgSubprogram;
-
- /// currentBytecodeIndex - The current bytecode being processed.
- uint16 currentBytecodeIndex;
-
- /// CreateLocation - Create debug information for a call.
- llvm::DebugLoc CreateLocation();
-
-//===--------------------------- Inline support ---------------------------===//
-
- /// inlineCompile - Parse the method and start its LLVM representation
- /// at curBB. endExBlock is the exception destination. args is the
- /// arguments of the method.
- llvm::Instruction* inlineCompile(llvm::BasicBlock*& curBB,
- llvm::BasicBlock* endExBlock,
- std::vector<llvm::Value*>& args);
-
-
- /// inlineMethods - Methods that are currently being inlined. The JIT
- /// uses this map to not inline a method currently bein inlined.
- std::map<JavaMethod*, bool> inlineMethods;
-
- /// inlining - Are we JITting a method inline?
- bool inlining;
-
- /// canBeInlined - Can this method's body be inlined?
- bool canBeInlined(JavaMethod* meth);
-
- /// callsStackWalker - Is the method calling a stack walker method? If it is,
- /// then this method can not be inlined.
- bool callsStackWalker;
-
-
-//===------------------------- Bytecode parsing ---------------------------===//
-
- /// compileOpcodes - Parse the bytecode and create LLVM instructions.
- void compileOpcodes(Reader& reader, uint32 codeLength);
-
- /// exploreOpcodes - Parse the bytecode and create the basic blocks.
- void exploreOpcodes(Reader& reader, uint32 codeLength);
-
- /// readExceptionTable - Read the exception table in the bytecode. Prepare
- /// exception destination for all Java instructions and set the exception
- /// object to handler blocks.
- unsigned readExceptionTable(Reader& reader, uint32 codeLength);
-
- /// loadConstant - Load a constant from the _ldc bytecode.
- void loadConstant(uint16 index);
-
-//===------------------------- Runtime exceptions -------------------------===//
-
- /// JITVerifyNull - Insert a null pointer check in the LLVM code.
- void JITVerifyNull(llvm::Value* obj);
-
-
- /// verifyAndComputePtr - Computes the address in the array. If out of bounds
- /// throw an exception.
- llvm::Value* verifyAndComputePtr(llvm::Value* obj, llvm::Value* index,
- const llvm::Type* arrayType,
- bool verif = true);
-
- /// compareFP - Do float comparisons.
- void compareFP(llvm::Value*, llvm::Value*, const llvm::Type*, bool l);
-
-
-//===------------------------- Stack manipulation -------------------------===//
-
- /// stack - The compiler stack.
- std::vector<CommonClass*> stack;
- uint32 currentStackIndex;
- std::vector<llvm::AllocaInst*> objectStack;
- std::vector<llvm::AllocaInst*> intStack;
- std::vector<llvm::AllocaInst*> longStack;
- std::vector<llvm::AllocaInst*> floatStack;
- std::vector<llvm::AllocaInst*> doubleStack;
-
- /// push - Push a new value in the stack.
- void push(llvm::Value* val, bool unsign, CommonClass* cl = 0) {
- const llvm::Type* type = val->getType();
- if (unsign) {
- val = new llvm::ZExtInst(val, llvm::Type::getInt32Ty(*llvmContext), "", currentBlock);
- new llvm::StoreInst(val, intStack[currentStackIndex++], false,
- currentBlock);
- stack.push_back(upcalls->OfInt);
- } else if (type == llvm::Type::getInt8Ty(*llvmContext) ||
- type == llvm::Type::getInt16Ty(*llvmContext)) {
- val = new llvm::SExtInst(val, llvm::Type::getInt32Ty(*llvmContext), "",
- currentBlock);
- new llvm::StoreInst(val, intStack[currentStackIndex++], false,
- currentBlock);
- stack.push_back(upcalls->OfInt);
- } else if (type == llvm::Type::getInt32Ty(*llvmContext)) {
- new llvm::StoreInst(val, intStack[currentStackIndex++], false,
- currentBlock);
- stack.push_back(upcalls->OfInt);
- } else if (type == llvm::Type::getInt64Ty(*llvmContext)) {
- new llvm::StoreInst(val, longStack[currentStackIndex++], false,
- currentBlock);
- stack.push_back(upcalls->OfLong);
- } else if (type == llvm::Type::getFloatTy(*llvmContext)) {
- new llvm::StoreInst(val, floatStack[currentStackIndex++], false,
- currentBlock);
- stack.push_back(upcalls->OfFloat);
- } else if (type == llvm::Type::getDoubleTy(*llvmContext)) {
- new llvm::StoreInst(val, doubleStack[currentStackIndex++], false,
- currentBlock);
- stack.push_back(upcalls->OfDouble);
- } else {
- assert(type == intrinsics->JavaObjectType && "Can't handle this type");
- llvm::Instruction* V = new
- llvm::StoreInst(val, objectStack[currentStackIndex++], false,
- currentBlock);
- stack.push_back(cl ? cl : upcalls->OfObject);
- addHighLevelType(V, topTypeInfo());
- if (llvm::Instruction* I = llvm::dyn_cast<llvm::Instruction>(val)) {
- addHighLevelType(I, topTypeInfo());
- }
- }
- }
-
- void addHighLevelType(llvm::Instruction* V, CommonClass* cl) {
- // Enable this when it will be actually used.
-#if 0
- llvm::Value* A[1] =
- { TheCompiler->getNativeClass(cl ? cl : upcalls->OfObject) };
- llvm::MDNode* Node = llvm::MDNode::get(*llvmContext, A, 1);
- V->setMetadata(intrinsics->MetadataTypeKind, Node);
-#endif
- }
-
-
- /// pop - Pop a value from the stack and return it.
- llvm::Value* pop() {
- llvm::Value* res = top();
- --currentStackIndex;
- stack.pop_back();
- return res;
- }
-
- /// top - Return the value on top of the stack.
- llvm::Value* top() {
- CommonClass* cl = stack.back();
- if (cl == upcalls->OfInt) {
- return new llvm::LoadInst(intStack[currentStackIndex - 1], "", false,
- currentBlock);
- } else if (cl == upcalls->OfFloat) {
- return new llvm::LoadInst(floatStack[currentStackIndex - 1], "", false,
- currentBlock);
- } else if (cl == upcalls->OfDouble) {
- return new llvm::LoadInst(doubleStack[currentStackIndex - 1], "", false,
- currentBlock);
- } else if (cl == upcalls->OfLong) {
- return new llvm::LoadInst(longStack[currentStackIndex - 1], "", false,
- currentBlock);
- } else {
- return new llvm::LoadInst(objectStack[currentStackIndex - 1], "",
- TheCompiler->useCooperativeGC(), currentBlock);
- }
- }
-
- /// topTypeInfo - Return the type of the value on top of the stack.
- CommonClass* topTypeInfo() {
- return stack.back();
- }
-
- /// stackSize - Return the size of the stack.
- uint32 stackSize() {
- return stack.size();
- }
-
- /// popAsInt - Pop a value from the stack and returns it as a Java
- /// int, ie signed int32.
- llvm::Value* popAsInt() {
- return pop();
- }
-
-//===------------------------- Exception support --------------------------===//
-
- /// jsrs - The list of jsrs (jump subroutine) instructions.
- std::vector<llvm::BasicBlock*> jsrs;
-
- /// endExceptionBlock - The initial exception block where each handler goes
- /// if it does not handle the exception.
- llvm::BasicBlock* endExceptionBlock;
-
- /// currentExceptionBlock - The exception block of the current instruction.
- llvm::BasicBlock* currentExceptionBlock;
-
- /// unifiedUnreachable - When an exception is thrown, the code after is
- /// unreachable. All invokes that only throw an exception have the
- /// unifiedUnreachable block as their normal destination.
- llvm::BasicBlock* unifiedUnreachable;
-
- /// throwException - Emit code to throw an exception.
- void throwException(llvm::Function* F, llvm::Value** args,
- uint32 nbArgs);
- void throwException(llvm::Function* F, llvm::Value* arg1);
- void throwException(llvm::Value* obj);
-
- /// finishExceptions - Emit code to unwind the current function if an
- /// exception is thrown.
- void finishExceptions();
-//===--------------------------- Control flow ----------------------------===//
-
- /// opcodeInfos - The informations for each instruction.
- Opinfo* opcodeInfos;
-
- /// currentBlock - The current block of the JIT.
- llvm::BasicBlock* currentBlock;
-
- /// createBasicBlock - Create a new basic block.
- llvm::BasicBlock* createBasicBlock(const char* name = "") {
- return llvm::BasicBlock::Create(*llvmContext, name, llvmFunction);
- }
-
- /// branch - Branch based on a boolean value.
- void branch(llvm::Value* test, llvm::BasicBlock* ifTrue,
- llvm::BasicBlock* ifFalse, llvm::BasicBlock* insert,
- Opinfo& info) {
- if (stackSize())
- if (!info.stack.size())
- info.stack = stack;
- llvm::BranchInst::Create(ifTrue, ifFalse, test, insert);
- }
-
- /// branch - Branch to a new block.
- void branch(Opinfo& info, llvm::BasicBlock* insert) {
- if (stackSize())
- if (!info.stack.size())
- info.stack = stack;
- llvm::BranchInst::Create(info.newBlock, insert);
- }
-
-//===-------------------------- Synchronization --------------------------===//
-
- llvm::Value* thisObject;
-
- /// beginSynchronize - Emit synchronization code to acquire the instance
- /// or the class.
- void beginSynchronize();
-
- /// endSynchronize - Emit synchronization code to release the instance or the
- /// class.
- void endSynchronize();
-
- /// monitorEnter - Emit synchronization code to acquire the lock of the value.
- void monitorEnter(llvm::Value* obj);
-
- /// monitorExit - Emit synchronization code to release the lock of the value.
- void monitorExit(llvm::Value* obj);
-
-//===----------------------- Java field accesses -------------------------===//
-
- /// getStaticField - Emit code to get the static field declared at the given
- /// index in the constant pool.
- void getStaticField(uint16 index);
-
- /// setStaticField - Emit code to set a value to the static field declared
- /// at the given index in the constant pool.
- void setStaticField(uint16 index);
-
- /// getVirtualField - Emit code to get the virtual field declared at the given
- /// index in the constant pool.
- void getVirtualField(uint16 index);
-
- /// setVirtualField - Emit code to set a value to the virtual field declared
- /// at the given index in the constant pool.
- void setVirtualField(uint16 index);
-
- /// ldResolved - Emit code to get a pointer to a field.
- llvm::Value* ldResolved(uint16 index, bool stat, llvm::Value* object,
- const llvm::Type* fieldTypePtr);
-
-//===--------------------- Constant pool accesses ------------------------===//
-
- /// getResolvedCommonClass - Emit code to get a resolved common class. If the
- /// constant pool already links to the class, the class is emitted directly.
- /// Otherwise the JIT installs a resolver which will be called at runtime.
- llvm::Value* getResolvedCommonClass(uint16 index, bool doThrow,
- UserCommonClass** alreadyResolved);
-
- /// getResolvedCommonClass - Similar to getResolvedCommonClass, but the type
- /// of the returned value is Class.
- llvm::Value* getResolvedClass(uint16 index, bool clinit, bool doThrow,
- UserClass** alreadyResolved);
-
- /// getConstantPoolAt - Return the value at the given index of the constant
- /// pool. The generated code invokes the resolver if the constant pool
- /// contains no value at the index.
- llvm::Value* getConstantPoolAt(uint32 index, llvm::Function* resolver,
- const llvm::Type* returnType,
- llvm::Value* addArg, bool doThrow = true);
-
-//===----------------------- Java method calls ---------------------------===//
-
- /// makeArgs - Insert the arguments of a method in the vector. The arguments
- /// are popped from the compilation stack.
- void makeArgs(llvm::FunctionType::param_iterator it,
- uint32 index, std::vector<llvm::Value*>& result, uint32 nb);
-
- /// getTarget - Get the target object for invocation.
- llvm::Value* getTarget(Signdef* signature);
-
- /// invokeVirtual - Invoke a Java virtual method.
- void invokeVirtual(uint16 index);
-
- /// invokeInterface - Invoke a Java interface method.
- void invokeInterface(uint16 index);
-
- /// invokeSpecial - Invoke an instance Java method directly.
- void invokeSpecial(uint16 index);
-
- /// invokeStatic - Invoke a static Java method.
- void invokeStatic(uint16 index);
-
- /// invokeNew - Allocate a new object.
- void invokeNew(uint16 index);
-
- /// invokeInline - Instead of calling the method, inline it.
- llvm::Instruction* invokeInline(JavaMethod* meth,
- std::vector<llvm::Value*>& args);
-
- /// lowerMathOps - Map Java Math operations to LLVM intrinsics.
- llvm::Instruction* lowerMathOps(const UTF8* name,
- std::vector<llvm::Value*>& args);
-
- /// lowerArraycopy - Create a fast path for System.arraycopy.
- void lowerArraycopy(std::vector<llvm::Value*>& args);
-
- /// invoke - invoke the LLVM method of a Java method.
- llvm::Instruction* invoke(llvm::Value *F, std::vector<llvm::Value*>&args,
- const char* Name,
- llvm::BasicBlock *InsertAtEnd);
- llvm::Instruction* invoke(llvm::Value *F, llvm::Value *Actual1,
- llvm::Value *Actual2, const char* Name,
- llvm::BasicBlock *InsertAtEnd);
- llvm::Instruction* invoke(llvm::Value *F, llvm::Value *Actual1,
- const char* Name, llvm::BasicBlock *InsertAtEnd);
- llvm::Instruction* invoke(llvm::Value *F, const char* Name,
- llvm::BasicBlock *InsertAtEnd);
-
-//===--------------------- Yield point support ---------------------------===//
-
- void checkYieldPoint();
-};
-
-enum Opcode {
- NOP = 0x00,
- ACONST_NULL = 0x01,
- ICONST_M1 = 0x02,
- ICONST_0 = 0x03,
- ICONST_1 = 0x04,
- ICONST_2 = 0x05,
- ICONST_3 = 0x06,
- ICONST_4 = 0x07,
- ICONST_5 = 0x08,
- LCONST_0 = 0x09,
- LCONST_1 = 0x0A,
- FCONST_0 = 0x0B,
- FCONST_1 = 0x0C,
- FCONST_2 = 0x0D,
- DCONST_0 = 0x0E,
- DCONST_1 = 0x0F,
- BIPUSH = 0x10,
- SIPUSH = 0x11,
- LDC = 0x12,
- LDC_W = 0x13,
- LDC2_W = 0x14,
- ILOAD = 0x15,
- LLOAD = 0x16,
- FLOAD = 0x17,
- DLOAD = 0x18,
- ALOAD = 0x19,
- ILOAD_0 = 0x1A,
- ILOAD_1 = 0x1B,
- ILOAD_2 = 0x1C,
- ILOAD_3 = 0x1D,
- LLOAD_0 = 0x1E,
- LLOAD_1 = 0x1F,
- LLOAD_2 = 0x20,
- LLOAD_3 = 0x21,
- FLOAD_0 = 0x22,
- FLOAD_1 = 0x23,
- FLOAD_2 = 0x24,
- FLOAD_3 = 0x25,
- DLOAD_0 = 0x26,
- DLOAD_1 = 0x27,
- DLOAD_2 = 0x28,
- DLOAD_3 = 0x29,
- ALOAD_0 = 0x2A,
- ALOAD_1 = 0x2B,
- ALOAD_2 = 0x2C,
- ALOAD_3 = 0x2D,
- IALOAD = 0x2E,
- LALOAD = 0x2F,
- FALOAD = 0x30,
- DALOAD = 0x31,
- AALOAD = 0x32,
- BALOAD = 0x33,
- CALOAD = 0x34,
- SALOAD = 0x35,
- ISTORE = 0x36,
- LSTORE = 0x37,
- FSTORE = 0x38,
- DSTORE = 0x39,
- ASTORE = 0x3A,
- ISTORE_0 = 0x3B,
- ISTORE_1 = 0x3C,
- ISTORE_2 = 0x3D,
- ISTORE_3 = 0x3E,
- LSTORE_0 = 0x3F,
- LSTORE_1 = 0x40,
- LSTORE_2 = 0x41,
- LSTORE_3 = 0x42,
- FSTORE_0 = 0x43,
- FSTORE_1 = 0x44,
- FSTORE_2 = 0x45,
- FSTORE_3 = 0x46,
- DSTORE_0 = 0x47,
- DSTORE_1 = 0x48,
- DSTORE_2 = 0x49,
- DSTORE_3 = 0x4A,
- ASTORE_0 = 0x4B,
- ASTORE_1 = 0x4C,
- ASTORE_2 = 0x4D,
- ASTORE_3 = 0x4E,
- IASTORE = 0x4F,
- LASTORE = 0x50,
- FASTORE = 0x51,
- DASTORE = 0x52,
- AASTORE = 0x53,
- BASTORE = 0x54,
- CASTORE = 0x55,
- SASTORE = 0x56,
- POP = 0x57,
- POP2 = 0x58,
- DUP = 0x59,
- DUP_X1 = 0x5A,
- DUP_X2 = 0x5B,
- DUP2 = 0x5C,
- DUP2_X1 = 0x5D,
- DUP2_X2 = 0x5E,
- SWAP = 0x5F,
- IADD = 0x60,
- LADD = 0x61,
- FADD = 0x62,
- DADD = 0x63,
- ISUB = 0x64,
- LSUB = 0x65,
- FSUB = 0x66,
- DSUB = 0x67,
- IMUL = 0x68,
- LMUL = 0x69,
- FMUL = 0x6A,
- DMUL = 0x6B,
- IDIV = 0x6C,
- LDIV = 0x6D,
- FDIV = 0x6E,
- DDIV = 0x6F,
- IREM = 0x70,
- LREM = 0x71,
- FREM = 0x72,
- DREM = 0x73,
- INEG = 0x74,
- LNEG = 0x75,
- FNEG = 0x76,
- DNEG = 0x77,
- ISHL = 0x78,
- LSHL = 0x79,
- ISHR = 0x7A,
- LSHR = 0x7B,
- IUSHR = 0x7C,
- LUSHR = 0x7D,
- IAND = 0x7E,
- LAND = 0x7F,
- IOR = 0x80,
- LOR = 0x81,
- IXOR = 0x82,
- LXOR = 0x83,
- IINC = 0x84,
- I2L = 0x85,
- I2F = 0x86,
- I2D = 0x87,
- L2I = 0x88,
- L2F = 0x89,
- L2D = 0x8A,
- F2I = 0x8B,
- F2L = 0x8C,
- F2D = 0x8D,
- D2I = 0x8E,
- D2L = 0x8F,
- D2F = 0x90,
- I2B = 0x91,
- I2C = 0x92,
- I2S = 0x93,
- LCMP = 0x94,
- FCMPL = 0x95,
- FCMPG = 0x96,
- DCMPL = 0x97,
- DCMPG = 0x98,
- IFEQ = 0x99,
- IFNE = 0x9A,
- IFLT = 0x9B,
- IFGE = 0x9C,
- IFGT = 0x9D,
- IFLE = 0x9E,
- IF_ICMPEQ = 0x9F,
- IF_ICMPNE = 0xA0,
- IF_ICMPLT = 0xA1,
- IF_ICMPGE = 0xA2,
- IF_ICMPGT = 0xA3,
- IF_ICMPLE = 0xA4,
- IF_ACMPEQ = 0xA5,
- IF_ACMPNE = 0xA6,
- GOTO = 0xA7,
- JSR = 0xA8,
- RET = 0xA9,
- TABLESWITCH = 0xAA,
- LOOKUPSWITCH = 0xAB,
- IRETURN = 0xAC,
- LRETURN = 0xAD,
- FRETURN = 0xAE,
- DRETURN = 0xAF,
- ARETURN = 0xB0,
- RETURN = 0xB1,
- GETSTATIC = 0xB2,
- PUTSTATIC = 0xB3,
- GETFIELD = 0xB4,
- PUTFIELD = 0xB5,
- INVOKEVIRTUAL = 0xB6,
- INVOKESPECIAL = 0xB7,
- INVOKESTATIC = 0xB8,
- INVOKEINTERFACE = 0xB9,
- UNUSED = 0xBA,
- NEW = 0xBB,
- NEWARRAY = 0xBC,
- ANEWARRAY = 0xBD,
- ARRAYLENGTH = 0xBE,
- ATHROW = 0xBF,
- CHECKCAST = 0xC0,
- INSTANCEOF = 0xC1,
- MONITORENTER = 0xC2,
- MONITOREXIT = 0xC3,
- WIDE = 0xC4,
- MULTIANEWARRAY = 0xC5,
- IFNULL = 0xC6,
- IFNONNULL = 0xC7,
- GOTO_W = 0xC8,
- JSR_W = 0xC9,
- BREAKPOINT = 0xCA,
- IMPDEP1 = 0xFE,
- IMPDEP2 = 0xFF
-};
-
-} // end namespace j3
-
-#endif
diff --git a/vmkit/lib/J3/Compiler/JavaJITCompiler.cpp b/vmkit/lib/J3/Compiler/JavaJITCompiler.cpp
deleted file mode 100644
index f7e8850..0000000
--- a/vmkit/lib/J3/Compiler/JavaJITCompiler.cpp
+++ /dev/null
@@ -1,480 +0,0 @@
-//===--------- JavaJITCompiler.cpp - Support for JIT compiling -------------===//
-//
-// The VMKit project
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#include "llvm/Constants.h"
-#include "llvm/DerivedTypes.h"
-#include "llvm/Function.h"
-#include "llvm/Instructions.h"
-#include "llvm/LLVMContext.h"
-#include "llvm/Module.h"
-#include "llvm/Analysis/DebugInfo.h"
-#include "llvm/CodeGen/GCStrategy.h"
-#include <llvm/CodeGen/JITCodeEmitter.h>
-#include "llvm/CodeGen/MachineFunction.h"
-#include "llvm/ExecutionEngine/ExecutionEngine.h"
-#include "llvm/Support/CommandLine.h"
-#include "llvm/Support/ManagedStatic.h"
-#include "llvm/Support/Debug.h"
-#include "llvm/Support/raw_ostream.h"
-#include <../lib/ExecutionEngine/JIT/JIT.h>
-
-#include "mvm/GC.h"
-#include "mvm/VirtualMachine.h"
-#include "mvm/VMKit.h"
-
-#include "JavaClass.h"
-#include "JavaConstantPool.h"
-#include "JavaThread.h"
-#include "JavaTypes.h"
-#include "Jnjvm.h"
-
-#include "j3/JavaJITCompiler.h"
-#include "j3/J3Intrinsics.h"
-#include "j3/LLVMMaterializer.h"
-
-using namespace j3;
-using namespace llvm;
-
-class JavaJITMethodInfo : public mvm::JITMethodInfo {
-public:
- virtual void print(void* ip, void* addr);
- virtual bool isHighLevelMethod() {
- return true;
- }
-
- JavaJITMethodInfo(llvm::GCFunctionInfo* GFI,
- JavaMethod* m) :
- mvm::JITMethodInfo(GFI) {
- MetaInfo = m;
- Owner = m->classDef->classLoader->getCompiler();
- }
-};
-
-void JavaJITMethodInfo::print(void* ip, void* addr) {
- void* new_ip = NULL;
- if (ip) new_ip = isStub(ip, addr);
- JavaMethod* meth = (JavaMethod*)MetaInfo;
- CodeLineInfo* info = meth->lookupCodeLineInfo((uintptr_t)ip);
- if (info != NULL) {
- fprintf(stderr, "; %p (%p) in %s.%s (line %d, bytecode %d, code start %p)", new_ip, addr,
- UTF8Buffer(meth->classDef->name).cString(),
- UTF8Buffer(meth->name).cString(),
- meth->lookupLineNumber((uintptr_t)ip),
- info->bytecodeIndex, meth->code);
- } else {
- fprintf(stderr, "; %p (%p) in %s.%s (native method, code start %p)", new_ip, addr,
- UTF8Buffer(meth->classDef->name).cString(),
- UTF8Buffer(meth->name).cString(), meth->code);
- }
- if (ip != new_ip) fprintf(stderr, " (from stub)");
- fprintf(stderr, "\n");
-}
-
-
-void JavaJITListener::NotifyFunctionEmitted(const Function &F,
- void *Code, size_t Size,
- const EmittedFunctionDetails &Details) {
-
- // The following is necessary for -load-bc.
- if (F.getParent() != TheCompiler->getLLVMModule()) return;
- assert(F.hasGC());
- if (TheCompiler->GCInfo != NULL) {
- assert(TheCompiler->GCInfo == Details.MF->getGMI());
- return;
- }
- TheCompiler->GCInfo = Details.MF->getGMI();
-}
-
-
-Constant* JavaJITCompiler::getNativeClass(CommonClass* classDef) {
- const llvm::Type* Ty = classDef->isClass() ? JavaIntrinsics.JavaClassType :
- JavaIntrinsics.JavaCommonClassType;
-
- ConstantInt* CI = ConstantInt::get(Type::getInt64Ty(getLLVMContext()),
- uint64_t(classDef));
- return ConstantExpr::getIntToPtr(CI, Ty);
-}
-
-Constant* JavaJITCompiler::getConstantPool(JavaConstantPool* ctp) {
- void* ptr = ctp->ctpRes;
- assert(ptr && "No constant pool found");
- ConstantInt* CI = ConstantInt::get(Type::getInt64Ty(getLLVMContext()),
- uint64_t(ptr));
- return ConstantExpr::getIntToPtr(CI, JavaIntrinsics.ConstantPoolType);
-}
-
-Constant* JavaJITCompiler::getMethodInClass(JavaMethod* meth) {
- ConstantInt* CI = ConstantInt::get(Type::getInt64Ty(getLLVMContext()),
- (int64_t)meth);
- return ConstantExpr::getIntToPtr(CI, JavaIntrinsics.JavaMethodType);
-}
-
-Constant* JavaJITCompiler::getString(JavaString* str) {
- llvm_gcroot(str, 0);
- fprintf(stderr, "Should not be here\n");
- abort();
-}
-
-Constant* JavaJITCompiler::getStringPtr(JavaString** str) {
- assert(str && "No string given");
- const llvm::Type* Ty = PointerType::getUnqual(JavaIntrinsics.JavaObjectType);
- ConstantInt* CI = ConstantInt::get(Type::getInt64Ty(getLLVMContext()),
- uint64(str));
- return ConstantExpr::getIntToPtr(CI, Ty);
-}
-
-Constant* JavaJITCompiler::getJavaClass(CommonClass* cl) {
- fprintf(stderr, "Should not be here\n");
- abort();
-}
-
-Constant* JavaJITCompiler::getJavaClassPtr(CommonClass* cl) {
- JavaObject* const* obj = cl->getClassDelegateePtr();
- assert(obj && "Delegatee not created");
- Constant* CI = ConstantInt::get(Type::getInt64Ty(getLLVMContext()),
- uint64(obj));
- const Type* Ty = PointerType::getUnqual(JavaIntrinsics.JavaObjectType);
- return ConstantExpr::getIntToPtr(CI, Ty);
-}
-
-JavaObject* JavaJITCompiler::getFinalObject(llvm::Value* obj) {
- // obj can not encode direclty an object.
- return NULL;
-}
-
-Constant* JavaJITCompiler::getFinalObject(JavaObject* obj, CommonClass* cl) {
- llvm_gcroot(obj, 0);
- return NULL;
-}
-
-Constant* JavaJITCompiler::getStaticInstance(Class* classDef) {
- void* obj = classDef->getStaticInstance();
- if (!obj) {
- classDef->acquire();
- obj = classDef->getStaticInstance();
- if (!obj) {
- // Allocate now so that compiled code can reference it.
- obj = classDef->allocateStaticInstance();
- }
- classDef->release();
- }
- Constant* CI = ConstantInt::get(Type::getInt64Ty(getLLVMContext()),
- (uint64_t(obj)));
- return ConstantExpr::getIntToPtr(CI, JavaIntrinsics.ptrType);
-}
-
-Constant* JavaJITCompiler::getVirtualTable(JavaVirtualTable* VT) {
- if (VT->cl->isClass()) {
- LLVMClassInfo* LCI = getClassInfo(VT->cl->asClass());
- LCI->getVirtualType();
- }
-
- ConstantInt* CI = ConstantInt::get(Type::getInt64Ty(getLLVMContext()),
- uint64_t(VT));
- return ConstantExpr::getIntToPtr(CI, JavaIntrinsics.VTType);
-}
-
-Constant* JavaJITCompiler::getNativeFunction(JavaMethod* meth, void* ptr) {
- LLVMSignatureInfo* LSI = getSignatureInfo(meth->getSignature());
- const llvm::Type* valPtrType = LSI->getNativePtrType();
-
- assert(ptr && "No native function given");
-
- Constant* CI = ConstantInt::get(Type::getInt64Ty(getLLVMContext()),
- uint64_t(ptr));
- return ConstantExpr::getIntToPtr(CI, valPtrType);
-}
-
-JavaJITCompiler::JavaJITCompiler(const std::string &ModuleID) :
- JavaLLVMCompiler(ModuleID), listener(this) {
-
- EmitFunctionName = false;
- GCInfo = NULL;
-
- executionEngine = ExecutionEngine::createJIT(TheModule, 0,
- 0, llvm::CodeGenOpt::Default, false);
- executionEngine->RegisterJITEventListener(&listener);
-
- addJavaPasses();
-}
-
-JavaJITCompiler::~JavaJITCompiler() {
- executionEngine->removeModule(TheModule);
- delete executionEngine;
- // ~JavaLLVMCompiler will delete the module.
-}
-
-void JavaJITCompiler::makeVT(Class* cl) {
- JavaVirtualTable* VT = cl->virtualVT;
- assert(VT && "No VT was allocated!");
-
- if (VT->init) {
- // The VT has already been filled by the AOT compiler so there
- // is nothing left to do!
- return;
- }
-
- if (cl->super) {
- // Copy the super VT into the current VT.
- uint32 size = cl->super->virtualTableSize -
- JavaVirtualTable::getFirstJavaMethodIndex();
- memcpy(VT->getFirstJavaMethod(), cl->super->virtualVT->getFirstJavaMethod(),
- size * sizeof(uintptr_t));
- VT->destructor = cl->super->virtualVT->destructor;
- }
-
-
- // Fill the virtual table with function pointers.
- for (uint32 i = 0; i < cl->nbVirtualMethods; ++i) {
- JavaMethod& meth = cl->virtualMethods[i];
-
- // Special handling for finalize method. Don't put a finalizer
- // if there is none, or if it is empty.
- if (meth.offset == 0) {
- if (!cl->super) {
- meth.canBeInlined = true;
- } else {
- VT->destructor = getPointerOrStub(meth, JavaMethod::Virtual);
- }
- } else {
- VT->getFunctions()[meth.offset] = getPointerOrStub(meth,
- JavaMethod::Virtual);
- }
- }
-
-}
-
-extern "C" void ThrowUnfoundInterface() {
- abort();
-}
-
-void JavaJITCompiler::makeIMT(Class* cl) {
- InterfaceMethodTable* IMT = cl->virtualVT->IMT;
- if (!IMT) return;
-
- std::set<JavaMethod*> contents[InterfaceMethodTable::NumIndexes];
- cl->fillIMT(contents);
-
-
- for (uint32_t i = 0; i < InterfaceMethodTable::NumIndexes; ++i) {
- std::set<JavaMethod*>& atIndex = contents[i];
- uint32_t size = atIndex.size();
- if (size == 1) {
- JavaMethod* Imeth = *(atIndex.begin());
- JavaMethod* meth = cl->lookupMethodDontThrow(Imeth->name,
- Imeth->type,
- false, true, 0);
- if (meth) {
- IMT->contents[i] = getPointerOrStub(*meth, JavaMethod::Interface);
- } else {
- IMT->contents[i] = (uintptr_t)ThrowUnfoundInterface;
- }
- } else if (size > 1) {
- std::vector<JavaMethod*> methods;
- bool SameMethod = true;
- JavaMethod* OldMethod = 0;
-
- for (std::set<JavaMethod*>::iterator it = atIndex.begin(),
- et = atIndex.end(); it != et; ++it) {
- JavaMethod* Imeth = *it;
- JavaMethod* Cmeth = cl->lookupMethodDontThrow(Imeth->name, Imeth->type,
- false, true, 0);
-
- if (OldMethod && OldMethod != Cmeth) SameMethod = false;
- else OldMethod = Cmeth;
-
- methods.push_back(Cmeth);
- }
-
- if (SameMethod) {
- if (methods[0]) {
- IMT->contents[i] = getPointerOrStub(*(methods[0]),
- JavaMethod::Interface);
- } else {
- IMT->contents[i] = (uintptr_t)ThrowUnfoundInterface;
- }
- } else {
-
- // Add one to have a NULL-terminated table.
- uint32_t length = (2 * size + 1) * sizeof(uintptr_t);
-
- uintptr_t* table = (uintptr_t*)
- cl->classLoader->allocator.Allocate(length, "IMT");
-
- IMT->contents[i] = (uintptr_t)table | 1;
-
- uint32_t j = 0;
- std::set<JavaMethod*>::iterator Interf = atIndex.begin();
- for (std::vector<JavaMethod*>::iterator it = methods.begin(),
- et = methods.end(); it != et; ++it, j += 2, ++Interf) {
- JavaMethod* Imeth = *Interf;
- JavaMethod* Cmeth = *it;
- assert(Imeth != NULL);
- assert(j < 2 * size - 1);
- table[j] = (uintptr_t)Imeth;
- if (Cmeth) {
- table[j + 1] = getPointerOrStub(*Cmeth, JavaMethod::Interface);
- } else {
- table[j + 1] = (uintptr_t)ThrowUnfoundInterface;
- }
- }
- assert(Interf == atIndex.end());
- }
- }
- }
-}
-
-void JavaJITCompiler::setMethod(Function* func, void* ptr, const char* name) {
- func->setLinkage(GlobalValue::ExternalLinkage);
- func->setName(name);
- assert(ptr && "No value given");
- executionEngine->updateGlobalMapping(func, ptr);
-}
-
-void* JavaJITCompiler::materializeFunction(JavaMethod* meth) {
- mvm::MvmModule::protectIR();
- Function* func = parseFunction(meth);
- void* res = executionEngine->getPointerToGlobal(func);
-
- if (!func->isDeclaration()) {
- llvm::GCFunctionInfo* GFI = &(GCInfo->getFunctionInfo(*func));
- assert((GFI != NULL) && "No GC information");
-
- mvm::VMKit* vmkit = mvm::Thread::get()->vmkit;
- mvm::JITMethodInfo* MI =
- new(allocator, "JavaJITMethodInfo") JavaJITMethodInfo(GFI, meth);
- MI->addToVMKit(vmkit, (JIT*)executionEngine);
-
- uint32_t infoLength = GFI->size();
- meth->codeInfoLength = infoLength;
- if (infoLength == 0) {
- meth->codeInfo = NULL;
- } else {
- mvm::BumpPtrAllocator& JavaAlloc = meth->classDef->classLoader->allocator;
- CodeLineInfo* infoTable =
- new(JavaAlloc, "CodeLineInfo") CodeLineInfo[infoLength];
- uint32_t index = 0;
- for (GCFunctionInfo::iterator I = GFI->begin(), E = GFI->end();
- I != E;
- I++, index++) {
- DebugLoc DL = I->Loc;
- uint32_t bytecodeIndex = DL.getLine();
- uint32_t second = DL.getCol();
- assert(second == 0 && "Wrong column number");
- uintptr_t address =
- ((JIT*)executionEngine)->getCodeEmitter()->getLabelAddress(I->Label);
- infoTable[index].address = address;
- infoTable[index].bytecodeIndex = bytecodeIndex;
- }
- meth->codeInfo = infoTable;
- }
- }
- // Now that it's compiled, we don't need the IR anymore
- func->deleteBody();
- mvm::MvmModule::unprotectIR();
- return res;
-}
-
-void* JavaJITCompiler::GenerateStub(llvm::Function* F) {
- mvm::MvmModule::protectIR();
- void* res = executionEngine->getPointerToGlobal(F);
-
- llvm::GCFunctionInfo* GFI = &(GCInfo->getFunctionInfo(*F));
- assert((GFI != NULL) && "No GC information");
-
- mvm::VMKit* vmkit = mvm::Thread::get()->vmkit;
- mvm::JITMethodInfo* MI =
- new(allocator, "JITMethodInfo") mvm::MvmJITMethodInfo(GFI, F, this);
- MI->addToVMKit(vmkit, (JIT*)executionEngine);
-
- // Now that it's compiled, we don't need the IR anymore
- F->deleteBody();
- mvm::MvmModule::unprotectIR();
- return res;
-}
-
-// Helper function to run an executable with a JIT
-extern "C" int StartJnjvmWithJIT(int argc, char** argv, char* mainClass) {
- llvm::llvm_shutdown_obj X;
-
- mvm::BumpPtrAllocator Allocator;
- mvm::VMKit* vmkit = new(Allocator, "VMKit") mvm::VMKit(Allocator);
-
- mvm::ThreadAllocator thallocator;
- char** newArgv = (char**)thallocator.Allocate((argc + 1) * sizeof(char*));
- memcpy(newArgv + 1, argv, argc * sizeof(void*));
- newArgv[0] = newArgv[1];
- newArgv[1] = mainClass;
-
- JavaJITCompiler* Comp = JavaJITCompiler::CreateCompiler("JITModule");
- Jnjvm* vm = new(Allocator, "VM") Jnjvm(Allocator, vmkit, Comp, true);
- vm->runApplication(argc + 1, newArgv);
- vmkit->waitNonDaemonThreads();
-
- return 0;
-}
-
-uintptr_t JavaJ3LazyJITCompiler::getPointerOrStub(JavaMethod& meth,
- int side) {
- return meth.getSignature()->getVirtualCallStub();
-}
-
-Value* JavaJ3LazyJITCompiler::addCallback(Class* cl, uint16 index,
- Signdef* sign, bool stat,
- llvm::BasicBlock* insert) {
- LLVMSignatureInfo* LSI = getSignatureInfo(sign);
- // Set the stub in the constant pool.
- JavaConstantPool* ctpInfo = cl->ctpInfo;
- uintptr_t stub = stat ? sign->getStaticCallStub() : sign->getSpecialCallStub();
- if (!ctpInfo->ctpRes[index]) {
- // Do a compare and swap, so that we do not overwrtie what a stub might
- // have just updated.
- uintptr_t val = (uintptr_t)
- __sync_val_compare_and_swap(&(ctpInfo->ctpRes[index]), NULL, stub);
- // If there is something in the the constant pool that is not NULL nor
- // the stub, then it's the method.
- if (val != 0 && val != stub) {
- return ConstantExpr::getIntToPtr(
- ConstantInt::get(Type::getInt64Ty(insert->getContext()), val),
- stat ? LSI->getStaticPtrType() : LSI->getVirtualPtrType());
- }
- }
- // Load the constant pool.
- Value* CTP = getConstantPool(ctpInfo);
- Value* Index = ConstantInt::get(Type::getInt32Ty(insert->getContext()),
- index);
- Value* func = GetElementPtrInst::Create(CTP, Index, "", insert);
- func = new LoadInst(func, "", false, insert);
- // Bitcast it to the LLVM function.
- func = new BitCastInst(func, stat ? LSI->getStaticPtrType() :
- LSI->getVirtualPtrType(),
- "", insert);
- return func;
-}
-
-bool JavaJ3LazyJITCompiler::needsCallback(JavaMethod* meth, bool* needsInit) {
- *needsInit = true;
- return (meth == NULL || meth->code == NULL);
-}
-
-JavaJ3LazyJITCompiler::JavaJ3LazyJITCompiler(const std::string& ModuleID)
- : JavaJITCompiler(ModuleID) {}
-
-
-static llvm::cl::opt<bool> LLVMLazy("llvm-lazy",
- cl::desc("Use LLVM lazy stubs"),
- cl::init(false));
-
-JavaJITCompiler* JavaJITCompiler::CreateCompiler(const std::string& ModuleID) {
- // This is called for the first compiler.
- if (LLVMLazy) {
- return new JavaLLVMLazyJITCompiler(ModuleID);
- }
- return new JavaJ3LazyJITCompiler(ModuleID);
-}
diff --git a/vmkit/lib/J3/Compiler/JavaJITOpcodes.cpp b/vmkit/lib/J3/Compiler/JavaJITOpcodes.cpp
deleted file mode 100644
index 93d1d11..0000000
--- a/vmkit/lib/J3/Compiler/JavaJITOpcodes.cpp
+++ /dev/null
@@ -1,2722 +0,0 @@
-//===---- JavaJITOpcodes.cpp - Reads and compiles opcodes -----------------===//
-//
-// The VMKit project
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#define DEBUG 0
-#define JNJVM_COMPILE 0
-#define JNJVM_EXECUTE 0
-
-#include <cstring>
-
-#include <llvm/Constants.h>
-#include <llvm/DerivedTypes.h>
-#include <llvm/Function.h>
-#include <llvm/Instructions.h>
-#include <llvm/Module.h>
-#include <llvm/Type.h>
-
-#include "mvm/JIT.h"
-
-#include "debug.h"
-
-#include "JavaArray.h"
-#include "JavaClass.h"
-#include "JavaConstantPool.h"
-#include "JavaObject.h"
-#include "JavaJIT.h"
-#include "JavaThread.h"
-#include "JavaTypes.h"
-#include "Jnjvm.h"
-#include "Reader.h"
-
-#include "j3/J3Intrinsics.h"
-
-#if DEBUG > 0 && (JNJVM_COMPILE > 0 || JNJVM_EXECUTE > 0)
-#include "j3/OpcodeNames.def"
-#endif
-
-using namespace j3;
-using namespace llvm;
-
-uint8 arrayType(JavaMethod* meth, unsigned int t) {
- if (t == JavaArray::T_CHAR) {
- return I_CHAR;
- } else if (t == JavaArray::T_BOOLEAN) {
- return I_BOOL;
- } else if (t == JavaArray::T_INT) {
- return I_INT;
- } else if (t == JavaArray::T_SHORT) {
- return I_SHORT;
- } else if (t == JavaArray::T_BYTE) {
- return I_BYTE;
- } else if (t == JavaArray::T_FLOAT) {
- return I_FLOAT;
- } else if (t == JavaArray::T_LONG) {
- return I_LONG;
- } else if (t == JavaArray::T_DOUBLE) {
- return I_DOUBLE;
- } else {
- fprintf(stderr, "I haven't verified your class file and it's malformed:"
- " unknown array type %d in %s.%s!\n", t,
- UTF8Buffer(meth->classDef->name).cString(),
- UTF8Buffer(meth->name).cString());
- abort();
- }
-}
-
-static inline uint32 WREAD_U1(Reader& reader, bool init, uint32 &i, bool& wide) {
- if (wide) {
- wide = init;
- i += 2;
- return reader.readU2();
- } else {
- i += 1;
- return reader.readU1();
- }
-}
-
-static inline sint32 WREAD_S1(Reader& reader, bool init, uint32 &i, bool &wide) {
- if (wide) {
- wide = init;
- i += 2;
- return reader.readS2();
- } else {
- i += 1;
- return reader.readS1();
- }
-}
-
-static inline uint32 WCALC(uint32 n, bool& wide) {
- if (wide) {
- wide = false;
- return n << 1;
- } else {
- return n;
- }
-}
-
-void JavaJIT::compileOpcodes(Reader& reader, uint32 codeLength) {
- bool wide = false;
- uint32 jsrIndex = 0;
- uint32 start = reader.cursor;
- mvm::ThreadAllocator allocator;
- for(uint32 i = 0; i < codeLength; ++i) {
- reader.cursor = start + i;
- uint8 bytecode = reader.readU1();
-
- PRINT_DEBUG(JNJVM_COMPILE, 1, COLOR_NORMAL, "\t[at %5d] %-5d ", i,
- bytecode);
- PRINT_DEBUG(JNJVM_COMPILE, 1, LIGHT_BLUE, "compiling ");
- PRINT_DEBUG(JNJVM_COMPILE, 1, LIGHT_CYAN, OpcodeNames[bytecode]);
- PRINT_DEBUG(JNJVM_COMPILE, 1, LIGHT_BLUE, "\n");
-
- Opinfo* opinfo = &(opcodeInfos[i]);
-
- if (opinfo->newBlock) {
- if (currentBlock->getTerminator() == 0) {
- // Load the exception object if we have branched to a handler.
- if (opinfo->handler) {
- Instruction* I = opinfo->newBlock->begin();
- PHINode * node = dyn_cast<PHINode>(I);
- assert(node && "Handler marlformed");
- Value* obj = pop();
- node->addIncoming(obj, currentBlock);
- }
- branch(*opinfo, currentBlock);
- }
-
- currentBlock = opinfo->newBlock;
-
- stack.clear();
- if (opinfo->handler) {
- Instruction* I = opinfo->newBlock->begin();
- assert(isa<PHINode>(I) && "Handler marlformed");
- // If it's a handler, put the exception object in the stack.
- new StoreInst(I, objectStack[0], "", currentBlock);
- stack.push_back(upcalls->OfObject);
- currentStackIndex = 1;
- } else {
- stack = opinfo->stack;
- currentStackIndex = stack.size();
- }
- }
-
- currentExceptionBlock = opinfo->exceptionBlock;
-
- currentBytecodeIndex = i;
-
- // To prevent a gcj bug with useless goto
- if (currentBlock->getTerminator() != 0) {
- currentBlock = createBasicBlock("gcj bug");
- }
-
-#if JNJVM_EXECUTE > 1
- // if (compilingMethod->name->equals(compilingClass->classLoader->asciizConstructUTF8("allocSlowOnce")))
- {
- Value* args[3] = {
- ConstantInt::get(Type::getInt32Ty(*llvmContext), (int64_t)bytecode),
- ConstantInt::get(Type::getInt32Ty(*llvmContext), (int64_t)i),
- TheCompiler->getMethodInClass(compilingMethod)
- };
-
-
- CallInst::Create(intrinsics->PrintExecutionFunction, args, args + 3, "",
- currentBlock);
- }
-#endif
-
- switch (bytecode) {
-
- case NOP : break;
-
- case ACONST_NULL :
- push(intrinsics->JavaObjectNullConstant, false);
- break;
-
- case ICONST_M1 :
- push(intrinsics->constantMinusOne, false);
- break;
-
- case ICONST_0 :
- push(intrinsics->constantZero, false);
- break;
-
- case ICONST_1 :
- push(intrinsics->constantOne, false);
- break;
-
- case ICONST_2 :
- push(intrinsics->constantTwo, false);
- break;
-
- case ICONST_3 :
- push(intrinsics->constantThree, false);
- break;
-
- case ICONST_4 :
- push(intrinsics->constantFour, false);
- break;
-
- case ICONST_5 :
- push(intrinsics->constantFive, false);
- break;
-
- case LCONST_0 :
- push(intrinsics->constantLongZero, false);
- push(intrinsics->constantZero, false);
- break;
-
- case LCONST_1 :
- push(intrinsics->constantLongOne, false);
- push(intrinsics->constantZero, false);
- break;
-
- case FCONST_0 :
- push(intrinsics->constantFloatZero, false);
- break;
-
- case FCONST_1 :
- push(intrinsics->constantFloatOne, false);
- break;
-
- case FCONST_2 :
- push(intrinsics->constantFloatTwo, false);
- break;
-
- case DCONST_0 :
- push(intrinsics->constantDoubleZero, false);
- push(intrinsics->constantZero, false);
- break;
-
- case DCONST_1 :
- push(intrinsics->constantDoubleOne, false);
- push(intrinsics->constantZero, false);
- break;
-
- case BIPUSH :
- push(ConstantExpr::getSExt(ConstantInt::get(Type::getInt8Ty(*llvmContext),
- reader.readU1()),
- Type::getInt32Ty(*llvmContext)), false);
- i++;
- break;
-
- case SIPUSH :
- push(ConstantExpr::getSExt(ConstantInt::get(Type::getInt16Ty(*llvmContext),
- reader.readS2()),
- Type::getInt32Ty(*llvmContext)), false);
- i += 2;
- break;
-
- case LDC :
- loadConstant(reader.readU1());
- i++;
- break;
-
- case LDC_W :
- loadConstant(reader.readS2());
- i += 2;
- break;
-
- case LDC2_W :
- loadConstant(reader.readS2());
- i += 2;
- push(intrinsics->constantZero, false);
- break;
-
- case ILOAD :
- push(new LoadInst(intLocals[WREAD_U1(reader, false, i, wide)], "", false,
- currentBlock), false);
- break;
-
- case LLOAD :
- push(new LoadInst(longLocals[WREAD_U1(reader, false, i, wide)], "", false,
- currentBlock), false);
- push(intrinsics->constantZero, false);
- break;
-
- case FLOAD :
- push(new LoadInst(floatLocals[WREAD_U1(reader, false, i, wide)], "", false,
- currentBlock), false);
- break;
-
- case DLOAD :
- push(new LoadInst(doubleLocals[WREAD_U1(reader, false, i, wide)], "", false,
- currentBlock), false);
- push(intrinsics->constantZero, false);
- break;
-
- case ALOAD :
- push(new LoadInst(objectLocals[WREAD_U1(reader, false, i, wide)], "",
- TheCompiler->useCooperativeGC(), currentBlock), false);
- break;
-
- case ILOAD_0 :
- push(new LoadInst(intLocals[0], "", false, currentBlock), false);
- break;
-
- case ILOAD_1 :
- push(new LoadInst(intLocals[1], "", false, currentBlock), false);
- break;
-
- case ILOAD_2 :
- push(new LoadInst(intLocals[2], "", false, currentBlock), false);
- break;
-
- case ILOAD_3 :
- push(new LoadInst(intLocals[3], "", false, currentBlock), false);
- break;
-
- case LLOAD_0 :
- push(new LoadInst(longLocals[0], "", false, currentBlock),
- false);
- push(intrinsics->constantZero, false);
- break;
-
- case LLOAD_1 :
- push(new LoadInst(longLocals[1], "", false, currentBlock),
- false);
- push(intrinsics->constantZero, false);
- break;
-
- case LLOAD_2 :
- push(new LoadInst(longLocals[2], "", false, currentBlock),
- false);
- push(intrinsics->constantZero, false);
- break;
-
- case LLOAD_3 :
- push(new LoadInst(longLocals[3], "", false, currentBlock),
- false);
- push(intrinsics->constantZero, false);
- break;
-
- case FLOAD_0 :
- push(new LoadInst(floatLocals[0], "", false, currentBlock),
- false);
- break;
-
- case FLOAD_1 :
- push(new LoadInst(floatLocals[1], "", false, currentBlock),
- false);
- break;
-
- case FLOAD_2 :
- push(new LoadInst(floatLocals[2], "", false, currentBlock),
- false);
- break;
-
- case FLOAD_3 :
- push(new LoadInst(floatLocals[3], "", false, currentBlock),
- false);
- break;
-
- case DLOAD_0 :
- push(new LoadInst(doubleLocals[0], "", false, currentBlock),
- false);
- push(intrinsics->constantZero, false);
- break;
-
- case DLOAD_1 :
- push(new LoadInst(doubleLocals[1], "", false, currentBlock),
- false);
- push(intrinsics->constantZero, false);
- break;
-
- case DLOAD_2 :
- push(new LoadInst(doubleLocals[2], "", false, currentBlock),
- false);
- push(intrinsics->constantZero, false);
- break;
-
- case DLOAD_3 :
- push(new LoadInst(doubleLocals[3], "", false, currentBlock),
- false);
- push(intrinsics->constantZero, false);
- break;
-
- case ALOAD_0 :
- push(new LoadInst(objectLocals[0], "", TheCompiler->useCooperativeGC(), currentBlock),
- false);
- break;
-
- case ALOAD_1 :
- push(new LoadInst(objectLocals[1], "", TheCompiler->useCooperativeGC(), currentBlock),
- false);
- break;
-
- case ALOAD_2 :
- push(new LoadInst(objectLocals[2], "", TheCompiler->useCooperativeGC(), currentBlock),
- false);
- break;
-
- case ALOAD_3 :
- push(new LoadInst(objectLocals[3], "", TheCompiler->useCooperativeGC(), currentBlock),
- false);
- break;
-
- case IALOAD : {
- Value* index = pop();
- Value* obj = pop();
- Value* ptr = verifyAndComputePtr(obj, index,
- intrinsics->JavaArraySInt32Type);
- push(new LoadInst(ptr, "", currentBlock), false);
- break;
- }
-
- case LALOAD : {
- Value* index = pop();
- Value* obj = pop();
- Value* ptr = verifyAndComputePtr(obj, index,
- intrinsics->JavaArrayLongType);
- push(new LoadInst(ptr, "", currentBlock), false);
- push(intrinsics->constantZero, false);
- break;
- }
-
- case FALOAD : {
- Value* index = pop();
- Value* obj = pop();
- Value* ptr = verifyAndComputePtr(obj, index,
- intrinsics->JavaArrayFloatType);
- push(new LoadInst(ptr, "", currentBlock), false);
- break;
- }
-
- case DALOAD : {
- Value* index = pop();
- Value* obj = pop();
- Value* ptr = verifyAndComputePtr(obj, index,
- intrinsics->JavaArrayDoubleType);
- push(new LoadInst(ptr, "", currentBlock), false);
- push(intrinsics->constantZero, false);
- break;
- }
-
- case AALOAD : {
- Value* index = pop();
- CommonClass* cl = topTypeInfo();
- Value* obj = pop();
- Value* ptr = verifyAndComputePtr(obj, index,
- intrinsics->JavaArrayObjectType);
-
- if (cl->isArray()) cl = cl->asArrayClass()->baseClass();
- push(new LoadInst(ptr, "", currentBlock), false, cl);
- break;
- }
-
- case BALOAD : {
- Value* index = pop();
- Value* obj = pop();
- Value* ptr = verifyAndComputePtr(obj, index,
- intrinsics->JavaArraySInt8Type);
- Value* val = new LoadInst(ptr, "", currentBlock);
- push(new SExtInst(val, Type::getInt32Ty(*llvmContext), "", currentBlock),
- false);
- break;
- }
-
- case CALOAD : {
- Value* index = pop();
- Value* obj = pop();
- Value* ptr = verifyAndComputePtr(obj, index,
- intrinsics->JavaArrayUInt16Type);
- Value* val = new LoadInst(ptr, "", currentBlock);
- push(new ZExtInst(val, Type::getInt32Ty(*llvmContext), "", currentBlock),
- false);
- break;
- }
-
- case SALOAD : {
- Value* index = pop();
- Value* obj = pop();
- Value* ptr = verifyAndComputePtr(obj, index,
- intrinsics->JavaArraySInt16Type);
- Value* val = new LoadInst(ptr, "", currentBlock);
- push(new SExtInst(val, Type::getInt32Ty(*llvmContext), "", currentBlock),
- false);
- break;
- }
-
- case ISTORE : {
- Value* val = popAsInt();
- new StoreInst(val, intLocals[WREAD_U1(reader, false, i, wide)],
- false, currentBlock);
- break;
- }
-
- case LSTORE :
- pop(); // remove the 0 on the stack
- new StoreInst(pop(), longLocals[WREAD_U1(reader, false, i, wide)],
- false, currentBlock);
- break;
-
- case FSTORE :
- new StoreInst(pop(), floatLocals[WREAD_U1(reader, false, i, wide)],
- false, currentBlock);
- break;
-
- case DSTORE :
- pop(); // remove the 0 on the stack
- new StoreInst(pop(), doubleLocals[WREAD_U1(reader, false, i, wide)],
- false, currentBlock);
- break;
-
- case ASTORE : {
- CommonClass* cl = topTypeInfo();
- Instruction* V =
- new StoreInst(pop(), objectLocals[WREAD_U1(reader, false, i, wide)],
- false, currentBlock);
- addHighLevelType(V, cl);
- break;
- }
- case ISTORE_0 : {
- Value* val = pop();
- if (val->getType() != Type::getInt32Ty(*llvmContext)) // int8 and int16
- val = new ZExtInst(val, Type::getInt32Ty(*llvmContext), "", currentBlock);
- new StoreInst(val, intLocals[0], false, currentBlock);
- break;
- }
-
- case ISTORE_1 : {
- Value* val = pop();
- if (val->getType() != Type::getInt32Ty(*llvmContext)) // int8 and int16
- val = new ZExtInst(val, Type::getInt32Ty(*llvmContext), "", currentBlock);
- new StoreInst(val, intLocals[1], false, currentBlock);
- break;
- }
-
- case ISTORE_2 : {
- Value* val = pop();
- if (val->getType() != Type::getInt32Ty(*llvmContext)) // int8 and int16
- val = new ZExtInst(val, Type::getInt32Ty(*llvmContext), "", currentBlock);
- new StoreInst(val, intLocals[2], false, currentBlock);
- break;
- }
-
- case ISTORE_3 : {
- Value* val = pop();
- if (val->getType() != Type::getInt32Ty(*llvmContext)) // int8 and int16
- val = new ZExtInst(val, Type::getInt32Ty(*llvmContext), "", currentBlock);
- new StoreInst(val, intLocals[3], false, currentBlock);
- break;
- }
-
- case LSTORE_0 :
- pop(); // remove the 0 on the stack
- new StoreInst(pop(), longLocals[0], false, currentBlock);
- break;
-
- case LSTORE_1 :
- pop(); // remove the 0 on the stack
- new StoreInst(pop(), longLocals[1], false, currentBlock);
- break;
-
- case LSTORE_2 :
- pop(); // remove the 0 on the stack
- new StoreInst(pop(), longLocals[2], false, currentBlock);
- break;
-
- case LSTORE_3 :
- pop(); // remove the 0 on the stack
- new StoreInst(pop(), longLocals[3], false, currentBlock);
- break;
-
- case FSTORE_0 :
- new StoreInst(pop(), floatLocals[0], false, currentBlock);
- break;
-
- case FSTORE_1 :
- new StoreInst(pop(), floatLocals[1], false, currentBlock);
- break;
-
- case FSTORE_2 :
- new StoreInst(pop(), floatLocals[2], false, currentBlock);
- break;
-
- case FSTORE_3 :
- new StoreInst(pop(), floatLocals[3], false, currentBlock);
- break;
-
- case DSTORE_0 :
- pop(); // remove the 0 on the stack
- new StoreInst(pop(), doubleLocals[0], false, currentBlock);
- break;
-
- case DSTORE_1 :
- pop(); // remove the 0 on the stack
- new StoreInst(pop(), doubleLocals[1], false, currentBlock);
- break;
-
- case DSTORE_2 :
- pop(); // remove the 0 on the stack
- new StoreInst(pop(), doubleLocals[2], false, currentBlock);
- break;
-
- case DSTORE_3 :
- pop(); // remove the 0 on the stack
- new StoreInst(pop(), doubleLocals[3], false, currentBlock);
- break;
-
- case ASTORE_0 : {
- CommonClass* cl = topTypeInfo();
- Instruction* V = new StoreInst(pop(), objectLocals[0], false,
- currentBlock);
- addHighLevelType(V, cl);
- break;
- }
-
- case ASTORE_1 : {
- CommonClass* cl = topTypeInfo();
- Instruction* V = new StoreInst(pop(), objectLocals[1], false,
- currentBlock);
- addHighLevelType(V, cl);
- break;
- }
-
- case ASTORE_2 : {
- CommonClass* cl = topTypeInfo();
- Instruction* V = new StoreInst(pop(), objectLocals[2], false,
- currentBlock);
- addHighLevelType(V, cl);
- break;
- }
-
- case ASTORE_3 : {
- CommonClass* cl = topTypeInfo();
- Instruction* V = new StoreInst(pop(), objectLocals[3], false,
- currentBlock);
- addHighLevelType(V, cl);
- break;
- }
-
- case IASTORE : {
- Value* val = popAsInt();
- Value* index = popAsInt();
- Value* obj = pop();
- Value* ptr = verifyAndComputePtr(obj, index,
- intrinsics->JavaArraySInt32Type);
- new StoreInst(val, ptr, false, currentBlock);
- break;
- }
-
- case LASTORE : {
- pop(); // remove the 0 on stack
- Value* val = pop();
- Value* index = pop();
- Value* obj = pop();
- Value* ptr = verifyAndComputePtr(obj, index,
- intrinsics->JavaArrayLongType);
- new StoreInst(val, ptr, false, currentBlock);
- break;
- }
-
- case FASTORE : {
- Value* val = pop();
- Value* index = pop();
- Value* obj = pop();
- Value* ptr = verifyAndComputePtr(obj, index,
- intrinsics->JavaArrayFloatType);
- new StoreInst(val, ptr, false, currentBlock);
- break;
- }
-
- case DASTORE : {
- pop(); // remove the 0 on stack
- Value* val = pop();
- Value* index = pop();
- Value* obj = pop();
- Value* ptr = verifyAndComputePtr(obj, index,
- intrinsics->JavaArrayDoubleType);
- new StoreInst(val, ptr, false, currentBlock);
- break;
- }
-
- case AASTORE : {
- if (TheCompiler->hasExceptionsEnabled()) {
- // Get val and object and don't pop them: IsAssignableFromFunction
- // may go into runtime and we don't want values in registers at that
- // point.
- Value* val = new LoadInst(objectStack[currentStackIndex - 1], "",
- TheCompiler->useCooperativeGC(),
- currentBlock);
- Value* obj = new LoadInst(objectStack[currentStackIndex - 3], "",
- TheCompiler->useCooperativeGC(),
- currentBlock);
- Value* cmp = new ICmpInst(*currentBlock, ICmpInst::ICMP_EQ, val,
- intrinsics->JavaObjectNullConstant, "");
-
- BasicBlock* endBlock = createBasicBlock("end array store check");
- BasicBlock* checkBlock = createBasicBlock("array store check");
- BasicBlock* exceptionBlock =
- createBasicBlock("array store exception");
- BranchInst::Create(endBlock, checkBlock, cmp, currentBlock);
- currentBlock = checkBlock;
-
- Value* valVT = CallInst::Create(intrinsics->GetVTFunction, val, "",
- currentBlock);
-
- Value* objVT = CallInst::Create(intrinsics->GetVTFunction, obj, "",
- currentBlock);
- objVT = CallInst::Create(intrinsics->GetBaseClassVTFromVTFunction, objVT,
- "", currentBlock);
-
- Value* VTArgs[2] = { valVT, objVT };
-
- Value* res = CallInst::Create(intrinsics->IsAssignableFromFunction,
- VTArgs, VTArgs + 2, "", currentBlock);
-
- BranchInst::Create(endBlock, exceptionBlock, res, currentBlock);
-
- currentBlock = exceptionBlock;
- throwException(intrinsics->ArrayStoreExceptionFunction, VTArgs, 2);
-
- currentBlock = endBlock;
- }
- Value* val = pop();
- Value* index = pop();
- Value* obj = pop();
- Value* ptr = verifyAndComputePtr(obj, index,
- intrinsics->JavaArrayObjectType);
-
- new StoreInst(val, ptr, false, currentBlock);
- break;
- }
-
- case BASTORE : {
- Value* val = pop();
- if (val->getType() != Type::getInt8Ty(*llvmContext)) {
- val = new TruncInst(val, Type::getInt8Ty(*llvmContext), "", currentBlock);
- }
- Value* index = pop();
- Value* obj = pop();
- Value* ptr = verifyAndComputePtr(obj, index,
- intrinsics->JavaArraySInt8Type);
- new StoreInst(val, ptr, false, currentBlock);
- break;
- }
-
- case CASTORE : {
- Value* val = pop();
- const Type* type = val->getType();
- if (type == Type::getInt32Ty(*llvmContext)) {
- val = new TruncInst(val, Type::getInt16Ty(*llvmContext), "", currentBlock);
- } else if (type == Type::getInt8Ty(*llvmContext)) {
- val = new ZExtInst(val, Type::getInt16Ty(*llvmContext), "", currentBlock);
- }
- Value* index = pop();
- Value* obj = pop();
- Value* ptr = verifyAndComputePtr(obj, index,
- intrinsics->JavaArrayUInt16Type);
- new StoreInst(val, ptr, false, currentBlock);
- break;
- }
-
- case SASTORE : {
- Value* val = pop();
- const Type* type = val->getType();
- if (type == Type::getInt32Ty(*llvmContext)) {
- val = new TruncInst(val, Type::getInt16Ty(*llvmContext), "", currentBlock);
- } else if (type == Type::getInt8Ty(*llvmContext)) {
- val = new SExtInst(val, Type::getInt16Ty(*llvmContext), "", currentBlock);
- }
- Value* index = pop();
- Value* obj = pop();
- Value* ptr = verifyAndComputePtr(obj, index,
- intrinsics->JavaArraySInt16Type);
- new StoreInst(val, ptr, false, currentBlock);
- break;
- }
-
- case POP :
- pop();
- break;
-
- case POP2 :
- pop(); pop();
- break;
-
- case DUP :
- push(top(), false, topTypeInfo());
- break;
-
- case DUP_X1 : {
- CommonClass* oneCl = topTypeInfo();
- Value* one = pop();
- CommonClass* twoCl = topTypeInfo();
- Value* two = pop();
-
- push(one, false, oneCl);
- push(two, false, twoCl);
- push(one, false, oneCl);
- break;
- }
-
- case DUP_X2 : {
- CommonClass* oneCl = topTypeInfo();
- Value* one = pop();
- CommonClass* twoCl = topTypeInfo();
- Value* two = pop();
- CommonClass* threeCl = topTypeInfo();
- Value* three = pop();
-
- push(one, false, oneCl);
- push(three, false, threeCl);
- push(two, false, twoCl);
- push(one, false, oneCl);
- break;
- }
-
- case DUP2 : {
- CommonClass* oneCl = topTypeInfo();
- Value* one = pop();
- CommonClass* twoCl = topTypeInfo();
- Value* two = pop();
-
- push(two, false, twoCl);
- push(one, false, oneCl);
- push(two, false, twoCl);
- push(one, false, oneCl);
- break;
- }
-
- case DUP2_X1 : {
- CommonClass* oneCl = topTypeInfo();
- Value* one = pop();
- CommonClass* twoCl = topTypeInfo();
- Value* two = pop();
- CommonClass* threeCl = topTypeInfo();
- Value* three = pop();
-
- push(two, false, twoCl);
- push(one, false, oneCl);
-
- push(three, false, threeCl);
- push(two, false, twoCl);
- push(one, false, oneCl);
-
- break;
- }
-
- case DUP2_X2 : {
- CommonClass* oneCl = topTypeInfo();
- Value* one = pop();
- CommonClass* twoCl = topTypeInfo();
- Value* two = pop();
- CommonClass* threeCl = topTypeInfo();
- Value* three = pop();
- CommonClass* fourCl = topTypeInfo();
- Value* four = pop();
-
- push(two, false, twoCl);
- push(one, false, oneCl);
-
- push(four, false, fourCl);
- push(three, false, threeCl);
- push(two, false, twoCl);
- push(one, false, oneCl);
-
- break;
- }
-
- case SWAP : {
- CommonClass* oneCl = topTypeInfo();
- Value* one = pop();
- CommonClass* twoCl = topTypeInfo();
- Value* two = pop();
- push(one, false, oneCl);
- push(two, false, twoCl);
- break;
- }
-
- case IADD : {
- Value* val2 = popAsInt();
- Value* val1 = popAsInt();
- push(BinaryOperator::CreateAdd(val1, val2, "", currentBlock),
- false);
- break;
- }
-
- case LADD : {
- pop();
- llvm::Value* val2 = pop();
- pop();
- llvm::Value* val1 = pop();
- push(BinaryOperator::CreateAdd(val1, val2, "", currentBlock),
- false);
- push(intrinsics->constantZero, false);
- break;
- }
-
- case FADD : {
- Value* val2 = pop();
- Value* val1 = pop();
- push(BinaryOperator::CreateFAdd(val1, val2, "", currentBlock),
- false);
- break;
- }
-
- case DADD : {
- pop();
- llvm::Value* val2 = pop();
- pop();
- llvm::Value* val1 = pop();
- push(BinaryOperator::CreateFAdd(val1, val2, "", currentBlock),
- false);
- push(intrinsics->constantZero, false);
- break;
- }
-
- case ISUB : {
- Value* val2 = popAsInt();
- Value* val1 = popAsInt();
- push(BinaryOperator::CreateSub(val1, val2, "", currentBlock),
- false);
- break;
- }
- case LSUB : {
- pop();
- llvm::Value* val2 = pop();
- pop();
- llvm::Value* val1 = pop();
- push(BinaryOperator::CreateSub(val1, val2, "", currentBlock),
- false);
- push(intrinsics->constantZero, false);
- break;
- }
-
- case FSUB : {
- Value* val2 = pop();
- Value* val1 = pop();
- push(BinaryOperator::CreateFSub(val1, val2, "", currentBlock),
- false);
- break;
- }
-
- case DSUB : {
- pop();
- llvm::Value* val2 = pop();
- pop();
- llvm::Value* val1 = pop();
- push(BinaryOperator::CreateFSub(val1, val2, "", currentBlock),
- false);
- push(intrinsics->constantZero, false);
- break;
- }
-
- case IMUL : {
- Value* val2 = popAsInt();
- Value* val1 = popAsInt();
- push(BinaryOperator::CreateMul(val1, val2, "", currentBlock),
- false);
- break;
- }
-
- case LMUL : {
- pop();
- llvm::Value* val2 = pop();
- pop();
- llvm::Value* val1 = pop();
- push(BinaryOperator::CreateMul(val1, val2, "", currentBlock),
- false);
- push(intrinsics->constantZero, false);
- break;
- }
-
- case FMUL : {
- Value* val2 = pop();
- Value* val1 = pop();
- push(BinaryOperator::CreateFMul(val1, val2, "", currentBlock),
- false);
- break;
- }
-
- case DMUL : {
- pop();
- llvm::Value* val2 = pop();
- pop();
- llvm::Value* val1 = pop();
- push(BinaryOperator::CreateFMul(val1, val2, "", currentBlock),
- false);
- push(intrinsics->constantZero, false);
- break;
- }
-
- case IDIV : {
- Value* val2 = popAsInt();
- Value* val1 = popAsInt();
- if (TheCompiler->hasExceptionsEnabled()) {
- Value* cmp = new ICmpInst(*currentBlock, ICmpInst::ICMP_EQ, val2,
- intrinsics->constantZero, "");
- BasicBlock* ifFalse = createBasicBlock("non null div");
- BasicBlock* ifTrue = createBasicBlock("null div");
-
- BranchInst::Create(ifTrue, ifFalse, cmp, currentBlock);
- currentBlock = ifTrue;
- throwException(intrinsics->ArithmeticExceptionFunction, 0, 0);
- currentBlock = ifFalse;
- }
- Value* cmp = new ICmpInst(*currentBlock, ICmpInst::ICMP_EQ, val2,
- intrinsics->constantMinusOne, "");
- BasicBlock* ifFalse = createBasicBlock("non -1 div");
- BasicBlock* ifTrue = createBasicBlock("-1 div");
- BasicBlock* endBlock = createBasicBlock("End division");
- PHINode* node = PHINode::Create(val1->getType(), "", endBlock);
- BranchInst::Create(ifTrue, ifFalse, cmp, currentBlock);
- currentBlock = ifTrue;
- node->addIncoming(BinaryOperator::CreateSub(intrinsics->constantZero,
- val1, "", currentBlock),
- currentBlock);
- BranchInst::Create(endBlock, currentBlock);
- currentBlock = ifFalse;
- node->addIncoming(
- BinaryOperator::CreateSDiv(val1, val2, "", currentBlock),
- currentBlock);
- BranchInst::Create(endBlock, currentBlock);
- currentBlock = endBlock;
- push(node, false);
- break;
- }
-
- case LDIV : {
- pop();
- llvm::Value* val2 = pop();
- pop();
- llvm::Value* val1 = pop();
- if (TheCompiler->hasExceptionsEnabled()) {
- Value* cmp = new ICmpInst(*currentBlock, ICmpInst::ICMP_EQ, val2,
- intrinsics->constantLongZero, "");
- BasicBlock* ifFalse = createBasicBlock("non null div");
- BasicBlock* ifTrue = createBasicBlock("null div");
-
- BranchInst::Create(ifTrue, ifFalse, cmp, currentBlock);
- currentBlock = ifTrue;
- throwException(intrinsics->ArithmeticExceptionFunction, 0, 0);
- currentBlock = ifFalse;
- }
- push(BinaryOperator::CreateSDiv(val1, val2, "", currentBlock),
- false);
- push(intrinsics->constantZero, false);
- break;
- }
-
- case FDIV : {
- Value* val2 = pop();
- Value* val1 = pop();
- push(BinaryOperator::CreateFDiv(val1, val2, "", currentBlock),
- false);
- break;
- }
-
- case DDIV : {
- pop();
- llvm::Value* val2 = pop();
- pop();
- llvm::Value* val1 = pop();
- push(BinaryOperator::CreateFDiv(val1, val2, "", currentBlock),
- false);
- push(intrinsics->constantZero, false);
- break;
- }
-
- case IREM : {
- Value* val2 = popAsInt();
- Value* val1 = popAsInt();
- if (TheCompiler->hasExceptionsEnabled()) {
- Value* cmp = new ICmpInst(*currentBlock, ICmpInst::ICMP_EQ, val2,
- intrinsics->constantZero, "");
- BasicBlock* ifFalse = createBasicBlock("non null rem");
- BasicBlock* ifTrue = createBasicBlock("null rem");
-
- BranchInst::Create(ifTrue, ifFalse, cmp, currentBlock);
- currentBlock = ifTrue;
- throwException(intrinsics->ArithmeticExceptionFunction, 0, 0);
- currentBlock = ifFalse;
- }
- Value* cmp = new ICmpInst(*currentBlock, ICmpInst::ICMP_EQ, val2,
- intrinsics->constantMinusOne, "");
- BasicBlock* ifFalse = createBasicBlock("non -1 rem");
- BasicBlock* endBlock = createBasicBlock("end block");
- PHINode* node = PHINode::Create(val1->getType(), "", endBlock);
- node->addIncoming(intrinsics->constantZero, currentBlock);
- BranchInst::Create(endBlock, ifFalse, cmp, currentBlock);
- currentBlock = ifFalse;
- node->addIncoming(
- BinaryOperator::CreateSRem(val1, val2, "", currentBlock),
- currentBlock);
- BranchInst::Create(endBlock, currentBlock);
- currentBlock = endBlock;
- push(node, false);
- break;
- }
-
- case LREM : {
- pop();
- llvm::Value* val2 = pop();
- pop();
- llvm::Value* val1 = pop();
- if (TheCompiler->hasExceptionsEnabled()) {
- Value* cmp = new ICmpInst(*currentBlock, ICmpInst::ICMP_EQ, val2,
- intrinsics->constantLongZero, "");
- BasicBlock* ifFalse = createBasicBlock("non null div");
- BasicBlock* ifTrue = createBasicBlock("null div");
-
- BranchInst::Create(ifTrue, ifFalse, cmp, currentBlock);
- currentBlock = ifTrue;
- throwException(intrinsics->ArithmeticExceptionFunction, 0, 0);
- currentBlock = ifFalse;
- }
- push(BinaryOperator::CreateSRem(val1, val2, "", currentBlock),
- false);
- push(intrinsics->constantZero, false);
- break;
- }
-
- case FREM : {
- Value* val2 = pop();
- Value* val1 = pop();
- push(BinaryOperator::CreateFRem(val1, val2, "", currentBlock),
- false);
- break;
- }
-
- case DREM : {
- pop();
- llvm::Value* val2 = pop();
- pop();
- llvm::Value* val1 = pop();
- push(BinaryOperator::CreateFRem(val1, val2, "", currentBlock),
- false);
- push(intrinsics->constantZero, false);
- break;
- }
-
- case INEG :
- push(BinaryOperator::CreateSub(
- intrinsics->constantZero,
- popAsInt(), "", currentBlock),
- false);
- break;
-
- case LNEG : {
- pop();
- push(BinaryOperator::CreateSub(
- intrinsics->constantLongZero,
- pop(), "", currentBlock), false);
- push(intrinsics->constantZero, false);
- break;
- }
-
- case FNEG :
- push(BinaryOperator::CreateFSub(
- intrinsics->constantFloatMinusZero,
- pop(), "", currentBlock), false);
- break;
-
- case DNEG : {
- pop();
- push(BinaryOperator::CreateFSub(
- intrinsics->constantDoubleMinusZero,
- pop(), "", currentBlock), false);
- push(intrinsics->constantZero, false);
- break;
- }
-
- case ISHL : {
- Value* val2 = popAsInt();
- Value* val1 = popAsInt();
- push(BinaryOperator::CreateShl(val1, val2, "", currentBlock),
- false);
- break;
- }
-
- case LSHL : {
- Value* val2 = new ZExtInst(pop(), Type::getInt64Ty(*llvmContext), "", currentBlock);
- pop(); // remove the 0 on the stack
- Value* val1 = pop();
- push(BinaryOperator::CreateShl(val1, val2, "", currentBlock),
- false);
- push(intrinsics->constantZero, false);
- break;
- }
-
- case ISHR : {
- Value* val2 = popAsInt();
- Value* val1 = popAsInt();
- push(BinaryOperator::CreateAShr(val1, val2, "", currentBlock),
- false);
- break;
- }
-
- case LSHR : {
- Value* val2 = new ZExtInst(pop(), Type::getInt64Ty(*llvmContext), "", currentBlock);
- pop(); // remove the 0 on the stack
- Value* val1 = pop();
- push(BinaryOperator::CreateAShr(val1, val2, "", currentBlock),
- false);
- push(intrinsics->constantZero, false);
- break;
- }
-
- case IUSHR : {
- Value* val2 = popAsInt();
- Value* val1 = popAsInt();
- Value* mask = ConstantInt::get(Type::getInt32Ty(*llvmContext), 0x1F);
- val2 = BinaryOperator::CreateAnd(val2, mask, "", currentBlock);
- push(BinaryOperator::CreateLShr(val1, val2, "", currentBlock),
- false);
- break;
- }
-
- case LUSHR : {
- Value* val2 = new ZExtInst(pop(), Type::getInt64Ty(*llvmContext), "", currentBlock);
- Value* mask = ConstantInt::get(Type::getInt64Ty(*llvmContext), 0x3F);
- val2 = BinaryOperator::CreateAnd(val2, mask, "", currentBlock);
- pop(); // remove the 0 on the stack
- Value* val1 = pop();
- push(BinaryOperator::CreateLShr(val1, val2, "", currentBlock),
- false);
- push(intrinsics->constantZero, false);
- break;
- }
-
- case IAND : {
- Value* val2 = popAsInt();
- Value* val1 = popAsInt();
- push(BinaryOperator::CreateAnd(val1, val2, "", currentBlock),
- false);
- break;
- }
-
- case LAND : {
- pop();
- Value* val2 = pop();
- pop(); // remove the 0 on the stack
- Value* val1 = pop();
- push(BinaryOperator::CreateAnd(val1, val2, "", currentBlock),
- false);
- push(intrinsics->constantZero, false);
- break;
- }
-
- case IOR : {
- Value* val2 = popAsInt();
- Value* val1 = popAsInt();
- push(BinaryOperator::CreateOr(val1, val2, "", currentBlock),
- false);
- break;
- }
-
- case LOR : {
- pop();
- Value* val2 = pop();
- pop(); // remove the 0 on the stack
- Value* val1 = pop();
- push(BinaryOperator::CreateOr(val1, val2, "", currentBlock),
- false);
- push(intrinsics->constantZero, false);
- break;
- }
-
- case IXOR : {
- Value* val2 = popAsInt();
- Value* val1 = popAsInt();
- push(BinaryOperator::CreateXor(val1, val2, "", currentBlock),
- false);
- break;
- }
-
- case LXOR : {
- pop();
- Value* val2 = pop();
- pop(); // remove the 0 on the stack
- Value* val1 = pop();
- push(BinaryOperator::CreateXor(val1, val2, "", currentBlock),
- false);
- push(intrinsics->constantZero, false);
- break;
- }
-
- case IINC : {
- uint16 idx = WREAD_U1(reader, true, i, wide);
- sint16 val = WREAD_S1(reader, false, i, wide);
- llvm::Value* add = BinaryOperator::CreateAdd(
- new LoadInst(intLocals[idx], "", currentBlock),
- ConstantInt::get(Type::getInt32Ty(*llvmContext), val), "",
- currentBlock);
- new StoreInst(add, intLocals[idx], false, currentBlock);
- break;
- }
-
- case I2L :
- push(new SExtInst(pop(), llvm::Type::getInt64Ty(*llvmContext), "", currentBlock),
- false);
- push(intrinsics->constantZero, false);
- break;
-
- case I2F :
- push(new SIToFPInst(pop(), llvm::Type::getFloatTy(*llvmContext), "", currentBlock),
- false);
- break;
-
- case I2D :
- push(new SIToFPInst(pop(), llvm::Type::getDoubleTy(*llvmContext), "", currentBlock),
- false);
- push(intrinsics->constantZero, false);
- break;
-
- case L2I :
- pop();
- push(new TruncInst(pop(), llvm::Type::getInt32Ty(*llvmContext), "", currentBlock),
- false);
- break;
-
- case L2F :
- pop();
- push(new SIToFPInst(pop(), llvm::Type::getFloatTy(*llvmContext), "", currentBlock),
- false);
- break;
-
- case L2D :
- pop();
- push(new SIToFPInst(pop(), llvm::Type::getDoubleTy(*llvmContext), "", currentBlock),
- false);
- push(intrinsics->constantZero, false);
- break;
-
- case F2I : {
- llvm::Value* val = pop();
- llvm::Value* test = new FCmpInst(*currentBlock, FCmpInst::FCMP_ONE,
- val, val, "");
-
- BasicBlock* res = createBasicBlock("F2I");
- PHINode* node = PHINode::Create(llvm::Type::getInt32Ty(*llvmContext), "", res);
- node->addIncoming(intrinsics->constantZero, currentBlock);
- BasicBlock* cont = createBasicBlock("F2I");
-
- BranchInst::Create(res, cont, test, currentBlock);
-
- currentBlock = cont;
-
- test = new FCmpInst(*currentBlock, FCmpInst::FCMP_OGE, val,
- intrinsics->constantMaxIntFloat, "");
-
- cont = createBasicBlock("F2I");
-
- BranchInst::Create(res, cont, test, currentBlock);
- node->addIncoming(intrinsics->constantMaxInt,
- currentBlock);
-
- currentBlock = cont;
-
- test = new FCmpInst(*currentBlock, FCmpInst::FCMP_OLE, val,
- intrinsics->constantMinIntFloat, "");
-
- cont = createBasicBlock("F2I");
-
- BranchInst::Create(res, cont, test, currentBlock);
- node->addIncoming(intrinsics->constantMinInt, currentBlock);
-
- currentBlock = cont;
- llvm::Value* newVal = new FPToSIInst(val, Type::getInt32Ty(*llvmContext), "",
- currentBlock);
- BranchInst::Create(res, currentBlock);
-
- node->addIncoming(newVal, currentBlock);
-
- currentBlock = res;
-
- push(node, false);
- break;
- }
-
- case F2L : {
- llvm::Value* val = pop();
- llvm::Value* test = new FCmpInst(*currentBlock, FCmpInst::FCMP_ONE,
- val, val, "");
-
- BasicBlock* res = createBasicBlock("F2L");
- PHINode* node = PHINode::Create(llvm::Type::getInt64Ty(*llvmContext), "", res);
- node->addIncoming(intrinsics->constantLongZero, currentBlock);
- BasicBlock* cont = createBasicBlock("F2L");
-
- BranchInst::Create(res, cont, test, currentBlock);
-
- currentBlock = cont;
-
- test = new FCmpInst(*currentBlock, FCmpInst::FCMP_OGE, val,
- intrinsics->constantMaxLongFloat, "");
-
- cont = createBasicBlock("F2L");
-
- BranchInst::Create(res, cont, test, currentBlock);
- node->addIncoming(intrinsics->constantMaxLong, currentBlock);
-
- currentBlock = cont;
-
- test = new FCmpInst(*currentBlock, FCmpInst::FCMP_OLE, val,
- intrinsics->constantMinLongFloat, "");
-
- cont = createBasicBlock("F2L");
-
- BranchInst::Create(res, cont, test, currentBlock);
- node->addIncoming(intrinsics->constantMinLong, currentBlock);
-
- currentBlock = cont;
- llvm::Value* newVal = new FPToSIInst(val, Type::getInt64Ty(*llvmContext), "",
- currentBlock);
- BranchInst::Create(res, currentBlock);
-
- node->addIncoming(newVal, currentBlock);
-
- currentBlock = res;
-
- push(node, false);
- push(intrinsics->constantZero, false);
- break;
- }
-
- case F2D :
- push(new FPExtInst(pop(), llvm::Type::getDoubleTy(*llvmContext), "", currentBlock),
- false);
- push(intrinsics->constantZero, false);
- break;
-
- case D2I : {
- pop(); // remove the 0 on the stack
- llvm::Value* val = pop();
- llvm::Value* test = new FCmpInst(*currentBlock, FCmpInst::FCMP_ONE,
- val, val, "");
-
- BasicBlock* res = createBasicBlock("D2I");
- PHINode* node = PHINode::Create(llvm::Type::getInt32Ty(*llvmContext), "", res);
- node->addIncoming(intrinsics->constantZero, currentBlock);
- BasicBlock* cont = createBasicBlock("D2I");
-
- BranchInst::Create(res, cont, test, currentBlock);
-
- currentBlock = cont;
-
- test = new FCmpInst(*currentBlock, FCmpInst::FCMP_OGE, val,
- intrinsics->constantMaxIntDouble, "");
-
- cont = createBasicBlock("D2I");
-
- BranchInst::Create(res, cont, test, currentBlock);
- node->addIncoming(intrinsics->constantMaxInt, currentBlock);
-
- currentBlock = cont;
-
- test = new FCmpInst(*currentBlock, FCmpInst::FCMP_OLE, val,
- intrinsics->constantMinIntDouble, "");
-
- cont = createBasicBlock("D2I");
-
- BranchInst::Create(res, cont, test, currentBlock);
- node->addIncoming(intrinsics->constantMinInt, currentBlock);
-
- currentBlock = cont;
- llvm::Value* newVal = new FPToSIInst(val, Type::getInt32Ty(*llvmContext), "",
- currentBlock);
- BranchInst::Create(res, currentBlock);
-
- node->addIncoming(newVal, currentBlock);
-
- currentBlock = res;
-
- push(node, false);
-
- break;
- }
-
- case D2L : {
- pop(); // remove the 0 on the stack
- llvm::Value* val = pop();
- llvm::Value* test = new FCmpInst(*currentBlock, FCmpInst::FCMP_ONE,
- val, val, "");
-
- BasicBlock* res = createBasicBlock("D2L");
- PHINode* node = PHINode::Create(llvm::Type::getInt64Ty(*llvmContext), "", res);
- node->addIncoming(intrinsics->constantLongZero, currentBlock);
- BasicBlock* cont = createBasicBlock("D2L");
-
- BranchInst::Create(res, cont, test, currentBlock);
-
- currentBlock = cont;
-
- test = new FCmpInst(*currentBlock, FCmpInst::FCMP_OGE, val,
- intrinsics->constantMaxLongDouble, "");
-
- cont = createBasicBlock("D2L");
-
- BranchInst::Create(res, cont, test, currentBlock);
- node->addIncoming(intrinsics->constantMaxLong, currentBlock);
-
- currentBlock = cont;
-
- test =
- new FCmpInst(*currentBlock, FCmpInst::FCMP_OLE, val,
- intrinsics->constantMinLongDouble, "");
-
- cont = createBasicBlock("D2L");
-
- BranchInst::Create(res, cont, test, currentBlock);
- node->addIncoming(intrinsics->constantMinLong, currentBlock);
-
- currentBlock = cont;
- llvm::Value* newVal = new FPToSIInst(val, Type::getInt64Ty(*llvmContext), "",
- currentBlock);
- BranchInst::Create(res, currentBlock);
-
- node->addIncoming(newVal, currentBlock);
-
- currentBlock = res;
-
- push(node, false);
- push(intrinsics->constantZero, false);
- break;
- }
-
- case D2F :
- pop(); // remove the 0 on the stack
- push(new FPTruncInst(pop(), llvm::Type::getFloatTy(*llvmContext), "", currentBlock),
- false);
- break;
-
- case I2B : {
- Value* val = pop();
- if (val->getType() == Type::getInt32Ty(*llvmContext)) {
- val = new TruncInst(val, llvm::Type::getInt8Ty(*llvmContext), "", currentBlock);
- }
- push(new SExtInst(val, llvm::Type::getInt32Ty(*llvmContext), "", currentBlock),
- false);
- break;
- }
-
- case I2C : {
- Value* val = pop();
- if (val->getType() == Type::getInt32Ty(*llvmContext)) {
- val = new TruncInst(val, llvm::Type::getInt16Ty(*llvmContext), "", currentBlock);
- }
- push(new ZExtInst(val, llvm::Type::getInt32Ty(*llvmContext), "", currentBlock),
- false);
- break;
- }
-
- case I2S : {
- Value* val = pop();
- if (val->getType() == Type::getInt32Ty(*llvmContext)) {
- val = new TruncInst(val, llvm::Type::getInt16Ty(*llvmContext), "", currentBlock);
- }
- push(new SExtInst(val, llvm::Type::getInt32Ty(*llvmContext), "", currentBlock),
- false);
- break;
- }
-
- case LCMP : {
- pop();
- llvm::Value* val2 = pop();
- pop();
- llvm::Value* val1 = pop();
-
- llvm::Value* test = new ICmpInst(*currentBlock, ICmpInst::ICMP_EQ, val1,
- val2, "");
-
- BasicBlock* cont = createBasicBlock("LCMP");
- BasicBlock* res = createBasicBlock("LCMP");
- PHINode* node = PHINode::Create(llvm::Type::getInt32Ty(*llvmContext), "", res);
- node->addIncoming(intrinsics->constantZero, currentBlock);
-
- BranchInst::Create(res, cont, test, currentBlock);
- currentBlock = cont;
-
- test = new ICmpInst(*currentBlock, ICmpInst::ICMP_SLT, val1, val2, "");
- node->addIncoming(intrinsics->constantMinusOne, currentBlock);
-
- cont = createBasicBlock("LCMP");
- BranchInst::Create(res, cont, test, currentBlock);
- currentBlock = cont;
- node->addIncoming(intrinsics->constantOne, currentBlock);
- BranchInst::Create(res, currentBlock);
- currentBlock = res;
-
- push(node, false);
- break;
- }
-
- case FCMPL : {
- llvm::Value* val2 = pop();
- llvm::Value* val1 = pop();
- compareFP(val1, val2, Type::getFloatTy(*llvmContext), false);
- break;
- }
-
- case FCMPG : {
- llvm::Value* val2 = pop();
- llvm::Value* val1 = pop();
- compareFP(val1, val2, Type::getFloatTy(*llvmContext), true);
- break;
- }
-
- case DCMPL : {
- pop();
- llvm::Value* val2 = pop();
- pop();
- llvm::Value* val1 = pop();
-
- compareFP(val1, val2, Type::getDoubleTy(*llvmContext), false);
- break;
- }
-
- case DCMPG : {
- pop();
- llvm::Value* val2 = pop();
- pop();
- llvm::Value* val1 = pop();
-
- compareFP(val1, val2, Type::getDoubleTy(*llvmContext), false);
- break;
- }
-
- case IFEQ : {
- uint32 tmp = i;
- Opinfo& ifTrueInfo = opcodeInfos[tmp + reader.readS2()];
- i += 2;
- BasicBlock* ifTrue = ifTrueInfo.newBlock;
-
- Value* op = pop();
- const Type* type = op->getType();
- Constant* val = Constant::getNullValue(type);
- llvm::Value* test = new ICmpInst(*currentBlock, ICmpInst::ICMP_EQ, op,
- val, "");
- BasicBlock* ifFalse = createBasicBlock("false IFEQ");
- branch(test, ifTrue, ifFalse, currentBlock, ifTrueInfo);
- currentBlock = ifFalse;
- break;
- }
-
- case IFNE : {
- uint32 tmp = i;
- Opinfo& ifTrueInfo = opcodeInfos[tmp + reader.readS2()];
- i += 2;
- BasicBlock* ifTrue = ifTrueInfo.newBlock;
-
- Value* op = pop();
- const Type* type = op->getType();
- Constant* val = Constant::getNullValue(type);
- llvm::Value* test = new ICmpInst(*currentBlock, ICmpInst::ICMP_NE, op,
- val, "");
- BasicBlock* ifFalse = createBasicBlock("false IFNE");
- branch(test, ifTrue, ifFalse, currentBlock, ifTrueInfo);
- currentBlock = ifFalse;
- break;
- }
-
- case IFLT : {
- uint32 tmp = i;
- Opinfo& ifTrueInfo = opcodeInfos[tmp + reader.readS2()];
- i += 2;
- BasicBlock* ifTrue = ifTrueInfo.newBlock;
- Value* op = pop();
- const Type* type = op->getType();
- Constant* val = Constant::getNullValue(type);
- llvm::Value* test = new ICmpInst(*currentBlock, ICmpInst::ICMP_SLT, op,
- val, "");
- BasicBlock* ifFalse = createBasicBlock("false IFLT");
- branch(test, ifTrue, ifFalse, currentBlock, ifTrueInfo);
- currentBlock = ifFalse;
- break;
- }
-
- case IFGE : {
- uint32 tmp = i;
- Opinfo& ifTrueInfo = opcodeInfos[tmp + reader.readS2()];
- i += 2;
- BasicBlock* ifTrue = ifTrueInfo.newBlock;
- Value* op = pop();
- const Type* type = op->getType();
- Constant* val = Constant::getNullValue(type);
- llvm::Value* test = new ICmpInst(*currentBlock, ICmpInst::ICMP_SGE, op,
- val, "");
- BasicBlock* ifFalse = createBasicBlock("false IFGE");
- branch(test, ifTrue, ifFalse, currentBlock, ifTrueInfo);
- currentBlock = ifFalse;
- break;
- }
-
- case IFGT : {
- uint32 tmp = i;
- Opinfo& ifTrueInfo = opcodeInfos[tmp + reader.readS2()];
- i += 2;
- BasicBlock* ifTrue = ifTrueInfo.newBlock;
- Value* op = pop();
- const Type* type = op->getType();
- Constant* val = Constant::getNullValue(type);
- llvm::Value* test = new ICmpInst(*currentBlock, ICmpInst::ICMP_SGT, op,
- val, "");
- BasicBlock* ifFalse = createBasicBlock("false IFGT");
- branch(test, ifTrue, ifFalse, currentBlock, ifTrueInfo);
- currentBlock = ifFalse;
- break;
- }
-
- case IFLE : {
- uint32 tmp = i;
- Opinfo& ifTrueInfo = opcodeInfos[tmp + reader.readS2()];
- i += 2;
- BasicBlock* ifTrue = ifTrueInfo.newBlock;
- Value* op = pop();
- const Type* type = op->getType();
- Constant* val = Constant::getNullValue(type);
- llvm::Value* test = new ICmpInst(*currentBlock, ICmpInst::ICMP_SLE, op,
- val, "");
- BasicBlock* ifFalse = createBasicBlock("false IFLE");
- branch(test, ifTrue, ifFalse, currentBlock, ifTrueInfo);
- currentBlock = ifFalse;
- break;
- }
-
- case IF_ICMPEQ : {
- Value *val2 = popAsInt();
- Value *val1 = popAsInt();
- uint32 tmp = i;
- Opinfo& ifTrueInfo = opcodeInfos[tmp + reader.readS2()];
- i += 2;
- BasicBlock* ifTrue = ifTrueInfo.newBlock;
- llvm::Value* test = new ICmpInst(*currentBlock, ICmpInst::ICMP_EQ, val1,
- val2, "");
- BasicBlock* ifFalse = createBasicBlock("false IF_ICMPEQ");
- branch(test, ifTrue, ifFalse, currentBlock, ifTrueInfo);
- currentBlock = ifFalse;
- break;
- }
-
- case IF_ICMPNE : {
- Value *val2 = popAsInt();
- Value *val1 = popAsInt();
- uint32 tmp = i;
- Opinfo& ifTrueInfo = opcodeInfos[tmp + reader.readS2()];
- i += 2;
- BasicBlock* ifTrue = ifTrueInfo.newBlock;
- llvm::Value* test = new ICmpInst(*currentBlock, ICmpInst::ICMP_NE, val1,
- val2, "");
- BasicBlock* ifFalse = createBasicBlock("false IF_ICMPNE");
- branch(test, ifTrue, ifFalse, currentBlock, ifTrueInfo);
- currentBlock = ifFalse;
- break;
- }
-
- case IF_ICMPLT : {
- Value *val2 = popAsInt();
- Value *val1 = popAsInt();
- uint32 tmp = i;
- Opinfo& ifTrueInfo = opcodeInfos[tmp + reader.readS2()];
- i += 2;
- BasicBlock* ifTrue = ifTrueInfo.newBlock;
- llvm::Value* test = new ICmpInst(*currentBlock, ICmpInst::ICMP_SLT,
- val1, val2, "");
- BasicBlock* ifFalse = createBasicBlock("false IF_IFCMPLT");
- branch(test, ifTrue, ifFalse, currentBlock, ifTrueInfo);
- currentBlock = ifFalse;
- break;
- }
-
- case IF_ICMPGE : {
- Value *val2 = popAsInt();
- Value *val1 = popAsInt();
- uint32 tmp = i;
- Opinfo& ifTrueInfo = opcodeInfos[tmp + reader.readS2()];
- i += 2;
- BasicBlock* ifTrue = ifTrueInfo.newBlock;
- llvm::Value* test = new ICmpInst(*currentBlock, ICmpInst::ICMP_SGE,
- val1, val2, "");
- BasicBlock* ifFalse = createBasicBlock("false IF_ICMPGE");
- branch(test, ifTrue, ifFalse, currentBlock, ifTrueInfo);
- currentBlock = ifFalse;
- break;
- }
-
- case IF_ICMPGT : {
- Value *val2 = popAsInt();
- Value *val1 = popAsInt();
- uint32 tmp = i;
- Opinfo& ifTrueInfo = opcodeInfos[tmp + reader.readS2()];
- i += 2;
- BasicBlock* ifTrue = ifTrueInfo.newBlock;
- llvm::Value* test = new ICmpInst(*currentBlock, ICmpInst::ICMP_SGT,
- val1, val2, "");
- BasicBlock* ifFalse = createBasicBlock("false IF_ICMPGT");
- branch(test, ifTrue, ifFalse, currentBlock, ifTrueInfo);
- currentBlock = ifFalse;
- break;
- }
-
- case IF_ICMPLE : {
- Value *val2 = popAsInt();
- Value *val1 = popAsInt();
- uint32 tmp = i;
- Opinfo& ifTrueInfo = opcodeInfos[tmp + reader.readS2()];
- i += 2;
- BasicBlock* ifTrue = ifTrueInfo.newBlock;
- llvm::Value* test = new ICmpInst(*currentBlock, ICmpInst::ICMP_SLE,
- val1, val2, "");
- BasicBlock* ifFalse = createBasicBlock("false IF_ICMPLE");
- branch(test, ifTrue, ifFalse, currentBlock, ifTrueInfo);
- currentBlock = ifFalse;
- break;
- }
-
- case IF_ACMPEQ : {
- Value *val2 = pop();
- Value *val1 = pop();
- uint32 tmp = i;
- Opinfo& ifTrueInfo = opcodeInfos[tmp + reader.readS2()];
- i += 2;
- BasicBlock* ifTrue = ifTrueInfo.newBlock;
- llvm::Value* test = new ICmpInst(*currentBlock, ICmpInst::ICMP_EQ,
- val1, val2, "");
- BasicBlock* ifFalse = createBasicBlock("false IF_ACMPEQ");
- branch(test, ifTrue, ifFalse, currentBlock, ifTrueInfo);
- currentBlock = ifFalse;
- break;
- }
-
- case IF_ACMPNE : {
- Value *val2 = pop();
- Value *val1 = pop();
- uint32 tmp = i;
- Opinfo& ifTrueInfo = opcodeInfos[tmp + reader.readS2()];
- i += 2;
- BasicBlock* ifTrue = ifTrueInfo.newBlock;
- llvm::Value* test = new ICmpInst(*currentBlock, ICmpInst::ICMP_NE,
- val1, val2, "");
- BasicBlock* ifFalse = createBasicBlock("false IF_ACMPNE");
- branch(test, ifTrue, ifFalse, currentBlock, ifTrueInfo);
- currentBlock = ifFalse;
- break;
- }
-
- case GOTO : {
- uint32 tmp = i;
- branch(opcodeInfos[tmp + reader.readS2()],
- currentBlock);
- i += 2;
- break;
- }
-
- case JSR : {
- uint32 tmp = i;
- uint32 index = jsrIndex | 1;
- jsrIndex += 2;
- Value* expr = ConstantExpr::getIntToPtr(
- ConstantInt::get(Type::getInt64Ty(*llvmContext),
- uint64_t (index)),
- intrinsics->JavaObjectType);
- push(expr, false);
- branch(opcodeInfos[tmp + reader.readS2()], currentBlock);
- i += 2;
- break;
- }
-
- case RET : {
- uint8 local = reader.readU1();
- i += 1;
- Value* _val = new LoadInst(
- objectLocals[local], "", TheCompiler->useCooperativeGC(), currentBlock);
- Value* val = new PtrToIntInst(_val, Type::getInt32Ty(*llvmContext), "", currentBlock);
- SwitchInst* inst = SwitchInst::Create(val, jsrs[0], jsrs.size(),
- currentBlock);
-
- uint32 index = 0;
- for (std::vector<BasicBlock*>::iterator i = jsrs.begin(),
- e = jsrs.end(); i!= e; ++i, index += 2) {
- inst->addCase(ConstantInt::get(Type::getInt32Ty(*llvmContext), index | 1), *i);
- }
-
- break;
- }
-
- case TABLESWITCH : {
- uint32 tmp = i;
- uint32 reste = (i + 1) & 3;
- uint32 filled = reste ? (4 - reste) : 0;
- i += filled;
- reader.cursor += filled;
- Opinfo& def = opcodeInfos[tmp + reader.readU4()];
- i += 4;
-
- sint32 low = reader.readS4();
- i += 4;
- sint32 high = reader.readS4() + 1;
- i += 4;
-
- Value* index = pop();
-
- const llvm::Type* type = index->getType();
- for (sint32 cur = low; cur < high; ++cur) {
- Value* cmp = new ICmpInst(*currentBlock, ICmpInst::ICMP_EQ,
- ConstantInt::get(type, cur), index, "");
- BasicBlock* falseBlock = createBasicBlock("continue tableswitch");
- Opinfo& info = opcodeInfos[tmp + reader.readU4()];
- i += 4;
- branch(cmp, info.newBlock, falseBlock, currentBlock, info);
- currentBlock = falseBlock;
- }
-
-
- branch(def, currentBlock);
- i = tmp + 12 + filled + ((high - low) << 2);
-
- break;
- }
-
- case LOOKUPSWITCH : {
- uint32 tmp = i;
- uint32 filled = (3 - i) & 3;
- i += filled;
- reader.cursor += filled;
- Opinfo& def = opcodeInfos[tmp + reader.readU4()];
- i += 4;
- uint32 nbs = reader.readU4();
- i += 4;
-
- Value* key = pop();
- for (uint32 cur = 0; cur < nbs; ++cur) {
- Value* val = ConstantInt::get(Type::getInt32Ty(*llvmContext), reader.readU4());
- i += 4;
- Value* cmp = new ICmpInst(*currentBlock, ICmpInst::ICMP_EQ, val, key,
- "");
- BasicBlock* falseBlock = createBasicBlock("continue lookupswitch");
- Opinfo& info = opcodeInfos[tmp + reader.readU4()];
- i += 4;
- branch(cmp, info.newBlock, falseBlock, currentBlock, info);
- currentBlock = falseBlock;
- }
- branch(def, currentBlock);
- i = tmp + 8 + filled + (nbs << 3);
- break;
- }
- case IRETURN : {
- Value* val = pop();
- assert(val->getType()->isIntegerTy());
- convertValue(val, endNode->getType(), currentBlock, false);
- endNode->addIncoming(val, currentBlock);
- BranchInst::Create(endBlock, currentBlock);
- break;
- }
- case LRETURN :
- pop(); // remove the 0 on the stack
- endNode->addIncoming(pop(), currentBlock);
- BranchInst::Create(endBlock, currentBlock);
- break;
-
- case FRETURN :
- endNode->addIncoming(pop(), currentBlock);
- BranchInst::Create(endBlock, currentBlock);
- break;
-
- case DRETURN :
- pop(); // remove the 0 on the stack
- endNode->addIncoming(pop(), currentBlock);
- BranchInst::Create(endBlock, currentBlock);
- break;
-
- case ARETURN :
- endNode->addIncoming(pop(), currentBlock);
- BranchInst::Create(endBlock, currentBlock);
- break;
-
- case RETURN : {
- // Prevent a javac bug.
- if (endNode != 0) {
- endNode->addIncoming(Constant::getNullValue(endNode->getType()),
- currentBlock);
- }
- BranchInst::Create(endBlock, currentBlock);
- break;
- }
-
- case GETSTATIC : {
- uint16 index = reader.readU2();
- i += 2;
- getStaticField(index);
- break;
- }
-
- case PUTSTATIC : {
- uint16 index = reader.readU2();
- i += 2;
- setStaticField(index);
- break;
- }
-
- case GETFIELD : {
- uint16 index = reader.readU2();
- i += 2;
- getVirtualField(index);
- break;
- }
-
- case PUTFIELD : {
- uint16 index = reader.readU2();
- i += 2;
- setVirtualField(index);
- break;
- }
-
- case INVOKEVIRTUAL : {
- uint16 index = reader.readU2();
- i += 2;
- invokeVirtual(index);
- break;
- }
-
- case INVOKESPECIAL : {
- uint16 index = reader.readU2();
- i += 2;
- invokeSpecial(index);
- break;
- }
-
- case INVOKESTATIC : {
- uint16 index = reader.readU2();
- i += 2;
- invokeStatic(index);
- break;
- }
-
- case INVOKEINTERFACE : {
- uint16 index = reader.readU2();
- i += 2;
- invokeInterface(index);
- i += 2;
- break;
- }
-
- case NEW : {
- uint16 index = reader.readU2();
- i += 2;
- invokeNew(index);
- break;
- }
-
- case NEWARRAY :
- case ANEWARRAY : {
-
- Constant* sizeElement = 0;
- Value* TheVT = 0;
- Value* valCl = 0;
- UserClassArray* dcl = 0;
-
- if (bytecode == NEWARRAY) {
- uint8 id = reader.readU1();
- i += 1;
- uint8 charId = arrayType(compilingMethod, id);
-
- dcl = upcalls->getArrayClass(id);
- valCl = TheCompiler->getNativeClass(dcl);
-
- LLVMAssessorInfo& LAI = TheCompiler->AssessorInfo[charId];
- sizeElement = ConstantInt::get(Type::getInt32Ty(*llvmContext),
- LAI.logSizeInBytesConstant);
- if (TheCompiler->isStaticCompiling() &&
- valCl->getType() != intrinsics->JavaClassArrayType) {
- valCl = new LoadInst(valCl, "", currentBlock);
- TheVT = CallInst::Create(intrinsics->GetVTFromClassArrayFunction,
- valCl, "", currentBlock);
- } else {
- TheVT = TheCompiler->getVirtualTable(dcl->virtualVT);
- }
- } else {
- uint16 index = reader.readU2();
- i += 2;
- CommonClass* cl =
- compilingClass->ctpInfo->getMethodClassIfLoaded(index);
-
- if (cl && (!cl->isClass() || cl->asClass()->isResolved())) {
- JnjvmClassLoader* JCL = cl->classLoader;
- const UTF8* arrayName = JCL->constructArrayName(1, cl->name);
-
- dcl = JCL->constructArray(arrayName);
- valCl = TheCompiler->getNativeClass(dcl);
-
- // If we're static compiling and the class is not a class we
- // are compiling, the result of getNativeClass is a pointer to
- // the class. Load it.
- if (TheCompiler->isStaticCompiling() &&
- valCl->getType() != intrinsics->JavaClassArrayType) {
- valCl = new LoadInst(valCl, "", currentBlock);
- TheVT = CallInst::Create(intrinsics->GetVTFromClassArrayFunction,
- valCl, "", currentBlock);
- } else {
- TheVT = TheCompiler->getVirtualTable(dcl->virtualVT);
- }
-
- } else {
- const llvm::Type* Ty =
- PointerType::getUnqual(intrinsics->VTType);
- Value* args[3]= { TheCompiler->getNativeClass(compilingClass),
- ConstantInt::get(Type::getInt32Ty(*llvmContext), index),
- Constant::getNullValue(Ty) };
- TheVT = CallInst::Create(intrinsics->GetArrayClassFunction, args,
- args + 3, "", currentBlock);
- }
-
- sizeElement = intrinsics->constantPtrLogSize;
- }
- Value* arg1 = popAsInt();
-
- if (TheCompiler->hasExceptionsEnabled()) {
- Value* cmp = new ICmpInst(*currentBlock, ICmpInst::ICMP_SLT, arg1,
- intrinsics->constantZero, "");
-
- BasicBlock* BB1 = createBasicBlock("");
- BasicBlock* BB2 = createBasicBlock("");
-
- BranchInst::Create(BB1, BB2, cmp, currentBlock);
- currentBlock = BB1;
- throwException(intrinsics->NegativeArraySizeExceptionFunction, arg1);
- currentBlock = BB2;
-
- cmp = new ICmpInst(*currentBlock, ICmpInst::ICMP_SGT, arg1,
- intrinsics->MaxArraySizeConstant, "");
-
- BB1 = createBasicBlock("");
- BB2 = createBasicBlock("");
-
- BranchInst::Create(BB1, BB2, cmp, currentBlock);
- currentBlock = BB1;
- throwException(intrinsics->OutOfMemoryErrorFunction, arg1);
- currentBlock = BB2;
- }
-
- Value* mult = BinaryOperator::CreateShl(arg1, sizeElement, "",
- currentBlock);
- Value* size =
- BinaryOperator::CreateAdd(intrinsics->JavaArraySizeConstant, mult,
- "", currentBlock);
- TheVT = new BitCastInst(TheVT, intrinsics->ptrType, "", currentBlock);
- Instruction* res = invoke(intrinsics->AllocateFunction, size, TheVT, "",
- currentBlock);
- Value* cast = new BitCastInst(res, intrinsics->JavaArrayType, "",
- currentBlock);
-
- // Set the size
- Value* gep4[2] = { intrinsics->constantZero,
- intrinsics->JavaArraySizeOffsetConstant };
- Value* GEP = GetElementPtrInst::Create(cast, gep4, gep4 + 2,
- "", currentBlock);
-
- arg1 = new IntToPtrInst(arg1, intrinsics->ptrType, "", currentBlock);
- new StoreInst(arg1, GEP, currentBlock);
-
- addHighLevelType(res, dcl ? dcl : upcalls->ArrayOfObject);
- res = new BitCastInst(res, intrinsics->JavaObjectType, "", currentBlock);
- push(res, false, dcl ? dcl : upcalls->ArrayOfObject);
-
- break;
- }
-
- case ARRAYLENGTH : {
- Value* val = pop();
- JITVerifyNull(val);
- push(arraySize(val), false);
- break;
- }
-
- case ATHROW : {
- llvm::Value* arg = pop();
- throwException(arg);
- break;
- }
-
- case CHECKCAST :
- if (!TheCompiler->hasExceptionsEnabled()) {
- i += 2;
- reader.cursor += 2;
- break;
- }
-
- case INSTANCEOF : {
-
- bool checkcast = (bytecode == CHECKCAST);
-
- BasicBlock* exceptionCheckcast = 0;
- BasicBlock* endCheckcast = 0;
-
- uint16 index = reader.readU2();
- i += 2;
- UserCommonClass* cl = 0;
- Value* clVar = getResolvedCommonClass(index, true, &cl);
- Value* obj = top();
- Value* args[2] = { obj, clVar };
- Value* cmp = new ICmpInst(*currentBlock, ICmpInst::ICMP_EQ, obj,
- intrinsics->JavaObjectNullConstant, "");
- BasicBlock* endBlock = createBasicBlock("end type compare");
- PHINode* node = PHINode::Create(Type::getInt1Ty(*llvmContext), "", endBlock);
-
- if (checkcast) {
- exceptionCheckcast = createBasicBlock("false checkcast");
-
-
- endCheckcast = createBasicBlock("null checkcast");
- BasicBlock* ifFalse = createBasicBlock("non null checkcast");
-
- BranchInst::Create(endCheckcast, ifFalse, cmp, currentBlock);
- currentBlock = exceptionCheckcast;
- throwException(intrinsics->ClassCastExceptionFunction, args, 2);
- currentBlock = ifFalse;
- } else {
- BasicBlock* ifFalse = createBasicBlock("false type compare");
- BranchInst::Create(endBlock, ifFalse, cmp, currentBlock);
- node->addIncoming(ConstantInt::getFalse(*llvmContext), currentBlock);
- currentBlock = ifFalse;
- }
-
- Value* TheVT = 0;
- if (!cl || TheCompiler->isStaticCompiling()) {
- TheVT = CallInst::Create(intrinsics->GetVTFromCommonClassFunction,
- clVar, "", currentBlock);
- } else {
- TheVT = TheCompiler->getVirtualTable(cl->virtualVT);
- }
-
-
- Value* objVT = CallInst::Create(intrinsics->GetVTFunction, obj, "",
- currentBlock);
- Value* classArgs[2] = { objVT, TheVT };
-
- Value* res = 0;
- if (cl) {
- if (cl->isSecondaryClass()) {
- res = CallInst::Create(intrinsics->IsSecondaryClassFunction,
- classArgs, classArgs + 2, "",
- currentBlock);
- } else {
- Value* inDisplay = CallInst::Create(intrinsics->GetDisplayFunction,
- objVT, "", currentBlock);
-
- uint32 depth = cl->virtualVT->depth;
- ConstantInt* CI = ConstantInt::get(Type::getInt32Ty(*llvmContext), depth);
- Value* displayArgs[2] = { inDisplay, CI };
- Value* VTInDisplay =
- CallInst::Create(intrinsics->GetVTInDisplayFunction,
- displayArgs, displayArgs + 2, "",
- currentBlock);
-
- res = new ICmpInst(*currentBlock, ICmpInst::ICMP_EQ, VTInDisplay,
- TheVT, "");
- }
- } else {
- res = CallInst::Create(intrinsics->IsAssignableFromFunction,
- classArgs, classArgs + 2, "",
- currentBlock);
- }
-
- node->addIncoming(res, currentBlock);
- BranchInst::Create(endBlock, currentBlock);
- currentBlock = endBlock;
-
- if (checkcast) {
- BranchInst::Create(endCheckcast, exceptionCheckcast, node,
- currentBlock);
- currentBlock = endCheckcast;
- } else {
- pop();
- push(new ZExtInst(node, Type::getInt32Ty(*llvmContext), "", currentBlock),
- false);
- }
-
- break;
- }
-
- case MONITORENTER : {
- Value* obj = pop();
- JITVerifyNull(obj);
- monitorEnter(obj);
- break;
- }
-
- case MONITOREXIT : {
- Value* obj = pop();
- JITVerifyNull(obj);
- monitorExit(obj);
- break;
- }
-
- case MULTIANEWARRAY : {
- uint16 index = reader.readU2();
- i += 2;
- uint8 dim = reader.readU1();
- i += 1;
-
- UserCommonClass* dcl = 0;
- Value* valCl = getResolvedCommonClass(index, true, &dcl);
- Value** args = (Value**)allocator.Allocate(sizeof(Value*) * (dim + 2));
- args[0] = valCl;
- args[1] = ConstantInt::get(Type::getInt32Ty(*llvmContext), dim);
-
- for (int cur = dim + 1; cur >= 2; --cur)
- args[cur] = pop();
-
- std::vector<Value*> Args;
- for (sint32 v = 0; v < dim + 2; ++v) {
- Args.push_back(args[v]);
- }
- push(invoke(intrinsics->MultiCallNewFunction, Args, "", currentBlock),
- false, dcl ? dcl : upcalls->ArrayOfObject);
- break;
- }
-
- case WIDE :
- wide = true;
- break;
-
- case IFNULL : {
- uint32 tmp = i;
- llvm::Value* val = pop();
- Constant* nil = Constant::getNullValue(val->getType());
- llvm::Value* test = new ICmpInst(*currentBlock, ICmpInst::ICMP_EQ, val,
- nil, "");
- BasicBlock* ifFalse = createBasicBlock("true IFNULL");
- Opinfo& ifTrueInfo = opcodeInfos[tmp + reader.readS2()];
- i += 2;
- BasicBlock* ifTrue = ifTrueInfo.newBlock;
- branch(test, ifTrue, ifFalse, currentBlock, ifTrueInfo);
- currentBlock = ifFalse;
- break;
- }
-
- case IFNONNULL : {
- uint32 tmp = i;
- llvm::Value* val = pop();
- Constant* nil = Constant::getNullValue(val->getType());
- llvm::Value* test = new ICmpInst(*currentBlock, ICmpInst::ICMP_NE, val,
- nil, "");
- BasicBlock* ifFalse = createBasicBlock("false IFNONNULL");
- Opinfo& ifTrueInfo = opcodeInfos[tmp + reader.readS2()];
- i += 2;
- BasicBlock* ifTrue = ifTrueInfo.newBlock;
- branch(test, ifTrue, ifFalse, currentBlock, ifTrueInfo);
- currentBlock = ifFalse;
- break;
- }
-
- default : {
- fprintf(stderr, "I haven't verified your class file and it's malformed:"
- " unknown bytecode %d in %s.%s\n!", bytecode,
- UTF8Buffer(compilingClass->name).cString(),
- UTF8Buffer(compilingMethod->name).cString());
- abort();
- }
- }
- }
-}
-
-void JavaJIT::exploreOpcodes(Reader& reader, uint32 codeLength) {
- bool wide = false;
- uint32 start = reader.cursor;
- for(uint32 i = 0; i < codeLength; ++i) {
- reader.cursor = start + i;
- uint8 bytecode = reader.readU1();
- PRINT_DEBUG(JNJVM_COMPILE, 1, COLOR_NORMAL, "\t[at %5d] %-5d ", i,
- bytecode);
- PRINT_DEBUG(JNJVM_COMPILE, 1, LIGHT_BLUE, "exploring ");
- PRINT_DEBUG(JNJVM_COMPILE, 1, LIGHT_CYAN, OpcodeNames[bytecode]);
- PRINT_DEBUG(JNJVM_COMPILE, 1, LIGHT_BLUE, "\n");
-
- switch (bytecode) {
-
- case NOP :
- case ACONST_NULL :
- case ICONST_M1 :
- case ICONST_0 :
- case ICONST_1 :
- case ICONST_2 :
- case ICONST_3 :
- case ICONST_4 :
- case ICONST_5 :
- case LCONST_0 :
- case LCONST_1 :
- case FCONST_0 :
- case FCONST_1 :
- case FCONST_2 :
- case DCONST_0 :
- case DCONST_1 : break;
-
- case BIPUSH : ++i; break;
-
- case SIPUSH : i += 2; break;
-
- case LDC : ++i; break;
-
- case LDC_W :
- case LDC2_W : i += 2; break;
-
- case ILOAD :
- case LLOAD :
- case FLOAD :
- case DLOAD :
- case ALOAD :
- i += WCALC(1, wide);
- break;
-
- case ILOAD_0 :
- case ILOAD_1 :
- case ILOAD_2 :
- case ILOAD_3 :
- case LLOAD_0 :
- case LLOAD_1 :
- case LLOAD_2 :
- case LLOAD_3 :
- case FLOAD_0 :
- case FLOAD_1 :
- case FLOAD_2 :
- case FLOAD_3 :
- case DLOAD_0 :
- case DLOAD_1 :
- case DLOAD_2 :
- case DLOAD_3 :
- case ALOAD_0 :
- case ALOAD_1 :
- case ALOAD_2 :
- case ALOAD_3 :
- case IALOAD :
- case LALOAD :
- case FALOAD :
- case DALOAD :
- case AALOAD :
- case BALOAD :
- case CALOAD :
- case SALOAD : break;
-
- case ISTORE :
- case LSTORE :
- case FSTORE :
- case DSTORE :
- case ASTORE :
- i += WCALC(1, wide);
- break;
-
- case ISTORE_0 :
- case ISTORE_1 :
- case ISTORE_2 :
- case ISTORE_3 :
- case LSTORE_0 :
- case LSTORE_1 :
- case LSTORE_2 :
- case LSTORE_3 :
- case FSTORE_0 :
- case FSTORE_1 :
- case FSTORE_2 :
- case FSTORE_3 :
- case DSTORE_0 :
- case DSTORE_1 :
- case DSTORE_2 :
- case DSTORE_3 :
- case ASTORE_0 :
- case ASTORE_1 :
- case ASTORE_2 :
- case ASTORE_3 :
- case IASTORE :
- case LASTORE :
- case FASTORE :
- case DASTORE :
- case AASTORE :
- case BASTORE :
- case CASTORE :
- case SASTORE :
- case POP :
- case POP2 :
- case DUP :
- case DUP_X1 :
- case DUP_X2 :
- case DUP2 :
- case DUP2_X1 :
- case DUP2_X2 :
- case SWAP :
- case IADD :
- case LADD :
- case FADD :
- case DADD :
- case ISUB :
- case LSUB :
- case FSUB :
- case DSUB :
- case IMUL :
- case LMUL :
- case FMUL :
- case DMUL :
- case IDIV :
- case LDIV :
- case FDIV :
- case DDIV :
- case IREM :
- case LREM :
- case FREM :
- case DREM :
- case INEG :
- case LNEG :
- case FNEG :
- case DNEG :
- case ISHL :
- case LSHL :
- case ISHR :
- case LSHR :
- case IUSHR :
- case LUSHR :
- case IAND :
- case LAND :
- case IOR :
- case LOR :
- case IXOR :
- case LXOR : break;
-
- case IINC :
- i += WCALC(2, wide);
- break;
-
- case I2L :
- case I2F :
- case I2D :
- case L2I :
- case L2F :
- case L2D :
- case F2I :
- case F2L :
- case F2D :
- case D2I :
- case D2L :
- case D2F :
- case I2B :
- case I2C :
- case I2S :
- case LCMP :
- case FCMPL :
- case FCMPG :
- case DCMPL :
- case DCMPG : break;
-
- case IFEQ :
- case IFNE :
- case IFLT :
- case IFGE :
- case IFGT :
- case IFLE :
- case IF_ICMPEQ :
- case IF_ICMPNE :
- case IF_ICMPLT :
- case IF_ICMPGE :
- case IF_ICMPGT :
- case IF_ICMPLE :
- case IF_ACMPEQ :
- case IF_ACMPNE :
- case GOTO : {
- uint32 tmp = i;
- uint16 index = tmp + reader.readU2();
- i += 2;
- if (!(opcodeInfos[index].newBlock))
- opcodeInfos[index].newBlock = createBasicBlock("GOTO or IF*");
- break;
- }
-
- case JSR : {
- uint32 tmp = i;
- uint16 index = tmp + reader.readU2();
- i += 2;
- if (!(opcodeInfos[index].newBlock)) {
- BasicBlock* block = createBasicBlock("JSR");
- opcodeInfos[index].newBlock = block;
- }
- if (!(opcodeInfos[tmp + 3].newBlock)) {
- BasicBlock* block = createBasicBlock("JSR2");
- jsrs.push_back(block);
- opcodeInfos[tmp + 3].newBlock = block;
- } else {
- jsrs.push_back(opcodeInfos[tmp + 3].newBlock);
- }
- break;
- }
-
- case RET : ++i; break;
-
- case TABLESWITCH : {
- uint32 tmp = i;
- uint32 reste = (i + 1) & 3;
- uint32 filled = reste ? (4 - reste) : 0;
- i += filled;
- reader.cursor += filled;
- uint32 index = tmp + reader.readU4();
- i += 4;
- if (!(opcodeInfos[index].newBlock)) {
- BasicBlock* block = createBasicBlock("tableswitch");
- opcodeInfos[index].newBlock = block;
- }
- uint32 low = reader.readU4();
- i += 4;
- uint32 high = reader.readU4() + 1;
- i += 4;
- uint32 depl = high - low;
- for (uint32 cur = 0; cur < depl; ++cur) {
- uint32 index2 = tmp + reader.readU4();
- i += 4;
- if (!(opcodeInfos[index2].newBlock)) {
- BasicBlock* block = createBasicBlock("tableswitch");
- opcodeInfos[index2].newBlock = block;
- }
- }
- i = tmp + 12 + filled + (depl << 2);
- break;
- }
-
- case LOOKUPSWITCH : {
- uint32 tmp = i;
- uint32 filled = (3 - i) & 3;
- i += filled;
- reader.cursor += filled;
- uint32 index = tmp + reader.readU4();
- i += 4;
- if (!(opcodeInfos[index].newBlock)) {
- BasicBlock* block = createBasicBlock("tableswitch");
- opcodeInfos[index].newBlock = block;
- }
- uint32 nbs = reader.readU4();
- i += 4;
- for (uint32 cur = 0; cur < nbs; ++cur) {
- i += 4;
- reader.cursor += 4;
- uint32 index2 = tmp + reader.readU4();
- i += 4;
- if (!(opcodeInfos[index2].newBlock)) {
- BasicBlock* block = createBasicBlock("tableswitch");
- opcodeInfos[index2].newBlock = block;
- }
- }
-
- i = tmp + 8 + filled + (nbs << 3);
- break;
- }
-
- case IRETURN :
- case LRETURN :
- case FRETURN :
- case DRETURN :
- case ARETURN :
- case RETURN : break;
-
- case GETSTATIC :
- case PUTSTATIC :
- case GETFIELD :
- case PUTFIELD :
- case INVOKEVIRTUAL :
- case INVOKESPECIAL :
- case INVOKESTATIC :
- i += 2;
- break;
-
- case INVOKEINTERFACE :
- i += 4;
- break;
-
- case NEW :
- i += 2;
- break;
-
- case NEWARRAY :
- ++i;
- break;
-
- case ANEWARRAY :
- i += 2;
- break;
-
- case ARRAYLENGTH :
- case ATHROW : break;
-
- case CHECKCAST :
- i += 2;
- break;
-
- case INSTANCEOF :
- i += 2;
- break;
-
- case MONITORENTER :
- break;
-
- case MONITOREXIT :
- break;
-
- case MULTIANEWARRAY :
- i += 3;
- break;
-
- case WIDE :
- wide = true;
- break;
-
- case IFNULL :
- case IFNONNULL : {
- uint32 tmp = i;
- uint16 index = tmp + reader.readU2();
- i += 2;
- if (!(opcodeInfos[index].newBlock))
- opcodeInfos[index].newBlock = createBasicBlock("true IF*NULL");
- break;
- }
-
-
- default : {
- fprintf(stderr, "I haven't verified your class file and it's malformed:"
- " unknown bytecode %d in %s.%s!\n", bytecode,
- UTF8Buffer(compilingClass->name).cString(),
- UTF8Buffer(compilingMethod->name).cString());
- abort();
- }
- }
- }
-}
diff --git a/vmkit/lib/J3/Compiler/JavaLLVMCompiler.cpp b/vmkit/lib/J3/Compiler/JavaLLVMCompiler.cpp
deleted file mode 100644
index 0729f00..0000000
--- a/vmkit/lib/J3/Compiler/JavaLLVMCompiler.cpp
+++ /dev/null
@@ -1,137 +0,0 @@
-//===-------- JavaLLVMCompiler.cpp - A LLVM Compiler for J3 ---------------===//
-//
-// The VMKit project
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#include "llvm/LLVMContext.h"
-#include "llvm/Module.h"
-#include "llvm/PassManager.h"
-#include "llvm/Analysis/LoopPass.h"
-#include "llvm/Target/TargetData.h"
-
-#include "mvm/JIT.h"
-
-#include "JavaClass.h"
-#include "JavaJIT.h"
-
-#include "j3/JavaLLVMCompiler.h"
-
-using namespace j3;
-using namespace llvm;
-
-JavaLLVMCompiler::JavaLLVMCompiler(const std::string& str) :
- TheModule(new llvm::Module(str, *(new LLVMContext()))),
- DebugFactory(new DIFactory(*TheModule)),
- JavaIntrinsics(TheModule) {
-
- enabledException = true;
-#ifdef WITH_LLVM_GCC
- cooperativeGC = true;
-#else
- cooperativeGC = false;
-#endif
- initialiseAssessorInfo();
-}
-
-void JavaLLVMCompiler::resolveVirtualClass(Class* cl) {
- // Lock here because we may be called by a class resolver
- mvm::MvmModule::protectIR();
- LLVMClassInfo* LCI = (LLVMClassInfo*)getClassInfo(cl);
- LCI->getVirtualType();
- mvm::MvmModule::unprotectIR();
-}
-
-void JavaLLVMCompiler::resolveStaticClass(Class* cl) {
- // Lock here because we may be called by a class initializer
- mvm::MvmModule::protectIR();
- LLVMClassInfo* LCI = (LLVMClassInfo*)getClassInfo(cl);
- LCI->getStaticType();
- mvm::MvmModule::unprotectIR();
-}
-
-Function* JavaLLVMCompiler::getMethod(JavaMethod* meth) {
- return getMethodInfo(meth)->getMethod();
-}
-
-Function* JavaLLVMCompiler::parseFunction(JavaMethod* meth) {
- LLVMMethodInfo* LMI = getMethodInfo(meth);
- Function* func = LMI->getMethod();
-
- // We are jitting. Take the lock.
- mvm::MvmModule::protectIR();
- if (func->getLinkage() == GlobalValue::ExternalWeakLinkage) {
- JavaJIT jit(this, meth, func);
- if (isNative(meth->access)) {
- jit.nativeCompile();
- mvm::MvmModule::runPasses(func, JavaNativeFunctionPasses);
- } else {
- jit.javaCompile();
- mvm::MvmModule::runPasses(func, JavaFunctionPasses);
- }
- func->setLinkage(GlobalValue::ExternalLinkage);
- }
- mvm::MvmModule::unprotectIR();
-
- return func;
-}
-
-JavaMethod* JavaLLVMCompiler::getJavaMethod(const llvm::Function& F) {
- function_iterator E = functions.end();
- function_iterator I = functions.find(&F);
- if (I == E) return 0;
- return I->second;
-}
-
-MDNode* JavaLLVMCompiler::GetDbgSubprogram(JavaMethod* meth) {
- if (getMethodInfo(meth)->getDbgSubprogram() == NULL) {
- MDNode* node = DebugFactory->CreateSubprogram(DIDescriptor(), "", "",
- "", DIFile(), 0,
- DIType(), false,
- false);
- DbgInfos.insert(std::make_pair(node, meth));
- getMethodInfo(meth)->setDbgSubprogram(node);
- }
- return getMethodInfo(meth)->getDbgSubprogram();
-}
-
-JavaLLVMCompiler::~JavaLLVMCompiler() {
- LLVMContext* Context = &(TheModule->getContext());
- delete TheModule;
- delete DebugFactory;
- delete JavaFunctionPasses;
- delete JavaNativeFunctionPasses;
- delete Context;
-}
-
-namespace mvm {
- llvm::FunctionPass* createEscapeAnalysisPass();
- llvm::LoopPass* createLoopSafePointsPass();
-}
-
-namespace j3 {
- llvm::FunctionPass* createLowerConstantCallsPass(JavaLLVMCompiler* I);
-}
-
-void JavaLLVMCompiler::addJavaPasses() {
- JavaNativeFunctionPasses = new FunctionPassManager(TheModule);
- JavaNativeFunctionPasses->add(new TargetData(TheModule));
- // Lower constant calls to lower things like getClass used
- // on synchronized methods.
- JavaNativeFunctionPasses->add(createLowerConstantCallsPass(this));
-
- JavaFunctionPasses = new FunctionPassManager(TheModule);
- if (cooperativeGC)
- JavaFunctionPasses->add(mvm::createLoopSafePointsPass());
- // Add other passes after the loop pass, because safepoints may move objects.
- // Moving objects disable many optimizations.
- mvm::MvmModule::addCommandLinePasses(JavaFunctionPasses);
-
- // Re-enable this when the pointers in stack-allocated objects can
- // be given to the GC.
- //JavaFunctionPasses->add(mvm::createEscapeAnalysisPass());
- JavaFunctionPasses->add(createLowerConstantCallsPass(this));
-}
diff --git a/vmkit/lib/J3/Compiler/LLVMInfo.cpp b/vmkit/lib/J3/Compiler/LLVMInfo.cpp
deleted file mode 100644
index 311d8b1..0000000
--- a/vmkit/lib/J3/Compiler/LLVMInfo.cpp
+++ /dev/null
@@ -1,765 +0,0 @@
-//===--- LLVMInfo.cpp - Implementation of LLVM info objects for J3---------===//
-//
-// The VMKit project
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#include "llvm/BasicBlock.h"
-#include "llvm/CallingConv.h"
-#include "llvm/Constants.h"
-#include "llvm/Instructions.h"
-#include "llvm/Module.h"
-#include "llvm/Support/CommandLine.h"
-#include "llvm/Support/MutexGuard.h"
-#include "llvm/Target/TargetData.h"
-
-#include "mvm/GC.h"
-#include "mvm/JIT.h"
-
-#include "JavaConstantPool.h"
-#include "JavaString.h"
-#include "JavaThread.h"
-#include "JavaTypes.h"
-#include "JavaUpcalls.h"
-#include "Jnjvm.h"
-#include "Reader.h"
-
-#include "j3/JavaLLVMCompiler.h"
-#include "j3/LLVMInfo.h"
-
-#include <cstdio>
-
-using namespace j3;
-using namespace llvm;
-
-const Type* LLVMClassInfo::getVirtualType() {
- if (!virtualType) {
- std::vector<const llvm::Type*> fields;
- const TargetData* targetData = mvm::MvmModule::TheTargetData;
- const StructLayout* sl = 0;
- const StructType* structType = 0;
- LLVMContext& context = Compiler->getLLVMModule()->getContext();
-
- if (classDef->super) {
- LLVMClassInfo* CLI = Compiler->getClassInfo(classDef->super);
- const llvm::Type* Ty = CLI->getVirtualType()->getContainedType(0);
- fields.push_back(Ty);
-
- for (uint32 i = 0; i < classDef->nbVirtualFields; ++i) {
- JavaField& field = classDef->virtualFields[i];
- Typedef* type = field.getSignature();
- LLVMAssessorInfo& LAI = Compiler->getTypedefInfo(type);
- fields.push_back(LAI.llvmType);
- }
-
-
- structType = StructType::get(context, fields, false);
- virtualType = PointerType::getUnqual(structType);
- sl = targetData->getStructLayout(structType);
-
- } else {
- virtualType = Compiler->getIntrinsics()->JavaObjectType;
- assert(virtualType && "intrinsics not initalized");
- structType = dyn_cast<const StructType>(virtualType->getContainedType(0));
- sl = targetData->getStructLayout(structType);
-
- }
-
- uint64 size = mvm::MvmModule::getTypeSize(structType);
- virtualSizeConstant = ConstantInt::get(Type::getInt32Ty(context), size);
-
- // TODO: put that elsewhere.
- if (Compiler == classDef->classLoader->getCompiler()) {
- for (uint32 i = 0; i < classDef->nbVirtualFields; ++i) {
- JavaField& field = classDef->virtualFields[i];
- field.ptrOffset = sl->getElementOffset(i + 1);
- field.num = i + 1;
- }
-
- classDef->virtualSize = (uint32)size;
- classDef->alignment = sl->getAlignment();
-
- Compiler->makeVT(classDef);
- Compiler->makeIMT(classDef);
- }
- }
-
- return virtualType;
-}
-
-const Type* LLVMClassInfo::getStaticType() {
-
- if (!staticType) {
- Class* cl = (Class*)classDef;
- std::vector<const llvm::Type*> fields;
-
- LLVMContext& context = Compiler->getLLVMModule()->getContext();
-
- for (uint32 i = 0; i < classDef->nbStaticFields; ++i) {
- JavaField& field = classDef->staticFields[i];
- Typedef* type = field.getSignature();
- LLVMAssessorInfo& LAI = Compiler->getTypedefInfo(type);
- fields.push_back(LAI.llvmType);
- }
-
- StructType* structType = StructType::get(context, fields, false);
- staticType = PointerType::getUnqual(structType);
- const TargetData* targetData = mvm::MvmModule::TheTargetData;
- const StructLayout* sl = targetData->getStructLayout(structType);
-
- // TODO: put that elsewhere.
- if (Compiler == classDef->classLoader->getCompiler()) {
- for (uint32 i = 0; i < classDef->nbStaticFields; ++i) {
- JavaField& field = classDef->staticFields[i];
- field.num = i;
- field.ptrOffset = sl->getElementOffset(i);
- }
-
- uint64 size = mvm::MvmModule::getTypeSize(structType);
- cl->staticSize = size;
- }
- }
- return staticType;
-}
-
-
-Value* LLVMClassInfo::getVirtualSize() {
- if (!virtualSizeConstant) {
- getVirtualType();
- assert(virtualSizeConstant && "No size for a class?");
- }
- return virtualSizeConstant;
-}
-
-extern llvm::cl::opt<bool> EmitDebugInfo;
-
-Function* LLVMMethodInfo::getMethod() {
- if (!methodFunction) {
- mvm::ThreadAllocator allocator;
- JnjvmClassLoader* JCL = methodDef->classDef->classLoader;
- if (Compiler->emitFunctionName() || EmitDebugInfo) {
- const UTF8* jniConsClName = methodDef->classDef->name;
- const UTF8* jniConsName = methodDef->name;
- const UTF8* jniConsType = methodDef->type;
- sint32 clen = jniConsClName->size;
- sint32 mnlen = jniConsName->size;
- sint32 mtlen = jniConsType->size;
-
- char* buf = (char*)allocator.Allocate(
- 3 + JNI_NAME_PRE_LEN + 1 + ((mnlen + clen + mtlen) << 3));
-
- bool j3 = false;
- if (isNative(methodDef->access)) {
- // Verify if it's defined by JnJVM
- JCL->nativeLookup(methodDef, j3, buf);
- }
-
- methodDef->jniConsFromMethOverloaded(buf + 1);
- memcpy(buf, "JnJVM", 5);
-
- methodFunction = Function::Create(getFunctionType(),
- GlobalValue::ExternalWeakLinkage, buf,
- Compiler->getLLVMModule());
- } else {
- methodFunction = Function::Create(getFunctionType(),
- GlobalValue::ExternalWeakLinkage,
- "", Compiler->getLLVMModule());
- }
-
- methodFunction->setGC("vmkit");
-
- Compiler->functions.insert(std::make_pair(methodFunction, methodDef));
- if (Compiler != JCL->getCompiler() && methodDef->code) {
- Compiler->setMethod(methodFunction, methodDef->code, methodFunction->getName().data());
- }
- }
- return methodFunction;
-}
-
-const FunctionType* LLVMMethodInfo::getFunctionType() {
- if (!functionType) {
- Signdef* sign = methodDef->getSignature();
- LLVMSignatureInfo* LSI = Compiler->getSignatureInfo(sign);
- assert(LSI);
- if (isStatic(methodDef->access)) {
- functionType = LSI->getStaticType();
- } else {
- functionType = LSI->getVirtualType();
- }
- }
- return functionType;
-}
-
-Constant* LLVMMethodInfo::getOffset() {
- if (!offsetConstant) {
- LLVMContext& context = Compiler->getLLVMModule()->getContext();
-
- Compiler->resolveVirtualClass(methodDef->classDef);
- offsetConstant = ConstantInt::get(Type::getInt32Ty(context),
- methodDef->offset);
- }
- return offsetConstant;
-}
-
-Constant* LLVMFieldInfo::getOffset() {
- if (!offsetConstant) {
- LLVMContext& context = Compiler->getLLVMModule()->getContext();
-
- if (isStatic(fieldDef->access)) {
- Compiler->resolveStaticClass(fieldDef->classDef);
- } else {
- Compiler->resolveVirtualClass(fieldDef->classDef);
- }
-
- offsetConstant = ConstantInt::get(Type::getInt32Ty(context), fieldDef->num);
- }
- return offsetConstant;
-}
-
-const llvm::FunctionType* LLVMSignatureInfo::getVirtualType() {
- if (!virtualType) {
- // Lock here because we are called by arbitrary code
- mvm::MvmModule::protectIR();
- std::vector<const llvm::Type*> llvmArgs;
- uint32 size = signature->nbArguments;
- Typedef* const* arguments = signature->getArgumentsType();
-
- llvmArgs.push_back(Compiler->getIntrinsics()->JavaObjectType);
-
- for (uint32 i = 0; i < size; ++i) {
- Typedef* type = arguments[i];
- LLVMAssessorInfo& LAI = Compiler->getTypedefInfo(type);
- llvmArgs.push_back(LAI.llvmType);
- }
-
- LLVMAssessorInfo& LAI =
- Compiler->getTypedefInfo(signature->getReturnType());
- virtualType = FunctionType::get(LAI.llvmType, llvmArgs, false);
- mvm::MvmModule::unprotectIR();
- }
- return virtualType;
-}
-
-const llvm::FunctionType* LLVMSignatureInfo::getStaticType() {
- if (!staticType) {
- // Lock here because we are called by arbitrary code
- mvm::MvmModule::protectIR();
- std::vector<const llvm::Type*> llvmArgs;
- uint32 size = signature->nbArguments;
- Typedef* const* arguments = signature->getArgumentsType();
-
- for (uint32 i = 0; i < size; ++i) {
- Typedef* type = arguments[i];
- LLVMAssessorInfo& LAI = Compiler->getTypedefInfo(type);
- llvmArgs.push_back(LAI.llvmType);
- }
-
- LLVMAssessorInfo& LAI =
- Compiler->getTypedefInfo(signature->getReturnType());
- staticType = FunctionType::get(LAI.llvmType, llvmArgs, false);
- mvm::MvmModule::unprotectIR();
- }
- return staticType;
-}
-
-const llvm::FunctionType* LLVMSignatureInfo::getNativeType() {
- if (!nativeType) {
- // Lock here because we are called by arbitrary code
- mvm::MvmModule::protectIR();
- std::vector<const llvm::Type*> llvmArgs;
- uint32 size = signature->nbArguments;
- Typedef* const* arguments = signature->getArgumentsType();
-
- const llvm::Type* Ty =
- PointerType::getUnqual(Compiler->getIntrinsics()->JavaObjectType);
-
- llvmArgs.push_back(Compiler->getIntrinsics()->ptrType);
- llvmArgs.push_back(Ty); // Class
-
- for (uint32 i = 0; i < size; ++i) {
- Typedef* type = arguments[i];
- LLVMAssessorInfo& LAI = Compiler->getTypedefInfo(type);
- const llvm::Type* Ty = LAI.llvmType;
- if (Ty == Compiler->getIntrinsics()->JavaObjectType) {
- llvmArgs.push_back(LAI.llvmTypePtr);
- } else {
- llvmArgs.push_back(LAI.llvmType);
- }
- }
-
- LLVMAssessorInfo& LAI =
- Compiler->getTypedefInfo(signature->getReturnType());
- const llvm::Type* RetType =
- LAI.llvmType == Compiler->getIntrinsics()->JavaObjectType ?
- LAI.llvmTypePtr : LAI.llvmType;
- nativeType = FunctionType::get(RetType, llvmArgs, false);
- mvm::MvmModule::unprotectIR();
- }
- return nativeType;
-}
-
-
-Function* LLVMSignatureInfo::createFunctionCallBuf(bool virt) {
-
- std::vector<Value*> Args;
-
- LLVMContext& context = Compiler->getLLVMModule()->getContext();
- J3Intrinsics& Intrinsics = *Compiler->getIntrinsics();
- Function* res = 0;
- if (Compiler->isStaticCompiling()) {
- mvm::ThreadAllocator allocator;
- const char* type = virt ? "virtual_buf" : "static_buf";
- char* buf = (char*)allocator.Allocate(
- (signature->keyName->size << 1) + 1 + 11);
- signature->nativeName(buf, type);
- res = Function::Create(virt ? getVirtualBufType() : getStaticBufType(),
- GlobalValue::ExternalLinkage, buf,
- Compiler->getLLVMModule());
-
-
- } else {
- res = Function::Create(virt ? getVirtualBufType() : getStaticBufType(),
- GlobalValue::ExternalLinkage, "",
- Compiler->getLLVMModule());
- }
-
- BasicBlock* currentBlock = BasicBlock::Create(context, "enter", res);
- Function::arg_iterator i = res->arg_begin();
- Value *obj, *ptr, *func;
-
- ++i;
- func = i;
- ++i;
- if (virt) {
- obj = i;
- ++i;
- Args.push_back(obj);
- }
- ptr = i;
-
- Typedef* const* arguments = signature->getArgumentsType();
- for (uint32 i = 0; i < signature->nbArguments; ++i) {
-
- LLVMAssessorInfo& LAI = Compiler->getTypedefInfo(arguments[i]);
- Value* arg = new LoadInst(ptr, "", currentBlock);
-
- if (arguments[i]->isReference()) {
- arg = new IntToPtrInst(arg, Intrinsics.JavaObjectType, "", currentBlock);
- Value* cmp = new ICmpInst(*currentBlock, ICmpInst::ICMP_EQ,
- Intrinsics.JavaObjectNullConstant,
- arg, "");
- BasicBlock* endBlock = BasicBlock::Create(context, "end", res);
- BasicBlock* loadBlock = BasicBlock::Create(context, "load", res);
- PHINode* node = PHINode::Create(Intrinsics.JavaObjectType, "",
- endBlock);
- node->addIncoming(Intrinsics.JavaObjectNullConstant, currentBlock);
- BranchInst::Create(endBlock, loadBlock, cmp, currentBlock);
- currentBlock = loadBlock;
- arg = new BitCastInst(arg,
- PointerType::getUnqual(Intrinsics.JavaObjectType),
- "", currentBlock);
- arg = new LoadInst(arg, "", false, currentBlock);
- node->addIncoming(arg, currentBlock);
- BranchInst::Create(endBlock, currentBlock);
- currentBlock = endBlock;
- arg = node;
- } else if (arguments[i]->isFloat()) {
- arg = new TruncInst(arg, Compiler->AssessorInfo[I_INT].llvmType,
- "", currentBlock);
- arg = new BitCastInst(arg, LAI.llvmType, "", currentBlock);
- } else if (arguments[i]->isDouble()) {
- arg = new BitCastInst(arg, LAI.llvmType, "", currentBlock);
- } else if (!arguments[i]->isLong()){
- arg = new TruncInst(arg, LAI.llvmType, "", currentBlock);
- }
- Args.push_back(arg);
- ptr = GetElementPtrInst::Create(ptr, Intrinsics.constantOne,"",
- currentBlock);
- }
-
- Value* val = CallInst::Create(func, Args.begin(), Args.end(), "",
- currentBlock);
- if (!signature->getReturnType()->isVoid()) {
- ReturnInst::Create(context, val, currentBlock);
- } else {
- ReturnInst::Create(context, currentBlock);
- }
-
- res->setGC("vmkit");
-
- return res;
-}
-
-Function* LLVMSignatureInfo::createFunctionCallAP(bool virt) {
-
- std::vector<Value*> Args;
-
- J3Intrinsics& Intrinsics = *Compiler->getIntrinsics();
- std::string name;
- if (Compiler->isStaticCompiling()) {
- name += UTF8Buffer(signature->keyName).cString();
- name += virt ? "virtual_ap" : "static_ap";
- } else {
- name = "";
- }
-
- Function* res = Function::Create(virt ? getVirtualBufType() :
- getStaticBufType(),
- GlobalValue::InternalLinkage, name,
- Compiler->getLLVMModule());
- LLVMContext& context = Compiler->getLLVMModule()->getContext();
-
- BasicBlock* currentBlock = BasicBlock::Create(context, "enter", res);
- Function::arg_iterator i = res->arg_begin();
- Value *obj, *ap, *func;
-
- ++i;
- func = i;
- ++i;
- if (virt) {
- obj = i;
- Args.push_back(obj);
- ++i;
- }
- ap = i;
-
- Typedef* const* arguments = signature->getArgumentsType();
- for (uint32 i = 0; i < signature->nbArguments; ++i) {
- LLVMAssessorInfo& LAI = Compiler->getTypedefInfo(arguments[i]);
- Value* arg = new VAArgInst(ap, LAI.llvmType, "", currentBlock);
- if (arguments[i]->isReference()) {
- arg = new IntToPtrInst(arg, Intrinsics.JavaObjectType, "", currentBlock);
- Value* cmp = new ICmpInst(*currentBlock, ICmpInst::ICMP_EQ,
- Intrinsics.JavaObjectNullConstant,
- arg, "");
- BasicBlock* endBlock = BasicBlock::Create(context, "end", res);
- BasicBlock* loadBlock = BasicBlock::Create(context, "load", res);
- PHINode* node = PHINode::Create(Intrinsics.JavaObjectType, "",
- endBlock);
- node->addIncoming(Intrinsics.JavaObjectNullConstant, currentBlock);
- BranchInst::Create(endBlock, loadBlock, cmp, currentBlock);
- currentBlock = loadBlock;
- arg = new BitCastInst(arg,
- PointerType::getUnqual(Intrinsics.JavaObjectType),
- "", currentBlock);
- arg = new LoadInst(arg, "", false, currentBlock);
- node->addIncoming(arg, currentBlock);
- BranchInst::Create(endBlock, currentBlock);
- currentBlock = endBlock;
- arg = node;
- }
- Args.push_back(arg);
- }
-
- Value* val = CallInst::Create(func, Args.begin(), Args.end(), "",
- currentBlock);
- if (!signature->getReturnType()->isVoid()) {
- ReturnInst::Create(context, val, currentBlock);
- } else {
- ReturnInst::Create(context, currentBlock);
- }
-
- res->setGC("vmkit");
-
- return res;
-}
-
-Function* LLVMSignatureInfo::createFunctionStub(bool special, bool virt) {
-
- std::vector<Value*> Args;
- std::vector<Value*> FunctionArgs;
- std::vector<Value*> TempArgs;
-
- J3Intrinsics& Intrinsics = *Compiler->getIntrinsics();
- std::string name;
- if (Compiler->isStaticCompiling()) {
- name += UTF8Buffer(signature->keyName).cString();
- name += virt ? "virtual_stub" : special ? "special_stub" : "static_stub";
- } else {
- name = "";
- }
-
- Function* stub = Function::Create((virt || special) ? getVirtualType() :
- getStaticType(),
- GlobalValue::InternalLinkage, name,
- Compiler->getLLVMModule());
- LLVMContext& context = Compiler->getLLVMModule()->getContext();
-
- BasicBlock* currentBlock = BasicBlock::Create(context, "enter", stub);
- BasicBlock* endBlock = BasicBlock::Create(context, "end", stub);
- BasicBlock* callBlock = BasicBlock::Create(context, "call", stub);
- PHINode* node = NULL;
- if (!signature->getReturnType()->isVoid()) {
- node = PHINode::Create(stub->getReturnType(), "", endBlock);
- }
-
-
- for (Function::arg_iterator arg = stub->arg_begin();
- arg != stub->arg_end(); ++arg) {
- Value* temp = arg;
- if (Compiler->useCooperativeGC() &&
- arg->getType() == Intrinsics.JavaObjectType) {
- temp = new AllocaInst(Intrinsics.JavaObjectType, "", currentBlock);
- new StoreInst(arg, temp, "", currentBlock);
- Value* GCArgs[2] = {
- new BitCastInst(temp, Intrinsics.ptrPtrType, "", currentBlock),
- Intrinsics.constantPtrNull
- };
-
- CallInst::Create(Intrinsics.llvm_gc_gcroot, GCArgs, GCArgs + 2, "",
- currentBlock);
- }
-
- TempArgs.push_back(temp);
- }
-
- if (virt) {
- if (Compiler->useCooperativeGC()) {
- Args.push_back(new LoadInst(TempArgs[0], "", false, currentBlock));
- } else {
- Args.push_back(TempArgs[0]);
- }
- }
-
- Value* val = CallInst::Create(virt ? Intrinsics.ResolveVirtualStubFunction :
- special ? Intrinsics.ResolveSpecialStubFunction:
- Intrinsics.ResolveStaticStubFunction,
- Args.begin(), Args.end(), "", currentBlock);
-
- Constant* nullValue = Constant::getNullValue(val->getType());
- Value* cmp = new ICmpInst(*currentBlock, ICmpInst::ICMP_EQ,
- nullValue, val, "");
- BranchInst::Create(endBlock, callBlock, cmp, currentBlock);
- if (node) node->addIncoming(Constant::getNullValue(node->getType()),
- currentBlock);
-
- currentBlock = callBlock;
- Value* Func = new BitCastInst(val, stub->getType(), "", currentBlock);
-
- int i = 0;
- for (Function::arg_iterator arg = stub->arg_begin();
- arg != stub->arg_end(); ++arg, ++i) {
- Value* temp = arg;
- if (Compiler->useCooperativeGC() &&
- arg->getType() == Intrinsics.JavaObjectType) {
- temp = new LoadInst(TempArgs[i], "", false, currentBlock);
- }
- FunctionArgs.push_back(temp);
- }
- Value* res = CallInst::Create(Func, FunctionArgs.begin(), FunctionArgs.end(),
- "", currentBlock);
- if (node) node->addIncoming(res, currentBlock);
- BranchInst::Create(endBlock, currentBlock);
-
- currentBlock = endBlock;
- if (node) {
- ReturnInst::Create(context, node, currentBlock);
- } else {
- ReturnInst::Create(context, currentBlock);
- }
-
- stub->setGC("vmkit");
-
- return stub;
-}
-
-const PointerType* LLVMSignatureInfo::getStaticPtrType() {
- if (!staticPtrType) {
- staticPtrType = PointerType::getUnqual(getStaticType());
- }
- return staticPtrType;
-}
-
-const PointerType* LLVMSignatureInfo::getVirtualPtrType() {
- if (!virtualPtrType) {
- virtualPtrType = PointerType::getUnqual(getVirtualType());
- }
- return virtualPtrType;
-}
-
-const PointerType* LLVMSignatureInfo::getNativePtrType() {
- if (!nativePtrType) {
- nativePtrType = PointerType::getUnqual(getNativeType());
- }
- return nativePtrType;
-}
-
-
-const FunctionType* LLVMSignatureInfo::getVirtualBufType() {
- if (!virtualBufType) {
- // Lock here because we are called by arbitrary code
- mvm::MvmModule::protectIR();
- std::vector<const llvm::Type*> Args;
- Args.push_back(Compiler->getIntrinsics()->ConstantPoolType); // ctp
- Args.push_back(getVirtualPtrType());
- Args.push_back(Compiler->getIntrinsics()->JavaObjectType);
- Args.push_back(Compiler->AssessorInfo[I_LONG].llvmTypePtr);
- LLVMAssessorInfo& LAI =
- Compiler->getTypedefInfo(signature->getReturnType());
- virtualBufType = FunctionType::get(LAI.llvmType, Args, false);
- mvm::MvmModule::unprotectIR();
- }
- return virtualBufType;
-}
-
-const FunctionType* LLVMSignatureInfo::getStaticBufType() {
- if (!staticBufType) {
- // Lock here because we are called by arbitrary code
- mvm::MvmModule::protectIR();
- std::vector<const llvm::Type*> Args;
- Args.push_back(Compiler->getIntrinsics()->ConstantPoolType); // ctp
- Args.push_back(getStaticPtrType());
- Args.push_back(Compiler->AssessorInfo[I_LONG].llvmTypePtr);
- LLVMAssessorInfo& LAI =
- Compiler->getTypedefInfo(signature->getReturnType());
- staticBufType = FunctionType::get(LAI.llvmType, Args, false);
- mvm::MvmModule::unprotectIR();
- }
- return staticBufType;
-}
-
-Function* LLVMSignatureInfo::getVirtualBuf() {
- // Lock here because we are called by arbitrary code. Also put that here
- // because we are waiting on virtualBufFunction to have an address.
- mvm::MvmModule::protectIR();
- if (!virtualBufFunction) {
- virtualBufFunction = createFunctionCallBuf(true);
- signature->setVirtualCallBuf(Compiler->GenerateStub(virtualBufFunction));
- }
- mvm::MvmModule::unprotectIR();
- return virtualBufFunction;
-}
-
-Function* LLVMSignatureInfo::getVirtualAP() {
- // Lock here because we are called by arbitrary code. Also put that here
- // because we are waiting on virtualAPFunction to have an address.
- mvm::MvmModule::protectIR();
- if (!virtualAPFunction) {
- virtualAPFunction = createFunctionCallAP(true);
- signature->setVirtualCallAP(Compiler->GenerateStub(virtualAPFunction));
- }
- mvm::MvmModule::unprotectIR();
- return virtualAPFunction;
-}
-
-Function* LLVMSignatureInfo::getStaticBuf() {
- // Lock here because we are called by arbitrary code. Also put that here
- // because we are waiting on staticBufFunction to have an address.
- mvm::MvmModule::protectIR();
- if (!staticBufFunction) {
- staticBufFunction = createFunctionCallBuf(false);
- signature->setStaticCallBuf(Compiler->GenerateStub(staticBufFunction));
- }
- mvm::MvmModule::unprotectIR();
- return staticBufFunction;
-}
-
-Function* LLVMSignatureInfo::getStaticAP() {
- // Lock here because we are called by arbitrary code. Also put that here
- // because we are waiting on staticAPFunction to have an address.
- mvm::MvmModule::protectIR();
- if (!staticAPFunction) {
- staticAPFunction = createFunctionCallAP(false);
- signature->setStaticCallAP(Compiler->GenerateStub(staticAPFunction));
- }
- mvm::MvmModule::unprotectIR();
- return staticAPFunction;
-}
-
-Function* LLVMSignatureInfo::getStaticStub() {
- // Lock here because we are called by arbitrary code. Also put that here
- // because we are waiting on staticStubFunction to have an address.
- mvm::MvmModule::protectIR();
- if (!staticStubFunction) {
- staticStubFunction = createFunctionStub(false, false);
- signature->setStaticCallStub(Compiler->GenerateStub(staticStubFunction));
- }
- mvm::MvmModule::unprotectIR();
- return staticStubFunction;
-}
-
-Function* LLVMSignatureInfo::getSpecialStub() {
- // Lock here because we are called by arbitrary code. Also put that here
- // because we are waiting on specialStubFunction to have an address.
- mvm::MvmModule::protectIR();
- if (!specialStubFunction) {
- specialStubFunction = createFunctionStub(true, false);
- signature->setSpecialCallStub(Compiler->GenerateStub(specialStubFunction));
- }
- mvm::MvmModule::unprotectIR();
- return specialStubFunction;
-}
-
-Function* LLVMSignatureInfo::getVirtualStub() {
- // Lock here because we are called by arbitrary code. Also put that here
- // because we are waiting on virtualStubFunction to have an address.
- mvm::MvmModule::protectIR();
- if (!virtualStubFunction) {
- virtualStubFunction = createFunctionStub(false, true);
- signature->setVirtualCallStub(Compiler->GenerateStub(virtualStubFunction));
- }
- mvm::MvmModule::unprotectIR();
- return virtualStubFunction;
-}
-
-void JavaLLVMCompiler::initialiseAssessorInfo() {
- AssessorInfo[I_VOID].llvmType = Type::getVoidTy(getLLVMContext());
- AssessorInfo[I_VOID].llvmTypePtr = 0;
- AssessorInfo[I_VOID].logSizeInBytesConstant = 0;
-
- AssessorInfo[I_BOOL].llvmType = Type::getInt8Ty(getLLVMContext());
- AssessorInfo[I_BOOL].llvmTypePtr =
- PointerType::getUnqual(Type::getInt8Ty(getLLVMContext()));
- AssessorInfo[I_BOOL].logSizeInBytesConstant = 0;
-
- AssessorInfo[I_BYTE].llvmType = Type::getInt8Ty(getLLVMContext());
- AssessorInfo[I_BYTE].llvmTypePtr =
- PointerType::getUnqual(Type::getInt8Ty(getLLVMContext()));
- AssessorInfo[I_BYTE].logSizeInBytesConstant = 0;
-
- AssessorInfo[I_SHORT].llvmType = Type::getInt16Ty(getLLVMContext());
- AssessorInfo[I_SHORT].llvmTypePtr =
- PointerType::getUnqual(Type::getInt16Ty(getLLVMContext()));
- AssessorInfo[I_SHORT].logSizeInBytesConstant = 1;
-
- AssessorInfo[I_CHAR].llvmType = Type::getInt16Ty(getLLVMContext());
- AssessorInfo[I_CHAR].llvmTypePtr =
- PointerType::getUnqual(Type::getInt16Ty(getLLVMContext()));
- AssessorInfo[I_CHAR].logSizeInBytesConstant = 1;
-
- AssessorInfo[I_INT].llvmType = Type::getInt32Ty(getLLVMContext());
- AssessorInfo[I_INT].llvmTypePtr =
- PointerType::getUnqual(Type::getInt32Ty(getLLVMContext()));
- AssessorInfo[I_INT].logSizeInBytesConstant = 2;
-
- AssessorInfo[I_FLOAT].llvmType = Type::getFloatTy(getLLVMContext());
- AssessorInfo[I_FLOAT].llvmTypePtr =
- PointerType::getUnqual(Type::getFloatTy(getLLVMContext()));
- AssessorInfo[I_FLOAT].logSizeInBytesConstant = 2;
-
- AssessorInfo[I_LONG].llvmType = Type::getInt64Ty(getLLVMContext());
- AssessorInfo[I_LONG].llvmTypePtr =
- PointerType::getUnqual(Type::getInt64Ty(getLLVMContext()));
- AssessorInfo[I_LONG].logSizeInBytesConstant = 3;
-
- AssessorInfo[I_DOUBLE].llvmType = Type::getDoubleTy(getLLVMContext());
- AssessorInfo[I_DOUBLE].llvmTypePtr =
- PointerType::getUnqual(Type::getDoubleTy(getLLVMContext()));
- AssessorInfo[I_DOUBLE].logSizeInBytesConstant = 3;
-
- AssessorInfo[I_TAB].llvmType = JavaIntrinsics.JavaObjectType;
- AssessorInfo[I_TAB].llvmTypePtr =
- PointerType::getUnqual(AssessorInfo[I_TAB].llvmType);
- AssessorInfo[I_TAB].logSizeInBytesConstant = sizeof(JavaObject*) == 8 ? 3 : 2;
-
- AssessorInfo[I_REF].llvmType = AssessorInfo[I_TAB].llvmType;
- AssessorInfo[I_REF].llvmTypePtr = AssessorInfo[I_TAB].llvmTypePtr;
- AssessorInfo[I_REF].logSizeInBytesConstant = sizeof(JavaObject*) == 8 ? 3 : 2;
-}
-
-LLVMAssessorInfo& JavaLLVMCompiler::getTypedefInfo(const Typedef* type) {
- return AssessorInfo[type->getKey()->elements[0]];
-}
diff --git a/vmkit/lib/J3/Compiler/LLVMMaterializer.cpp b/vmkit/lib/J3/Compiler/LLVMMaterializer.cpp
deleted file mode 100644
index 57f75ae..0000000
--- a/vmkit/lib/J3/Compiler/LLVMMaterializer.cpp
+++ /dev/null
@@ -1,184 +0,0 @@
-//===-------- LLVMMaterializer.cpp - LLVM Materializer for J3 -------------===//
-//
-// The VMKit project
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#include "llvm/Constants.h"
-#include "llvm/Module.h"
-#include "llvm/ExecutionEngine/ExecutionEngine.h"
-
-#include "mvm/JIT.h"
-
-#include "JavaAccess.h"
-#include "JavaClass.h"
-#include "JavaConstantPool.h"
-#include "JavaThread.h"
-#include "JavaTypes.h"
-#include "Jnjvm.h"
-
-#include "j3/J3Intrinsics.h"
-#include "j3/LLVMMaterializer.h"
-
-using namespace llvm;
-using namespace j3;
-
-
-JavaLLVMLazyJITCompiler::JavaLLVMLazyJITCompiler(const std::string& ModuleID)
- : JavaJITCompiler(ModuleID) {
- TheMaterializer = new LLVMMaterializer(TheModule, this);
- executionEngine->DisableLazyCompilation(false);
-}
-
-JavaLLVMLazyJITCompiler::~JavaLLVMLazyJITCompiler() {
- // The module already destroys the materializer.
-}
-
-void* JavaLLVMLazyJITCompiler::loadMethod(void* handle, const char* symbol) {
- Function* F = mvm::MvmModule::globalModule->getFunction(symbol);
- if (F) {
- void* res = executionEngine->getPointerToFunctionOrStub(F);
- return res;
- }
-
- return JavaCompiler::loadMethod(handle, symbol);
-}
-
-uintptr_t JavaLLVMLazyJITCompiler::getPointerOrStub(JavaMethod& meth,
- int side) {
- LLVMMethodInfo* LMI = getMethodInfo(&meth);
- Function* func = LMI->getMethod();
- return (uintptr_t)executionEngine->getPointerToFunctionOrStub(func);
-}
-
-static JavaMethod* staticLookup(CallbackInfo& F) {
- Class* caller = F.cl;
- uint16 index = F.index;
- bool isStatic = F.stat;
- JavaConstantPool* ctpInfo = caller->getConstantPool();
-
- CommonClass* cl = 0;
- const UTF8* utf8 = 0;
- Signdef* sign = 0;
-
- ctpInfo->resolveMethod(index, cl, utf8, sign);
- UserClass* lookup = cl->isArray() ? cl->super : cl->asClass();
- JavaMethod* meth = lookup->lookupMethod(utf8, sign->keyName, isStatic, true,
- 0);
-
- assert(lookup->isInitializing() && "Class not ready");
-
- return meth;
-}
-
-
-Value* JavaLLVMLazyJITCompiler::addCallback(Class* cl, uint16 index,
- Signdef* sign, bool stat,
- BasicBlock* insert) {
-
- Function* F = 0;
- LLVMSignatureInfo* LSI = getSignatureInfo(sign);
- mvm::ThreadAllocator allocator;
-
- const UTF8* name = cl->name;
- char* key = (char*)allocator.Allocate(name->size + 16);
- for (sint32 i = 0; i < name->size; ++i)
- key[i] = name->elements[i];
- sprintf(key + name->size, "%d", index);
- F = TheModule->getFunction(key);
- if (F) return F;
-
- const FunctionType* type = stat ? LSI->getStaticType() :
- LSI->getVirtualType();
-
- F = Function::Create(type, GlobalValue::ExternalWeakLinkage, key, TheModule);
-
- CallbackInfo A(cl, index, stat);
- callbacks.insert(std::make_pair(F, A));
-
- return F;
-}
-
-
-bool LLVMMaterializer::Materialize(GlobalValue *GV, std::string *ErrInfo) {
-
- Function* F = dyn_cast<Function>(GV);
- assert(F && "Not a function");
- if (F->getLinkage() == GlobalValue::ExternalLinkage) return false;
-
- // The caller of materializeFunction *must* always hold the JIT lock.
- // Because we are materializing a function here, we must release the
- // JIT lock and get the global vmkit lock to be thread-safe.
- // This prevents jitting the function while someone else is doing it.
- Comp->executionEngine->lock.release();
- mvm::MvmModule::protectIR();
-
- // Don't use hasNotBeenReadFromBitcode: materializeFunction is called
- // by the pass manager, and we don't want another thread to JIT the
- // function while all passes have not been run.
- if (!(F->isDeclaration())) {
- mvm::MvmModule::unprotectIR();
- // TODO: Is this still valid?
- // Reacquire and go back to the JIT function.
- // mvm::MvmModule::executionEngine->lock.acquire();
- return false;
- }
-
- if (Comp->executionEngine->getPointerToGlobalIfAvailable(F)) {
- mvm::MvmModule::unprotectIR();
- // TODO: Is this still valid?
- // Reacquire and go back to the JIT function.
- // mvm::MvmModule::executionEngine->lock.acquire();
- return false;
- }
-
- JavaMethod* meth = Comp->getJavaMethod(*F);
-
- if (!meth) {
- // It's a callback
- JavaLLVMLazyJITCompiler::callback_iterator I = Comp->callbacks.find(F);
- assert(I != Comp->callbacks.end() && "No callbacks found");
- meth = staticLookup(I->second);
- }
-
- void* val = meth->compiledPtr();
-
- if (isVirtual(meth->access)) {
- LLVMMethodInfo* LMI = Comp->getMethodInfo(meth);
- uint64_t offset = dyn_cast<ConstantInt>(LMI->getOffset())->getZExtValue();
- assert(meth->classDef->isResolved() && "Class not resolved");
- assert(meth->classDef->isInitializing() && "Class not ready");
- assert(meth->classDef->virtualVT && "Class has no VT");
- assert(meth->classDef->virtualTableSize > offset &&
- "The method's offset is greater than the virtual table size");
- ((void**)meth->classDef->virtualVT)[offset] = val;
- } else {
- assert(meth->classDef->isInitializing() && "Class not ready");
- }
-
- mvm::MvmModule::unprotectIR();
-
- // TODO: Is this still valid?
- // Reacquire to go back to the JIT function.
- // mvm::MvmModule::executionEngine->lock.acquire();
-
- if (F->isDeclaration())
- Comp->executionEngine->updateGlobalMapping(F, val);
-
- return false;
-}
-
-bool LLVMMaterializer::isMaterializable(const llvm::GlobalValue* GV) const {
- return GV->getLinkage() == GlobalValue::ExternalWeakLinkage;
-}
-
-
-LLVMMaterializer::LLVMMaterializer(
- llvm::Module* m, JavaLLVMLazyJITCompiler* C) {
- Comp = C;
- TheModule = m;
- m->setMaterializer(this);
-}
diff --git a/vmkit/lib/J3/Compiler/LowerConstantCalls.cpp b/vmkit/lib/J3/Compiler/LowerConstantCalls.cpp
deleted file mode 100644
index dbdfd79..0000000
--- a/vmkit/lib/J3/Compiler/LowerConstantCalls.cpp
+++ /dev/null
@@ -1,711 +0,0 @@
-//===----- LowerConstantCalls.cpp - Changes arrayLength calls --------------===//
-//
-// The VMKit project
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#include "llvm/Constants.h"
-#include "llvm/GlobalVariable.h"
-#include "llvm/Pass.h"
-#include "llvm/Function.h"
-#include "llvm/Instructions.h"
-#include "llvm/Support/CallSite.h"
-#include "llvm/Support/Compiler.h"
-#include "llvm/Support/Debug.h"
-
-#include "JavaClass.h"
-#include "j3/JavaLLVMCompiler.h"
-#include "j3/J3Intrinsics.h"
-
-using namespace llvm;
-
-namespace j3 {
-
- class LowerConstantCalls : public FunctionPass {
- public:
- static char ID;
- JavaLLVMCompiler* TheCompiler;
- LowerConstantCalls(JavaLLVMCompiler* Compiler) : FunctionPass(ID),
- TheCompiler(Compiler) { }
-
- virtual bool runOnFunction(Function &F);
- private:
- };
- char LowerConstantCalls::ID = 0;
-
-#if 0
- static RegisterPass<LowerConstantCalls> X("LowerConstantCalls",
- "Lower Constant calls");
-#endif
-
-
-static Value* getTCM(J3Intrinsics* intrinsics, Value* Arg, Instruction* CI) {
- Value* GEP[2] = { intrinsics->constantZero,
- intrinsics->OffsetTaskClassMirrorInClassConstant };
- Value* TCMArray = GetElementPtrInst::Create(Arg, GEP, GEP + 2, "", CI);
-
- Value* GEP2[2] = { intrinsics->constantZero, intrinsics->constantZero };
-
- Value* TCM = GetElementPtrInst::Create(TCMArray, GEP2, GEP2 + 2, "",
- CI);
- return TCM;
-
-}
-
-static Value* getDelegatee(J3Intrinsics* intrinsics, Value* Arg, Instruction* CI) {
- Value* GEP[2] = { intrinsics->constantZero,
- intrinsics->constantZero };
- Value* TCMArray = GetElementPtrInst::Create(Arg, GEP, GEP + 2, "", CI);
-
- Value* GEP2[2] = { intrinsics->constantZero, intrinsics->constantZero };
-
- Value* TCM = GetElementPtrInst::Create(TCMArray, GEP2, GEP2 + 2, "",
- CI);
- return new LoadInst(TCM, "", CI);
-
-}
-
-bool LowerConstantCalls::runOnFunction(Function& F) {
- LLVMContext* Context = &F.getContext();
- bool Changed = false;
- J3Intrinsics* intrinsics = TheCompiler->getIntrinsics();
- JavaMethod* meth = TheCompiler->getJavaMethod(F);
- assert(meth && "Method not registered");
- for (Function::iterator BI = F.begin(), BE = F.end(); BI != BE; BI++) {
- BasicBlock *Cur = BI;
- for (BasicBlock::iterator II = Cur->begin(), IE = Cur->end(); II != IE;) {
- Instruction *I = II;
- II++;
-
- if (ICmpInst* Cmp = dyn_cast<ICmpInst>(I)) {
- if (Cmp->getOperand(1) == intrinsics->JavaObjectNullConstant) {
- Value* Arg = Cmp->getOperand(0);
- if (isVirtual(meth->access) && Arg == F.arg_begin()) {
- Changed = true;
- Cmp->replaceAllUsesWith(ConstantInt::getFalse(*Context));
- Cmp->eraseFromParent();
- break;
- }
-
- Instruction* InsArg = dyn_cast<Instruction>(Arg);
- if (InsArg != NULL &&
- (InsArg->getOpcode() == Instruction::Call ||
- InsArg->getOpcode() == Instruction::Invoke)) {
- CallSite Ca(Arg);
- if (Ca.getCalledValue() == intrinsics->AllocateFunction) {
- Changed = true;
- Cmp->replaceAllUsesWith(ConstantInt::getFalse(*Context));
- Cmp->eraseFromParent();
- break;
- }
- }
- }
- }
-
- // Remove useless Alloca's, usually used for stacks or temporary values.
- // The optimizers may have rendered them useless.
- if (AllocaInst* AI = dyn_cast<AllocaInst>(I)) {
- bool ToDelete = true;
- for (Value::use_iterator UI = AI->use_begin(), UE = AI->use_end();
- UI != UE; ++UI) {
- if (dyn_cast<StoreInst>(*UI)) continue;
- if (BitCastInst* BI = dyn_cast<BitCastInst>(*UI)) {
- if (BI->hasOneUse()) {
- Instruction* use = dyn_cast<Instruction>(*(BI->use_begin()));
- if (use != NULL &&
- (use->getOpcode() == Instruction::Call ||
- use->getOpcode() == Instruction::Invoke)) {
- CallSite Call(use);
- if (Call.getCalledFunction() == intrinsics->llvm_gc_gcroot) {
- continue;
- }
- }
- }
- }
-
- ToDelete = false;
- break;
- }
-
- if (ToDelete) {
- Changed = true;
- for (Value::use_iterator UI = AI->use_begin(), UE = AI->use_end();
- UI != UE;) {
- Value* Temp = *UI;
- ++UI;
- if (StoreInst* SI = dyn_cast<StoreInst>(Temp)) {
- if (dyn_cast<Instruction>(II) == SI) ++II;
- SI->eraseFromParent();
- } else if (BitCastInst* BI = dyn_cast<BitCastInst>(Temp)) {
- CallSite Call(*(BI->use_begin()));
- Instruction* CI = Call.getInstruction();
- if (dyn_cast<Instruction>(II) == CI) ++II;
- CI->eraseFromParent();
- if (dyn_cast<Instruction>(II) == BI) ++II;
- BI->eraseFromParent();
- }
- }
- AI->eraseFromParent();
- }
- continue;
- }
- // Make sure all Loads on objects are volatile to cooperate with the GC.
- if (LoadInst* LI = dyn_cast<LoadInst>(I)) {
- if (LI->getType() == intrinsics->JavaObjectType &&
- dyn_cast<AllocaInst>(LI->getPointerOperand()) != NULL) {
- if (TheCompiler->useCooperativeGC()) {
- assert(LI->isVolatile());
- } else {
- assert(!LI->isVolatile());
- }
- }
- }
-
- if ((I->getOpcode() == Instruction::Call ||
- I->getOpcode() == Instruction::Invoke)) {
- Instruction* CI = I;
- CallSite Call(I);
- Value* V = Call.getCalledValue();
- if (V == intrinsics->ArrayLengthFunction) {
- Changed = true;
- Value* val = Call.getArgument(0); // get the array
- Value* array = new BitCastInst(val, intrinsics->JavaArrayType,
- "", CI);
- Value* args[2] = { intrinsics->constantZero,
- intrinsics->JavaArraySizeOffsetConstant };
- Value* ptr = GetElementPtrInst::Create(array, args, args + 2,
- "", CI);
- Value* load = new LoadInst(ptr, "", CI);
- load = new PtrToIntInst(load, Type::getInt32Ty(*Context), "", CI);
- CI->replaceAllUsesWith(load);
- CI->eraseFromParent();
- } else if (V == intrinsics->GetVTFunction) {
- Changed = true;
- Value* val = Call.getArgument(0); // get the object
- Value* indexes[2] = { intrinsics->constantZero, intrinsics->constantZero };
- Value* VTPtr = GetElementPtrInst::Create(val, indexes, indexes + 2,
- "", CI);
- Value* VT = new LoadInst(VTPtr, "", CI);
- CI->replaceAllUsesWith(VT);
- CI->eraseFromParent();
- } else if (V == intrinsics->GetIMTFunction) {
- Changed = true;
- Value* val = Call.getArgument(0); // get the VT
- Value* indexes[2] = { intrinsics->constantZero,
- intrinsics->OffsetIMTInVTConstant };
- Value* IMTPtr = GetElementPtrInst::Create(val, indexes, indexes + 2,
- "", CI);
- Value* IMT = new LoadInst(IMTPtr, "", CI);
- IMT = new BitCastInst(IMT, CI->getType(), "", CI);
- CI->replaceAllUsesWith(IMT);
- CI->eraseFromParent();
- } else if (V == intrinsics->GetClassFunction) {
- Changed = true;
- Value* val = Call.getArgument(0); // get the object
- Value* args2[2] = { intrinsics->constantZero,
- intrinsics->JavaObjectVTOffsetConstant };
- Value* VTPtr = GetElementPtrInst::Create(val, args2, args2 + 2,
- "", CI);
- Value* VT = new LoadInst(VTPtr, "", CI);
- Value* args3[2] = { intrinsics->constantZero,
- intrinsics->OffsetClassInVTConstant };
-
- Value* clPtr = GetElementPtrInst::Create(VT, args3, args3 + 2,
- "", CI);
- Value* cl = new LoadInst(clPtr, "", CI);
- cl = new BitCastInst(cl, intrinsics->JavaCommonClassType, "", CI);
-
- CI->replaceAllUsesWith(cl);
- CI->eraseFromParent();
- } else if (V == intrinsics->GetVTFromClassFunction) {
- Changed = true;
-
- Value* val = Call.getArgument(0);
- Value* indexes[3] = { intrinsics->constantZero,
- intrinsics->constantZero,
- intrinsics->OffsetVTInClassConstant };
- Value* VTPtr = GetElementPtrInst::Create(val, indexes, indexes + 3,
- "", CI);
- Value* VT = new LoadInst(VTPtr, "", CI);
- CI->replaceAllUsesWith(VT);
- CI->eraseFromParent();
- } else if (V == intrinsics->GetVTFromCommonClassFunction) {
- Changed = true;
-
- Value* val = Call.getArgument(0);
- Value* indexes[2] = { intrinsics->constantZero,
- intrinsics->OffsetVTInClassConstant };
- Value* VTPtr = GetElementPtrInst::Create(val, indexes, indexes + 2,
- "", CI);
- Value* VT = new LoadInst(VTPtr, "", CI);
- CI->replaceAllUsesWith(VT);
- CI->eraseFromParent();
- } else if (V == intrinsics->GetVTFromClassArrayFunction) {
- Changed = true;
-
- Value* val = Call.getArgument(0);
- Value* indexes[3] = { intrinsics->constantZero,
- intrinsics->constantZero,
- intrinsics->OffsetVTInClassConstant };
- Value* VTPtr = GetElementPtrInst::Create(val, indexes, indexes + 3,
- "", CI);
- Value* VT = new LoadInst(VTPtr, "", CI);
- CI->replaceAllUsesWith(VT);
- CI->eraseFromParent();
- } else if (V == intrinsics->GetBaseClassVTFromVTFunction) {
- Changed = true;
-
- Value* val = Call.getArgument(0);
- Value* indexes[2] = { intrinsics->constantZero,
- intrinsics->OffsetBaseClassVTInVTConstant };
- Value* VTPtr = GetElementPtrInst::Create(val, indexes, indexes + 2,
- "", CI);
- Value* VT = new LoadInst(VTPtr, "", CI);
- VT = new BitCastInst(VT, intrinsics->VTType, "", CI);
- CI->replaceAllUsesWith(VT);
- CI->eraseFromParent();
- } else if (V == intrinsics->GetObjectSizeFromClassFunction) {
- Changed = true;
-
- Value* val = Call.getArgument(0);
- Value* indexes[2] = { intrinsics->constantZero,
- intrinsics->OffsetObjectSizeInClassConstant };
- Value* SizePtr = GetElementPtrInst::Create(val, indexes, indexes + 2,
- "", CI);
- Value* Size = new LoadInst(SizePtr, "", CI);
- CI->replaceAllUsesWith(Size);
- CI->eraseFromParent();
- } else if (V == intrinsics->GetDepthFunction) {
- Changed = true;
- Value* val = Call.getArgument(0);
- Value* indexes[2] = { intrinsics->constantZero,
- intrinsics->OffsetDepthInVTConstant };
- Value* DepthPtr = GetElementPtrInst::Create(val, indexes,
- indexes + 2, "", CI);
- Value* Depth = new LoadInst(DepthPtr, "", CI);
- Depth = new PtrToIntInst(Depth, Type::getInt32Ty(*Context), "", CI);
- CI->replaceAllUsesWith(Depth);
- CI->eraseFromParent();
- } else if (V == intrinsics->GetDisplayFunction) {
- Changed = true;
- Value* val = Call.getArgument(0);
- Value* indexes[2] = { intrinsics->constantZero,
- intrinsics->OffsetDisplayInVTConstant };
- Value* DisplayPtr = GetElementPtrInst::Create(val, indexes,
- indexes + 2, "", CI);
- const llvm::Type* Ty = PointerType::getUnqual(intrinsics->VTType);
- DisplayPtr = new BitCastInst(DisplayPtr, Ty, "", CI);
- CI->replaceAllUsesWith(DisplayPtr);
- CI->eraseFromParent();
- } else if (V == intrinsics->GetVTInDisplayFunction) {
- Changed = true;
- Value* val = Call.getArgument(0);
- Value* depth = Call.getArgument(1);
- Value* ClassPtr = GetElementPtrInst::Create(val, depth, "", CI);
- Value* Class = new LoadInst(ClassPtr, "", CI);
- CI->replaceAllUsesWith(Class);
- CI->eraseFromParent();
- } else if (V == intrinsics->GetClassDelegateeFunction) {
- Changed = true;
- BasicBlock* NBB = II->getParent()->splitBasicBlock(II);
- I->getParent()->getTerminator()->eraseFromParent();
- Value* Del = getDelegatee(intrinsics, Call.getArgument(0), CI);
- Value* cmp = new ICmpInst(CI, ICmpInst::ICMP_EQ, Del,
- intrinsics->JavaObjectNullConstant, "");
-
- BasicBlock* NoDelegatee = BasicBlock::Create(*Context, "No delegatee", &F);
- BasicBlock* DelegateeOK = BasicBlock::Create(*Context, "Delegatee OK", &F);
- BranchInst::Create(NoDelegatee, DelegateeOK, cmp, CI);
- PHINode* phi = PHINode::Create(intrinsics->JavaObjectType, "", DelegateeOK);
- phi->addIncoming(Del, CI->getParent());
-
- Instruction* Res = CallInst::Create(intrinsics->RuntimeDelegateeFunction,
- Call.getArgument(0), "", NoDelegatee);
- Res->setDebugLoc(CI->getDebugLoc());
- BranchInst::Create(DelegateeOK, NoDelegatee);
- phi->addIncoming(Res, NoDelegatee);
-
- CI->replaceAllUsesWith(phi);
- CI->eraseFromParent();
- BranchInst::Create(NBB, DelegateeOK);
- break;
-
- } else if (V == intrinsics->InitialisationCheckFunction) {
- Changed = true;
-
- BasicBlock* NBB = 0;
- if (CI->getParent()->getTerminator() != CI) {
- NBB = II->getParent()->splitBasicBlock(II);
- CI->getParent()->getTerminator()->eraseFromParent();
- } else {
- InvokeInst* Invoke = dyn_cast<InvokeInst>(CI);
- assert(Invoke && "Last instruction is not an invoke");
- NBB = Invoke->getNormalDest();
- }
-
- Value* Cl = Call.getArgument(0);
- Value* TCM = getTCM(intrinsics, Call.getArgument(0), CI);
- Value* GEP[2] =
- { intrinsics->constantZero,
- intrinsics->OffsetInitializedInTaskClassMirrorConstant };
- Value* StatusPtr = GetElementPtrInst::Create(TCM, GEP, GEP + 2, "",
- CI);
-
- Value* test = new LoadInst(StatusPtr, "", CI);
-
- BasicBlock* trueCl = BasicBlock::Create(*Context, "Initialized", &F);
- BasicBlock* falseCl = BasicBlock::Create(*Context, "Uninitialized", &F);
- PHINode* node = llvm::PHINode::Create(intrinsics->JavaClassType, "", trueCl);
- node->addIncoming(Cl, CI->getParent());
- BranchInst::Create(trueCl, falseCl, test, CI);
-
-
- Instruction* res = 0;
- if (InvokeInst* Invoke = dyn_cast<InvokeInst>(CI)) {
- Value* Args[1] = { Cl };
- BasicBlock* UI = Invoke->getUnwindDest();
-
- res = InvokeInst::Create(intrinsics->InitialiseClassFunction,
- trueCl, UI, Args, Args + 1,
- "", falseCl);
-
- // For some reason, an LLVM pass may add PHI nodes to the
- // exception destination.
- BasicBlock::iterator Temp = UI->getInstList().begin();
- while (PHINode* PHI = dyn_cast<PHINode>(Temp)) {
- Value* Val = PHI->getIncomingValueForBlock(CI->getParent());
- PHI->removeIncomingValue(CI->getParent(), false);
- PHI->addIncoming(Val, falseCl);
- Temp++;
- }
-
- // And here we set the phi nodes of the normal dest of the Invoke
- // instruction. The phi nodes have now the trueCl as basic block.
- Temp = NBB->getInstList().begin();
- while (PHINode* PHI = dyn_cast<PHINode>(Temp)) {
- Value* Val = PHI->getIncomingValueForBlock(CI->getParent());
- PHI->removeIncomingValue(CI->getParent(), false);
- PHI->addIncoming(Val, trueCl);
- Temp++;
- }
-
- } else {
- res = CallInst::Create(intrinsics->InitialiseClassFunction,
- Cl, "", falseCl);
- BranchInst::Create(trueCl, falseCl);
- }
- res->setDebugLoc(CI->getDebugLoc());
-
- node->addIncoming(res, falseCl);
-
-
- CI->replaceAllUsesWith(node);
- CI->eraseFromParent();
- BranchInst::Create(NBB, trueCl);
- break;
- } else if (V == intrinsics->GetConstantPoolAtFunction) {
- Function* resolver = dyn_cast<Function>(Call.getArgument(0));
- assert(resolver && "Wrong use of GetConstantPoolAt");
- const Type* returnType = resolver->getReturnType();
- Value* CTP = Call.getArgument(1);
- Value* Index = Call.getArgument(3);
- Changed = true;
- BasicBlock* NBB = 0;
- if (CI->getParent()->getTerminator() != CI) {
- NBB = II->getParent()->splitBasicBlock(II);
- CI->getParent()->getTerminator()->eraseFromParent();
- } else {
- InvokeInst* Invoke = dyn_cast<InvokeInst>(CI);
- assert(Invoke && "Last instruction is not an invoke");
- NBB = Invoke->getNormalDest();
- }
-
- Value* indexes = Index;
- Value* arg1 = GetElementPtrInst::Create(CTP, indexes, "", CI);
- arg1 = new LoadInst(arg1, "", false, CI);
- Value* test = new ICmpInst(CI, ICmpInst::ICMP_EQ, arg1,
- intrinsics->constantPtrNull, "");
-
- BasicBlock* trueCl = BasicBlock::Create(*Context, "Ctp OK", &F);
- BasicBlock* falseCl = BasicBlock::Create(*Context, "Ctp Not OK", &F);
- PHINode* node = llvm::PHINode::Create(returnType, "", trueCl);
- node->addIncoming(arg1, CI->getParent());
- BranchInst::Create(falseCl, trueCl, test, CI);
-
- std::vector<Value*> Args;
- unsigned ArgSize = Call.arg_size(), i = 1;
- while (++i < ArgSize) {
- Args.push_back(Call.getArgument(i));
- }
-
- Instruction* res = 0;
- if (InvokeInst* Invoke = dyn_cast<InvokeInst>(CI)) {
- BasicBlock* UI = Invoke->getUnwindDest();
- res = InvokeInst::Create(resolver, trueCl, UI, Args.begin(),
- Args.end(), "", falseCl);
-
- // For some reason, an LLVM pass may add PHI nodes to the
- // exception destination.
- BasicBlock::iterator Temp = UI->getInstList().begin();
- while (PHINode* PHI = dyn_cast<PHINode>(Temp)) {
- Value* Val = PHI->getIncomingValueForBlock(CI->getParent());
- PHI->removeIncomingValue(CI->getParent(), false);
- PHI->addIncoming(Val, falseCl);
- Temp++;
- }
-
- // And here we set the phi nodes of the normal dest of the Invoke
- // instruction. The phi nodes have now the trueCl as basic block.
- Temp = NBB->getInstList().begin();
- while (PHINode* PHI = dyn_cast<PHINode>(Temp)) {
- Value* Val = PHI->getIncomingValueForBlock(CI->getParent());
- PHI->removeIncomingValue(CI->getParent(), false);
- PHI->addIncoming(Val, trueCl);
- Temp++;
- }
-
- } else {
- res = CallInst::Create(resolver, Args.begin(), Args.end(), "",
- falseCl);
- BranchInst::Create(trueCl, falseCl);
- }
-
- res->setDebugLoc(CI->getDebugLoc());
- node->addIncoming(res, falseCl);
-
- CI->replaceAllUsesWith(node);
- CI->eraseFromParent();
- BranchInst::Create(NBB, trueCl);
- break;
- } else if (V == intrinsics->GetArrayClassFunction) {
- const llvm::Type* Ty = PointerType::getUnqual(intrinsics->VTType);
- Constant* nullValue = Constant::getNullValue(Ty);
- // Check if we have already proceed this call.
- if (Call.getArgument(2) == nullValue) {
- BasicBlock* NBB = II->getParent()->splitBasicBlock(II);
- I->getParent()->getTerminator()->eraseFromParent();
-
- Constant* init = Constant::getNullValue(intrinsics->VTType);
- GlobalVariable* GV =
- new GlobalVariable(*(F.getParent()), intrinsics->VTType,
- false, GlobalValue::ExternalLinkage,
- init, "");
-
- Value* LoadedGV = new LoadInst(GV, "", CI);
- Value* cmp = new ICmpInst(CI, ICmpInst::ICMP_EQ, LoadedGV, init,
- "");
-
- BasicBlock* OKBlock = BasicBlock::Create(*Context, "", &F);
- BasicBlock* NotOKBlock = BasicBlock::Create(*Context, "", &F);
- PHINode* node = PHINode::Create(intrinsics->VTType, "",
- OKBlock);
- node->addIncoming(LoadedGV, CI->getParent());
-
- BranchInst::Create(NotOKBlock, OKBlock, cmp, CI);
-
- Value* args[3] = { Call.getArgument(0), Call.getArgument(1), GV };
- Instruction* res = CallInst::Create(intrinsics->GetArrayClassFunction, args,
- args + 3, "", NotOKBlock);
- res->setDebugLoc(CI->getDebugLoc());
- BranchInst::Create(OKBlock, NotOKBlock);
- node->addIncoming(res, NotOKBlock);
-
- CI->replaceAllUsesWith(node);
- CI->eraseFromParent();
- BranchInst::Create(NBB, OKBlock);
- Changed = true;
- break;
- }
- } else if (V == intrinsics->ForceInitialisationCheckFunction ||
- V == intrinsics->ForceLoadedCheckFunction ) {
- Changed = true;
- CI->eraseFromParent();
- } else if (V == intrinsics->GetFinalInt8FieldFunction ||
- V == intrinsics->GetFinalInt16FieldFunction ||
- V == intrinsics->GetFinalInt32FieldFunction ||
- V == intrinsics->GetFinalLongFieldFunction ||
- V == intrinsics->GetFinalFloatFieldFunction ||
- V == intrinsics->GetFinalDoubleFieldFunction) {
- Changed = true;
- Value* val = Call.getArgument(0);
- Value* res = new LoadInst(val, "", CI);
- CI->replaceAllUsesWith(res);
- CI->eraseFromParent();
- } else if (V == intrinsics->IsAssignableFromFunction) {
- Changed = true;
- Value* VT1 = Call.getArgument(0);
- Value* VT2 = Call.getArgument(1);
-
- BasicBlock* EndBlock = II->getParent()->splitBasicBlock(II);
- I->getParent()->getTerminator()->eraseFromParent();
-
- BasicBlock* CurEndBlock = BasicBlock::Create(*Context, "", &F);
- BasicBlock* FailedBlock = BasicBlock::Create(*Context, "", &F);
- PHINode* node = PHINode::Create(Type::getInt1Ty(*Context), "", CurEndBlock);
-
- ConstantInt* CC = ConstantInt::get(Type::getInt32Ty(*Context),
- JavaVirtualTable::getOffsetIndex());
- Value* indices[2] = { intrinsics->constantZero, CC };
- Value* Offset = GetElementPtrInst::Create(VT2, indices, indices + 2,
- "", CI);
- Offset = new LoadInst(Offset, "", false, CI);
- Offset = new PtrToIntInst(Offset, Type::getInt32Ty(*Context), "", CI);
- indices[1] = Offset;
- Value* CurVT = GetElementPtrInst::Create(VT1, indices, indices + 2,
- "", CI);
- CurVT = new LoadInst(CurVT, "", false, CI);
- CurVT = new BitCastInst(CurVT, intrinsics->VTType, "", CI);
-
- Instruction* res =
- new ICmpInst(CI, ICmpInst::ICMP_EQ, CurVT, VT2, "");
-
- node->addIncoming(ConstantInt::getTrue(*Context), CI->getParent());
- BranchInst::Create(CurEndBlock, FailedBlock, res, CI);
-
- Value* Args[2] = { VT1, VT2 };
- res = CallInst::Create(intrinsics->IsSecondaryClassFunction, Args,
- Args + 2, "", FailedBlock);
- res->setDebugLoc(CI->getDebugLoc());
-
- node->addIncoming(res, FailedBlock);
- BranchInst::Create(CurEndBlock, FailedBlock);
-
- // Branch to the next block.
- BranchInst::Create(EndBlock, CurEndBlock);
-
- // We can now replace the previous instruction.
- CI->replaceAllUsesWith(node);
- CI->eraseFromParent();
-
- // Reanalyse the current block.
- break;
-
- } else if (V == intrinsics->IsSecondaryClassFunction) {
- Changed = true;
- Value* VT1 = Call.getArgument(0);
- Value* VT2 = Call.getArgument(1);
-
- BasicBlock* EndBlock = II->getParent()->splitBasicBlock(II);
- I->getParent()->getTerminator()->eraseFromParent();
-
-
- BasicBlock* Preheader = BasicBlock::Create(*Context, "preheader", &F);
- BasicBlock* BB4 = BasicBlock::Create(*Context, "BB4", &F);
- BasicBlock* BB5 = BasicBlock::Create(*Context, "BB5", &F);
- BasicBlock* BB6 = BasicBlock::Create(*Context, "BB6", &F);
- BasicBlock* BB7 = BasicBlock::Create(*Context, "BB7", &F);
- BasicBlock* BB9 = BasicBlock::Create(*Context, "BB9", &F);
- const Type* Ty = PointerType::getUnqual(intrinsics->VTType);
-
- PHINode* resFwd = PHINode::Create(Type::getInt32Ty(*Context), "", BB7);
-
- // This corresponds to:
- // if (VT1.cache == VT2 || VT1 == VT2) goto end with true;
- // else goto headerLoop;
- ConstantInt* cacheIndex =
- ConstantInt::get(Type::getInt32Ty(*Context), JavaVirtualTable::getCacheIndex());
- Value* indices[2] = { intrinsics->constantZero, cacheIndex };
- Instruction* CachePtr =
- GetElementPtrInst::Create(VT1, indices, indices + 2, "", CI);
- CachePtr = new BitCastInst(CachePtr, Ty, "", CI);
- Value* Cache = new LoadInst(CachePtr, "", false, CI);
- ICmpInst* cmp1 = new ICmpInst(CI, ICmpInst::ICMP_EQ, Cache, VT2, "");
- ICmpInst* cmp2 = new ICmpInst(CI, ICmpInst::ICMP_EQ, VT1, VT2, "");
- BinaryOperator* Or = BinaryOperator::Create(Instruction::Or, cmp1,
- cmp2, "", CI);
- BranchInst::Create(BB9, Preheader, Or, CI);
-
- // First test failed. Go into the loop. The Preheader looks like this:
- // headerLoop:
- // types = VT1->secondaryTypes;
- // size = VT1->nbSecondaryTypes;
- // i = 0;
- // goto test;
- ConstantInt* sizeIndex = ConstantInt::get(Type::getInt32Ty(*Context),
- JavaVirtualTable::getNumSecondaryTypesIndex());
- indices[1] = sizeIndex;
- Instruction* Size = GetElementPtrInst::Create(VT1, indices,
- indices + 2, "",
- Preheader);
- Size = new LoadInst(Size, "", false, Preheader);
- Size = new PtrToIntInst(Size, Type::getInt32Ty(*Context), "", Preheader);
-
- ConstantInt* secondaryTypesIndex = ConstantInt::get(Type::getInt32Ty(*Context),
- JavaVirtualTable::getSecondaryTypesIndex());
- indices[1] = secondaryTypesIndex;
- Instruction* secondaryTypes =
- GetElementPtrInst::Create(VT1, indices, indices + 2, "", Preheader);
- secondaryTypes = new LoadInst(secondaryTypes, "", false, Preheader);
- secondaryTypes = new BitCastInst(secondaryTypes, Ty, "", Preheader);
- BranchInst::Create(BB7, Preheader);
-
- // Here is the test if the current secondary type is VT2.
- // test:
- // CurVT = types[i];
- // if (CurVT == VT2) goto update cache;
- // est goto inc;
- Instruction* CurVT = GetElementPtrInst::Create(secondaryTypes, resFwd,
- "", BB4);
- CurVT = new LoadInst(CurVT, "", false, BB4);
- cmp1 = new ICmpInst(*BB4, ICmpInst::ICMP_EQ, CurVT, VT2, "");
- BranchInst::Create(BB5, BB6, cmp1, BB4);
-
- // Increment i if the previous test failed
- // inc:
- // ++i;
- // goto endLoopTest;
- BinaryOperator* IndVar =
- BinaryOperator::CreateAdd(resFwd, intrinsics->constantOne, "", BB6);
- BranchInst::Create(BB7, BB6);
-
- // Verify that we haven't reached the end of the loop:
- // endLoopTest:
- // if (i < size) goto test
- // else goto end with false
- resFwd->reserveOperandSpace(2);
- resFwd->addIncoming(intrinsics->constantZero, Preheader);
- resFwd->addIncoming(IndVar, BB6);
-
- cmp1 = new ICmpInst(*BB7, ICmpInst::ICMP_SGT, Size, resFwd, "");
- BranchInst::Create(BB4, BB9, cmp1, BB7);
-
- // Update the cache if the result is found.
- // updateCache:
- // VT1->cache = result
- // goto end with true
- new StoreInst(VT2, CachePtr, false, BB5);
- BranchInst::Create(BB9, BB5);
-
- // Final block, that gets the result.
- PHINode* node = PHINode::Create(Type::getInt1Ty(*Context), "", BB9);
- node->reserveOperandSpace(3);
- node->addIncoming(ConstantInt::getTrue(*Context), CI->getParent());
- node->addIncoming(ConstantInt::getFalse(*Context), BB7);
- node->addIncoming(ConstantInt::getTrue(*Context), BB5);
-
- // Don't forget to jump to the next block.
- BranchInst::Create(EndBlock, BB9);
-
- // We can now replace the previous instruction
- CI->replaceAllUsesWith(node);
- CI->eraseFromParent();
-
- // And reanalyse the current block.
- break;
- }
-
- }
- }
- }
- return Changed;
-}
-
-
-FunctionPass* createLowerConstantCallsPass(JavaLLVMCompiler* Compiler) {
- return new LowerConstantCalls(Compiler);
-}
-
-}
diff --git a/vmkit/lib/J3/Compiler/Makefile b/vmkit/lib/J3/Compiler/Makefile
deleted file mode 100644
index 835b5f5..0000000
--- a/vmkit/lib/J3/Compiler/Makefile
+++ /dev/null
@@ -1,25 +0,0 @@
-##===- lib/JnJVM/Compiler/Makefile -------------------------*- Makefile -*-===##
-#
-# The VMKit project
-#
-# This file is distributed under the University of Illinois Open Source
-# License. See LICENSE.TXT for details.
-#
-##===----------------------------------------------------------------------===##
-LEVEL = ../../..
-
-include $(LEVEL)/Makefile.config
-
-ifeq ($(WITH_LLVM_GCC), 1)
- MODULE_NAME = J3Compiler
-else
- LIBRARYNAME = J3Compiler
-endif
-
-EXTRA_DIST = ExceptionsCheck.inc ExceptionsDwarf.inc
-
-
-include $(LEVEL)/Makefile.common
-
-CXX.Flags += -I$(PROJ_OBJ_DIR)/../LLVMRuntime -I$(PROJ_SRC_DIR)/../Classpath $(CLASSPATH_FLAGS) -I$(PROJ_SRC_DIR)/../VMCore
-
diff --git a/vmkit/lib/J3/IJvm/BundleTermination.cpp b/vmkit/lib/J3/IJvm/BundleTermination.cpp
deleted file mode 100644
index 0ec75d3..0000000
--- a/vmkit/lib/J3/IJvm/BundleTermination.cpp
+++ /dev/null
@@ -1,149 +0,0 @@
-#ifdef SERVICE
-
-#include "llvm/ExecutionEngine/ExecutionEngine.h"
-#include "llvm/Target/TargetJITInfo.h"
-
-#include "../lib/ExecutionEngine/JIT/JIT.h"
-
-#include "JavaThread.h"
-#include "JavaJIT.h"
-#include "Jnjvm.h"
-#include "mvm/VirtualMachine.h"
-#include "mvm/Threads/Cond.h"
-#include "mvm/Threads/Locks.h"
-#include "mvm/JIT.h"
-
-#include "signal.h"
-
-using namespace jnjvm;
-
-#if defined(__MACH__) && !defined(__i386__)
-#define FRAME_IP(fp) (fp[2])
-#else
-#define FRAME_IP(fp) (fp[1])
-#endif
-
-
-
-static void throwInlineStoppedBundleException() {
- void** addr = (void**)__builtin_frame_address(0);
- JavaThread* th = JavaThread::get();
- FRAME_IP(addr) = (void**)th->replacedEIPs[--th->eipIndex];
- th->throwException(th->ServiceException);
-}
-
-static void throwStoppedBundleException() {
- JavaThread* th = JavaThread::get();
- th->throwException(th->ServiceException);
-}
-
-
-static mvm::LockNormal lock;
-static mvm::Cond cond;
-static mvm::Thread* initiator = 0;
-static bool Finished = true;
-
-void terminationHandler(int) {
- void** addr = (void**)__builtin_frame_address(0);
- mvm::Thread* th = mvm::Thread::get();
- JnjvmClassLoader* stoppedBundle =
- (JnjvmClassLoader*)(th->stoppingService->CU);
- void* baseSP = th->baseSP;
- bool inStack = false;
- while (addr && addr < baseSP && addr < addr[0]) {
- addr = (void**)addr[0];
- void** ptr = (void**)FRAME_IP(addr);
- JavaMethod* meth = JavaJIT::IPToJavaMethod(ptr);
- if (meth) {
- if (meth->classDef->classLoader == stoppedBundle) {
- inStack = true;
- JavaThread* th = JavaThread::get();
- th->replacedEIPs[th->eipIndex++] = FRAME_IP(addr);
- FRAME_IP(addr) = (void**)(uintptr_t)throwInlineStoppedBundleException;
- }
- }
- }
-
- // If the malicious bundle is in the stack, interrupt the thread.
- if (inStack) {
- JavaThread* th = JavaThread::get();
- th->lock.lock();
- th->interruptFlag = 1;
-
- // here we could also raise a signal for interrupting I/O
- if (th->state == JavaThread::StateWaiting) {
- th->state = JavaThread::StateInterrupted;
- th->varcond.signal();
- }
-
- th->lock.unlock();
-
- }
-
- if (mvm::Thread::get() != initiator) {
- lock.lock();
- while (!Finished)
- cond.wait(&lock);
- lock.unlock();
- }
-}
-
-
-
-void Jnjvm::stopService() {
-
- lock.lock();
- while (!Finished)
- cond.wait(&lock);
-
- Finished = false;
- lock.unlock();
-
- JnjvmClassLoader* bundle = (JnjvmClassLoader*)CU;
- bundle->getIsolate()->status = 1;
- mvm::Thread* th = mvm::Thread::get();
- th->stoppingService = this;
- initiator = th;
- for(mvm::Thread* cur = (mvm::Thread*)th->next(); cur != th;
- cur = (mvm::Thread*)cur->next()) {
- mvm::VirtualMachine* executingVM = cur->MyVM;
- assert(executingVM && "Thread with no VM!");
- cur->stoppingService = this;
- uint32 res = cur->kill(SIGUSR1);
- assert(res == 0);
-
- }
-
- // I have to do it too!
- terminationHandler(0);
-
- llvm::TargetJITInfo& TJI =
- ((llvm::JIT*)mvm::MvmModule::executionEngine)->getJITInfo();
- for (ClassMap::iterator i = bundle->getClasses()->map.begin(),
- e = bundle->getClasses()->map.end(); i!= e; ++i) {
- Class* cl = i->second->asClass();
-
- if (cl) {
- for (uint32 i = 0; i < cl->nbVirtualMethods; ++i) {
- if (cl->virtualMethods[i].code) {
- TJI.replaceMachineCodeForFunction(cl->virtualMethods[i].code,
- (void*)(uintptr_t)throwStoppedBundleException);
- }
- }
-
- for (uint32 i = 0; i < cl->nbStaticMethods; ++i) {
- if (cl->staticMethods[i].code) {
- TJI.replaceMachineCodeForFunction(cl->staticMethods[i].code,
- (void*)(uintptr_t)throwStoppedBundleException);
- }
- }
- }
- }
-
- lock.lock();
- Finished = true;
- cond.broadcast();
- lock.unlock();
-}
-
-#endif
diff --git a/vmkit/lib/J3/IJvm/Makefile b/vmkit/lib/J3/IJvm/Makefile
deleted file mode 100644
index 9267e29..0000000
--- a/vmkit/lib/J3/IJvm/Makefile
+++ /dev/null
@@ -1,21 +0,0 @@
-##===- lib/JnJVM/VMCore/Makefile ---------------------------*- Makefile -*-===##
-#
-# The vmkit project
-#
-# This file is distributed under the University of Illinois Open Source
-# License. See LICENSE.TXT for details.
-#
-##===----------------------------------------------------------------------===##
-LEVEL = ../../..
-
-LIBRARYNAME = IJvm
-
-include $(LEVEL)/Makefile.config
-
-include $(LEVEL)/Makefile.common
-
-CXX.Flags += -I$(PROJ_OBJ_DIR)/../Classpath -I$(PROJ_OBJ_DIR)/../LLVMRuntime -I$(PROJ_SRC_DIR)/../Classpath $(CLASSPATH_FLAGS) -I$(PROJ_SRC_DIR)/../../../include/jnjvm
-
-ifeq ($(ISOLATE_BUILD), 1)
- CXX.Flags += -I$(PROJ_SRC_DIR)/../Isolate
-endif
diff --git a/vmkit/lib/J3/Isolate/IsolateCommonClass.cpp b/vmkit/lib/J3/Isolate/IsolateCommonClass.cpp
deleted file mode 100644
index a22f80a..0000000
--- a/vmkit/lib/J3/Isolate/IsolateCommonClass.cpp
+++ /dev/null
@@ -1,355 +0,0 @@
-//===--- IsolateCommonClass.cpp - User visible classes with isolates -------===//
-//
-// JnJVM
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-
-#include "IsolateSharedLoader.h"
-#include "JavaAllocator.h"
-#include "JavaClass.h"
-#include "JavaThread.h"
-#include "JavaUpcalls.h"
-#include "Jnjvm.h"
-#include "JnjvmModule.h"
-
-using namespace jnjvm;
-
-UserCommonClass::UserCommonClass() {
- this->lockVar = mvm::Lock::allocRecursive();
- this->condVar = mvm::Cond::allocCond();
- this->status = loaded;
-}
-
-UserClass::UserClass(JnjvmClassLoader* JCL, const UTF8* name,
- ArrayUInt8* bytes) {
- Class* cl = JnjvmSharedLoader::sharedLoader->constructSharedClass(name,
- bytes);
- if (!cl) {
- cl = allocator_new(JCL->allocator, Class)(JCL, name, bytes);
- }
-
- classDef = cl;
- classLoader = JCL;
- delegatee = 0;
- staticInstance = 0;
- ctpInfo = 0;
-}
-
-UserClassArray::UserClassArray(JnjvmClassLoader* JCL, const UTF8* name) {
- ClassArray* cl = JnjvmSharedLoader::sharedLoader->constructSharedClassArray(name);
- if (!cl) {
- cl = allocator_new(JCL->allocator, ClassArray)(JCL, name);
- }
- classDef = cl;
- classLoader = JCL;
- delegatee = 0;
- _baseClass = 0;
- _funcs = 0;
- super = JCL->bootstrapLoader->SuperArray;
- interfaces = JCL->bootstrapLoader->InterfacesArray;
- depth = 1;
- display = (UserCommonClass**)malloc(2 * sizeof(UserCommonClass*));
- display[0] = super;
- display[1] = this;
-}
-
-UserClassPrimitive::UserClassPrimitive(JnjvmClassLoader* JCL, const UTF8* name,
- uint32 nb) {
- ClassPrimitive* cl =
- JnjvmSharedLoader::sharedLoader->constructSharedClassPrimitive(name, nb);
- if (!cl) {
- cl = new ClassPrimitive(JCL, name, nb);
- }
- classDef = cl;
- classLoader = JCL;
- delegatee = 0;
- display = (UserCommonClass**)malloc(sizeof(UserCommonClass*));
- display[0] = this;
- virtualSize = nb;
- status = ready;
-}
-
-void UserCommonClass::resolveClass() {
- if (status < resolved) {
- acquire();
- if (status >= resolved) {
- release();
- } else if (status == loaded) {
- if (isArray()) {
- UserClassArray* arrayCl = (UserClassArray*)this;
- UserCommonClass* baseClass = arrayCl->baseClass();
- baseClass->resolveClass();
- status = resolved;
- } else {
- UserClass* cl = (UserClass*)this;
- Class* def = (Class*)classDef;
- if (classDef->status < resolved) {
- classDef->acquire();
- if (classDef->status == loaded) {
- def->readClass();
- def->status = classRead;
- status = classRead;
- cl->ctpInfo =
- new(classLoader->allocator, def->ctpInfo->ctpSize) UserConstantPool(cl);
- cl->loadParents();
- if (cl->super)
- def->super = cl->super->classDef;
- for (std::vector<UserClass*>::iterator i = interfaces.begin(),
- e = interfaces.end(); i != e; ++i) {
- def->interfaces.push_back((Class*)((*i)->classDef));
- }
- def->status = prepared;
- status = prepared;
- def->classLoader->TheModule->resolveVirtualClass(def);
- virtualSize = def->virtualSize;
-
- uint64 vtSize = def->virtualTableSize * sizeof(void*);
-
- virtualVT = (VirtualTable*)malloc(2 * vtSize);
-
- memcpy((void*)((uint64)virtualVT + vtSize), def->virtualVT, vtSize);
- if (super) {
- memcpy(virtualVT, (void*)((uint64)super->virtualVT - vtSize),
- vtSize);
- }
-
- virtualVT = (VirtualTable*)((uint64)virtualVT + vtSize);
-
- for (CommonClass::method_iterator i = def->virtualMethods.begin(),
- e = def->virtualMethods.end(); i != e; ++i) {
- if (i->second->offset > 0) {
- ((void**)virtualVT)[-(i->second->offset)] = ctpInfo;
- }
- }
-
- def->status = resolved;
- status = resolved;
- classDef->broadcastClass();
- } else {
- while (classDef->status < resolved) {
- classDef->waitClass();
- }
- }
- classDef->release();
- } else {
- cl->ctpInfo =
- new(classLoader->allocator, def->ctpInfo->ctpSize) UserConstantPool(cl);
- release();
- status = classRead,
- cl->loadParents();
- status = resolved;
- broadcastClass();
- }
- }
- release();
- } else {
- while (status < resolved) {
- waitClass();
- }
- release();
- }
- }
-}
-
-UserClass* UserCommonClass::lookupClassFromMethod(JavaMethod* meth) {
- UserClass* res = 0;
- lookupMethodDontThrow(meth->name, meth->type,
- isStatic(meth->access), true, res);
- return res;
-}
-
-UserCommonClass* UserCommonClass::getUserClass(CommonClass* cl) {
- fprintf(stderr, "implement me");
- abort();
- return 0;
-}
-
-
-UserCommonClass* UserConstantPool::isClassLoaded(uint32 entry) {
- JavaConstantPool* ctpInfo = getSharedPool();
- if (! ((entry > 0) && (entry < ctpInfo->ctpSize) &&
- ctpInfo->typeAt(entry) == JavaConstantPool::ConstantClass)) {
- JavaThread::get()->isolate->classFormatError(
- "bad constant pool number for class at entry %d", entry);
- }
- return (UserCommonClass*)ctpRes[entry];
-}
-
-UserCommonClass* UserConstantPool::loadClass(uint32 index) {
- UserCommonClass* temp = isClassLoaded(index);
- if (!temp) {
- JavaConstantPool* ctpInfo = getSharedPool();
- JnjvmClassLoader* loader = getClass()->classLoader;
- const UTF8* name = ctpInfo->UTF8At(ctpInfo->ctpDef[index]);
- if (name->elements[0] == AssessorDesc::I_TAB) {
- temp = loader->constructArray(name);
- temp->resolveClass();
- } else {
- // Put into ctpRes because there is only one representation of the class
- temp = loader->loadName(name, true, false);
- }
- ctpRes[index] = temp;
- ctpInfo->ctpRes[index] = temp->classDef;
- }
- return temp;
-}
-
-void UserConstantPool::resolveMethod(uint32 index, UserCommonClass*& cl,
- const UTF8*& utf8, Signdef*& sign) {
- JavaConstantPool* ctpInfo = getSharedPool();
- sint32 entry = ctpInfo->ctpDef[index];
- sint32 ntIndex = entry & 0xFFFF;
- sign = (Signdef*)ctpInfo->ctpRes[ntIndex];
- assert(sign && "No cached signature after JITting");
- utf8 = ctpInfo->UTF8At(ctpInfo->ctpDef[ntIndex] >> 16);
- cl = loadClass(entry >> 16);
- assert(cl && cl->isResolved() && "No resolved class when resolving method");
-}
-
-void UserConstantPool::resolveField(uint32 index, UserCommonClass*& cl,
- const UTF8*& utf8, Typedef*& sign) {
- JavaConstantPool* ctpInfo = getSharedPool();
- sint32 entry = ctpInfo->ctpDef[index];
- sint32 ntIndex = entry & 0xFFFF;
- sign = (Typedef*)ctpInfo->ctpRes[ntIndex];
- assert(sign && "No cached Typedef after JITting");
- utf8 = ctpInfo->UTF8At(ctpInfo->ctpDef[ntIndex] >> 16);
- cl = loadClass(entry >> 16);
- assert(cl && cl->isResolved() && "No resolved class when resolving field");
-}
-
-void* UserConstantPool::operator new(size_t sz, JavaAllocator* alloc,
- uint32 size){
- return alloc->allocateObject(sz + size * sizeof(void*), VT);
-}
-
-UserClassPrimitive* AssessorDesc::getPrimitiveClass() const {
- Jnjvm* vm = JavaThread::get()->isolate;
- if (numId > VOID_ID && numId < ARRAY_ID) {
- UserClassArray* arrayCl = vm->arrayClasses[numId];
- UserClassPrimitive* cl = (UserClassPrimitive*)arrayCl->_baseClass;
- assert(cl && "Primitive array class does not have a primitive.");
- return cl;
- } else if (numId == VOID_ID) {
- return vm->upcalls->OfVoid;
- }
- return 0;
-}
-
-UserClassArray* AssessorDesc::getArrayClass() const {
- Jnjvm* vm = JavaThread::get()->isolate;
- UserClassArray* arrayCl = vm->arrayClasses[numId];
- return arrayCl;
-}
-
-JavaMethod* UserCommonClass::lookupMethodDontThrow(const UTF8* name,
- const UTF8* type,
- bool isStatic,
- bool recurse,
- UserClass*& methodCl) {
-
- CommonClass::FieldCmp CC(name, type);
- CommonClass::method_map* map = isStatic ? getStaticMethods() :
- getVirtualMethods();
- CommonClass::method_iterator End = map->end();
- CommonClass::method_iterator I = map->find(CC);
- if (I != End) {
- methodCl = (UserClass*)this;
- return I->second;
- }
-
- JavaMethod *cur = 0;
-
- if (recurse) {
- if (super) cur = super->lookupMethodDontThrow(name, type, isStatic,
- recurse, methodCl);
- if (cur) return cur;
-
- if (isStatic) {
- std::vector<UserClass*>* interfaces = getInterfaces();
- for (std::vector<UserClass*>::iterator i = interfaces->begin(),
- e = interfaces->end(); i!= e; i++) {
- cur = (*i)->lookupMethodDontThrow(name, type, isStatic, recurse,
- methodCl);
- if (cur) return cur;
- }
- }
- }
-
- return 0;
-}
-
-JavaMethod* UserCommonClass::lookupMethod(const UTF8* name, const UTF8* type,
- bool isStatic, bool recurse,
- UserClass*& methodCl) {
- JavaMethod* res = lookupMethodDontThrow(name, type, isStatic, recurse,
- methodCl);
- if (!res) {
- JavaThread::get()->isolate->noSuchMethodError(this->classDef, name);
- }
- return res;
-}
-
-JavaField*
-UserCommonClass::lookupFieldDontThrow(const UTF8* name, const UTF8* type,
- bool isStatic, bool recurse,
- UserCommonClass*& definingClass) {
-
- CommonClass::FieldCmp CC(name, type);
- CommonClass::field_map* map = isStatic ? getStaticFields() :
- getVirtualFields();
- CommonClass::field_iterator End = map->end();
- CommonClass::field_iterator I = map->find(CC);
- if (I != End) {
- definingClass = this;
- return I->second;
- }
-
- JavaField *cur = 0;
-
- if (recurse) {
- if (super) cur = super->lookupFieldDontThrow(name, type, isStatic,
- recurse, definingClass);
- if (cur) return cur;
-
- if (isStatic) {
- std::vector<UserClass*>* interfaces = getInterfaces();
- for (std::vector<UserClass*>::iterator i = interfaces->begin(),
- e = interfaces->end(); i!= e; i++) {
- cur = (*i)->lookupFieldDontThrow(name, type, isStatic, recurse,
- definingClass);
- if (cur) return cur;
- }
- }
- }
-
- return 0;
-}
-
-JavaField* UserCommonClass::lookupField(const UTF8* name, const UTF8* type,
- bool isStatic, bool recurse,
- UserCommonClass*& definingClass) {
-
- JavaField* res = lookupFieldDontThrow(name, type, isStatic, recurse,
- definingClass);
- if (!res) {
- JavaThread::get()->isolate->noSuchFieldError(this->classDef, name);
- }
- return res;
-}
-
-void UserConstantPool::print(mvm::PrintBuffer* buf) const {
- buf->write("User constant pool of <");
- getClass()->classDef->print(buf);
- buf->write(">");
-}
-
-void UserCommonClass::print(mvm::PrintBuffer* buf) const {
- buf->write("User class of <");
- classDef->print(buf);
- buf->write(">");
-}
diff --git a/vmkit/lib/J3/Isolate/IsolateCommonClass.h b/vmkit/lib/J3/Isolate/IsolateCommonClass.h
deleted file mode 100644
index 7daa294..0000000
--- a/vmkit/lib/J3/Isolate/IsolateCommonClass.h
+++ /dev/null
@@ -1,439 +0,0 @@
-//===---- IsolateCommonClass.h - User visible classes with isolates -------===//
-//
-// JnJVM
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#ifndef JNJVM_JAVA_CLASS_H
-#error "Never use <IsolateCommonClass.h> directly, but include <JavaClass.h>"
-#endif
-
-#ifndef ISOLATE_COMMON_CLASS_H
-#define ISOLATE_COMMON_CLASS_H
-
-#include "mvm/Object.h"
-
-#include "JavaConstantPool.h"
-
-namespace jnjvm {
-
-class ArrayUInt8;
-class AssessorDesc;
-class CommonClass;
-class Class;
-class ClassArray;
-class ClassPrimitive;
-class JavaConstantPool;
-class JavaField;
-class JavaMethod;
-class JavaObject;
-class Jnjvm;
-class JnjvmClassLoader;
-class UserClass;
-class UserClassArray;
-class UserConstantPool;
-class UTF8;
-enum JavaState;
-
-class UserCommonClass : public mvm::Object {
-public:
-
- //===----------------------------------------------------------------------===//
-//
-// Do not reorder these fields or add new ones! the LLVM runtime assumes that
-// classes have the following beginning layout.
-//
-//===----------------------------------------------------------------------===//
-
-
- /// virtualSize - The size of instances of this class. Array classes do
- /// not need this information, but to simplify accessing this field in
- /// the JIT, we put this in here.
- ///
- uint32 virtualSize;
-
- /// virtualVT - The virtual table of instances of this class. Like the
- /// virtualSize field, array classes do not need this information. But we
- /// simplify JIT generation to set it here.
- ///
- VirtualTable* virtualVT;
-
- /// display - The class hierarchy of supers for this class. Array classes
- /// do not need it.
- ///
- UserCommonClass** display;
-
- /// depth - The depth of this class in its class hierarchy.
- /// display[depth] contains the class. Array classes do not need it.
- ///
- uint32 depth;
-
- /// status - The loading/resolve/initialization state of the class.
- ///
- JavaState status;
-
- /// ctpInfo - The private constant pool of this class.
- ///
- UserConstantPool* ctpInfo;
-
- JavaObject* staticInstance;
-
-//===----------------------------------------------------------------------===//
-//
-// New fields can be added from now, or reordered.
-//
-//===----------------------------------------------------------------------===//
-
- JnjvmClassLoader* classLoader;
- JavaObject* delegatee;
- CommonClass* classDef;
- UserClass* super;
- std::vector<UserClass*> interfaces;
-
- bool inheritName(const UTF8* Tname);
- bool isOfTypeName(const UTF8* name);
- bool isAssignableFrom(UserCommonClass* cl);
-
- /// subclassOf - If this class is a regular class, is it a subclass of the
- /// given class?
- ///
- bool subclassOf(UserCommonClass* cl);
-
- bool isArray() {
- return classDef->isArray();
- }
- bool isPrimitive() {
- return classDef->isPrimitive();
- }
-
- bool isInterface() {
- return classDef->isInterface();
- }
-
- bool isReady() {
- return status >= inClinit;
- }
-
- bool isResolved() {
- return status >= resolved;
- }
-
- uint8 getAccess() {
- return classDef->access;
- }
-
- const UTF8* getName() {
- return classDef->name;
- }
-
- void getDeclaredConstructors(std::vector<JavaMethod*>& res, bool publicOnly) {
- classDef->getDeclaredConstructors(res, publicOnly);
- }
-
- void getDeclaredFields(std::vector<JavaField*>& res, bool publicOnly) {
- classDef->getDeclaredFields(res, publicOnly);
- }
-
- void getDeclaredMethods(std::vector<JavaMethod*>& res, bool publicOnly) {
- classDef->getDeclaredMethods(res, publicOnly);
- }
-
- void initialiseClass(Jnjvm* vm);
- JavaObject* getClassDelegatee(Jnjvm* vm, JavaObject* pd = 0);
-
- void resolveClass();
-
- UserClass* getSuper() {
- return super;
- }
-
- std::vector<UserClass*>* getInterfaces() {
- return &interfaces;
- }
-
- CommonClass::field_map* getStaticFields() {
- return classDef->getStaticFields();
- }
-
- CommonClass::field_map* getVirtualFields() {
- return classDef->getVirtualFields();
- }
-
- CommonClass::method_map* getStaticMethods() {
- return classDef->getStaticMethods();
- }
-
- CommonClass::method_map* getVirtualMethods() {
- return classDef->getVirtualMethods();
- }
-
- void resolveStaticClass() {
- ((Class*)classDef)->resolveStaticClass();
- }
-
-
- JavaMethod* lookupMethodDontThrow(const UTF8* name, const UTF8* type,
- bool isStatic, bool recurse,
- UserClass*& methodCl);
-
- JavaMethod* lookupMethod(const UTF8* name, const UTF8* type,
- bool isStatic, bool recurse, UserClass*& methodCl);
-
- JavaField* lookupField(const UTF8* name, const UTF8* type,
- bool isStatic, bool recurse,
- UserCommonClass*& fieldCl);
-
- JavaField* lookupFieldDontThrow(const UTF8* name, const UTF8* type,
- bool isStatic, bool recurse,
- UserCommonClass*& fieldCl);
-
-
- uint32 getVirtualSize() {
- return virtualSize;
- }
-
- VirtualTable* getVirtualVT() {
- return virtualVT;
- }
-
- void setInterfaces(std::vector<UserClass*> Is) {
- interfaces = Is;
- }
-
- void setSuper(UserClass* S) {
- super = S;
- }
-
- bool instantiationOfArray(UserClassArray* cl);
- bool implements(UserCommonClass* cl);
-
- /// constructMethod - Add a new method in this class method map.
- ///
- JavaMethod* constructMethod(const UTF8* name, const UTF8* type,
- uint32 access) {
- return classDef->constructMethod(name, type, access);
- }
-
- /// constructField - Add a new field in this class field map.
- ///
- JavaField* constructField(const UTF8* name, const UTF8* type,
- uint32 access) {
- return classDef->constructField(name, type, access);
- }
-
-
- UserClass* lookupClassFromMethod(JavaMethod* meth);
- UserCommonClass* getUserClass(CommonClass* cl);
-
- /// lockVar - When multiple threads want to initialize a class,
- /// they must be synchronized so that it is only performed once
- /// for a given class.
- mvm::Lock* lockVar;
-
- /// condVar - Used to wake threads waiting on the initialization
- /// process of this class, done by another thread.
- mvm::Cond* condVar;
-
- /// acquire - Acquire this class lock.
- ///
- void acquire() {
- lockVar->lock();
- }
-
- /// release - Release this class lock.
- ///
- void release() {
- lockVar->unlock();
- }
-
- /// waitClass - Wait for the class to be loaded/initialized/resolved.
- ///
- void waitClass() {
- condVar->wait(lockVar);
- }
-
- /// broadcastClass - Unblock threads that were waiting on the class being
- /// loaded/initialized/resolved.
- ///
- void broadcastClass() {
- condVar->broadcast();
- }
-
- /// ownerClass - Is the current thread the owner of this thread?
- ///
- bool ownerClass() {
- return mvm::Lock::selfOwner(lockVar);
- }
-
- const UTF8* getSuperUTF8(){
- return classDef->superUTF8;
- }
-
- std::vector<const UTF8*>* getInterfacesUTF8(){
- return &classDef->interfacesUTF8;
- }
-
- UserCommonClass();
-
- virtual void print(mvm::PrintBuffer *buf) const;
-};
-
-class UserClass : public UserCommonClass {
-public:
- static VirtualTable* VT;
-
- virtual void TRACER;
-
- UserClass(JnjvmClassLoader* JCL, const UTF8* name, ArrayUInt8* bytes);
- UserClass() {}
-
- JavaObject* doNew(Jnjvm* vm);
-
- std::vector<UserClass*> innerClasses;
- UserClass* outerClass;
-
- std::vector<UserClass*>* getInnerClasses() {
- return &innerClasses;
- }
-
- UserClass* getOuterClass() {
- return outerClass;
- }
-
- bool innerOuterResolved;
-
- void resolveInnerOuterClasses();
-
- void setInnerAccess(uint32 access) {
- ((Class*)classDef)->setInnerAccess(access);
- }
-
- JavaObject* getStaticInstance() {
- return staticInstance;
- }
-
- void setStaticInstance(JavaObject* obj) {
- staticInstance = obj;
- }
-
- UserConstantPool* getConstantPool() {
- return ctpInfo;
- }
-
- uint32 getStaticSize() {
- return ((Class*)classDef)->getStaticSize();
- }
-
- VirtualTable* getStaticVT() {
- return ((Class*)classDef)->getStaticVT();
- }
-
- /// loadParents - Loads and resolves the parents, i.e. super and interfarces,
- /// of the class.
- ///
- void loadParents();
-
- Attribut* lookupAttribut(const UTF8* Att) {
- return ((Class*)classDef)->lookupAttribut(Att);
- }
-
- ArrayUInt8* getBytes() {
- return ((Class*)classDef)->bytes;
- }
-};
-
-class UserClassArray : public UserCommonClass {
-public:
- static VirtualTable* VT;
- UserCommonClass* _baseClass;
- AssessorDesc* _funcs;
-
- virtual void TRACER;
- UserClassArray(JnjvmClassLoader* JCL, const UTF8* name);
- UserClassArray() {}
-
- void resolveComponent();
-
- UserCommonClass* baseClass() {
- if (_baseClass == 0)
- resolveComponent();
- return _baseClass;
- }
-
- AssessorDesc* funcs() {
- if (_funcs == 0)
- resolveComponent();
- return _funcs;
- }
-};
-
-class UserClassPrimitive : public UserCommonClass {
- static VirtualTable* VT;
-public:
-
- virtual void TRACER;
- UserClassPrimitive(JnjvmClassLoader* JCL, const UTF8* name, uint32 nb);
-};
-
-class UserConstantPool : public mvm::Object {
-public:
-
- static VirtualTable* VT;
- /// ctpRes - Objects resolved dynamically, e.g. UTF8s, classes, methods,
- /// fields, strings.
- ///
- void* ctpRes[1];
-
- /// resolveMethod - Resolve the class and the signature of the method. May
- /// perform class loading. This function is called just in time, ie when
- /// the method call is actually made and not yet resolved.
- ///
- void resolveMethod(uint32 index, UserCommonClass*& cl,
- const UTF8*& utf8, Signdef*& sign);
-
- /// resolveField - Resolve the class and signature of the field. May
- /// perform class loading. This function is called just in time, ie when
- /// the field is accessed and not yet resolved.
- ///
- void resolveField(uint32 index, UserCommonClass*& cl, const UTF8*& utf8,
- Typedef*& sign);
-
- UserClass* getClass() const {
- return (UserClass*)ctpRes[0];
- }
-
- JavaConstantPool* getSharedPool() const {
- return ((Class*)(getClass()->classDef))->ctpInfo;
- }
-
- /// UTF8At - Get the UTF8 referenced from this string entry.
- ///
- const UTF8* UTF8AtForString(uint32 entry) const {
- return getSharedPool()->UTF8AtForString(entry);
- }
-
- /// loadClass - Loads the class and returns it. This is called just in time,
- /// ie when the class will be used and not yet resolved.
- ///
- UserCommonClass* loadClass(uint32 index);
-
- void* operator new(size_t sz, JavaAllocator* alloc, uint32 size);
-
- UserConstantPool(){}
-
- UserConstantPool(UserClass* cl) {
- ctpRes[0] = cl;
- }
-
- UserCommonClass* isClassLoaded(uint32 entry);
-
- virtual void print(mvm::PrintBuffer *buf) const;
-
-};
-
-} // end namespace jnjvm
-
-#endif // JNJVM_CLASS_ISOLATE_H
diff --git a/vmkit/lib/J3/Isolate/IsolateSharedLoader.cpp b/vmkit/lib/J3/Isolate/IsolateSharedLoader.cpp
deleted file mode 100644
index 4e8e884..0000000
--- a/vmkit/lib/J3/Isolate/IsolateSharedLoader.cpp
+++ /dev/null
@@ -1,85 +0,0 @@
-//===---- IsolateSharedLoader.cpp - Shared loader for isolates ------------===//
-//
-// JnJVM
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#include "IsolateSharedLoader.h"
-#include "JavaAllocator.h"
-#include "JavaClass.h"
-#include "JnjvmClassLoader.h"
-#include "JnjvmModule.h"
-#include "JnjvmModuleProvider.h"
-#include "LockedMap.h"
-
-using namespace jnjvm;
-
-JnjvmSharedLoader* JnjvmSharedLoader::sharedLoader;
-
-JnjvmSharedLoader* JnjvmSharedLoader::createSharedLoader() {
-
- JnjvmSharedLoader* JCL = gc_new(JnjvmSharedLoader)();
- JCL->TheModule = new JnjvmModule("Bootstrap JnJVM");
- JCL->TheModuleProvider = new JnjvmModuleProvider(JCL->TheModule);
-
- JCL->allocator = new JavaAllocator();
-
- JCL->hashUTF8 = new UTF8Map(JCL->allocator, 0);
- JCL->classes = allocator_new(allocator, ClassMap)();
- JCL->nameClasses = new SharedClassNameMap();
- JCL->byteClasses = allocator_new(allocator, SharedClassByteMap)();
- JCL->javaTypes = new TypeMap();
- JCL->javaSignatures = new SignMap();
-
- return JCL;
-}
-
-Class* JnjvmSharedLoader::constructSharedClass(const UTF8* name,
- ArrayUInt8* bytes) {
- byteClasses->lock->lock();
- SharedClassByteMap::iterator End = byteClasses->map.end();
- SharedClassByteMap::iterator I = byteClasses->map.find(bytes);
- Class* res = 0;
- if (I == End) {
- res = new Class(this, name, bytes);
- byteClasses->map.insert(std::make_pair(bytes, res));
- } else {
- res = ((Class*)(I->second));
- }
- byteClasses->lock->unlock();
- return res;
-}
-
-ClassArray* JnjvmSharedLoader::constructSharedClassArray(const UTF8* name) {
- nameClasses->lock->lock();
- SharedClassNameMap::iterator End = nameClasses->map.end();
- SharedClassNameMap::iterator I = nameClasses->map.find(name);
- ClassArray* res = 0;
- if (I == End) {
- res = new ClassArray(this, name);
- nameClasses->map.insert(std::make_pair(name, res));
- } else {
- res = ((ClassArray*)(I->second));
- }
- nameClasses->lock->unlock();
- return res;
-}
-
-ClassPrimitive*
-JnjvmSharedLoader::constructSharedClassPrimitive(const UTF8* name, uint32 nb) {
- nameClasses->lock->lock();
- SharedClassNameMap::iterator End = nameClasses->map.end();
- SharedClassNameMap::iterator I = nameClasses->map.find(name);
- ClassPrimitive* res = 0;
- if (I == End) {
- res = new ClassPrimitive(this, name, nb);
- nameClasses->map.insert(std::make_pair(name, res));
- } else {
- res = ((ClassPrimitive*)(I->second));
- }
- nameClasses->lock->unlock();
- return res;
-}
diff --git a/vmkit/lib/J3/Isolate/IsolateSharedLoader.h b/vmkit/lib/J3/Isolate/IsolateSharedLoader.h
deleted file mode 100644
index 3c5a47d..0000000
--- a/vmkit/lib/J3/Isolate/IsolateSharedLoader.h
+++ /dev/null
@@ -1,54 +0,0 @@
-//===---- IsolateSharedLoader.h - Shared loader for isolates --------------===//
-//
-// JnJVM
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#ifndef ISOLATE_SHARED_LOADER_H
-#define ISOLATE_SHARED_LOADER_H
-
-#include "JnjvmClassLoader.h"
-#include "SharedMaps.h"
-
-namespace jnjvm {
-
-class JnjvmSharedLoader : public JnjvmClassLoader {
-private:
-
- /// internalLoad - Load the class with the given name.
- ///
- virtual UserClass* internalLoad(const UTF8* utf8) {
- fprintf(stderr, "Don't use me");
- abort();
- }
-
- SharedClassByteMap* byteClasses;
- SharedClassNameMap* nameClasses;
-
-public:
-
- /// VT - The virtual table of this class.
- ///
- static VirtualTable* VT;
-
- virtual void TRACER;
-
- /// constructSharedClass - Create a shared representation of the class.
- /// If two classes have the same name but not the same array of bytes,
- /// raise an exception.
- ///
- Class* constructSharedClass(const UTF8* name, ArrayUInt8* bytes);
- ClassArray* constructSharedClassArray(const UTF8* name);
- ClassPrimitive* constructSharedClassPrimitive(const UTF8* name, uint32 nb);
-
- static JnjvmSharedLoader* createSharedLoader();
-
- static JnjvmSharedLoader* sharedLoader;
-};
-
-} // end namespace jnjvm
-
-#endif //ISOLATE_SHARED_LOADER_H
diff --git a/vmkit/lib/J3/Isolate/Makefile b/vmkit/lib/J3/Isolate/Makefile
deleted file mode 100644
index 45bdbd8..0000000
--- a/vmkit/lib/J3/Isolate/Makefile
+++ /dev/null
@@ -1,14 +0,0 @@
-##===- lib/JnJVM/Classpath/Makefile ------------------------*- Makefile -*-===##
-#
-# The vmkit project
-#
-# This file is distributed under the University of Illinois Open Source
-# License. See LICENSE.TXT for details.
-#
-##===----------------------------------------------------------------------===##
-LEVEL = ../../..
-
-LIBRARYNAME = Isolate
-include $(LEVEL)/Makefile.common
-
-CXX.Flags += -I../VMCore
diff --git a/vmkit/lib/J3/Isolate/SharedMaps.h b/vmkit/lib/J3/Isolate/SharedMaps.h
deleted file mode 100644
index 7325031..0000000
--- a/vmkit/lib/J3/Isolate/SharedMaps.h
+++ /dev/null
@@ -1,61 +0,0 @@
-//===------- SharedMaps.h - Maps for the shared class loader --------------===//
-//
-// JnJVM
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#include "LockedMap.h"
-
-#ifndef ISOLATE_JNJVM_SHARED_MAPS_H
-#define ISOLATE_JNJVM_SHARED_MAPS_H
-
-namespace jnjvm {
-
-
-struct ltarray {
- bool operator()(const ArrayUInt8* a1, const ArrayUInt8* a2) {
- if (a1->size < a2->size) return true;
- else if (a1->size > a2->size) return false;
- else return memcmp((const char*)a1->elements, (const char*)a2->elements,
- a1->size * sizeof(uint8)) < 0;
- }
-};
-
-
-class SharedClassByteMap :
- public LockedMap<const ArrayUInt8*, Class*, ltarray, JnjvmClassLoader* > {
-public:
- static VirtualTable* VT;
-
- SharedClassByteMap() {
- lock = mvm::Lock::allocNormal();
- }
-
- ~SharedClassByteMap() {
- delete lock;
- }
-
- virtual void TRACER;
-};
-
-
-class SharedClassNameMap :
- public LockedMap<const UTF8*, CommonClass*, ltutf8, JnjvmClassLoader* > {
-public:
-
- SharedClassNameMap() {
- lock = mvm::Lock::allocNormal();
- }
-
- ~SharedClassNameMap() {
- delete lock;
- }
-
-};
-
-} // end namespace jnjvm
-
-#endif //ISOLATE_JNJVM_SHARED_MAPS_H
diff --git a/vmkit/lib/J3/Isolate/VirtualTables.cpp b/vmkit/lib/J3/Isolate/VirtualTables.cpp
deleted file mode 100644
index 1ea655f..0000000
--- a/vmkit/lib/J3/Isolate/VirtualTables.cpp
+++ /dev/null
@@ -1,50 +0,0 @@
-//===--- VirtualTables.cpp - Virtual methods for Isolate objects ----------===//
-//
-// The VMKit project
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#include "SharedMaps.h"
-#include "IsolateSharedLoader.h"
-
-using namespace jnjvm;
-
-#define INIT(X) VirtualTable* X::VT = 0
-
- INIT(JnjvmSharedLoader);
- INIT(SharedClassByteMap);
- INIT(UserClass);
- INIT(UserClassArray);
- INIT(UserConstantPool);
-
-#undef INIT
-
-void UserClass::TRACER {
- classLoader->MARK_AND_TRACE;
- delegatee->MARK_AND_TRACE;
- staticInstance->MARK_AND_TRACE;
- ctpInfo->MARK_AND_TRACE;
-}
-
-void UserClassPrimitive::TRACER {
- classLoader->MARK_AND_TRACE;
- delegatee->MARK_AND_TRACE;
-}
-
-void UserClassArray::TRACER {
- classLoader->MARK_AND_TRACE;
- delegatee->MARK_AND_TRACE;
-}
-
-void SharedClassByteMap::TRACER {
- for (iterator i = map.begin(), e = map.end(); i!= e; ++i) {
- i->first->MARK_AND_TRACE;
- }
-}
-
-void JnjvmSharedLoader::TRACER {
- byteClasses->MARK_AND_TRACE;
-}
diff --git a/vmkit/lib/J3/LLVMRuntime/Makefile b/vmkit/lib/J3/LLVMRuntime/Makefile
deleted file mode 100644
index c05f3ff..0000000
--- a/vmkit/lib/J3/LLVMRuntime/Makefile
+++ /dev/null
@@ -1,18 +0,0 @@
-##===- lib/JnJVM/LLVMRuntime/Makefile ----------------------*- Makefile -*-===##
-#
-# The vmkit project
-#
-# This file is distributed under the University of Illinois Open Source
-# License. See LICENSE.TXT for details.
-#
-##===----------------------------------------------------------------------===##
-LEVEL = ../../..
-
-include $(LEVEL)/Makefile.config
-
-VMKIT_RUNTIME = $(PROJ_SRC_DIR)/../../Mvm/Compiler/LLVMRuntime.gen.ll \
- $(PROJ_SRC_DIR)/j3-runtime.ll
-
-BUILT_SOURCES = LLVMRuntime.inc
-
-include $(LEVEL)/Makefile.common
diff --git a/vmkit/lib/J3/LLVMRuntime/j3-runtime.ll b/vmkit/lib/J3/LLVMRuntime/j3-runtime.ll
deleted file mode 100644
index 2a7fa72..0000000
--- a/vmkit/lib/J3/LLVMRuntime/j3-runtime.ll
+++ /dev/null
@@ -1,230 +0,0 @@
-;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
-;;;;;;;;;;;;;;;;;;;;;;;; Type definitions ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
-;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
-
-;;; The root of all Java Objects: a VT and a lock.
-%JavaObject = type { %VT*, i8* }
-
-;;; Types for Java arrays. A size of 0 means an undefined size.
-%JavaArray = type { %JavaObject, i8* }
-%ArrayDouble = type { %JavaObject, i8*, [0 x double] }
-%ArrayFloat = type { %JavaObject, i8*, [0 x float] }
-%ArrayLong = type { %JavaObject, i8*, [0 x i64] }
-%ArrayObject = type { %JavaObject, i8*, [0 x %JavaObject*] }
-%ArraySInt16 = type { %JavaObject, i8*, [0 x i16] }
-%ArraySInt32 = type { %JavaObject, i8*, [0 x i32] }
-%ArraySInt8 = type { %JavaObject, i8*, [0 x i8] }
-%ArrayUInt16 = type { %JavaObject, i8*, [0 x i16] }
-%ArrayUInt32 = type { %JavaObject, i8*, [0 x i32] }
-%ArrayUInt8 = type { %JavaObject, i8*, [0 x i8] }
-
-;;; The task class mirror.
-;;; Field 1: The class state
-;;; Field 2: The initialization state
-;;; Field 3: The static instance
-%TaskClassMirror = type { i8, i1, i8* }
-
-;;; The Java Thread
-;;; Field 1: VMThreadData parent
-;;; Field 2: void* jniEnv
-%JavaThread = type { %VMThreadData, i8* }
-
-%JavaConstantPool = type { %JavaClass*, i32, i8*, i32*, i8** }
-
-%Attribut = type { %UTF8*, i32, i32 }
-
-%UTF8 = type { %JavaObject, i8*, [0 x i16] }
-
-
-%JavaField = type { i8*, i16, %UTF8*, %UTF8*, %Attribut*, i16, %JavaClass*, i32,
- i16 }
-
-%CodeLineInfo = type { i8*, %JavaMethod*, %CodeLineInfo* }
-
-%JavaMethod = type { i8*, i16, %Attribut*, i16, %JavaClass*,
- %UTF8*, %UTF8*, i8, i8*, %CodeLineInfo*, i16, i32 }
-
-%JavaClassPrimitive = type { %JavaCommonClass, i32 }
-%JavaClassArray = type { %JavaCommonClass, %JavaCommonClass* }
-
-%JavaCommonClass = type { [1 x %JavaObject*], i16,
- %JavaClass**, i16, %UTF8*, %JavaClass*, i8*, %VT* }
-
-%JavaClass = type { %JavaCommonClass, i32, i32, [1 x %TaskClassMirror],
- %JavaField*, i16, %JavaField*, i16, %JavaMethod*, i16,
- %JavaMethod*, i16, i8*, %ArrayUInt8*, i8*, %Attribut*,
- i16, %JavaClass**, i16, %JavaClass*, i16, i8, i8, i32, i32 }
-
-;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
-;;;;; Constant calls for Jnjvm runtime internal objects field accesses ;;;;;;;;;
-;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
-
-;;; j3RuntimeInitialiseClass - Initialises the class.
-declare %JavaClass* @j3RuntimeInitialiseClass(%JavaClass*)
-
-;;; arrayLength - Get the length of an array.
-declare i32 @arrayLength(%JavaObject*) readnone
-
-;;; getVT - Get the VT of the object.
-declare %VT* @getVT(%JavaObject*) readnone
-
-;;; getIMT - Get the IMT of the VT.
-declare %VT* @getIMT(%VT*) readnone
-
-;;; getClass - Get the class of an object.
-declare %JavaCommonClass* @getClass(%JavaObject*) readnone
-
-;;; getLock - Get the lock of an object.
-declare i8* @getLock(%JavaObject*)
-
-;;; getVTFromCommonClass - Get the VT of a class from its runtime
-;;; representation.
-declare %VT* @getVTFromCommonClass(%JavaCommonClass*) readnone
-
-;;; getVTFromClass - Get the VT of a class from its runtime representation.
-declare %VT* @getVTFromClass(%JavaClass*) readnone
-
-;;; getVTFromClassArray - Get the VT of an array class from its runtime
-;;; representation.
-declare %VT* @getVTFromClassArray(%JavaClassArray*) readnone
-
-;;; getObjectSizeFromClass - Get the size of a class from its runtime
-;;; representation.
-declare i32 @getObjectSizeFromClass(%JavaClass*) readnone
-
-;;; getBaseClassVTFromVT - Get the VT of the base class of an array, or the
-;;; VT of the array class of a regular class.
-declare %VT* @getBaseClassVTFromVT(%VT*) readnone
-
-;;; getDisplay - Get the display array of this VT.
-declare %VT** @getDisplay(%VT*) readnone
-
-;;; getVTInDisplay - Get the super class at the given offset.
-declare %VT* @getVTInDisplay(%VT**, i32) readnone
-
-;;; getDepth - Get the depth of the VT.
-declare i32 @getDepth(%VT*) readnone
-
-;;; getStaticInstance - Get the static instance of this class.
-declare i8* @getStaticInstance(%JavaClass*) readnone
-
-
-;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
-;;;;;;;;;;;;;;;;;;;;;;;; Generic Runtime methods ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
-;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
-
-;;; j3InterfaceLookup - Used for interface calls.
-declare i8* @j3InterfaceLookup(%JavaClass*, i32, ...)
-
-;;; j3MultiCallNew - Allocate multi-dimensional arrays. This will go to
-;;; allocation specific methods.
-declare %JavaObject* @j3MultiCallNew(%JavaCommonClass*, i32, ...)
-
-;;; initialisationCheck - Checks if the class has been initialized and
-;;; initializes if not. This is used for initialization barriers in an isolate
-;;; environment, and in some specific scenario in a single environment.
-declare %JavaClass* @initialisationCheck(%JavaClass*) readnone
-
-;;; forceInitialisationCheck - Force to check initialization. The difference
-;;; between this function and the initialisationCheck function is that the
-;;; latter is readnone and can thus be removed. This function is removed
-;;; by Jnjvm after the GVN pass, therefore it does not have an actual
-;;; implementation.
-declare void @forceInitialisationCheck(%JavaClass*)
-
-;;; forceLoadedCheck - Force to check if the class was loaded. Since we do
-;;; not want to run Java code in a callback, we have to make sure the class
-;;; of the method that we want to compile is loaded. This is used for
-;;; the invokespecial bytecode.
-declare void @forceLoadedCheck(%JavaCommonClass*)
-
-;;; getConstantPoolAt - Get the value in the constant pool of this class.
-;;; This function is removed by Jnjvm after the GVn pass, therefore it does
-;;; not have an actual implementation.
-declare i8* @getConstantPoolAt(i8* (%JavaClass*, i32, ...)*, i8**,
- %JavaClass*, i32, ...) readnone
-
-;;; j3VirtualTableLookup - Look up the offset in a virtual table of a
-;;; specific function.
-declare i32 @j3VirtualTableLookup(%JavaClass*, i32, i32*, %JavaObject*)
-
-;;; j3ClassLookup - Look up a specific class. The function takes a class and
-;;; an index to lookup in the constant pool and returns and stores it in the
-;;; constant pool cache.
-declare i8* @j3ClassLookup(%JavaClass*, i32, ...)
-
-;;; j3VirtualFieldLookup - Look up a specific virtual field.
-declare i8* @j3VirtualFieldLookup(%JavaClass*, i32, ...)
-
-;;; j3StaticFieldLookup - Look up a specific static field.
-declare i8* @j3StaticFieldLookup(%JavaClass*, i32, ...)
-
-;;; j3StringLookup - Get a pointer on a string.
-declare i8* @j3StringLookup(%JavaClass*, i32, ...) readnone
-
-;;; j3JavaObjectAquire - This function is called when starting a synchronized
-;;; block or method.
-declare void @j3JavaObjectAquire(%JavaObject*)
-
-;;; j3JavaObjectRelease - This function is called when leaving a synchronized
-;;; block or method.
-declare void @j3JavaObjectRelease(%JavaObject*)
-
-;;; isAssignableFrom - Returns if a type is a subtype of another type.
-declare i1 @isAssignableFrom(%VT*, %VT*) readnone
-
-;;; isSecondaryClass - Returns if a type is a secondary super type of
-;;; another type.
-declare i1 @isSecondaryClass(%VT*, %VT*) readnone
-
-;;; getClassDelegatee - Returns the java/lang/Class representation of the
-;;; class. This method is lowered to the GEP to the class delegatee in
-;;; the common class.
-declare %JavaObject* @getClassDelegatee(%JavaCommonClass*)
-
-;;; j3RuntimeDelegatee - Returns the java/lang/Class representation of the
-;;; class. This method is called if the class delegatee has not been created
-;;; yet.
-declare %JavaObject* @j3RuntimeDelegatee(%JavaCommonClass*)
-
-;;; j3GetArrayClass - Get the array user class of the user class.
-declare %VT* @j3GetArrayClass(%JavaClass*, i32, %VT**) readnone
-
-declare i8 @getFinalInt8Field(i8*) readnone
-declare i16 @getFinalInt16Field(i16*) readnone
-declare i32 @getFinalInt32Field(i32*) readnone
-declare i64 @getFinalLongField(i64*) readnone
-declare double @getFinalDoubleField(double*) readnone
-declare float @getFinalFloatField(float*) readnone
-
-declare i8* @j3ResolveVirtualStub(%JavaObject*)
-declare i8* @j3ResolveSpecialStub()
-declare i8* @j3ResolveStaticStub()
-declare i8* @j3ResolveInterface(%JavaObject*, %JavaMethod*, i32)
-
-;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
-;;;;;;;;;;;;;;;;;;;;;;;;;;;;; Exception methods ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
-;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
-
-declare %JavaObject* @j3NullPointerException()
-declare %JavaObject* @j3ClassCastException(%JavaObject*, %JavaCommonClass*)
-declare %JavaObject* @j3IndexOutOfBoundsException(%JavaObject*, i32)
-declare %JavaObject* @j3NegativeArraySizeException(i32)
-declare %JavaObject* @j3OutOfMemoryError(i32)
-declare %JavaObject* @j3StackOverflowError()
-declare %JavaObject* @j3ArrayStoreException(%VT*, %VT*)
-declare %JavaObject* @j3ArithmeticException()
-declare void @j3ThrowException(%JavaObject*)
-declare void @j3ThrowExceptionFromJIT()
-
-declare void @j3EndJNI(i32**)
-declare void @j3StartJNI(i32*, i32**, i8*)
-
-
-;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
-;;;;;;;;;;;;;;;;;;;;;;;;;;;;; Debugging methods ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
-;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
-
-declare void @j3PrintExecution(i32, i32, %JavaMethod*)
-declare void @j3PrintMethodStart(%JavaMethod*)
-declare void @j3PrintMethodEnd(%JavaMethod*)
diff --git a/vmkit/lib/J3/Makefile b/vmkit/lib/J3/Makefile
deleted file mode 100644
index 6f951d6..0000000
--- a/vmkit/lib/J3/Makefile
+++ /dev/null
@@ -1,15 +0,0 @@
-##===- lib/JnJVM/Makefile ----------------------------------*- Makefile -*-===##
-#
-# The vmkit project
-#
-# This file is distributed under the University of Illinois Open Source
-# License. See LICENSE.TXT for details.
-#
-##===----------------------------------------------------------------------===##
-LEVEL = ../..
-
-DIRS = LLVMRuntime VMCore Classpath Compiler
-
-include $(LEVEL)/Makefile.config
-include $(LEVEL)/Makefile.common
-
diff --git a/vmkit/lib/J3/README.txt b/vmkit/lib/J3/README.txt
deleted file mode 100644
index 8fd4b77..0000000
--- a/vmkit/lib/J3/README.txt
+++ /dev/null
@@ -1,29 +0,0 @@
-GNU Classpath
-Current version 0.97.2. Use ecj to compile Classpath.
-
- a - unzip classpath
- tar -xzf classpath-0.97.2
- b - compile classpath
- cd classpath-0.97.2
- ./configure --disable-plugin --disable-examples && make
-
-IMPORTANT: for local use
-cd classpath-x.y/lib;
-ln -s ../native/jni/gtk-peer/.libs/libgtkpeer.so;
-ln -s ../native/jni/gconf-peer/.libs/libgconfpeer.so;
-ln -s ../native/jni/java-io/.libs/libjavaio.so;
-ln -s ../native/jni/java-lang/.libs/libjavalangreflect.so;
-ln -s ../native/jni/java-lang/.libs/libjavalang.so;
-ln -s ../native/jni/java-net/.libs/libjavanet.so;
-ln -s ../native/jni/java-nio/.libs/libjavanio.so;
-ln -s ../native/jni/java-util/.libs/libjavautil.so;
-
-Or for Darwin
-ln -s ../native/jni/gtk-peer/.libs/libgtkpeer.dylib;
-ln -s ../native/jni/gconf-peer/.libs/libgconfpeer.dylib;
-ln -s ../native/jni/java-io/.libs/libjavaio.dylib;
-ln -s ../native/jni/java-lang/.libs/libjavalangreflect.dylib;
-ln -s ../native/jni/java-lang/.libs/libjavalang.dylib;
-ln -s ../native/jni/java-net/.libs/libjavanet.dylib;
-ln -s ../native/jni/java-nio/.libs/libjavanio.dylib;
-ln -s ../native/jni/java-util/.libs/libjavautil.dylib;
diff --git a/vmkit/lib/J3/VMCore/JNIReferences.h b/vmkit/lib/J3/VMCore/JNIReferences.h
deleted file mode 100644
index 5d4e833..0000000
--- a/vmkit/lib/J3/VMCore/JNIReferences.h
+++ /dev/null
@@ -1,91 +0,0 @@
-//===--------- JNIReferences.cpp - Management of JNI references -----------===//
-//
-// The VMKit project
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#ifndef JNI_REFERENCES_H
-#define JNI_REFERENCES_H
-
-#include "mvm/Allocator.h"
-
-namespace j3 {
-
-class JavaObject;
-class JavaThread;
-
-#define MAXIMUM_REFERENCES 100
-
-class JNILocalReferences {
- friend class JavaThread;
-
-private:
- JNILocalReferences* prev;
- uint32_t length;
- mvm::gc* localReferences[MAXIMUM_REFERENCES];
-
-public:
-
- JNILocalReferences() {
- prev = 0;
- length = 0;
- }
-
- mvm::gc** addJNIReference(JavaThread* th, mvm::gc* obj);
-
- void removeJNIReferences(JavaThread* th, uint32_t num);
-
-};
-
-class JNIGlobalReferences {
- friend class Jnjvm;
-
-private:
- JNIGlobalReferences* next;
- JNIGlobalReferences* prev;
- uint32_t length;
- uint32_t count;
- JavaObject* globalReferences[MAXIMUM_REFERENCES];
-
-
-public:
- JNIGlobalReferences() {
- next = 0;
- prev = 0;
- length = 0;
- count = 0;
- }
-
- JavaObject** addJNIReference(JavaObject* obj) {
- llvm_gcroot(obj, 0);
- if (length == MAXIMUM_REFERENCES) {
- if (!next) {
- next = new JNIGlobalReferences();
- next->prev = this;
- }
- return next->addJNIReference(obj);
- } else {
- ++count;
- globalReferences[length] = obj;
- return &globalReferences[length++];
- }
- }
-
- void removeJNIReference(JavaObject** obj) {
- if (((uintptr_t)obj >= (uintptr_t)globalReferences) &&
- ((uintptr_t)obj) < (uintptr_t)(globalReferences + MAXIMUM_REFERENCES)) {
- *obj = 0;
- --count;
- } else {
- assert(next && "No global reference located there");
- next->removeJNIReference(obj);
- }
- }
-};
-
-}
-
-#endif
diff --git a/vmkit/lib/J3/VMCore/JavaAccess.h b/vmkit/lib/J3/VMCore/JavaAccess.h
deleted file mode 100644
index 2b53788..0000000
--- a/vmkit/lib/J3/VMCore/JavaAccess.h
+++ /dev/null
@@ -1,71 +0,0 @@
-//===----------- JavaAccess.h - Java access description -------------------===//
-//
-// The VMKit project
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-//
-// This file defines macros and functions for knowing and checking the access
-// type of Java class, fields or methods.
-//
-//===----------------------------------------------------------------------===//
-
-#ifndef JNJVM_JAVA_ACCESS_H
-#define JNJVM_JAVA_ACCESS_H
-
-namespace j3 {
-
-#define ACC_PUBLIC 0x0001
-#define ACC_PRIVATE 0x0002
-#define ACC_PROTECTED 0x0004
-#define ACC_VIRTUAL 0x0000
-#define ACC_STATIC 0x0008
-#define ACC_FINAL 0x0010
-#define ACC_SYNCHRONIZED 0x0020
-#define ACC_SUPER 0x0020
-#define ACC_VOLATILE 0x0040
-#define ACC_TRANSIENT 0x0080
-#define ACC_NATIVE 0x0100
-#define ACC_INTERFACE 0x0200
-#define ACC_ABSTRACT 0x0400
-#define ACC_STRICT 0x0800
-#define ACC_SYNTHETIC 0x1000
-
-#define JNJVM_CLASS 0x1000
-#define JNJVM_ARRAY 0x2000
-#define JNJVM_PRIMITIVE 0x4000
-
-#define MK_VERIFIER(name, flag) \
- inline bool name(unsigned int param) { \
- return (flag & param) != 0; \
- } \
-
-MK_VERIFIER(isStatic, ACC_STATIC)
-MK_VERIFIER(isNative, ACC_NATIVE)
-MK_VERIFIER(isInterface, ACC_INTERFACE)
-MK_VERIFIER(isSynchro, ACC_SYNCHRONIZED)
-MK_VERIFIER(isPublic, ACC_PUBLIC)
-MK_VERIFIER(isPrivate, ACC_PRIVATE)
-MK_VERIFIER(isAbstract, ACC_ABSTRACT)
-MK_VERIFIER(isProtected, ACC_PROTECTED)
-MK_VERIFIER(isFinal, ACC_FINAL)
-MK_VERIFIER(isSuper, ACC_SUPER)
-MK_VERIFIER(isSynthetic, ACC_SYNTHETIC)
-
-
-inline bool isVirtual(unsigned int param) {
- return !(ACC_STATIC & param);
-}
-
-MK_VERIFIER(isClass, JNJVM_CLASS)
-MK_VERIFIER(isPrimitive, JNJVM_PRIMITIVE)
-MK_VERIFIER(isArray, JNJVM_ARRAY)
-
-
-#undef MK_VERIFIER
-
-} // end namespace j3
-
-#endif
diff --git a/vmkit/lib/J3/VMCore/JavaArray.cpp b/vmkit/lib/J3/VMCore/JavaArray.cpp
deleted file mode 100644
index 827034a..0000000
--- a/vmkit/lib/J3/VMCore/JavaArray.cpp
+++ /dev/null
@@ -1,36 +0,0 @@
-//===----------------- JavaArray.cpp - Java arrays ------------------------===//
-//
-// The VMKit project
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#include <cstdarg>
-#include <cstdlib>
-
-#include "JavaArray.h"
-#include "JavaClass.h"
-#include "JavaObject.h"
-#include "JavaTypes.h"
-#include "Jnjvm.h"
-#include "JavaThread.h"
-#include "JavaUpcalls.h"
-#include "LockedMap.h"
-
-
-using namespace j3;
-
-/// This value is the same value than IBM's JVM.
-const sint32 JavaArray::MaxArraySize = 268435455;
-
-/// The JVM defines constants for referencing arrays of primitive types.
-const unsigned int JavaArray::T_BOOLEAN = 4;
-const unsigned int JavaArray::T_CHAR = 5;
-const unsigned int JavaArray::T_FLOAT = 6;
-const unsigned int JavaArray::T_DOUBLE = 7;
-const unsigned int JavaArray::T_BYTE = 8;
-const unsigned int JavaArray::T_SHORT = 9;
-const unsigned int JavaArray::T_INT = 10;
-const unsigned int JavaArray::T_LONG = 11;
diff --git a/vmkit/lib/J3/VMCore/JavaArray.h b/vmkit/lib/J3/VMCore/JavaArray.h
deleted file mode 100644
index 55f78ae..0000000
--- a/vmkit/lib/J3/VMCore/JavaArray.h
+++ /dev/null
@@ -1,170 +0,0 @@
-//===----------------- JavaArray.h - Java arrays --------------------------===//
-//
-// The VMKit project
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-//
-// This file defines the internal representation of Java arrays.
-//
-//===----------------------------------------------------------------------===//
-
-#ifndef JNJVM_JAVA_ARRAY_H
-#define JNJVM_JAVA_ARRAY_H
-
-#include "mvm/Allocator.h"
-
-#include "types.h"
-
-#include "JavaObject.h"
-
-#include "UTF8.h"
-
-namespace j3 {
-
-class ClassArray;
-class CommonClass;
-class JavaObject;
-class Jnjvm;
-
-/// TJavaArray - Template class to be instantiated by real arrays. All arrays
-/// have a constant size and an array of element. When JnJVM allocates an
-/// instantiation of this class, it allocates with the actual size of this
-/// array. Hence instantiation of TJavaArrays have a layout of
-/// {JavaObject, size, [0 * T]}.
-template <class T>
-class TJavaArray : public JavaObject {
-public:
- /// size - The (constant) size of the array.
- ssize_t size;
-
- /// elements - Elements of this array. The size here is different than the
- /// actual size of the Java array. This is to facilitate Java array accesses
- /// in JnJVM code. The size should be set to zero, but this is invalid C99.
- T elements[1];
-
-public:
- static int32_t getSize(const TJavaArray* self) {
- llvm_gcroot(self, 0);
- return self->size;
- }
-
- static T getElement(const TJavaArray* self, uint32_t i) {
- llvm_gcroot(self, 0);
- return self->elements[i];
- }
-
- static void setElement(TJavaArray* self, T value, uint32_t i) {
- llvm_gcroot(self, 0);
- self->elements[i] = value;
- }
-
- static const T* getElements(const TJavaArray* self) {
- llvm_gcroot(self, 0);
- return self->elements;
- }
-
- static T* getElements(TJavaArray* self) {
- llvm_gcroot(self, 0);
- return self->elements;
- }
-
- friend class JavaArray;
-};
-
-class ArrayObject : public JavaObject {
-public:
- /// size - The (constant) size of the array.
- ssize_t size;
-
- /// elements - Elements of this array. The size here is different than the
- /// actual size of the Java array. This is to facilitate Java array accesses
- /// in JnJVM code. The size should be set to zero, but this is invalid C99.
- JavaObject* elements[1];
-
-public:
- static int32_t getSize(const ArrayObject* self) {
- llvm_gcroot(self, 0);
- return self->size;
- }
-
- static JavaObject* getElement(const ArrayObject* self, uint32_t i) {
- llvm_gcroot(self, 0);
- return self->elements[i];
- }
-
- static void setElement(ArrayObject* self, JavaObject* value, uint32_t i) {
- llvm_gcroot(self, 0);
- llvm_gcroot(value, 0);
- if (value != NULL) assert(value->getVirtualTable());
- self->elements[i] = value;
- }
-
- static JavaObject** getElements(ArrayObject* self) {
- llvm_gcroot(self, 0);
- return self->elements;
- }
-};
-
-/// Instantiation of the TJavaArray class for Java arrays.
-#define ARRAYCLASS(name, elmt) \
- class name : public TJavaArray<elmt> { \
- }
-
-ARRAYCLASS(ArrayUInt8, uint8);
-ARRAYCLASS(ArraySInt8, sint8);
-ARRAYCLASS(ArrayUInt16, uint16);
-ARRAYCLASS(ArraySInt16, sint16);
-ARRAYCLASS(ArrayUInt32, uint32);
-ARRAYCLASS(ArraySInt32, sint32);
-ARRAYCLASS(ArrayLong, sint64);
-ARRAYCLASS(ArrayFloat, float);
-ARRAYCLASS(ArrayDouble, double);
-ARRAYCLASS(ArrayPtr, void*);
-
-#undef ARRAYCLASS
-
-/// JavaArray - This class is just a placeholder for constants.
-class JavaArray {
-public:
- /// MaxArraySize - The maximum size a Java array can have. Allocating an
- /// array with a bigger size than MaxArraySize raises an out of memory
- /// error.
- static const sint32 MaxArraySize;
-
- /// JVM representation of Java arrays of primitive types.
- static const unsigned int T_BOOLEAN;
- static const unsigned int T_CHAR;
- static const unsigned int T_FLOAT;
- static const unsigned int T_DOUBLE;
- static const unsigned int T_BYTE;
- static const unsigned int T_SHORT;
- static const unsigned int T_INT;
- static const unsigned int T_LONG;
-
- static void setSize(JavaObject* array, int size) {
- llvm_gcroot(array, 0);
- ((ArrayUInt8*)array)->size = size;
- }
-
- static sint32 getSize(const JavaObject* array) {
- llvm_gcroot(array, 0);
- return ((const ArrayUInt8*)array)->size;
- }
-
- static const unsigned char* getElements(const JavaObject* array) {
- llvm_gcroot(array, 0);
- return ((const ArrayUInt8*)array)->elements;
- }
-
- static unsigned char* getElements(JavaObject* array) {
- llvm_gcroot(array, 0);
- return ((ArrayUInt8*)array)->elements;
- }
-};
-
-} // end namespace j3
-
-#endif
diff --git a/vmkit/lib/J3/VMCore/JavaClass.cpp b/vmkit/lib/J3/VMCore/JavaClass.cpp
deleted file mode 100644
index 6ad8b52..0000000
--- a/vmkit/lib/J3/VMCore/JavaClass.cpp
+++ /dev/null
@@ -1,1788 +0,0 @@
-//===-------- JavaClass.cpp - Java class representation -------------------===//
-//
-// The VMKit project
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#define JNJVM_LOAD 0
-
-#include "debug.h"
-#include "types.h"
-
-#include "ClasspathReflect.h"
-#include "JavaArray.h"
-#include "JavaClass.h"
-#include "JavaCompiler.h"
-#include "JavaConstantPool.h"
-#include "JavaObject.h"
-#include "JavaThread.h"
-#include "JavaTypes.h"
-#include "JavaUpcalls.h"
-#include "Jnjvm.h"
-#include "LockedMap.h"
-#include "Reader.h"
-
-#include <cstring>
-
-using namespace j3;
-
-const UTF8* Attribut::annotationsAttribut = 0;
-const UTF8* Attribut::codeAttribut = 0;
-const UTF8* Attribut::exceptionsAttribut = 0;
-const UTF8* Attribut::constantAttribut = 0;
-const UTF8* Attribut::lineNumberTableAttribut = 0;
-const UTF8* Attribut::innerClassesAttribut = 0;
-const UTF8* Attribut::sourceFileAttribut = 0;
-
-Class* ClassArray::SuperArray;
-Class** ClassArray::InterfacesArray;
-
-extern "C" void JavaObjectTracer(JavaObject*);
-extern "C" void ArrayObjectTracer(JavaObject*);
-extern "C" void RegularObjectTracer(JavaObject*);
-extern "C" void ReferenceObjectTracer(JavaObject*);
-
-Attribut::Attribut(const UTF8* name, uint32 length,
- uint32 offset) {
-
- this->start = offset;
- this->nbb = length;
- this->name = name;
-}
-
-Attribut* Class::lookupAttribut(const UTF8* key ) {
- for (uint32 i = 0; i < nbAttributs; ++i) {
- Attribut* cur = &(attributs[i]);
- if (cur->name->equals(key)) return cur;
- }
-
- return 0;
-}
-
-Attribut* JavaField::lookupAttribut(const UTF8* key ) {
- for (uint32 i = 0; i < nbAttributs; ++i) {
- Attribut* cur = &(attributs[i]);
- if (cur->name->equals(key)) return cur;
- }
-
- return 0;
-}
-
-Attribut* JavaMethod::lookupAttribut(const UTF8* key ) {
- for (uint32 i = 0; i < nbAttributs; ++i) {
- Attribut* cur = &(attributs[i]);
- if (cur->name->equals(key)) return cur;
- }
-
- return 0;
-}
-
-CommonClass::~CommonClass() {
-}
-
-Class::~Class() {
- for (uint32 i = 0; i < nbAttributs; ++i) {
- Attribut* cur = &(attributs[i]);
- cur->~Attribut();
- classLoader->allocator.Deallocate(cur);
- }
-
- for (uint32 i = 0; i < nbStaticFields; ++i) {
- JavaField* cur = &(staticFields[i]);
- cur->~JavaField();
- classLoader->allocator.Deallocate(cur);
- }
-
- for (uint32 i = 0; i < nbVirtualFields; ++i) {
- JavaField* cur = &(virtualFields[i]);
- cur->~JavaField();
- classLoader->allocator.Deallocate(cur);
- }
-
- for (uint32 i = 0; i < nbVirtualMethods; ++i) {
- JavaMethod* cur = &(virtualMethods[i]);
- cur->~JavaMethod();
- classLoader->allocator.Deallocate(cur);
- }
-
- for (uint32 i = 0; i < nbStaticMethods; ++i) {
- JavaMethod* cur = &(staticMethods[i]);
- cur->~JavaMethod();
- classLoader->allocator.Deallocate(cur);
- }
-
- if (ctpInfo) {
- ctpInfo->~JavaConstantPool();
- classLoader->allocator.Deallocate(ctpInfo);
- }
-
- classLoader->allocator.Deallocate(IsolateInfo);
-
- // Currently, only regular classes have a heap allocated virtualVT.
- // Array classes have a C++ allocated virtualVT and primitive classes
- // do not have a virtualVT.
- classLoader->allocator.Deallocate(virtualVT);
-}
-
-JavaField::~JavaField() {
- for (uint32 i = 0; i < nbAttributs; ++i) {
- Attribut* cur = &(attributs[i]);
- cur->~Attribut();
- classDef->classLoader->allocator.Deallocate(cur);
- }
-}
-
-JavaMethod::~JavaMethod() {
-
- for (uint32 i = 0; i < nbAttributs; ++i) {
- Attribut* cur = &(attributs[i]);
- cur->~Attribut();
- classDef->classLoader->allocator.Deallocate(cur);
- }
-
-}
-
-UserClassPrimitive* CommonClass::toPrimitive() const {
- Jnjvm* vm = classLoader->vm;
- if (this == vm->upcalls->voidClass) {
- return vm->upcalls->OfVoid;
- } else if (this == vm->upcalls->intClass) {
- return vm->upcalls->OfInt;
- } else if (this == vm->upcalls->shortClass) {
- return vm->upcalls->OfShort;
- } else if (this == vm->upcalls->charClass) {
- return vm->upcalls->OfChar;
- } else if (this == vm->upcalls->doubleClass) {
- return vm->upcalls->OfDouble;
- } else if (this == vm->upcalls->byteClass) {
- return vm->upcalls->OfByte;
- } else if (this == vm->upcalls->boolClass) {
- return vm->upcalls->OfBool;
- } else if (this == vm->upcalls->longClass) {
- return vm->upcalls->OfLong;
- } else if (this == vm->upcalls->floatClass) {
- return vm->upcalls->OfFloat;
- } else {
- return 0;
- }
-}
-
-
-UserClassPrimitive*
-ClassPrimitive::byteIdToPrimitive(char id, Classpath* upcalls) {
- switch (id) {
- case I_FLOAT :
- return upcalls->OfFloat;
- case I_INT :
- return upcalls->OfInt;
- case I_SHORT :
- return upcalls->OfShort;
- case I_CHAR :
- return upcalls->OfChar;
- case I_DOUBLE :
- return upcalls->OfDouble;
- case I_BYTE :
- return upcalls->OfByte;
- case I_BOOL :
- return upcalls->OfBool;
- case I_LONG :
- return upcalls->OfLong;
- case I_VOID :
- return upcalls->OfVoid;
- default :
- return 0;
- }
-}
-
-CommonClass::CommonClass(JnjvmClassLoader* loader, const UTF8* n) {
- name = n;
- classLoader = loader;
- nbInterfaces = 0;
- interfaces = 0;
- access = 0;
- super = 0;
- memset(delegatee, 0, sizeof(JavaObject*) * NR_ISOLATES);
-}
-
-ClassPrimitive::ClassPrimitive(JnjvmClassLoader* loader, const UTF8* n,
- uint32 nb) :
- CommonClass(loader, n) {
-
- uint32 size = JavaVirtualTable::getBaseSize();
- virtualVT = new(loader->allocator, size) JavaVirtualTable(this);
- access = ACC_ABSTRACT | ACC_FINAL | ACC_PUBLIC | JNJVM_PRIMITIVE;
- logSize = nb;
-}
-
-Class::Class(JnjvmClassLoader* loader, const UTF8* n, ClassBytes* B) :
- CommonClass(loader, n) {
- virtualVT = 0;
- bytes = B;
- super = 0;
- ctpInfo = 0;
- outerClass = 0;
- innerOuterResolved = false;
- nbInnerClasses = 0;
- nbVirtualMethods = 0;
- nbStaticMethods = 0;
- nbStaticFields = 0;
- nbVirtualFields = 0;
- virtualMethods = 0;
- staticMethods = 0;
- virtualFields = 0;
- staticFields = 0;
- ownerClass = 0;
- innerAccess = 0;
- access = JNJVM_CLASS;
- memset(IsolateInfo, 0, sizeof(TaskClassMirror) * NR_ISOLATES);
-}
-
-ClassArray::ClassArray(JnjvmClassLoader* loader, const UTF8* n,
- UserCommonClass* base) : CommonClass(loader, n) {
- _baseClass = base;
- super = ClassArray::SuperArray;
- interfaces = ClassArray::InterfacesArray;
- nbInterfaces = 2;
-
- uint32 size = JavaVirtualTable::getBaseSize();
- virtualVT = new(loader->allocator, size) JavaVirtualTable(this);
-
- access = ACC_FINAL | ACC_ABSTRACT | ACC_PUBLIC | JNJVM_ARRAY;
-}
-
-JavaObject* UserClassArray::doNew(sint32 n) {
- JavaObject* res = NULL;
- llvm_gcroot(res, 0);
- if (n < 0) {
- classLoader->vm->negativeArraySizeException(n);
- } else if (n > JavaArray::MaxArraySize) {
- classLoader->vm->outOfMemoryError();
- }
- UserCommonClass* cl = baseClass();
- uint32 logSize = cl->isPrimitive() ?
- cl->asPrimitiveClass()->logSize : (sizeof(JavaObject*) == 8 ? 3 : 2);
- mvm::VirtualTable* VT = virtualVT;
- uint32 size = sizeof(JavaObject) + sizeof(ssize_t) + (n << logSize);
- res = (JavaObject*)mvm::gc::operator new(size, VT);
- JavaArray::setSize(res, n);
- return res;
-}
-
-void* JavaMethod::compiledPtr() {
- if (code != 0)
- return code;
- else
- code = classDef->classLoader->getCompiler()->materializeFunction(this);
-
- return code;
-}
-
-void JavaMethod::setNative() {
- access |= ACC_NATIVE;
-}
-
-void JavaVirtualTable::setNativeTracer(uintptr_t ptr, const char* name) {
- tracer = ptr;
-}
-
-void JavaVirtualTable::setNativeDestructor(uintptr_t ptr, const char* name) {
- if (!cl->classLoader->getCompiler()->isStaticCompiling()) {
- destructor = ptr;
- operatorDelete = ptr;
- }
-}
-
-JavaMethod* Class::lookupInterfaceMethodDontThrow(const UTF8* name,
- const UTF8* type) {
- JavaMethod* cur = lookupMethodDontThrow(name, type, false, false, 0);
- if (cur == NULL) {
- for (uint16 i = 0; i < nbInterfaces; ++i) {
- Class* I = interfaces[i];
- cur = I->lookupInterfaceMethodDontThrow(name, type);
- if (cur) return cur;
- }
- }
- if (cur == NULL && super != NULL) {
- cur = super->lookupInterfaceMethodDontThrow(name, type);
- }
- return cur;
-}
-
-JavaMethod* Class::lookupSpecialMethodDontThrow(const UTF8* name,
- const UTF8* type,
- Class* current) {
- JavaMethod* meth = lookupMethodDontThrow(name, type, false, true, NULL);
-
- if (meth &&
- isSuper(current->access) &&
- current != meth->classDef &&
- meth->classDef->isAssignableFrom(current) &&
- !name->equals(classLoader->vm->upcalls->initName)) {
- meth = current->super->lookupMethodDontThrow(name, type, false, true, NULL);
- }
-
- return meth;
-}
-
-JavaMethod* Class::lookupMethodDontThrow(const UTF8* name, const UTF8* type,
- bool isStatic, bool recurse,
- Class** methodCl) {
-
- JavaMethod* methods = 0;
- uint32 nb = 0;
- if (isStatic) {
- methods = getStaticMethods();
- nb = nbStaticMethods;
- } else {
- methods = getVirtualMethods();
- nb = nbVirtualMethods;
- }
-
- for (uint32 i = 0; i < nb; ++i) {
- JavaMethod& res = methods[i];
- if (res.name->equals(name) && res.type->equals(type)) {
- if (methodCl) *methodCl = (Class*)this;
- return &res;
- }
- }
-
- JavaMethod *cur = 0;
-
- if (recurse) {
- if (super) cur = super->lookupMethodDontThrow(name, type, isStatic,
- recurse, methodCl);
- if (cur) return cur;
- if (isStatic) {
- for (uint16 i = 0; i < nbInterfaces; ++i) {
- Class* I = interfaces[i];
- cur = I->lookupMethodDontThrow(name, type, isStatic, recurse,
- methodCl);
- if (cur) return cur;
- }
- }
- }
-
- return 0;
-}
-
-JavaMethod* Class::lookupMethod(const UTF8* name, const UTF8* type,
- bool isStatic, bool recurse,
- Class** methodCl) {
- JavaMethod* res = lookupMethodDontThrow(name, type, isStatic, recurse,
- methodCl);
- if (!res) {
- classLoader->vm->noSuchMethodError(this, name);
- }
- return res;
-}
-
-JavaMethod* Class::lookupInterfaceMethod(const UTF8* name, const UTF8* type) {
- JavaMethod* res = lookupInterfaceMethodDontThrow(name, type);
-
- if (!res) {
- classLoader->vm->noSuchMethodError(this, name);
- }
- return res;
-}
-
-JavaField*
-Class::lookupFieldDontThrow(const UTF8* name, const UTF8* type,
- bool isStatic, bool recurse,
- Class** definingClass) {
- JavaField* fields = 0;
- uint32 nb = 0;
- if (isStatic) {
- fields = getStaticFields();
- nb = nbStaticFields;
- } else {
- fields = getVirtualFields();
- nb = nbVirtualFields;
- }
-
- for (uint32 i = 0; i < nb; ++i) {
- JavaField& res = fields[i];
- if (res.name->equals(name) && res.type->equals(type)) {
- if (definingClass) *definingClass = this;
- return &res;
- }
- }
-
- JavaField *cur = 0;
-
- if (recurse) {
- if (super) cur = super->lookupFieldDontThrow(name, type, isStatic,
- recurse, definingClass);
- if (cur) return cur;
- if (isStatic) {
- for (uint16 i = 0; i < nbInterfaces; ++i) {
- Class* I = interfaces[i];
- cur = I->lookupFieldDontThrow(name, type, isStatic, recurse,
- definingClass);
- if (cur) return cur;
- }
- }
- }
-
- return 0;
-}
-
-JavaField* Class::lookupField(const UTF8* name, const UTF8* type,
- bool isStatic, bool recurse,
- Class** definingClass) {
-
- JavaField* res = lookupFieldDontThrow(name, type, isStatic, recurse,
- definingClass);
- if (!res) {
- classLoader->vm->noSuchFieldError(this, name);
- }
- return res;
-}
-
-JavaObject* UserClass::doNew() {
- JavaObject* res = NULL;
- llvm_gcroot(res, 0);
- assert(this && "No class when allocating.");
- assert((this->isInitializing() ||
- classLoader->getCompiler()->isStaticCompiling() ||
- this == classLoader->bootstrapLoader->upcalls->newClass)
- && "Uninitialized class when allocating.");
- assert(getVirtualVT() && "No VT\n");
- res = (JavaObject*)mvm::gc::operator new(getVirtualSize(), getVirtualVT());
-
- return res;
-}
-
-bool UserCommonClass::inheritName(const uint16* buf, uint32 len) {
- if (getName()->equals(buf, len)) {
- return true;
- } else if (isPrimitive()) {
- return false;
- } else if (super) {
- if (getSuper()->inheritName(buf, len)) return true;
- }
-
- for (uint32 i = 0; i < nbInterfaces; ++i) {
- if (interfaces[i]->inheritName(buf, len)) return true;
- }
- return false;
-}
-
-bool UserCommonClass::isOfTypeName(const UTF8* Tname) {
- if (inheritName(Tname->elements, Tname->size)) {
- return true;
- } else if (isArray()) {
- UserCommonClass* curS = this;
- uint32 prof = 0;
- uint32 len = Tname->size;
- bool res = true;
-
- while (res && Tname->elements[prof] == I_TAB) {
- UserCommonClass* cl = ((UserClassArray*)curS)->baseClass();
- ++prof;
- if (cl->isClass()) cl->asClass()->resolveClass();
- res = curS->isArray() && cl && (prof < len);
- curS = cl;
- }
-
- return (Tname->elements[prof] == I_REF) &&
- (res && curS->inheritName(&(Tname->elements[prof + 1]), len - 1));
- } else {
- return false;
- }
-}
-
-bool UserCommonClass::isAssignableFrom(UserCommonClass* cl) {
- assert(virtualVT && cl->virtualVT);
- return virtualVT->isSubtypeOf(cl->virtualVT);
-}
-
-bool JavaVirtualTable::isSubtypeOf(JavaVirtualTable* otherVT) {
-
- assert(this);
- assert(otherVT);
- if (otherVT == ((JavaVirtualTable**)this)[otherVT->offset]) return true;
- else if (otherVT->offset != getCacheIndex()) return false;
- else if (this == otherVT) return true;
- else {
- for (uint32 i = 0; i < nbSecondaryTypes; ++i) {
- if (secondaryTypes[i] == otherVT) {
- cache = otherVT;
- return true;
- }
- }
- }
- return false;
-}
-
-void JavaField::InitNullStaticField() {
-
- Typedef* type = getSignature();
- void* obj = classDef->getStaticInstance();
- if (!type->isPrimitive()) {
- ((JavaObject**)((uint64)obj + ptrOffset))[0] = NULL;
- return;
- }
-
- PrimitiveTypedef* prim = (PrimitiveTypedef*)type;
- if (prim->isLong()) {
- ((sint64*)((uint64)obj + ptrOffset))[0] = 0;
- } else if (prim->isInt()) {
- ((sint32*)((uint64)obj + ptrOffset))[0] = 0;
- } else if (prim->isChar()) {
- ((uint16*)((uint64)obj + ptrOffset))[0] = 0;
- } else if (prim->isShort()) {
- ((sint16*)((uint64)obj + ptrOffset))[0] = 0;
- } else if (prim->isByte()) {
- ((sint8*)((uint64)obj + ptrOffset))[0] = 0;
- } else if (prim->isBool()) {
- ((uint8*)((uint64)obj + ptrOffset))[0] = 0;
- } else if (prim->isDouble()) {
- ((double*)((uint64)obj + ptrOffset))[0] = 0.0;
- } else if (prim->isFloat()) {
- ((float*)((uint64)obj + ptrOffset))[0] = 0.0;
- } else {
- abort();
- }
-}
-
-void JavaField::InitStaticField(uint64 val) {
- Typedef* type = getSignature();
- void* obj = classDef->getStaticInstance();
- assert(type->isPrimitive() && "Non primitive field");
- PrimitiveTypedef* prim = (PrimitiveTypedef*)type;
- if (prim->isLong()) {
- ((sint64*)((uint64)obj + ptrOffset))[0] = val;
- } else if (prim->isInt()) {
- ((sint32*)((uint64)obj + ptrOffset))[0] = (sint32)val;
- } else if (prim->isChar()) {
- ((uint16*)((uint64)obj + ptrOffset))[0] = (uint16)val;
- } else if (prim->isShort()) {
- ((sint16*)((uint64)obj + ptrOffset))[0] = (sint16)val;
- } else if (prim->isByte()) {
- ((sint8*)((uint64)obj + ptrOffset))[0] = (sint8)val;
- } else if (prim->isBool()) {
- ((uint8*)((uint64)obj + ptrOffset))[0] = (uint8)val;
- } else {
- // Should never be here.
- abort();
- }
-}
-
-void JavaField::InitStaticField(JavaObject* val) {
- llvm_gcroot(val, 0);
- void* obj = classDef->getStaticInstance();
- ((JavaObject**)((uint64)obj + ptrOffset))[0] = val;
-}
-
-void JavaField::InitStaticField(double val) {
- void* obj = classDef->getStaticInstance();
- ((double*)((uint64)obj + ptrOffset))[0] = val;
-}
-
-void JavaField::InitStaticField(float val) {
- void* obj = classDef->getStaticInstance();
- ((float*)((uint64)obj + ptrOffset))[0] = val;
-}
-
-void JavaField::InitStaticField() {
- const Typedef* type = getSignature();
- Attribut* attribut = lookupAttribut(Attribut::constantAttribut);
-
- if (!attribut) {
- InitNullStaticField();
- } else {
- Reader reader(attribut, classDef->bytes);
- JavaConstantPool * ctpInfo = classDef->ctpInfo;
- uint16 idx = reader.readU2();
- if (type->isPrimitive()) {
- Jnjvm* vm = classDef->classLoader->vm;
- UserCommonClass* cl = type->assocClass(vm->bootstrapLoader);
- if (cl == vm->upcalls->OfLong) {
- InitStaticField((uint64)ctpInfo->LongAt(idx));
- } else if (cl == vm->upcalls->OfDouble) {
- InitStaticField(ctpInfo->DoubleAt(idx));
- } else if (cl == vm->upcalls->OfFloat) {
- InitStaticField(ctpInfo->FloatAt(idx));
- } else {
- InitStaticField((uint64)ctpInfo->IntegerAt(idx));
- }
- } else if (type->isReference()){
- const UTF8* utf8 = ctpInfo->UTF8At(ctpInfo->ctpDef[idx]);
- InitStaticField((JavaObject*)ctpInfo->resolveString(utf8, idx));
- } else {
- fprintf(stderr, "I haven't verified your class file and it's malformed:"
- " unknown constant %s!\n",
- UTF8Buffer(type->keyName).cString());
- abort();
- }
- }
-}
-
-void* UserClass::allocateStaticInstance() {
-#ifdef USE_GC_BOEHM
- void* val = GC_MALLOC(getStaticSize());
-#else
- void* val = classLoader->allocator.Allocate(getStaticSize(),
- "Static instance");
-#endif
- setStaticInstance(val);
- return val;
-}
-
-
-void JavaMethod::initialise(Class* cl, const UTF8* N, const UTF8* T, uint16 A) {
- name = N;
- type = T;
- classDef = cl;
- _signature = 0;
- code = 0;
- access = A;
- canBeInlined = false;
- offset = 0;
- codeInfo = NULL;
-}
-
-void JavaField::initialise(Class* cl, const UTF8* N, const UTF8* T, uint16 A) {
- name = N;
- type = T;
- classDef = cl;
- _signature = 0;
- ptrOffset = 0;
- access = A;
-}
-
-void Class::readParents(Reader& reader) {
- uint16 superEntry = reader.readU2();
- if (superEntry) {
- const UTF8* superUTF8 = ctpInfo->resolveClassName(superEntry);
- super = classLoader->loadName(superUTF8, false, true, NULL);
- }
-
- uint16 nbI = reader.readU2();
-
- interfaces = (Class**)
- classLoader->allocator.Allocate(nbI * sizeof(Class*), "Interfaces");
-
- // Do not set nbInterfaces yet, we may be interrupted by the GC
- // in anon-cooperative environment.
- for (int i = 0; i < nbI; i++) {
- const UTF8* name = ctpInfo->resolveClassName(reader.readU2());
- interfaces[i] = classLoader->loadName(name, false, true, NULL);
- }
- nbInterfaces = nbI;
-
-}
-
-void internalLoadExceptions(JavaMethod& meth) {
-
- Attribut* codeAtt = meth.lookupAttribut(Attribut::codeAttribut);
-
- if (codeAtt) {
- Reader reader(codeAtt, meth.classDef->bytes);
- //uint16 maxStack =
- reader.readU2();
- //uint16 maxLocals =
- reader.readU2();
- uint16 codeLen = reader.readU4();
-
- reader.seek(codeLen, Reader::SeekCur);
-
- uint16 nbe = reader.readU2();
- for (uint16 i = 0; i < nbe; ++i) {
- //startpc =
- reader.readU2();
- //endpc=
- reader.readU2();
- //handlerpc =
- reader.readU2();
-
- uint16 catche = reader.readU2();
- if (catche) meth.classDef->ctpInfo->loadClass(catche, false);
- }
- }
-}
-
-void UserClass::loadExceptions() {
- for (uint32 i = 0; i < nbVirtualMethods; ++i)
- internalLoadExceptions(virtualMethods[i]);
-
- for (uint32 i = 0; i < nbStaticMethods; ++i)
- internalLoadExceptions(staticMethods[i]);
-}
-
-Attribut* Class::readAttributs(Reader& reader, uint16& size) {
- uint16 nba = reader.readU2();
-
- Attribut* attributs = new(classLoader->allocator, "Attributs") Attribut[nba];
-
- for (int i = 0; i < nba; i++) {
- const UTF8* attName = ctpInfo->UTF8At(reader.readU2());
- uint32 attLen = reader.readU4();
- Attribut& att = attributs[i];
- att.start = reader.cursor;
- att.nbb = attLen;
- att.name = attName;
- reader.seek(attLen, Reader::SeekCur);
- }
-
- size = nba;
- return attributs;
-}
-
-void Class::readFields(Reader& reader) {
- uint16 nbFields = reader.readU2();
- virtualFields = new (classLoader->allocator, "Fields") JavaField[nbFields];
- staticFields = virtualFields + nbFields;
- for (int i = 0; i < nbFields; i++) {
- uint16 access = reader.readU2();
- const UTF8* name = ctpInfo->UTF8At(reader.readU2());
- const UTF8* type = ctpInfo->UTF8At(reader.readU2());
- JavaField* field = 0;
- if (isStatic(access)) {
- --staticFields;
- field = &(staticFields[0]);
- field->initialise(this, name, type, access);
- ++nbStaticFields;
- } else {
- field = &(virtualFields[nbVirtualFields]);
- field->initialise(this, name, type, access);
- ++nbVirtualFields;
- }
- field->attributs = readAttributs(reader, field->nbAttributs);
- }
-}
-
-void Class::fillIMT(std::set<JavaMethod*>* meths) {
- for (uint32 i = 0; i < nbInterfaces; ++i) {
- interfaces[i]->fillIMT(meths);
- }
-
- if (super != NULL) {
- super->fillIMT(meths);
- }
-
- // Specification says that an invokeinterface also looks at j.l.Object.
- if (isInterface() || (super == NULL)) {
- for (uint32 i = 0; i < nbVirtualMethods; ++i) {
- JavaMethod& meth = virtualMethods[i];
- uint32_t index = InterfaceMethodTable::getIndex(meth.name, meth.type);
- meths[index].insert(&meth);
- }
- }
-}
-
-void Class::makeVT() {
- if (super == NULL) {
- virtualTableSize = JavaVirtualTable::getFirstJavaMethodIndex();
- } else {
- virtualTableSize = super->virtualTableSize;
- }
-
- for (uint32 i = 0; i < nbVirtualMethods; ++i) {
- JavaMethod& meth = virtualMethods[i];
- if (meth.name->equals(classLoader->vm->upcalls->finalize) &&
- meth.type->equals(classLoader->vm->upcalls->clinitType)) {
- meth.offset = 0;
- } else {
- JavaMethod* parent = super?
- super->lookupMethodDontThrow(meth.name, meth.type, false, true, 0) :
- 0;
-
- uint64_t offset = 0;
- if (!parent) {
- offset = virtualTableSize++;
- meth.offset = offset;
- } else {
- offset = parent->offset;
- meth.offset = parent->offset;
- }
- }
- }
-
- mvm::BumpPtrAllocator& allocator = classLoader->allocator;
- virtualVT = new(allocator, virtualTableSize) JavaVirtualTable(this);
-}
-
-static void computeMirandaMethods(Class* current,
- Class* baseClass, std::vector<JavaMethod*>& mirandaMethods) {
- for (uint32 i = 0; i < current->nbInterfaces; i++) {
- Class* I = current->interfaces[i];
- // TODO: At this point, the interface may have not been read, so there
- // is no methods yet.
- for (uint32 j = 0; j < I->nbVirtualMethods; j++) {
- JavaMethod& orig = I->virtualMethods[j];
- JavaMethod* meth = baseClass->lookupMethodDontThrow(orig.name, orig.type,
- false, true, 0);
- if (meth == NULL) {
- mirandaMethods.push_back(&orig);
- }
- }
- computeMirandaMethods(I, baseClass, mirandaMethods);
- }
-}
-
-void Class::readMethods(Reader& reader) {
- uint16 nbMethods = reader.readU2();
- mvm::ThreadAllocator allocator;
- if (isAbstract(access)) {
- virtualMethods = (JavaMethod*)
- allocator.Allocate(nbMethods * sizeof(JavaMethod));
- } else {
- virtualMethods =
- new(classLoader->allocator, "Methods") JavaMethod[nbMethods];
- }
- staticMethods = virtualMethods + nbMethods;
- for (int i = 0; i < nbMethods; i++) {
- uint16 access = reader.readU2();
- const UTF8* name = ctpInfo->UTF8At(reader.readU2());
- const UTF8* type = ctpInfo->UTF8At(reader.readU2());
- JavaMethod* meth = 0;
- if (isStatic(access)) {
- --staticMethods;
- meth = &(staticMethods[0]);
- meth->initialise(this, name, type, access);
- ++nbStaticMethods;
- } else {
- meth = &(virtualMethods[nbVirtualMethods]);
- meth->initialise(this, name, type, access);
- ++nbVirtualMethods;
- }
- meth->attributs = readAttributs(reader, meth->nbAttributs);
- }
-
- if (isAbstract(access)) {
- std::vector<JavaMethod*> mirandaMethods;
- computeMirandaMethods(this, this, mirandaMethods);
- uint32 size = mirandaMethods.size();
- nbMethods += size;
- JavaMethod* realMethods =
- new(classLoader->allocator, "Methods") JavaMethod[nbMethods];
- memcpy(realMethods + size, virtualMethods,
- sizeof(JavaMethod) * (nbMethods - size));
- nbVirtualMethods += size;
- staticMethods = realMethods + nbVirtualMethods;
- if (size != 0) {
- int j = 0;
- for (std::vector<JavaMethod*>::iterator i = mirandaMethods.begin(),
- e = mirandaMethods.end(); i != e; i++) {
- JavaMethod* cur = *i;
- realMethods[j++].initialise(this, cur->name, cur->type, cur->access);
- }
- }
- virtualMethods = realMethods;
- }
-}
-
-void Class::readClass() {
-
- assert(getInitializationState() == loaded && "Wrong init state");
-
- PRINT_DEBUG(JNJVM_LOAD, 0, COLOR_NORMAL, "; ", 0);
- PRINT_DEBUG(JNJVM_LOAD, 0, LIGHT_GREEN, "reading ", 0);
- PRINT_DEBUG(JNJVM_LOAD, 0, COLOR_NORMAL, "%s\n", mvm::PrintBuffer(this).cString());
-
- Reader reader(bytes);
- uint32 magic = reader.readU4();
- assert(magic == Jnjvm::Magic && "I've created a class but magic is no good!");
-
- /* uint16 minor = */ reader.readU2();
- /* uint16 major = */ reader.readU2();
- uint32 ctpSize = reader.readU2();
- ctpInfo = new(classLoader->allocator, ctpSize) JavaConstantPool(this, reader,
- ctpSize);
- access |= (reader.readU2() & 0x0FFF);
-
- if (!isPublic(access)) access |= ACC_PRIVATE;
-
- const UTF8* thisClassName =
- ctpInfo->resolveClassName(reader.readU2());
-
- if (!(thisClassName->equals(name))) {
- classLoader->vm->noClassDefFoundError(this, thisClassName);
- }
-
- readParents(reader);
- readFields(reader);
- readMethods(reader);
- attributs = readAttributs(reader, nbAttributs);
-}
-
-void UserClass::resolveParents() {
- if (super != NULL) {
- super->resolveClass();
- }
-
- for (unsigned i = 0; i < nbInterfaces; i++)
- interfaces[i]->resolveClass();
-}
-
-void Class::resolveClass() {
- if (isResolved() || isErroneous()) return;
- resolveParents();
- loadExceptions();
- // Do a compare and swap in case another thread initialized the class.
- __sync_val_compare_and_swap(
- &(getCurrentTaskClassMirror().status), loaded, resolved);
- assert(isResolved() || isErroneous());
-}
-
-void UserClass::resolveInnerOuterClasses() {
- if (!innerOuterResolved) {
- Attribut* attribut = lookupAttribut(Attribut::innerClassesAttribut);
- if (attribut != 0) {
- Reader reader(attribut, bytes);
- uint16 nbi = reader.readU2();
- for (uint16 i = 0; i < nbi; ++i) {
- uint16 inner = reader.readU2();
- uint16 outer = reader.readU2();
- uint16 innerName = reader.readU2();
- uint16 accessFlags = reader.readU2();
- UserClass* clInner = 0;
- UserClass* clOuter = 0;
- if (inner) clInner = (UserClass*)ctpInfo->loadClass(inner);
- if (outer) clOuter = (UserClass*)ctpInfo->loadClass(outer);
-
- if (clInner == this) {
- outerClass = clOuter;
- } else if (clOuter == this) {
- if (!innerClasses) {
- innerClasses = (Class**)
- classLoader->allocator.Allocate(nbi * sizeof(Class*),
- "Inner classes");
- }
- clInner->setInnerAccess(accessFlags);
- if (!innerName) isAnonymous = true;
- innerClasses[nbInnerClasses++] = clInner;
- }
- }
- }
- innerOuterResolved = true;
- }
-}
-
-static JavaObject* getClassType(JnjvmClassLoader* loader,
- Typedef* type) {
- UserCommonClass* res = type->assocClass(loader);
- assert(res && "No associated class");
- return res->getClassDelegatee();
-}
-
-ArrayObject* JavaMethod::getParameterTypes(JnjvmClassLoader* loader) {
-
- ArrayObject* res = NULL;
- JavaObject* delegatee = NULL;
- llvm_gcroot(res, 0);
- llvm_gcroot(delegatee, 0);
-
- Signdef* sign = getSignature();
- Typedef* const* arguments = sign->getArgumentsType();
- res = (ArrayObject*)loader->vm->upcalls->classArrayClass->doNew(sign->nbArguments);
-
- for (uint32 index = 0; index < sign->nbArguments; ++index) {
- delegatee = getClassType(loader, arguments[index]);
- ArrayObject::setElement(res, delegatee, index);
- }
-
- return res;
-
-}
-
-JavaObject* JavaMethod::getReturnType(JnjvmClassLoader* loader) {
- Typedef* ret = getSignature()->getReturnType();
- return getClassType(loader, ret);
-}
-
-ArrayObject* JavaMethod::getExceptionTypes(JnjvmClassLoader* loader) {
-
- ArrayObject* res = NULL;
- JavaObject* delegatee = NULL;
- llvm_gcroot(res, 0);
- llvm_gcroot(delegatee, 0);
-
- Attribut* exceptionAtt = lookupAttribut(Attribut::exceptionsAttribut);
- Jnjvm* vm = loader->vm;
- if (exceptionAtt == 0) {
- return (ArrayObject*)vm->upcalls->classArrayClass->doNew(0);
- } else {
- UserConstantPool* ctp = classDef->getConstantPool();
- Reader reader(exceptionAtt, classDef->bytes);
- uint16 nbe = reader.readU2();
- res = (ArrayObject*)vm->upcalls->classArrayClass->doNew(nbe);
-
- for (uint16 i = 0; i < nbe; ++i) {
- uint16 idx = reader.readU2();
- UserCommonClass* cl = ctp->loadClass(idx);
- assert(cl->asClass() && "Wrong exception type");
- cl->asClass()->resolveClass();
- delegatee = cl->getClassDelegatee();
- ArrayObject::setElement(res, delegatee, i);
- }
- return res;
- }
-}
-
-JavaObject* CommonClass::setDelegatee(JavaObject* val) {
- JavaObject* prev = NULL;
- llvm_gcroot(val, 0);
- llvm_gcroot(prev, 0);
- prev = (JavaObject*)__sync_val_compare_and_swap(&(delegatee[0]), NULL, val);
-
- if (!prev) return val;
- else return prev;
-}
-
-
-
-UserCommonClass* UserCommonClass::resolvedImplClass(JavaObject* clazz,
- bool doClinit) {
-
- llvm_gcroot(clazz, 0);
-
- UserCommonClass* cl = JavaObjectClass::getClass((JavaObjectClass*)clazz);
- assert(cl && "No class in Class object");
- if (cl->isClass()) {
- cl->asClass()->resolveClass();
- if (doClinit) cl->asClass()->initialiseClass();
- }
- return cl;
-}
-
-void JavaMethod::jniConsFromMeth(char* buf, const UTF8* jniConsClName,
- const UTF8* jniConsName,
- const UTF8* jniConsType,
- bool synthetic) {
- sint32 clen = jniConsClName->size;
- sint32 mnlen = jniConsName->size;
-
- uint32 cur = 0;
- char* ptr = &(buf[JNI_NAME_PRE_LEN]);
-
- memcpy(buf, JNI_NAME_PRE, JNI_NAME_PRE_LEN);
-
- for (sint32 i =0; i < clen; ++i) {
- cur = jniConsClName->elements[i];
- if (cur == '/') ptr[0] = '_';
- else if (cur == '_') {
- ptr[0] = '_';
- ptr[1] = '1';
- ++ptr;
- }
- else ptr[0] = (uint8)cur;
- ++ptr;
- }
-
- ptr[0] = '_';
- ++ptr;
-
- for (sint32 i =0; i < mnlen; ++i) {
- cur = jniConsName->elements[i];
- if (cur == '/') {
- ptr[0] = '_';
- ++ptr;
- } else if (cur == '_') {
- ptr[0] = '_';
- ptr[1] = '1';
- ptr += 2;
- } else if (cur == '<') {
- ptr[0] = '_';
- ptr[1] = '0';
- ptr[2] = '0';
- ptr[3] = '0';
- ptr[4] = '3';
- ptr[5] = 'C';
- ptr += 6;
- } else if (cur == '>') {
- ptr[0] = '_';
- ptr[1] = '0';
- ptr[2] = '0';
- ptr[3] = '0';
- ptr[4] = '3';
- ptr[5] = 'E';
- ptr += 6;
- } else {
- ptr[0] = (uint8)cur;
- ++ptr;
- }
- }
- ptr[0] = 0;
-}
-
-void JavaMethod::jniConsFromMethOverloaded(char* buf, const UTF8* jniConsClName,
- const UTF8* jniConsName,
- const UTF8* jniConsType,
- bool synthetic) {
- sint32 clen = jniConsClName->size;
- sint32 mnlen = jniConsName->size;
-
- uint32 cur = 0;
- char* ptr = &(buf[JNI_NAME_PRE_LEN]);
-
- memcpy(buf, JNI_NAME_PRE, JNI_NAME_PRE_LEN);
-
- for (sint32 i =0; i < clen; ++i) {
- cur = jniConsClName->elements[i];
- if (cur == '/') {
- ptr[0] = '_';
- ++ptr;
- } else if (cur == '_') {
- ptr[0] = '_';
- ptr[1] = '1';
- ptr += 2;
- } else if (cur == '$') {
- ptr[0] = '_';
- ptr[1] = '0';
- ptr[2] = '0';
- ptr[3] = '0';
- ptr[4] = '2';
- ptr[5] = '4';
- ptr += 6;
- } else {
- ptr[0] = (uint8)cur;
- ++ptr;
- }
- }
-
- ptr[0] = '_';
- ++ptr;
-
- for (sint32 i =0; i < mnlen; ++i) {
- cur = jniConsName->elements[i];
- if (cur == '/') ptr[0] = '_';
- else if (cur == '_') {
- ptr[0] = '_';
- ptr[1] = '1';
- ptr += 2;
- } else if (cur == '<') {
- ptr[0] = '_';
- ptr[1] = '0';
- ptr[2] = '0';
- ptr[3] = '0';
- ptr[4] = '3';
- ptr[5] = 'C';
- ptr += 6;
- } else if (cur == '>') {
- ptr[0] = '_';
- ptr[1] = '0';
- ptr[2] = '0';
- ptr[3] = '0';
- ptr[4] = '3';
- ptr[5] = 'E';
- ptr += 6;
- } else {
- ptr[0] = (uint8)cur;
- ++ptr;
- }
- }
-
- sint32 i = 0;
- while (i < jniConsType->size) {
- char c = jniConsType->elements[i++];
- if (c == I_PARG) {
- ptr[0] = '_';
- ptr[1] = '_';
- ptr += 2;
- } else if (c == '/') {
- ptr[0] = '_';
- ++ptr;
- } else if (c == '_') {
- ptr[0] = '_';
- ptr[1] = '1';
- ptr += 2;
- } else if (c == '$') {
- ptr[0] = '_';
- ptr[1] = '0';
- ptr[2] = '0';
- ptr[3] = '0';
- ptr[4] = '2';
- ptr[5] = '4';
- ptr += 6;
- } else if (c == I_END_REF) {
- ptr[0] = '_';
- ptr[1] = '2';
- ptr += 2;
- } else if (c == I_TAB) {
- ptr[0] = '_';
- ptr[1] = '3';
- ptr += 2;
- } else if (c == I_PARD) {
- break;
- } else {
- ptr[0] = c;
- ++ptr;
- }
- }
-
- if (synthetic) {
- ptr[0] = 'S';
- ++ptr;
- }
- ptr[0] = 0;
-
-}
-
-bool UserClass::isNativeOverloaded(JavaMethod* meth) {
-
- for (uint32 i = 0; i < nbVirtualMethods; ++i) {
- JavaMethod& cur = virtualMethods[i];
- if (&cur != meth && isNative(cur.access) && cur.name->equals(meth->name))
- return true;
- }
-
- for (uint32 i = 0; i < nbStaticMethods; ++i) {
- JavaMethod& cur = staticMethods[i];
- if (&cur != meth && isNative(cur.access) && cur.name->equals(meth->name))
- return true;
- }
-
- return false;
-}
-
-
-ArrayUInt16* JavaMethod::toString() const {
-
- Jnjvm* vm = classDef->classLoader->vm;
- uint32 size = classDef->name->size + name->size + type->size + 1;
- ArrayUInt16* res = (ArrayUInt16*)vm->upcalls->ArrayOfChar->doNew(size);
- llvm_gcroot(res, 0);
-
- uint32 i = 0;
-
- for (sint32 j = 0; j < classDef->name->size; ++j) {
- if (classDef->name->elements[j] == '/') {
- ArrayUInt16::setElement(res, '.', i);
- } else {
- ArrayUInt16::setElement(res, classDef->name->elements[j], i);
- }
- i++;
- }
-
- ArrayUInt16::setElement(res, '.', i);
- i++;
-
- for (sint32 j = 0; j < name->size; ++j) {
- ArrayUInt16::setElement(res, name->elements[j], i);
- i++;
- }
-
- for (sint32 j = 0; j < type->size; ++j) {
- ArrayUInt16::setElement(res, type->elements[j], i);
- i++;
- }
-
- return res;
-}
-
-bool UserClass::needsInitialisationCheck() {
-
- if (isReady()) return false;
-
- if (super && super->needsInitialisationCheck())
- return true;
-
- if (nbStaticFields) return true;
-
- JavaMethod* meth =
- lookupMethodDontThrow(classLoader->vm->upcalls->clinitName,
- classLoader->vm->upcalls->clinitType,
- true, false, 0);
-
- if (meth) return true;
-
- setInitializationState(ready);
- return false;
-}
-
-void ClassArray::initialiseVT(Class* javaLangObject) {
-
- ClassArray::SuperArray = javaLangObject;
- JnjvmClassLoader* JCL = javaLangObject->classLoader;
- Classpath* upcalls = JCL->vm->upcalls;
-
- assert(javaLangObject->virtualVT->init &&
- "Initializing array VT before JavaObjectVT");
-
- // Load and resolve interfaces of array classes. We resolve them now
- // so that the secondary type list of array VTs can reference them.
- ClassArray::InterfacesArray[0] =
- JCL->loadName(JCL->asciizConstructUTF8("java/lang/Cloneable"),
- true, false, NULL);
-
- ClassArray::InterfacesArray[1] =
- JCL->loadName(JCL->asciizConstructUTF8("java/io/Serializable"),
- true, false, NULL);
-
- // Load base array classes that JnJVM internally uses. Now that the interfaces
- // have been loaded, the secondary type can be safely created.
- upcalls->ArrayOfObject =
- JCL->constructArray(JCL->asciizConstructUTF8("[Ljava/lang/Object;"));
-
- upcalls->ArrayOfString =
- JCL->constructArray(JCL->asciizConstructUTF8("[Ljava/lang/String;"));
-
- // Update native array classes. A few things have not been set properly
- // when loading these classes because java.lang.Object and java.lang.Object[]
- // were not loaded yet. Correct that now by updating these classes.
- #define COPY(CLASS) \
- memcpy(CLASS->virtualVT->getFirstJavaMethod(), \
- javaLangObject->virtualVT->getFirstJavaMethod(), \
- sizeof(uintptr_t) * JavaVirtualTable::getNumJavaMethods()); \
- CLASS->super = javaLangObject; \
- CLASS->virtualVT->display[0] = javaLangObject->virtualVT; \
- CLASS->virtualVT->secondaryTypes = \
- upcalls->ArrayOfObject->virtualVT->secondaryTypes; \
-
- COPY(upcalls->ArrayOfBool)
- COPY(upcalls->ArrayOfByte)
- COPY(upcalls->ArrayOfChar)
- COPY(upcalls->ArrayOfShort)
- COPY(upcalls->ArrayOfInt)
- COPY(upcalls->ArrayOfFloat)
- COPY(upcalls->ArrayOfDouble)
- COPY(upcalls->ArrayOfLong)
-
-#undef COPY
-
-}
-
-JavaVirtualTable::JavaVirtualTable(Class* C) {
- vm = C->classLoader->vm;
-
- if (C->super) {
-
- Class* referenceClass =
- C->classLoader->vm->upcalls->newReference;
- if (referenceClass != NULL && C->super->isAssignableFrom(referenceClass)) {
- tracer = (uintptr_t)ReferenceObjectTracer;
- } else {
- tracer = (uintptr_t)RegularObjectTracer;
- }
- destructor = 0;
- operatorDelete = 0;
-
- // Set IMT.
- if (!isAbstract(C->access)) {
- IMT = new (C->classLoader->allocator, "IMT") InterfaceMethodTable();
- }
-
- // Set the class of this VT.
- cl = C;
-
- // Set depth and display for fast dynamic type checking.
- JavaVirtualTable* superVT = C->super->virtualVT;
- assert(superVT && "Super has no VT");
- depth = superVT->depth + 1;
- nbSecondaryTypes = superVT->nbSecondaryTypes + cl->nbInterfaces;
-
- for (uint32 i = 0; i < cl->nbInterfaces; ++i) {
- nbSecondaryTypes += cl->interfaces[i]->virtualVT->nbSecondaryTypes;
- }
-
- uint32 length = getDisplayLength() < depth ? getDisplayLength() : depth;
- memcpy(display, superVT->display, length * sizeof(JavaVirtualTable*));
- uint32 outOfDepth = 0;
- if (C->isInterface()) {
- offset = getCacheIndex();
- } else if (depth < getDisplayLength()) {
- display[depth] = this;
- offset = getCacheIndex() + depth + 1;
- } else {
- offset = getCacheIndex();
- ++nbSecondaryTypes;
- outOfDepth = 1;
- }
-
- mvm::BumpPtrAllocator& allocator = C->classLoader->allocator;
- secondaryTypes = (JavaVirtualTable**)
- allocator.Allocate(sizeof(JavaVirtualTable*) * nbSecondaryTypes,
- "Secondary types");
-
- if (outOfDepth) {
- secondaryTypes[0] = this;
- }
-
- if (superVT->nbSecondaryTypes) {
- memcpy(secondaryTypes + outOfDepth, superVT->secondaryTypes,
- sizeof(JavaVirtualTable*) * superVT->nbSecondaryTypes);
- }
-
- for (uint32 i = 0; i < cl->nbInterfaces; ++i) {
- JavaVirtualTable* cur = cl->interfaces[i]->virtualVT;
- assert(cur && "Interface not resolved!\n");
- uint32 index = superVT->nbSecondaryTypes + outOfDepth + i;
- secondaryTypes[index] = cur;
- }
-
- uint32 lastIndex = superVT->nbSecondaryTypes + cl->nbInterfaces +
- outOfDepth;
-
- for (uint32 i = 0; i < cl->nbInterfaces; ++i) {
- JavaVirtualTable* cur = cl->interfaces[i]->virtualVT;
- memcpy(secondaryTypes + lastIndex, cur->secondaryTypes,
- sizeof(JavaVirtualTable*) * cur->nbSecondaryTypes);
- lastIndex += cur->nbSecondaryTypes;
- }
-
- } else {
- // Set the tracer, destructor and delete.
- tracer = (uintptr_t)JavaObjectTracer;
- destructor = 0;
- operatorDelete = 0;
-
- // Set the class of this VT.
- cl = C;
-
- // Set depth and display for fast dynamic type checking.
- // java.lang.Object does not have any secondary types.
- offset = getCacheIndex() + 1;
- depth = 0;
- display[0] = this;
- destructor = 0;
- nbSecondaryTypes = 0;
- }
-}
-
-JavaVirtualTable::JavaVirtualTable(ClassArray* C) {
- vm = C->classLoader->vm;
-
- if (C->baseClass()->isClass())
- C->baseClass()->asClass()->resolveClass();
-
- if (!C->baseClass()->isPrimitive()) {
- baseClassVT = C->baseClass()->virtualVT;
-
- // Copy the super VT into the current VT.
- uint32 size = (getBaseSize() - getFirstJavaMethodIndex());
- memcpy(this->getFirstJavaMethod(),
- C->super->virtualVT->getFirstJavaMethod(),
- size * sizeof(uintptr_t));
- tracer = (uintptr_t)ArrayObjectTracer;
-
- // Set the class of this VT.
- cl = C;
-
- // Set depth and display for fast dynamic type checking.
- JnjvmClassLoader* JCL = cl->classLoader;
- Classpath* upcalls = JCL->vm->upcalls;
-
- if (upcalls->ArrayOfObject) {
- UserCommonClass* base = C->baseClass();
- uint32 dim = 1;
- while (base->isArray()) {
- base = base->asArrayClass()->baseClass();
- ++dim;
- }
-
- bool newSecondaryTypes = false;
- bool intf = base->isInterface();
- ClassArray* super = 0;
-
- if (base->isPrimitive()) {
- // If the base class is primitive, then the super is one
- // dimension below, e.g. the super of int[][] is Object[].
- --dim;
- const UTF8* superName = JCL->constructArrayName(dim, C->super->name);
- super = JCL->constructArray(superName);
- } else if (base == C->super) {
- // If the base class is java.lang.Object, then the super is one
- // dimension below, e.g. the super of Object[][] is Object[].
- // Also, the class is the first class in the dimension hierarchy,
- // so it must create a new secondary type list.
- --dim;
- newSecondaryTypes = true;
- super = C->baseClass()->asArrayClass();
- } else {
- // If the base class is any other class, interface or not,
- // the super is of the dimension of the current array class,
- // and whose base class is the super of this base class.
- const UTF8* superName = JCL->constructArrayName(dim, base->super->name);
- JnjvmClassLoader* superLoader = base->super->classLoader;
- super = superLoader->constructArray(superName);
- }
-
- assert(super && "No super found");
- JavaVirtualTable* superVT = super->virtualVT;
- depth = superVT->depth + 1;
-
- // Record if we need to add the super in the list of secondary types.
- uint32 addSuper = 0;
-
- uint32 length = getDisplayLength() < depth ? getDisplayLength() : depth;
- memcpy(display, superVT->display, length * sizeof(JavaVirtualTable*));
- if (depth < getDisplayLength() && !intf) {
- display[depth] = this;
- offset = getCacheIndex() + depth + 1;
- } else {
- offset = getCacheIndex();
- // We add the super if the current class is an interface or if the super
- // class is out of depth.
- if (intf || depth != getDisplayLength()) addSuper = 1;
- }
-
- mvm::BumpPtrAllocator& allocator = JCL->allocator;
-
- if (!newSecondaryTypes) {
- if (base->nbInterfaces || addSuper) {
- // If the base class implements interfaces, we must also add the
- // arrays of these interfaces, of the same dimension than this array
- // class and add them to the secondary types list.
- nbSecondaryTypes = base->nbInterfaces + superVT->nbSecondaryTypes +
- addSuper;
- secondaryTypes = (JavaVirtualTable**)
- allocator.Allocate(sizeof(JavaVirtualTable*) * nbSecondaryTypes,
- "Secondary types");
-
- // Put the super in the list of secondary types.
- if (addSuper) secondaryTypes[0] = superVT;
-
- // Copy the list of secondary types of the super.
- memcpy(secondaryTypes + addSuper, superVT->secondaryTypes,
- superVT->nbSecondaryTypes * sizeof(JavaVirtualTable*));
-
- // Add our own secondary types: the interfaces of the base class put
- // in the dimension of the current array class.
- for (uint32 i = 0; i < base->nbInterfaces; ++i) {
- const UTF8* name =
- JCL->constructArrayName(dim, base->interfaces[i]->name);
- ClassArray* interface = JCL->constructArray(name);
- JavaVirtualTable* CurVT = interface->virtualVT;
- secondaryTypes[i + superVT->nbSecondaryTypes + addSuper] = CurVT;
- }
- } else {
- // If the super is not a secondary type and the base class does not
- // implement any interface, we can reuse the list of secondary types
- // of super.
- nbSecondaryTypes = superVT->nbSecondaryTypes;
- secondaryTypes = superVT->secondaryTypes;
- }
- } else {
-
- // This is an Object[....] array class. It will create the list of
- // secondary types and all array classes of the same dimension whose
- // base class does not have interfaces point to this array.
-
- // If we're superior than the display limit, we must make room for one
- // slot that will contain the current VT.
- uint32 outOfDepth = 0;
- if (depth >= getDisplayLength()) outOfDepth = 1;
-
- assert(cl->nbInterfaces == 2 && "Arrays have more than 2 interface?");
-
- // The list of secondary types is composed of:
- // (1) The list of secondary types of super array.
- // (2) The array of inherited interfaces with the same dimensions.
- // (3) This VT, if its depth is superior than the display size.
- nbSecondaryTypes = superVT->nbSecondaryTypes + 2 + outOfDepth;
-
- secondaryTypes = (JavaVirtualTable**)
- allocator.Allocate(sizeof(JavaVirtualTable*) * nbSecondaryTypes,
- "Secondary types");
-
- // First, copy the list of secondary types from super array.
- memcpy(secondaryTypes + outOfDepth, superVT->secondaryTypes,
- superVT->nbSecondaryTypes * sizeof(JavaVirtualTable*));
-
- // If the depth is superior than the display size, put the current VT
- // at the beginning of the list.
- if (outOfDepth) secondaryTypes[0] = this;
-
- // Load Cloneable[...] and Serializable[...]
- const UTF8* name = JCL->constructArrayName(dim, cl->interfaces[0]->name);
- ClassArray* firstInterface = JCL->constructArray(name);
- name = JCL->constructArrayName(dim, cl->interfaces[1]->name);
- ClassArray* secondInterface = JCL->constructArray(name);
-
- uint32 index = superVT->nbSecondaryTypes + outOfDepth;
-
- // Put Cloneable[...] and Serializable[...] at the end of the list.
- secondaryTypes[index] = firstInterface->virtualVT;
- secondaryTypes[index + 1] = secondInterface->virtualVT;
-
- // If the depth is greater than the display size,
- // Cloneable[...] and Serializable[...] have their own list of
- // secondary types, and we must therefore tell them that they
- // implement themselves.
- // If the depth is less than than the display size, there is nothing
- // to do: the array of secondary types has been created before loading
- // the interface arrays, so the interface arrays already reference
- // the array.
- if (outOfDepth) {
- firstInterface->virtualVT->secondaryTypes[index] =
- firstInterface->virtualVT;
- firstInterface->virtualVT->secondaryTypes[index + 1] =
- secondInterface->virtualVT;
- secondInterface->virtualVT->secondaryTypes[index] =
- firstInterface->virtualVT;
- secondInterface->virtualVT->secondaryTypes[index + 1] =
- secondInterface->virtualVT;
- }
- }
-
- } else {
- // This is java.lang.Object[].
- depth = 1;
- display[0] = C->super->virtualVT;
- display[1] = this;
- offset = getCacheIndex() + 2;
- nbSecondaryTypes = 2;
-
- mvm::BumpPtrAllocator& allocator = JCL->allocator;
- secondaryTypes = (JavaVirtualTable**)
- allocator.Allocate(sizeof(JavaVirtualTable*) * nbSecondaryTypes,
- "Secondary types");
-
- // The interfaces have already been resolved.
- secondaryTypes[0] = cl->interfaces[0]->virtualVT;
- secondaryTypes[1] = cl->interfaces[1]->virtualVT;
- }
-
- } else {
- // Set the tracer, destructor and delete
- tracer = (uintptr_t)JavaObjectTracer;
- destructor = 0;
- operatorDelete = 0;
-
- // Set the class of this VT.
- cl = C;
-
- // Set depth and display for fast dynamic type checking. Since
- // JavaObject has not been loaded yet, don't use super.
- depth = 1;
- display[0] = 0;
- display[1] = this;
- nbSecondaryTypes = 2;
- offset = getCacheIndex() + 2;
-
- // The list of secondary types has not been allocated yet by
- // java.lang.Object[]. The initialiseVT function will update the current
- // array to point to java.lang.Object[]'s secondary list.
- }
-}
-
-
-JavaVirtualTable::JavaVirtualTable(ClassPrimitive* C) {
- // Only used for subtype checking
- vm = C->classLoader->vm;
- cl = C;
- depth = 0;
- display[0] = this;
- nbSecondaryTypes = 0;
- offset = getCacheIndex() + 1;
-}
-
-void AnnotationReader::readAnnotation() {
- uint16 typeIndex = reader.readU2();
- uint16 numPairs = reader.readU2();
-
- for (uint16 j = 0; j < numPairs; ++j) {
- /* uint16 nameIndex = */ reader.readU2();
- readElementValue();
- }
- AnnotationNameIndex = typeIndex;
-}
-
-void AnnotationReader::readElementValue() {
- uint8 tag = reader.readU1();
- if ((tag == 'B') || (tag == 'C') || (tag == 'D') || (tag == 'F') ||
- (tag == 'J') || (tag == 'S') || (tag == 'I') || (tag == 'Z') ||
- (tag == 's')) {
- /* uint16 constValue = */ reader.readU2();
- } else if (tag == 'e') {
- /* uint16 typeName = */ reader.readU2();
- /* uint16 constName = */ reader.readU2();
- } else if (tag == 'c') {
- /* uint16 classInfoIndex = */ reader.readU2();
- } else if (tag == '@') {
- readAnnotation();
- } else if (tag == '[') {
- uint16 numValues = reader.readU2();
- for (uint32 i = 0; i < numValues; ++i) {
- readElementValue();
- }
- }
-}
-
-CodeLineInfo* JavaMethod::lookupCodeLineInfo(uintptr_t ip) {
- for(uint16 i = 0; i < codeInfoLength; ++i) {
- if (codeInfo[i].address == ip) {
- return &(codeInfo[i]);
- }
- }
- return NULL;
-}
-
-uint16 JavaMethod::lookupLineNumber(uintptr_t ip) {
- for(uint16 i = 0; i < codeInfoLength; ++i) {
- if (codeInfo[i].address == ip) {
- Attribut* codeAtt = lookupAttribut(Attribut::codeAttribut);
- if (codeAtt == NULL) return 0;
- Reader reader(codeAtt, classDef->bytes);
- reader.readU2(); // max_stack
- reader.readU2(); // max_locals;
- uint32_t codeLength = reader.readU4();
- reader.seek(codeLength, Reader::SeekCur);
- uint16_t exceptionTableLength = reader.readU2();
- reader.seek(8 * exceptionTableLength, Reader::SeekCur);
- uint16_t nba = reader.readU2();
- for (uint16 att = 0; att < nba; ++att) {
- const UTF8* attName = classDef->ctpInfo->UTF8At(reader.readU2());
- uint32 attLen = reader.readU4();
- if (attName->equals(Attribut::lineNumberTableAttribut)) {
- uint16_t lineLength = reader.readU2();
- uint16_t currentLine = 0;
- for (uint16 j = 0; j < lineLength; ++j) {
- uint16 pc = reader.readU2();
- if (pc > codeInfo[i].bytecodeIndex + 1) return currentLine;
- currentLine = reader.readU2();
- }
- return currentLine;
- } else {
- reader.seek(attLen, Reader::SeekCur);
- }
- }
- }
- }
- return 0;
-}
-
-uint16 JavaMethod::lookupCtpIndex(uintptr_t ip) {
- for(uint16 i = 0; i < codeInfoLength; ++i) {
- if (codeInfo[i].address == ip) {
- Attribut* codeAtt = lookupAttribut(Attribut::codeAttribut);
- Reader reader(codeAtt, classDef->bytes);
- reader.cursor = reader.cursor + 2 + 2 + 4 + codeInfo[i].bytecodeIndex + 1;
- return reader.readU2();
- }
- }
- return 0;
-}
-
-void Class::acquire() {
- JavaObject* delegatee = NULL;
- llvm_gcroot(delegatee, 0);
- delegatee = getClassDelegatee();
- JavaObject::acquire(delegatee);
-}
-
-void Class::release() {
- JavaObject* delegatee = NULL;
- llvm_gcroot(delegatee, 0);
- delegatee = getClassDelegatee();
- JavaObject::release(delegatee);
-}
-
-void Class::waitClass() {
- JavaObject* delegatee = NULL;
- llvm_gcroot(delegatee, 0);
- delegatee = getClassDelegatee();
- JavaObject::wait(delegatee);
-}
-
-void Class::broadcastClass() {
- JavaObject* delegatee = NULL;
- llvm_gcroot(delegatee, 0);
- delegatee = getClassDelegatee();
- JavaObject::notifyAll(delegatee);
-}
diff --git a/vmkit/lib/J3/VMCore/JavaClass.h b/vmkit/lib/J3/VMCore/JavaClass.h
deleted file mode 100644
index 0142925..0000000
--- a/vmkit/lib/J3/VMCore/JavaClass.h
+++ /dev/null
@@ -1,1287 +0,0 @@
-//===-------- JavaClass.h - Java class representation -------------------===//
-//
-// The VMKit project
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#ifndef JNJVM_JAVA_CLASS_H
-#define JNJVM_JAVA_CLASS_H
-
-
-#include "types.h"
-
-#include "mvm/Allocator.h"
-#include "mvm/MethodInfo.h"
-#include "mvm/Threads/Cond.h"
-#include "mvm/Threads/Locks.h"
-
-#include "JavaAccess.h"
-#include "JavaObject.h"
-#include "JnjvmClassLoader.h"
-#include "JnjvmConfig.h"
-
-#include <cassert>
-#include <set>
-
-namespace j3 {
-
-class ArrayObject;
-class ArrayUInt8;
-class ArrayUInt16;
-class Class;
-class ClassArray;
-class ClassBytes;
-class JavaArray;
-class JavaConstantPool;
-class JavaField;
-class JavaMethod;
-class JavaObject;
-class JavaVirtualTable;
-class Reader;
-class Signdef;
-class Typedef;
-
-
-/// JavaState - List of states a Java class can have. A class is ready to be
-/// used (i.e allocating instances of the class, calling methods of the class
-/// and accessing static fields of the class) when it is in the ready state.
-///
-#define loaded 0 /// The .class file has been found.
-#define resolving 1 /// The .class file is being resolved.
-#define resolved 2 /// The class has been resolved.
-#define vmjc 3 /// The class is defined in a shared library.
-#define inClinit 4 /// The class is cliniting.
-#define ready 5 /// The class is ready to be used.
-#define erroneous 6 /// The class is in an erroneous state.
-
-
-class AnnotationReader {
-public:
- Reader& reader;
- Class* cl;
- uint16 AnnotationNameIndex;
-
- AnnotationReader(Reader& R, Class* C) : reader(R), cl(C),
- AnnotationNameIndex(0) {}
- void readAnnotation();
- void readElementValue();
-};
-
-/// Attribut - This class represents JVM attributes to Java class, methods and
-/// fields located in the .class file.
-///
-class Attribut : public mvm::PermanentObject {
-public:
-
- /// name - The name of the attribut. These are specified in the JVM book.
- /// Experimental attributes exist, but the JnJVM does nor parse them.
- ///
- const UTF8* name;
-
- /// start - The offset in the class of this attribut.
- ///
- uint32 start;
-
- /// nbb - The size of the attribut.
- ///
- uint32 nbb;
-
- /// Attribut - Create an attribut at the given length and offset.
- ///
- Attribut(const UTF8* name, uint32 length, uint32 offset);
- Attribut() {}
-
- /// codeAttribut - The "Code" JVM attribut. This is a method attribut for
- /// finding the bytecode of a method in the .class file.
- //
- static const UTF8* codeAttribut;
-
- /// annotationsAttribut - The "RuntimeVisibleAnnotations" JVM attribut.
- /// This is a method attribut for getting the runtime annotations.
- //
- static const UTF8* annotationsAttribut;
-
- /// exceptionsAttribut - The "Exceptions" attribut. This is a method
- /// attribut for finding the exception table of a method in the .class
- /// file.
- ///
- static const UTF8* exceptionsAttribut;
-
- /// constantAttribut - The "ConstantValue" attribut. This is a field attribut
- /// when the field has a static constant value.
- ///
- static const UTF8* constantAttribut;
-
- /// lineNumberTableAttribut - The "LineNumberTable" attribut. This is used
- /// for corresponding JVM bytecode to source line in the .java file.
- ///
- static const UTF8* lineNumberTableAttribut;
-
- /// innerClassAttribut - The "InnerClasses" attribut. This is a class attribut
- /// for knowing the inner/outer informations of a Java class.
- ///
- static const UTF8* innerClassesAttribut;
-
- /// sourceFileAttribut - The "SourceFile" attribut. This is a class attribut
- /// and gives the correspondance between a class and the name of its Java
- /// file.
- ///
- static const UTF8* sourceFileAttribut;
-
-};
-
-/// TaskClassMirror - The isolate specific class information: the initialization
-/// state and the static instance. In a non-isolate environment, there is only
-/// one instance of a TaskClassMirror per Class.
-class TaskClassMirror {
-public:
-
- /// status - The state.
- ///
- uint8 status;
-
- /// initialized - Is the class initialized?
- bool initialized;
-
- /// staticInstance - Memory that holds the static variables of the class.
- ///
- void* staticInstance;
-};
-
-/// CommonClass - This class is the root class of all Java classes. It is
-/// GC-allocated because CommonClasses have to be traceable. A java/lang/Class
-/// object that stays in memory has a reference to the class. Same for
-/// super or interfaces.
-///
-class CommonClass : public mvm::PermanentObject {
-public:
-
-//===----------------------------------------------------------------------===//
-//
-// If you want to add new fields or modify the types of fields, you must also
-// change their LLVM representation in LLVMRuntime/runtime-*.ll, and their
-// offsets in JnjvmModule.cpp.
-//
-//===----------------------------------------------------------------------===//
-
- /// delegatees - The java/lang/Class delegatee.
- ///
- JavaObject* delegatee[NR_ISOLATES];
-
- /// access - {public, private, protected}.
- ///
- uint16 access;
-
- /// interfaces - The interfaces this class implements.
- ///
- Class** interfaces;
- uint16 nbInterfaces;
-
- /// name - The name of the class.
- ///
- const UTF8* name;
-
- /// super - The parent of this class.
- ///
- Class * super;
-
- /// classLoader - The Jnjvm class loader that loaded the class.
- ///
- JnjvmClassLoader* classLoader;
-
- /// virtualVT - The virtual table of instances of this class.
- ///
- JavaVirtualTable* virtualVT;
-
-
-//===----------------------------------------------------------------------===//
-//
-// End field declaration.
-//
-//===----------------------------------------------------------------------===//
-
- bool isSecondaryClass() {
- return virtualVT->offset == JavaVirtualTable::getCacheIndex();
- }
-
- // Assessor methods.
- uint32 getAccess() const { return access; }
- Class** getInterfaces() const { return interfaces; }
- const UTF8* getName() const { return name; }
- Class* getSuper() const { return super; }
-
- /// isArray - Is the class an array class?
- ///
- bool isArray() const {
- return j3::isArray(access);
- }
-
- /// isPrimitive - Is the class a primitive class?
- ///
- bool isPrimitive() const {
- return j3::isPrimitive(access);
- }
-
- /// isInterface - Is the class an interface?
- ///
- bool isInterface() const {
- return j3::isInterface(access);
- }
-
- /// isClass - Is the class a real, instantiable class?
- ///
- bool isClass() const {
- return j3::isClass(access);
- }
-
- /// asClass - Returns the class as a user-defined class
- /// if it is not a primitive or an array.
- ///
- UserClass* asClass() {
- if (isClass()) return (UserClass*)this;
- return 0;
- }
-
- /// asClass - Returns the class as a user-defined class
- /// if it is not a primitive or an array.
- ///
- const UserClass* asClass() const {
- if (isClass()) return (const UserClass*)this;
- return 0;
- }
-
- /// asPrimitiveClass - Returns the class if it's a primitive class.
- ///
- UserClassPrimitive* asPrimitiveClass() {
- if (isPrimitive()) return (UserClassPrimitive*)this;
- return 0;
- }
-
- const UserClassPrimitive* asPrimitiveClass() const {
- if (isPrimitive()) return (const UserClassPrimitive*)this;
- return 0;
- }
-
- /// asArrayClass - Returns the class if it's an array class.
- ///
- UserClassArray* asArrayClass() {
- if (isArray()) return (UserClassArray*)this;
- return 0;
- }
-
- const UserClassArray* asArrayClass() const {
- if (isArray()) return (const UserClassArray*)this;
- return 0;
- }
-
- /// tracer - The tracer of this GC-allocated class.
- ///
- void tracer(uintptr_t closure);
-
- /// inheritName - Does this class in its class hierarchy inherits
- /// the given name? Equality is on the name. This function does not take
- /// into account array classes.
- ///
- bool inheritName(const uint16* buf, uint32 len);
-
- /// isOfTypeName - Does this class inherits the given name? Equality is on
- /// the name. This function takes into account array classes.
- ///
- bool isOfTypeName(const UTF8* Tname);
-
- /// isAssignableFrom - Is this class assignable from the given class? The
- /// classes may be of any type.
- ///
- bool isAssignableFrom(CommonClass* cl);
-
- /// getClassDelegatee - Return the java/lang/Class representation of this
- /// class.
- ///
- JavaObject* getClassDelegatee(JavaObject* pd = NULL);
-
- /// getClassDelegateePtr - Return a pointer on the java/lang/Class
- /// representation of this class. Used for JNI.
- ///
- JavaObject* const* getClassDelegateePtr(JavaObject* pd = NULL);
-
- /// CommonClass - Create a class with th given name.
- ///
- CommonClass(JnjvmClassLoader* loader, const UTF8* name);
-
- /// ~CommonClass - Free memory used by this class, and remove it from
- /// metadata.
- ///
- ~CommonClass();
-
- /// setInterfaces - Set the interfaces of the class.
- ///
- void setInterfaces(Class** I) {
- interfaces = I;
- }
-
- /// toPrimitive - Returns the primitive class which represents
- /// this class, ie void for java/lang/Void.
- ///
- UserClassPrimitive* toPrimitive() const;
-
- /// getInternal - Return the class.
- ///
- CommonClass* getInternal() {
- return this;
- }
-
- /// setDelegatee - Set the java/lang/Class object of this class.
- ///
- JavaObject* setDelegatee(JavaObject* val);
-
- /// getDelegatee - Get the java/lang/Class object representing this class.
- ///
- JavaObject* getDelegatee() const {
- return delegatee[0];
- }
-
- /// getDelegatee - Get a pointer on the java/lang/Class object
- /// representing this class.
- ///
- JavaObject* const* getDelegateePtr() const {
- return delegatee;
- }
-
- /// resolvedImplClass - Return the internal representation of the
- /// java.lang.Class object. The class must be resolved.
- //
- static UserCommonClass* resolvedImplClass(JavaObject* delegatee,
- bool doClinit);
-#ifdef USE_GC_BOEHM
- void* operator new(size_t sz, mvm::BumpPtrAllocator& allocator) {
- return GC_MALLOC(sz);
- }
-#endif
-
-};
-
-/// ClassPrimitive - This class represents internal classes for primitive
-/// types, e.g. java/lang/Integer.TYPE.
-///
-class ClassPrimitive : public CommonClass {
-public:
-
- /// logSize - The log size of this class, eg 2 for int.
- ///
- uint32 logSize;
-
-
- /// ClassPrimitive - Constructs a primitive class. Only called at boot
- /// time.
- ///
- ClassPrimitive(JnjvmClassLoader* loader, const UTF8* name, uint32 nb);
-
- /// byteIdToPrimitive - Get the primitive class from its byte representation,
- /// ie int for I.
- ///
- static UserClassPrimitive* byteIdToPrimitive(char id, Classpath* upcalls);
-
-};
-
-
-/// Class - This class is the representation of Java regular classes (i.e not
-/// array or primitive). Theses classes have a constant pool.
-///
-class Class : public CommonClass {
-
-public:
-
- /// virtualSize - The size of instances of this class.
- ///
- uint32 virtualSize;
-
- /// aligment - Alignment of instances of this class.
- ///
- uint32 alignment;
-
- /// IsolateInfo - Per isolate informations for static instances and
- /// initialization state.
- ///
- TaskClassMirror IsolateInfo[NR_ISOLATES];
-
- /// virtualFields - List of all the virtual fields defined in this class.
- /// This does not contain non-redefined super fields.
- JavaField* virtualFields;
-
- /// nbVirtualFields - The number of virtual fields.
- ///
- uint16 nbVirtualFields;
-
- /// staticFields - List of all the static fields defined in this class.
- ///
- JavaField* staticFields;
-
- /// nbStaticFields - The number of static fields.
- ///
- uint16 nbStaticFields;
-
- /// virtualMethods - List of all the virtual methods defined by this class.
- /// This does not contain non-redefined super methods.
- JavaMethod* virtualMethods;
-
- /// nbVirtualMethods - The number of virtual methods.
- ///
- uint16 nbVirtualMethods;
-
- /// staticMethods - List of all the static methods defined by this class.
- ///
- JavaMethod* staticMethods;
-
- /// nbStaticMethods - The number of static methods.
- ///
- uint16 nbStaticMethods;
-
- /// ownerClass - Who is initializing this class.
- ///
- mvm::Thread* ownerClass;
-
- /// bytes - The .class file of this class.
- ///
- ClassBytes* bytes;
-
- /// ctpInfo - The constant pool info of this class.
- ///
- JavaConstantPool* ctpInfo;
-
- /// attributs - JVM attributes of this class.
- ///
- Attribut* attributs;
-
- /// nbAttributs - The number of attributes.
- ///
- uint16 nbAttributs;
-
- /// innerClasses - The inner classes of this class.
- ///
- Class** innerClasses;
-
- /// nbInnerClasses - The number of inner classes.
- ///
- uint16 nbInnerClasses;
-
- /// outerClass - The outer class, if this class is an inner class.
- ///
- Class* outerClass;
-
- /// innerAccess - The access of this class, if this class is an inner class.
- ///
- uint16 innerAccess;
-
- /// innerOuterResolved - Is the inner/outer resolution done?
- ///
- bool innerOuterResolved;
-
- /// isAnonymous - Is the class an anonymous class?
- ///
- bool isAnonymous;
-
- /// virtualTableSize - The size of the virtual table of this class.
- ///
- uint32 virtualTableSize;
-
- /// staticSize - The size of the static instance of this class.
- ///
- uint32 staticSize;
-
- /// getVirtualSize - Get the virtual size of instances of this class.
- ///
- uint32 getVirtualSize() const { return virtualSize; }
-
- /// getVirtualVT - Get the virtual VT of instances of this class.
- ///
- JavaVirtualTable* getVirtualVT() const { return virtualVT; }
-
- /// getOwnerClass - Get the thread that is currently initializing the class.
- ///
- mvm::Thread* getOwnerClass() const {
- return ownerClass;
- }
-
- /// setOwnerClass - Set the thread that is currently initializing the class.
- ///
- void setOwnerClass(mvm::Thread* th) {
- ownerClass = th;
- }
-
- /// getOuterClass - Get the class that contains the definition of this class.
- ///
- Class* getOuterClass() const {
- return outerClass;
- }
-
- /// getInnterClasses - Get the classes that this class defines.
- ///
- Class** getInnerClasses() const {
- return innerClasses;
- }
-
- /// lookupMethodDontThrow - Lookup a method in the method map of this class.
- /// Do not throw if the method is not found.
- ///
- JavaMethod* lookupMethodDontThrow(const UTF8* name, const UTF8* type,
- bool isStatic, bool recurse, Class** cl);
-
- /// lookupInterfaceMethodDontThrow - Lookup a method in the interfaces of
- /// this class.
- /// Do not throw if the method is not found.
- ///
- JavaMethod* lookupInterfaceMethodDontThrow(const UTF8* name,
- const UTF8* type);
-
- /// lookupSpecialMethodDontThrow - Lookup a method following the
- /// invokespecial specification.
- /// Do not throw if the method is not found.
- ///
- JavaMethod* lookupSpecialMethodDontThrow(const UTF8* name,
- const UTF8* type,
- Class* current);
-
- /// lookupMethod - Lookup a method and throw an exception if not found.
- ///
- JavaMethod* lookupMethod(const UTF8* name, const UTF8* type, bool isStatic,
- bool recurse, Class** cl);
-
- /// lookupInterfaceMethodDontThrow - Lookup a method in the interfaces of
- /// this class.
- /// Throws a MethodNotFoundError if the method can not ne found.
- ///
- JavaMethod* lookupInterfaceMethod(const UTF8* name, const UTF8* type);
-
- /// lookupFieldDontThrow - Lookup a field in the field map of this class. Do
- /// not throw if the field is not found.
- ///
- JavaField* lookupFieldDontThrow(const UTF8* name, const UTF8* type,
- bool isStatic, bool recurse,
- Class** definingClass);
-
- /// lookupField - Lookup a field and throw an exception if not found.
- ///
- JavaField* lookupField(const UTF8* name, const UTF8* type, bool isStatic,
- bool recurse, Class** definingClass);
-
- /// Assessor methods.
- JavaField* getStaticFields() const { return staticFields; }
- JavaField* getVirtualFields() const { return virtualFields; }
- JavaMethod* getStaticMethods() const { return staticMethods; }
- JavaMethod* getVirtualMethods() const { return virtualMethods; }
-
-
- /// setInnerAccess - Set the access flags of this inner class.
- ///
- void setInnerAccess(uint16 access) {
- innerAccess = access;
- }
-
- /// getStaticSize - Get the size of the static instance.
- ///
- uint32 getStaticSize() const {
- return staticSize;
- }
-
- /// doNew - Allocates a Java object whose class is this class.
- ///
- JavaObject* doNew();
-
- /// tracer - Tracer function of instances of Class.
- ///
- void tracer(uintptr_t closure);
-
- ~Class();
- Class();
-
- /// lookupAttribut - Look up a JVM attribut of this class.
- ///
- Attribut* lookupAttribut(const UTF8* key);
-
- /// allocateStaticInstance - Allocate the static instance of this class.
- ///
- void* allocateStaticInstance();
-
- /// Class - Create a class in the given virtual machine and with the given
- /// name.
- Class(JnjvmClassLoader* loader, const UTF8* name, ClassBytes* bytes);
-
- /// readParents - Reads the parents, i.e. super and interfaces, of the class.
- ///
- void readParents(Reader& reader);
-
- /// loadExceptions - Loads and resolves the exception classes used in catch
- /// clauses of methods defined in this class.
- ///
- void loadExceptions();
-
- /// readAttributs - Reads the attributs of the class.
- ///
- Attribut* readAttributs(Reader& reader, uint16& size);
-
- /// readFields - Reads the fields of the class.
- ///
- void readFields(Reader& reader);
-
- /// readMethods - Reads the methods of the class.
- ///
- void readMethods(Reader& reader);
-
- /// readClass - Reads the class.
- ///
- void readClass();
-
- /// getConstantPool - Get the constant pool of the class.
- ///
- JavaConstantPool* getConstantPool() const {
- return ctpInfo;
- }
-
- /// getBytes - Get the bytes of the class file.
- ///
- ClassBytes* getBytes() const {
- return bytes;
- }
-
- /// resolveInnerOuterClasses - Resolve the inner/outer information.
- ///
- void resolveInnerOuterClasses();
-
- /// resolveClass - If the class has not been resolved yet, resolve it.
- ///
- void resolveClass();
- void resolveParents();
-
- /// initialiseClass - If the class has not been initialized yet,
- /// initialize it.
- ///
- void initialiseClass();
-
- /// acquire - Acquire this class lock.
- ///
- void acquire();
-
- /// release - Release this class lock.
- ///
- void release();
-
- /// waitClass - Wait for the class to be loaded/initialized/resolved.
- ///
- void waitClass();
-
- /// broadcastClass - Unblock threads that were waiting on the class being
- /// loaded/initialized/resolved.
- ///
- void broadcastClass();
-
- /// getCurrentTaskClassMirror - Get the class task mirror of the executing
- /// isolate.
- ///
- TaskClassMirror& getCurrentTaskClassMirror() {
- return IsolateInfo[0];
- }
-
- /// isReadyForCompilation - Can this class be inlined when JITing?
- ///
- bool isReadyForCompilation() {
- return isReady();
- }
-
- /// setResolved - Set the status of the class as resolved.
- ///
- void setResolved() {
- getCurrentTaskClassMirror().status = resolved;
- }
-
- /// setErroneous - Set the class as erroneous.
- ///
- void setErroneous() {
- getCurrentTaskClassMirror().status = erroneous;
- }
-
- /// setIsResolving - The class file is being resolved.
- ///
- void setIsResolving() {
- getCurrentTaskClassMirror().status = resolving;
- }
-
- /// getStaticInstance - Get the memory that holds static variables.
- ///
- void* getStaticInstance() {
- return getCurrentTaskClassMirror().staticInstance;
- }
-
- /// setStaticInstance - Set the memory that holds static variables.
- ///
- void setStaticInstance(void* val) {
- getCurrentTaskClassMirror().staticInstance = val;
- }
-
- /// getInitializationState - Get the state of the class.
- ///
- uint8 getInitializationState() {
- return getCurrentTaskClassMirror().status;
- }
-
- /// setInitializationState - Set the state of the class.
- ///
- void setInitializationState(uint8 st) {
- TaskClassMirror& TCM = getCurrentTaskClassMirror();
- TCM.status = st;
- if (st == ready) TCM.initialized = true;
- }
-
- /// isReady - Has this class been initialized?
- ///
- bool isReady() {
- return getCurrentTaskClassMirror().status == ready;
- }
-
- /// isInitializing - Is the class currently being initialized?
- ///
- bool isInitializing() {
- return getCurrentTaskClassMirror().status >= inClinit;
- }
-
- /// isResolved - Has this class been resolved?
- ///
- bool isResolved() {
- uint8 stat = getCurrentTaskClassMirror().status;
- return (stat >= resolved && stat != erroneous);
- }
-
- /// isErroneous - Is the class in an erroneous state.
- ///
- bool isErroneous() {
- return getCurrentTaskClassMirror().status == erroneous;
- }
-
- /// isResolving - Is the class currently being resolved?
- ///
- bool isResolving() {
- return getCurrentTaskClassMirror().status == resolving;
- }
-
- /// isNativeOverloaded - Is the method overloaded with a native function?
- ///
- bool isNativeOverloaded(JavaMethod* meth);
-
- /// needsInitialisationCheck - Does the method need an initialisation check?
- ///
- bool needsInitialisationCheck();
-
- /// fillIMT - Fill the vector with vectors of methods with the same IMT
- /// index.
- ///
- void fillIMT(std::set<JavaMethod*>* meths);
-
- /// makeVT - Create the virtual table of this class.
- ///
- void makeVT();
-
-};
-
-/// ClassArray - This class represents Java array classes.
-///
-class ClassArray : public CommonClass {
-
-public:
-
- /// _baseClass - The base class of the array.
- ///
- CommonClass* _baseClass;
-
- /// baseClass - Get the base class of this array class.
- ///
- CommonClass* baseClass() const {
- return _baseClass;
- }
-
- /// doNew - Allocate a new array in the given vm.
- ///
- JavaObject* doNew(sint32 n);
-
- /// ClassArray - Construct a Java array class with the given name.
- ///
- ClassArray(JnjvmClassLoader* loader, const UTF8* name,
- UserCommonClass* baseClass);
-
- /// SuperArray - The super of class arrays. Namely java/lang/Object.
- ///
- static Class* SuperArray;
-
- /// InterfacesArray - The list of interfaces for array classes.
- ///
- static Class** InterfacesArray;
-
- /// initialiseVT - Initialise the primitive and reference array VT.
- /// super is the java/lang/Object class.
- ///
- static void initialiseVT(Class* javaLangObject);
-
-};
-
-class CodeLineInfo : public mvm::PermanentObject {
-public:
- uintptr_t address;
- uint16 bytecodeIndex;
- // TODO: Use these fields when inlining.
- JavaMethod* executingMethod;
- // The code where the inlined method starts.
- CodeLineInfo* inlineLocation;
-};
-
-/// JavaMethod - This class represents Java methods.
-///
-class JavaMethod : public mvm::PermanentObject {
-private:
-
- /// _signature - The signature of this method. Null if not resolved.
- ///
- Signdef* _signature;
-
-public:
-
- enum Type {
- Static,
- Special,
- Interface,
- Virtual
- };
-
- /// constructMethod - Create a new method.
- ///
- void initialise(Class* cl, const UTF8* name, const UTF8* type, uint16 access);
-
- /// compiledPtr - Return a pointer to the compiled code of this Java method,
- /// compiling it if necessary.
- ///
- void* compiledPtr();
-
- /// setNative - Set the method as native.
- ///
- void setNative();
-
- /// JavaMethod - Delete the method as well as the cache enveloppes and
- /// attributes of the method.
- ///
- ~JavaMethod();
-
- /// access - Java access type of this method (e.g. private, public...).
- ///
- uint16 access;
-
- /// attributs - List of Java attributs of this method.
- ///
- Attribut* attributs;
-
- /// nbAttributs - The number of attributes.
- ///
- uint16 nbAttributs;
-
- /// classDef - The Java class where the method is defined.
- ///
- Class* classDef;
-
- /// name - The name of the method.
- ///
- const UTF8* name;
-
- /// type - The UTF8 signature of the method.
- ///
- const UTF8* type;
-
- /// canBeInlined - Can the method be inlined?
- ///
- bool canBeInlined;
-
- /// code - Pointer to the compiled code of this method.
- ///
- void* code;
-
- /// codeInfo - Array of CodeLineInfo objects.
- ///
- CodeLineInfo* codeInfo;
-
- /// codeInfoLength - Number of entries in the codeInfo field.
- ///
- uint16 codeInfoLength;
-
- /// offset - The index of the method in the virtual table.
- ///
- uint32 offset;
-
- /// lookupAttribut - Look up an attribut in the method's attributs. Returns
- /// null if the attribut is not found.
- ///
- Attribut* lookupAttribut(const UTF8* key);
-
- /// lookupLineNumber - Find the line number based on the given instruction
- /// pointer.
- ///
- uint16 lookupLineNumber(uintptr_t ip);
-
- /// lookupCtpIndex - Lookup the constant pool index pointed by the opcode
- /// related to the given instruction pointer.
- ///
- uint16 lookupCtpIndex(uintptr_t ip);
-
- /// lookupCodeLineInfo - Lookup the code line info related to the given
- /// instruction pointer.
- ///
- CodeLineInfo* lookupCodeLineInfo(uintptr_t ip);
-
- /// getSignature - Get the signature of thes method, resolving it if
- /// necessary.
- ///
- Signdef* getSignature() {
- if(!_signature)
- _signature = classDef->classLoader->constructSign(type);
- return _signature;
- }
-
- /// toString - Return an array of chars, suitable for creating a string.
- ///
- ArrayUInt16* toString() const;
-
- /// jniConsFromMeth - Construct the JNI name of this method as if
- /// there is no other function in the class with the same name.
- ///
- void jniConsFromMeth(char* buf) const {
- jniConsFromMeth(buf, classDef->name, name, type, isSynthetic(access));
- }
-
- /// jniConsFromMethOverloaded - Construct the JNI name of this method
- /// as if its name is overloaded in the class.
- ///
- void jniConsFromMethOverloaded(char* buf) const {
- jniConsFromMethOverloaded(buf, classDef->name, name, type,
- isSynthetic(access));
- }
-
- /// jniConsFromMeth - Construct the non-overloaded JNI name with
- /// the given name and type.
- ///
- static void jniConsFromMeth(char* buf, const UTF8* clName, const UTF8* name,
- const UTF8* sign, bool synthetic);
-
- /// jniConsFromMethOverloaded - Construct the overloaded JNI name with
- /// the given name and type.
- ///
- static void jniConsFromMethOverloaded(char* buf, const UTF8* clName,
- const UTF8* name, const UTF8* sign,
- bool synthetic);
-
- /// getParameterTypes - Get the java.lang.Class of the parameters of
- /// the method, with the given class loader.
- ///
- ArrayObject* getParameterTypes(JnjvmClassLoader* loader);
-
- /// getExceptionTypes - Get the java.lang.Class of the exceptions of the
- /// method, with the given class loader.
- ///
- ArrayObject* getExceptionTypes(JnjvmClassLoader* loader);
-
- /// getReturnType - Get the java.lang.Class of the result of the method,
- /// with the given class loader.
- ///
- JavaObject* getReturnType(JnjvmClassLoader* loader);
-
-
-//===----------------------------------------------------------------------===//
-//
-// Upcalls from JnJVM code to Java code.
-//
-//===----------------------------------------------------------------------===//
-
- /// This class of methods takes a variable argument list.
- uint32 invokeIntSpecialAP(UserClass*, JavaObject* obj, va_list ap)
- __attribute__ ((noinline));
- float invokeFloatSpecialAP(UserClass*, JavaObject* obj, va_list ap)
- __attribute__ ((noinline));
- double invokeDoubleSpecialAP(UserClass*, JavaObject* obj,
- va_list ap) __attribute__ ((noinline));
- sint64 invokeLongSpecialAP(UserClass*, JavaObject* obj, va_list ap)
- __attribute__ ((noinline));
- JavaObject* invokeJavaObjectSpecialAP(UserClass*, JavaObject* obj,
- va_list ap) __attribute__ ((noinline));
-
- uint32 invokeIntVirtualAP(UserClass*, JavaObject* obj, va_list ap)
- __attribute__ ((noinline));
- float invokeFloatVirtualAP(UserClass*, JavaObject* obj, va_list ap)
- __attribute__ ((noinline));
- double invokeDoubleVirtualAP(UserClass*, JavaObject* obj,
- va_list ap) __attribute__ ((noinline));
- sint64 invokeLongVirtualAP(UserClass*, JavaObject* obj, va_list ap)
- __attribute__ ((noinline));
- JavaObject* invokeJavaObjectVirtualAP(UserClass*, JavaObject* obj,
- va_list ap) __attribute__ ((noinline));
-
- uint32 invokeIntStaticAP(UserClass*, va_list ap)
- __attribute__ ((noinline));
- float invokeFloatStaticAP(UserClass*, va_list ap)
- __attribute__ ((noinline));
- double invokeDoubleStaticAP(UserClass*, va_list ap)
- __attribute__ ((noinline));
- sint64 invokeLongStaticAP(UserClass*, va_list ap)
- __attribute__ ((noinline));
- JavaObject* invokeJavaObjectStaticAP(UserClass*, va_list ap)
- __attribute__ ((noinline));
-
- /// This class of methods takes a buffer which contain the arguments of the
- /// call.
- uint32 invokeIntSpecialBuf(UserClass*, JavaObject* obj, void* buf)
- __attribute__ ((noinline));
- float invokeFloatSpecialBuf(UserClass*, JavaObject* obj, void* buf)
- __attribute__ ((noinline));
- double invokeDoubleSpecialBuf(UserClass*, JavaObject* obj,
- void* buf) __attribute__ ((noinline));
- sint64 invokeLongSpecialBuf(UserClass*, JavaObject* obj, void* buf)
- __attribute__ ((noinline));
- JavaObject* invokeJavaObjectSpecialBuf(UserClass*, JavaObject* obj,
- void* buf) __attribute__ ((noinline));
-
- uint32 invokeIntVirtualBuf(UserClass*, JavaObject* obj, void* buf)
- __attribute__ ((noinline));
- float invokeFloatVirtualBuf(UserClass*, JavaObject* obj, void* buf)
- __attribute__ ((noinline));
- double invokeDoubleVirtualBuf(UserClass*, JavaObject* obj,
- void* buf) __attribute__ ((noinline));
- sint64 invokeLongVirtualBuf(UserClass*, JavaObject* obj, void* buf)
- __attribute__ ((noinline));
- JavaObject* invokeJavaObjectVirtualBuf(UserClass*, JavaObject* obj,
- void* buf) __attribute__ ((noinline));
-
- uint32 invokeIntStaticBuf(UserClass*, void* buf)
- __attribute__ ((noinline));
- float invokeFloatStaticBuf(UserClass*, void* buf)
- __attribute__ ((noinline));
- double invokeDoubleStaticBuf(UserClass*, void* buf)
- __attribute__ ((noinline));
- sint64 invokeLongStaticBuf(UserClass*, void* buf)
- __attribute__ ((noinline));
- JavaObject* invokeJavaObjectStaticBuf(UserClass*, void* buf)
- __attribute__ ((noinline));
-
- /// This class of methods is variadic.
- uint32 invokeIntSpecial(UserClass*, JavaObject* obj, ...)
- __attribute__ ((noinline));
- float invokeFloatSpecial(UserClass*, JavaObject* obj, ...)
- __attribute__ ((noinline));
- double invokeDoubleSpecial(UserClass*, JavaObject* obj, ...)
- __attribute__ ((noinline));
- sint64 invokeLongSpecial(UserClass*, JavaObject* obj, ...)
- __attribute__ ((noinline));
- JavaObject* invokeJavaObjectSpecial(UserClass*, JavaObject* obj,
- ...) __attribute__ ((noinline));
-
- uint32 invokeIntVirtual(UserClass*, JavaObject* obj, ...)
- __attribute__ ((noinline));
- float invokeFloatVirtual(UserClass*, JavaObject* obj, ...)
- __attribute__ ((noinline));
- double invokeDoubleVirtual(UserClass*, JavaObject* obj, ...)
- __attribute__ ((noinline));
- sint64 invokeLongVirtual(UserClass*, JavaObject* obj, ...)
- __attribute__ ((noinline));
- JavaObject* invokeJavaObjectVirtual(UserClass*, JavaObject* obj,
- ...) __attribute__ ((noinline));
-
- uint32 invokeIntStatic(UserClass*, ...)
- __attribute__ ((noinline));
- float invokeFloatStatic(UserClass*, ...)
- __attribute__ ((noinline));
- double invokeDoubleStatic(UserClass*, ...)
- __attribute__ ((noinline));
- sint64 invokeLongStatic(UserClass*, ...)
- __attribute__ ((noinline));
- JavaObject* invokeJavaObjectStatic(UserClass*, ...)
- __attribute__ ((noinline));
-
- #define JNI_NAME_PRE "Java_"
- #define JNI_NAME_PRE_LEN 5
-
-};
-
-/// JavaField - This class represents a Java field.
-///
-class JavaField : public mvm::PermanentObject {
-private:
- /// _signature - The signature of the field. Null if not resolved.
- ///
- Typedef* _signature;
-
- /// InitField - Set an initial value to the field.
- ///
- void InitStaticField(uint64 val);
- void InitStaticField(JavaObject* val);
- void InitStaticField(double val);
- void InitStaticField(float val);
- void InitNullStaticField();
-
-public:
-
- /// constructField - Create a new field.
- ///
- void initialise(Class* cl, const UTF8* name, const UTF8* type, uint16 access);
-
- /// ~JavaField - Destroy the field as well as its attributes.
- ///
- ~JavaField();
-
- /// access - The Java access type of this field (e.g. public, private).
- ///
- uint16 access;
-
- /// name - The name of the field.
- ///
- const UTF8* name;
-
- /// type - The UTF8 type name of the field.
- ///
- const UTF8* type;
-
- /// attributs - List of Java attributs for this field.
- ///
- Attribut* attributs;
-
- /// nbAttributs - The number of attributes.
- ///
- uint16 nbAttributs;
-
- /// classDef - The class where the field is defined.
- ///
- Class* classDef;
-
- /// ptrOffset - The offset of the field when the object containing
- /// the field is casted to an array of bytes.
- ///
- uint32 ptrOffset;
-
- /// num - The index of the field in the field list.
- ///
- uint16 num;
-
- /// getSignature - Get the signature of this field, resolving it if
- /// necessary.
- ///
- Typedef* getSignature() {
- if(!_signature)
- _signature = classDef->classLoader->constructType(type);
- return _signature;
- }
-
- /// InitStaticField - Init the value of the field in the given object. This is
- /// used for static fields which have a default value.
- ///
- void InitStaticField();
-
- /// lookupAttribut - Look up the attribut in the field's list of attributs.
- ///
- Attribut* lookupAttribut(const UTF8* key);
-
- JavaObject** getStaticObjectFieldPtr() {
- assert(classDef->isResolved());
- return (JavaObject**)((uint64)classDef->getStaticInstance() + ptrOffset);
- }
-
- JavaObject** getInstanceObjectFieldPtr(JavaObject* obj) {
- llvm_gcroot(obj, 0);
- return (JavaObject**)((uint64)obj + ptrOffset);
- }
-
- /// getStatic*Field - Get a static field.
- ///
- #define GETSTATICFIELD(TYPE, TYPE_NAME) \
- TYPE getStatic##TYPE_NAME##Field() { \
- assert(classDef->isResolved()); \
- void* ptr = (void*)((uint64)classDef->getStaticInstance() + ptrOffset); \
- return ((TYPE*)ptr)[0]; \
- }
-
- /// setStatic*Field - Set a field of an object.
- ///
- #define SETSTATICFIELD(TYPE, TYPE_NAME) \
- void setStatic##TYPE_NAME##Field(TYPE val) { \
- assert(classDef->isResolved()); \
- void* ptr = (void*)((uint64)classDef->getStaticInstance() + ptrOffset); \
- ((TYPE*)ptr)[0] = val; \
- }
-
- /// getInstance*Field - Get an instance field.
- ///
- #define GETINSTANCEFIELD(TYPE, TYPE_NAME) \
- TYPE getInstance##TYPE_NAME##Field(JavaObject* obj) { \
- llvm_gcroot(obj, 0); \
- assert(classDef->isResolved()); \
- void* ptr = (void*)((uint64)obj + ptrOffset); \
- return ((TYPE*)ptr)[0]; \
- }
-
- /// setInstance*Field - Set an instance field.
- ///
- #define SETINSTANCEFIELD(TYPE, TYPE_NAME) \
- void setInstance##TYPE_NAME##Field(JavaObject* obj, TYPE val) { \
- llvm_gcroot(obj, 0); \
- assert(classDef->isResolved()); \
- void* ptr = (void*)((uint64)obj + ptrOffset); \
- ((TYPE*)ptr)[0] = val; \
- }
-
- #define MK_ASSESSORS(TYPE, TYPE_NAME) \
- GETSTATICFIELD(TYPE, TYPE_NAME) \
- SETSTATICFIELD(TYPE, TYPE_NAME) \
- GETINSTANCEFIELD(TYPE, TYPE_NAME) \
- SETINSTANCEFIELD(TYPE, TYPE_NAME) \
-
- MK_ASSESSORS(float, Float);
- MK_ASSESSORS(double, Double);
- MK_ASSESSORS(uint8, Int8);
- MK_ASSESSORS(uint16, Int16);
- MK_ASSESSORS(uint32, Int32);
- MK_ASSESSORS(sint64, Long);
-
- JavaObject* getStaticObjectField() {
- assert(classDef->isResolved());
- void* ptr = (void*)((uint64)classDef->getStaticInstance() + ptrOffset);
- return ((JavaObject**)ptr)[0];
- }
-
- void setStaticObjectField(JavaObject* val) {
- llvm_gcroot(val, 0);
- if (val != NULL) assert(val->getVirtualTable());
- assert(classDef->isResolved());
- void* ptr = (void*)((uint64)classDef->getStaticInstance() + ptrOffset);
- ((JavaObject**)ptr)[0] = val;
- }
-
- JavaObject* getInstanceObjectField(JavaObject* obj) {
- llvm_gcroot(obj, 0);
- assert(classDef->isResolved());
- void* ptr = (void*)((uint64)obj + ptrOffset);
- return ((JavaObject**)ptr)[0];
- }
-
- void setInstanceObjectField(JavaObject* obj, JavaObject* val) {
- llvm_gcroot(obj, 0);
- llvm_gcroot(val, 0);
- if (val != NULL) assert(val->getVirtualTable());
- assert(classDef->isResolved());
- void* ptr = (void*)((uint64)obj + ptrOffset);
- ((JavaObject**)ptr)[0] = val;
- }
-
- bool isReference() {
- uint16 val = type->elements[0];
- return (val == '[' || val == 'L');
- }
-
-};
-
-
-} // end namespace j3
-
-
-#endif
diff --git a/vmkit/lib/J3/VMCore/JavaConstantPool.cpp b/vmkit/lib/J3/VMCore/JavaConstantPool.cpp
deleted file mode 100644
index 8129d4a..0000000
--- a/vmkit/lib/J3/VMCore/JavaConstantPool.cpp
+++ /dev/null
@@ -1,539 +0,0 @@
-//===--- JavaConstantPool.cpp - Java constant pool definition ---------------===//
-//
-// The VMKit project
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#define JNJVM_LOAD 0
-
-#include <alloca.h>
-#include <cstdio>
-#include <cstdlib>
-
-#include "debug.h"
-
-#include "JavaAccess.h"
-#include "JavaArray.h"
-#include "JavaClass.h"
-#include "JavaCompiler.h"
-#include "JavaConstantPool.h"
-#include "Jnjvm.h"
-#include "JavaThread.h"
-#include "JavaTypes.h"
-#include "LockedMap.h"
-#include "Reader.h"
-#include "JnjvmClassLoader.h"
-
-using namespace j3;
-
-const uint32 JavaConstantPool::ConstantUTF8 = 1;
-const uint32 JavaConstantPool::ConstantInteger = 3;
-const uint32 JavaConstantPool::ConstantFloat = 4;
-const uint32 JavaConstantPool::ConstantLong = 5;
-const uint32 JavaConstantPool::ConstantDouble = 6;
-const uint32 JavaConstantPool::ConstantClass = 7;
-const uint32 JavaConstantPool::ConstantString = 8;
-const uint32 JavaConstantPool::ConstantFieldref = 9;
-const uint32 JavaConstantPool::ConstantMethodref = 10;
-const uint32 JavaConstantPool::ConstantInterfaceMethodref = 11;
-const uint32 JavaConstantPool::ConstantNameAndType = 12;
-
-
-static uint32 unimplemented(JavaConstantPool* ctp, Reader& reader,
- uint32 index) {
- fprintf(stderr, "Unimplemented in constant pool: %d\n", index);
- abort();
- return 1;
-}
-
-
-uint32 JavaConstantPool::CtpReaderClass(JavaConstantPool* ctp, Reader& reader,
- uint32 index) {
- uint16 entry = reader.readU2();
- ctp->ctpDef[index] = entry;
- PRINT_DEBUG(JNJVM_LOAD, 3, COLOR_NORMAL, "; [%5d] <class>\t\tutf8 is at %d\n", e,
- entry);
- return 1;
-}
-
-uint32 JavaConstantPool::CtpReaderInteger(JavaConstantPool* ctp, Reader& reader,
- uint32 index) {
- uint32 val = reader.readU4();
- ctp->ctpDef[index] = val;
- PRINT_DEBUG(JNJVM_LOAD, 3, COLOR_NORMAL, "; [%5d] <class>\tinteger: %d\n", e,
- val);
- return 1;
-}
-
-uint32 JavaConstantPool::CtpReaderFloat(JavaConstantPool* ctp, Reader& reader,
- uint32 index) {
- uint32 val = reader.readU4();
- ctp->ctpDef[index] = val;
- PRINT_DEBUG(JNJVM_LOAD, 3, COLOR_NORMAL, "; [%5d] <class>\tfloat: %d\n", e,
- val);
- return 1;
-}
-
-uint32 JavaConstantPool::CtpReaderUTF8(JavaConstantPool* ctp, Reader& reader,
- uint32 index) {
- ctp->ctpDef[index] = reader.cursor;
- uint16 len = reader.readU2();
- reader.cursor += len;
- return 1;
-}
-
-uint32 JavaConstantPool::CtpReaderNameAndType(JavaConstantPool* ctp, Reader& reader,
- uint32 index) {
- uint32 entry = reader.readU4();
- ctp->ctpDef[index] = entry;
- PRINT_DEBUG(JNJVM_LOAD, 3, COLOR_NORMAL,
- "; [%5d] <name/type>\tname is at %d, type is at %d\n", index,
- (entry >> 16), (entry & 0xffff));
- return 1;
-}
-
-uint32 JavaConstantPool::CtpReaderFieldref(JavaConstantPool* ctp,
- Reader& reader, uint32 index) {
-
- uint32 entry = reader.readU4();
- ctp->ctpDef[index] = entry;
- PRINT_DEBUG(JNJVM_LOAD, 3, COLOR_NORMAL,
- "; [%5d] <fieldref>\tclass is at %d, name/type is at %d\n", index,
- (entry >> 16), (entry & 0xffff));
- return 1;
-}
-
-uint32 JavaConstantPool::CtpReaderString(JavaConstantPool* ctp, Reader& reader,
- uint32 index) {
- uint16 entry = reader.readU2();
- ctp->ctpDef[index] = entry;
- PRINT_DEBUG(JNJVM_LOAD, 3, COLOR_NORMAL, "; [%5d] <string>\tutf8 is at %d\n",
- index, entry);
- return 1;
-}
-
-uint32 JavaConstantPool::CtpReaderMethodref(JavaConstantPool* ctp,
- Reader& reader,
- uint32 index) {
- uint32 entry = reader.readU4();
- ctp->ctpDef[index] = entry;
- PRINT_DEBUG(JNJVM_LOAD, 3, COLOR_NORMAL,
- "; [%5d] <methodref>\tclass is at %d, name/type is at %d\n",
- index, (entry >> 16), (entry & 0xffff));
- return 1;
-}
-
-uint32 JavaConstantPool::CtpReaderInterfaceMethodref(JavaConstantPool* ctp,
- Reader& reader,
- uint32 index) {
- uint32 entry = reader.readU4();
- ctp->ctpDef[index] = entry;
- PRINT_DEBUG(JNJVM_LOAD, 3, COLOR_NORMAL,
- "; [%5d] <Interface xmethodref>\tclass is at %d, name/type is at %d\n",
- index, (entry >> 16), (entry & 0xffff));
- return 1;
-}
-
-uint32 JavaConstantPool::CtpReaderLong(JavaConstantPool* ctp, Reader& reader,
- uint32 index) {
- ctp->ctpDef[index + 1] = reader.readU4();
- ctp->ctpDef[index] = reader.readU4();
- PRINT_DEBUG(JNJVM_LOAD, 3, COLOR_NORMAL, "; [%5d] <long>%d %d\n", index,
- ctpDef[e], ctpDef[e + 1]);
- return 2;
-}
-
-uint32 JavaConstantPool::CtpReaderDouble(JavaConstantPool* ctp, Reader& reader,
- uint32 index) {
- ctp->ctpDef[index + 1] = reader.readU4();
- ctp->ctpDef[index] = reader.readU4();
- PRINT_DEBUG(JNJVM_LOAD, 3, COLOR_NORMAL, "; [%5d] <double>%d %d\n", index,
- ctp->ctpDef[index], ctp->ctpDef[index + 1]);
- return 2;
-}
-
-
-void*
-JavaConstantPool::operator new(size_t sz, mvm::BumpPtrAllocator& allocator,
- uint32 ctpSize) {
- uint32 size = sz + ctpSize * (sizeof(void*) + sizeof(sint32) + sizeof(uint8));
- return allocator.Allocate(size, "Constant pool");
-}
-
-JavaConstantPool::JavaConstantPool(Class* cl, Reader& reader, uint32 size) {
- ctpSize = size;
- classDef = cl;
-
- ctpType = (uint8*)((uint64)this + sizeof(JavaConstantPool));
- ctpDef = (sint32*)((uint64)ctpType + ctpSize * sizeof(uint8));
- ctpRes = (void**)((uint64)ctpDef + ctpSize * sizeof(sint32));
-
- memset(ctpType, 0,
- ctpSize * (sizeof(uint8) + sizeof(sint32) + sizeof(void*)));
-
- uint32 cur = 1;
- while (cur < ctpSize) {
- uint8 curType = reader.readU1();
- ctpType[cur] = curType;
- cur += ((funcsReader[curType])(this, reader, cur));
- }
-}
-
-const UTF8* JavaConstantPool::UTF8At(uint32 entry) {
- if (!((entry > 0) && (entry < ctpSize) && typeAt(entry) == ConstantUTF8)) {
- fprintf(stderr, "Malformed class %s\n",
- UTF8Buffer(classDef->name).cString());
- abort();
- }
-
- if (!ctpRes[entry]) {
- mvm::ThreadAllocator allocator;
- Reader reader(classDef->bytes, ctpDef[entry]);
- uint32 len = reader.readU2();
- uint16* buf = (uint16*)allocator.Allocate(len * sizeof(uint16));
- uint32 n = 0;
- uint32 i = 0;
-
- while (i < len) {
- uint32 cur = reader.readU1();
- if (cur & 0x80) {
- uint32 y = reader.readU1();
- if (cur & 0x20) {
- uint32 z = reader.readU1();
- cur = ((cur & 0x0F) << 12) +
- ((y & 0x3F) << 6) +
- (z & 0x3F);
- i += 3;
- } else {
- cur = ((cur & 0x1F) << 6) +
- (y & 0x3F);
- i += 2;
- }
- } else {
- ++i;
- }
- buf[n] = ((uint16)cur);
- ++n;
- }
-
- JnjvmClassLoader* loader = classDef->classLoader;
- const UTF8* utf8 = loader->hashUTF8->lookupOrCreateReader(buf, n);
- ctpRes[entry] = const_cast<UTF8*>(utf8);
-
- PRINT_DEBUG(JNJVM_LOAD, 3, COLOR_NORMAL, "; [%5d] <utf8>\t\t\"%s\"\n",
- entry, UTF8Buffer(utf8)->cString());
-
- }
- return (const UTF8*)ctpRes[entry];
-}
-
-float JavaConstantPool::FloatAt(uint32 entry) {
- if (!((entry > 0) && (entry < ctpSize) && typeAt(entry) == ConstantFloat)) {
- fprintf(stderr, "Malformed class %s\n",
- UTF8Buffer(classDef->name).cString());
- abort();
- }
- return ((float*)ctpDef)[entry];
-}
-
-sint32 JavaConstantPool::IntegerAt(uint32 entry) {
- if (!((entry > 0) && (entry < ctpSize) && typeAt(entry) == ConstantInteger)) {
- fprintf(stderr, "Malformed class %s\n",
- UTF8Buffer(classDef->name).cString());
- abort();
- }
- return ((sint32*)ctpDef)[entry];
-}
-
-sint64 JavaConstantPool::LongAt(uint32 entry) {
- if (!((entry > 0) && (entry < ctpSize) && typeAt(entry) == ConstantLong)) {
- fprintf(stderr, "Malformed class %s\n",
- UTF8Buffer(classDef->name).cString());
- abort();
- }
- return Reader::readLong(ctpDef[entry], ctpDef[entry + 1]);
-}
-
-double JavaConstantPool::DoubleAt(uint32 entry) {
- if (!((entry > 0) && (entry < ctpSize) && typeAt(entry) == ConstantDouble)) {
- fprintf(stderr, "Malformed class %s\n",
- UTF8Buffer(classDef->name).cString());
- abort();
- }
- return Reader::readDouble(ctpDef[entry], ctpDef[entry + 1]);
-}
-
-CommonClass* JavaConstantPool::isClassLoaded(uint32 entry) {
- if (!((entry > 0) && (entry < ctpSize) && typeAt(entry) == ConstantClass)) {
- fprintf(stderr, "Malformed class %s\n",
- UTF8Buffer(classDef->name).cString());
- abort();
- }
- return (CommonClass*)ctpRes[entry];
-}
-
-const UTF8* JavaConstantPool::resolveClassName(uint32 index) {
- CommonClass* cl = isClassLoaded(index);
- if (cl) return cl->name;
- else return UTF8At(ctpDef[index]);
-}
-
-CommonClass* JavaConstantPool::loadClass(uint32 index, bool resolve) {
- CommonClass* temp = isClassLoaded(index);
- if (!temp) {
- JnjvmClassLoader* loader = classDef->classLoader;
- const UTF8* name = UTF8At(ctpDef[index]);
- if (name->elements[0] == I_TAB) {
- temp = loader->constructArray(name);
- } else {
- temp = loader->loadName(name, resolve, false, NULL);
- }
- ctpRes[index] = temp;
- }
- return temp;
-}
-
-CommonClass* JavaConstantPool::getMethodClassIfLoaded(uint32 index) {
- CommonClass* temp = isClassLoaded(index);
- if (!temp) {
- JnjvmClassLoader* loader = classDef->classLoader;
- assert(loader && "Class has no loader?");
- const UTF8* name = UTF8At(ctpDef[index]);
- temp = loader->lookupClassOrArray(name);
- }
-
- if (!temp && classDef->classLoader->getCompiler()->isStaticCompiling()) {
- temp = loadClass(index);
- }
- return temp;
-}
-
-Typedef* JavaConstantPool::resolveNameAndType(uint32 index) {
- void* res = ctpRes[index];
- if (!res) {
- if (typeAt(index) != ConstantNameAndType) {
- fprintf(stderr, "Malformed class %s\n",
- UTF8Buffer(classDef->name).cString());
- abort();
- }
- sint32 entry = ctpDef[index];
- const UTF8* type = UTF8At(entry & 0xFFFF);
- Typedef* sign = classDef->classLoader->constructType(type);
- ctpRes[index] = sign;
- return sign;
- }
- return (Typedef*)res;
-}
-
-Signdef* JavaConstantPool::resolveNameAndSign(uint32 index) {
- void* res = ctpRes[index];
- if (!res) {
- if (typeAt(index) != ConstantNameAndType) {
- fprintf(stderr, "Malformed class %s\n",
- UTF8Buffer(classDef->name).cString());
- abort();
- }
- sint32 entry = ctpDef[index];
- const UTF8* type = UTF8At(entry & 0xFFFF);
- Signdef* sign = classDef->classLoader->constructSign(type);
- ctpRes[index] = sign;
- return sign;
- }
- return (Signdef*)res;
-}
-
-Typedef* JavaConstantPool::infoOfField(uint32 index) {
- if (typeAt(index) != ConstantFieldref) {
- fprintf(stderr, "Malformed class %s\n",
- UTF8Buffer(classDef->name).cString());
- abort();
- }
-
- return resolveNameAndType(ctpDef[index] & 0xFFFF);
-}
-
-void JavaConstantPool::infoOfMethod(uint32 index, uint32 access,
- CommonClass*& cl, JavaMethod*& meth) {
- uint8 id = typeAt(index);
- if (id != ConstantMethodref && id != ConstantInterfaceMethodref) {
- fprintf(stderr, "Malformed class %s\n", UTF8Buffer(classDef->name).cString());
- abort();
- }
-
- Signdef* sign = resolveNameAndSign(ctpDef[index] & 0xFFFF);
- sint32 entry = ctpDef[index];
- sint32 ntIndex = entry & 0xFFFF;
- const UTF8* utf8 = UTF8At(ctpDef[ntIndex] >> 16);
- cl = getMethodClassIfLoaded(entry >> 16);
- if (cl) {
- Class* lookup = cl->isArray() ? cl->super : cl->asClass();
- if (lookup->isResolved()) {
-
- // lookup the method
- meth = lookup->lookupMethodDontThrow(utf8, sign->keyName, isStatic(access),
- true, 0);
- // OK, this is rare, but the Java bytecode may do an invokevirtual on an
- // interface method. Lookup the method as if it was static.
- // The caller is responsible for taking any action if the method is
- // an interface method.
- if (!meth) {
- meth = lookup->lookupInterfaceMethodDontThrow(utf8, sign->keyName);
- }
- }
- }
-}
-
-uint32 JavaConstantPool::getClassIndexFromMethod(uint32 index) {
- sint32 entry = ctpDef[index];
- return (uint32)(entry >> 16);
-}
-
-
-void JavaConstantPool::nameOfStaticOrSpecialMethod(uint32 index,
- const UTF8*& cl,
- const UTF8*& name,
- Signdef*& sign) {
- uint8 id = typeAt(index);
- if (id != ConstantMethodref && id != ConstantInterfaceMethodref) {
- fprintf(stderr, "Malformed class %s\n",
- UTF8Buffer(classDef->name).cString());
- abort();
- }
-
- sign = resolveNameAndSign(ctpDef[index] & 0xFFFF);
- sint32 entry = ctpDef[index];
- sint32 ntIndex = entry & 0xFFFF;
- name = UTF8At(ctpDef[ntIndex] >> 16);
- cl = resolveClassName(entry >> 16);
-}
-
-JavaMethod* JavaConstantPool::infoOfStaticOrSpecialMethod(uint32 index,
- uint32 access,
- Signdef* sign) {
- uint8 id = typeAt(index);
- if (id != ConstantMethodref && id != ConstantInterfaceMethodref) {
- fprintf(stderr, "Malformed class %s\n",
- UTF8Buffer(classDef->name).cString());
- abort();
- }
-
- sint32 entry = ctpDef[index];
- sint32 ntIndex = entry & 0xFFFF;
- const UTF8* utf8 = UTF8At(ctpDef[ntIndex] >> 16);
- CommonClass* cl = getMethodClassIfLoaded(entry >> 16);
- JavaMethod* meth = 0;
- if (cl) {
- Class* lookup = cl->isArray() ? cl->super : cl->asClass();
- if (lookup->isResolved()) {
- // lookup the method
- if (isStatic(access)) {
- meth = lookup->lookupMethodDontThrow(utf8, sign->keyName,
- true, true, 0);
- } else {
- meth = lookup->lookupSpecialMethodDontThrow(utf8, sign->keyName,
- classDef);
- }
- }
- }
-
- return meth;
-}
-
-
-Signdef* JavaConstantPool::infoOfInterfaceOrVirtualMethod(uint32 index,
- const UTF8*& name) {
-
- uint8 id = typeAt(index);
- if (id != ConstantMethodref && id != ConstantInterfaceMethodref) {
- fprintf(stderr, "Malformed class %s\n",
- UTF8Buffer(classDef->name).cString());
- abort();
- }
-
- sint32 entry = ctpDef[index];
- sint32 ntIndex = entry & 0xFFFF;
- Signdef* sign = resolveNameAndSign(ntIndex);
- name = UTF8At(ctpDef[ntIndex] >> 16);
- return sign;
-}
-
-void JavaConstantPool::resolveMethod(uint32 index, CommonClass*& cl,
- const UTF8*& utf8, Signdef*& sign) {
- sint32 entry = ctpDef[index];
- sint32 ntIndex = entry & 0xFFFF;
- sign = (Signdef*)ctpRes[ntIndex];
- assert(sign && "No cached signature after JITting");
- utf8 = UTF8At(ctpDef[ntIndex] >> 16);
- cl = loadClass(entry >> 16);
- assert(cl && "No class after loadClass");
- assert((cl->isClass() && cl->asClass()->isResolved()) &&
- "Class not resolved after loadClass");
-}
-
-void JavaConstantPool::resolveField(uint32 index, CommonClass*& cl,
- const UTF8*& utf8, Typedef*& sign) {
- sint32 entry = ctpDef[index];
- sint32 ntIndex = entry & 0xFFFF;
- sign = (Typedef*)ctpRes[ntIndex];
- assert(sign && "No cached Typedef after JITting");
- utf8 = UTF8At(ctpDef[ntIndex] >> 16);
- cl = loadClass(entry >> 16);
- assert(cl && "No class after loadClass");
- assert((cl->isClass() && cl->asClass()->isResolved()) &&
- "Class not resolved after loadClass");
-}
-
-JavaField* JavaConstantPool::lookupField(uint32 index, bool stat) {
- sint32 entry = ctpDef[index];
- sint32 ntIndex = entry & 0xFFFF;
- Typedef* sign = (Typedef*)ctpRes[ntIndex];
- const UTF8* utf8 = UTF8At(ctpDef[ntIndex] >> 16);
- CommonClass* cl = getMethodClassIfLoaded(entry >> 16);
- if (cl) {
- Class* lookup = cl->isArray() ? cl->super : cl->asClass();
- if (lookup->isResolved()) {
- JavaField* field = lookup->lookupFieldDontThrow(utf8, sign->keyName, stat,
- true, 0);
- // don't throw if no field, the exception will be thrown just in time
- if (field) {
- if (!stat) {
- ctpRes[index] = (void*)field->ptrOffset;
- } else if (lookup->isReady()) {
- void* S = field->classDef->getStaticInstance();
- ctpRes[index] = (void*)((uint64)S + field->ptrOffset);
- }
- }
- return field;
- }
- }
- return 0;
-}
-
-JavaString* JavaConstantPool::resolveString(const UTF8* utf8, uint16 index) {
- JavaString* str = NULL;
- llvm_gcroot(str, 0);
- str = classDef->classLoader->vm->internalUTF8ToStr(utf8);
- return str;
-}
-
-JavaConstantPool::ctpReader JavaConstantPool::funcsReader[16] = {
- unimplemented,
- CtpReaderUTF8,
- unimplemented,
- CtpReaderInteger,
- CtpReaderFloat,
- CtpReaderLong,
- CtpReaderDouble,
- CtpReaderClass,
- CtpReaderString,
- CtpReaderFieldref,
- CtpReaderMethodref,
- CtpReaderInterfaceMethodref,
- CtpReaderNameAndType,
- unimplemented,
- unimplemented,
- unimplemented
-};
diff --git a/vmkit/lib/J3/VMCore/JavaConstantPool.h b/vmkit/lib/J3/VMCore/JavaConstantPool.h
deleted file mode 100644
index ac65ec7..0000000
--- a/vmkit/lib/J3/VMCore/JavaConstantPool.h
+++ /dev/null
@@ -1,264 +0,0 @@
-//===--- JavaConstantPool.h - Java constant pool definition ---------------===//
-//
-// The VMKit project
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#ifndef JNJVM_JAVA_CONSTANT_POOL_H
-#define JNJVM_JAVA_CONSTANT_POOL_H
-
-#include "mvm/Allocator.h"
-#include "types.h"
-
-#include "UTF8.h"
-
-namespace j3 {
-
-class Class;
-class CommonClass;
-class JavaField;
-class JavaMethod;
-class JavaString;
-class Reader;
-class Signdef;
-class Typedef;
-
-/// JavaConstantPool - This class represents a Java constant pool, a place where
-/// a Java class makes external references such as classes and methods and
-/// stores constants such as integers or UTF8s.
-class JavaConstantPool : public mvm::PermanentObject {
-public:
-
- /// classDef - The owning class of this constant pool.
- ///
- Class* classDef;
-
- /// ctpSize - The number of entries in the constant pool.
- ///
- uint32 ctpSize;
-
- /// ctpType - The types of the constant pool entries.
- ///
- uint8* ctpType;
-
- /// ctpDef - The values of the constant pool entries: may be constants or
- /// references to other entries.
- ///
- sint32* ctpDef;
-
- /// ctpRes - Objects resolved dynamically, e.g. UTF8s, classes, methods,
- /// fields, string pointers.
- ///
- void** ctpRes;
-
- /// operator new - Redefine the operator to allocate the arrays of a
- /// constant pool inline.
- void* operator new(size_t sz, mvm::BumpPtrAllocator& allocator,
- uint32 ctpSize);
-
- /// CtpReaderClass - Reads a class entry.
- static uint32 CtpReaderClass(JavaConstantPool* ctp, Reader& reader,
- uint32 index);
-
- /// CtpReaderInteger - Reads an integer entry.
- static uint32 CtpReaderInteger(JavaConstantPool* ctp, Reader& reader,
- uint32 index);
-
- /// CtpReaderFloat - Reads a float entry.
- static uint32 CtpReaderFloat(JavaConstantPool* ctp, Reader& reader,
- uint32 index);
-
- /// CtpReaderClass - Reads an UTF8 entry.
- static uint32 CtpReaderUTF8(JavaConstantPool* ctp, Reader& reader,
- uint32 index);
-
- /// CtpReaderNameAndType - Reads a name/signature entry.
- static uint32 CtpReaderNameAndType(JavaConstantPool* ctp, Reader& reader,
- uint32 index);
-
- /// CtpReaderFieldref - Reads a field entry.
- static uint32 CtpReaderFieldref(JavaConstantPool* ctp, Reader& reader,
- uint32 index);
-
- /// CtpReaderString - Reads a string entry.
- static uint32 CtpReaderString(JavaConstantPool* ctp, Reader& reader,
- uint32 index);
-
- /// CtpReaderMethodref - Reads a method entry.
- static uint32 CtpReaderMethodref(JavaConstantPool* ctp, Reader& reader,
- uint32 index);
-
- /// CtpReaderInterfaceMethodref - Reads a method of an interface entry.
- static uint32 CtpReaderInterfaceMethodref(JavaConstantPool* ctp,
- Reader& reader,
- uint32 index);
-
- /// CtpReaderLong - Reads a long entry.
- static uint32 CtpReaderLong(JavaConstantPool* ctp, Reader& reader,
- uint32 index);
-
- /// CtpReaderClass - Reads a double entry.
- static uint32 CtpReaderDouble(JavaConstantPool* ctp, Reader& reader,
- uint32 index);
-
- static const uint32 ConstantUTF8;
- static const uint32 ConstantInteger;
- static const uint32 ConstantFloat;
- static const uint32 ConstantLong;
- static const uint32 ConstantDouble;
- static const uint32 ConstantClass;
- static const uint32 ConstantString;
- static const uint32 ConstantFieldref;
- static const uint32 ConstantMethodref;
- static const uint32 ConstantInterfaceMethodref;
- static const uint32 ConstantNameAndType;
-
- typedef uint32 (*ctpReader)(JavaConstantPool*, Reader&, uint32);
-
- /// funcsReader - Array of CtpReader* functions.
- ///
- static ctpReader funcsReader[16];
-
- /// isAStaticCall - Is the name/type at the given entry a reference to a
- /// static method?
- bool isAStaticCall(uint32 index) {
- return (ctpType[index] & 0x80) != 0;
- }
-
- /// markAsStaticCall - Set the name/type entry as a reference to a static
- /// method.
- void markAsStaticCall(uint32 index) {
- ctpType[index] |= 0x80;
- }
-
- /// typeAt - Get the constant pool type of the given entry.
- ///
- uint8 typeAt(uint32 index) {
- return ctpType[index] & 0x7F;
- }
-
- /// UTF8At - Get the UTF8 at the given entry.
- ///
- const UTF8* UTF8At(uint32 entry);
-
- /// UTF8At - Get the UTF8 referenced from this string entry.
- ///
- const UTF8* UTF8AtForString(uint32 entry) {
- return UTF8At(ctpDef[entry]);
- }
-
- /// FloatAt - Get the float at the given entry.
- ///
- float FloatAt(uint32 entry);
-
- /// IntegerAt - Get the int at the given entry.
- ///
- sint32 IntegerAt(uint32 entry);
-
- /// LongAt - Get the long at the given entry.
- ///
- sint64 LongAt(uint32 entry);
-
- /// DoubleAt - Get the double at the given entry.
- ///
- double DoubleAt(uint32 entry);
-
- /// isClassLoaded - Is the class at the given entry already loaded?
- ///
- CommonClass* isClassLoaded(uint32 index);
-
- /// resolveClassName - Get the name of the class referenced and returns
- /// it.
- ///
- const UTF8* resolveClassName(uint32 index);
-
- /// resolveNameAndType - Resolve the name/type at the given index,
- /// and returns the type.
- Typedef* resolveNameAndType(uint32 index);
-
- /// resolveNameAndSign - Resolve the name/sign at the given index,
- /// and returns the signature.
- Signdef* resolveNameAndSign(uint32 index);
-
- /// infoOfInterfaceOrVirtualMethod - Get the signature of the method
- /// referenced at the given entry.
- Signdef* infoOfInterfaceOrVirtualMethod(uint32 index, const UTF8*& name);
-
- /// infoOfStaticOrSpecialMethod - Get the JavaMethod of a non-virtual
- /// method. Return null if not loaded yet.
- ///
- JavaMethod* infoOfStaticOrSpecialMethod(uint32 index, uint32 access,
- Signdef* sign);
-
-
- /// nameOfStaticOrSpecialMethod - Get the name and the signature
- /// of a non-virtual method.
- ///
- void nameOfStaticOrSpecialMethod(uint32 index, const UTF8*& cl,
- const UTF8*& name, Signdef*& sign);
-
- /// getClassIndexFromMethod - Get the entry of the class that owns
- /// the referenced method.
- ///
- uint32 getClassIndexFromMethod(uint32 index);
-
- /// getMethodClassIfLoaded - Returns the class of the given method if
- /// loaded, null if not.
- CommonClass* getMethodClassIfLoaded(uint32 index);
-
- /// infoOfField - Get the Typedef representation of the field referenced
- /// at the given entry. This does not involve any class loading.
- ///
- Typedef* infoOfField(uint32 index);
-
- /// infoOfMethod - Get the signature of the method referenced at the given
- /// entry and try to find the method. This does not involve any class
- /// loading.
- ///
- void infoOfMethod(uint32 index, uint32 access, CommonClass*& cl,
- JavaMethod*& meth);
-
- /// lookupField - Lookup the field at the given entry.
- ///
- JavaField* lookupField(uint32 index, bool stat);
-
- /// resolveString - Get the string referenced at the given
- /// index from the UTF8.
- JavaString* resolveString(const UTF8* utf8, uint16 index);
-
- /// resolveMethod - Resolve the class and the signature of the method. May
- /// perform class loading. This function is called just in time, ie when
- /// the method call is actually made and not yet resolved.
- ///
- void resolveMethod(uint32 index, CommonClass*& cl,
- const UTF8*& utf8, Signdef*& sign);
-
- /// resolveField - Resolve the class and signature of the field. May
- /// perform class loading. This function is called just in time, ie when
- /// the field is accessed and not yet resolved.
- ///
- void resolveField(uint32 index, CommonClass*& cl, const UTF8*& utf8,
- Typedef*& sign);
-
- /// loadClass - Loads the class and returns it. This is called just in time,
- /// ie when the class will be used and not yet resolved, and also for
- /// loading exceptions when JITting catch clauses.
- ///
- CommonClass* loadClass(uint32 index, bool resolve = true);
-
- /// JavaConstantPool - Reads the bytecode of the class to get
- /// the initial types and constants definitions.
- ///
- JavaConstantPool(Class*, Reader& reader, uint32 ctpSize);
-
- /// ~JavaConstantPool - Delete the constant pool.
- ///
- ~JavaConstantPool() {}
-};
-
-} // end namespace j3
-
-#endif
diff --git a/vmkit/lib/J3/VMCore/JavaMetaJIT.cpp b/vmkit/lib/J3/VMCore/JavaMetaJIT.cpp
deleted file mode 100644
index 21db8b2..0000000
--- a/vmkit/lib/J3/VMCore/JavaMetaJIT.cpp
+++ /dev/null
@@ -1,291 +0,0 @@
-//===----- JavaMetaJIT.cpp - Caling Java methods from native code ---------===//
-//
-// The VMKit project
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#include <cstdarg>
-#include <cstring>
-#include <jni.h>
-
-#include "debug.h"
-
-#include "JavaClass.h"
-#include "JavaObject.h"
-#include "JavaThread.h"
-#include "JavaTypes.h"
-#include "JavaUpcalls.h"
-#include "Jnjvm.h"
-
-using namespace j3;
-
-
-#define readArgs(buf, signature, ap, jni) { \
- jvalue* buffer = (jvalue*)buf; \
- Typedef* const* arguments = signature->getArgumentsType(); \
- for (uint32 i = 0; i < signature->nbArguments; ++i) { \
- const Typedef* type = arguments[i];\
- if (type->isPrimitive()) {\
- const PrimitiveTypedef* prim = (const PrimitiveTypedef*)type;\
- if (prim->isLong()) {\
- buffer[i].j = va_arg(ap, sint64);\
- } else if (prim->isInt()){ \
- buffer[i].i = va_arg(ap, sint32);\
- } else if (prim->isChar()) { \
- buffer[i].c = va_arg(ap, uint32);\
- } else if (prim->isShort()) { \
- buffer[i].s = va_arg(ap, sint32);\
- } else if (prim->isByte()) { \
- buffer[i].b = va_arg(ap, sint32);\
- } else if (prim->isBool()) { \
- buffer[i].z = va_arg(ap, uint32);\
- } else if (prim->isFloat()) {\
- buffer[i].f = (float)va_arg(ap, double);\
- } else if (prim->isDouble()) {\
- buffer[i].d = va_arg(ap, double);\
- } else {\
- fprintf(stderr, "Can't happen");\
- abort();\
- }\
- } else{\
- buffer[i].l = reinterpret_cast<jobject>(va_arg(ap, JavaObject**));\
- }\
- }\
-}
-
-#if defined(DWARF_EXCEPTIONS)
-
-#define DO_TRY try {
-#define DO_CATCH } catch(...) { th->throwFromJava(); } \
-
-#else
-
-#define DO_TRY
-#define DO_CATCH if (th->mut->getPendingException()) { th->throwFromJava(); }
-
-#endif
-
-//===----------------------------------------------------------------------===//
-// We do not need to have special care on the GC-pointers in the buffer
-// manipulated in these functions because the objects in the buffer are
-// addressed and never stored directly.
-//===----------------------------------------------------------------------===//
-
-#if 1 // VA_ARGS do not work on all platforms for LLVM.
-#define INVOKE_AP(TYPE, TYPE_NAME, FUNC_TYPE_VIRTUAL_AP, FUNC_TYPE_STATIC_AP, FUNC_TYPE_VIRTUAL_BUF, FUNC_TYPE_STATIC_BUF) \
-\
-TYPE JavaMethod::invoke##TYPE_NAME##VirtualAP(UserClass* cl, JavaObject* obj, va_list ap) { \
- llvm_gcroot(obj, 0); \
- verifyNull(obj); \
- Signdef* sign = getSignature(); \
- mvm::ThreadAllocator allocator; \
- jvalue* buf = (jvalue*)allocator.Allocate(sign->nbArguments * sizeof(jvalue)); \
- readArgs(buf, sign, ap, jni); \
- return invoke##TYPE_NAME##VirtualBuf(cl, obj, buf); \
-}\
-\
-TYPE JavaMethod::invoke##TYPE_NAME##SpecialAP(UserClass* cl, JavaObject* obj, va_list ap) {\
- llvm_gcroot(obj, 0); \
- verifyNull(obj); \
- Signdef* sign = getSignature(); \
- mvm::ThreadAllocator allocator; \
- jvalue* buf = (jvalue*)allocator.Allocate(sign->nbArguments * sizeof(jvalue)); \
- readArgs(buf, sign, ap, jni); \
- return invoke##TYPE_NAME##SpecialBuf(cl, obj, buf); \
-}\
-\
-TYPE JavaMethod::invoke##TYPE_NAME##StaticAP(UserClass* cl, va_list ap) {\
- Signdef* sign = getSignature(); \
- mvm::ThreadAllocator allocator; \
- jvalue* buf = (jvalue*)allocator.Allocate(sign->nbArguments * sizeof(jvalue)); \
- readArgs(buf, sign, ap, jni); \
- return invoke##TYPE_NAME##StaticBuf(cl, buf); \
-}
-
-#else
-
-#define INVOKE_AP(TYPE, TYPE_NAME, FUNC_TYPE_VIRTUAL_AP, FUNC_TYPE_STATIC_AP, FUNC_TYPE_VIRTUAL_BUF, FUNC_TYPE_STATIC_BUF) \
-TYPE JavaMethod::invoke##TYPE_NAME##VirtualAP(UserClass* cl, JavaObject* obj, va_list ap) { \
- llvm_gcroot(obj, 0); \
- verifyNull(obj); \
- UserClass* objCl = JavaObject::getClass(obj)->isArray() ? JavaObject::getClass(obj)->super : JavaObject::getClass(obj)->asClass(); \
- if (objCl == classDef || isFinal(access)) { \
- meth = this; \
- } else { \
- meth = objCl->lookupMethodDontThrow(name, type, false, true, &cl); \
- } \
- assert(meth && "No method found"); \
- void* func = meth->compiledPtr(); \
- Signdef* sign = getSignature(); \
- FUNC_TYPE_VIRTUAL_AP call = (FUNC_TYPE_VIRTUAL_AP)sign->getVirtualCallAP(); \
- JavaThread* th = JavaThread::get(); \
- th->startJava(); \
- TYPE res = 0; \
- DO_TRY \
- res = call(cl->getConstantPool(), func, obj, ap);\
- DO_CATCH \
- th->endJava(); \
- return res; \
-}\
-\
-TYPE JavaMethod::invoke##TYPE_NAME##SpecialAP(UserClass* cl, JavaObject* obj, va_list ap) {\
- llvm_gcroot(obj, 0); \
- verifyNull(obj);\
- void* func = this->compiledPtr();\
- Signdef* sign = getSignature(); \
- FUNC_TYPE_VIRTUAL_AP call = (FUNC_TYPE_VIRTUAL_AP)sign->getVirtualCallAP(); \
- JavaThread* th = JavaThread::get(); \
- th->startJava(); \
- TYPE res = 0; \
- DO_TRY \
- res = call(cl->getConstantPool(), func, obj, ap);\
- DO_CATCH \
- th->endJava(); \
- return res; \
-}\
-\
-TYPE JavaMethod::invoke##TYPE_NAME##StaticAP(UserClass* cl, va_list ap) {\
- if (!cl->isReady()) { \
- cl->resolveClass(); \
- cl->initialiseClass(); \
- } \
- \
- void* func = this->compiledPtr();\
- Signdef* sign = getSignature(); \
- FUNC_TYPE_STATIC_AP call = (FUNC_TYPE_STATIC_AP)sign->getStaticCallAP(); \
- JavaThread* th = JavaThread::get(); \
- th->startJava(); \
- TYPE res = 0; \
- DO_TRY \
- res = call(cl->getConstantPool(), func, ap);\
- DO_CATCH \
- th->endJava(); \
- return res; \
-}
-
-#endif
-
-#define INVOKE_BUF(TYPE, TYPE_NAME, FUNC_TYPE_VIRTUAL_AP, FUNC_TYPE_STATIC_AP, FUNC_TYPE_VIRTUAL_BUF, FUNC_TYPE_STATIC_BUF) \
-TYPE JavaMethod::invoke##TYPE_NAME##VirtualBuf(UserClass* cl, JavaObject* obj, void* buf) {\
- llvm_gcroot(obj, 0); \
- verifyNull(obj);\
- Signdef* sign = getSignature(); \
- UserClass* objCl = JavaObject::getClass(obj)->isArray() ? JavaObject::getClass(obj)->super : JavaObject::getClass(obj)->asClass(); \
- JavaMethod* meth = NULL; \
- if (objCl == classDef || isFinal(access)) { \
- meth = this; \
- } else { \
- meth = objCl->lookupMethodDontThrow(name, type, false, true, &cl); \
- } \
- assert(meth && "No method found"); \
- assert(objCl->isAssignableFrom(meth->classDef) && "Wrong type"); \
- void* func = meth->compiledPtr(); \
- FUNC_TYPE_VIRTUAL_BUF call = (FUNC_TYPE_VIRTUAL_BUF)sign->getVirtualCallBuf(); \
- JavaThread* th = JavaThread::get(); \
- th->startJava(); \
- TYPE res = 0; \
- DO_TRY \
- res = call(cl->getConstantPool(), func, obj, buf);\
- DO_CATCH \
- th->endJava(); \
- return res; \
-}\
-TYPE JavaMethod::invoke##TYPE_NAME##SpecialBuf(UserClass* cl, JavaObject* obj, void* buf) {\
- llvm_gcroot(obj, 0); \
- verifyNull(obj);\
- void* func = this->compiledPtr();\
- Signdef* sign = getSignature(); \
- FUNC_TYPE_VIRTUAL_BUF call = (FUNC_TYPE_VIRTUAL_BUF)sign->getVirtualCallBuf(); \
- JavaThread* th = JavaThread::get(); \
- th->startJava(); \
- TYPE res = 0; \
- DO_TRY \
- res = call(cl->getConstantPool(), func, obj, buf);\
- DO_CATCH \
- th->endJava(); \
- return res; \
-}\
-\
-TYPE JavaMethod::invoke##TYPE_NAME##StaticBuf(UserClass* cl, void* buf) {\
- if (!cl->isReady()) { \
- cl->resolveClass(); \
- cl->initialiseClass(); \
- } \
- \
- void* func = this->compiledPtr();\
- Signdef* sign = getSignature(); \
- FUNC_TYPE_STATIC_BUF call = (FUNC_TYPE_STATIC_BUF)sign->getStaticCallBuf(); \
- JavaThread* th = JavaThread::get(); \
- th->startJava(); \
- TYPE res = 0; \
- DO_TRY \
- res = call(cl->getConstantPool(), func, buf);\
- DO_CATCH \
- th->endJava(); \
- return res; \
-}\
-
-#define INVOKE_VA(TYPE, TYPE_NAME, FUNC_TYPE_VIRTUAL_AP, FUNC_TYPE_STATIC_AP, FUNC_TYPE_VIRTUAL_BUF, FUNC_TYPE_STATIC_BUF) \
-TYPE JavaMethod::invoke##TYPE_NAME##Virtual(UserClass* cl, JavaObject* obj, ...) { \
- llvm_gcroot(obj, 0); \
- va_list ap;\
- va_start(ap, obj);\
- TYPE res = invoke##TYPE_NAME##VirtualAP(cl, obj, ap);\
- va_end(ap); \
- return res; \
-}\
-\
-TYPE JavaMethod::invoke##TYPE_NAME##Special(UserClass* cl, JavaObject* obj, ...) {\
- llvm_gcroot(obj, 0); \
- va_list ap;\
- va_start(ap, obj);\
- TYPE res = invoke##TYPE_NAME##SpecialAP(cl, obj, ap);\
- va_end(ap); \
- return res; \
-}\
-\
-TYPE JavaMethod::invoke##TYPE_NAME##Static(UserClass* cl, ...) {\
- va_list ap;\
- va_start(ap, cl);\
- TYPE res = invoke##TYPE_NAME##StaticAP(cl, ap);\
- va_end(ap); \
- return res; \
-}\
-
-#define INVOKE(TYPE, TYPE_NAME, FUNC_TYPE_VIRTUAL_AP, FUNC_TYPE_STATIC_AP, FUNC_TYPE_VIRTUAL_BUF, FUNC_TYPE_STATIC_BUF) \
- INVOKE_AP(TYPE, TYPE_NAME, FUNC_TYPE_VIRTUAL_AP, FUNC_TYPE_STATIC_AP, FUNC_TYPE_VIRTUAL_BUF, FUNC_TYPE_STATIC_BUF) \
- INVOKE_BUF(TYPE, TYPE_NAME, FUNC_TYPE_VIRTUAL_AP, FUNC_TYPE_STATIC_AP, FUNC_TYPE_VIRTUAL_BUF, FUNC_TYPE_STATIC_BUF) \
- INVOKE_VA(TYPE, TYPE_NAME, FUNC_TYPE_VIRTUAL_AP, FUNC_TYPE_STATIC_AP, FUNC_TYPE_VIRTUAL_BUF, FUNC_TYPE_STATIC_BUF)
-
-typedef uint32 (*uint32_virtual_ap)(UserConstantPool*, void*, JavaObject*, va_list);
-typedef sint64 (*sint64_virtual_ap)(UserConstantPool*, void*, JavaObject*, va_list);
-typedef float (*float_virtual_ap)(UserConstantPool*, void*, JavaObject*, va_list);
-typedef double (*double_virtual_ap)(UserConstantPool*, void*, JavaObject*, va_list);
-typedef JavaObject* (*object_virtual_ap)(UserConstantPool*, void*, JavaObject*, va_list);
-
-typedef uint32 (*uint32_static_ap)(UserConstantPool*, void*, va_list);
-typedef sint64 (*sint64_static_ap)(UserConstantPool*, void*, va_list);
-typedef float (*float_static_ap)(UserConstantPool*, void*, va_list);
-typedef double (*double_static_ap)(UserConstantPool*, void*, va_list);
-typedef JavaObject* (*object_static_ap)(UserConstantPool*, void*, va_list);
-
-typedef uint32 (*uint32_virtual_buf)(UserConstantPool*, void*, JavaObject*, void*);
-typedef sint64 (*sint64_virtual_buf)(UserConstantPool*, void*, JavaObject*, void*);
-typedef float (*float_virtual_buf)(UserConstantPool*, void*, JavaObject*, void*);
-typedef double (*double_virtual_buf)(UserConstantPool*, void*, JavaObject*, void*);
-typedef JavaObject* (*object_virtual_buf)(UserConstantPool*, void*, JavaObject*, void*);
-
-typedef uint32 (*uint32_static_buf)(UserConstantPool*, void*, void*);
-typedef sint64 (*sint64_static_buf)(UserConstantPool*, void*, void*);
-typedef float (*float_static_buf)(UserConstantPool*, void*, void*);
-typedef double (*double_static_buf)(UserConstantPool*, void*, void*);
-typedef JavaObject* (*object_static_buf)(UserConstantPool*, void*, void*);
-
-INVOKE(uint32, Int, uint32_virtual_ap, uint32_static_ap, uint32_virtual_buf, uint32_static_buf)
-INVOKE(sint64, Long, sint64_virtual_ap, sint64_static_ap, sint64_virtual_buf, sint64_static_buf)
-INVOKE(float, Float, float_virtual_ap, float_static_ap, float_virtual_buf, float_static_buf)
-INVOKE(double, Double, double_virtual_ap, double_static_ap, double_virtual_buf, double_static_buf)
-INVOKE(JavaObject*, JavaObject, object_virtual_ap, object_static_ap, object_virtual_buf, object_static_buf)
diff --git a/vmkit/lib/J3/VMCore/JavaObject.cpp b/vmkit/lib/J3/VMCore/JavaObject.cpp
deleted file mode 100644
index 931f546..0000000
--- a/vmkit/lib/J3/VMCore/JavaObject.cpp
+++ /dev/null
@@ -1,269 +0,0 @@
-//===----------- JavaObject.cpp - Java object definition ------------------===//
-//
-// The VMKit project
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#include "mvm/Threads/Locks.h"
-
-#include "JavaClass.h"
-#include "JavaObject.h"
-#include "JavaThread.h"
-#include "JavaTypes.h"
-#include "JavaUpcalls.h"
-#include "Jnjvm.h"
-
-#include <jni.h>
-#include "debug.h"
-
-using namespace j3;
-
-static const int hashCodeIncrement = mvm::GCBitMask + 1;
-uint16_t JavaObject::hashCodeGenerator = hashCodeIncrement;
-static const uint64_t HashMask = ((1 << mvm::HashBits) - 1) << mvm::GCBits;
-
-
-/// hashCode - Return the hash code of this object.
-uint32_t JavaObject::hashCode(JavaObject* self) {
- llvm_gcroot(self, 0);
- if (!mvm::MovesObject) return (uint32_t)(long)self;
- assert(HashMask != 0);
- assert(mvm::HashBits != 0);
-
- uintptr_t header = self->header;
- uintptr_t GCBits = header & mvm::GCBitMask;
- uintptr_t val = header & HashMask;
- if (val != 0) {
- return val ^ (uintptr_t)getClass(self);
- }
- val = hashCodeGenerator;
- hashCodeGenerator += hashCodeIncrement;
- val = val & HashMask;
- if (val == 0) {
- // It is possible that in the same time, a thread is in this method and
- // gets the same hash code value than this thread. This is fine.
- val = hashCodeIncrement;
- hashCodeGenerator += hashCodeIncrement;
- }
- assert(val > mvm::GCBitMask);
- assert(val <= HashMask);
-
- do {
- header = self->header;
- if ((header & HashMask) != 0) break;
- uintptr_t newHeader = header | val;
- assert((newHeader & ~HashMask) == header);
- __sync_val_compare_and_swap(&(self->header), header, newHeader);
- } while (true);
-
- assert((self->header & HashMask) != 0);
- assert(GCBits == (self->header & mvm::GCBitMask));
- return (self->header & HashMask) ^ (uintptr_t)getClass(self);
-}
-
-
-void JavaObject::waitIntern(
- JavaObject* self, struct timeval* info, bool timed) {
- llvm_gcroot(self, 0);
- JavaThread* thread = JavaThread::get();
- mvm::LockSystem& table = thread->getJVM()->lockSystem;
-
- if (!owner(self)) {
- thread->getJVM()->illegalMonitorStateException(self);
- UNREACHABLE();
- }
-
- bool interrupted = thread->lockingThread.wait(self, table, info, timed);
-
- if (interrupted) {
- thread->getJVM()->interruptedException(self);
- UNREACHABLE();
- }
-}
-
-void JavaObject::wait(JavaObject* self) {
- llvm_gcroot(self, 0);
- waitIntern(self, NULL, false);
-}
-
-void JavaObject::timedWait(JavaObject* self, struct timeval& info) {
- llvm_gcroot(self, 0);
- waitIntern(self, &info, true);
-}
-
-void JavaObject::notify(JavaObject* self) {
- llvm_gcroot(self, 0);
- JavaThread* thread = JavaThread::get();
- mvm::LockSystem& table = thread->getJVM()->lockSystem;
-
- if (!owner(self)) {
- thread->getJVM()->illegalMonitorStateException(self);
- UNREACHABLE();
- }
- thread->lockingThread.notify(self, table);
-}
-
-void JavaObject::notifyAll(JavaObject* self) {
- llvm_gcroot(self, 0);
- JavaThread* thread = JavaThread::get();
- mvm::LockSystem& table = thread->getJVM()->lockSystem;
-
- if (!owner(self)) {
- thread->getJVM()->illegalMonitorStateException(self);
- UNREACHABLE();
- }
- thread->lockingThread.notifyAll(self, table);
-}
-
-void JavaObject::overflowThinLock(JavaObject* self) {
- llvm_gcroot(self, 0);
- mvm::ThinLock::overflowThinLock(self, self->getJVM()->lockSystem);
-}
-
-void JavaObject::acquire(JavaObject* self) {
- llvm_gcroot(self, 0);
- mvm::ThinLock::acquire(self, self->getJVM()->lockSystem);
-}
-
-void JavaObject::release(JavaObject* self) {
- llvm_gcroot(self, 0);
- mvm::ThinLock::release(self, self->getJVM()->lockSystem);
-}
-
-bool JavaObject::owner(JavaObject* self) {
- llvm_gcroot(self, 0);
- return mvm::ThinLock::owner(self, self->getJVM()->lockSystem);
-}
-
-void JavaObject::decapsulePrimitive(JavaObject* obj, jvalue* buf,
- const Typedef* signature) {
-
- llvm_gcroot(obj, 0);
-
- Jnjvm* vm = obj->getJVM();
-
- if (!signature->isPrimitive()) {
- if (obj && !(getClass(obj)->isOfTypeName(signature->getName()))) {
- vm->illegalArgumentException("wrong type argument");
- }
- return;
- } else if (obj == NULL) {
- vm->illegalArgumentException("");
- } else {
- UserCommonClass* cl = getClass(obj);
- UserClassPrimitive* value = cl->toPrimitive();
- const PrimitiveTypedef* prim = (const PrimitiveTypedef*)signature;
-
- if (value == 0) {
- vm->illegalArgumentException("");
- }
-
- if (prim->isShort()) {
- if (value == vm->upcalls->OfShort) {
- (*buf).s = vm->upcalls->shortValue->getInstanceInt16Field(obj);
- return;
- } else if (value == vm->upcalls->OfByte) {
- (*buf).s = (sint16)vm->upcalls->byteValue->getInstanceInt8Field(obj);
- return;
- } else {
- vm->illegalArgumentException("");
- }
- } else if (prim->isByte()) {
- if (value == vm->upcalls->OfByte) {
- (*buf).b = vm->upcalls->byteValue->getInstanceInt8Field(obj);
- return;
- } else {
- vm->illegalArgumentException("");
- }
- } else if (prim->isBool()) {
- if (value == vm->upcalls->OfBool) {
- (*buf).z = vm->upcalls->boolValue->getInstanceInt8Field(obj);
- return;
- } else {
- vm->illegalArgumentException("");
- }
- } else if (prim->isInt()) {
- if (value == vm->upcalls->OfInt) {
- (*buf).i = vm->upcalls->intValue->getInstanceInt32Field(obj);
- } else if (value == vm->upcalls->OfByte) {
- (*buf).i = (sint32)vm->upcalls->byteValue->getInstanceInt8Field(obj);
- } else if (value == vm->upcalls->OfChar) {
- (*buf).i = (uint32)vm->upcalls->charValue->getInstanceInt16Field(obj);
- } else if (value == vm->upcalls->OfShort) {
- (*buf).i = (sint32)vm->upcalls->shortValue->getInstanceInt16Field(obj);
- } else {
- vm->illegalArgumentException("");
- }
- return;
- } else if (prim->isChar()) {
- if (value == vm->upcalls->OfChar) {
- (*buf).c = (uint16)vm->upcalls->charValue->getInstanceInt16Field(obj);
- } else {
- vm->illegalArgumentException("");
- }
- return;
- } else if (prim->isFloat()) {
- if (value == vm->upcalls->OfFloat) {
- (*buf).f = (float)vm->upcalls->floatValue->getInstanceFloatField(obj);
- } else if (value == vm->upcalls->OfByte) {
- (*buf).f = (float)(sint32)vm->upcalls->byteValue->getInstanceInt8Field(obj);
- } else if (value == vm->upcalls->OfChar) {
- (*buf).f = (float)(uint32)vm->upcalls->charValue->getInstanceInt16Field(obj);
- } else if (value == vm->upcalls->OfShort) {
- (*buf).f = (float)(sint32)vm->upcalls->shortValue->getInstanceInt16Field(obj);
- } else if (value == vm->upcalls->OfInt) {
- (*buf).f = (float)(sint32)vm->upcalls->intValue->getInstanceInt32Field(obj);
- } else if (value == vm->upcalls->OfLong) {
- (*buf).f = (float)vm->upcalls->longValue->getInstanceLongField(obj);
- } else {
- vm->illegalArgumentException("");
- }
- return;
- } else if (prim->isDouble()) {
- if (value == vm->upcalls->OfDouble) {
- (*buf).d = (double)vm->upcalls->doubleValue->getInstanceDoubleField(obj);
- } else if (value == vm->upcalls->OfFloat) {
- (*buf).d = (double)vm->upcalls->floatValue->getInstanceFloatField(obj);
- } else if (value == vm->upcalls->OfByte) {
- (*buf).d = (double)(sint64)vm->upcalls->byteValue->getInstanceInt8Field(obj);
- } else if (value == vm->upcalls->OfChar) {
- (*buf).d = (double)(uint64)vm->upcalls->charValue->getInstanceInt16Field(obj);
- } else if (value == vm->upcalls->OfShort) {
- (*buf).d = (double)(sint16)vm->upcalls->shortValue->getInstanceInt16Field(obj);
- } else if (value == vm->upcalls->OfInt) {
- (*buf).d = (double)(sint32)vm->upcalls->intValue->getInstanceInt32Field(obj);
- } else if (value == vm->upcalls->OfLong) {
- (*buf).d = (double)(sint64)vm->upcalls->longValue->getInstanceLongField(obj);
- } else {
- vm->illegalArgumentException("");
- }
- return;
- } else if (prim->isLong()) {
- if (value == vm->upcalls->OfByte) {
- (*buf).j = (sint64)vm->upcalls->byteValue->getInstanceInt8Field(obj);
- } else if (value == vm->upcalls->OfChar) {
- (*buf).j = (sint64)(uint64)vm->upcalls->charValue->getInstanceInt16Field(obj);
- } else if (value == vm->upcalls->OfShort) {
- (*buf).j = (sint64)vm->upcalls->shortValue->getInstanceInt16Field(obj);
- } else if (value == vm->upcalls->OfInt) {
- (*buf).j = (sint64)vm->upcalls->intValue->getInstanceInt32Field(obj);
- } else if (value == vm->upcalls->OfLong) {
- (*buf).j = (sint64)vm->upcalls->intValue->getInstanceLongField(obj);
- } else {
- vm->illegalArgumentException("");
- }
- return;
- }
- }
- // can not be here
- return;
-}
-
-bool JavaObject::instanceOf(JavaObject* self, UserCommonClass* cl) {
- llvm_gcroot(self, 0);
- if (self == NULL) return false;
- else return getClass(self)->isAssignableFrom(cl);
-}
diff --git a/vmkit/lib/J3/VMCore/JavaObject.h b/vmkit/lib/J3/VMCore/JavaObject.h
deleted file mode 100644
index 641238e..0000000
--- a/vmkit/lib/J3/VMCore/JavaObject.h
+++ /dev/null
@@ -1,308 +0,0 @@
-//===----------- JavaObject.h - Java object definition -------------------===//
-//
-// The VMKit project
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#ifndef JNJVM_JAVA_OBJECT_H
-#define JNJVM_JAVA_OBJECT_H
-
-#include "mvm/Allocator.h"
-#include "mvm/GC.h"
-#include "mvm/UTF8.h"
-#include "mvm/Threads/Locks.h"
-#include "mvm/Threads/Thread.h"
-
-#include "types.h"
-
-#include "JnjvmConfig.h"
-
-union jvalue;
-
-namespace j3 {
-
-class JavaObject;
-class JavaThread;
-class Jnjvm;
-class Typedef;
-class UserCommonClass;
-
-class InterfaceMethodTable : public mvm::PermanentObject {
-public:
- static const uint32_t NumIndexes = 29;
- uintptr_t contents[NumIndexes];
-
- static uint32_t getIndex(const mvm::UTF8* name, const mvm::UTF8* type) {
- return (name->hash() + type->hash()) % NumIndexes;
- }
-};
-
-/// JavaVirtualTable - This class is the virtual table of instances of
-/// Java classes. Besides holding function pointers for virtual calls,
-/// it contains a bunch of information useful for fast dynamic type checking.
-/// These are placed here for fast access of information from a Java object
-/// (that only points to the VT, not the class).
-///
-class JavaVirtualTable : public mvm::VirtualTable {
-public:
-
- /// cl - The class which defined this virtual table.
- ///
- CommonClass* cl;
-
- /// depth - The super hierarchy depth of the class.
- ///
- size_t depth;
-
- /// offset - Offset in the virtual table where this virtual
- /// table may be pointed. The offset is the cache if the class
- /// is an interface or depth is too big, or an offset in the display.
- ///
- size_t offset;
-
- /// cache - The cached result for better type checks on secondary types.
- ///
- JavaVirtualTable* cache;
-
- /// display - Array of super classes.
- ///
- JavaVirtualTable* display[8];
-
- /// nbSecondaryTypes - The length of the secondary type list.
- ///
- size_t nbSecondaryTypes;
-
- /// secondaryTypes - The list of secondary types of this type. These
- /// are the interface and all the supers whose depth is too big.
- ///
- JavaVirtualTable** secondaryTypes;
-
- /// baseClassVT - Holds the base class VT of an array. Used for AASTORE
- /// checks.
- ///
- JavaVirtualTable* baseClassVT;
-
- /// IMT - The interface method table.
- ///
- InterfaceMethodTable* IMT;
-
- /// Java methods for the virtual table functions.
- uintptr_t init;
- uintptr_t equals;
- uintptr_t hashCode;
- uintptr_t toString;
- uintptr_t clone;
- uintptr_t getClass;
- uintptr_t notify;
- uintptr_t notifyAll;
- uintptr_t waitIndefinitely;
- uintptr_t waitMs;
- uintptr_t waitMsNs;
- uintptr_t virtualMethods[1];
-
- /// operator new - Allocates a JavaVirtualTable with the given size. The
- /// size must contain the additional information for type checking, as well
- /// as the function pointers.
- ///
- void* operator new(size_t sz, mvm::BumpPtrAllocator& allocator,
- uint32 nbMethods) {
- return allocator.Allocate(sizeof(uintptr_t) * (nbMethods), "Virtual table");
- }
-
- /// JavaVirtualTable - Create JavaVirtualTable objects for classes, array
- /// classes and primitive classes.
- ///
- JavaVirtualTable(Class* C);
- JavaVirtualTable(ClassArray* C);
- JavaVirtualTable(ClassPrimitive* C);
-
-
- /// getFirstJavaMethod - Get the byte offset of the first Java method
- /// (<init>).
- ///
- uintptr_t* getFirstJavaMethod() {
- return &init;
- }
-
- /// getFirstJavaMethodIndex - Get the word offset of the first Java method.
- ///
- static uint32_t getFirstJavaMethodIndex() {
- return numberOfBaseFunctions() + 16;
- }
-
- /// getBaseSize - Get the size of the java.lang.Object virtual table.
- ///
- static uint32_t getBaseSize() {
- return numberOfBaseFunctions() + 27;
- }
-
- /// getNumJavaMethods - Get the number of methods of the java.lang.Object
- /// class.
- ///
- static uint32_t getNumJavaMethods() {
- return 11;
- }
-
- /// getDisplayLength - Get the length of the display (primary type) array.
- ///
- static uint32_t getDisplayLength() {
- return 8;
- }
-
- /// getClassIndex - Get the word offset of the class.
- ///
- static uint32_t getClassIndex() {
- return numberOfBaseFunctions();
- }
-
- /// getDepthIndex - Get the word offset of the depth.
- ///
- static uint32_t getDepthIndex() {
- return numberOfBaseFunctions() + 1;
- }
-
- /// getOffsetIndex - Get the word offset of the type cache.
- ///
- static uint32_t getOffsetIndex() {
- return numberOfBaseFunctions() + 2;
- }
-
- /// getCacheIndex - Get the word offset of the type cache.
- ///
- static uint32_t getCacheIndex() {
- return numberOfBaseFunctions() + 3;
- }
-
- /// getDisplayIndex - Get the word offset of the display.
- ///
- static uint32_t getDisplayIndex() {
- return numberOfBaseFunctions() + 4;
- }
-
- /// getNumSecondaryTypesIndex - Get the word offset of the number of
- /// secondary types.
- ///
- static uint32_t getNumSecondaryTypesIndex() {
- return numberOfBaseFunctions() + 12;
- }
-
- /// getSecondaryTypesIndex - Get the word offset of the secondary types
- /// list.
- ///
- static uint32_t getSecondaryTypesIndex() {
- return numberOfBaseFunctions() + 13;
- }
-
- /// getBaseClassIndex - Get the word offset of the base class.
- ///
- static uint32_t getBaseClassIndex() {
- return numberOfBaseFunctions() + 14;
- }
-
- /// getIMTIndex - Get the word offset of the IMT.
- ///
- static uint32_t getIMTIndex() {
- return numberOfBaseFunctions() + 15;
- }
-
- /// isSubtypeOf - Returns true if the given VT is a subtype of the this
- /// VT.
- ///
- bool isSubtypeOf(JavaVirtualTable* VT);
-
- /// setNativeTracer - Set the tracer of this virtual table as a method
- /// defined by JnJVM.
- ///
- void setNativeTracer(uintptr_t tracer, const char* name);
-
- /// setNativeDestructor - Set the destructor of this virtual table as a method
- /// defined by JnJVM.
- ///
- void setNativeDestructor(uintptr_t tracer, const char* name);
-
-};
-
-
-/// JavaObject - This class represents a Java object.
-///
-class JavaObject : public mvm::gc {
-private:
-
- /// waitIntern - internal wait on a monitor
- ///
- static void waitIntern(JavaObject* self, struct timeval *info, bool timed);
-
-public:
-
- Jnjvm* getJVM() { return (Jnjvm*)getVirtualTable()->vm; }
-
- /// getClass - Returns the class of this object.
- ///
- static UserCommonClass* getClass(const JavaObject* self) {
- llvm_gcroot(self, 0);
- return ((JavaVirtualTable*)self->getVirtualTable())->cl;
- }
-
- /// instanceOf - Is this object's class of type the given class?
- ///
- static bool instanceOf(JavaObject* self, UserCommonClass* cl);
-
- /// wait - Java wait. Makes the current thread waiting on a monitor.
- ///
- static void wait(JavaObject* self);
-
- /// timedWait - Java timed wait. Makes the current thread waiting on a
- /// monitor for the given amount of time.
- ///
- static void timedWait(JavaObject* self, struct timeval &info);
-
- /// notify - Java notify. Notifies a thread from the availability of the
- /// monitor.
- ///
- static void notify(JavaObject* self);
-
- /// notifyAll - Java notifyAll. Notifies all threads from the availability of
- /// the monitor.
- ///
- static void notifyAll(JavaObject* self);
-
- /// overflowThinLock - Notify that the thin lock has overflowed.
- ///
- static void overflowThinLock(JavaObject* self);
-
- /// acquire - Acquire the lock on this object.
- static void acquire(JavaObject* self);
-
- /// release - Release the lock on this object
- static void release(JavaObject* self);
-
- /// owner - Returns true if the current thread is the owner of this object's
- /// lock.
- static bool owner(JavaObject* self);
-
-#ifdef SIGSEGV_THROW_NULL
- #define verifyNull(obj) {}
-#else
- #define verifyNull(obj) \
- if (obj == NULL) JavaThread::get()->getJVM()->nullPointerException();
-#endif
-
- /// decapsulePrimitive - Based on the signature argument, decapsule
- /// obj as a primitive and put it in the buffer.
- ///
- static void decapsulePrimitive(JavaObject* self, jvalue* buf,
- const Typedef* signature);
-
- static uint16_t hashCodeGenerator;
-
- /// hashCode - Return the hash code of this object.
- static uint32_t hashCode(JavaObject* self);
-};
-
-
-} // end namespace j3
-
-#endif
diff --git a/vmkit/lib/J3/VMCore/JavaRuntimeJIT.cpp b/vmkit/lib/J3/VMCore/JavaRuntimeJIT.cpp
deleted file mode 100644
index 3debd1f..0000000
--- a/vmkit/lib/J3/VMCore/JavaRuntimeJIT.cpp
+++ /dev/null
@@ -1,740 +0,0 @@
-//===-------------------- JavaRuntimeJIT.cpp ------------------------------===//
-//=== ---- Runtime functions called by code compiled by the JIT -----------===//
-//
-// The VMKit project
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-
-#include "ClasspathReflect.h"
-#include "JavaArray.h"
-#include "JavaClass.h"
-#include "JavaConstantPool.h"
-#include "JavaString.h"
-#include "JavaThread.h"
-#include "JavaTypes.h"
-#include "JavaUpcalls.h"
-#include "Jnjvm.h"
-
-#include "j3/OpcodeNames.def"
-
-#include <cstdarg>
-
-using namespace j3;
-
-extern "C" void* j3InterfaceLookup(UserClass* caller, uint32 index) {
-
- void* res = 0;
-
- BEGIN_NATIVE_EXCEPTION(1)
-
- UserConstantPool* ctpInfo = caller->getConstantPool();
- if (ctpInfo->ctpRes[index]) {
- res = ctpInfo->ctpRes[index];
- } else {
- UserCommonClass* cl = 0;
- const UTF8* utf8 = 0;
- Signdef* sign = 0;
-
- ctpInfo->resolveMethod(index, cl, utf8, sign);
- assert(cl->isClass() && isInterface(cl->access) && "Wrong type of method");
- res = cl->asClass()->lookupInterfaceMethod(utf8, sign->keyName);
-
- ctpInfo->ctpRes[index] = (void*)res;
- }
-
-
- END_NATIVE_EXCEPTION
-
- // Since the function is marked readnone, LLVM may move it after the
- // exception check. Therefore, we trick LLVM to check the return value of the
- // function.
-#define hack_check(type) \
- mvm::gc* obj = mvm::Thread::get()->getPendingException(); \
- if (obj) return (type)obj;
-
- hack_check(void*);
-
- return res;
-}
-
-// Throws if the field is not found.
-extern "C" void* j3VirtualFieldLookup(UserClass* caller, uint32 index) {
-
- void* res = 0;
-
- BEGIN_NATIVE_EXCEPTION(1)
-
- UserConstantPool* ctpInfo = caller->getConstantPool();
- if (ctpInfo->ctpRes[index]) {
- res = ctpInfo->ctpRes[index];
- } else {
-
- UserCommonClass* cl = 0;
- const UTF8* utf8 = 0;
- Typedef* sign = 0;
-
- ctpInfo->resolveField(index, cl, utf8, sign);
-
- UserClass* lookup = cl->isArray() ? cl->super : cl->asClass();
- JavaField* field = lookup->lookupField(utf8, sign->keyName, false, true, 0);
-
- ctpInfo->ctpRes[index] = (void*)field->ptrOffset;
-
- res = (void*)field->ptrOffset;
- }
-
- END_NATIVE_EXCEPTION
-
- hack_check(void*);
-
- return res;
-}
-
-// Throws if the field or its class is not found.
-extern "C" void* j3StaticFieldLookup(UserClass* caller, uint32 index) {
-
- void* res = 0;
-
- BEGIN_NATIVE_EXCEPTION(1)
-
- UserConstantPool* ctpInfo = caller->getConstantPool();
-
- if (ctpInfo->ctpRes[index]) {
- res = ctpInfo->ctpRes[index];
- } else {
-
- UserCommonClass* cl = 0;
- UserClass* fieldCl = 0;
- const UTF8* utf8 = 0;
- Typedef* sign = 0;
-
- ctpInfo->resolveField(index, cl, utf8, sign);
-
- assert(cl->asClass() && "Lookup a field of something not an array");
- JavaField* field = cl->asClass()->lookupField(utf8, sign->keyName, true,
- true, &fieldCl);
-
- fieldCl->initialiseClass();
- void* obj = ((UserClass*)fieldCl)->getStaticInstance();
-
- assert(obj && "No static instance in static field lookup");
-
- void* ptr = (void*)((uint64)obj + field->ptrOffset);
- ctpInfo->ctpRes[index] = ptr;
-
- res = ptr;
- }
-
- END_NATIVE_EXCEPTION
-
- hack_check(void*);
-
- return res;
-}
-
-#ifndef WITHOUT_VTABLE
-// Throws if the method is not found.
-extern "C" uint32 j3VirtualTableLookup(UserClass* caller, uint32 index,
- uint32* offset, JavaObject* obj) {
- llvm_gcroot(obj, 0);
- uint32 res = 0;
-
- BEGIN_NATIVE_EXCEPTION(1)
-
- UserCommonClass* cl = 0;
- const UTF8* utf8 = 0;
- Signdef* sign = 0;
-
- caller->getConstantPool()->resolveMethod(index, cl, utf8, sign);
- UserClass* lookup = cl->isArray() ? cl->super : cl->asClass();
- JavaMethod* dmeth = lookup->lookupMethodDontThrow(utf8, sign->keyName, false,
- true, 0);
- if (!dmeth) {
- assert((JavaObject::getClass(obj)->isClass() &&
- JavaObject::getClass(obj)->asClass()->isInitializing()) &&
- "Class not ready in a virtual lookup.");
- // Arg, the bytecode is buggy! Perform the lookup on the object class
- // and do not update offset.
- lookup = JavaObject::getClass(obj)->isArray() ?
- JavaObject::getClass(obj)->super :
- JavaObject::getClass(obj)->asClass();
- dmeth = lookup->lookupMethod(utf8, sign->keyName, false, true, 0);
- } else {
- *offset = dmeth->offset;
- }
-
- assert(dmeth->classDef->isInitializing() &&
- "Class not ready in a virtual lookup.");
-
- res = dmeth->offset;
-
- END_NATIVE_EXCEPTION
-
- return res;
-}
-#endif
-
-// Throws if the class is not found.
-extern "C" void* j3ClassLookup(UserClass* caller, uint32 index) {
-
- void* res = 0;
-
- BEGIN_NATIVE_EXCEPTION(1)
-
- UserConstantPool* ctpInfo = caller->getConstantPool();
- UserCommonClass* cl = ctpInfo->loadClass(index);
- // We can not initialize here, because bytecodes such as CHECKCAST
- // or classes used in catch clauses do not trigger class initialization.
- // This is really sad, because we need to insert class initialization checks
- // in the LLVM code.
- assert(cl && "No cl after class lookup");
- res = (void*)cl;
-
- // Create the array class, in case we come from a ANEWARRAY.
- if (cl->isClass() && !cl->virtualVT->baseClassVT) {
- const UTF8* arrayName =
- cl->classLoader->constructArrayName(1, cl->getName());
- cl->virtualVT->baseClassVT =
- cl->classLoader->constructArray(arrayName)->virtualVT;
- }
-
- END_NATIVE_EXCEPTION
-
-
- hack_check(void*);
-
- return res;
-}
-
-// Calls Java code.
-// Throws if initializing the class throws an exception.
-extern "C" UserCommonClass* j3RuntimeInitialiseClass(UserClass* cl) {
- BEGIN_NATIVE_EXCEPTION(1)
-
- cl->resolveClass();
- cl->initialiseClass();
-
- END_NATIVE_EXCEPTION
-
- hack_check(UserCommonClass*);
-
- return cl;
-}
-
-// Calls Java code.
-extern "C" JavaObject* j3RuntimeDelegatee(UserCommonClass* cl) {
- JavaObject* res = 0;
- llvm_gcroot(res, 0);
-
- BEGIN_NATIVE_EXCEPTION(1)
- res = cl->getClassDelegatee();
- END_NATIVE_EXCEPTION
-
- hack_check(JavaObject*);
-
- return res;
-}
-
-// Throws if one of the dimension is negative.
-JavaObject* multiCallNewIntern(UserClassArray* cl, uint32 len, sint32* dims) {
- assert(len > 0 && "Negative size given by VMKit");
-
- JavaObject* _res = cl->doNew(dims[0]);
- ArrayObject* res = NULL;
- JavaObject* temp = NULL;
- llvm_gcroot(_res, 0);
- llvm_gcroot(res, 0);
- llvm_gcroot(temp, 0);
-
- if (len > 1) {
- res = (ArrayObject*)_res;
- UserCommonClass* _base = cl->baseClass();
- assert(_base->isArray() && "Base class not an array");
- UserClassArray* base = (UserClassArray*)_base;
- if (dims[0] > 0) {
- for (sint32 i = 0; i < dims[0]; ++i) {
- temp = multiCallNewIntern(base, (len - 1), &dims[1]);
- ArrayObject::setElement(res, temp, i);
- }
- } else {
- for (uint32 i = 1; i < len; ++i) {
- sint32 p = dims[i];
- if (p < 0) {
- cl->classLoader->vm->negativeArraySizeException(p);
- }
- }
- }
- }
- return _res;
-}
-
-// Throws if one of the dimension is negative.
-extern "C" JavaObject* j3MultiCallNew(UserClassArray* cl, uint32 len, ...) {
- JavaObject* res = 0;
- llvm_gcroot(res, 0);
-
- BEGIN_NATIVE_EXCEPTION(1)
-
- va_list ap;
- va_start(ap, len);
- mvm::ThreadAllocator allocator;
- sint32* dims = (sint32*)allocator.Allocate(sizeof(sint32) * len);
- for (uint32 i = 0; i < len; ++i){
- dims[i] = va_arg(ap, int);
- }
- res = multiCallNewIntern(cl, len, dims);
-
- END_NATIVE_EXCEPTION
-
- return res;
-}
-
-// Throws if the class can not be resolved.
-extern "C" JavaVirtualTable* j3GetArrayClass(UserClass* caller,
- uint32 index,
- JavaVirtualTable** VT) {
- JavaVirtualTable* res = 0;
- assert(VT && "Incorrect call to j3GetArrayClass");
- BEGIN_NATIVE_EXCEPTION(1)
-
- UserConstantPool* ctpInfo = caller->getConstantPool();
- UserCommonClass* cl = ctpInfo->loadClass(index);
-
- JnjvmClassLoader* JCL = cl->classLoader;
- if (cl->asClass()) cl->asClass()->resolveClass();
- const UTF8* arrayName = JCL->constructArrayName(1, cl->getName());
-
- res = JCL->constructArray(arrayName)->virtualVT;
- *VT = res;
-
- END_NATIVE_EXCEPTION
-
- hack_check(JavaVirtualTable*);
-
- return res;
-}
-
-// Does not call Java code. Can not yield a GC.
-extern "C" void j3EndJNI(uint32** oldLRN) {
- JavaThread* th = JavaThread::get();
-
- // We're going back to Java
- th->endJNI();
-
- // Update the number of references.
- th->currentAddedReferences = *oldLRN;
-}
-
-extern "C" void* j3StartJNI(uint32* localReferencesNumber,
- uint32** oldLocalReferencesNumber,
- mvm::KnownFrame* Frame)
- __attribute__((noinline));
-
-// Never throws. Does not call Java code. Can not yied a GC.
-extern "C" void* j3StartJNI(uint32* localReferencesNumber,
- uint32** oldLocalReferencesNumber,
- mvm::KnownFrame* Frame) {
-
- mvm::Thread* mut = mvm::Thread::get();
- JavaThread* th = JavaThread::j3Thread(mut);
-
- *oldLocalReferencesNumber = th->currentAddedReferences;
- th->currentAddedReferences = localReferencesNumber;
- th->startJNI();
- mut->startUnknownFrame(*Frame);
- mut->enterUncooperativeCode();
- assert(mut->getLastSP() == mut->lastKnownFrame->currentFP);
-
- return Frame->currentFP;
-}
-
-// Never throws.
-extern "C" void j3JavaObjectAquire(JavaObject* obj) {
- llvm_gcroot(obj, 0);
- JavaObject::acquire(obj);
-}
-
-// Never throws.
-extern "C" void j3JavaObjectRelease(JavaObject* obj) {
- llvm_gcroot(obj, 0);
- JavaObject::release(obj);
-}
-
-// Does not call any Java code. Can not yield a GC.
-extern "C" void j3ThrowException(JavaObject* obj) {
- llvm_gcroot(obj, 0);
- return mvm::Thread::get()->setPendingException(obj)->throwIt();
-}
-
-// Creates a Java object and then throws it.
-extern "C" JavaObject* j3NullPointerException() {
- JavaObject *exc = 0;
- llvm_gcroot(exc, 0);
- JavaThread *th = JavaThread::get();
-
- BEGIN_NATIVE_EXCEPTION(1)
-
- exc = th->getJVM()->CreateNullPointerException();
-
- END_NATIVE_EXCEPTION
-
- th->mut->setPendingException(exc);
- th->throwFromNative();
-
- return exc;
-}
-
-// Creates a Java object and then throws it.
-extern "C" JavaObject* j3NegativeArraySizeException(sint32 val) {
- JavaObject *exc = 0;
- llvm_gcroot(exc, 0);
- JavaThread *th = JavaThread::get();
-
- BEGIN_NATIVE_EXCEPTION(1)
-
- exc = th->getJVM()->CreateNegativeArraySizeException();
-
- END_NATIVE_EXCEPTION
-
- th->mut->setPendingException(exc);
- th->throwFromNative();
-
- return exc;
-}
-
-// Creates a Java object and then throws it.
-extern "C" JavaObject* j3OutOfMemoryError(sint32 val) {
- JavaObject *exc = 0;
- llvm_gcroot(exc, 0);
- JavaThread *th = JavaThread::get();
-
- BEGIN_NATIVE_EXCEPTION(1)
-
- exc = th->getJVM()->CreateOutOfMemoryError();
-
- END_NATIVE_EXCEPTION
-
- th->mut->setPendingException(exc);
- th->throwFromNative();
-
- return exc;
-}
-
-// Creates a Java object and then throws it.
-extern "C" JavaObject* j3StackOverflowError() {
- JavaObject *exc = 0;
- llvm_gcroot(exc, 0);
- JavaThread *th = JavaThread::get();
-
- BEGIN_NATIVE_EXCEPTION(1)
-
- exc = th->getJVM()->CreateStackOverflowError();
-
- END_NATIVE_EXCEPTION
-
- th->mut->setPendingException(exc);
- th->throwFromNative();
-
- return exc;
-}
-
-// Creates a Java object and then throws it.
-extern "C" JavaObject* j3ArithmeticException() {
- JavaObject *exc = 0;
- llvm_gcroot(exc, 0);
- JavaThread *th = JavaThread::get();
-
- BEGIN_NATIVE_EXCEPTION(1)
-
- exc = th->getJVM()->CreateArithmeticException();
-
- END_NATIVE_EXCEPTION
-
- th->mut->setPendingException(exc);
- th->throwFromNative();
-
- return exc;
-}
-
-// Creates a Java object and then throws it.
-extern "C" JavaObject* j3ClassCastException(JavaObject* obj,
- UserCommonClass* cl) {
- JavaObject *exc = 0;
- llvm_gcroot(obj, 0);
- llvm_gcroot(exc, 0);
-
- JavaThread *th = JavaThread::get();
-
- BEGIN_NATIVE_EXCEPTION(1)
-
- exc = th->getJVM()->CreateClassCastException(obj, cl);
-
- END_NATIVE_EXCEPTION
-
- th->mut->setPendingException(exc);
- th->throwFromNative();
-
- return exc;
-}
-
-// Creates a Java object and then throws it.
-extern "C" JavaObject* j3IndexOutOfBoundsException(JavaObject* obj,
- sint32 index) {
- JavaObject *exc = 0;
- llvm_gcroot(obj, 0);
- llvm_gcroot(exc, 0);
-
- JavaThread *th = JavaThread::get();
-
- BEGIN_NATIVE_EXCEPTION(1)
-
- exc = th->getJVM()->CreateIndexOutOfBoundsException(index);
-
- END_NATIVE_EXCEPTION
-
- th->mut->setPendingException(exc);
- th->throwFromNative();
-
- return exc;
-}
-
-// Creates a Java object and then throws it.
-extern "C" JavaObject* j3ArrayStoreException(JavaVirtualTable* VT,
- JavaVirtualTable* VT2) {
- JavaObject *exc = 0;
- llvm_gcroot(exc, 0);
- JavaThread *th = JavaThread::get();
-
- BEGIN_NATIVE_EXCEPTION(1)
- exc = th->getJVM()->CreateArrayStoreException(VT);
-
- END_NATIVE_EXCEPTION
-
- th->mut->setPendingException(exc);
- th->throwFromNative();
-
- return exc;
-}
-
-// Create an exception then throws it.
-extern "C" void j3ThrowExceptionFromJIT() {
- JavaObject *exc = 0;
- llvm_gcroot(exc, 0);
- JavaThread *th = JavaThread::get();
-
- BEGIN_NATIVE_EXCEPTION(1)
-
- JavaMethod* meth = th->getCallingMethodLevel(0);
- exc = th->getJVM()->CreateUnsatisfiedLinkError(meth);
-
- END_NATIVE_EXCEPTION
-
- th->mut->setPendingException(exc);
- th->throwFromNative();
-
-}
-
-extern "C" void* j3StringLookup(UserClass* cl, uint32 index) {
-
- JavaString** str = 0;
-
- BEGIN_NATIVE_EXCEPTION(1)
-
- UserConstantPool* ctpInfo = cl->getConstantPool();
- const UTF8* utf8 = ctpInfo->UTF8At(ctpInfo->ctpDef[index]);
- str = cl->classLoader->UTF8ToStr(utf8);
- ctpInfo->ctpRes[index] = str;
-
- END_NATIVE_EXCEPTION
-
- return (void*)str;
-}
-
-extern "C" void* j3ResolveVirtualStub(JavaObject* obj) {
- llvm_gcroot(obj, 0);
- mvm::Thread *mut = mvm::Thread::get();
- UserCommonClass* cl = JavaObject::getClass(obj);
- void* result = NULL;
-
- BEGIN_NATIVE_EXCEPTION(1)
-
- // Lookup the caller of this class.
- mvm::StackWalker Walker(mut);
- ++Walker; // Remove the stub.
- mvm::MethodInfo* MI = Walker.get();
- assert(MI->isHighLevelMethod() && "Wrong stack trace");
- JavaMethod* meth = (JavaMethod*)MI->MetaInfo;
- void* ip = *Walker;
-
- // Lookup the method info in the constant pool of the caller.
- uint16 ctpIndex = meth->lookupCtpIndex(reinterpret_cast<uintptr_t>(ip));
- assert(ctpIndex && "No constant pool index");
- JavaConstantPool* ctpInfo = meth->classDef->getConstantPool();
- CommonClass* ctpCl = 0;
- const UTF8* utf8 = 0;
- Signdef* sign = 0;
- JavaMethod* origMeth = 0;
- ctpInfo->infoOfMethod(ctpIndex, ACC_VIRTUAL, ctpCl, origMeth);
-
- ctpInfo->resolveMethod(ctpIndex, ctpCl, utf8, sign);
- assert(cl->isAssignableFrom(ctpCl) && "Wrong call object");
- UserClass* lookup = cl->isArray() ? cl->super : cl->asClass();
- JavaMethod* Virt = lookup->lookupMethod(utf8, sign->keyName, false, true, 0);
-
- // Compile the found method.
- result = Virt->compiledPtr();
-
- // Update the virtual table.
- assert(lookup->isResolved() && "Class not resolved");
- assert(lookup->isInitializing() && "Class not ready");
- assert(lookup->virtualVT && "Class has no VT");
- assert(lookup->virtualTableSize > Virt->offset &&
- "The method's offset is greater than the virtual table size");
- ((void**)obj->getVirtualTable())[Virt->offset] = result;
-
- if (isInterface(origMeth->classDef->access)) {
- InterfaceMethodTable* IMT = cl->virtualVT->IMT;
- uint32_t index = InterfaceMethodTable::getIndex(Virt->name, Virt->type);
- if ((IMT->contents[index] & 1) == 0) {
- IMT->contents[index] = (uintptr_t)result;
- } else {
- JavaMethod* Imeth =
- ctpCl->asClass()->lookupInterfaceMethodDontThrow(utf8, sign->keyName);
- assert(Imeth && "Method not in hierarchy?");
- uintptr_t* table = (uintptr_t*)(IMT->contents[index] & ~1);
- uint32 i = 0;
- while (table[i] != (uintptr_t)Imeth) { i += 2; }
- table[i + 1] = (uintptr_t)result;
- }
- }
-
- END_NATIVE_EXCEPTION
-
- return result;
-}
-
-extern "C" void* j3ResolveStaticStub() {
- mvm::Thread *mut = mvm::Thread::get();
- void* result = NULL;
-
- BEGIN_NATIVE_EXCEPTION(1)
-
- // Lookup the caller of this class.
- mvm::StackWalker Walker(mut);
- ++Walker; // Remove the stub.
- mvm::MethodInfo* MI = Walker.get();
- assert(MI->isHighLevelMethod() && "Wrong stack trace");
- JavaMethod* caller = (JavaMethod*)MI->MetaInfo;
- void* ip = *Walker;
-
- // Lookup the method info in the constant pool of the caller.
- uint16 ctpIndex = caller->lookupCtpIndex(reinterpret_cast<uintptr_t>(ip));
- assert(ctpIndex && "No constant pool index");
- JavaConstantPool* ctpInfo = caller->classDef->getConstantPool();
- CommonClass* cl = 0;
- const UTF8* utf8 = 0;
- Signdef* sign = 0;
-
- ctpInfo->resolveMethod(ctpIndex, cl, utf8, sign);
- UserClass* lookup = cl->isArray() ? cl->super : cl->asClass();
- assert(lookup->isInitializing() && "Class not ready");
- JavaMethod* callee = lookup->lookupMethod(utf8, sign->keyName, true, true, 0);
-
- // Compile the found method.
- result = callee->compiledPtr();
-
- // Update the entry in the constant pool.
- ctpInfo->ctpRes[ctpIndex] = result;
-
- END_NATIVE_EXCEPTION
-
- return result;
-}
-
-extern "C" void* j3ResolveSpecialStub() {
- mvm::Thread *mut = mvm::Thread::get();
- void* result = NULL;
-
- BEGIN_NATIVE_EXCEPTION(1)
-
- // Lookup the caller of this class.
- mvm::StackWalker Walker(mut);
- ++Walker; // Remove the stub.
- mvm::MethodInfo* MI = Walker.get();
- assert(MI->isHighLevelMethod() && "Wrong stack trace");
- JavaMethod* caller = (JavaMethod*)MI->MetaInfo;
- void* ip = *Walker;
-
- // Lookup the method info in the constant pool of the caller.
- uint16 ctpIndex = caller->lookupCtpIndex(reinterpret_cast<uintptr_t>(ip));
- assert(ctpIndex && "No constant pool index");
- JavaConstantPool* ctpInfo = caller->classDef->getConstantPool();
- CommonClass* cl = 0;
- const UTF8* utf8 = 0;
- Signdef* sign = 0;
-
- ctpInfo->resolveMethod(ctpIndex, cl, utf8, sign);
- UserClass* lookup = cl->isArray() ? cl->super : cl->asClass();
- assert(lookup->isInitializing() && "Class not ready");
- JavaMethod* callee =
- lookup->lookupSpecialMethodDontThrow(utf8, sign->keyName, caller->classDef);
-
- if (!callee) {
- cl->classLoader->vm->noSuchMethodError(lookup, utf8);
- }
-
- // Compile the found method.
- result = callee->compiledPtr();
-
- // Update the entry in the constant pool.
- ctpInfo->ctpRes[ctpIndex] = result;
-
- END_NATIVE_EXCEPTION
-
- return result;
-}
-
-// Does not throw an exception.
-extern "C" void* j3ResolveInterface(JavaObject* obj, JavaMethod* meth, uint32_t index) {
- uintptr_t result = NULL;
- InterfaceMethodTable* IMT = JavaObject::getClass(obj)->virtualVT->IMT;
- assert(JavaObject::instanceOf(obj, meth->classDef));
- assert(meth->classDef->isInterface() ||
- (meth->classDef == meth->classDef->classLoader->bootstrapLoader->upcalls->OfObject));
- assert(index == InterfaceMethodTable::getIndex(meth->name, meth->type));
- if ((IMT->contents[index] & 1) == 0) {
- result = IMT->contents[index];
- } else {
- uintptr_t* table = (uintptr_t*)(IMT->contents[index] & ~1);
- uint32 i = 0;
- while (table[i] != (uintptr_t)meth && table[i] != 0) { i += 2; }
- assert(table[i] != 0);
- result = table[i + 1];
- }
- assert((result != 0) && "Bad IMT");
- return (void*)result;
-}
-
-extern "C" void j3PrintMethodStart(JavaMethod* meth) {
- fprintf(stderr, "[%p] executing %s.%s\n", (void*)mvm::Thread::get(),
- UTF8Buffer(meth->classDef->name).cString(),
- UTF8Buffer(meth->name).cString());
-}
-
-extern "C" void j3PrintMethodEnd(JavaMethod* meth) {
- fprintf(stderr, "[%p] return from %s.%s\n", (void*)mvm::Thread::get(),
- UTF8Buffer(meth->classDef->name).cString(),
- UTF8Buffer(meth->name).cString());
-}
-
-extern "C" void j3PrintExecution(uint32 opcode, uint32 index,
- JavaMethod* meth) {
- fprintf(stderr, "[%p] executing %s.%s %s at %d\n", (void*)mvm::Thread::get(),
- UTF8Buffer(meth->classDef->name).cString(),
- UTF8Buffer(meth->name).cString(),
- OpcodeNames[opcode], index);
-}
diff --git a/vmkit/lib/J3/VMCore/JavaString.cpp b/vmkit/lib/J3/VMCore/JavaString.cpp
deleted file mode 100644
index 7bb0de9..0000000
--- a/vmkit/lib/J3/VMCore/JavaString.cpp
+++ /dev/null
@@ -1,141 +0,0 @@
-//===-- JavaString.cpp - Internal correspondance with Java Strings --------===//
-//
-// The VMKit project
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#include "JavaArray.h"
-#include "JavaClass.h"
-#include "JavaString.h"
-#include "JavaThread.h"
-#include "JavaUpcalls.h"
-#include "Jnjvm.h"
-#include "LockedMap.h"
-
-using namespace j3;
-
-JavaVirtualTable* JavaString::internStringVT = 0;
-
-JavaString* JavaString::stringDup(const ArrayUInt16*& _array, Jnjvm* vm) {
-
- JavaString* res = 0;
- const ArrayUInt16* array = _array;
- llvm_gcroot(array, 0);
- llvm_gcroot(res, 0);
-
- UserClass* cl = vm->upcalls->newString;
- res = (JavaString*)cl->doNew();
-
- // It's a hashed string, set the destructor so that the string
- // removes itself from the vm string map. Do this only if
- // internStringVT exists (in case of AOT).
- if (internStringVT) res->setVirtualTable(internStringVT);
-
- // No need to call the Java function: both the Java function and
- // this function do the same thing.
- JavaString::setValue(res, array);
- res->count = ArrayUInt16::getSize(array);
- res->offset = 0;
- res->cachedHashCode = 0;
- return res;
-}
-
-char* JavaString::strToAsciiz(JavaString* self) {
- const ArrayUInt16* value = NULL;
- llvm_gcroot(self, 0);
- llvm_gcroot(value, 0);
- value = JavaString::getValue(self);
- char* buf = new char[self->count + 1];
- for (sint32 i = 0; i < self->count; ++i) {
- buf[i] = ArrayUInt16::getElement(value, i + self->offset);
- }
- buf[self->count] = 0;
- return buf;
-}
-
-char* JavaString::strToAsciiz(JavaString* self,
- mvm::ThreadAllocator* allocator) {
- const ArrayUInt16* value = NULL;
- llvm_gcroot(self, 0);
- llvm_gcroot(value, 0);
- value = JavaString::getValue(self);
- char* buf = (char*)allocator->Allocate((self->count + 1) * sizeof(char));
- for (sint32 i = 0; i < self->count; ++i) {
- buf[i] = ArrayUInt16::getElement(value, i + self->offset);
- }
- buf[self->count] = 0;
- return buf;
-}
-
-const ArrayUInt16* JavaString::strToArray(JavaString* self, Jnjvm* vm) {
- ArrayUInt16* array = NULL;
- const ArrayUInt16* value = NULL;
- llvm_gcroot(self, 0);
- llvm_gcroot(array, 0);
- llvm_gcroot(value, 0);
- value = JavaString::getValue(self);
-
- assert(getValue(self) && "String without an array?");
- if (self->offset || (self->count != ArrayUInt16::getSize(getValue(self)))) {
- array = (ArrayUInt16*)vm->upcalls->ArrayOfChar->doNew(self->count);
- for (sint32 i = 0; i < self->count; i++) {
- ArrayUInt16::setElement(
- array, ArrayUInt16::getElement(value, i + self->offset), i);
- }
- return array;
- } else {
- return value;
- }
-}
-
-void JavaString::stringDestructor(JavaString* str) {
- const ArrayUInt16* value = NULL;
- llvm_gcroot(str, 0);
- llvm_gcroot(value, 0);
- value = JavaString::getValue(str);
-
- Jnjvm* vm = str->getJVM();
- assert(vm && "No vm when destroying a string");
- if (value != NULL) vm->hashStr.removeUnlocked(value, str);
-}
-
-JavaString* JavaString::internalToJava(const UTF8* name, Jnjvm* vm) {
-
- ArrayUInt16* array = 0;
- llvm_gcroot(array, 0);
-
- array = (ArrayUInt16*)vm->upcalls->ArrayOfChar->doNew(name->size);
-
- for (sint32 i = 0; i < name->size; i++) {
- uint16 cur = name->elements[i];
- if (cur == '/') {
- ArrayUInt16::setElement(array, '.', i);
- } else {
- ArrayUInt16::setElement(array, cur, i);
- }
- }
-
- return vm->constructString(array);
-}
-
-const UTF8* JavaString::javaToInternal(const JavaString* self, UTF8Map* map) {
- const ArrayUInt16* value = NULL;
- llvm_gcroot(self, 0);
- llvm_gcroot(value, 0);
- value = JavaString::getValue(self);
-
- mvm::ThreadAllocator allocator;
- uint16* java = (uint16*)allocator.Allocate(self->count * sizeof(uint16));
-
- for (sint32 i = 0; i < self->count; ++i) {
- uint16 cur = ArrayUInt16::getElement(value, self->offset + i);
- if (cur == '.') java[i] = '/';
- else java[i] = cur;
- }
-
- const UTF8* res = map->lookupOrCreateReader(java, self->count);
- return res;
-}
diff --git a/vmkit/lib/J3/VMCore/JavaString.h b/vmkit/lib/J3/VMCore/JavaString.h
deleted file mode 100644
index 101b1e4..0000000
--- a/vmkit/lib/J3/VMCore/JavaString.h
+++ /dev/null
@@ -1,63 +0,0 @@
-//===--- JavaString.h - Internal correspondance with Java Strings ---------===//
-//
-// The VMKit project
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#ifndef JNJVM_JAVA_STRING_H
-#define JNJVM_JAVA_STRING_H
-
-#include "types.h"
-
-#include "JavaObject.h"
-#include "UTF8.h"
-
-namespace j3 {
-
-class ArrayUInt16;
-class Jnjvm;
-
-class JavaString : public JavaObject {
-public:
- // CLASSPATH FIELDS!!
- const ArrayUInt16* value;
- sint32 count;
- sint32 cachedHashCode;
- sint32 offset;
-
- static void setValue(JavaString* self, const ArrayUInt16* array) {
- llvm_gcroot(self, 0);
- llvm_gcroot(array, 0);
- self->value = array;
- }
- static const ArrayUInt16* getValue(const JavaString* self) {
- llvm_gcroot(self, 0);
- return self->value;
- }
-
- static JavaString* stringDup(const ArrayUInt16*& array, Jnjvm* vm);
-
- /// internalToJava - Creates a copy of the UTF8 at its given offset and size
- /// with all its '.' replaced by '/'. The JVM bytecode reference classes in
- /// packages with the '.' as the separating character. The JVM language uses
- /// the '/' character. Returns a Java String.
- ///
- static JavaString* internalToJava(const UTF8* utf8, Jnjvm* vm);
-
- static void stringDestructor(JavaString*);
- static char* strToAsciiz(JavaString* self);
- static char* strToAsciiz(JavaString* self, mvm::ThreadAllocator* allocator);
- static const ArrayUInt16* strToArray(JavaString* self, Jnjvm* vm);
-
- /// javaToInternal - Replaces all '/' into '.'.
- static const UTF8* javaToInternal(const JavaString* self, UTF8Map* map);
-
- static JavaVirtualTable* internStringVT;
-};
-
-} // end namespace j3
-
-#endif
diff --git a/vmkit/lib/J3/VMCore/JavaThread.cpp b/vmkit/lib/J3/VMCore/JavaThread.cpp
deleted file mode 100644
index 7399a12..0000000
--- a/vmkit/lib/J3/VMCore/JavaThread.cpp
+++ /dev/null
@@ -1,158 +0,0 @@
-//===--------- JavaThread.cpp - Java thread description -------------------===//
-//
-// The VMKit project
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#include "mvm/Threads/Locks.h"
-#include "mvm/Threads/Thread.h"
-
-#include "JavaClass.h"
-#include "JavaObject.h"
-#include "JavaThread.h"
-#include "JavaUpcalls.h"
-#include "Jnjvm.h"
-
-
-using namespace j3;
-
-JavaThread::JavaThread(Jnjvm* vm, mvm::Thread* mut) : mvm::VMThreadData(vm, mut) {
- jniEnv = vm->jniEnv;
- localJNIRefs = new JNILocalReferences();
- currentAddedReferences = NULL;
- javaThread = NULL;
- vmThread = NULL;
-}
-
-JavaThread* JavaThread::j3Thread(mvm::Thread* mut) {
- return (JavaThread*)mut->vmData;
-}
-
-JavaThread* JavaThread::associate(Jnjvm* vm, mvm::Thread* mut) {
- JavaThread *th = new JavaThread(vm, mut);
- mut->allVmsData[vm->vmID] = th;
- mut->attach(vm);
- return th;
-}
-
-
-void JavaThread::initialise(JavaObject* thread, JavaObject* vmth) {
- llvm_gcroot(thread, 0);
- llvm_gcroot(vmth, 0);
- javaThread = thread;
- vmThread = vmth;
-}
-
-JavaThread::~JavaThread() {
- delete localJNIRefs;
-}
-
-void JavaThread::startJNI() {
- // Interesting, but no need to do anything.
-}
-
-void JavaThread::endJNI() {
- localJNIRefs->removeJNIReferences(this, *currentAddedReferences);
- mut->endUnknownFrame();
-
- // Go back to cooperative mode.
- mut->leaveUncooperativeCode();
-}
-
-uint32 JavaThread::getJavaFrameContext(void** buffer) {
- mvm::StackWalker Walker(mut);
- uint32 i = 0;
-
- while (mvm::MethodInfo* MI = Walker.get()) {
- if (MI->isHighLevelMethod()) {
- JavaMethod* M = (JavaMethod*)MI->MetaInfo;
- buffer[i++] = M;
- }
- ++Walker;
- }
- return i;
-}
-
-JavaMethod* JavaThread::getCallingMethodLevel(uint32 level) {
- mvm::StackWalker Walker(mut);
- uint32 index = 0;
-
- while (mvm::MethodInfo* MI = Walker.get()) {
- if (MI->isHighLevelMethod()) {
- if (index == level) {
- return (JavaMethod*)MI->MetaInfo;
- }
- ++index;
- }
- ++Walker;
- }
- return 0;
-}
-
-UserClass* JavaThread::getCallingClassLevel(uint32 level) {
- JavaMethod* meth = getCallingMethodLevel(level);
- if (meth) return meth->classDef;
- return 0;
-}
-
-JavaObject* JavaThread::getNonNullClassLoader() {
-
- JavaObject* obj = 0;
- llvm_gcroot(obj, 0);
-
- mvm::StackWalker Walker(mut);
-
- while (mvm::MethodInfo* MI = Walker.get()) {
- if (MI->isHighLevelMethod() == 1) {
- JavaMethod* meth = (JavaMethod*)MI->MetaInfo;
- JnjvmClassLoader* loader = meth->classDef->classLoader;
- obj = loader->getJavaClassLoader();
- if (obj) return obj;
- }
- ++Walker;
- }
- return 0;
-}
-
-
-void JavaThread::printJavaBacktrace() {
- mvm::StackWalker Walker(mut);
-
- while (mvm::MethodInfo* MI = Walker.get()) {
- if (MI->isHighLevelMethod())
- MI->print(Walker.ip, Walker.addr);
- ++Walker;
- }
-}
-
-mvm::gc** JNILocalReferences::addJNIReference(JavaThread* th, mvm::gc* obj) {
- llvm_gcroot(obj, 0);
-
- if (length == MAXIMUM_REFERENCES) {
- JNILocalReferences* next = new JNILocalReferences();
- th->localJNIRefs = next;
- next->prev = this;
- return next->addJNIReference(th, obj);
- } else {
- localReferences[length] = obj;
- return &localReferences[length++];
- }
-}
-
-void JNILocalReferences::removeJNIReferences(JavaThread* th, uint32_t num) {
-
- if (th->localJNIRefs != this) {
- delete th->localJNIRefs;
- th->localJNIRefs = this;
- }
-
- if (num > length) {
- assert(prev && "No prev and deleting too much local references");
- prev->removeJNIReferences(th, num - length);
- } else {
- length -= num;
- }
-}
diff --git a/vmkit/lib/J3/VMCore/JavaThread.h b/vmkit/lib/J3/VMCore/JavaThread.h
deleted file mode 100644
index e11d859..0000000
--- a/vmkit/lib/J3/VMCore/JavaThread.h
+++ /dev/null
@@ -1,211 +0,0 @@
-//===----------- JavaThread.h - Java thread description -------------------===//
-//
-// The VMKit project
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#ifndef JNJVM_JAVA_THREAD_H
-#define JNJVM_JAVA_THREAD_H
-
-#include "mvm/Threads/Cond.h"
-#include "mvm/Threads/Locks.h"
-#include "mvm/Threads/ObjectLocks.h"
-#include "mvm/Threads/Thread.h"
-
-#include "MutatorThread.h"
-
-#include "JavaObject.h"
-#include "JNIReferences.h"
-
-namespace j3 {
-
-class Class;
-class JavaMethod;
-class JavaObject;
-class Jnjvm;
-
-
-#define BEGIN_NATIVE_EXCEPTION(level) \
- JavaThread* __th = JavaThread::get(); \
- TRY {
-
-#define END_NATIVE_EXCEPTION \
- } CATCH { \
- __th->throwFromNative(); \
- } END_CATCH;
-
-#define BEGIN_JNI_EXCEPTION \
- mvm::Thread* mut = mvm::Thread::get(); \
- void* SP = mut->getLastSP(); \
- mut->leaveUncooperativeCode(); \
- mvm::KnownFrame Frame; \
- mut->startKnownFrame(Frame); \
- TRY {
-
-#define END_JNI_EXCEPTION \
- } CATCH { \
- JavaThread::j3Thread(mut)->throwFromJNI(SP); \
- } END_CATCH;
-
-#define RETURN_FROM_JNI(a) { \
- mut->endKnownFrame(); \
- mut->enterUncooperativeCode(SP); \
- return (a); } \
-
-#define RETURN_VOID_FROM_JNI { \
- mut->endKnownFrame(); \
- mut->enterUncooperativeCode(SP); \
- return; } \
-
-/// JavaThread - This class is the internal representation of a Java thread.
-/// It maintains thread-specific information such as its state, the current
-/// exception if there is one, the layout of the stack, etc.
-///
-class JavaThread : public mvm::VMThreadData {
-public:
-
- /// jniEnv - The JNI environment of the thread.
- ///
- void* jniEnv;
-
- /// javaThread - The Java representation of this thread.
- ///
- JavaObject* javaThread;
-
- /// vmThread - The VMThread object of this thread.
- ///
- JavaObject* vmThread;
-
- mvm::LockingThread lockingThread;
-
- /// currentAddedReferences - Current number of added local references.
- ///
- uint32_t* currentAddedReferences;
-
- /// localJNIRefs - List of local JNI references.
- ///
- JNILocalReferences* localJNIRefs;
-
- mvm::gc** pushJNIRef(mvm::gc* obj) {
- llvm_gcroot(obj, 0);
- if (!obj) return 0;
-
- ++(*currentAddedReferences);
- return localJNIRefs->addJNIReference(this, obj);
-
- }
-
- /// tracer - Traces GC-objects pointed by this thread object.
- ///
- virtual void tracer(uintptr_t closure);
-
- /// JavaThread - Empty constructor, used to get the VT.
- ///
- JavaThread() : mvm::VMThreadData(0, 0) {
- }
-
- /// ~JavaThread - Delete any potential malloc'ed objects used by this thread.
- ///
- ~JavaThread();
-
-private:
- /// JavaThread - Creates a Java thread.
- ///
- JavaThread(Jnjvm* vm, mvm::Thread*mut);
-
-public:
- /// associate - Associate a java thread to the mutator
- ///
- static JavaThread* associate(Jnjvm* vm, mvm::Thread* mut);
-
- /// j3Thread - gives the JavaThread associated with the mutator thread
- ///
- static JavaThread* j3Thread(mvm::Thread* mut);
-
- /// initialise - initialise the thread
- ///
- void initialise(JavaObject* thread, JavaObject* vmth);
-
- /// get - Get the current thread as a J3 object.
- ///
- static JavaThread* get() {
- return j3Thread(mvm::Thread::get());
- }
-
- /// getJVM - Get the Java VM in which this thread executes.
- ///
- Jnjvm* getJVM() {
- return (Jnjvm*)vm;
- }
-
- /// currentThread - Return the current thread as a Java object.
- ///
- JavaObject* currentThread() {
- return javaThread;
- }
-
- /// throwFromJNI - Throw an exception after executing JNI code.
- ///
- void throwFromJNI(void* SP) {
- mut->endKnownFrame();
- mut->enterUncooperativeCode(SP);
- }
-
- /// throwFromNative - Throw an exception after executing Native code.
- ///
- void throwFromNative() {
-#ifdef DWARF_EXCEPTIONS
- mut->throwIt();
-#endif
- }
-
- /// throwFromJava - Throw an exception after executing Java code.
- ///
- void throwFromJava() {
- mut->throwIt();
- }
-
- /// startJava - Interesting, but actually does nothing :)
- void startJava() {}
-
- /// endJava - Interesting, but actually does nothing :)
- void endJava() {}
-
- /// startJNI - Record that we are entering native code.
- ///
- void startJNI();
-
- void endJNI();
-
- /// getCallingMethod - Get the Java method in the stack at the specified
- /// level.
- ///
- JavaMethod* getCallingMethodLevel(uint32 level);
-
- /// getCallingClassLevel - Get the Java method in the stack at the
- /// specified level.
- ///
- UserClass* getCallingClassLevel(uint32 level);
-
- /// getNonNullClassLoader - Get the first non-null class loader on the
- /// stack.
- ///
- JavaObject* getNonNullClassLoader();
-
- /// printJavaBacktrace - Prints the backtrace of this thread. Only prints
- /// the Java methods on the stack.
- ///
- void printJavaBacktrace();
-
- /// getJavaFrameContext - Fill the buffer with Java methods currently on
- /// the stack.
- ///
- uint32 getJavaFrameContext(void** buffer);
-};
-
-} // end namespace j3
-
-#endif
diff --git a/vmkit/lib/J3/VMCore/JavaTypes.cpp b/vmkit/lib/J3/VMCore/JavaTypes.cpp
deleted file mode 100644
index 7c0c09a..0000000
--- a/vmkit/lib/J3/VMCore/JavaTypes.cpp
+++ /dev/null
@@ -1,205 +0,0 @@
-//===------------- JavaTypes.cpp - Java primitives ------------------------===//
-//
-// The VMKit project
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#include <vector>
-
-#include "JavaArray.h"
-#include "JavaClass.h"
-#include "JavaCompiler.h"
-#include "JavaTypes.h"
-
-using namespace j3;
-
-UserCommonClass* ArrayTypedef::assocClass(JnjvmClassLoader* loader) const {
- return loader->constructArray(keyName);
-}
-
-UserCommonClass* ObjectTypedef::assocClass(JnjvmClassLoader* loader) const {
- return loader->loadName(pseudoAssocClassName, false, true, NULL);
-}
-
-UserCommonClass* ObjectTypedef::findAssocClass(JnjvmClassLoader* loader) const {
- return loader->lookupClassOrArray(pseudoAssocClassName);
-}
-
-UserCommonClass* ArrayTypedef::findAssocClass(JnjvmClassLoader* loader) const {
- return loader->lookupClassOrArray(keyName);
-}
-
-Signdef::Signdef(const UTF8* name, JnjvmClassLoader* loader,
- std::vector<Typedef*>& args, Typedef* ret) {
-
- arguments[0] = ret;
- Typedef** myArgs = &(arguments[1]);
- nbArguments = args.size();
- uint32 index = 0;
- for (std::vector<Typedef*>::iterator i = args.begin(), e = args.end();
- i != e; ++i) {
- myArgs[index++] = *i;
- }
- initialLoader = loader;
- keyName = name;
- _virtualCallBuf = 0;
- _staticCallBuf = 0;
- _virtualCallAP = 0;
- _staticCallAP = 0;
-
-}
-
-ObjectTypedef::ObjectTypedef(const UTF8* name, UTF8Map* map) {
- keyName = name;
- pseudoAssocClassName = name->extract(map, 1, name->size - 1);
-}
-
-intptr_t Signdef::staticCallBuf() {
- if (!_staticCallBuf) {
- mvm::ThreadAllocator allocator;
- char* buf = (char*)allocator.Allocate((keyName->size << 1) + 1 + 11);
- nativeName(buf, "static_buf");
- bool unused = false;
- intptr_t res = initialLoader->loadInLib(buf, unused);
- if (res) {
- _staticCallBuf = res;
- } else {
- initialLoader->getCompiler()->staticCallBuf(this);
- }
- }
- return _staticCallBuf;
-}
-
-intptr_t Signdef::virtualCallBuf() {
- if (!_virtualCallBuf) {
- mvm::ThreadAllocator allocator;
- char* buf = (char*)allocator.Allocate((keyName->size << 1) + 1 + 11);
- nativeName(buf, "virtual_buf");
- bool unused = false;
- intptr_t res = initialLoader->loadInLib(buf, unused);
- if (res) {
- _virtualCallBuf = res;
- } else {
- initialLoader->getCompiler()->virtualCallBuf(this);
- }
- }
- return _virtualCallBuf;
-}
-
-intptr_t Signdef::staticCallAP() {
- if (!_staticCallAP) {
- mvm::ThreadAllocator allocator;
- char* buf = (char*)allocator.Allocate((keyName->size << 1) + 1 + 11);
- nativeName(buf, "static_ap");
- bool unused = false;
- intptr_t res = initialLoader->loadInLib(buf, unused);
- if (res) {
- _staticCallAP = res;
- } else {
- initialLoader->getCompiler()->staticCallAP(this);
- }
- }
- return _staticCallAP;
-}
-
-intptr_t Signdef::virtualCallAP() {
- if (!_virtualCallAP) {
- mvm::ThreadAllocator allocator;
- char* buf = (char*)allocator.Allocate((keyName->size << 1) + 1 + 11);
- nativeName(buf, "virtual_ap");
- bool unused = false;
- intptr_t res = initialLoader->loadInLib(buf, unused);
- if (res) {
- _virtualCallAP = res;
- } else {
- initialLoader->getCompiler()->virtualCallAP(this);
- }
- }
- return _virtualCallAP;
-}
-
-intptr_t Signdef::virtualCallStub() {
- if (!_virtualCallAP) {
- mvm::ThreadAllocator allocator;
- char* buf = (char*)allocator.Allocate((keyName->size << 1) + 1 + 11);
- nativeName(buf, "virtual_stub");
- bool unused = false;
- intptr_t res = initialLoader->loadInLib(buf, unused);
- if (res) {
- _virtualCallStub = res;
- } else {
- initialLoader->getCompiler()->virtualCallStub(this);
- }
- }
- return _virtualCallStub;
-}
-
-intptr_t Signdef::specialCallStub() {
- if (!_specialCallStub) {
- mvm::ThreadAllocator allocator;
- char* buf = (char*)allocator.Allocate((keyName->size << 1) + 1 + 11);
- nativeName(buf, "special_stub");
- bool unused = false;
- intptr_t res = initialLoader->loadInLib(buf, unused);
- if (res) {
- _specialCallStub = res;
- } else {
- initialLoader->getCompiler()->specialCallStub(this);
- }
- }
- return _specialCallStub;
-}
-
-intptr_t Signdef::staticCallStub() {
- if (!_staticCallStub) {
- mvm::ThreadAllocator allocator;
- char* buf = (char*)allocator.Allocate((keyName->size << 1) + 1 + 11);
- nativeName(buf, "static_stub");
- bool unused = false;
- intptr_t res = initialLoader->loadInLib(buf, unused);
- if (res) {
- _staticCallStub = res;
- } else {
- initialLoader->getCompiler()->staticCallStub(this);
- }
- }
- return _staticCallStub;
-}
-
-void Signdef::nativeName(char* ptr, const char* ext) const {
- sint32 i = 0;
- while (i < keyName->size) {
- char c = keyName->elements[i++];
- if (c == I_PARG) {
- ptr[0] = '_';
- ptr[1] = '_';
- ptr += 2;
- } else if (c == '/') {
- ptr[0] = '_';
- ++ptr;
- } else if (c == '_') {
- ptr[0] = '_';
- ptr[1] = '1';
- ptr += 2;
- } else if (c == I_END_REF) {
- ptr[0] = '_';
- ptr[1] = '2';
- ptr += 2;
- } else if (c == I_TAB) {
- ptr[0] = '_';
- ptr[1] = '3';
- ptr += 2;
- } else if (c == I_PARD) {
- break;
- } else {
- ptr[0] = c;
- ++ptr;
- }
- }
-
- assert(ext && "I need an extension");
- memcpy(ptr, ext, strlen(ext) + 1);
-}
diff --git a/vmkit/lib/J3/VMCore/JavaTypes.h b/vmkit/lib/J3/VMCore/JavaTypes.h
deleted file mode 100644
index b6acf7a..0000000
--- a/vmkit/lib/J3/VMCore/JavaTypes.h
+++ /dev/null
@@ -1,438 +0,0 @@
-//===--------------- JavaTypes.h - Java primitives ------------------------===//
-//
-// The VMKit project
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#ifndef JNJVM_JAVA_TYPES_H
-#define JNJVM_JAVA_TYPES_H
-
-#include "types.h"
-
-#include "mvm/Allocator.h"
-
-#include "JnjvmClassLoader.h"
-
-namespace j3 {
-
-class UserCommonClass;
-class JnjvmClassLoader;
-class UserClassPrimitive;
-
-#define VOID_ID 0
-#define BOOL_ID 1
-#define BYTE_ID 2
-#define CHAR_ID 3
-#define SHORT_ID 4
-#define INT_ID 5
-#define FLOAT_ID 6
-#define LONG_ID 7
-#define DOUBLE_ID 8
-#define OBJECT_ID 9
-#define ARRAY_ID 10
-#define NUM_ASSESSORS 11
-
-static const char I_TAB = '[';
-static const char I_END_REF = ';';
-static const char I_PARG = '(';
-static const char I_PARD = ')';
-static const char I_BYTE = 'B';
-static const char I_CHAR = 'C';
-static const char I_DOUBLE = 'D';
-static const char I_FLOAT = 'F';
-static const char I_INT = 'I';
-static const char I_LONG = 'J';
-static const char I_REF = 'L';
-static const char I_SHORT = 'S';
-static const char I_VOID = 'V';
-static const char I_BOOL = 'Z';
-static const char I_SEP = '/';
-
-/// Typedef - Each class has a Typedef representation. A Typedef is also a class
-/// which has not been loaded yet. Typedefs are hashed on the name of the class.
-/// Hashing is for memory purposes, not for comparison.
-///
-class Typedef : public mvm::PermanentObject {
-public:
-
- /// keyName - The name of the Typedef. It is the representation of a class
- /// in a Java signature, e.g. "Ljava/lang/Object;".
- ///
- const UTF8* keyName;
-
- /// assocClass - Given the loaded, try to load the class represented by this
- /// Typedef.
- ///
- virtual UserCommonClass* assocClass(JnjvmClassLoader* loader) const = 0;
-
- virtual UserCommonClass* findAssocClass(JnjvmClassLoader* loader) const {
- return assocClass(loader);
- }
-
- /// trace - Does this type need to be traced by the GC?
- ///
- virtual bool trace() const = 0;
-
- /// isPrimitive - Is this type a primitive type?
- ///
- virtual bool isPrimitive() const {
- return false;
- }
-
- /// isReference - Is this type a reference type?
- ///
- virtual bool isReference() const {
- return true;
- }
-
- /// isUnsigned - Is this type unsigned?
- ///
- virtual bool isUnsigned() const {
- return false;
- }
-
- virtual bool isVoid() const {
- return false;
- }
-
- virtual bool isLong() const {
- return false;
- }
-
- virtual bool isInt() const {
- return false;
- }
-
- virtual bool isChar() const {
- return false;
- }
-
- virtual bool isShort() const {
- return false;
- }
-
- virtual bool isByte() const {
- return false;
- }
-
- virtual bool isBool() const {
- return false;
- }
-
- virtual bool isFloat() const {
- return false;
- }
-
- virtual bool isDouble() const {
- return false;
- }
-
- /// getName - Get the name of the type, i.e. java.lang.String or
- /// I.
- virtual const UTF8* getName() const {
- return keyName;
- }
-
- /// getKey - Get the name of the type, i.e. Ljava/lang/String; or
- /// I.
- const UTF8* getKey() const {
- return keyName;
- }
-
- virtual ~Typedef() {}
-};
-
-class PrimitiveTypedef : public Typedef {
-private:
- UserClassPrimitive* prim;
- bool unsign;
- char charId;
-
-public:
-
- virtual bool trace() const {
- return false;
- }
-
- virtual bool isPrimitive() const {
- return true;
- }
-
- virtual bool isReference() const {
- return false;
- }
-
- virtual bool isUnsigned() const {
- return unsign;
- }
-
- virtual UserCommonClass* assocClass(JnjvmClassLoader* loader) const {
- return (UserCommonClass*)prim;
- }
-
- PrimitiveTypedef(const UTF8* name, UserClassPrimitive* cl, bool u, char i) {
- keyName = name;
- prim = cl;
- unsign = u;
- charId = i;
- }
-
- virtual bool isVoid() const {
- return charId == I_VOID;
- }
-
- virtual bool isLong() const {
- return charId == I_LONG;
- }
-
- virtual bool isInt() const {
- return charId == I_INT;
- }
-
- virtual bool isChar() const {
- return charId == I_CHAR;
- }
-
- virtual bool isShort() const {
- return charId == I_SHORT;
- }
-
- virtual bool isByte() const {
- return charId == I_BYTE;
- }
-
- virtual bool isBool() const {
- return charId == I_BOOL;
- }
-
- virtual bool isFloat() const {
- return charId == I_FLOAT;
- }
-
- virtual bool isDouble() const {
- return charId == I_DOUBLE;
- }
-
-};
-
-class ArrayTypedef : public Typedef {
-public:
-
- virtual bool trace() const {
- return true;
- }
-
- virtual UserCommonClass* assocClass(JnjvmClassLoader* loader) const;
- virtual UserCommonClass* findAssocClass(JnjvmClassLoader* loader) const;
-
- ArrayTypedef(const UTF8* name) {
- keyName = name;
- }
-};
-
-class ObjectTypedef : public Typedef {
-private:
- /// pseudoAssocClassName - The real name of the class this Typedef
- /// represents, e.g. "java/lang/Object"
- ///
- const UTF8* pseudoAssocClassName;
-
-public:
- virtual bool trace() const {
- return true;
- }
-
- virtual UserCommonClass* assocClass(JnjvmClassLoader* loader) const;
- virtual UserCommonClass* findAssocClass(JnjvmClassLoader* loader) const;
-
- ObjectTypedef(const UTF8*name, UTF8Map* map);
-
- virtual const UTF8* getName() const {
- return pseudoAssocClassName;
- }
-
-};
-
-
-/// Signdef - This class represents a Java signature. Each Java method has a
-/// Java signature. Signdefs are hashed for memory purposes, not equality
-/// purposes.
-///
-class Signdef : public mvm::PermanentObject {
-private:
-
- /// _staticCallBuf - A dynamically generated method which calls a static Java
- /// function with the specific signature and receive the arguments in a
- /// buffer.
- ///
- intptr_t _staticCallBuf;
- intptr_t staticCallBuf();
-
- /// _virtualCallBuf - A dynamically generated method which calls a virtual
- /// Java function with the specific signature and receive the arguments in a
- /// buffer.
- ///
- intptr_t _virtualCallBuf;
- intptr_t virtualCallBuf();
-
- /// _staticCallAP - A dynamically generated method which calls a static Java
- /// function with the specific signature and receive the arguments in a
- /// variable argument handle.
- ///
- intptr_t _staticCallAP;
- intptr_t staticCallAP();
-
- /// _virtualCallBuf - A dynamically generated method which calls a virtual
- /// Java function with the specific signature and receive the arguments in a
- /// variable argument handle.
- ///
- intptr_t _virtualCallAP;
- intptr_t virtualCallAP();
-
- intptr_t _virtualCallStub;
- intptr_t virtualCallStub();
-
- intptr_t _specialCallStub;
- intptr_t specialCallStub();
-
- intptr_t _staticCallStub;
- intptr_t staticCallStub();
-
-public:
-
- /// initialLoader - The loader that first loaded this signdef.
- ///
- JnjvmClassLoader* initialLoader;
-
- /// keyName - The Java name of the signature, e.g. "()V".
- ///
- const UTF8* keyName;
-
- /// nativeName - Get a native name for callbacks emitted AOT.
- ///
- void nativeName(char* buf, const char* ext) const;
-
- /// Signdef - Create a new Signdef.
- ///
- Signdef(const UTF8* name, JnjvmClassLoader* loader,
- std::vector<Typedef*>& args, Typedef* ret);
-
- /// operator new - Redefines the new operator of this class to allocate
- /// the arguments in the object itself.
- ///
- void* operator new(size_t sz, mvm::BumpPtrAllocator& allocator,
- sint32 size) {
- return allocator.Allocate(sizeof(Signdef) + size * sizeof(Typedef),
- "Signdef");
- }
-
-
-//===----------------------------------------------------------------------===//
-//
-// Inline calls to get the dynamically generated functions to call Java
-// functions. Note that this calls the JIT.
-//
-//===----------------------------------------------------------------------===//
-
- intptr_t getStaticCallBuf() {
- if(!_staticCallBuf) return staticCallBuf();
- return _staticCallBuf;
- }
-
- intptr_t getVirtualCallBuf() {
- if(!_virtualCallBuf) return virtualCallBuf();
- return _virtualCallBuf;
- }
-
- intptr_t getStaticCallAP() {
- if (!_staticCallAP) return staticCallAP();
- return _staticCallAP;
- }
-
- intptr_t getVirtualCallAP() {
- if (!_virtualCallAP) return virtualCallAP();
- return _virtualCallAP;
- }
-
- intptr_t getVirtualCallStub() {
- if (!_virtualCallStub) return virtualCallStub();
- return _virtualCallStub;
- }
-
- intptr_t getSpecialCallStub() {
- if (!_specialCallStub) return specialCallStub();
- return _specialCallStub;
- }
-
- intptr_t getStaticCallStub() {
- if (!_staticCallStub) return staticCallStub();
- return _staticCallStub;
- }
-
- void setStaticCallBuf(void* code) {
- _staticCallBuf = (intptr_t)code;
- }
-
- void setVirtualCallBuf(void* code) {
- _virtualCallBuf = (intptr_t)code;
- }
-
- void setStaticCallAP(void* code) {
- _staticCallAP = (intptr_t)code;
- }
-
- void setVirtualCallAP(void* code) {
- _virtualCallAP = (intptr_t)code;
- }
-
- void setVirtualCallStub(void* code) {
- _virtualCallStub = (intptr_t)code;
- }
-
- void setSpecialCallStub(void* code) {
- _specialCallStub = (intptr_t)code;
- }
-
- void setStaticCallStub(void* code) {
- _staticCallStub = (intptr_t)code;
- }
-
-//===----------------------------------------------------------------------===//
-//
-// End of inlined methods of getting dynamically generated functions.
-//
-//===----------------------------------------------------------------------===//
-
- /// nbArguments - The number of arguments in the signature.
- ///
- uint32 nbArguments;
-
- /// getReturnType - Get the type of the return of this signature.
- ///
- Typedef* getReturnType() const {
- return arguments[0];
- }
-
- /// getArgumentsType - Get the list of arguments of this signature.
- ///
- Typedef* const* getArgumentsType() const {
- return &(arguments[1]);
- }
-
-private:
-
- /// arguments - The list of arguments of the signature. First is the return
- /// type.
- ///
- Typedef* arguments[1];
-
-
-};
-
-
-} // end namespace j3
-
-#endif
diff --git a/vmkit/lib/J3/VMCore/Jni.cpp b/vmkit/lib/J3/VMCore/Jni.cpp
deleted file mode 100644
index 81783a2..0000000
--- a/vmkit/lib/J3/VMCore/Jni.cpp
+++ /dev/null
@@ -1,3942 +0,0 @@
-//===---------------- Jni.cpp - Jni interface for J3 ----------------------===//
-//
-// The VMKit project
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#include <jni.h>
-
-#include "ClasspathReflect.h"
-#include "JavaArray.h"
-#include "JavaClass.h"
-#include "JavaObject.h"
-#include "JavaString.h"
-#include "JavaThread.h"
-#include "JavaTypes.h"
-#include "JavaUpcalls.h"
-#include "Jnjvm.h"
-
-
-using namespace j3;
-
-Jnjvm* myVM(JNIEnv* env) {
- return JavaThread::get()->getJVM();
-}
-
-UserClass* getClassFromStaticMethod(JavaMethod* meth,
- JavaObject* clazz) {
- llvm_gcroot(clazz, 0);
- return meth->classDef;
-}
-
-static UserClass* getClassFromVirtualMethod(JavaMethod* meth,
- UserCommonClass* cl) {
- return meth->classDef;
-}
-
-extern "C" const struct JNIInvokeInterface_ JNI_JavaVMTable;
-extern "C" struct JNINativeInterface_ JNI_JNIEnvTable;
-
-jint GetVersion(JNIEnv *env) {
- return JNI_VERSION_1_4;
-}
-
-
-jclass DefineClass(JNIEnv *env, const char *name, jobject loader,
- const jbyte *buf, jsize bufLen) {
- fprintf(stderr, "Implement me\n"); abort();
- return 0;
-}
-
-
-jclass FindClass(JNIEnv *env, const char *asciiz) {
-
- BEGIN_JNI_EXCEPTION
-
- JnjvmClassLoader* loader = 0;
- JavaThread* th = JavaThread::get();
- UserClass* currentClass = th->getCallingClassLevel(0);
- if (currentClass) loader = currentClass->classLoader;
- else loader = myVM(env)->appClassLoader;
-
- UserCommonClass* cl = loader->loadClassFromAsciiz(asciiz, true, true);
- if (cl && cl->asClass()) {
- assert(cl->asClass()->isResolved());
- cl->asClass()->initialiseClass();
- }
- jclass res = (jclass)cl->getClassDelegateePtr();
- RETURN_FROM_JNI(res);
-
- END_JNI_EXCEPTION
- RETURN_FROM_JNI(0);
-}
-
-
-jmethodID FromReflectedMethod(JNIEnv *env, jobject method) {
-
- BEGIN_JNI_EXCEPTION
-
- // Local object references.
- JavaObject* meth = *(JavaObject**)method;
- llvm_gcroot(meth, 0);
-
- UserCommonClass* cl = JavaObject::getClass(meth);
- Jnjvm* vm = cl->classLoader->vm;
- Classpath* upcalls = vm->upcalls;
- if (cl == upcalls->newConstructor) {
- jmethodID res = (jmethodID)JavaObjectMethod::getInternalMethod((JavaObjectMethod*)meth);
- RETURN_FROM_JNI(res);
- } else if (cl == upcalls->newMethod) {
- jmethodID res = (jmethodID)JavaObjectConstructor::getInternalMethod((JavaObjectConstructor*)meth);
- RETURN_FROM_JNI(res);
- }
-
- END_JNI_EXCEPTION
-
- RETURN_FROM_JNI(0);
-}
-
-
-jclass GetSuperclass(JNIEnv *env, jclass sub) {
- fprintf(stderr, "Implement me\n"); abort();
- return 0;
-}
-
-
-jboolean IsAssignableFrom(JNIEnv *env, jclass _sub, jclass _sup) {
-
- BEGIN_JNI_EXCEPTION
-
- // Local object references.
- JavaObject* sub = *(JavaObject**)_sub;
- JavaObject* sup = *(JavaObject**)_sup;
- llvm_gcroot(sub, 0);
- llvm_gcroot(sup, 0);
-
- UserCommonClass* cl2 =
- UserCommonClass::resolvedImplClass(sup, false);
- UserCommonClass* cl1 =
- UserCommonClass::resolvedImplClass(sub, false);
-
- jboolean res = (jboolean)cl1->isAssignableFrom(cl2);
- RETURN_FROM_JNI(res);
-
- END_JNI_EXCEPTION
-
- RETURN_FROM_JNI(false);
-}
-
-
-jint Throw(JNIEnv *env, jthrowable obj) {
- fprintf(stderr, "Implement me\n");
- abort();
- return 0;
-}
-
-
-jint ThrowNew(JNIEnv* env, jclass _Cl, const char *msg) {
-
- BEGIN_JNI_EXCEPTION
-
- // Local object references.
- JavaObject* Cl = *(JavaObject**)_Cl;
- JavaObject* res = 0;
- JavaString* str = 0;
- llvm_gcroot(Cl, 0);
- llvm_gcroot(res, 0);
- llvm_gcroot(str, 0);
-
- verifyNull(Cl);
- UserCommonClass* cl = UserCommonClass::resolvedImplClass(Cl, true);
- if (!cl->isClass()) RETURN_FROM_JNI(0);
-
- Jnjvm* vm = cl->classLoader->vm;
-
- UserClass* realCl = cl->asClass();
- res = realCl->doNew();
- JavaMethod* init = realCl->lookupMethod(vm->upcalls->initName,
- vm->upcalls->initExceptionSig,
- false, true, 0);
- str = vm->asciizToStr(msg);
- init->invokeIntSpecial(realCl, res, &str);
- mut->setPendingException(res);
-
- RETURN_FROM_JNI(1);
-
- END_JNI_EXCEPTION
-
- RETURN_FROM_JNI(0);
-}
-
-
-jthrowable ExceptionOccurred(JNIEnv *env) {
-
- BEGIN_JNI_EXCEPTION
-
- mvm::gc* obj = mut->getPendingException();
- llvm_gcroot(obj, 0);
- if (obj == NULL) RETURN_FROM_JNI(NULL);
- jthrowable res = (jthrowable)JavaThread::j3Thread(mut)->pushJNIRef(obj);
- RETURN_FROM_JNI(res);
-
- END_JNI_EXCEPTION
-
- RETURN_FROM_JNI(0);
-}
-
-
-void ExceptionDescribe(JNIEnv *env) {
- fprintf(stderr, "Implement me\n");
- abort();
-}
-
-
-void ExceptionClear(JNIEnv *env) {
- fprintf(stderr, "Implement me\n");
- abort();
-}
-
-
-void FatalError(JNIEnv *env, const char *msg) {
- fprintf(stderr, "Implement me\n");
- abort();
-}
-
-
-jint PushLocalFrame(JNIEnv* env, jint capacity) {
- fprintf(stderr, "Implement me\n");
- abort();
- return 0;
-}
-
-jobject PopLocalFrame(JNIEnv* env, jobject result) {
- fprintf(stderr, "Implement me\n");
- abort();
- return 0;
-}
-
-
-void DeleteLocalRef(JNIEnv *env, jobject localRef) {
-}
-
-
-jboolean IsSameObject(JNIEnv *env, jobject ref1, jobject ref2) {
-
- BEGIN_JNI_EXCEPTION
-
- JavaObject* Ref1 = *(JavaObject**)ref1;
- JavaObject* Ref2 = *(JavaObject**)ref2;
- llvm_gcroot(Ref1, 0);
- llvm_gcroot(Ref2, 0);
-
- RETURN_FROM_JNI(Ref1 == Ref2);
-
- END_JNI_EXCEPTION
- RETURN_FROM_JNI(false);
-}
-
-
-jobject NewLocalRef(JNIEnv *env, jobject ref) {
- fprintf(stderr, "Implement me\n");
- abort();
- return 0;
-}
-
-
-jint EnsureLocalCapacity(JNIEnv* env, jint capacity) {
- fprintf(stderr, "Implement me\n");
- abort();
- return 0;
-}
-
-
-jobject AllocObject(JNIEnv *env, jclass _clazz) {
-
- BEGIN_JNI_EXCEPTION
-
- // Local object references.
- JavaObject* clazz = *(JavaObject**)_clazz;
- JavaObject* res = 0;
- llvm_gcroot(clazz, 0);
- llvm_gcroot(res, 0);
-
- JavaThread* th = JavaThread::get();
-
- UserCommonClass* cl = UserCommonClass::resolvedImplClass(clazz, true);
- if (!cl->isClass()) RETURN_FROM_JNI(0);
-
- // Store local reference
- res = cl->asClass()->doNew();
-
- jobject ret = (jobject)th->pushJNIRef(res);
- RETURN_FROM_JNI(ret);
-
- END_JNI_EXCEPTION
- RETURN_FROM_JNI(0);
-}
-
-
-jobject NewObject(JNIEnv *env, jclass _clazz, jmethodID methodID, ...) {
- BEGIN_JNI_EXCEPTION
-
-
- // Local object references
- JavaObject* clazz = *(JavaObject**)_clazz;
- JavaObject* res = 0;
- llvm_gcroot(clazz, 0);
- llvm_gcroot(res, 0);
-
- JavaMethod* meth = (JavaMethod*)methodID;
- JavaThread* th = JavaThread::get();
- UserCommonClass* cl = UserCommonClass::resolvedImplClass(clazz, true);
- if (!cl->isClass()) RETURN_FROM_JNI(0);
-
- // Store local reference
- res = cl->asClass()->doNew();
-
- va_list ap;
- va_start(ap, methodID);
- meth->invokeIntSpecialAP(cl->asClass(), res, ap);
- va_end(ap);
-
- jobject ret = (jobject)th->pushJNIRef(res);
- RETURN_FROM_JNI(ret);
-
- END_JNI_EXCEPTION
- RETURN_FROM_JNI(0);
-}
-
-
-jobject NewObjectV(JNIEnv* env, jclass clazz, jmethodID methodID,
- va_list args) {
- fprintf(stderr, "Implement me\n");
- abort();
- return 0;
-}
-
-jobject NewObjectA(JNIEnv* env, jclass _clazz, jmethodID methodID,
- const jvalue *args) {
-
- BEGIN_JNI_EXCEPTION
-
- // Local object references
- JavaObject* clazz = *(JavaObject**)_clazz;
- JavaObject* res = 0;
- llvm_gcroot(clazz, 0);
- llvm_gcroot(res, 0);
-
- JavaThread* th = JavaThread::get();
- JavaMethod* meth = (JavaMethod*)methodID;
- UserCommonClass* cl = UserCommonClass::resolvedImplClass(clazz, true);
-
- // Store local reference
- res = cl->asClass()->doNew();
-
- meth->invokeIntSpecialBuf(cl->asClass(), res, (void*)args);
-
- jobject ret = (jobject)th->pushJNIRef(res);
- RETURN_FROM_JNI(ret);
-
- END_JNI_EXCEPTION
- RETURN_FROM_JNI(0);
-}
-
-
-jclass GetObjectClass(JNIEnv *env, jobject _obj) {
-
- BEGIN_JNI_EXCEPTION
-
- // Local object references
- JavaObject* obj = *(JavaObject**)_obj;
- llvm_gcroot(obj, 0);
-
- // Store local reference
- jclass res = (jclass)JavaObject::getClass(obj)->getClassDelegateePtr();
- RETURN_FROM_JNI(res);
-
- END_JNI_EXCEPTION
- RETURN_FROM_JNI(0);
-}
-
-
-jboolean IsInstanceOf(JNIEnv *env, jobject obj, jclass clazz) {
- fprintf(stderr, "Implement me\n");
- abort();
- return 0;
-}
-
-
-jfieldID FromReflectedField(JNIEnv* env, jobject field) {
- fprintf(stderr, "Implement me\n");
- abort();
- return 0;
-}
-
-
-jobject ToReflectedMethod(JNIEnv* env, jclass cls, jmethodID methodID,
- jboolean isStatic) {
- fprintf(stderr, "Implement me\n");
- abort();
- return 0;
-}
-
-
-jobject ToReflectedField(JNIEnv* env, jclass cls, jfieldID fieldID,
- jboolean isStatic) {
- fprintf(stderr, "Implement me\n");
- abort();
- return 0;
-}
-
-
-jmethodID GetMethodID(JNIEnv* env, jclass _clazz, const char *aname,
- const char *atype) {
-
- BEGIN_JNI_EXCEPTION
-
- // Local object references.
- JavaObject* clazz = *(JavaObject**)_clazz;
- llvm_gcroot(clazz, 0);
-
- UserCommonClass* cl = UserCommonClass::resolvedImplClass(clazz, true);
-
- UserClass* realCl = cl->isClass() ? cl->asClass() : cl->super;
-
- const UTF8* name = cl->classLoader->hashUTF8->lookupAsciiz(aname);
- if (name) {
- const UTF8* type = cl->classLoader->hashUTF8->lookupAsciiz(atype);
- if (type) {
- JavaMethod* meth = realCl->lookupMethod(name, type, false, true, 0);
- RETURN_FROM_JNI((jmethodID)meth);
- }
- }
-
- END_JNI_EXCEPTION
- RETURN_FROM_JNI(0);
-}
-
-
-jobject CallObjectMethod(JNIEnv *env, jobject _obj, jmethodID methodID, ...) {
-
- BEGIN_JNI_EXCEPTION
-
- verifyNull(_obj);
-
- va_list ap;
- va_start(ap, methodID);
-
- // Local object references.
- JavaObject* obj = *(JavaObject**)_obj;
- JavaObject* res = 0;
- llvm_gcroot(obj, 0);
- llvm_gcroot(res, 0);
-
- JavaMethod* meth = (JavaMethod*)methodID;
- JavaThread* th = JavaThread::get();
- UserClass* cl = getClassFromVirtualMethod(meth, JavaObject::getClass(obj));
-
- res = meth->invokeJavaObjectVirtualAP(cl, obj, ap);
- va_end(ap);
-
- jobject ret = (jobject)th->pushJNIRef(res);
- RETURN_FROM_JNI(ret);
-
- END_JNI_EXCEPTION
- RETURN_FROM_JNI(0);
-}
-
-
-jobject CallObjectMethodV(JNIEnv *env, jobject _obj, jmethodID methodID,
- va_list args) {
-
- BEGIN_JNI_EXCEPTION
-
- verifyNull(_obj);
-
- // Local object references.
- JavaObject* obj = *(JavaObject**)_obj;
- JavaObject* res = 0;
- llvm_gcroot(obj, 0);
- llvm_gcroot(res, 0);
-
- JavaMethod* meth = (JavaMethod*)methodID;
- JavaThread* th = JavaThread::get();
- UserClass* cl = getClassFromVirtualMethod(meth, JavaObject::getClass(obj));
-
- // Store local reference.
- res = meth->invokeJavaObjectVirtualAP(cl, obj, args);
-
- jobject ret = (jobject)th->pushJNIRef(res);
- RETURN_FROM_JNI(ret);
-
- END_JNI_EXCEPTION
-
- RETURN_FROM_JNI(0);
-}
-
-
-jobject CallObjectMethodA(JNIEnv *env, jobject obj, jmethodID methodID,
- const jvalue * args) {
- fprintf(stderr, "Implement me\n");
- abort();
- return 0;
-}
-
-
-jboolean CallBooleanMethod(JNIEnv *env, jobject _obj, jmethodID methodID, ...) {
-
- BEGIN_JNI_EXCEPTION
-
- verifyNull(_obj);
-
- va_list ap;
- va_start(ap, methodID);
-
- // Local object references.
- JavaObject* self = *(JavaObject**)_obj;
- llvm_gcroot(self, 0);
-
- JavaMethod* meth = (JavaMethod*)methodID;
- UserClass* cl =
- getClassFromVirtualMethod(meth, JavaObject::getClass(self));
-
- uint32 res = meth->invokeIntVirtualAP(cl, self, ap);
- va_end(ap);
-
- RETURN_FROM_JNI(res);
-
- END_JNI_EXCEPTION
- RETURN_FROM_JNI(0);
-}
-
-
-jboolean CallBooleanMethodV(JNIEnv *env, jobject _obj, jmethodID methodID,
- va_list args) {
-
- BEGIN_JNI_EXCEPTION
-
- verifyNull(_obj);
-
- // Local object references.
- JavaObject* obj = *(JavaObject**)_obj;
- llvm_gcroot(obj, 0);
-
- JavaMethod* meth = (JavaMethod*)methodID;
- UserClass* cl = getClassFromVirtualMethod(meth, JavaObject::getClass(obj));
- jboolean res = (jboolean)meth->invokeIntVirtualAP(cl, obj, args);
- RETURN_FROM_JNI(res);
-
- END_JNI_EXCEPTION
-
- RETURN_FROM_JNI(0);
-}
-
-
-jboolean CallBooleanMethodA(JNIEnv *env, jobject obj, jmethodID methodID,
- const jvalue * args) {
- fprintf(stderr, "Implement me\n");
- abort();
- return 0;
-}
-
-
-jbyte CallByteMethod(JNIEnv *env, jobject obj, jmethodID methodID, ...) {
- fprintf(stderr, "Implement me\n");
- abort();
- return 0;
-}
-
-jbyte CallByteMethodV(JNIEnv *env, jobject _obj, jmethodID methodID,
- va_list args) {
-
- BEGIN_JNI_EXCEPTION
-
- verifyNull(_obj);
-
- // Local object references.
- JavaObject* obj = *(JavaObject**)_obj;
- llvm_gcroot(obj, 0);
-
- JavaMethod* meth = (JavaMethod*)methodID;
- UserClass* cl = getClassFromVirtualMethod(meth, JavaObject::getClass(obj));
- jbyte res = (jbyte)meth->invokeIntVirtualAP(cl, obj, args);
- RETURN_FROM_JNI(res);
-
- END_JNI_EXCEPTION
-
- RETURN_FROM_JNI(0);
-}
-
-
-jbyte CallByteMethodA(JNIEnv *env, jobject obj, jmethodID methodID,
- const jvalue *args) {
- fprintf(stderr, "Implement me\n");
- abort();
- return 0;
-}
-
-
-jchar CallCharMethod(JNIEnv *env, jobject obj, jmethodID methodID, ...) {
- fprintf(stderr, "Implement me\n");
- abort();
- return 0;
-}
-
-
-jchar CallCharMethodV(JNIEnv *env, jobject _obj, jmethodID methodID,
- va_list args) {
-
- BEGIN_JNI_EXCEPTION
-
- verifyNull(_obj);
-
- // Local object references.
- JavaObject* obj = *(JavaObject**)_obj;
- llvm_gcroot(obj, 0);
-
- JavaMethod* meth = (JavaMethod*)methodID;
- UserClass* cl = getClassFromVirtualMethod(meth, JavaObject::getClass(obj));
- jchar res = (jchar)meth->invokeIntVirtualAP(cl, obj, args);
- RETURN_FROM_JNI(res);
-
- END_JNI_EXCEPTION
-
- RETURN_FROM_JNI(0);
-}
-
-
-jchar CallCharMethodA(JNIEnv *env, jobject obj, jmethodID methodID,
- const jvalue *args) {
- fprintf(stderr, "Implement me\n");
- abort();
- return 0;
-}
-
-
-jshort CallShortMethod(JNIEnv *env, jobject obj, jmethodID methodID, ...) {
- fprintf(stderr, "Implement me\n");
- abort();
- return 0;
-}
-
-
-jshort CallShortMethodV(JNIEnv *env, jobject _obj, jmethodID methodID,
- va_list args) {
-
- BEGIN_JNI_EXCEPTION
-
- verifyNull(_obj);
-
- // Local object references.
- JavaObject* obj = *(JavaObject**)_obj;
- llvm_gcroot(obj, 0);
-
- JavaMethod* meth = (JavaMethod*)methodID;
- UserClass* cl = getClassFromVirtualMethod(meth, JavaObject::getClass(obj));
- jshort res = (jshort)meth->invokeIntVirtualAP(cl, obj, args);
- RETURN_FROM_JNI(res);
-
- END_JNI_EXCEPTION
-
- RETURN_FROM_JNI(0);
-}
-
-
-jshort CallShortMethodA(JNIEnv *env, jobject obj, jmethodID methodID,
- const jvalue *args) {
- fprintf(stderr, "Implement me\n");
- abort();
- return 0;
-}
-
-
-
-jint CallIntMethod(JNIEnv *env, jobject _obj, jmethodID methodID, ...) {
-
- BEGIN_JNI_EXCEPTION
-
- verifyNull(_obj);
-
- va_list ap;
- va_start(ap, methodID);
-
- // Local object references.
- JavaObject* obj = *(JavaObject**)_obj;
- llvm_gcroot(obj, 0);
-
- JavaMethod* meth = (JavaMethod*)methodID;
- UserClass* cl = getClassFromVirtualMethod(meth, JavaObject::getClass(obj));
-
- uint32 res = meth->invokeIntVirtualAP(cl, obj, ap);
- va_end(ap);
-
- RETURN_FROM_JNI(res);
-
- END_JNI_EXCEPTION
- RETURN_FROM_JNI(0);
-}
-
-
-jint CallIntMethodV(JNIEnv *env, jobject _obj, jmethodID methodID,
- va_list args) {
-
- BEGIN_JNI_EXCEPTION
-
- verifyNull(_obj);
-
- // Local object references.
- JavaObject* obj = *(JavaObject**)_obj;
- llvm_gcroot(obj, 0);
-
- JavaMethod* meth = (JavaMethod*)methodID;
- UserClass* cl = getClassFromVirtualMethod(meth, JavaObject::getClass(obj));
-
- jint res = (jint)meth->invokeIntVirtualAP(cl, obj, args);
- RETURN_FROM_JNI(res);
-
- END_JNI_EXCEPTION
-
- RETURN_FROM_JNI(0);
-}
-
-
-jint CallIntMethodA(JNIEnv *env, jobject _obj, jmethodID methodID,
- const jvalue *args) {
- fprintf(stderr, "Implement me\n");
- abort();
- return 0;
-}
-
-
-
-jlong CallLongMethod(JNIEnv *env, jobject _obj, jmethodID methodID, ...) {
- fprintf(stderr, "Implement me\n");
- abort();
- return 0;
-}
-
-
-jlong CallLongMethodV(JNIEnv *env, jobject _obj, jmethodID methodID,
- va_list args) {
-
- BEGIN_JNI_EXCEPTION
-
- verifyNull(_obj);
-
- // Local object references.
- JavaObject* obj = *(JavaObject**)_obj;
- llvm_gcroot(obj, 0);
-
- JavaMethod* meth = (JavaMethod*)methodID;
- UserClass* cl = getClassFromVirtualMethod(meth, JavaObject::getClass(obj));
- jlong res = (jlong)meth->invokeLongVirtualAP(cl, obj, args);
- RETURN_FROM_JNI(res);
-
- END_JNI_EXCEPTION
-
- RETURN_FROM_JNI(0);
-}
-
-
-jlong CallLongMethodA(JNIEnv *env, jobject obj, jmethodID methodID,
- const jvalue *args) {
- fprintf(stderr, "Implement me\n");
- abort();
- return 0;
-}
-
-
-
-jfloat CallFloatMethod(JNIEnv *env, jobject _obj, jmethodID methodID, ...) {
-
- BEGIN_JNI_EXCEPTION
-
- verifyNull(_obj);
-
- va_list ap;
- va_start(ap, methodID);
-
- // Local object references.
- JavaObject* obj = *(JavaObject**)_obj;
- llvm_gcroot(obj, 0);
-
- JavaMethod* meth = (JavaMethod*)methodID;
- UserClass* cl = getClassFromVirtualMethod(meth, JavaObject::getClass(obj));
- jfloat res = meth->invokeFloatVirtualAP(cl, obj, ap);
- va_end(ap);
- RETURN_FROM_JNI(res);
-
- END_JNI_EXCEPTION;
- RETURN_FROM_JNI(0.0);
-}
-
-
-jfloat CallFloatMethodV(JNIEnv *env, jobject _obj, jmethodID methodID,
- va_list args) {
-
- BEGIN_JNI_EXCEPTION
-
- verifyNull(_obj);
-
- // Local object references.
- JavaObject* obj = *(JavaObject**)_obj;
- llvm_gcroot(obj, 0);
-
- JavaMethod* meth = (JavaMethod*)methodID;
- UserClass* cl = getClassFromVirtualMethod(meth, JavaObject::getClass(obj));
- jfloat res = (jfloat)meth->invokeFloatVirtualAP(cl, obj, args);
- RETURN_FROM_JNI(res);
-
- END_JNI_EXCEPTION
-
- RETURN_FROM_JNI(0.0f);
-}
-
-
-jfloat CallFloatMethodA(JNIEnv *env, jobject _obj, jmethodID methodID,
- const jvalue *args) {
- fprintf(stderr, "Implement me\n");
- abort();
- return 0;
-}
-
-
-
-jdouble CallDoubleMethod(JNIEnv *env, jobject _obj, jmethodID methodID, ...) {
-
- BEGIN_JNI_EXCEPTION
-
- verifyNull(_obj);
-
- va_list ap;
- va_start(ap, methodID);
-
- // Local object references.
- JavaObject* obj = *(JavaObject**)_obj;
- llvm_gcroot(obj, 0);
-
- JavaMethod* meth = (JavaMethod*)methodID;
- UserClass* cl = getClassFromVirtualMethod(meth, JavaObject::getClass(obj));
- jdouble res = meth->invokeDoubleVirtualAP(cl, obj, ap);
- va_end(ap);
- RETURN_FROM_JNI(res);
-
- END_JNI_EXCEPTION
- RETURN_FROM_JNI(0.0);
-}
-
-
-jdouble CallDoubleMethodV(JNIEnv *env, jobject _obj, jmethodID methodID,
- va_list args) {
-
- BEGIN_JNI_EXCEPTION
-
- verifyNull(_obj);
-
- // Local object references.
- JavaObject* obj = *(JavaObject**)_obj;
- llvm_gcroot(obj, 0);
-
- JavaMethod* meth = (JavaMethod*)methodID;
- UserClass* cl = getClassFromVirtualMethod(meth, JavaObject::getClass(obj));
- jdouble res = (jdouble)meth->invokeDoubleVirtualAP(cl, obj, args);
- RETURN_FROM_JNI(res);
-
- END_JNI_EXCEPTION
- RETURN_FROM_JNI(0.0);
-
-}
-
-
-jdouble CallDoubleMethodA(JNIEnv *env, jobject _obj, jmethodID methodID,
- const jvalue *args) {
- fprintf(stderr, "Implement me\n");
- abort();
- return 0;
-}
-
-
-
-void CallVoidMethod(JNIEnv *env, jobject _obj, jmethodID methodID, ...) {
-
- BEGIN_JNI_EXCEPTION
-
- verifyNull(_obj);
-
- va_list ap;
- va_start(ap, methodID);
-
- // Local object references.
- JavaObject* obj = *(JavaObject**)_obj;
- llvm_gcroot(obj, 0);
-
- JavaMethod* meth = (JavaMethod*)methodID;
- UserClass* cl = getClassFromVirtualMethod(meth, JavaObject::getClass(obj));
- meth->invokeIntVirtualAP(cl, obj, ap);
- va_end(ap);
-
- RETURN_VOID_FROM_JNI;
-
- END_JNI_EXCEPTION
-
- RETURN_VOID_FROM_JNI;
-}
-
-
-void CallVoidMethodV(JNIEnv *env, jobject _obj, jmethodID methodID,
- va_list args) {
-
- BEGIN_JNI_EXCEPTION
-
- verifyNull(_obj);
-
- // Local object references.
- JavaObject* obj = *(JavaObject**)_obj;
- llvm_gcroot(obj, 0);
-
- JavaMethod* meth = (JavaMethod*)methodID;
- UserClass* cl = getClassFromVirtualMethod(meth, JavaObject::getClass(obj));
- meth->invokeIntVirtualAP(cl, obj, args);
-
- RETURN_VOID_FROM_JNI;
-
- END_JNI_EXCEPTION
-
- RETURN_VOID_FROM_JNI;
-}
-
-
-void CallVoidMethodA(JNIEnv *env, jobject _obj, jmethodID methodID,
- const jvalue *args) {
- BEGIN_JNI_EXCEPTION
-
- verifyNull(_obj);
-
- // Local object references.
- JavaObject* obj = *(JavaObject**)_obj;
- llvm_gcroot(obj, 0);
-
- JavaMethod* meth = (JavaMethod*)methodID;
- UserClass* cl = getClassFromVirtualMethod(meth, JavaObject::getClass(obj));
-
- meth->invokeIntVirtualBuf(cl, obj, (void*)args);
-
- RETURN_VOID_FROM_JNI;
-
- END_JNI_EXCEPTION
-
- RETURN_VOID_FROM_JNI;
-}
-
-
-
-jobject CallNonvirtualObjectMethod(JNIEnv *env, jobject obj, jclass clazz,
- jmethodID methodID, ...) {
- fprintf(stderr, "Implement me\n");
- abort();
- return 0;
-}
-
-
-jobject CallNonvirtualObjectMethodV(JNIEnv *env, jobject obj, jclass clazz,
- jmethodID methodID, va_list args) {
- fprintf(stderr, "Implement me\n");
- abort();
- return 0;
-}
-
-
-jobject CallNonvirtualObjectMethodA(JNIEnv *env, jobject obj, jclass clazz,
- jmethodID methodID, const jvalue *args) {
- fprintf(stderr, "Implement me\n");
- abort();
- return 0;
-}
-
-
-
-jboolean CallNonvirtualBooleanMethod(JNIEnv *env, jobject obj, jclass clazz,
- jmethodID methodID, ...) {
- fprintf(stderr, "Implement me\n");
- abort();
- return 0;
-}
-
-
-jboolean CallNonvirtualBooleanMethodV(JNIEnv *env, jobject obj, jclass clazz,
- jmethodID methodID, va_list args) {
- fprintf(stderr, "Implement me\n");
- abort();
- return 0;
-}
-
-
-jboolean CallNonvirtualBooleanMethodA(JNIEnv *env, jobject obj, jclass clazz,
- jmethodID methodID, const jvalue *args) {
- fprintf(stderr, "Implement me\n");
- abort();
- return 0;
-}
-
-
-jbyte CallNonvirtualByteMethod(JNIEnv *env, jobject obj, jclass clazz,
- jmethodID methodID, ...) {
- fprintf(stderr, "Implement me\n");
- abort();
- return 0;
-}
-
-
-jbyte CallNonvirtualByteMethodV (JNIEnv *env, jobject obj, jclass clazz,
- jmethodID methodID, va_list args) {
- fprintf(stderr, "Implement me\n");
- abort();
- return 0;
-}
-
-
-jbyte CallNonvirtualByteMethodA(JNIEnv *env, jobject obj, jclass clazz,
- jmethodID methodID, const jvalue *args) {
- fprintf(stderr, "Implement me\n");
- abort();
- return 0;
-}
-
-
-
-jchar CallNonvirtualCharMethod(JNIEnv *env, jobject obj, jclass clazz,
- jmethodID methodID, ...) {
- fprintf(stderr, "Implement me\n");
- abort();
- return 0;
-}
-
-
-jchar CallNonvirtualCharMethodV(JNIEnv *env, jobject obj, jclass clazz,
- jmethodID methodID, va_list args) {
- fprintf(stderr, "Implement me\n");
- abort();
- return 0;
-}
-
-
-jchar CallNonvirtualCharMethodA(JNIEnv *env, jobject obj, jclass clazz,
- jmethodID methodID, const jvalue *args) {
- fprintf(stderr, "Implement me\n");
- abort();
- return 0;
-}
-
-
-
-jshort CallNonvirtualShortMethod(JNIEnv *env, jobject obj, jclass clazz,
- jmethodID methodID, ...) {
- fprintf(stderr, "Implement me\n");
- abort();
- return 0;
-}
-
-
-jshort CallNonvirtualShortMethodV(JNIEnv *env, jobject obj, jclass clazz,
- jmethodID methodID, va_list args) {
- fprintf(stderr, "Implement me\n");
- abort();
- return 0;
-}
-
-
-jshort CallNonvirtualShortMethodA(JNIEnv *env, jobject obj, jclass clazz,
- jmethodID methodID, const jvalue *args) {
- fprintf(stderr, "Implement me\n");
- abort();
- return 0;
-}
-
-
-
-jint CallNonvirtualIntMethod(JNIEnv *env, jobject obj, jclass clazz,
- jmethodID methodID, ...) {
- fprintf(stderr, "Implement me\n");
- abort();
- return 0;
-}
-
-
-jint CallNonvirtualIntMethodV(JNIEnv *env, jobject obj, jclass clazz,
- jmethodID methodID, va_list args) {
- fprintf(stderr, "Implement me\n");
- abort();
- return 0;
-}
-
-
-jint CallNonvirtualIntMethodA(JNIEnv *env, jobject obj, jclass clazz,
- jmethodID methodID, const jvalue *args) {
- fprintf(stderr, "Implement me\n");
- abort();
- return 0;
-}
-
-
-
-jlong CallNonvirtualLongMethod(JNIEnv *env, jobject obj, jclass clazz,
- jmethodID methodID, ...) {
- fprintf(stderr, "Implement me\n");
- abort();
- return 0;
-}
-
-
-jlong CallNonvirtualLongMethodV(JNIEnv *env, jobject obj, jclass clazz,
- jmethodID methodID, va_list args) {
- fprintf(stderr, "Implement me\n");
- abort();
- return 0;
-}
-
-
-jlong CallNonvirtualLongMethodA(JNIEnv *env, jobject obj, jclass clazz,
- jmethodID methodID, const jvalue *args) {
- fprintf(stderr, "Implement me\n");
- abort();
- return 0;
-}
-
-
-
-jfloat CallNonvirtualFloatMethod(JNIEnv *env, jobject obj, jclass clazz,
- jmethodID methodID, ...) {
- fprintf(stderr, "Implement me\n");
- abort();
- return 0;
-}
-
-
-jfloat CallNonvirtualFloatMethodV(JNIEnv *env, jobject obj, jclass clazz,
- jmethodID methodID, va_list args) {
- fprintf(stderr, "Implement me\n");
- abort();
- return 0;
-}
-
-
-jfloat CallNonvirtualFloatMethodA(JNIEnv *env, jobject obj, jclass clazz,
- jmethodID methodID, const jvalue *args) {
- fprintf(stderr, "Implement me\n");
- abort();
- return 0;
-}
-
-
-
-jdouble CallNonvirtualDoubleMethod(JNIEnv *env, jobject obj, jclass clazz,
- jmethodID methodID, ...) {
- fprintf(stderr, "Implement me\n");
- abort();
- return 0;
-}
-
-
-jdouble CallNonvirtualDoubleMethodV(JNIEnv *env, jobject obj, jclass clazz,
- jmethodID methodID, va_list args) {
- fprintf(stderr, "Implement me\n");
- abort();
- return 0;
-}
-
-
-jdouble CallNonvirtualDoubleMethodA(JNIEnv *env, jobject obj, jclass clazz,
- jmethodID methodID, const jvalue *args) {
- fprintf(stderr, "Implement me\n");
- abort();
- return 0;
-}
-
-
-
-void CallNonvirtualVoidMethod(JNIEnv *env, jobject _obj, jclass clazz,
- jmethodID methodID, ...) {
-
- BEGIN_JNI_EXCEPTION
-
- verifyNull(_obj);
-
- va_list ap;
- va_start(ap, methodID);
-
- // Local object references.
- JavaObject* obj = *(JavaObject**)_obj;
- llvm_gcroot(obj, 0);
-
- JavaMethod* meth = (JavaMethod*)methodID;
- UserClass* cl = getClassFromVirtualMethod(meth, JavaObject::getClass(obj));
- meth->invokeIntSpecialAP(cl, obj, ap);
- va_end(ap);
-
- RETURN_VOID_FROM_JNI;
-
- END_JNI_EXCEPTION
-
- RETURN_VOID_FROM_JNI;
-}
-
-
-void CallNonvirtualVoidMethodV(JNIEnv *env, jobject obj, jclass clazz,
- jmethodID methodID, va_list args) {
- fprintf(stderr, "Implement me\n");
- abort();
-}
-
-
-void CallNonvirtualVoidMethodA(JNIEnv *env, jobject obj, jclass clazz,
- jmethodID methodID, const jvalue * args) {
- fprintf(stderr, "Implement me\n");
- abort();
-}
-
-
-jfieldID GetFieldID(JNIEnv *env, jclass _clazz, const char *aname,
- const char *sig) {
-
- BEGIN_JNI_EXCEPTION
-
- // Local object references.
- JavaObject* clazz = *(JavaObject**)_clazz;
- llvm_gcroot(clazz, 0);
-
- UserCommonClass* cl = UserCommonClass::resolvedImplClass(clazz, true);
-
- if (cl->isClass()) {
- const UTF8* name = cl->classLoader->hashUTF8->lookupAsciiz(aname);
- if (name) {
- const UTF8* type = cl->classLoader->hashUTF8->lookupAsciiz(sig);
- if (type) {
- JavaField* field = cl->asClass()->lookupField(name, type, false, true,
- 0);
- RETURN_FROM_JNI((jfieldID)field);
- }
- }
- }
-
- END_JNI_EXCEPTION
- RETURN_FROM_JNI(0);
-
-}
-
-
-jobject GetObjectField(JNIEnv *env, jobject _obj, jfieldID fieldID) {
-
- BEGIN_JNI_EXCEPTION
-
- // Local object references.
- JavaObject* obj = *(JavaObject**)_obj;
- JavaObject* res = 0;
- llvm_gcroot(obj, 0);
- llvm_gcroot(res, 0);
-
- JavaField* field = (JavaField*)fieldID;
-
- // Store local reference.
- res = field->getInstanceObjectField(obj);
-
- JavaThread* th = JavaThread::get();
- jobject ret = (jobject)th->pushJNIRef(res);
- RETURN_FROM_JNI(ret);
-
- END_JNI_EXCEPTION
- RETURN_FROM_JNI(0);
-}
-
-
-jboolean GetBooleanField(JNIEnv *env, jobject _obj, jfieldID fieldID) {
-
- BEGIN_JNI_EXCEPTION
-
- // Local object references.
- JavaObject* obj = *(JavaObject**)_obj;
- llvm_gcroot(obj, 0);
-
- JavaField* field = (JavaField*)fieldID;
- uint8 res = (uint8)field->getInstanceInt8Field(obj);
- RETURN_FROM_JNI(res);
-
- END_JNI_EXCEPTION
- RETURN_FROM_JNI(0);
-}
-
-
-jbyte GetByteField(JNIEnv *env, jobject _obj, jfieldID fieldID) {
-
- BEGIN_JNI_EXCEPTION
-
- // Local object references.
- JavaObject* obj = *(JavaObject**)_obj;
- llvm_gcroot(obj, 0);
-
- JavaField* field = (JavaField*)fieldID;
- sint8 res = (sint8)field->getInstanceInt8Field(obj);
- RETURN_FROM_JNI(res);
-
- END_JNI_EXCEPTION
- RETURN_FROM_JNI(0);
-}
-
-
-jchar GetCharField(JNIEnv *env, jobject _obj, jfieldID fieldID) {
-
- BEGIN_JNI_EXCEPTION
-
- // Local object references.
- JavaObject* obj = *(JavaObject**)_obj;
- llvm_gcroot(obj, 0);
-
- JavaField* field = (JavaField*)fieldID;
- uint16 res = (uint16)field->getInstanceInt16Field(obj);
- RETURN_FROM_JNI(res);
-
- END_JNI_EXCEPTION
- RETURN_FROM_JNI(0);
-}
-
-
-jshort GetShortField(JNIEnv *env, jobject _obj, jfieldID fieldID) {
-
- BEGIN_JNI_EXCEPTION
-
- // Local object references.
- JavaObject* obj = *(JavaObject**)_obj;
- llvm_gcroot(obj, 0);
-
- JavaField* field = (JavaField*)fieldID;
- sint16 res = (sint16)field->getInstanceInt16Field(obj);
- RETURN_FROM_JNI(res);
-
- END_JNI_EXCEPTION
- RETURN_FROM_JNI(0);
-}
-
-
-jint GetIntField(JNIEnv *env, jobject _obj, jfieldID fieldID) {
-
- BEGIN_JNI_EXCEPTION
-
- // Local object references.
- JavaObject* obj = *(JavaObject**)_obj;
- llvm_gcroot(obj, 0);
-
- JavaField* field = (JavaField*)fieldID;
- sint32 res = (sint32)field->getInstanceInt32Field(obj);
- RETURN_FROM_JNI(res);
-
- END_JNI_EXCEPTION
- RETURN_FROM_JNI(0);
-}
-
-
-jlong GetLongField(JNIEnv *env, jobject _obj, jfieldID fieldID) {
-
- BEGIN_JNI_EXCEPTION
-
- // Local object references.
- JavaObject* obj = *(JavaObject**)_obj;
- llvm_gcroot(obj, 0);
-
- JavaField* field = (JavaField*)fieldID;
- sint64 res = (sint64)field->getInstanceLongField(obj);
- RETURN_FROM_JNI(res);
-
- END_JNI_EXCEPTION
- RETURN_FROM_JNI(0);
-}
-
-
-jfloat GetFloatField(JNIEnv *env, jobject _obj, jfieldID fieldID) {
-
- BEGIN_JNI_EXCEPTION
-
- // Local object references.
- JavaObject* obj = *(JavaObject**)_obj;
- llvm_gcroot(obj, 0);
-
- JavaField* field = (JavaField*)fieldID;
- jfloat res = (jfloat)field->getInstanceFloatField(obj);
- RETURN_FROM_JNI(res);
-
- END_JNI_EXCEPTION
- RETURN_FROM_JNI(0);
-}
-
-
-jdouble GetDoubleField(JNIEnv *env, jobject _obj, jfieldID fieldID) {
-
- BEGIN_JNI_EXCEPTION
-
- // Local object references.
- JavaObject* obj = *(JavaObject**)_obj;
- llvm_gcroot(obj, 0);
-
- JavaField* field = (JavaField*)fieldID;
- jdouble res = (jdouble)field->getInstanceDoubleField(obj);
- RETURN_FROM_JNI(res);
-
- END_JNI_EXCEPTION
- RETURN_FROM_JNI(0);
-}
-
-
-void SetObjectField(JNIEnv *env, jobject _obj, jfieldID fieldID, jobject _value) {
-
- BEGIN_JNI_EXCEPTION
-
- // Local object references.
- JavaObject* obj = *(JavaObject**)_obj;
- JavaObject* value = *(JavaObject**)_value;
- llvm_gcroot(obj, 0);
- llvm_gcroot(value, 0);
-
- JavaField* field = (JavaField*)fieldID;
- field->setInstanceObjectField(obj, value);
-
- RETURN_VOID_FROM_JNI;
-
- END_JNI_EXCEPTION
-
- RETURN_VOID_FROM_JNI;
-}
-
-
-void SetBooleanField(JNIEnv *env, jobject _obj, jfieldID fieldID,
- jboolean value) {
-
- BEGIN_JNI_EXCEPTION
-
- // Local object references.
- JavaObject* obj = *(JavaObject**)_obj;
- llvm_gcroot(obj, 0);
-
- JavaField* field = (JavaField*)fieldID;
- field->setInstanceInt8Field(obj, (uint8)value);
-
- RETURN_VOID_FROM_JNI;
-
- END_JNI_EXCEPTION
-
- RETURN_VOID_FROM_JNI;
-}
-
-
-void SetByteField(JNIEnv *env, jobject _obj, jfieldID fieldID, jbyte value) {
-
- BEGIN_JNI_EXCEPTION
-
- // Local object references.
- JavaObject* obj = *(JavaObject**)_obj;
- llvm_gcroot(obj, 0);
-
- JavaField* field = (JavaField*)fieldID;
- field->setInstanceInt8Field(obj, (uint8)value);
-
- RETURN_VOID_FROM_JNI;
-
- END_JNI_EXCEPTION
-
- RETURN_VOID_FROM_JNI;
-}
-
-
-void SetCharField(JNIEnv *env, jobject _obj, jfieldID fieldID, jchar value) {
-
- BEGIN_JNI_EXCEPTION
-
- // Local object references.
- JavaObject* obj = *(JavaObject**)_obj;
- llvm_gcroot(obj, 0);
-
- JavaField* field = (JavaField*)fieldID;
- field->setInstanceInt16Field(obj, (uint16)value);
-
- RETURN_VOID_FROM_JNI;
-
- END_JNI_EXCEPTION
-
- RETURN_VOID_FROM_JNI;
-}
-
-
-void SetShortField(JNIEnv *env, jobject _obj, jfieldID fieldID, jshort value) {
-
- BEGIN_JNI_EXCEPTION
-
- // Local object references.
- JavaObject* obj = *(JavaObject**)_obj;
- llvm_gcroot(obj, 0);
-
- JavaField* field = (JavaField*)fieldID;
- field->setInstanceInt16Field(obj, (sint16)value);
-
- RETURN_VOID_FROM_JNI;
-
- END_JNI_EXCEPTION
-
- RETURN_VOID_FROM_JNI;
-}
-
-
-void SetIntField(JNIEnv *env, jobject _obj, jfieldID fieldID, jint value) {
-
- BEGIN_JNI_EXCEPTION
-
- // Local object references.
- JavaObject* obj = *(JavaObject**)_obj;
- llvm_gcroot(obj, 0);
-
- JavaField* field = (JavaField*)fieldID;
- field->setInstanceInt32Field(obj, (sint32)value);
-
- RETURN_VOID_FROM_JNI;
-
- END_JNI_EXCEPTION
-
- RETURN_VOID_FROM_JNI;
-}
-
-
-void SetLongField(JNIEnv *env, jobject _obj, jfieldID fieldID, jlong value) {
-
- BEGIN_JNI_EXCEPTION
-
- // Local object references.
- JavaObject* obj = *(JavaObject**)_obj;
- llvm_gcroot(obj, 0);
-
- JavaField* field = (JavaField*)fieldID;
- field->setInstanceLongField(obj, (sint64)value);
-
- RETURN_VOID_FROM_JNI;
-
- END_JNI_EXCEPTION
-
- RETURN_VOID_FROM_JNI;
-}
-
-
-void SetFloatField(JNIEnv *env, jobject _obj, jfieldID fieldID, jfloat value) {
-
- BEGIN_JNI_EXCEPTION
-
- // Local object references.
- JavaObject* obj = *(JavaObject**)_obj;
- llvm_gcroot(obj, 0);
-
- JavaField* field = (JavaField*)fieldID;
- field->setInstanceFloatField(obj, (float)value);
-
- RETURN_VOID_FROM_JNI;
-
- END_JNI_EXCEPTION
-
- RETURN_VOID_FROM_JNI;
-}
-
-
-void SetDoubleField(JNIEnv *env, jobject _obj, jfieldID fieldID, jdouble value) {
-
- BEGIN_JNI_EXCEPTION
-
- // Local object references.
- JavaObject* obj = *(JavaObject**)_obj;
- llvm_gcroot(obj, 0);
-
- JavaField* field = (JavaField*)fieldID;
- field->setInstanceDoubleField(obj, (float)value);
-
- RETURN_VOID_FROM_JNI;
-
- END_JNI_EXCEPTION
-
- RETURN_VOID_FROM_JNI;
-}
-
-
-jmethodID GetStaticMethodID(JNIEnv *env, jclass _clazz, const char *aname,
- const char *atype) {
-
- BEGIN_JNI_EXCEPTION
-
- // Local object references.
- JavaObject* clazz = *(JavaObject**)_clazz;
- llvm_gcroot(clazz, 0);
-
- UserCommonClass* cl = UserCommonClass::resolvedImplClass(clazz, true);
-
- if (cl->isClass()) {
- const UTF8* name = cl->classLoader->hashUTF8->lookupAsciiz(aname);
- if (name) {
- const UTF8* type = cl->classLoader->hashUTF8->lookupAsciiz(atype);
- if (type) {
- JavaMethod* meth = cl->asClass()->lookupMethod(name, type, true, true,
- 0);
- RETURN_FROM_JNI((jmethodID)meth);
- }
- }
- }
-
- END_JNI_EXCEPTION
- RETURN_FROM_JNI(0);
-}
-
-
-jobject CallStaticObjectMethod(JNIEnv *env, jclass _clazz, jmethodID methodID,
- ...) {
-
- BEGIN_JNI_EXCEPTION
-
- va_list ap;
- va_start(ap, methodID);
-
- // Local object references.
- JavaObject* clazz = *(JavaObject**)_clazz;
- JavaObject* res = 0;
- llvm_gcroot(clazz, 0);
- llvm_gcroot(res, 0);
-
-
- JavaMethod* meth = (JavaMethod*)methodID;
- JavaThread* th = JavaThread::get();
- UserClass* cl = getClassFromStaticMethod(meth, clazz);
-
- // Store local reference.
- res = meth->invokeJavaObjectStaticAP(cl, ap);
- va_end(ap);
-
- jobject ret = (jobject)th->pushJNIRef(res);
- RETURN_FROM_JNI(ret);
-
- END_JNI_EXCEPTION
- RETURN_FROM_JNI(0);
-}
-
-
-jobject CallStaticObjectMethodV(JNIEnv *env, jclass _clazz, jmethodID methodID,
- va_list args) {
- BEGIN_JNI_EXCEPTION
-
- // Local object references.
- JavaObject* clazz = *(JavaObject**)_clazz;
- JavaObject* res = 0;
- llvm_gcroot(clazz, 0);
- llvm_gcroot(res, 0);
-
- JavaMethod* meth = (JavaMethod*)methodID;
- JavaThread* th = JavaThread::get();
- UserClass* cl = getClassFromStaticMethod(meth, clazz);
-
- // Store local reference.
- res = meth->invokeJavaObjectStaticAP(cl, args);
-
- jobject ret = (jobject)th->pushJNIRef(res);
- RETURN_FROM_JNI(ret);
-
- END_JNI_EXCEPTION
- RETURN_FROM_JNI(0);
-}
-
-
-jobject CallStaticObjectMethodA(JNIEnv *env, jclass clazz, jmethodID methodID,
- const jvalue *args) {
- fprintf(stderr, "Implement me\n");
- abort();
- return 0;
-}
-
-
-jboolean CallStaticBooleanMethod(JNIEnv *env, jclass _clazz, jmethodID methodID,
- ...) {
-
- BEGIN_JNI_EXCEPTION
-
- va_list ap;
- va_start(ap, methodID);
-
- // Local object references.
- JavaObject* clazz = *(JavaObject**)_clazz;
- llvm_gcroot(clazz, 0);
-
- JavaMethod* meth = (JavaMethod*)methodID;
- UserClass* cl = getClassFromStaticMethod(meth, clazz);
- uint32 res = meth->invokeIntStaticAP(cl, ap);
- va_end(ap);
- RETURN_FROM_JNI(res);
-
- END_JNI_EXCEPTION
- RETURN_FROM_JNI(0);
-}
-
-
-jboolean CallStaticBooleanMethodV(JNIEnv *env, jclass _clazz, jmethodID methodID,
- va_list args) {
-
- BEGIN_JNI_EXCEPTION
-
- // Local object references.
- JavaObject* clazz = *(JavaObject**)_clazz;
- llvm_gcroot(clazz, 0);
-
- JavaMethod* meth = (JavaMethod*)methodID;
- UserClass* cl = getClassFromStaticMethod(meth, clazz);
- jboolean res = (jboolean)meth->invokeIntStaticAP(cl, args);
- RETURN_FROM_JNI(res);
-
- END_JNI_EXCEPTION
- RETURN_FROM_JNI(0);
-}
-
-
-jboolean CallStaticBooleanMethodA(JNIEnv *env, jclass clazz, jmethodID methodID,
- const jvalue *args) {
- fprintf(stderr, "Implement me\n");
- abort();
- return 0;
-}
-
-
-jbyte CallStaticByteMethod(JNIEnv *env, jclass _clazz, jmethodID methodID, ...) {
-
- BEGIN_JNI_EXCEPTION
-
- // Local object references.
- JavaObject* clazz = *(JavaObject**)_clazz;
- llvm_gcroot(clazz, 0);
-
- va_list ap;
- va_start(ap, methodID);
- JavaMethod* meth = (JavaMethod*)methodID;
- UserClass* cl = getClassFromStaticMethod(meth, clazz);
- jbyte res = (jbyte) meth->invokeIntStaticAP(cl, ap);
- va_end(ap);
- RETURN_FROM_JNI(res);
-
- END_JNI_EXCEPTION
- RETURN_FROM_JNI(0);
-}
-
-
-jbyte CallStaticByteMethodV(JNIEnv *env, jclass _clazz, jmethodID methodID,
- va_list args) {
-
- BEGIN_JNI_EXCEPTION
-
- // Local object references.
- JavaObject* clazz = *(JavaObject**)_clazz;
- llvm_gcroot(clazz, 0);
-
- JavaMethod* meth = (JavaMethod*)methodID;
- UserClass* cl = getClassFromStaticMethod(meth, clazz);
- jbyte res = (jbyte)meth->invokeIntStaticAP(cl, args);
- RETURN_FROM_JNI(res);
-
- END_JNI_EXCEPTION
- RETURN_FROM_JNI(0);
-}
-
-
-jbyte CallStaticByteMethodA(JNIEnv *env, jclass clazz, jmethodID methodID,
- const jvalue *args) {
- fprintf(stderr, "Implement me\n");
- abort();
- return 0;
-}
-
-
-jchar CallStaticCharMethod(JNIEnv *env, jclass _clazz, jmethodID methodID, ...) {
-
- BEGIN_JNI_EXCEPTION
-
- va_list ap;
- va_start(ap, methodID);
-
- // Local object references.
- JavaObject* clazz = *(JavaObject**)_clazz;
- llvm_gcroot(clazz, 0);
-
- JavaMethod* meth = (JavaMethod*)methodID;
- UserClass* cl = getClassFromStaticMethod(meth, clazz);
- jchar res = (jchar) meth->invokeIntStaticAP(cl, ap);
- va_end(ap);
- RETURN_FROM_JNI(res);
-
- END_JNI_EXCEPTION
- RETURN_FROM_JNI(0);
-}
-
-
-jchar CallStaticCharMethodV(JNIEnv *env, jclass _clazz, jmethodID methodID,
- va_list args) {
- BEGIN_JNI_EXCEPTION
-
- // Local object references.
- JavaObject* clazz = *(JavaObject**)_clazz;
- llvm_gcroot(clazz, 0);
-
- JavaMethod* meth = (JavaMethod*)methodID;
- UserClass* cl = getClassFromStaticMethod(meth, clazz);
- jchar res = (jchar)meth->invokeIntStaticAP(cl, args);
- RETURN_FROM_JNI(res);
-
- END_JNI_EXCEPTION
- RETURN_FROM_JNI(0);
-}
-
-
-jchar CallStaticCharMethodA(JNIEnv *env, jclass _clazz, jmethodID methodID,
- const jvalue *args) {
- fprintf(stderr, "Implement me\n");
- abort();
- return 0;
-}
-
-
-jshort CallStaticShortMethod(JNIEnv *env, jclass _clazz, jmethodID methodID,
- ...) {
-
- BEGIN_JNI_EXCEPTION
-
- va_list ap;
- va_start(ap, methodID);
-
- // Local object references.
- JavaObject* clazz = *(JavaObject**)_clazz;
- llvm_gcroot(clazz, 0);
-
- JavaMethod* meth = (JavaMethod*)methodID;
- UserClass* cl = getClassFromStaticMethod(meth, clazz);
- jshort res = (jshort) meth->invokeIntStaticAP(cl, ap);
- va_end(ap);
- RETURN_FROM_JNI(res);
-
- END_JNI_EXCEPTION
- RETURN_FROM_JNI(0);
-}
-
-
-jshort CallStaticShortMethodV(JNIEnv *env, jclass _clazz, jmethodID methodID,
- va_list args) {
-
- BEGIN_JNI_EXCEPTION
-
- // Local object references.
- JavaObject* clazz = *(JavaObject**)_clazz;
- llvm_gcroot(clazz, 0);
-
- JavaMethod* meth = (JavaMethod*)methodID;
- UserClass* cl = getClassFromStaticMethod(meth, clazz);
- jshort res = (jshort)meth->invokeIntStaticAP(cl, args);
- RETURN_FROM_JNI(res);
-
- END_JNI_EXCEPTION
- RETURN_FROM_JNI(0);
-}
-
-
-jshort CallStaticShortMethodA(JNIEnv *env, jclass clazz, jmethodID methodID,
- const jvalue *args) {
- fprintf(stderr, "Implement me\n");
- abort();
- return 0;
-}
-
-
-jint CallStaticIntMethod(JNIEnv *env, jclass _clazz, jmethodID methodID, ...) {
-
- BEGIN_JNI_EXCEPTION
-
- va_list ap;
- va_start(ap, methodID);
-
- // Local object references.
- JavaObject* clazz = *(JavaObject**)_clazz;
- llvm_gcroot(clazz, 0);
-
- JavaMethod* meth = (JavaMethod*)methodID;
- UserClass* cl = getClassFromStaticMethod(meth, clazz);
- jint res = (jint) meth->invokeIntStaticAP(cl, ap);
- va_end(ap);
- RETURN_FROM_JNI(res);
-
- END_JNI_EXCEPTION
- RETURN_FROM_JNI(0);
-}
-
-
-jint CallStaticIntMethodV(JNIEnv *env, jclass _clazz, jmethodID methodID,
- va_list args) {
- BEGIN_JNI_EXCEPTION
-
- // Local object references.
- JavaObject* clazz = *(JavaObject**)_clazz;
- llvm_gcroot(clazz, 0);
-
- JavaMethod* meth = (JavaMethod*)methodID;
- UserClass* cl = getClassFromStaticMethod(meth, clazz);
- jint res = (jint)meth->invokeIntStaticAP(cl, args);
- RETURN_FROM_JNI(res);
-
- END_JNI_EXCEPTION
-
- RETURN_FROM_JNI(0);
-}
-
-
-jint CallStaticIntMethodA(JNIEnv *env, jclass clazz, jmethodID methodID,
- const jvalue *args) {
- fprintf(stderr, "Implement me\n");
- abort();
- return 0;
-}
-
-
-jlong CallStaticLongMethod(JNIEnv *env, jclass _clazz, jmethodID methodID, ...) {
-
- BEGIN_JNI_EXCEPTION
-
- va_list ap;
- va_start(ap, methodID);
-
- // Local object references.
- JavaObject* clazz = *(JavaObject**)_clazz;
- llvm_gcroot(clazz, 0);
-
- JavaMethod* meth = (JavaMethod*)methodID;
- UserClass* cl = getClassFromStaticMethod(meth, clazz);
- jlong res = (jlong) meth->invokeLongStaticAP(cl, ap);
- va_end(ap);
- RETURN_FROM_JNI(res);
-
- END_JNI_EXCEPTION
- RETURN_FROM_JNI(0);
-}
-
-
-jlong CallStaticLongMethodV(JNIEnv *env, jclass _clazz, jmethodID methodID,
- va_list args) {
-
- BEGIN_JNI_EXCEPTION
-
- // Local object references.
- JavaObject* clazz = *(JavaObject**)_clazz;
- llvm_gcroot(clazz, 0);
-
- JavaMethod* meth = (JavaMethod*)methodID;
- UserClass* cl = getClassFromStaticMethod(meth, clazz);
- jlong res = (jlong)meth->invokeLongStaticAP(cl, args);
- RETURN_FROM_JNI(res);
-
- END_JNI_EXCEPTION
-
- RETURN_FROM_JNI(0);
-}
-
-
-jlong CallStaticLongMethodA(JNIEnv *env, jclass clazz, jmethodID methodID,
- const jvalue *args) {
- fprintf(stderr, "Implement me\n");
- abort();
- return 0;
-}
-
-
-
-jfloat CallStaticFloatMethod(JNIEnv *env, jclass _clazz, jmethodID methodID,
- ...) {
-
- BEGIN_JNI_EXCEPTION
-
- va_list ap;
- va_start(ap, methodID);
-
- // Local object references.
- JavaObject* clazz = *(JavaObject**)_clazz;
- llvm_gcroot(clazz, 0);
-
- JavaMethod* meth = (JavaMethod*)methodID;
- UserClass* cl = getClassFromStaticMethod(meth, clazz);
- jfloat res = (jfloat) meth->invokeFloatStaticAP(cl, ap);
- va_end(ap);
- RETURN_FROM_JNI(res);
-
- END_JNI_EXCEPTION
- RETURN_FROM_JNI(0.0f);
-}
-
-
-jfloat CallStaticFloatMethodV(JNIEnv *env, jclass _clazz, jmethodID methodID,
- va_list args) {
-
- BEGIN_JNI_EXCEPTION
-
- // Local object references.
- JavaObject* clazz = *(JavaObject**)_clazz;
- llvm_gcroot(clazz, 0);
-
- JavaMethod* meth = (JavaMethod*)methodID;
- UserClass* cl = getClassFromStaticMethod(meth, clazz);
- jfloat res = (jfloat)meth->invokeFloatStaticAP(cl, args);
- RETURN_FROM_JNI(res);
-
- END_JNI_EXCEPTION
-
- RETURN_FROM_JNI(0.0f);
-}
-
-
-jfloat CallStaticFloatMethodA(JNIEnv *env, jclass clazz, jmethodID methodID,
- const jvalue *args) {
- fprintf(stderr, "Implement me\n");
- abort();
- return 0;
-}
-
-
-jdouble CallStaticDoubleMethod(JNIEnv *env, jclass _clazz, jmethodID methodID,
- ...) {
-
- BEGIN_JNI_EXCEPTION
-
- va_list ap;
- va_start(ap, methodID);
-
- // Local object references.
- JavaObject* clazz = *(JavaObject**)_clazz;
- llvm_gcroot(clazz, 0);
-
- JavaMethod* meth = (JavaMethod*)methodID;
- UserClass* cl = getClassFromStaticMethod(meth, clazz);
- jdouble res = (jdouble) meth->invokeDoubleStaticAP(cl, ap);
- va_end(ap);
- RETURN_FROM_JNI(res);
-
- END_JNI_EXCEPTION
- RETURN_FROM_JNI(0.0);
-}
-
-
-jdouble CallStaticDoubleMethodV(JNIEnv *env, jclass _clazz, jmethodID methodID,
- va_list args) {
- BEGIN_JNI_EXCEPTION
-
- // Local object references.
- JavaObject* clazz = *(JavaObject**)_clazz;
- llvm_gcroot(clazz, 0);
-
- JavaMethod* meth = (JavaMethod*)methodID;
- UserClass* cl = getClassFromStaticMethod(meth, clazz);
- jdouble res = (jdouble)meth->invokeDoubleStaticAP(cl, args);
- RETURN_FROM_JNI(res);
-
- END_JNI_EXCEPTION
-
- RETURN_FROM_JNI(0.0);
-}
-
-
-jdouble CallStaticDoubleMethodA(JNIEnv *env, jclass clazz, jmethodID methodID,
- const jvalue *args) {
- fprintf(stderr, "Implement me\n");
- abort();
- return 0;
-}
-
-
-void CallStaticVoidMethod(JNIEnv *env, jclass _clazz, jmethodID methodID, ...) {
-
- BEGIN_JNI_EXCEPTION
-
- va_list ap;
- va_start(ap, methodID);
-
- // Local object references.
- JavaObject* clazz = *(JavaObject**)_clazz;
- llvm_gcroot(clazz, 0);
-
- JavaMethod* meth = (JavaMethod*)methodID;
- UserClass* cl = getClassFromStaticMethod(meth, clazz);
- meth->invokeIntStaticAP(cl, ap);
- va_end(ap);
-
- RETURN_VOID_FROM_JNI;
-
- END_JNI_EXCEPTION
-
- RETURN_VOID_FROM_JNI;
-}
-
-
-void CallStaticVoidMethodV(JNIEnv *env, jclass _clazz, jmethodID methodID,
- va_list args) {
-
- BEGIN_JNI_EXCEPTION
-
- // Local object references.
- JavaObject* clazz = *(JavaObject**)_clazz;
- llvm_gcroot(clazz, 0);
-
- JavaMethod* meth = (JavaMethod*)methodID;
- UserClass* cl = getClassFromStaticMethod(meth, clazz);
- meth->invokeIntStaticAP(cl, args);
-
- RETURN_VOID_FROM_JNI;
-
- END_JNI_EXCEPTION
-
- RETURN_VOID_FROM_JNI;
-}
-
-
-void CallStaticVoidMethodA(JNIEnv *env, jclass clazz, jmethodID methodID,
- const jvalue * args) {
- fprintf(stderr, "Implement me\n");
- abort();
-}
-
-
-jfieldID GetStaticFieldID(JNIEnv *env, jclass _clazz, const char *aname,
- const char *sig) {
-
- BEGIN_JNI_EXCEPTION
-
- // Local object references.
- JavaObject* clazz = *(JavaObject**)_clazz;
- llvm_gcroot(clazz, 0);
-
- UserCommonClass* cl = UserCommonClass::resolvedImplClass(clazz, true);
-
- if (cl->isClass()) {
- const UTF8* name = cl->classLoader->hashUTF8->lookupAsciiz(aname);
- if (name) {
- const UTF8* type = cl->classLoader->hashUTF8->lookupAsciiz(sig);
- if (type) {
- JavaField* field = cl->asClass()->lookupField(name, type, true, true,
- 0);
- RETURN_FROM_JNI((jfieldID)field);
- }
- }
- }
-
- END_JNI_EXCEPTION
- RETURN_FROM_JNI(0);
-}
-
-
-jobject GetStaticObjectField(JNIEnv *env, jclass _clazz, jfieldID fieldID) {
-
- BEGIN_JNI_EXCEPTION
-
- // Local object references.
- JavaObject* obj = 0;
- llvm_gcroot(obj, 0);
-
- JavaThread* th = JavaThread::get();
- JavaField* field = (JavaField*)fieldID;
- obj = field->getStaticObjectField();
- jobject res = (jobject)th->pushJNIRef(obj);
- RETURN_FROM_JNI(res);
-
- END_JNI_EXCEPTION
- RETURN_FROM_JNI(0);
-}
-
-
-jboolean GetStaticBooleanField(JNIEnv *env, jclass _clazz, jfieldID fieldID) {
-
- BEGIN_JNI_EXCEPTION
-
- JavaField* field = (JavaField*)fieldID;
- jboolean res = (jboolean)field->getStaticInt8Field();
- RETURN_FROM_JNI(res);
-
- END_JNI_EXCEPTION
- RETURN_FROM_JNI(0);
-}
-
-
-jbyte GetStaticByteField(JNIEnv *env, jclass _clazz, jfieldID fieldID) {
-
- BEGIN_JNI_EXCEPTION
-
- JavaField* field = (JavaField*)fieldID;
- jbyte res = (jbyte)field->getStaticInt8Field();
- RETURN_FROM_JNI(res);
-
- END_JNI_EXCEPTION
- RETURN_FROM_JNI(0);
-}
-
-
-jchar GetStaticCharField(JNIEnv *env, jclass _clazz, jfieldID fieldID) {
-
- BEGIN_JNI_EXCEPTION
-
- JavaField* field = (JavaField*)fieldID;
- jchar res = (jchar)field->getStaticInt16Field();
- RETURN_FROM_JNI(res);
-
- END_JNI_EXCEPTION
- RETURN_FROM_JNI(0);
-}
-
-
-jshort GetStaticShortField(JNIEnv *env, jclass _clazz, jfieldID fieldID) {
-
- BEGIN_JNI_EXCEPTION
-
- JavaField* field = (JavaField*)fieldID;
- jshort res = (jshort)field->getStaticInt16Field();
- RETURN_FROM_JNI(res);
-
- END_JNI_EXCEPTION
- RETURN_FROM_JNI(0);
-}
-
-
-jint GetStaticIntField(JNIEnv *env, jclass _clazz, jfieldID fieldID) {
-
- BEGIN_JNI_EXCEPTION
-
- JavaField* field = (JavaField*)fieldID;
- jint res = (jint)field->getStaticInt32Field();
- RETURN_FROM_JNI(res);
-
- END_JNI_EXCEPTION
- RETURN_FROM_JNI(0);
-}
-
-
-jlong GetStaticLongField(JNIEnv *env, jclass _clazz, jfieldID fieldID) {
-
- BEGIN_JNI_EXCEPTION
-
- JavaField* field = (JavaField*)fieldID;
- jlong res = (jlong)field->getStaticLongField();
- RETURN_FROM_JNI(res);
-
- END_JNI_EXCEPTION
- RETURN_FROM_JNI(0);
-}
-
-
-jfloat GetStaticFloatField(JNIEnv *env, jclass _clazz, jfieldID fieldID) {
-
- BEGIN_JNI_EXCEPTION
-
- JavaField* field = (JavaField*)fieldID;
- jfloat res = (jfloat)field->getStaticFloatField();
- RETURN_FROM_JNI(res);
-
- END_JNI_EXCEPTION
- RETURN_FROM_JNI(0);
-}
-
-
-jdouble GetStaticDoubleField(JNIEnv *env, jclass _clazz, jfieldID fieldID) {
-
- BEGIN_JNI_EXCEPTION
-
- JavaField* field = (JavaField*)fieldID;
- jdouble res = (jdouble)field->getStaticDoubleField();
- RETURN_FROM_JNI(res);
-
- END_JNI_EXCEPTION
- RETURN_FROM_JNI(0);
-}
-
-
-void SetStaticObjectField(JNIEnv *env, jclass _clazz, jfieldID fieldID,
- jobject _value) {
-
- BEGIN_JNI_EXCEPTION
-
- // Local object references.
- JavaObject* value = *(JavaObject**)_value;
- llvm_gcroot(value, 0);
-
- JavaField* field = (JavaField*)fieldID;
- field->setStaticObjectField(value);
-
- RETURN_VOID_FROM_JNI;
-
- END_JNI_EXCEPTION
-
- RETURN_VOID_FROM_JNI;
-}
-
-
-void SetStaticBooleanField(JNIEnv *env, jclass _clazz, jfieldID fieldID,
- jboolean value) {
-
- BEGIN_JNI_EXCEPTION
-
- JavaField* field = (JavaField*)fieldID;
- field->setStaticInt8Field((uint8)value);
-
- RETURN_VOID_FROM_JNI;
-
- END_JNI_EXCEPTION
-
- RETURN_VOID_FROM_JNI;
-}
-
-
-void SetStaticByteField(JNIEnv *env, jclass _clazz, jfieldID fieldID,
- jbyte value) {
-
- BEGIN_JNI_EXCEPTION
-
- JavaField* field = (JavaField*)fieldID;
- field->setStaticInt8Field((sint8)value);
-
- RETURN_VOID_FROM_JNI;
-
- END_JNI_EXCEPTION
-
- RETURN_VOID_FROM_JNI;
-}
-
-
-void SetStaticCharField(JNIEnv *env, jclass _clazz, jfieldID fieldID,
- jchar value) {
-
- BEGIN_JNI_EXCEPTION
-
- JavaField* field = (JavaField*)fieldID;
- field->setStaticInt16Field((uint16)value);
-
- RETURN_VOID_FROM_JNI;
-
- END_JNI_EXCEPTION
-
- RETURN_VOID_FROM_JNI;
-}
-
-
-void SetStaticShortField(JNIEnv *env, jclass _clazz, jfieldID fieldID,
- jshort value) {
-
- BEGIN_JNI_EXCEPTION
-
- JavaField* field = (JavaField*)fieldID;
- field->setStaticInt16Field((sint16)value);
-
- RETURN_VOID_FROM_JNI;
-
- END_JNI_EXCEPTION
-
- RETURN_VOID_FROM_JNI;
-}
-
-
-void SetStaticIntField(JNIEnv *env, jclass _clazz, jfieldID fieldID,
- jint value) {
-
- BEGIN_JNI_EXCEPTION
-
- JavaField* field = (JavaField*)fieldID;
- field->setStaticInt32Field((sint32)value);
-
- RETURN_VOID_FROM_JNI;
-
- END_JNI_EXCEPTION
-
- RETURN_VOID_FROM_JNI;
-}
-
-
-void SetStaticLongField(JNIEnv *env, jclass _clazz, jfieldID fieldID,
- jlong value) {
-
- BEGIN_JNI_EXCEPTION
-
- JavaField* field = (JavaField*)fieldID;
- field->setStaticLongField((sint64)value);
-
- RETURN_VOID_FROM_JNI;
-
- END_JNI_EXCEPTION
-
- RETURN_VOID_FROM_JNI;
-}
-
-
-void SetStaticFloatField(JNIEnv *env, jclass _clazz, jfieldID fieldID,
- jfloat value) {
-
- BEGIN_JNI_EXCEPTION
-
- JavaField* field = (JavaField*)fieldID;
- field->setStaticFloatField((float)value);
-
- RETURN_VOID_FROM_JNI;
-
- END_JNI_EXCEPTION
-
- RETURN_VOID_FROM_JNI;
-}
-
-
-void SetStaticDoubleField(JNIEnv *env, jclass _clazz, jfieldID fieldID,
- jdouble value) {
-
- BEGIN_JNI_EXCEPTION
-
- JavaField* field = (JavaField*)fieldID;
- field->setStaticDoubleField((double)value);
-
- RETURN_VOID_FROM_JNI;
-
- END_JNI_EXCEPTION
-
- RETURN_VOID_FROM_JNI;
-}
-
-
-jstring NewString(JNIEnv *env, const jchar *buf, jsize len) {
- fprintf(stderr, "Implement me\n");
- abort();
- return 0;
-}
-
-
-jsize GetStringLength(JNIEnv *env, jstring str) {
- fprintf(stderr, "Implement me\n");
- abort();
- return 0;
-}
-
-
-const jchar *GetStringChars(JNIEnv *env, jstring str, jboolean *isCopy) {
- fprintf(stderr, "Implement me\n");
- abort();
- return 0;
-}
-
-
-void ReleaseStringChars(JNIEnv *env, jstring str, const jchar *chars) {
- fprintf(stderr, "Implement me\n");
- abort();
-}
-
-
-jstring NewStringUTF(JNIEnv *env, const char *bytes) {
-
- BEGIN_JNI_EXCEPTION
-
- JavaObject* obj = NULL;
- llvm_gcroot(obj, 0);
-
- JavaThread* th = JavaThread::get();
- Jnjvm* vm = th->getJVM();
- obj = vm->asciizToStr(bytes);
- jstring ret = (jstring)th->pushJNIRef(obj);
- RETURN_FROM_JNI(ret);
-
- END_JNI_EXCEPTION
- RETURN_FROM_JNI(0);
-}
-
-
-jsize GetStringUTFLength (JNIEnv *env, jstring string) {
- fprintf(stderr, "Implement me\n");
- abort();
- return 0;
-}
-
-
-const char *GetStringUTFChars(JNIEnv *env, jstring _string, jboolean *isCopy) {
-
- BEGIN_JNI_EXCEPTION
-
- // Local object references.
- JavaString* string = *(JavaString**)_string;
- llvm_gcroot(string, 0);
-
- if (isCopy != 0) (*isCopy) = true;
- const char* res = JavaString::strToAsciiz(string);
- RETURN_FROM_JNI(res);
-
- END_JNI_EXCEPTION
- RETURN_FROM_JNI(0);
-}
-
-
-void ReleaseStringUTFChars(JNIEnv *env, jstring _string, const char *utf) {
- delete[] utf;
-}
-
-
-jsize GetArrayLength(JNIEnv *env, jarray _array) {
-
- BEGIN_JNI_EXCEPTION
-
- // Local object references.
- JavaObject* array = *(JavaObject**)_array;
- llvm_gcroot(array, 0);
-
- RETURN_FROM_JNI(JavaArray::getSize(array));
-
- END_JNI_EXCEPTION
- RETURN_FROM_JNI(0);
-}
-
-
-jobjectArray NewObjectArray(JNIEnv *env, jsize length, jclass _elementClass,
- jobject _initialElement) {
- BEGIN_JNI_EXCEPTION
-
- // Local object references.
- JavaObject* elementClass = *(JavaObject**)_elementClass;
- JavaObject* initialElement = _initialElement ?
- *(JavaObject**)_initialElement : 0;
- ArrayObject* res = 0;
- llvm_gcroot(elementClass, 0);
- llvm_gcroot(initialElement, 0);
- llvm_gcroot(res, 0);
-
- JavaThread* th = JavaThread::get();
-
- if (length < 0) th->getJVM()->negativeArraySizeException(length);
-
- UserCommonClass* base =
- UserCommonClass::resolvedImplClass(elementClass, true);
- JnjvmClassLoader* loader = base->classLoader;
- const UTF8* name = base->getName();
- const UTF8* arrayName = loader->constructArrayName(1, name);
- UserClassArray* array = loader->constructArray(arrayName, base);
- res = (ArrayObject*)array->doNew(length);
-
- if (initialElement) {
- for (sint32 i = 0; i < length; ++i) {
- ArrayObject::setElement(res, initialElement, i);
- }
- }
-
- jobjectArray ret = (jobjectArray)th->pushJNIRef(res);
- RETURN_FROM_JNI(ret);
-
- END_JNI_EXCEPTION
- RETURN_FROM_JNI(0);
-}
-
-
-jobject GetObjectArrayElement(JNIEnv *env, jobjectArray _array, jsize index) {
-
- BEGIN_JNI_EXCEPTION
-
- // Local object references.
- ArrayObject* array = *(ArrayObject**)_array;
- JavaObject* res = 0;
- llvm_gcroot(array, 0);
- llvm_gcroot(res, 0);
-
- JavaThread* th = JavaThread::get();
-
- if (index >= ArrayObject::getSize(array)) {
- th->getJVM()->indexOutOfBounds(array, index);
- }
-
- // Store local refererence.
- res = ArrayObject::getElement(array, index);
-
- jobject ret = (jobject)th->pushJNIRef(res);
- RETURN_FROM_JNI(ret);
-
- END_JNI_EXCEPTION
-
- RETURN_FROM_JNI(0);
-}
-
-
-void SetObjectArrayElement(JNIEnv *env, jobjectArray _array, jsize index,
- jobject _val) {
-
- BEGIN_JNI_EXCEPTION
-
- // Local object references.
- ArrayObject* array = *(ArrayObject**)_array;
- JavaObject* val = *(JavaObject**)_val;
- llvm_gcroot(array, 0);
- llvm_gcroot(val, 0);
-
- if (index >= ArrayObject::getSize(array)) {
- myVM(env)->indexOutOfBounds(array, index);
- }
-
- // Store global reference.
- ArrayObject::setElement(array, val, index);
-
- RETURN_VOID_FROM_JNI;
-
- END_JNI_EXCEPTION
-
- RETURN_VOID_FROM_JNI;
-}
-
-
-jbooleanArray NewBooleanArray(JNIEnv *env, jsize len) {
-
- BEGIN_JNI_EXCEPTION
-
- JavaObject* res = NULL;
- llvm_gcroot(res, 0);
-
- JavaThread* th = JavaThread::get();
- res = th->getJVM()->upcalls->ArrayOfBool->doNew(len);
- jbooleanArray ret = (jbooleanArray)th->pushJNIRef(res);
- RETURN_FROM_JNI(ret);
-
-
- END_JNI_EXCEPTION
- RETURN_FROM_JNI(0);
-}
-
-
-jbyteArray NewByteArray(JNIEnv *env, jsize len) {
-
- BEGIN_JNI_EXCEPTION
-
- JavaObject* res = NULL;
- llvm_gcroot(res, 0);
-
- JavaThread* th = JavaThread::get();
- res = th->getJVM()->upcalls->ArrayOfByte->doNew(len);
- jbyteArray ret = (jbyteArray)th->pushJNIRef(res);
- RETURN_FROM_JNI(ret);
-
- END_JNI_EXCEPTION
- RETURN_FROM_JNI(0);
-}
-
-
-jcharArray NewCharArray(JNIEnv *env, jsize len) {
-
- BEGIN_JNI_EXCEPTION
-
- JavaObject* res = NULL;
- llvm_gcroot(res, 0);
-
- JavaThread* th = JavaThread::get();
- res = th->getJVM()->upcalls->ArrayOfChar->doNew(len);
- jcharArray ret = (jcharArray)th->pushJNIRef(res);
- RETURN_FROM_JNI(ret);
-
- END_JNI_EXCEPTION
- RETURN_FROM_JNI(0);
-}
-
-
-jshortArray NewShortArray(JNIEnv *env, jsize len) {
-
- BEGIN_JNI_EXCEPTION
-
- JavaObject* res = NULL;
- llvm_gcroot(res, 0);
-
- JavaThread* th = JavaThread::get();
- res = th->getJVM()->upcalls->ArrayOfShort->doNew(len);
- jshortArray ret = (jshortArray)th->pushJNIRef(res);
- RETURN_FROM_JNI(ret);
-
- END_JNI_EXCEPTION
- RETURN_FROM_JNI(0);
-}
-
-
-jintArray NewIntArray(JNIEnv *env, jsize len) {
-
- BEGIN_JNI_EXCEPTION
-
- JavaObject* res = NULL;
- llvm_gcroot(res, 0);
-
- JavaThread* th = JavaThread::get();
- res = th->getJVM()->upcalls->ArrayOfInt->doNew(len);
- jintArray ret = (jintArray)th->pushJNIRef(res);
- RETURN_FROM_JNI(ret);
-
- END_JNI_EXCEPTION
- RETURN_FROM_JNI(0);
-}
-
-
-jlongArray NewLongArray(JNIEnv *env, jsize len) {
-
- BEGIN_JNI_EXCEPTION
-
- JavaObject* res = NULL;
- llvm_gcroot(res, 0);
-
- JavaThread* th = JavaThread::get();
- res = th->getJVM()->upcalls->ArrayOfLong->doNew(len);
- jlongArray ret = (jlongArray)th->pushJNIRef(res);
- RETURN_FROM_JNI(ret);
-
- END_JNI_EXCEPTION
- RETURN_FROM_JNI(0);
-}
-
-
-jfloatArray NewFloatArray(JNIEnv *env, jsize len) {
-
- BEGIN_JNI_EXCEPTION
-
- JavaObject* res = NULL;
- llvm_gcroot(res, 0);
-
- JavaThread* th = JavaThread::get();
- res = th->getJVM()->upcalls->ArrayOfFloat->doNew(len);
- jfloatArray ret = (jfloatArray)th->pushJNIRef(res);
- RETURN_FROM_JNI(ret);
-
- END_JNI_EXCEPTION
- RETURN_FROM_JNI(0);
-}
-
-
-jdoubleArray NewDoubleArray(JNIEnv *env, jsize len) {
-
- BEGIN_JNI_EXCEPTION
-
- JavaObject* res = NULL;
- llvm_gcroot(res, 0);
-
- JavaThread* th = JavaThread::get();
- res = th->getJVM()->upcalls->ArrayOfDouble->doNew(len);
- jdoubleArray ret = (jdoubleArray)th->pushJNIRef(res);
- RETURN_FROM_JNI(ret);
-
- END_JNI_EXCEPTION
- RETURN_FROM_JNI(0);
-}
-
-
-jboolean* GetBooleanArrayElements(JNIEnv *env, jbooleanArray _array,
- jboolean *isCopy) {
-
- BEGIN_JNI_EXCEPTION
-
- // Local object references.
- ArrayUInt8* array = *(ArrayUInt8**)_array;
- llvm_gcroot(array, 0);
-
- if (isCopy) (*isCopy) = true;
-
- sint32 len = ArrayUInt8::getSize(array) * sizeof(uint8);
- void* buffer = malloc(len);
- memcpy(buffer, ArrayUInt8::getElements(array), len);
-
- RETURN_FROM_JNI((jboolean*)buffer);
-
- END_JNI_EXCEPTION
- RETURN_FROM_JNI(0);
-}
-
-
-jbyte *GetByteArrayElements(JNIEnv *env, jbyteArray _array, jboolean *isCopy) {
-
- BEGIN_JNI_EXCEPTION
-
- // Local object references.
- ArraySInt8* array = *(ArraySInt8**)_array;
- llvm_gcroot(array, 0);
-
- if (isCopy) (*isCopy) = true;
-
- sint32 len = ArraySInt8::getSize(array) * sizeof(uint8);
- void* buffer = malloc(len);
- memcpy(buffer, ArraySInt8::getElements(array), len);
-
- RETURN_FROM_JNI((jbyte*)buffer);
-
- END_JNI_EXCEPTION
- RETURN_FROM_JNI(0);
-}
-
-
-jchar *GetCharArrayElements(JNIEnv *env, jcharArray _array, jboolean *isCopy) {
-
- BEGIN_JNI_EXCEPTION
-
- // Local object references.
- ArrayUInt16* array = *(ArrayUInt16**)_array;
- llvm_gcroot(array, 0);
-
- if (isCopy) (*isCopy) = true;
-
- sint32 len = ArrayUInt16::getSize(array) * sizeof(uint16);
- void* buffer = malloc(len);
- memcpy(buffer, ArrayUInt16::getElements(array), len);
-
- RETURN_FROM_JNI((jchar*)buffer);
-
- END_JNI_EXCEPTION
- RETURN_FROM_JNI(0);
-}
-
-
-jshort *GetShortArrayElements(JNIEnv *env, jshortArray _array,
- jboolean *isCopy) {
-
- BEGIN_JNI_EXCEPTION
-
- // Local object references.
- ArraySInt16* array = *(ArraySInt16**)_array;
- llvm_gcroot(array, 0);
-
- if (isCopy) (*isCopy) = true;
-
- sint32 len = ArraySInt16::getSize(array) * sizeof(sint16);
- void* buffer = malloc(len);
- memcpy(buffer, ArraySInt16::getElements(array), len);
-
- RETURN_FROM_JNI((jshort*)buffer);
-
- END_JNI_EXCEPTION
- RETURN_FROM_JNI(0);
-}
-
-
-jint *GetIntArrayElements(JNIEnv *env, jintArray _array, jboolean *isCopy) {
-
- BEGIN_JNI_EXCEPTION
-
- // Local object references.
- ArraySInt32* array = *(ArraySInt32**)_array;
- llvm_gcroot(array, 0);
-
- if (isCopy) (*isCopy) = true;
-
- sint32 len = ArraySInt32::getSize(array) * sizeof(sint32);
- void* buffer = malloc(len);
- memcpy(buffer, ArraySInt32::getElements(array), len);
-
- RETURN_FROM_JNI((jint*)buffer);
-
- END_JNI_EXCEPTION
- RETURN_FROM_JNI(0);
-}
-
-
-jlong *GetLongArrayElements(JNIEnv *env, jlongArray _array, jboolean *isCopy) {
-
- BEGIN_JNI_EXCEPTION
-
- // Local object references.
- ArrayLong* array = *(ArrayLong**)_array;
- llvm_gcroot(array, 0);
-
- if (isCopy) (*isCopy) = true;
-
- sint32 len = ArrayLong::getSize(array) * sizeof(sint64);
- void* buffer = malloc(len);
- memcpy(buffer, ArrayLong::getElements(array), len);
-
- RETURN_FROM_JNI((jlong*)buffer);
-
- END_JNI_EXCEPTION
- RETURN_FROM_JNI(0);
-}
-
-
-jfloat *GetFloatArrayElements(JNIEnv *env, jfloatArray _array,
- jboolean *isCopy) {
-
- BEGIN_JNI_EXCEPTION
-
- // Local object references.
- ArrayFloat* array = *(ArrayFloat**)_array;
- llvm_gcroot(array, 0);
-
- if (isCopy) (*isCopy) = true;
-
- sint32 len = ArrayFloat::getSize(array) * sizeof(float);
- void* buffer = malloc(len);
- memcpy(buffer, ArrayFloat::getElements(array), len);
-
- RETURN_FROM_JNI((jfloat*)buffer);
-
- END_JNI_EXCEPTION
- RETURN_FROM_JNI(0);
-}
-
-
-jdouble *GetDoubleArrayElements(JNIEnv *env, jdoubleArray _array,
- jboolean *isCopy) {
-
- BEGIN_JNI_EXCEPTION
-
- // Local object references.
- ArrayDouble* array = *(ArrayDouble**)_array;
- llvm_gcroot(array, 0);
-
- if (isCopy) (*isCopy) = true;
-
- sint32 len = ArrayDouble::getSize(array) * sizeof(double);
- void* buffer = malloc(len);
- memcpy(buffer, ArrayDouble::getElements(array), len);
-
- RETURN_FROM_JNI((jdouble*)buffer);
-
- END_JNI_EXCEPTION
- RETURN_FROM_JNI(0);
-}
-
-
-void ReleaseBooleanArrayElements(JNIEnv *env, jbooleanArray _array,
- jboolean *elems, jint mode) {
-
- BEGIN_JNI_EXCEPTION
-
- ArrayUInt8* array = *(ArrayUInt8**)_array;
- llvm_gcroot(array, 0);
-
- if (mode == JNI_ABORT) {
- free(elems);
- } else {
- sint32 len = ArrayUInt8::getSize(array);
- memcpy(ArrayUInt8::getElements(array), elems, len);
-
- if (mode == 0) free(elems);
- }
-
- END_JNI_EXCEPTION
-
- RETURN_VOID_FROM_JNI;
-}
-
-
-void ReleaseByteArrayElements(JNIEnv *env, jbyteArray _array, jbyte *elems,
- jint mode) {
-
- BEGIN_JNI_EXCEPTION
-
- ArraySInt16* array = *(ArraySInt16**)_array;
- llvm_gcroot(array, 0);
-
- if (mode == JNI_ABORT) {
- free(elems);
- } else {
- sint32 len = ArraySInt16::getSize(array);
- memcpy(ArraySInt16::getElements(array), elems, len);
-
- if (mode == 0) free(elems);
- }
-
- END_JNI_EXCEPTION
-
- RETURN_VOID_FROM_JNI;
-}
-
-
-void ReleaseCharArrayElements(JNIEnv *env, jcharArray _array, jchar *elems,
- jint mode) {
-
- BEGIN_JNI_EXCEPTION
-
- ArrayUInt16* array = *(ArrayUInt16**)_array;
- llvm_gcroot(array, 0);
-
- if (mode == JNI_ABORT) {
- free(elems);
- } else {
- sint32 len = ArrayUInt16::getSize(array) << 1;
- memcpy(ArrayUInt16::getElements(array), elems, len);
-
- if (mode == 0) free(elems);
- }
-
- END_JNI_EXCEPTION
-
- RETURN_VOID_FROM_JNI;
-}
-
-
-void ReleaseShortArrayElements(JNIEnv *env, jshortArray _array, jshort *elems,
- jint mode) {
-
- BEGIN_JNI_EXCEPTION
-
- ArraySInt16* array = *(ArraySInt16**)_array;
- llvm_gcroot(array, 0);
-
- if (mode == JNI_ABORT) {
- free(elems);
- } else {
- sint32 len = ArraySInt16::getSize(array) << 1;
- memcpy(ArraySInt16::getElements(array), elems, len);
-
- if (mode == 0) free(elems);
- }
-
- END_JNI_EXCEPTION
-
- RETURN_VOID_FROM_JNI;
-}
-
-
-void ReleaseIntArrayElements(JNIEnv *env, jintArray _array, jint *elems,
- jint mode) {
-
- BEGIN_JNI_EXCEPTION
-
- ArraySInt32* array = *(ArraySInt32**)_array;
- llvm_gcroot(array, 0);
-
- if (mode == JNI_ABORT) {
- free(elems);
- } else {
- sint32 len = ArraySInt32::getSize(array) << 2;
- memcpy(ArraySInt32::getElements(array), elems, len);
-
- if (mode == 0) free(elems);
- }
-
- END_JNI_EXCEPTION
-
- RETURN_VOID_FROM_JNI;
-}
-
-
-void ReleaseLongArrayElements(JNIEnv *env, jlongArray _array, jlong *elems,
- jint mode) {
-
- BEGIN_JNI_EXCEPTION
-
- ArrayLong* array = *(ArrayLong**)_array;
- llvm_gcroot(array, 0);
-
- if (mode == JNI_ABORT) {
- free(elems);
- } else {
- sint32 len = ArrayLong::getSize(array) << 3;
- memcpy(ArrayLong::getElements(array), elems, len);
-
- if (mode == 0) free(elems);
- }
-
- END_JNI_EXCEPTION
-
- RETURN_VOID_FROM_JNI;
-}
-
-
-void ReleaseFloatArrayElements(JNIEnv *env, jfloatArray _array, jfloat *elems,
- jint mode) {
- BEGIN_JNI_EXCEPTION
-
- ArrayFloat* array = *(ArrayFloat**)_array;
- llvm_gcroot(array, 0);
-
- if (mode == JNI_ABORT) {
- free(elems);
- } else {
- sint32 len = ArrayFloat::getSize(array) << 2;
- memcpy(ArrayFloat::getElements(array), elems, len);
-
- if (mode == 0) free(elems);
- }
-
- END_JNI_EXCEPTION
-
- RETURN_VOID_FROM_JNI;
-}
-
-
-void ReleaseDoubleArrayElements(JNIEnv *env, jdoubleArray _array,
- jdouble *elems, jint mode) {
-
- BEGIN_JNI_EXCEPTION
-
- ArrayDouble* array = *(ArrayDouble**)_array;
- llvm_gcroot(array, 0);
-
- if (mode == JNI_ABORT) {
- free(elems);
- } else {
- sint32 len = ArrayDouble::getSize(array) << 3;
- memcpy(ArrayDouble::getElements(array), elems, len);
-
- if (mode == 0) free(elems);
- }
-
- END_JNI_EXCEPTION
-
- RETURN_VOID_FROM_JNI;
-}
-
-
-void GetBooleanArrayRegion(JNIEnv *env, jbooleanArray array, jsize start,
- jsize len, jboolean *buf) {
- BEGIN_JNI_EXCEPTION
-
- ArrayUInt8* Array = *(ArrayUInt8**)array;
- llvm_gcroot(Array, 0);
- memcpy(buf, ArrayUInt8::getElements(Array) + start, len * sizeof(uint8));
-
- END_JNI_EXCEPTION
-
- RETURN_VOID_FROM_JNI;
-}
-
-
-void GetByteArrayRegion(JNIEnv *env, jbyteArray array, jsize start, jsize len,
- jbyte *buf) {
-
- BEGIN_JNI_EXCEPTION
-
- ArraySInt8* Array = *(ArraySInt8**)array;
- llvm_gcroot(Array, 0);
- memcpy(buf, ArraySInt8::getElements(Array) + start, len * sizeof(uint8));
-
- END_JNI_EXCEPTION
-
- RETURN_VOID_FROM_JNI;
-}
-
-
-void GetCharArrayRegion(JNIEnv *env, jcharArray array, jsize start, jsize len,
- jchar *buf) {
-
- BEGIN_JNI_EXCEPTION
-
- ArrayUInt16* Array = *(ArrayUInt16**)array;
- llvm_gcroot(Array, 0);
- memcpy(buf, ArrayUInt16::getElements(Array) + start, len * sizeof(uint16));
-
- END_JNI_EXCEPTION
-
- RETURN_VOID_FROM_JNI;
-}
-
-
-void GetShortArrayRegion(JNIEnv *env, jshortArray array, jsize start,
- jsize len, jshort *buf) {
-
- BEGIN_JNI_EXCEPTION
-
- ArraySInt16* Array = *(ArraySInt16**)array;
- llvm_gcroot(Array, 0);
- memcpy(buf, ArraySInt16::getElements(Array) + start, len * sizeof(sint16));
-
- END_JNI_EXCEPTION
-
- RETURN_VOID_FROM_JNI;
-}
-
-
-void GetIntArrayRegion(JNIEnv *env, jintArray array, jsize start, jsize len,
- jint *buf) {
-
- BEGIN_JNI_EXCEPTION
-
- ArraySInt32* Array = *(ArraySInt32**)array;
- llvm_gcroot(Array, 0);
- memcpy(buf, ArraySInt32::getElements(Array) + start, len * sizeof(sint32));
-
- END_JNI_EXCEPTION
-
- RETURN_VOID_FROM_JNI;
-}
-
-
-void GetLongArrayRegion(JNIEnv *env, jlongArray array, jsize start, jsize len,
- jlong *buf) {
-
- BEGIN_JNI_EXCEPTION
-
- ArrayLong* Array = *(ArrayLong**)array;
- llvm_gcroot(Array, 0);
- memcpy(buf, ArrayLong::getElements(Array) + start, len * sizeof(sint64));
-
- END_JNI_EXCEPTION
-
- RETURN_VOID_FROM_JNI;
-}
-
-
-void GetFloatArrayRegion(JNIEnv *env, jfloatArray array, jsize start,
- jsize len, jfloat *buf) {
-
- BEGIN_JNI_EXCEPTION
-
- ArrayFloat* Array = *(ArrayFloat**)array;
- llvm_gcroot(Array, 0);
- memcpy(buf, ArrayFloat::getElements(Array) + start, len * sizeof(float));
-
- END_JNI_EXCEPTION
-
- RETURN_VOID_FROM_JNI;
-}
-
-
-void GetDoubleArrayRegion(JNIEnv *env, jdoubleArray array, jsize start,
- jsize len, jdouble *buf) {
-
- BEGIN_JNI_EXCEPTION
-
- ArrayDouble* Array = *(ArrayDouble**)array;
- llvm_gcroot(Array, 0);
- memcpy(buf, ArrayDouble::getElements(Array) + start, len * sizeof(double));
-
- END_JNI_EXCEPTION
-
- RETURN_VOID_FROM_JNI;
-}
-
-
-void SetBooleanArrayRegion(JNIEnv *env, jbooleanArray array, jsize start,
- jsize len, const jboolean *buf) {
-
- BEGIN_JNI_EXCEPTION
-
- ArrayUInt8* Array = *(ArrayUInt8**)array;
- llvm_gcroot(Array, 0);
- memcpy(ArrayUInt8::getElements(Array) + start, buf, len * sizeof(uint8));
-
- END_JNI_EXCEPTION
-
- RETURN_VOID_FROM_JNI;
-}
-
-
-void SetByteArrayRegion(JNIEnv *env, jbyteArray array, jsize start, jsize len,
- const jbyte *buf) {
-
- BEGIN_JNI_EXCEPTION
-
- ArraySInt8* Array = *(ArraySInt8**)array;
- llvm_gcroot(Array, 0);
- memcpy(ArraySInt8::getElements(Array) + start, buf, len * sizeof(sint8));
-
- END_JNI_EXCEPTION
-
- RETURN_VOID_FROM_JNI;
-}
-
-
-void SetCharArrayRegion(JNIEnv *env, jcharArray array, jsize start, jsize len,
- const jchar *buf) {
-
- BEGIN_JNI_EXCEPTION
-
- ArrayUInt16* Array = *(ArrayUInt16**)array;
- llvm_gcroot(Array, 0);
- memcpy(ArrayUInt16::getElements(Array) + start, buf, len * sizeof(uint16));
-
- END_JNI_EXCEPTION
-
- RETURN_VOID_FROM_JNI;
-}
-
-
-void SetShortArrayRegion(JNIEnv *env, jshortArray array, jsize start,
- jsize len, const jshort *buf) {
-
- BEGIN_JNI_EXCEPTION
-
- ArraySInt16* Array = *(ArraySInt16**)array;
- llvm_gcroot(Array, 0);
- memcpy(ArraySInt16::getElements(Array) + start, buf, len * sizeof(sint16));
-
- END_JNI_EXCEPTION
-
- RETURN_VOID_FROM_JNI;
-}
-
-
-void SetIntArrayRegion(JNIEnv *env, jintArray array, jsize start, jsize len,
- const jint *buf) {
-
- BEGIN_JNI_EXCEPTION
-
- ArraySInt32* Array = *(ArraySInt32**)array;
- llvm_gcroot(Array, 0);
- memcpy(ArraySInt32::getElements(Array) + start, buf, len * sizeof(sint32));
-
- END_JNI_EXCEPTION
-
- RETURN_VOID_FROM_JNI;
-}
-
-
-void SetLongArrayRegion(JNIEnv* env, jlongArray array, jsize start, jsize len,
- const jlong *buf) {
-
- BEGIN_JNI_EXCEPTION
-
- ArrayLong* Array = *(ArrayLong**)array;
- llvm_gcroot(Array, 0);
- memcpy(ArrayLong::getElements(Array) + start, buf, len * sizeof(sint64));
-
- END_JNI_EXCEPTION
-
- RETURN_VOID_FROM_JNI;
-}
-
-
-void SetFloatArrayRegion(JNIEnv *env, jfloatArray array, jsize start,
- jsize len, const jfloat *buf) {
-
- BEGIN_JNI_EXCEPTION
-
- ArrayFloat* Array = *(ArrayFloat**)array;
- llvm_gcroot(Array, 0);
- memcpy(ArrayFloat::getElements(Array) + start, buf, len * sizeof(float));
-
- END_JNI_EXCEPTION
-
- RETURN_VOID_FROM_JNI;
-}
-
-
-void SetDoubleArrayRegion(JNIEnv *env, jdoubleArray array, jsize start,
- jsize len, const jdouble *buf) {
-
- BEGIN_JNI_EXCEPTION
-
- ArrayDouble* Array = *(ArrayDouble**)array;
- llvm_gcroot(Array, 0);
- memcpy(ArrayDouble::getElements(Array) + start, buf, len * sizeof(double));
-
- END_JNI_EXCEPTION
-
- RETURN_VOID_FROM_JNI;
-}
-
-
-jint RegisterNatives(JNIEnv *env, jclass clazz, const JNINativeMethod *methods,
- jint nMethods) {
- fprintf(stderr, "Implement me\n");
- abort();
- return 0;
-}
-
-
-jint UnregisterNatives(JNIEnv *env, jclass clazz) {
- fprintf(stderr, "Implement me\n");
- abort();
- return 0;
-}
-
-jint MonitorEnter(JNIEnv *env, jobject _obj) {
-
- BEGIN_JNI_EXCEPTION
-
- JavaObject* Obj = *(JavaObject**)_obj;
- llvm_gcroot(Obj, 0);
-
- if (Obj != NULL) {
- JavaObject::acquire(Obj);
- RETURN_FROM_JNI(0);
- } else {
- RETURN_FROM_JNI(-1);
- }
-
-
- END_JNI_EXCEPTION
- RETURN_FROM_JNI(-1);
-}
-
-
-jint MonitorExit(JNIEnv *env, jobject _obj) {
-
- BEGIN_JNI_EXCEPTION
-
- JavaObject* Obj = *(JavaObject**)_obj;
- llvm_gcroot(Obj, 0);
-
- if (Obj != NULL) {
-
- if (!JavaObject::owner(Obj)) {
- myVM(env)->illegalMonitorStateException(Obj);
- }
-
- JavaObject::release(Obj);
- RETURN_FROM_JNI(0);
- } else {
- RETURN_FROM_JNI(-1);
- }
-
- END_JNI_EXCEPTION
- RETURN_FROM_JNI(-1);
-}
-
-
-jint GetJavaVM(JNIEnv *env, JavaVM **vm) {
- BEGIN_JNI_EXCEPTION
- (*vm) = (JavaVM*)(void*)(&(myVM(env)->javavmEnv));
- RETURN_FROM_JNI(0);
- END_JNI_EXCEPTION
- RETURN_FROM_JNI(0);
-}
-
-
-void GetStringRegion(JNIEnv* env, jstring str, jsize start, jsize len,
- jchar *buf) {
- fprintf(stderr, "Implement me\n");
- abort();
-}
-
-
-void GetStringUTFRegion(JNIEnv* env, jstring str, jsize start, jsize len,
- char *buf) {
- fprintf(stderr, "Implement me\n");
- abort();
-}
-
-
-void *GetPrimitiveArrayCritical(JNIEnv *env, jarray _array, jboolean *isCopy) {
- BEGIN_JNI_EXCEPTION
-
- JavaObject* array = *(JavaObject**)_array;
- llvm_gcroot(array, 0);
-
- if (isCopy) (*isCopy) = true;
-
- UserClassArray* cl = JavaObject::getClass(array)->asArrayClass();
- uint32 logSize = cl->baseClass()->asPrimitiveClass()->logSize;
- sint32 len = JavaArray::getSize(array) << logSize;
- void* buffer = malloc(len);
- memcpy(buffer, JavaArray::getElements(array), len);
-
- RETURN_FROM_JNI((jchar*)buffer);
-
- END_JNI_EXCEPTION
- RETURN_FROM_JNI(0);
-}
-
-
-void ReleasePrimitiveArrayCritical(JNIEnv *env, jarray _array, void *carray,
- jint mode) {
-
- BEGIN_JNI_EXCEPTION
-
- JavaObject* array = *(JavaObject**)_array;
- llvm_gcroot(array, 0);
-
- if (mode == JNI_ABORT) {
- free(carray);
- } else {
- UserClassArray* cl = JavaObject::getClass(array)->asArrayClass();
- uint32 logSize = cl->baseClass()->asPrimitiveClass()->logSize;
- sint32 len = JavaArray::getSize(array) << logSize;
- memcpy(JavaArray::getElements(array), carray, len);
-
- if (mode == 0) free(carray);
- }
-
- END_JNI_EXCEPTION
-
- RETURN_VOID_FROM_JNI;
-}
-
-
-const jchar *GetStringCritical(JNIEnv *env, jstring string, jboolean *isCopy) {
- fprintf(stderr, "Implement me\n");
- abort();
- return 0;
-}
-
-
-void ReleaseStringCritical(JNIEnv *env, jstring string, const jchar *cstring) {
- fprintf(stderr, "Implement me\n");
- abort();
-}
-
-
-jweak NewWeakGlobalRef(JNIEnv* env, jobject obj) {
- fprintf(stderr, "Implement me\n");
- abort();
- return 0;
-}
-
-
-void DeleteWeakGlobalRef(JNIEnv* env, jweak ref) {
- fprintf(stderr, "Implement me\n");
- abort();
-}
-
-
-jobject NewGlobalRef(JNIEnv* env, jobject obj) {
-
- BEGIN_JNI_EXCEPTION
-
- JavaObject* Obj = NULL;
- llvm_gcroot(Obj, 0);
-
- // Local object references.
- if (obj) {
- Obj = *(JavaObject**)obj;
- llvm_gcroot(Obj, 0);
-
- Jnjvm* vm = myVM(env);
-
- vm->globalRefsLock.lock();
- JavaObject** res = vm->globalRefs.addJNIReference(Obj);
- vm->globalRefsLock.unlock();
-
- RETURN_FROM_JNI((jobject)res);
- } else {
- RETURN_FROM_JNI(0);
- }
-
- END_JNI_EXCEPTION
- RETURN_FROM_JNI(0);
-}
-
-
-void DeleteGlobalRef(JNIEnv* env, jobject globalRef) {
-
- BEGIN_JNI_EXCEPTION
-
- Jnjvm* vm = myVM(env);
- vm->globalRefsLock.lock();
- vm->globalRefs.removeJNIReference((JavaObject**)globalRef);
- vm->globalRefsLock.unlock();
-
- END_JNI_EXCEPTION
-
- RETURN_VOID_FROM_JNI;
-}
-
-
-jboolean ExceptionCheck(JNIEnv *env) {
- BEGIN_JNI_EXCEPTION
-
- if (mut->getPendingException()) {
- RETURN_FROM_JNI(JNI_TRUE);
- } else {
- RETURN_FROM_JNI(JNI_FALSE);
- }
-
- END_JNI_EXCEPTION
- RETURN_FROM_JNI(false);
-}
-
-
-jobject NewDirectByteBuffer(JNIEnv *env, void *address, jlong capacity) {
-
- BEGIN_JNI_EXCEPTION
-
- JavaObject* res = 0;
- JavaObject* p = 0;
- llvm_gcroot(res, 0);
- llvm_gcroot(p, 0);
-
- JavaThread* th = JavaThread::get();
- Jnjvm* vm = th->getJVM();
- UserClass* BB = vm->upcalls->newDirectByteBuffer;
-
- res = BB->doNew();
-
-#if (__WORDSIZE == 32)
- UserClass* PP = vm->upcalls->newPointer32;
- p = PP->doNew();
- vm->upcalls->dataPointer32->setInstanceInt32Field(p, (uint32)address);
-#else
- UserClass* PP = vm->upcalls->newPointer64;
- p = PP->doNew();
- vm->upcalls->dataPointer64->setInstanceLongField(p, (jlong)address);
-#endif
-
- vm->upcalls->InitDirectByteBuffer->invokeIntSpecial(BB, res, 0, &p,
- (uint32)capacity,
- (uint32)capacity, 0);
-
- jobject ret = (jobject)th->pushJNIRef(res);
- RETURN_FROM_JNI(ret);
-
- END_JNI_EXCEPTION
-
- RETURN_FROM_JNI(0);
-}
-
-
-void *GetDirectBufferAddress(JNIEnv *env, jobject _buf) {
-
- BEGIN_JNI_EXCEPTION
-
- // Local object references.
- JavaObject* buf = *(JavaObject**)_buf;
- JavaObject* address = 0;
- llvm_gcroot(buf, 0);
- llvm_gcroot(address, 0);
-
- Jnjvm* vm = myVM(env);
- address = vm->upcalls->bufferAddress->getInstanceObjectField(buf);
- if (address != 0) {
-#if (__WORDSIZE == 32)
- int res = vm->upcalls->dataPointer32->getInstanceInt32Field(address);
-#else
- jlong res = vm->upcalls->dataPointer64->getInstanceLongField(address);
-#endif
- RETURN_FROM_JNI((void*)res);
- } else {
- RETURN_FROM_JNI(0);
- }
-
- END_JNI_EXCEPTION
- RETURN_FROM_JNI(0);
-}
-
-
-jlong GetDirectBufferCapacity(JNIEnv* env, jobject buf) {
- fprintf(stderr, "Implement me\n");
- abort();
- return 0;
-}
-
-jobjectRefType GetObjectRefType(JNIEnv* env, jobject obj) {
- fprintf(stderr, "Implement me\n");
- abort();
- return (jobjectRefType)0;
-}
-
-
-
-jint DestroyJavaVM(JavaVM *vm) {
- fprintf(stderr, "Implement me\n");
- abort();
- return 0;
-}
-
-
-jint AttachCurrentThread(JavaVM *vm, void **env, void *thr_args) {
- fprintf(stderr, "Implement me\n");
- abort();
- return 0;
-}
-
-
-jint DetachCurrentThread(JavaVM *vm) {
- fprintf(stderr, "Implement me\n");
- abort();
- return 0;
-}
-
-
-jint GetEnv(JavaVM *vm, void **env, jint version) {
-
- BEGIN_JNI_EXCEPTION
-
- JavaThread* th = JavaThread::get();
- JavaObject* obj = th->currentThread();
- llvm_gcroot(obj, 0);
-
- Jnjvm* vm = th->getJVM();
- if (obj != 0) {
- (*env) = &(vm->jniEnv);
- RETURN_FROM_JNI(JNI_OK);
- } else {
- (*env) = 0;
- RETURN_FROM_JNI(JNI_EDETACHED);
- }
-
- END_JNI_EXCEPTION
- RETURN_FROM_JNI(0);
-}
-
-
-
-jint AttachCurrentThreadAsDaemon(JavaVM *vm, void **par1, void *par2) {
- fprintf(stderr, "Implement me\n");
- abort();
- return 0;
-}
-
-
-const struct JNIInvokeInterface_ JNI_JavaVMTable = {
- NULL,
- NULL,
- NULL,
-
- DestroyJavaVM,
- AttachCurrentThread,
- DetachCurrentThread,
- GetEnv,
- AttachCurrentThreadAsDaemon
-};
-
-
-struct JNINativeInterface_ JNI_JNIEnvTable = {
- NULL,
- NULL,
- NULL,
- NULL,
- &GetVersion,
-
- &DefineClass,
- &FindClass,
- &FromReflectedMethod,
- &FromReflectedField,
- &ToReflectedMethod,
- &GetSuperclass,
- &IsAssignableFrom,
- &ToReflectedField,
-
- &Throw,
- &ThrowNew,
- &ExceptionOccurred,
- &ExceptionDescribe,
- &ExceptionClear,
- &FatalError,
- &PushLocalFrame,
- &PopLocalFrame,
-
- &NewGlobalRef,
- &DeleteGlobalRef,
- &DeleteLocalRef,
- &IsSameObject,
- &NewLocalRef,
- &EnsureLocalCapacity,
-
- &AllocObject,
- &NewObject,
- &NewObjectV,
- &NewObjectA,
-
- &GetObjectClass,
- &IsInstanceOf,
-
- &GetMethodID,
-
- &CallObjectMethod,
- &CallObjectMethodV,
- &CallObjectMethodA,
- &CallBooleanMethod,
- &CallBooleanMethodV,
- &CallBooleanMethodA,
- &CallByteMethod,
- &CallByteMethodV,
- &CallByteMethodA,
- &CallCharMethod,
- &CallCharMethodV,
- &CallCharMethodA,
- &CallShortMethod,
- &CallShortMethodV,
- &CallShortMethodA,
- &CallIntMethod,
- &CallIntMethodV,
- &CallIntMethodA,
- &CallLongMethod,
- &CallLongMethodV,
- &CallLongMethodA,
- &CallFloatMethod,
- &CallFloatMethodV,
- &CallFloatMethodA,
- &CallDoubleMethod,
- &CallDoubleMethodV,
- &CallDoubleMethodA,
- &CallVoidMethod,
- &CallVoidMethodV,
- &CallVoidMethodA,
-
- &CallNonvirtualObjectMethod,
- &CallNonvirtualObjectMethodV,
- &CallNonvirtualObjectMethodA,
- &CallNonvirtualBooleanMethod,
- &CallNonvirtualBooleanMethodV,
- &CallNonvirtualBooleanMethodA,
- &CallNonvirtualByteMethod,
- &CallNonvirtualByteMethodV,
- &CallNonvirtualByteMethodA,
- &CallNonvirtualCharMethod,
- &CallNonvirtualCharMethodV,
- &CallNonvirtualCharMethodA,
- &CallNonvirtualShortMethod,
- &CallNonvirtualShortMethodV,
- &CallNonvirtualShortMethodA,
- &CallNonvirtualIntMethod,
- &CallNonvirtualIntMethodV,
- &CallNonvirtualIntMethodA,
- &CallNonvirtualLongMethod,
- &CallNonvirtualLongMethodV,
- &CallNonvirtualLongMethodA,
- &CallNonvirtualFloatMethod,
- &CallNonvirtualFloatMethodV,
- &CallNonvirtualFloatMethodA,
- &CallNonvirtualDoubleMethod,
- &CallNonvirtualDoubleMethodV,
- &CallNonvirtualDoubleMethodA,
- &CallNonvirtualVoidMethod,
- &CallNonvirtualVoidMethodV,
- &CallNonvirtualVoidMethodA,
-
- &GetFieldID,
-
- &GetObjectField,
- &GetBooleanField,
- &GetByteField,
- &GetCharField,
- &GetShortField,
- &GetIntField,
- &GetLongField,
- &GetFloatField,
- &GetDoubleField,
- &SetObjectField,
- &SetBooleanField,
- &SetByteField,
- &SetCharField,
- &SetShortField,
- &SetIntField,
- &SetLongField,
- &SetFloatField,
- &SetDoubleField,
-
- &GetStaticMethodID,
-
- &CallStaticObjectMethod,
- &CallStaticObjectMethodV,
- &CallStaticObjectMethodA,
- &CallStaticBooleanMethod,
- &CallStaticBooleanMethodV,
- &CallStaticBooleanMethodA,
- &CallStaticByteMethod,
- &CallStaticByteMethodV,
- &CallStaticByteMethodA,
- &CallStaticCharMethod,
- &CallStaticCharMethodV,
- &CallStaticCharMethodA,
- &CallStaticShortMethod,
- &CallStaticShortMethodV,
- &CallStaticShortMethodA,
- &CallStaticIntMethod,
- &CallStaticIntMethodV,
- &CallStaticIntMethodA,
- &CallStaticLongMethod,
- &CallStaticLongMethodV,
- &CallStaticLongMethodA,
- &CallStaticFloatMethod,
- &CallStaticFloatMethodV,
- &CallStaticFloatMethodA,
- &CallStaticDoubleMethod,
- &CallStaticDoubleMethodV,
- &CallStaticDoubleMethodA,
- &CallStaticVoidMethod,
- &CallStaticVoidMethodV,
- &CallStaticVoidMethodA,
-
- &GetStaticFieldID,
-
- &GetStaticObjectField,
- &GetStaticBooleanField,
- &GetStaticByteField,
- &GetStaticCharField,
- &GetStaticShortField,
- &GetStaticIntField,
- &GetStaticLongField,
- &GetStaticFloatField,
- &GetStaticDoubleField,
- &SetStaticObjectField,
- &SetStaticBooleanField,
- &SetStaticByteField,
- &SetStaticCharField,
- &SetStaticShortField,
- &SetStaticIntField,
- &SetStaticLongField,
- &SetStaticFloatField,
- &SetStaticDoubleField,
-
- &NewString,
- &GetStringLength,
- &GetStringChars,
- &ReleaseStringChars,
-
- &NewStringUTF,
- &GetStringUTFLength,
- &GetStringUTFChars,
- &ReleaseStringUTFChars,
-
- &GetArrayLength,
-
- &NewObjectArray,
- &GetObjectArrayElement,
- &SetObjectArrayElement,
-
- &NewBooleanArray,
- &NewByteArray,
- &NewCharArray,
- &NewShortArray,
- &NewIntArray,
- &NewLongArray,
- &NewFloatArray,
- &NewDoubleArray,
-
- &GetBooleanArrayElements,
- &GetByteArrayElements,
- &GetCharArrayElements,
- &GetShortArrayElements,
- &GetIntArrayElements,
- &GetLongArrayElements,
- &GetFloatArrayElements,
- &GetDoubleArrayElements,
-
- &ReleaseBooleanArrayElements,
- &ReleaseByteArrayElements,
- &ReleaseCharArrayElements,
- &ReleaseShortArrayElements,
- &ReleaseIntArrayElements,
- &ReleaseLongArrayElements,
- &ReleaseFloatArrayElements,
- &ReleaseDoubleArrayElements,
-
- &GetBooleanArrayRegion,
- &GetByteArrayRegion,
- &GetCharArrayRegion,
- &GetShortArrayRegion,
- &GetIntArrayRegion,
- &GetLongArrayRegion,
- &GetFloatArrayRegion,
- &GetDoubleArrayRegion,
- &SetBooleanArrayRegion,
- &SetByteArrayRegion,
- &SetCharArrayRegion,
- &SetShortArrayRegion,
- &SetIntArrayRegion,
- &SetLongArrayRegion,
- &SetFloatArrayRegion,
- &SetDoubleArrayRegion,
-
- &RegisterNatives,
- &UnregisterNatives,
-
- &MonitorEnter,
- &MonitorExit,
-
- &GetJavaVM,
-
- /* new JNI 1.2 functions */
-
- &GetStringRegion,
- &GetStringUTFRegion,
-
- &GetPrimitiveArrayCritical,
- &ReleasePrimitiveArrayCritical,
-
- &GetStringCritical,
- &ReleaseStringCritical,
-
- &NewWeakGlobalRef,
- &DeleteWeakGlobalRef,
-
- &ExceptionCheck,
-
- /* new JNI 1.4 functions */
-
- &NewDirectByteBuffer,
- &GetDirectBufferAddress,
- &GetDirectBufferCapacity,
-
- /* ---- JNI 1.6 functions ---- */
- &GetObjectRefType
-};
diff --git a/vmkit/lib/J3/VMCore/Jnjvm.cpp b/vmkit/lib/J3/VMCore/Jnjvm.cpp
deleted file mode 100644
index 3bf5e70..0000000
--- a/vmkit/lib/J3/VMCore/Jnjvm.cpp
+++ /dev/null
@@ -1,1446 +0,0 @@
-//===---------- Jnjvm.cpp - Java virtual machine description --------------===//
-//
-// The VMKit project
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#define JNJVM_LOAD 0
-
-#include <cfloat>
-#include <climits>
-#include <cstdarg>
-#include <cstdio>
-#include <cstdlib>
-#include <cstring>
-#include <string>
-#include "debug.h"
-
-#include "mvm/Threads/Thread.h"
-#include "mvm/VMKit.h"
-#include "mvm/GC.h"
-
-#include "ClasspathReflect.h"
-#include "JavaArray.h"
-#include "JavaClass.h"
-#include "JavaCompiler.h"
-#include "JavaConstantPool.h"
-#include "JavaString.h"
-#include "JavaThread.h"
-#include "JavaTypes.h"
-#include "JavaUpcalls.h"
-#include "Jnjvm.h"
-#include "LinkJavaRuntime.h"
-#include "LockedMap.h"
-#include "Reader.h"
-#include "Zip.h"
-
-using namespace j3;
-
-const char* Jnjvm::dirSeparator = "/";
-const char* Jnjvm::envSeparator = ":";
-const unsigned int Jnjvm::Magic = 0xcafebabe;
-
-/// initialiseClass - Java class initialisation. Java specification §2.17.5.
-
-void UserClass::initialiseClass() {
- mvm::gc* exc = NULL;
- JavaObject* obj = NULL;
- JavaObject* jexc;
-
- llvm_gcroot(jexc, 0);
- llvm_gcroot(exc, 0);
- llvm_gcroot(obj, 0);
-
- // Primitives are initialized at boot time, arrays are initialized directly.
-
- // Assumes that the Class object has already been verified and prepared and
- // that the Class object contains state that can indicate one of four
- // situations:
- //
- // * This Class object is verified and prepared but not initialized.
- // * This Class object is being initialized by some particular thread T.
- // * This Class object is fully initialized and ready for use.
- // * This Class object is in an erroneous state, perhaps because the
- // verification step failed or because initialization was attempted and
- // failed.
-
- assert((isResolved() || getOwnerClass() || isReady() ||
- isErroneous()) && "Class in wrong state");
-
- if (getInitializationState() != ready) {
-
- // 1. Synchronize on the Class object that represents the class or
- // interface to be initialized. This involves waiting until the
- // current thread can obtain the lock for that object
- // (Java specification §8.13).
- acquire();
- mvm::Thread* mut = mvm::Thread::get();
-
- if (getInitializationState() == inClinit) {
- // 2. If initialization by some other thread is in progress for the
- // class or interface, then wait on this Class object (which
- // temporarily releases the lock). When the current thread awakens
- // from the wait, repeat this step.
- if (getOwnerClass() != mut) {
- while (getOwnerClass()) {
- waitClass();
- }
- } else {
- // 3. If initialization is in progress for the class or interface by
- // the current thread, then this must be a recursive request for
- // initialization. Release the lock on the Class object and complete
- // normally.
- release();
- return;
- }
- }
-
- // 4. If the class or interface has already been initialized, then no
- // further action is required. Release the lock on the Class object
- // and complete normally.
- if (getInitializationState() == ready) {
- release();
- return;
- }
-
- // 5. If the Class object is in an erroneous state, then initialization is
- // not possible. Release the lock on the Class object and throw a
- // NoClassDefFoundError.
- if (isErroneous()) {
- release();
- classLoader->vm->noClassDefFoundError(name);
- }
-
- // 6. Otherwise, record the fact that initialization of the Class object is
- // now in progress by the current thread and release the lock on the
- // Class object.
- setOwnerClass(mut);
- bool vmjced = (getInitializationState() == vmjc);
- setInitializationState(inClinit);
- UserClass* cl = (UserClass*)this;
-
- // Single environment allocates the static instance during resolution, so
- // that compiled code can access it directly (with an initialization
- // check just before the access)
- if (!cl->getStaticInstance()) cl->allocateStaticInstance();
-
- release();
-
-
- // 7. Next, if the Class object represents a class rather than an interface,
- // and the direct superclass of this class has not yet been initialized,
- // then recursively perform this entire procedure for the uninitialized
- // superclass. If the initialization of the direct superclass completes
- // abruptly because of a thrown exception, then lock this Class object,
- // label it erroneous, notify all waiting threads, release the lock,
- // and complete abruptly, throwing the same exception that resulted from
- // the initializing the superclass.
- UserClass* super = getSuper();
- if (super) {
- TRY {
- super->initialiseClass();
- } CATCH {
- acquire();
- setErroneous();
- setOwnerClass(0);
- broadcastClass();
- release();
- } END_CATCH;
-
- if (mut->getPendingException() != NULL) {
- mut->throwIt();
- return;
- }
- }
-
- // 8. Next, execute either the class variable initializers and static
- // initializers of the class or the field initializers of the interface,
- // in textual order, as though they were a single block, except that
- // final static variables and fields of interfaces whose values are
- // compile-time constants are initialized first.
-
- PRINT_DEBUG(JNJVM_LOAD, 0, COLOR_NORMAL, "; ", 0);
- PRINT_DEBUG(JNJVM_LOAD, 0, LIGHT_GREEN, "clinit ", 0);
- PRINT_DEBUG(JNJVM_LOAD, 0, COLOR_NORMAL, "%s\n", mvm::PrintString(this).cString());
-
-
-
- if (!vmjced) {
- JavaField* fields = cl->getStaticFields();
- for (uint32 i = 0; i < cl->nbStaticFields; ++i) {
- fields[i].InitStaticField();
- }
- }
-
-
-
- JavaMethod* meth = lookupMethodDontThrow(classLoader->vm->upcalls->clinitName,
- classLoader->vm->upcalls->clinitType,
- true, false, 0);
-
- if (meth) {
- TRY {
- meth->invokeIntStatic(cl);
- } CATCH {
- exc = mut->getPendingException();
- assert(exc && "no exception?");
- mut->clearPendingException();
- } END_CATCH;
- }
-
- // 9. If the execution of the initializers completes normally, then lock
- // this Class object, label it fully initialized, notify all waiting
- // threads, release the lock, and complete this procedure normally.
- if (!exc) {
- acquire();
- setInitializationState(ready);
- setOwnerClass(0);
- broadcastClass();
- release();
- return;
- }
-
- // 10. Otherwise, the initializers must have completed abruptly by
- // throwing some exception E. If the class of E is not Error or one
- // of its subclasses, then create a new instance of the class
- // ExceptionInInitializerError, with E as the argument, and use this
- // object in place of E in the following step. But if a new instance of
- // ExceptionInInitializerError cannot be created because an
- // OutOfMemoryError occurs, then instead use an OutOfMemoryError object
- // in place of E in the following step.
- jexc = Jnjvm::asJavaException(exc);
- if (jexc && JavaObject::getClass(jexc)->isAssignableFrom(classLoader->vm->upcalls->newException)) {
- Classpath* upcalls = classLoader->vm->upcalls;
- UserClass* clExcp = upcalls->ExceptionInInitializerError;
- obj = clExcp->doNew();
- if (obj == NULL) {
- fprintf(stderr, "implement me");
- abort();
- }
- JavaMethod* init = upcalls->ErrorWithExcpExceptionInInitializerError;
- init->invokeIntSpecial(clExcp, obj, &exc);
- exc = obj;
- }
-
- // 11. Lock the Class object, label it erroneous, notify all waiting
- // threads, release the lock, and complete this procedure abruptly
- // with reason E or its replacement as determined in the previous step.
- acquire();
- setErroneous();
- setOwnerClass(0);
- broadcastClass();
- release();
- mut->setPendingException(exc)->throwIt();
- return;
- }
-}
-
-void Jnjvm::errorWithExcp(UserClass* cl, JavaMethod* init,
- const JavaObject* excp) {
- JavaObject* obj = NULL;
- llvm_gcroot(obj, 0);
- llvm_gcroot(excp, 0);
-
- obj = cl->doNew();
- init->invokeIntSpecial(cl, obj, &excp);
- mvm::Thread::get()->setPendingException(obj)->throwIt();
-}
-
-JavaObject* Jnjvm::CreateError(UserClass* cl, JavaMethod* init,
- const char* asciiz) {
- JavaObject* obj = NULL;
- JavaString* str = NULL;
- llvm_gcroot(obj, 0);
- llvm_gcroot(str, 0);
- obj = cl->doNew();
-
- if (asciiz) str = asciizToStr(asciiz);
-
- init->invokeIntSpecial(cl, obj, &str);
- return obj;
-}
-
-JavaObject* Jnjvm::CreateError(UserClass* cl, JavaMethod* init,
- JavaString* str) {
- JavaObject* obj = NULL;
- llvm_gcroot(str, 0);
- llvm_gcroot(obj, 0);
- obj = cl->doNew();
- init->invokeIntSpecial(cl, obj, &str);
- return obj;
-}
-
-void Jnjvm::error(UserClass* cl, JavaMethod* init, JavaString* str) {
- JavaObject* obj = 0;
- llvm_gcroot(obj, 0);
- llvm_gcroot(str, 0);
- obj = CreateError(cl, init, str);
- mvm::Thread::get()->setPendingException(obj)->throwIt();
-}
-
-void Jnjvm::arrayStoreException() {
- error(upcalls->ArrayStoreException,
- upcalls->InitArrayStoreException, (JavaString*)0);
-}
-
-void Jnjvm::indexOutOfBounds(const JavaObject* obj, sint32 entry) {
- JavaString* str = NULL;
- llvm_gcroot(obj, 0);
- llvm_gcroot(str, 0);
- str = (JavaString*)upcalls->IntToString->invokeJavaObjectStatic(
- upcalls->intClass, entry, 10);
- error(upcalls->ArrayIndexOutOfBoundsException,
- upcalls->InitArrayIndexOutOfBoundsException, str);
-}
-
-void Jnjvm::negativeArraySizeException(sint32 size) {
- JavaString* str = NULL;
- llvm_gcroot(str, 0);
- str = (JavaString*)
- upcalls->IntToString->invokeJavaObjectStatic(upcalls->intClass,
- size, 10);
- error(upcalls->NegativeArraySizeException,
- upcalls->InitNegativeArraySizeException, str);
-}
-
-void Jnjvm::nullPointerException() {
- error(upcalls->NullPointerException,
- upcalls->InitNullPointerException, (JavaString*)0);
-}
-
-JavaObject* Jnjvm::CreateIndexOutOfBoundsException(sint32 entry) {
- JavaString* str = NULL;
- llvm_gcroot(str, 0);
- str = (JavaString*)
- upcalls->IntToString->invokeJavaObjectStatic(upcalls->intClass,
- entry, 10);
- return CreateError(upcalls->ArrayIndexOutOfBoundsException,
- upcalls->InitArrayIndexOutOfBoundsException, str);
-}
-
-JavaObject* Jnjvm::CreateNegativeArraySizeException() {
- return CreateError(upcalls->NegativeArraySizeException,
- upcalls->InitNegativeArraySizeException,
- (JavaString*)0);
-}
-
-JavaObject* Jnjvm::CreateUnsatisfiedLinkError(JavaMethod* meth) {
- JavaString* str = NULL;
- llvm_gcroot(str, 0);
- str = constructString(meth->toString());
- return CreateError(upcalls->UnsatisfiedLinkError,
- upcalls->InitUnsatisfiedLinkError,
- str);
-}
-
-JavaObject* Jnjvm::CreateArithmeticException() {
- JavaString* str = NULL;
- llvm_gcroot(str, 0);
- str = asciizToStr("/ by zero");
- return CreateError(upcalls->ArithmeticException,
- upcalls->InitArithmeticException, str);
-}
-
-JavaObject* Jnjvm::CreateNullPointerException() {
- return CreateError(upcalls->NullPointerException,
- upcalls->InitNullPointerException,
- (JavaString*)0);
-}
-
-JavaObject* Jnjvm::CreateOutOfMemoryError() {
- JavaString* str = NULL;
- llvm_gcroot(str, 0);
- str = asciizToStr("Java heap space");
- return CreateError(upcalls->OutOfMemoryError,
- upcalls->InitOutOfMemoryError, str);
-}
-
-JavaObject* Jnjvm::CreateStackOverflowError() {
- // Don't call init, or else we'll get a new stack overflow error.
- JavaObject* obj = NULL;
- llvm_gcroot(obj, 0);
- obj = upcalls->StackOverflowError->doNew();
- JavaObjectThrowable::fillInStackTrace((JavaObjectThrowable*)obj);
- return obj;
-}
-
-JavaObject* Jnjvm::CreateArrayStoreException(JavaVirtualTable* VT) {
- JavaString* str = NULL;
- llvm_gcroot(str, 0);
- if (VT != NULL) str = JavaString::internalToJava(VT->cl->name, this);
- return CreateError(upcalls->ArrayStoreException,
- upcalls->InitArrayStoreException, str);
-}
-
-JavaObject* Jnjvm::CreateClassCastException(JavaObject* obj,
- UserCommonClass* cl) {
- llvm_gcroot(obj, 0);
- return CreateError(upcalls->ClassCastException,
- upcalls->InitClassCastException,
- (JavaString*)0);
-}
-
-JavaObject* Jnjvm::CreateLinkageError(const char* msg) {
- JavaString* str = NULL;
- llvm_gcroot(str, 0);
- str = asciizToStr(msg);
- return CreateError(upcalls->LinkageError,
- upcalls->InitLinkageError, str);
-}
-
-void Jnjvm::illegalAccessException(const char* msg) {
- JavaString* str = NULL;
- llvm_gcroot(str, 0);
- str = asciizToStr(msg);
- error(upcalls->IllegalAccessException,
- upcalls->InitIllegalAccessException, str);
-}
-
-void Jnjvm::illegalMonitorStateException(const JavaObject* obj) {
- llvm_gcroot(obj, 0);
- error(upcalls->IllegalMonitorStateException,
- upcalls->InitIllegalMonitorStateException,
- (JavaString*)0);
-}
-
-void Jnjvm::interruptedException(const JavaObject* obj) {
- llvm_gcroot(obj, 0);
- error(upcalls->InterruptedException,
- upcalls->InitInterruptedException,
- (JavaString*)0);
-}
-
-
-void Jnjvm::initializerError(const JavaObject* excp) {
- llvm_gcroot(excp, 0);
- errorWithExcp(upcalls->ExceptionInInitializerError,
- upcalls->ErrorWithExcpExceptionInInitializerError,
- excp);
-}
-
-void Jnjvm::invocationTargetException(const JavaObject* excp) {
- llvm_gcroot(excp, 0);
- errorWithExcp(upcalls->InvocationTargetException,
- upcalls->ErrorWithExcpInvocationTargetException,
- excp);
-}
-
-void Jnjvm::outOfMemoryError() {
- JavaString* str = NULL;
- llvm_gcroot(str, 0);
- str = asciizToStr("Java heap space");
- error(upcalls->OutOfMemoryError,
- upcalls->InitOutOfMemoryError, str);
-}
-
-void Jnjvm::illegalArgumentException(const char* msg) {
- JavaString* str = NULL;
- llvm_gcroot(str, 0);
- str = asciizToStr(msg);
- error(upcalls->IllegalArgumentException,
- upcalls->InitIllegalArgumentException, str);
-}
-
-void Jnjvm::classCastException(JavaObject* obj, UserCommonClass* cl) {
- llvm_gcroot(obj, 0);
- error(upcalls->ClassCastException,
- upcalls->InitClassCastException,
- (JavaString*)0);
-}
-
-void Jnjvm::noClassDefFoundError(JavaObject* obj) {
- llvm_gcroot(obj, 0);
- errorWithExcp(upcalls->NoClassDefFoundError,
- upcalls->ErrorWithExcpNoClassDefFoundError,
- obj);
-}
-
-void Jnjvm::instantiationException(UserCommonClass* cl) {
- JavaString* str = NULL;
- llvm_gcroot(str, 0);
- str = internalUTF8ToStr(cl->name);
- error(upcalls->InstantiationException, upcalls->InitInstantiationException,
- str);
-}
-
-void Jnjvm::instantiationError(UserCommonClass* cl) {
- JavaString* str = NULL;
- llvm_gcroot(str, 0);
- str = internalUTF8ToStr(cl->name);
- error(upcalls->InstantiationError, upcalls->InitInstantiationError, str);
-}
-
-
-JavaString* CreateNoSuchMsg(CommonClass* cl, const UTF8* name,
- Jnjvm* vm) {
- ArrayUInt16* msg = NULL;
- JavaString* str = NULL;
- llvm_gcroot(msg, 0);
- llvm_gcroot(str, 0);
- msg = (ArrayUInt16*)
- vm->upcalls->ArrayOfChar->doNew(19 + cl->name->size + name->size);
-
- uint32 i = 0;
-
-
- ArrayUInt16::setElement(msg, 'u', i); i++;
- ArrayUInt16::setElement(msg, 'n', i); i++;
- ArrayUInt16::setElement(msg, 'a', i); i++;
- ArrayUInt16::setElement(msg, 'b', i); i++;
- ArrayUInt16::setElement(msg, 'l', i); i++;
- ArrayUInt16::setElement(msg, 'e', i); i++;
- ArrayUInt16::setElement(msg, ' ', i); i++;
- ArrayUInt16::setElement(msg, 't', i); i++;
- ArrayUInt16::setElement(msg, 'o', i); i++;
- ArrayUInt16::setElement(msg, ' ', i); i++;
- ArrayUInt16::setElement(msg, 'f', i); i++;
- ArrayUInt16::setElement(msg, 'i', i); i++;
- ArrayUInt16::setElement(msg, 'n', i); i++;
- ArrayUInt16::setElement(msg, 'd', i); i++;
- ArrayUInt16::setElement(msg, ' ', i); i++;
-
- for (sint32 j = 0; j < name->size; ++j) {
- ArrayUInt16::setElement(msg, name->elements[j], i);
- i++;
- }
-
- ArrayUInt16::setElement(msg, ' ', i); i++;
- ArrayUInt16::setElement(msg, 'i', i); i++;
- ArrayUInt16::setElement(msg, 'n', i); i++;
- ArrayUInt16::setElement(msg, ' ', i); i++;
-
- for (sint32 j = 0; j < cl->name->size; ++j) {
- if (cl->name->elements[j] == '/') {
- ArrayUInt16::setElement(msg, '.', i);
- i++;
- } else {
- ArrayUInt16::setElement(msg, cl->name->elements[i], i);
- i++;
- }
- }
-
- str = vm->constructString(msg);
-
- return str;
-}
-
-void Jnjvm::noSuchFieldError(CommonClass* cl, const UTF8* name) {
- JavaString* str = NULL;
- llvm_gcroot(str, 0);
- str = CreateNoSuchMsg(cl, name, this);
- error(upcalls->NoSuchFieldError,
- upcalls->InitNoSuchFieldError, str);
-}
-
-void Jnjvm::noSuchMethodError(CommonClass* cl, const UTF8* name) {
- JavaString* str = NULL;
- llvm_gcroot(str, 0);
- str = CreateNoSuchMsg(cl, name, this);
- error(upcalls->NoSuchMethodError,
- upcalls->InitNoSuchMethodError, str);
-}
-
-void Jnjvm::abstractMethodError(CommonClass* cl, const UTF8* name) {
- JavaString* str = NULL;
- llvm_gcroot(str, 0);
- str = CreateNoSuchMsg(cl, name, this);
- error(upcalls->AbstractMethodError,
- upcalls->InitAbstractMethodError, str);
-}
-
-JavaString* CreateUnableToLoad(const UTF8* name, Jnjvm* vm) {
- ArrayUInt16* msg = NULL;
- JavaString* str = NULL;
- llvm_gcroot(msg, 0);
- llvm_gcroot(str, 0);
-
- msg = (ArrayUInt16*)vm->upcalls->ArrayOfChar->doNew(15 + name->size);
- uint32 i = 0;
-
-
- ArrayUInt16::setElement(msg, 'u', i); i++;
- ArrayUInt16::setElement(msg, 'n', i); i++;
- ArrayUInt16::setElement(msg, 'a', i); i++;
- ArrayUInt16::setElement(msg, 'b', i); i++;
- ArrayUInt16::setElement(msg, 'l', i); i++;
- ArrayUInt16::setElement(msg, 'e', i); i++;
- ArrayUInt16::setElement(msg, ' ', i); i++;
- ArrayUInt16::setElement(msg, 't', i); i++;
- ArrayUInt16::setElement(msg, 'o', i); i++;
- ArrayUInt16::setElement(msg, ' ', i); i++;
- ArrayUInt16::setElement(msg, 'l', i); i++;
- ArrayUInt16::setElement(msg, 'o', i); i++;
- ArrayUInt16::setElement(msg, 'a', i); i++;
- ArrayUInt16::setElement(msg, 'd', i); i++;
- ArrayUInt16::setElement(msg, ' ', i); i++;
-
- for (sint32 j = 0; j < name->size; ++j) {
- if (name->elements[j] == '/') {
- ArrayUInt16::setElement(msg, '.', i); i++;
- } else {
- ArrayUInt16::setElement(msg, name->elements[i], i); i++;
- }
- }
-
- str = vm->constructString(msg);
-
- return str;
-}
-
-JavaString* CreateUnableToLoad(JavaString* name, Jnjvm* vm) {
- JavaString* str = NULL;
- ArrayUInt16* msg = NULL;
- llvm_gcroot(msg, 0);
- llvm_gcroot(str, 0);
-
- msg = (ArrayUInt16*)vm->upcalls->ArrayOfChar->doNew(15 + name->count);
- uint32 i = 0;
-
- ArrayUInt16::setElement(msg, 'u', i); i++;
- ArrayUInt16::setElement(msg, 'n', i); i++;
- ArrayUInt16::setElement(msg, 'a', i); i++;
- ArrayUInt16::setElement(msg, 'b', i); i++;
- ArrayUInt16::setElement(msg, 'l', i); i++;
- ArrayUInt16::setElement(msg, 'e', i); i++;
- ArrayUInt16::setElement(msg, ' ', i); i++;
- ArrayUInt16::setElement(msg, 't', i); i++;
- ArrayUInt16::setElement(msg, 'o', i); i++;
- ArrayUInt16::setElement(msg, ' ', i); i++;
- ArrayUInt16::setElement(msg, 'l', i); i++;
- ArrayUInt16::setElement(msg, 'o', i); i++;
- ArrayUInt16::setElement(msg, 'a', i); i++;
- ArrayUInt16::setElement(msg, 'd', i); i++;
- ArrayUInt16::setElement(msg, ' ', i); i++;
-
- for (sint32 j = name->offset; j < name->offset + name->count; ++j) {
- if (ArrayUInt16::getElement(JavaString::getValue(name), j) == '/') {
- ArrayUInt16::setElement(msg, '.', i); i++;
- } else {
- ArrayUInt16::setElement(msg, ArrayUInt16::getElement(JavaString::getValue(name), j), i);
- }
- }
-
- str = vm->constructString(msg);
-
- return str;
-}
-
-
-
-void Jnjvm::noClassDefFoundError(const UTF8* name) {
- JavaString* str = NULL;
- llvm_gcroot(str, 0);
- str = CreateUnableToLoad(name, this);
- error(upcalls->NoClassDefFoundError,
- upcalls->InitNoClassDefFoundError, str);
-}
-
-void Jnjvm::classNotFoundException(JavaString* name) {
- JavaString* str = NULL;
- llvm_gcroot(str, 0);
- str = CreateUnableToLoad(name, this);
- error(upcalls->ClassNotFoundException,
- upcalls->InitClassNotFoundException, str);
-}
-
-void Jnjvm::noClassDefFoundError(UserClass* cl, const UTF8* name) {
- ArrayUInt16* msg = NULL;
- JavaString* str = NULL;
- llvm_gcroot(msg, 0);
- llvm_gcroot(str, 0);
-
- uint32 size = 35 + name->size + cl->name->size;
- msg = (ArrayUInt16*)upcalls->ArrayOfChar->doNew(size);
- uint32 i = 0;
-
-
- ArrayUInt16::setElement(msg, 't', i);
- ArrayUInt16::setElement(msg, 'r', i);
- ArrayUInt16::setElement(msg, 'y', i);
- ArrayUInt16::setElement(msg, ' ', i);
- ArrayUInt16::setElement(msg, 't', i);
- ArrayUInt16::setElement(msg, 'o', i);
- ArrayUInt16::setElement(msg, ' ', i);
- ArrayUInt16::setElement(msg, 'l', i);
- ArrayUInt16::setElement(msg, 'o', i);
- ArrayUInt16::setElement(msg, 'a', i);
- ArrayUInt16::setElement(msg, 'd', i);
- ArrayUInt16::setElement(msg, ' ', i);
-
- for (sint32 j = 0; j < cl->name->size; ++j) {
- if (cl->name->elements[j] == '/') {
- ArrayUInt16::setElement(msg, '.', i); i++;
- } else {
- ArrayUInt16::setElement(msg, cl->name->elements[j], i); i++;
- }
- }
-
- ArrayUInt16::setElement(msg, ' ', i); i++;
- ArrayUInt16::setElement(msg, 'a', i); i++;
- ArrayUInt16::setElement(msg, 'n', i); i++;
- ArrayUInt16::setElement(msg, 'd', i); i++;
- ArrayUInt16::setElement(msg, ' ', i); i++;
- ArrayUInt16::setElement(msg, 'f', i); i++;
- ArrayUInt16::setElement(msg, 'o', i); i++;
- ArrayUInt16::setElement(msg, 'u', i); i++;
- ArrayUInt16::setElement(msg, 'n', i); i++;
- ArrayUInt16::setElement(msg, 'd', i); i++;
- ArrayUInt16::setElement(msg, ' ', i); i++;
- ArrayUInt16::setElement(msg, 'c', i); i++;
- ArrayUInt16::setElement(msg, 'l', i); i++;
- ArrayUInt16::setElement(msg, 'a', i); i++;
- ArrayUInt16::setElement(msg, 's', i); i++;
- ArrayUInt16::setElement(msg, 's', i); i++;
- ArrayUInt16::setElement(msg, ' ', i); i++;
- ArrayUInt16::setElement(msg, 'n', i); i++;
- ArrayUInt16::setElement(msg, 'a', i); i++;
- ArrayUInt16::setElement(msg, 'm', i); i++;
- ArrayUInt16::setElement(msg, 'e', i); i++;
- ArrayUInt16::setElement(msg, 'd', i); i++;
- ArrayUInt16::setElement(msg, ' ', i); i++;
-
- for (sint32 j = 0; j < name->size; ++j) {
- if (name->elements[j] == '/') {
- ArrayUInt16::setElement(msg, '.', i); i++;
- } else {
- ArrayUInt16::setElement(msg, name->elements[j], i); i++;
- }
- }
-
- assert(i == size && "Array overflow");
-
- str = constructString(msg);
- error(upcalls->NoClassDefFoundError, upcalls->InitNoClassDefFoundError, str);
-}
-
-
-void Jnjvm::classFormatError(const char* msg) {
- JavaString* str = NULL;
- llvm_gcroot(str, 0);
- str = asciizToStr(msg);
- error(upcalls->ClassFormatError, upcalls->InitClassFormatError, str);
-}
-
-JavaString* Jnjvm::internalUTF8ToStr(const UTF8* utf8) {
- ArrayUInt16* tmp = NULL;
- llvm_gcroot(tmp, 0);
- uint32 size = utf8->size;
- tmp = (ArrayUInt16*)upcalls->ArrayOfChar->doNew(size);
-
- for (uint32 i = 0; i < size; i++) {
- ArrayUInt16::setElement(tmp, utf8->elements[i], i);
- }
-
- return hashStr.lookupOrCreate(const_cast<const ArrayUInt16*&>(tmp), this,
- JavaString::stringDup);
-}
-
-JavaString* Jnjvm::constructString(const ArrayUInt16* array) {
- JavaString* res = NULL;
- llvm_gcroot(array, 0);
- llvm_gcroot(res, 0);
- res = hashStr.lookupOrCreate(array, this, JavaString::stringDup);
- return res;
-}
-
-JavaString* Jnjvm::asciizToStr(const char* asciiz) {
- ArrayUInt16* var = NULL;
- llvm_gcroot(var, 0);
- assert(asciiz && "No asciiz given");
- var = asciizToArray(asciiz);
- return constructString(var);
-}
-
-void Jnjvm::addProperty(char* key, char* value) {
- postProperties.push_back(std::make_pair(key, value));
-}
-
-// Mimic what's happening in Classpath when creating a java.lang.Class object.
-JavaObject* UserCommonClass::getClassDelegatee(JavaObject* pd) {
- JavaObjectClass* delegatee = 0;
- JavaObjectClass* base = 0;
- llvm_gcroot(pd, 0);
- llvm_gcroot(delegatee, 0);
- llvm_gcroot(base, 0);
-
- if (getDelegatee() == NULL) {
- UserClass* cl = classLoader->vm->upcalls->newClass;
- delegatee = (JavaObjectClass*)cl->doNew();
- JavaObjectClass::setClass(delegatee, this);
- if (pd == NULL && isArray()) {
- base = (JavaObjectClass*)
- asArrayClass()->baseClass()->getClassDelegatee(pd);
- JavaObjectClass::setProtectionDomain(
- delegatee, JavaObjectClass::getProtectionDomain(base));
- } else {
- JavaObjectClass::setProtectionDomain(delegatee, pd);
- }
- setDelegatee(delegatee);
- }
- return getDelegatee();
-}
-
-JavaObject* const* UserCommonClass::getClassDelegateePtr(JavaObject* pd) {
- llvm_gcroot(pd, 0);
- // Make sure it's created.
- getClassDelegatee(pd);
- return getDelegateePtr();
-}
-
-#define PATH_MANIFEST "META-INF/MANIFEST.MF"
-#define MAIN_CLASS "Main-Class: "
-#define MAIN_LOWER_CLASS "Main-class: "
-#define PREMAIN_CLASS "Premain-Class: "
-#define BOOT_CLASS_PATH "Boot-Class-Path: "
-#define CAN_REDEFINE_CLASS_PATH "Can-Redefine-Classes: "
-
-#define LENGTH_MAIN_CLASS 12
-#define LENGTH_PREMAIN_CLASS 15
-#define LENGTH_BOOT_CLASS_PATH 17
-
-extern "C" struct JNINativeInterface JNI_JNIEnvTable;
-extern "C" const struct JNIInvokeInterface JNI_JavaVMTable;
-
-void ClArgumentsInfo::javaAgent(char* cur) {
- assert(0 && "implement me");
-}
-
-extern "C" int sys_strnstr(const char *haystack, const char *needle) {
- const char* res = strstr(haystack, needle);
- if (res) return res - haystack;
- else return -1;
-}
-
-
-static char* findInformation(Jnjvm* vm, ClassBytes* manifest, const char* entry,
- uint32 len) {
- sint32 index = sys_strnstr((char*)manifest->elements, entry);
- if (index != -1) {
- index += len;
- sint32 end = sys_strnstr((char*)manifest->elements + index, "\n");
- if (end == -1) end = manifest->size;
- else end += index;
-
- sint32 length = end - index - 1;
- char* name = (char*)vm->allocator.Allocate(length + 1, "class name");
- memcpy(name, manifest->elements + index, length);
- name[length] = 0;
- return name;
- } else {
- return 0;
- }
-}
-
-void ClArgumentsInfo::extractClassFromJar(Jnjvm* vm, int argc, char** argv,
- int i) {
- ClassBytes* bytes = NULL;
- ClassBytes* res = NULL;
- jarFile = argv[i];
-
- vm->setClasspath(jarFile);
-
- bytes = Reader::openFile(vm->bootstrapLoader, jarFile);
-
- if (bytes == NULL) {
- printf("Unable to access jarfile %s\n", jarFile);
- return;
- }
-
- mvm::BumpPtrAllocator allocator;
- ZipArchive* archive = new(allocator, "TempZipArchive")
- ZipArchive(bytes, allocator);
- if (archive->getOfscd() != -1) {
- ZipFile* file = archive->getFile(PATH_MANIFEST);
- if (file != NULL) {
- res = new (allocator, file->ucsize) ClassBytes(file->ucsize);
- int ok = archive->readFile(res, file);
- if (ok) {
- char* mainClass = findInformation(vm, res, MAIN_CLASS,
- LENGTH_MAIN_CLASS);
- if (mainClass == NULL) {
- mainClass = findInformation(vm, res, MAIN_LOWER_CLASS,
- LENGTH_MAIN_CLASS);
- }
- if (mainClass != NULL) {
- className = mainClass;
- } else {
- printf("No Main-Class: in Manifest of archive %s.\n", jarFile);
- }
- } else {
- printf("Can't extract Manifest file from archive %s\n", jarFile);
- }
- } else {
- printf("Can't find Manifest file in archive %s\n", jarFile);
- }
- } else {
- printf("Can't find archive %s\n", jarFile);
- }
-}
-
-void ClArgumentsInfo::nyi() {
- fprintf(stdout, "Not yet implemented\n");
-}
-
-void ClArgumentsInfo::printVersion() {
- fprintf(stdout, "J3 for Java 1.1 -- 1.5\n");
-}
-
-void ClArgumentsInfo::printInformation() {
- fprintf(stdout,
- "Usage: j3 [-options] class [args...] (to execute a class)\n"
- "or j3 [-options] -jar jarfile [args...]\n"
- "(to execute a jar file) where options include:\n"
- "-cp <class search path of directories and zip/jar files>\n"
- "-classpath <class search path of directories and zip/jar files>\n"
- " A : separated list of directories, JAR archives,\n"
- " and ZIP archives to search for class files.\n"
- "-D<name>=<value>\n"
- " set a system property\n"
- "-verbose[:class|gc|jni]\n"
- " enable verbose output\n"
- "-version print product version and exit\n"
- "-version:<value>\n"
- " require the specified version to run\n"
- "-showversion print product version and continue\n"
- "-jre-restrict-search | -jre-no-restrict-search\n"
- " include/exclude user private JREs in the version search\n"
- "-? -help print this help message\n"
- "-X print help on non-standard options\n"
- "-ea[:<packagename>...|:<classname>]\n"
- "-enableassertions[:<packagename>...|:<classname>]\n"
- " enable assertions\n"
- "-da[:<packagename>...|:<classname>]\n"
- "-disableassertions[:<packagename>...|:<classname>]\n"
- " disable assertions\n"
- "-esa | -enablesystemassertions\n"
- " enable system assertions\n"
- "-dsa | -disablesystemassertions\n"
- " disable system assertions\n"
- "-agentlib:<libname>[=<options>]\n"
- " load native agent library <libname>, e.g. -agentlib:hprof\n"
- " see also, -agentlib:jdwp=help and -agentlib:hprof=help\n"
- "-agentpath:<pathname>[=<options>]\n"
- " load native agent library by full pathname\n"
- "-javaagent:<jarpath>[=<options>]\n"
- " load Java programming language agent, see java.lang.instrument\n");
-}
-
-void ClArgumentsInfo::readArgs(Jnjvm* vm) {
- className = 0;
- appArgumentsPos = 0;
- sint32 i = 1;
- if (i == argc) printInformation();
- while (i < argc) {
- char* cur = argv[i];
- if (!(strcmp(cur, "-classpath"))) {
- ++i;
- if (i == argc) printInformation();
- else vm->setClasspath(argv[i]);
- } else if (!(strcmp(cur, "-cp"))) {
- ++i;
- if (i == argc) printInformation();
- else vm->setClasspath(argv[i]);
- } else if (!(strncmp(cur, "-D", 2))) {
- uint32 len = strlen(cur);
- if (len == 2) {
- printInformation();
- } else {
- char* key = &cur[2];
- char* value = strchr(key, '=');
- if (!value) {
- printInformation();
- return;
- } else {
- value[0] = 0;
- vm->addProperty(key, &value[1]);
- }
- }
- } else if (!(strncmp(cur, "-Xbootclasspath:", 16))) {
- uint32 len = strlen(cur);
- if (len == 16) {
- printInformation();
- } else {
- char* path = &cur[16];
- vm->bootstrapLoader->analyseClasspathEnv(path);
- }
- } else if (!(strcmp(cur, "-enableassertions"))) {
- nyi();
- } else if (!(strcmp(cur, "-ea"))) {
- nyi();
- } else if (!(strcmp(cur, "-disableassertions"))) {
- nyi();
- } else if (!(strcmp(cur, "-da"))) {
- nyi();
- } else if (!(strcmp(cur, "-enablesystemassertions"))) {
- nyi();
- } else if (!(strcmp(cur, "-esa"))) {
- nyi();
- } else if (!(strcmp(cur, "-disablesystemassertions"))) {
- nyi();
- } else if (!(strcmp(cur, "-dsa"))) {
- nyi();
- } else if (!(strcmp(cur, "-jar"))) {
- ++i;
- if (i == argc) {
- printInformation();
- } else {
- extractClassFromJar(vm, argc, argv, i);
- appArgumentsPos = i;
- return;
- }
- } else if (!(strcmp(cur, "-jre-restrict-research"))) {
- nyi();
- } else if (!(strcmp(cur, "-jre-no-restrict-research"))) {
- nyi();
- } else if (!(strcmp(cur, "-noclassgc"))) {
- nyi();
- } else if (!(strcmp(cur, "-ms"))) {
- nyi();
- } else if (!(strcmp(cur, "-mx"))) {
- nyi();
- } else if (!(strcmp(cur, "-ss"))) {
- nyi();
- } else if (!(strcmp(cur, "-verbose"))) {
- nyi();
- } else if (!(strcmp(cur, "-verbose:class"))) {
- nyi();
- } else if (!(strcmp(cur, "-verbosegc"))) {
- nyi();
- } else if (!(strcmp(cur, "-verbose:gc"))) {
- mvm::Collector::verbose = 1;
- } else if (!(strcmp(cur, "-verbose:jni"))) {
- nyi();
- } else if (!(strcmp(cur, "-version"))) {
- printVersion();
- } else if (!(strcmp(cur, "-showversion"))) {
- nyi();
- } else if (!(strcmp(cur, "-?"))) {
- printInformation();
- } else if (!(strcmp(cur, "-help"))) {
- printInformation();
- } else if (!(strcmp(cur, "-X"))) {
- nyi();
- } else if (!(strcmp(cur, "-agentlib"))) {
- nyi();
- } else if (!(strcmp(cur, "-agentpath"))) {
- nyi();
- } else if (cur[0] == '-') {
- } else if (!(strcmp(cur, "-javaagent"))) {
- javaAgent(cur);
- } else {
- className = cur;
- appArgumentsPos = i;
- return;
- }
- ++i;
- }
-}
-
-
-JnjvmClassLoader* Jnjvm::loadAppClassLoader() {
- JavaObject* loader = 0;
- llvm_gcroot(loader, 0);
-
- if (appClassLoader == NULL) {
- UserClass* cl = upcalls->newClassLoader;
- loader = upcalls->getSystemClassLoader->invokeJavaObjectStatic(cl);
- appClassLoader = JnjvmClassLoader::getJnjvmLoaderFromJavaObject(loader,
- this);
- if (argumentsInfo.jarFile) {
- appClassLoader->loadLibFromJar(argumentsInfo.jarFile,
- argumentsInfo.className);
- } else if (argumentsInfo.className) {
- appClassLoader->loadLibFromFile(argumentsInfo.className);
- }
- }
- return appClassLoader;
-}
-
-mvm::VMThreadData* Jnjvm::buildVMThreadData(mvm::Thread* mut) {
- JavaThread* th = JavaThread::associate(this, mut);
- upcalls->CreateForeignJavaThread(this, th);
- return th;
-}
-
-void Jnjvm::loadBootstrap() {
- JavaObject* obj = NULL;
- JavaObject* javaLoader = NULL;
- llvm_gcroot(obj, 0);
- llvm_gcroot(javaLoader, 0);
- JnjvmClassLoader* loader = bootstrapLoader;
-
- // Initialise the bootstrap class loader if it's not
- // done already.
- if (upcalls->newString == NULL) {
- upcalls->postInitialiseClasspath(bootstrapLoader);
- }
-
-#define LOAD_CLASS(cl) \
- cl->resolveClass(); \
- cl->initialiseClass();
-
- // If a string belongs to the vm hashmap, we must remove it when
- // it's destroyed. So we define a new VT for strings that will be
- // placed in the hashmap. This VT will have its destructor set so
- // that the string is removed when deallocated.
- upcalls->newString->resolveClass();
- if (JavaString::internStringVT == NULL) {
- JavaVirtualTable* stringVT = upcalls->newString->getVirtualVT();
- uint32 size = upcalls->newString->virtualTableSize * sizeof(uintptr_t);
-
- JavaString::internStringVT =
- (JavaVirtualTable*)bootstrapLoader->allocator.Allocate(size, "String VT");
-
- memcpy(JavaString::internStringVT, stringVT, size);
-
- JavaString::internStringVT->destructor =
- (uintptr_t)JavaString::stringDestructor;
-
- // Tell the finalizer that this is a native destructor.
- JavaString::internStringVT->operatorDelete =
- (uintptr_t)JavaString::stringDestructor;
- }
- upcalls->newString->initialiseClass();
-
- // The initialization code of the classes initialized below may require
- // to get the Java thread, so we create the Java thread object first.
- upcalls->InitializeThreading(this);
-
- LOAD_CLASS(upcalls->newClass);
- LOAD_CLASS(upcalls->newConstructor);
- LOAD_CLASS(upcalls->newField);
- LOAD_CLASS(upcalls->newMethod);
- LOAD_CLASS(upcalls->newVMThread);
- LOAD_CLASS(upcalls->newStackTraceElement);
- LOAD_CLASS(upcalls->newVMThrowable);
- LOAD_CLASS(upcalls->boolClass);
- LOAD_CLASS(upcalls->byteClass);
- LOAD_CLASS(upcalls->charClass);
- LOAD_CLASS(upcalls->shortClass);
- LOAD_CLASS(upcalls->intClass);
- LOAD_CLASS(upcalls->longClass);
- LOAD_CLASS(upcalls->floatClass);
- LOAD_CLASS(upcalls->doubleClass);
- LOAD_CLASS(upcalls->InvocationTargetException);
- LOAD_CLASS(upcalls->ArrayStoreException);
- LOAD_CLASS(upcalls->ClassCastException);
- LOAD_CLASS(upcalls->IllegalMonitorStateException);
- LOAD_CLASS(upcalls->IllegalArgumentException);
- LOAD_CLASS(upcalls->InterruptedException);
- LOAD_CLASS(upcalls->IndexOutOfBoundsException);
- LOAD_CLASS(upcalls->ArrayIndexOutOfBoundsException);
- LOAD_CLASS(upcalls->NegativeArraySizeException);
- LOAD_CLASS(upcalls->NullPointerException);
- LOAD_CLASS(upcalls->SecurityException);
- LOAD_CLASS(upcalls->ClassFormatError);
- LOAD_CLASS(upcalls->ClassCircularityError);
- LOAD_CLASS(upcalls->NoClassDefFoundError);
- LOAD_CLASS(upcalls->UnsupportedClassVersionError);
- LOAD_CLASS(upcalls->NoSuchFieldError);
- LOAD_CLASS(upcalls->NoSuchMethodError);
- LOAD_CLASS(upcalls->InstantiationError);
- LOAD_CLASS(upcalls->IllegalAccessError);
- LOAD_CLASS(upcalls->IllegalAccessException);
- LOAD_CLASS(upcalls->VerifyError);
- LOAD_CLASS(upcalls->ExceptionInInitializerError);
- LOAD_CLASS(upcalls->LinkageError);
- LOAD_CLASS(upcalls->AbstractMethodError);
- LOAD_CLASS(upcalls->UnsatisfiedLinkError);
- LOAD_CLASS(upcalls->InternalError);
- LOAD_CLASS(upcalls->OutOfMemoryError);
- LOAD_CLASS(upcalls->StackOverflowError);
- LOAD_CLASS(upcalls->UnknownError);
- LOAD_CLASS(upcalls->ClassNotFoundException);
- LOAD_CLASS(upcalls->ArithmeticException);
- LOAD_CLASS(upcalls->InstantiationException);
- LOAD_CLASS(upcalls->SystemClass);
-#undef LOAD_CLASS
-
- loadAppClassLoader();
- obj = JavaThread::get()->currentThread();
- javaLoader = appClassLoader->getJavaClassLoader();
-
- upcalls->setContextClassLoader->invokeIntSpecial(upcalls->newThread,
- obj, &javaLoader);
- // load and initialise math since it is responsible for dlopen'ing
- // libjavalang.so and we are optimizing some math operations
- UserCommonClass* math = loader->loadName(
- loader->asciizConstructUTF8("java/lang/Math"), true, true, NULL);
- math->asClass()->initialiseClass();
-}
-
-void Jnjvm::executeClass(const char* className, ArrayObject* args) {
- mvm::gc* exc = NULL;
- JavaObject* obj = NULL;
- JavaObject* group = NULL;
-
- llvm_gcroot(args, 0);
- llvm_gcroot(exc, 0);
- llvm_gcroot(obj, 0);
- llvm_gcroot(group, 0);
-
- TRY {
- // First try to see if we are a self-contained executable.
- UserClass* cl = appClassLoader->loadClassFromSelf(className);
-
- // If not, load the class.
- if (cl == NULL) {
- const UTF8* name = appClassLoader->asciizConstructUTF8(className);
- cl = (UserClass*)appClassLoader->loadName(name, true, true, NULL);
- }
-
- cl->initialiseClass();
-
- const UTF8* funcSign =
- appClassLoader->asciizConstructUTF8("([Ljava/lang/String;)V");
- const UTF8* funcName = appClassLoader->asciizConstructUTF8("main");
- JavaMethod* method = cl->lookupMethod(funcName, funcSign, true, true, 0);
- if (isPublic(method->access)) {
- method->invokeIntStatic(method->classDef, &args);
- } else {
- fprintf(stderr, "Main method not public.\n");
- }
- } CATCH {
- } END_CATCH;
-
- mvm::Thread* mut = mvm::Thread::get();
- exc = mut->getPendingException();
-
- if (exc != NULL) {
- JavaThread* th = JavaThread::get();
- mut->clearPendingException();
- obj = th->currentThread();
- group = upcalls->group->getInstanceObjectField(obj);
- TRY {
- upcalls->uncaughtException->invokeIntSpecial(upcalls->threadGroup,
- group, &obj, &exc);
- } CATCH {
- fprintf(stderr, "Exception in thread \"main\": "
- "Can not print stack trace.\n");
- } END_CATCH;
- }
-}
-
-void Jnjvm::executePremain(const char* className, JavaString* args,
- JavaObject* instrumenter) {
- llvm_gcroot(args, 0);
- llvm_gcroot(instrumenter, 0);
- TRY {
- const UTF8* name = appClassLoader->asciizConstructUTF8(className);
- UserClass* cl = (UserClass*)
- appClassLoader->loadName(name, true, true, NULL);
- cl->initialiseClass();
-
- const UTF8* funcSign = appClassLoader->asciizConstructUTF8(
- "(Ljava/lang/String;Ljava/lang/instrument/Instrumentation;)V");
- const UTF8* funcName = appClassLoader->asciizConstructUTF8("premain");
- JavaMethod* method = cl->lookupMethod(funcName, funcSign, true, true, 0);
-
- method->invokeIntStatic(method->classDef, &args, &instrumenter);
- } IGNORE;
-}
-
-void Jnjvm::runApplicationImpl(int argc, char** argv) {
- JavaString* str = NULL;
- JavaObject* instrumenter = NULL;
- ArrayObject* args = NULL;
- mvm::gc* exc = NULL;
- JavaObject *jexc;
-
- llvm_gcroot(jexc, 0);
- llvm_gcroot(str, 0);
- llvm_gcroot(instrumenter, 0);
- llvm_gcroot(args, 0);
- llvm_gcroot(exc, 0);
-
- JavaThread::associate(this, mvm::Thread::get());
-
- argumentsInfo.argc = argc;
- argumentsInfo.argv = argv;
-
- bootstrapLoader->analyseClasspathEnv(bootstrapLoader->bootClasspathEnv);
- argumentsInfo.readArgs(this);
- if (argumentsInfo.className == NULL)
- return;
-
- int pos = argumentsInfo.appArgumentsPos;
- argumentsInfo.argv = argumentsInfo.argv + pos - 1;
- argumentsInfo.argc = argumentsInfo.argc - pos + 1;
-
- TRY {
- loadBootstrap();
- } CATCH {
- exc = mvm::Thread::get()->getPendingException();
- } END_CATCH;
-
- if (exc != NULL) {
- jexc = Jnjvm::asJavaException(exc);
- fprintf(stderr, "Exception %s while bootstrapping VM.",
- exc ? UTF8Buffer(JavaObject::getClass(jexc)->name).cString() : " foreign exception");
- } else {
- ClArgumentsInfo& info = argumentsInfo;
-
- if (info.agents.size()) {
- assert(0 && "implement me");
- instrumenter = 0;//createInstrumenter();
- for (std::vector< std::pair<char*, char*> >::iterator i =
- info.agents.begin(), e = info.agents.end(); i!= e; ++i) {
- str = asciizToStr(i->second);
- executePremain(i->first, str, instrumenter);
- }
- }
-
- UserClassArray* array = upcalls->ArrayOfString;
- args = (ArrayObject*)array->doNew(info.argc - 2);
- for (int i = 2; i < info.argc; ++i) {
- ArrayObject::setElement(args, (JavaObject*)asciizToStr(info.argv[i]), i - 2);
- }
-
- executeClass(info.className, args);
- }
-}
-
-Jnjvm::Jnjvm(mvm::BumpPtrAllocator& Alloc, mvm::VMKit* vmkit, JavaCompiler* Comp, bool dlLoad) :
- VirtualMachine(Alloc, vmkit),
- lockSystem(Alloc) {
-
- bootstrapLoader = new(Alloc, "bootstrap loader") JnjvmBootstrapLoader(Alloc, this, Comp);
-
- upcalls = new(allocator, "Classpath") Classpath(bootstrapLoader, dlLoad);
-
- initialiseInternalVTs();
-
- classpath = getenv("CLASSPATH");
- if (!classpath) classpath = ".";
-
- appClassLoader = 0;
- jniEnv = &JNI_JNIEnvTable;
- javavmEnv = &JNI_JavaVMTable;
-
- throwable = upcalls->newThrowable;
-
- StringList* end = bootstrapLoader->strings;
- while (end) {
- for (uint32 i = 0; i < end->length; ++i) {
- JavaString* obj = end->strings[i];
- hashStr.insert(obj);
- }
- end = end->prev;
- }
-
- bootstrapLoader->insertAllMethodsInVM();
-}
-
-Jnjvm::~Jnjvm() {
-}
-
-ArrayUInt16* Jnjvm::asciizToArray(const char* asciiz) {
- ArrayUInt16* tmp = NULL;
- llvm_gcroot(tmp, 0);
-
- uint32 size = strlen(asciiz);
- tmp = (ArrayUInt16*)upcalls->ArrayOfChar->doNew(size);
-
- for (uint32 i = 0; i < size; i++) {
- ArrayUInt16::setElement(tmp, asciiz[i], i);
- }
- return tmp;
-}
-
-void Jnjvm::finalizeObject(mvm::gc* _o) {
- JavaObject *obj = (JavaObject*)_o;
-
- llvm_gcroot(_o, 0);
- llvm_gcroot(obj, 0);
-
- JavaMethod* meth = upcalls->FinalizeObject;
- UserClass* cl = JavaObject::getClass(obj)->asClass();
- meth->invokeIntVirtualBuf(cl, obj, 0);
-}
-
-mvm::gc** Jnjvm::getReferent(mvm::gc* _obj) {
- llvm_gcroot(_obj, 0);
- JavaObjectReference* obj = (JavaObjectReference*)_obj;
- llvm_gcroot(obj, 0);
- return (mvm::gc**)JavaObjectReference::getReferentPtr(obj);
-}
-
-void Jnjvm::setReferent(mvm::gc* _obj, mvm::gc* val) {
- llvm_gcroot(_obj, 0);
- JavaObjectReference* obj = (JavaObjectReference*)_obj;
- llvm_gcroot(obj, 0);
- llvm_gcroot(val, 0);
- JavaObjectReference::setReferent(obj, (JavaObject*)val);
-}
-
-bool Jnjvm::enqueueReference(mvm::gc* _obj) {
- JavaObject* obj = (JavaObject*)_obj;
- llvm_gcroot(obj, 0);
- JavaMethod* meth = upcalls->EnqueueReference;
- UserClass* cl = JavaObject::getClass(obj)->asClass();
- return (bool)meth->invokeIntSpecialBuf(cl, obj, 0);
-}
-
-size_t Jnjvm::getObjectSize(mvm::gc* object) {
- // TODO: because this is called during GC, there is no need to do
- // llvm_gcroot. For clarity, it may be useful to have a special type
- // in this case.
- size_t size = 0;
- JavaObject* src = (JavaObject*)object;
- if (VMClassLoader::isVMClassLoader(this, src)) {
- size = sizeof(VMClassLoader);
- } else {
- CommonClass* cl = JavaObject::getClass(src);
- if (cl->isArray()) {
- UserClassArray* array = cl->asArrayClass();
- UserCommonClass* base = array->baseClass();
- uint32 logSize = base->isPrimitive() ?
- base->asPrimitiveClass()->logSize : (sizeof(JavaObject*) == 8 ? 3 : 2);
-
- size = sizeof(JavaObject) + sizeof(ssize_t) +
- (JavaArray::getSize(src) << logSize);
- } else {
- assert(cl->isClass() && "Not a class!");
- size = cl->asClass()->getVirtualSize();
- }
- }
- return size;
-}
-
-const char* Jnjvm::getObjectTypeName(mvm::gc* object) {
- JavaObject* src = (JavaObject*)object;
- if (VMClassLoader::isVMClassLoader(this, src)) {
- return "VMClassLoader";
- } else {
- CommonClass* cl = JavaObject::getClass(src);
- // This code is only used for debugging on a fatal error. It is fine to
- // allocate in the C++ heap.
- return (new UTF8Buffer(cl->name))->cString();
- }
-}
-
-// Helper function to run J3 without JIT.
-extern "C" int StartJnjvmWithoutJIT(int argc, char** argv, char* mainClass) {
- mvm::BumpPtrAllocator Allocator;
-
- mvm::VMKit* vmkit = new(Allocator, "VMKit") mvm::VMKit(Allocator);
-
- JavaCompiler* Comp = new JavaCompiler();
-
- Jnjvm* vm = new(Allocator, "VM") Jnjvm(Allocator, vmkit, Comp, true);
-
- mvm::ThreadAllocator thallocator;
- char** newArgv = (char**)thallocator.Allocate((argc + 1) * sizeof(char*));
- memcpy(newArgv + 1, argv, argc * sizeof(char*));
- newArgv[0] = newArgv[1];
- newArgv[1] = mainClass;
-
- vm->runApplication(argc + 1, newArgv);
-
- vmkit->waitNonDaemonThreads();
-
- return 0;
-}
diff --git a/vmkit/lib/J3/VMCore/Jnjvm.h b/vmkit/lib/J3/VMCore/Jnjvm.h
deleted file mode 100644
index ed657bc..0000000
--- a/vmkit/lib/J3/VMCore/Jnjvm.h
+++ /dev/null
@@ -1,302 +0,0 @@
-//===---------- Jnjvm.h - Java virtual machine description ---------------===//
-//
-// The VMKit project
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#ifndef JNJVM_JAVA_VM_H
-#define JNJVM_JAVA_VM_H
-
-#include <vector>
-
-#include "types.h"
-
-#include "mvm/Allocator.h"
-#include "mvm/VirtualMachine.h"
-#include "mvm/Threads/Cond.h"
-#include "mvm/Threads/Locks.h"
-#include "mvm/Threads/ObjectLocks.h"
-
-#include "JnjvmConfig.h"
-#include "JNIReferences.h"
-#include "LockedMap.h"
-
-namespace mvm {
- class MutatorThread;
-}
-
-namespace j3 {
-
-class ArrayObject;
-class Classpath;
-class CommonClass;
-class JavaField;
-class JavaMethod;
-class JavaObject;
-class JavaString;
-class JavaThread;
-class JavaVirtualTable;
-class JnjvmBootstrapLoader;
-class JnjvmClassLoader;
-class ReferenceThread;
-class UserClass;
-class UserClassArray;
-class UserClassPrimitive;
-class UserCommonClass;
-
-class ClArgumentsInfo {
-public:
- int argc;
- char** argv;
- uint32 appArgumentsPos;
- char* className;
- char* jarFile;
- std::vector< std::pair<char*, char*> > agents;
-
- void readArgs(Jnjvm *vm);
- void extractClassFromJar(Jnjvm* vm, int argc, char** argv, int i);
- void javaAgent(char* cur);
-
- void printInformation();
- void nyi();
- void printVersion();
-};
-
-/// Jnjvm - A JVM. Each execution of a program allocates a Jnjvm.
-///
-class Jnjvm : public mvm::VirtualMachine {
- friend class JnjvmClassLoader;
-public:
- /// throwable - The java/lang/Throwable class. In an isolate
- /// environment, generated code references this field.
- UserClass* throwable;
-
-private:
-
- virtual size_t getObjectSize(mvm::gc* obj);
- virtual const char* getObjectTypeName(mvm::gc* obj);
-
- /// CreateError - Creates a Java object of the specified exception class
- /// and calling its <init> function.
- ///
- JavaObject* CreateError(UserClass* cl, JavaMethod* meth, const char* str);
- JavaObject* CreateError(UserClass* cl, JavaMethod* meth, JavaString* str);
-
- /// error - Throws an exception in the execution of a JVM for the thread
- /// that calls this functions. This is used internally by Jnjvm to control
- /// which pair class/method are used.
- ///
- void error(UserClass* cl, JavaMethod* meth, JavaString*);
-
- /// errorWithExcp - Throws an exception whose cause is the Java object excp.
- ///
- void errorWithExcp(UserClass* cl, JavaMethod* meth, const JavaObject* excp);
-
- /// loadAppClassLoader - Loads the application class loader, so that VMKit
- /// knowns which loader has to load the main class.
- ///
- JnjvmClassLoader* loadAppClassLoader();
-
- /// executeClass - Executes in the given JVM this main class with the given
- /// Java args.
- ///
- void executeClass(const char* className, ArrayObject* args);
-
- /// executePremain - Executes the premain class for the java/lang/instrument
- /// feature.
- ///
- void executePremain(const char* className, JavaString* args,
- JavaObject* instrumenter);
-
- /// mainJavaStart - Starts the execution of the application in a Java thread.
- ///
- static void mainJavaStart(mvm::Thread* thread);
-
-public:
-
- /// tracer - Traces instances of this class.
- ///
- virtual void tracer(uintptr_t closure);
-
- /// dirSeparator - Directory separator for file paths, e.g. '\' for windows,
- /// '/' for Unix.
- ///
- static const char* dirSeparator;
-
- /// envSeparator - Paths separator for environment variables, e.g. ':'.
- ///
- static const char* envSeparator;
-
- /// Magic - The magic number at the beginning of each .class file. 0xcafebabe.
- ///
- static const unsigned int Magic;
-
- /// bootstraLoader - Bootstrap loader for base classes of this virtual
- /// machine.
- ///
- JnjvmBootstrapLoader* bootstrapLoader;
-
- /// upcalls - Upcalls to call Java methods and access Java fields.
- ///
- Classpath* upcalls;
-
- /// lockSystem - The lock system to allocate and manage Java locks.
- ///
- mvm::LockSystem lockSystem;
-
- /// argumentsInfo - The command line arguments given to the vm
- ///
- ClArgumentsInfo argumentsInfo;
-
- /// jniEnv - The JNI environment of this JVM.
- ///
- void* jniEnv;
-
- /// javavmEnv - The Java VM environment of this JVM.
- ///
- const void* javavmEnv;
-
- /// postProperties - Properties set at runtime and in command line.
- ///
- std::vector< std::pair<char*, char*> > postProperties;
-
- /// classpath - The CLASSPATH value, or the paths given in command line.
- ///
- const char* classpath;
-
- /// globalRefs - Global references that JNI wants to protect.
- ///
- JNIGlobalReferences globalRefs;
-
- /// globalRefsLock - Lock for adding a new global reference.
- ///
- mvm::LockNormal globalRefsLock;
-
- /// appClassLoader - The bootstrap class loader.
- ///
- JnjvmClassLoader* appClassLoader;
-
- /// hashStr - Hash map of java/lang/String objects allocated by this JVM.
- ///
- StringMap hashStr;
-
- mvm::VirtualTable* VMClassLoader__VT;
-
- void initialiseInternalVTs();
-public:
-
- /// CreateExceptions - These are the runtime exceptions thrown by Java code
- /// compiled by VMKit.
- ///
- JavaObject* CreateNullPointerException();
- JavaObject* CreateOutOfMemoryError();
- JavaObject* CreateIndexOutOfBoundsException(sint32 entry);
- JavaObject* CreateNegativeArraySizeException();
- JavaObject* CreateClassCastException(JavaObject* obj, UserCommonClass* cl);
- JavaObject* CreateArithmeticException();
- JavaObject* CreateStackOverflowError();
- JavaObject* CreateLinkageError(const char* msg);
- JavaObject* CreateArrayStoreException(JavaVirtualTable* VT);
- JavaObject* CreateUnsatisfiedLinkError(JavaMethod* meth);
-
- /// Exceptions - These are the only exceptions VMKit will make.
- ///
- void arrayStoreException();
- void indexOutOfBounds(const JavaObject* obj, sint32 entry);
- void negativeArraySizeException(int size);
- void nullPointerException();
- void illegalAccessException(const char* msg);
- void illegalMonitorStateException(const JavaObject* obj);
- void interruptedException(const JavaObject* obj);
- void initializerError(const JavaObject* excp);
- void invocationTargetException(const JavaObject* obj);
- void outOfMemoryError();
- void noClassDefFoundError(JavaObject* obj);
- void instantiationException(UserCommonClass* cl);
- void instantiationError(UserCommonClass* cl);
- void illegalArgumentException(const char* msg);
- void classCastException(JavaObject* obj, UserCommonClass* cl);
- void noSuchFieldError(CommonClass* cl, const UTF8* name);
- void noSuchMethodError(CommonClass* cl, const UTF8* name);
- void abstractMethodError(CommonClass* cl, const UTF8* name);
- void noClassDefFoundError(const UTF8* name);
- void classNotFoundException(JavaString* str);
- void noClassDefFoundError(UserClass* cl, const UTF8* name);
- void classFormatError(const char* str);
-
- /// asciizToStr - Constructs a java/lang/String object from the given asciiz.
- ///
- JavaString* asciizToStr(const char* asciiz);
-
- /// UTF8ToStr - Constructs a java/lang/String object from the given UTF8.
- ///
- JavaString* constructString(const ArrayUInt16* array);
-
- /// UTF8ToStr - Constructs a java/lang/String object from the given internal
- /// UTF8, thus duplicating the UTF8.
- ///
- JavaString* internalUTF8ToStr(const UTF8* utf8);
-
- /// asciizToUTF8 - Constructs an UTF8 out of the asciiz.
- ///
- ArrayUInt16* asciizToArray(const char* asciiz);
-
- /// finalizeObject - invoke the finalizer of a java object
- ///
- virtual void finalizeObject(mvm::gc* obj);
-
- /// getReferentPtr - return the referent of a reference
- ///
- virtual mvm::gc** getReferent(mvm::gc* ref);
-
- /// setReferentPtr - set the referent of a reference
- ///
- virtual void setReferent(mvm::gc* ref, mvm::gc* val);
-
- /// enqueueReference - enqueue the reference
- ///
- virtual bool enqueueReference(mvm::gc* _obj);
-
- /// ~Jnjvm - Destroy the JVM.
- ///
- ~Jnjvm();
-
- /// addProperty - Adds a new property in the postProperties map.
- ///
- void addProperty(char* key, char* value);
-
- /// setClasspath - Sets the application classpath for the JVM.
- ///
- void setClasspath(char* cp) {
- classpath = cp;
- }
-
- /// Jnjvm - Allocates a new JVM.
- ///
- Jnjvm(mvm::BumpPtrAllocator& Alloc, mvm::VMKit* vmkit, JavaCompiler* Comp, bool dlLoad);
-
- /// runApplicationImpl - function executed in a thread after a call to runApplication
- ///
- virtual void runApplicationImpl(int argc, char** argv);
-
- /// buildVMThreadData - allocate a java thread for the underlying mutator. Called when the java thread is a foreign thread.
- ///
- virtual mvm::VMThreadData* buildVMThreadData(mvm::Thread* mut);
-
- /// loadBootstrap - Bootstraps the JVM, getting the class loader, initializing
- /// bootstrap classes (e.g. java/lang/Class, java/lang/Exception) and
- /// mapping the initial thread.
- ///
- void loadBootstrap();
-
- // asjavaException - convert from gc to JavaObject. Will be used to identify the points
- // where we must test the original vm of the exception
- static JavaObject* asJavaException(mvm::gc* o) { llvm_gcroot(o, 0); return (JavaObject*)o; }
-};
-
-} // end namespace j3
-
-#endif
diff --git a/vmkit/lib/J3/VMCore/JnjvmClassLoader.cpp b/vmkit/lib/J3/VMCore/JnjvmClassLoader.cpp
deleted file mode 100644
index 7ef0877..0000000
--- a/vmkit/lib/J3/VMCore/JnjvmClassLoader.cpp
+++ /dev/null
@@ -1,1068 +0,0 @@
-//===-- JnjvmClassLoader.cpp - Jnjvm representation of a class loader ------===//
-//
-// The VMKit project
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#include <climits>
-#include <cstdlib>
-
-// for strrchr
-#include <cstring>
-
-// for dlopen and dlsym
-#include <dlfcn.h>
-
-// for stat, S_IFMT and S_IFDIR
-#include <sys/types.h>
-#include <sys/stat.h>
-#include <unistd.h>
-
-#include <string>
-
-#include "debug.h"
-#include "mvm/Allocator.h"
-#include "mvm/VMKit.h"
-
-#include "Classpath.h"
-#include "ClasspathReflect.h"
-#include "JavaClass.h"
-#include "JavaCompiler.h"
-#include "JavaConstantPool.h"
-#include "JavaString.h"
-#include "JavaThread.h"
-#include "JavaTypes.h"
-#include "JavaUpcalls.h"
-#include "Jnjvm.h"
-#include "JnjvmClassLoader.h"
-#include "LockedMap.h"
-#include "Reader.h"
-#include "Zip.h"
-
-using namespace j3;
-
-typedef void (*static_init_t)(JnjvmClassLoader*);
-
-JnjvmBootstrapLoader::JnjvmBootstrapLoader(mvm::BumpPtrAllocator& Alloc,
- Jnjvm* vm,
- JavaCompiler* Comp) :
- JnjvmClassLoader(Alloc, vm) {
-
- TheCompiler = Comp;
-
- hashUTF8 = new(allocator, "UTF8Map") UTF8Map(allocator);
- classes = new(allocator, "ClassMap") ClassMap();
- javaTypes = new(allocator, "TypeMap") TypeMap();
- javaSignatures = new(allocator, "SignMap") SignMap();
- strings = new(allocator, "StringList") StringList();
-
- bootClasspathEnv = getenv("JNJVM_BOOTCLASSPATH");
- if (!bootClasspathEnv) {
- bootClasspathEnv = GNUClasspathGlibj;
- }
-
- libClasspathEnv = getenv("JNJVM_LIBCLASSPATH");
- if (!libClasspathEnv) {
- libClasspathEnv = GNUClasspathLibs;
- }
-}
-
-JnjvmClassLoader::JnjvmClassLoader(mvm::BumpPtrAllocator& Alloc,
- JavaObject* loader,
- VMClassLoader* vmdata,
- Jnjvm* v) : allocator(Alloc) {
- llvm_gcroot(loader, 0);
- llvm_gcroot(vmdata, 0);
-
- vm = v;
-
- TheCompiler = vm->bootstrapLoader->getCompiler()->Create("Applicative loader");
-
- hashUTF8 = new(allocator, "UTF8Map") UTF8Map(allocator);
- classes = new(allocator, "ClassMap") ClassMap();
- javaTypes = new(allocator, "TypeMap") TypeMap();
- javaSignatures = new(allocator, "SignMap") SignMap();
- strings = new(allocator, "StringList") StringList();
-
- vmdata->JCL = this;
- javaLoader = loader;
-
- JavaMethod* meth = vm->upcalls->loadInClassLoader;
- loadClassMethod =
- JavaObject::getClass(loader)->asClass()->lookupMethodDontThrow(
- meth->name, meth->type, false, true, &loadClass);
- assert(loadClass && "Loader does not have a loadClass function");
-}
-
-void JnjvmClassLoader::setCompiler(JavaCompiler* Comp) {
- // Set the new compiler.
- TheCompiler = Comp;
-}
-
-ClassBytes* JnjvmBootstrapLoader::openName(const UTF8* utf8) {
- ClassBytes* res = 0;
- mvm::ThreadAllocator threadAllocator;
-
- char* asciiz = (char*)threadAllocator.Allocate(utf8->size + 1);
- for (sint32 i = 0; i < utf8->size; ++i)
- asciiz[i] = utf8->elements[i];
- asciiz[utf8->size] = 0;
-
- uint32 alen = utf8->size;
-
- for (std::vector<const char*>::iterator i = bootClasspath.begin(),
- e = bootClasspath.end(); i != e; ++i) {
- const char* str = *i;
- unsigned int strLen = strlen(str);
- char* buf = (char*)threadAllocator.Allocate(strLen + alen + 7);
-
- sprintf(buf, "%s%s.class", str, asciiz);
- res = Reader::openFile(this, buf);
- if (res) return res;
- }
-
- for (std::vector<ZipArchive*>::iterator i = bootArchives.begin(),
- e = bootArchives.end(); i != e; ++i) {
-
- ZipArchive* archive = *i;
- char* buf = (char*)threadAllocator.Allocate(alen + 7);
- sprintf(buf, "%s.class", asciiz);
- res = Reader::openZip(this, archive, buf);
- if (res) return res;
- }
-
- return 0;
-}
-
-
-UserClass* JnjvmBootstrapLoader::internalLoad(const UTF8* name,
- bool doResolve,
- JavaString* strName) {
- ClassBytes* bytes = NULL;
- llvm_gcroot(strName, 0);
-
- UserCommonClass* cl = lookupClass(name);
-
- if (!cl) {
- bytes = openName(name);
- if (bytes != NULL) {
- cl = constructClass(name, bytes);
- }
- }
-
- if (cl) {
- assert(!cl->isArray());
- if (doResolve) cl->asClass()->resolveClass();
- }
-
- return (UserClass*)cl;
-}
-
-UserClass* JnjvmClassLoader::internalLoad(const UTF8* name, bool doResolve,
- JavaString* strName) {
- JavaObject* obj = 0;
- llvm_gcroot(strName, 0);
- llvm_gcroot(obj, 0);
-
- UserCommonClass* cl = lookupClass(name);
-
- if (!cl) {
- UserClass* forCtp = loadClass;
- if (strName == NULL) {
- strName = JavaString::internalToJava(name, vm);
- }
- obj = loadClassMethod->invokeJavaObjectVirtual(forCtp, javaLoader,
- &strName);
- cl = JavaObjectClass::getClass(((JavaObjectClass*)obj));
- }
-
- if (cl) {
- assert(!cl->isArray());
- if (doResolve) cl->asClass()->resolveClass();
- }
-
- return (UserClass*)cl;
-}
-
-UserClass* JnjvmClassLoader::loadName(const UTF8* name, bool doResolve,
- bool doThrow, JavaString* strName) {
-
- llvm_gcroot(strName, 0);
-
- UserClass* cl = internalLoad(name, doResolve, strName);
-
- if (!cl && doThrow) {
- if (name->equals(vm->upcalls->NoClassDefFoundErrorName)) {
- fprintf(stderr, "Unable to load NoClassDefFoundError");
- abort();
- }
- if (TheCompiler->isStaticCompiling()) {
- fprintf(stderr, "Could not find %s, needed for static compiling\n",
- UTF8Buffer(name).cString());
- abort();
- }
- vm->noClassDefFoundError(name);
- }
-
- if (cl && cl->classLoader != this) {
- classes->lock.lock();
- ClassMap::iterator End = classes->map.end();
- ClassMap::iterator I = classes->map.find(cl->name);
- if (I == End)
- classes->map.insert(std::make_pair(cl->name, cl));
- classes->lock.unlock();
- }
-
- return cl;
-}
-
-
-const UTF8* JnjvmClassLoader::lookupComponentName(const UTF8* name,
- UTF8* holder,
- bool& prim) {
- uint32 len = name->size;
- uint32 start = 0;
- uint32 origLen = len;
-
- while (true) {
- --len;
- if (len == 0) {
- return 0;
- } else {
- ++start;
- if (name->elements[start] != I_TAB) {
- if (name->elements[start] == I_REF) {
- uint32 size = (uint32)name->size;
- if ((size == (start + 1)) || (size == (start + 2)) ||
- (name->elements[start + 1] == I_TAB) ||
- (name->elements[origLen - 1] != I_END_REF)) {
- return 0;
- } else {
- const uint16* buf = &(name->elements[start + 1]);
- uint32 bufLen = len - 2;
- const UTF8* componentName = hashUTF8->lookupReader(buf, bufLen);
- if (!componentName && holder) {
- holder->size = len - 2;
- for (uint32 i = 0; i < len - 2; ++i) {
- holder->elements[i] = name->elements[start + 1 + i];
- }
- componentName = holder;
- }
- return componentName;
- }
- } else {
- uint16 cur = name->elements[start];
- if ((cur == I_BOOL || cur == I_BYTE ||
- cur == I_CHAR || cur == I_SHORT ||
- cur == I_INT || cur == I_FLOAT ||
- cur == I_DOUBLE || cur == I_LONG)
- && ((uint32)name->size) == start + 1) {
- prim = true;
- }
- return 0;
- }
- }
- }
- }
-
- return 0;
-}
-
-UserCommonClass* JnjvmClassLoader::lookupClassOrArray(const UTF8* name) {
- UserCommonClass* temp = lookupClass(name);
- if (temp) return temp;
-
- if (this != vm->bootstrapLoader) {
- temp = vm->bootstrapLoader->lookupClassOrArray(name);
- if (temp) return temp;
- }
-
-
- if (name->elements[0] == I_TAB) {
- bool prim = false;
- const UTF8* componentName = lookupComponentName(name, 0, prim);
- if (prim) return constructArray(name);
- if (componentName) {
- UserCommonClass* temp = lookupClass(componentName);
- if (temp) return constructArray(name);
- }
- }
-
- return 0;
-}
-
-UserCommonClass* JnjvmClassLoader::loadClassFromUserUTF8(const UTF8* name,
- bool doResolve,
- bool doThrow,
- JavaString* strName) {
- llvm_gcroot(strName, 0);
-
- if (name->size == 0) {
- return 0;
- } else if (name->elements[0] == I_TAB) {
- mvm::ThreadAllocator threadAllocator;
- bool prim = false;
- UTF8* holder = (UTF8*)threadAllocator.Allocate(
- sizeof(UTF8) + name->size * sizeof(uint16));
- if (!holder) return 0;
-
- const UTF8* componentName = lookupComponentName(name, holder, prim);
- if (prim) return constructArray(name);
- if (componentName) {
- UserCommonClass* temp = loadName(componentName, doResolve, doThrow, NULL);
- if (temp) return constructArray(name);
- }
- } else {
- return loadName(name, doResolve, doThrow, strName);
- }
-
- return NULL;
-}
-
-UserCommonClass* JnjvmClassLoader::loadClassFromAsciiz(const char* asciiz,
- bool doResolve,
- bool doThrow) {
- const UTF8* name = hashUTF8->lookupAsciiz(asciiz);
- mvm::ThreadAllocator threadAllocator;
- UserCommonClass* result = NULL;
- if (!name) name = vm->bootstrapLoader->hashUTF8->lookupAsciiz(asciiz);
- if (!name) {
- uint32 size = strlen(asciiz);
- UTF8* temp = (UTF8*)threadAllocator.Allocate(
- sizeof(UTF8) + size * sizeof(uint16));
- temp->size = size;
-
- for (uint32 i = 0; i < size; ++i) {
- temp->elements[i] = asciiz[i];
- }
- name = temp;
- }
-
- result = lookupClass(name);
- if ((result == NULL) && (this != vm->bootstrapLoader)) {
- result = vm->bootstrapLoader->lookupClassOrArray(name);
- if (result != NULL) {
- if (result->isClass() && doResolve) {
- result->asClass()->resolveClass();
- }
- return result;
- }
- }
-
- return loadClassFromUserUTF8(name, doResolve, doThrow, NULL);
-}
-
-
-UserCommonClass*
-JnjvmClassLoader::loadClassFromJavaString(JavaString* str, bool doResolve,
- bool doThrow) {
-
- llvm_gcroot(str, 0);
- mvm::ThreadAllocator allocator;
- UTF8* name = (UTF8*)allocator.Allocate(sizeof(UTF8) + str->count * sizeof(uint16));
-
- name->size = str->count;
- if (ArrayUInt16::getElement(JavaString::getValue(str), str->offset) != I_TAB) {
- for (sint32 i = 0; i < str->count; ++i) {
- uint16 cur = ArrayUInt16::getElement(JavaString::getValue(str), str->offset + i);
- if (cur == '.') name->elements[i] = '/';
- else if (cur == '/') {
- return 0;
- }
- else name->elements[i] = cur;
- }
- } else {
- for (sint32 i = 0; i < str->count; ++i) {
- uint16 cur = ArrayUInt16::getElement(JavaString::getValue(str), str->offset + i);
- if (cur == '.') {
- name->elements[i] = '/';
- } else if (cur == '/') {
- return 0;
- } else {
- name->elements[i] = cur;
- }
- }
- }
-
- UserCommonClass* cls = loadClassFromUserUTF8(name, doResolve, doThrow, str);
- return cls;
-}
-
-UserCommonClass* JnjvmClassLoader::lookupClassFromJavaString(JavaString* str) {
-
- const ArrayUInt16* value = NULL;
- llvm_gcroot(str, 0);
- llvm_gcroot(value, 0);
- value = JavaString::getValue(str);
- mvm::ThreadAllocator allocator;
-
- UTF8* name = (UTF8*)allocator.Allocate(sizeof(UTF8) + str->count * sizeof(uint16));
- name->size = str->count;
- for (sint32 i = 0; i < str->count; ++i) {
- uint16 cur = ArrayUInt16::getElement(value, str->offset + i);
- if (cur == '.') name->elements[i] = '/';
- else name->elements[i] = cur;
- }
- UserCommonClass* cls = lookupClass(name);
- return cls;
-}
-
-UserCommonClass* JnjvmClassLoader::lookupClass(const UTF8* utf8) {
- return classes->lookup(utf8);
-}
-
-UserCommonClass* JnjvmClassLoader::loadBaseClass(const UTF8* name,
- uint32 start, uint32 len) {
-
- if (name->elements[start] == I_TAB) {
- UserCommonClass* baseClass = loadBaseClass(name, start + 1, len - 1);
- JnjvmClassLoader* loader = baseClass->classLoader;
- const UTF8* arrayName = name->extract(loader->hashUTF8, start, start + len);
- return loader->constructArray(arrayName, baseClass);
- } else if (name->elements[start] == I_REF) {
- const UTF8* componentName = name->extract(hashUTF8,
- start + 1, start + len - 1);
- UserCommonClass* cl = loadName(componentName, false, true, NULL);
- return cl;
- } else {
- Classpath* upcalls = vm->upcalls;
- UserClassPrimitive* prim =
- UserClassPrimitive::byteIdToPrimitive(name->elements[start], upcalls);
- assert(prim && "No primitive found");
- return prim;
- }
-}
-
-
-UserClassArray* JnjvmClassLoader::constructArray(const UTF8* name) {
- ClassArray* res = (ClassArray*)lookupClass(name);
- if (res) return res;
-
- UserCommonClass* cl = loadBaseClass(name, 1, name->size - 1);
- assert(cl && "no base class for an array");
- JnjvmClassLoader* ld = cl->classLoader;
- res = ld->constructArray(name, cl);
-
- if (res && res->classLoader != this) {
- classes->lock.lock();
- ClassMap::iterator End = classes->map.end();
- ClassMap::iterator I = classes->map.find(res->name);
- if (I == End)
- classes->map.insert(std::make_pair(res->name, res));
- classes->lock.unlock();
- }
- return res;
-}
-
-UserClass* JnjvmClassLoader::constructClass(const UTF8* name,
- ClassBytes* bytes) {
- mvm::gc* excp = NULL;
- llvm_gcroot(excp, 0);
- UserClass* res = NULL;
- lock.lock();
- classes->lock.lock();
- ClassMap::iterator End = classes->map.end();
- ClassMap::iterator I = classes->map.find(name);
- classes->lock.unlock();
- if (I != End) {
- res = ((UserClass*)(I->second));
- } else {
- TRY {
- const UTF8* internalName = readerConstructUTF8(name->elements, name->size);
- res = new(allocator, "Class") UserClass(this, internalName, bytes);
- res->readClass();
- res->makeVT();
- getCompiler()->resolveVirtualClass(res);
- getCompiler()->resolveStaticClass(res);
- classes->lock.lock();
- assert(res->getDelegatee() == NULL);
- assert(res->getStaticInstance() == NULL);
- bool success = classes->map.insert(std::make_pair(internalName, res)).second;
- classes->lock.unlock();
- assert(success && "Could not add class in map");
- } CATCH {
- mvm::Thread* mut = mvm::Thread::get();
- excp = mut->getPendingException();
- mut->clearPendingException();
- } END_CATCH;
- }
- if (excp != NULL) {
- mvm::Thread::get()->setPendingException(excp)->throwIt();
- }
- lock.unlock();
-
- if (res->super == NULL) {
- // java.lang.Object just got created, initialise VTs of arrays.
- ClassArray::initialiseVT(res);
- }
- return res;
-}
-
-UserClassArray* JnjvmClassLoader::constructArray(const UTF8* name,
- UserCommonClass* baseClass) {
- assert(baseClass && "constructing an array class without a base class");
- assert(baseClass->classLoader == this &&
- "constructing an array with wrong loader");
- classes->lock.lock();
- ClassMap::iterator End = classes->map.end();
- ClassMap::iterator I = classes->map.find(name);
- UserClassArray* res = 0;
- if (I == End) {
- const UTF8* internalName = readerConstructUTF8(name->elements, name->size);
- res = new(allocator, "Array class") UserClassArray(this, internalName,
- baseClass);
- classes->map.insert(std::make_pair(internalName, res));
- } else {
- res = ((UserClassArray*)(I->second));
- }
- classes->lock.unlock();
- return res;
-}
-
-Typedef* JnjvmClassLoader::internalConstructType(const UTF8* name) {
- short int cur = name->elements[0];
- Typedef* res = 0;
- switch (cur) {
- case I_TAB :
- res = new(allocator, "ArrayTypedef") ArrayTypedef(name);
- break;
- case I_REF :
- res = new(allocator, "ObjectTypedef") ObjectTypedef(name, hashUTF8);
- break;
- default :
- UserClassPrimitive* cl =
- vm->upcalls->getPrimitiveClass((char)name->elements[0]);
- assert(cl && "No primitive");
- bool unsign = (cl == vm->upcalls->OfChar ||
- cl == vm->upcalls->OfBool);
- res = new(allocator, "PrimitiveTypedef") PrimitiveTypedef(name, cl,
- unsign, cur);
- }
- return res;
-}
-
-
-Typedef* JnjvmClassLoader::constructType(const UTF8* name) {
- javaTypes->lock.lock();
- Typedef* res = javaTypes->lookup(name);
- if (res == 0) {
- res = internalConstructType(name);
- javaTypes->hash(name, res);
- }
- javaTypes->lock.unlock();
- return res;
-}
-
-static void typeError(const UTF8* name, short int l) {
- if (l != 0) {
- fprintf(stderr, "wrong type %d in %s", l, UTF8Buffer(name).cString());
- } else {
- fprintf(stderr, "wrong type %s", UTF8Buffer(name).cString());
- }
- abort();
-}
-
-
-static bool analyseIntern(const UTF8* name, uint32 pos, uint32 meth,
- uint32& ret) {
- short int cur = name->elements[pos];
- switch (cur) {
- case I_PARD :
- ret = pos + 1;
- return true;
- case I_BOOL :
- ret = pos + 1;
- return false;
- case I_BYTE :
- ret = pos + 1;
- return false;
- case I_CHAR :
- ret = pos + 1;
- return false;
- case I_SHORT :
- ret = pos + 1;
- return false;
- case I_INT :
- ret = pos + 1;
- return false;
- case I_FLOAT :
- ret = pos + 1;
- return false;
- case I_DOUBLE :
- ret = pos + 1;
- return false;
- case I_LONG :
- ret = pos + 1;
- return false;
- case I_VOID :
- ret = pos + 1;
- return false;
- case I_TAB :
- if (meth == 1) {
- pos++;
- } else {
- while (name->elements[++pos] == I_TAB) {}
- analyseIntern(name, pos, 1, pos);
- }
- ret = pos;
- return false;
- case I_REF :
- if (meth != 2) {
- while (name->elements[++pos] != I_END_REF) {}
- }
- ret = pos + 1;
- return false;
- default :
- typeError(name, cur);
- }
- return false;
-}
-
-Signdef* JnjvmClassLoader::constructSign(const UTF8* name) {
- javaSignatures->lock.lock();
- Signdef* res = javaSignatures->lookup(name);
- if (res == 0) {
- std::vector<Typedef*> buf;
- uint32 len = (uint32)name->size;
- uint32 pos = 1;
- uint32 pred = 0;
-
- while (pos < len) {
- pred = pos;
- bool end = analyseIntern(name, pos, 0, pos);
- if (end) break;
- else {
- buf.push_back(constructType(name->extract(hashUTF8, pred, pos)));
- }
- }
-
- if (pos == len) {
- typeError(name, 0);
- }
-
- analyseIntern(name, pos, 0, pred);
-
- if (pred != len) {
- typeError(name, 0);
- }
-
- Typedef* ret = constructType(name->extract(hashUTF8, pos, pred));
-
- res = new(allocator, buf.size()) Signdef(name, this, buf, ret);
-
- javaSignatures->hash(name, res);
- }
- javaSignatures->lock.unlock();
- return res;
-}
-
-
-JnjvmClassLoader*
-JnjvmClassLoader::getJnjvmLoaderFromJavaObject(JavaObject* jloader, Jnjvm* vm) {
-
- VMClassLoader* vmdata = 0;
-
- llvm_gcroot(jloader, 0);
- llvm_gcroot(vmdata, 0);
-
- if (jloader == NULL) return vm->bootstrapLoader;
-
- JnjvmClassLoader* JCL = 0;
- Classpath* upcalls = vm->upcalls;
- vmdata =
- (VMClassLoader*)(upcalls->vmdataClassLoader->getInstanceObjectField(jloader));
-
- if (vmdata == NULL) {
- JavaObject::acquire(jloader);
- vmdata =
- (VMClassLoader*)(upcalls->vmdataClassLoader->getInstanceObjectField(jloader));
- if (!vmdata) {
- vmdata = VMClassLoader::allocate(vm);
- mvm::BumpPtrAllocator* A = new mvm::BumpPtrAllocator();
- JCL = new(*A, "Class loader") JnjvmClassLoader(*A, jloader, vmdata, vm);
- upcalls->vmdataClassLoader->setInstanceObjectField(jloader, (JavaObject*)vmdata);
- }
- JavaObject::release(jloader);
- } else {
- JCL = vmdata->getClassLoader();
- assert(JCL->javaLoader == jloader);
- }
-
- return JCL;
-}
-
-const UTF8* JnjvmClassLoader::asciizConstructUTF8(const char* asciiz) {
- return hashUTF8->lookupOrCreateAsciiz(asciiz);
-}
-
-const UTF8* JnjvmClassLoader::readerConstructUTF8(const uint16* buf,
- uint32 size) {
- return hashUTF8->lookupOrCreateReader(buf, size);
-}
-
-JnjvmClassLoader::~JnjvmClassLoader() {
-
- mvm::Thread::get()->vmkit->removeMethodInfos(TheCompiler);
-
- if (classes) {
- classes->~ClassMap();
- allocator.Deallocate(classes);
- }
-
- if (hashUTF8) {
- hashUTF8->~UTF8Map();
- allocator.Deallocate(hashUTF8);
- }
-
- if (javaTypes) {
- javaTypes->~TypeMap();
- allocator.Deallocate(javaTypes);
- }
-
- if (javaSignatures) {
- javaSignatures->~SignMap();
- allocator.Deallocate(javaSignatures);
- }
-
- for (std::vector<void*>::iterator i = nativeLibs.begin();
- i < nativeLibs.end(); ++i) {
- dlclose(*i);
- }
-
- delete TheCompiler;
-
- // Don't delete the allocator. The caller of this method must
- // delete it after the current object is deleted.
-}
-
-
-JnjvmBootstrapLoader::~JnjvmBootstrapLoader() {
-}
-
-JavaString** JnjvmClassLoader::UTF8ToStr(const UTF8* val) {
- JavaString* res = NULL;
- llvm_gcroot(res, 0);
- res = vm->internalUTF8ToStr(val);
- return strings->addString(this, res);
-}
-
-void JnjvmBootstrapLoader::analyseClasspathEnv(const char* str) {
- ClassBytes* bytes = NULL;
- mvm::ThreadAllocator threadAllocator;
- if (str != 0) {
- unsigned int len = strlen(str);
- char* buf = (char*)threadAllocator.Allocate((len + 1) * sizeof(char));
- const char* cur = str;
- int top = 0;
- char c = 1;
- while (c != 0) {
- while (((c = cur[top]) != 0) && c != Jnjvm::envSeparator[0]) {
- top++;
- }
- if (top != 0) {
- memcpy(buf, cur, top);
- buf[top] = 0;
- char* rp = (char*)threadAllocator.Allocate(PATH_MAX);
- memset(rp, 0, PATH_MAX);
- rp = realpath(buf, rp);
- if (rp && rp[PATH_MAX - 1] == 0 && strlen(rp) != 0) {
- struct stat st;
- stat(rp, &st);
- if ((st.st_mode & S_IFMT) == S_IFDIR) {
- unsigned int len = strlen(rp);
- char* temp = (char*)allocator.Allocate(len + 2, "Boot classpath");
- memcpy(temp, rp, len);
- temp[len] = Jnjvm::dirSeparator[0];
- temp[len + 1] = 0;
- bootClasspath.push_back(temp);
- } else {
- bytes = Reader::openFile(this, rp);
- if (bytes) {
- ZipArchive *archive = new(allocator, "ZipArchive")
- ZipArchive(bytes, allocator);
- if (archive) {
- bootArchives.push_back(archive);
- }
- }
- }
- }
- }
- cur = cur + top + 1;
- top = 0;
- }
- }
-}
-
-// constructArrayName can allocate the UTF8 directly in the classloader
-// memory because it is called by safe places, ie only valid names are
-// created.
-const UTF8* JnjvmClassLoader::constructArrayName(uint32 steps,
- const UTF8* className) {
- uint32 len = className->size;
- uint32 pos = steps;
- bool isTab = (className->elements[0] == I_TAB ? true : false);
- uint32 n = steps + len + (isTab ? 0 : 2);
- mvm::ThreadAllocator allocator;
- uint16* buf = (uint16*)allocator.Allocate(n * sizeof(uint16));
-
- for (uint32 i = 0; i < steps; i++) {
- buf[i] = I_TAB;
- }
-
- if (!isTab) {
- ++pos;
- buf[steps] = I_REF;
- }
-
- for (uint32 i = 0; i < len; i++) {
- buf[pos + i] = className->elements[i];
- }
-
- if (!isTab) {
- buf[n - 1] = I_END_REF;
- }
-
- const UTF8* res = readerConstructUTF8(buf, n);
- return res;
-}
-
-intptr_t JnjvmClassLoader::loadInLib(const char* buf, bool& j3) {
- uintptr_t res = (uintptr_t)TheCompiler->loadMethod(SELF_HANDLE, buf);
-
- if (!res) {
- for (std::vector<void*>::iterator i = nativeLibs.begin(),
- e = nativeLibs.end(); i!= e; ++i) {
- res = (uintptr_t)TheCompiler->loadMethod((*i), buf);
- if (res) break;
- }
- } else {
- j3 = true;
- }
-
- if (!res && this != vm->bootstrapLoader)
- res = vm->bootstrapLoader->loadInLib(buf, j3);
-
- return (intptr_t)res;
-}
-
-void* JnjvmClassLoader::loadLib(const char* buf) {
- void* handle = dlopen(buf, RTLD_LAZY | RTLD_LOCAL);
- if (handle) nativeLibs.push_back(handle);
- return handle;
-}
-
-intptr_t JnjvmClassLoader::loadInLib(const char* name, void* handle) {
- return (intptr_t)TheCompiler->loadMethod(handle, name);
-}
-
-intptr_t JnjvmClassLoader::nativeLookup(JavaMethod* meth, bool& j3,
- char* buf) {
-
- meth->jniConsFromMeth(buf);
- intptr_t res = loadInLib(buf, j3);
- if (!res) {
- meth->jniConsFromMethOverloaded(buf);
- res = loadInLib(buf, j3);
- }
- return res;
-}
-
-class JavaStaticMethodInfo : public mvm::CamlMethodInfo {
-public:
- virtual void print(void* ip, void* addr);
- virtual bool isHighLevelMethod() {
- return true;
- }
-
- JavaStaticMethodInfo(mvm::CamlMethodInfo* super, void* ip, JavaMethod* M) :
- mvm::CamlMethodInfo(super->CF) {
- MetaInfo = M;
- Owner = M->classDef->classLoader->getCompiler();
- }
-};
-
-void JavaStaticMethodInfo::print(void* ip, void* addr) {
- void* new_ip = NULL;
- if (ip) new_ip = mvm::MethodInfo::isStub(ip, addr);
- JavaMethod* meth = (JavaMethod*)MetaInfo;
- fprintf(stderr, "; %p in %s.%s", new_ip,
- UTF8Buffer(meth->classDef->name).cString(),
- UTF8Buffer(meth->name).cString());
- if (ip != new_ip) fprintf(stderr, " (from stub)");
- fprintf(stderr, "\n");
-}
-
-void JnjvmClassLoader::insertAllMethodsInVM() {
- for (ClassMap::iterator i = classes->map.begin(), e = classes->map.end();
- i != e; ++i) {
- CommonClass* cl = i->second;
- if (cl->isClass()) {
- Class* C = cl->asClass();
-
- for (uint32 i = 0; i < C->nbVirtualMethods; ++i) {
- JavaMethod& meth = C->virtualMethods[i];
- if (!isAbstract(meth.access) && meth.code) {
- JavaStaticMethodInfo* MI = new (allocator, "JavaStaticMethodInfo")
- JavaStaticMethodInfo(0, meth.code, &meth);
- vm->vmkit->FunctionsCache.addMethodInfo(MI, meth.code);
- }
- }
-
- for (uint32 i = 0; i < C->nbStaticMethods; ++i) {
- JavaMethod& meth = C->staticMethods[i];
- if (!isAbstract(meth.access) && meth.code) {
- JavaStaticMethodInfo* MI = new (allocator, "JavaStaticMethodInfo")
- JavaStaticMethodInfo(0, meth.code, &meth);
- vm->vmkit->FunctionsCache.addMethodInfo(MI, meth.code);
- }
- }
- }
- }
-}
-
-void JnjvmClassLoader::loadLibFromJar(const char* name,
- const char* file) {
-
- mvm::ThreadAllocator threadAllocator;
- char* soName = (char*)threadAllocator.Allocate(
- strlen(name) + strlen(DYLD_EXTENSION));
- const char* ptr = strrchr(name, '/');
- sprintf(soName, "%s%s", ptr ? ptr + 1 : name, DYLD_EXTENSION);
- void* handle = dlopen(soName, RTLD_LAZY | RTLD_LOCAL);
- if (handle) {
- Class* cl = (Class*)dlsym(handle, file);
- if (cl) {
- static_init_t init = (static_init_t)(uintptr_t)cl->classLoader;
- assert(init && "Loaded the wrong library");
- init(this);
- insertAllMethodsInVM();
- }
- }
-}
-
-void JnjvmClassLoader::loadLibFromFile(const char* name) {
- mvm::ThreadAllocator threadAllocator;
- assert(classes->map.size() == 0);
- char* soName = (char*)threadAllocator.Allocate(
- strlen(name) + strlen(DYLD_EXTENSION));
- sprintf(soName, "%s%s", name, DYLD_EXTENSION);
- void* handle = dlopen(soName, RTLD_LAZY | RTLD_LOCAL);
- if (handle) {
- Class* cl = (Class*)dlsym(handle, name);
- if (cl) {
- static_init_t init = (static_init_t)(uintptr_t)cl->classLoader;
- init(this);
- insertAllMethodsInVM();
- }
- }
-}
-
-Class* JnjvmClassLoader::loadClassFromSelf(const char* name) {
- assert(classes->map.size() == 0);
- Class* cl = (Class*)dlsym(SELF_HANDLE, name);
- if (cl) {
- static_init_t init = (static_init_t)(uintptr_t)cl->classLoader;
- init(this);
- insertAllMethodsInVM();
- }
- return cl;
-}
-
-
-// Extern "C" functions called by the vmjc static intializer.
-extern "C" void vmjcAddPreCompiledClass(JnjvmClassLoader* JCL,
- CommonClass* cl) {
- cl->classLoader = JCL;
- cl->virtualVT->vm = JCL->vm;
-
- JCL->hashUTF8->insert(cl->name);
-
- if (cl->isClass()) {
- Class* realCl = cl->asClass();
- // To avoid data alignment in the llvm assembly emitter, we set the
- // staticMethods and staticFields fields here.
- realCl->staticMethods = realCl->virtualMethods + realCl->nbVirtualMethods;
- realCl->staticFields = realCl->virtualFields + realCl->nbVirtualFields;
- cl->virtualVT->setNativeTracer(cl->virtualVT->tracer, "");
-
- for (uint32 i = 0; i< realCl->nbStaticMethods; ++i) {
- JavaMethod& meth = realCl->staticMethods[i];
- JCL->hashUTF8->insert(meth.name);
- JCL->hashUTF8->insert(meth.type);
- }
-
- for (uint32 i = 0; i< realCl->nbVirtualMethods; ++i) {
- JavaMethod& meth = realCl->virtualMethods[i];
- JCL->hashUTF8->insert(meth.name);
- JCL->hashUTF8->insert(meth.type);
- }
-
- for (uint32 i = 0; i< realCl->nbStaticFields; ++i) {
- JavaField& field = realCl->staticFields[i];
- JCL->hashUTF8->insert(field.name);
- JCL->hashUTF8->insert(field.type);
- }
-
- for (uint32 i = 0; i< realCl->nbVirtualFields; ++i) {
- JavaField& field = realCl->virtualFields[i];
- JCL->hashUTF8->insert(field.name);
- JCL->hashUTF8->insert(field.type);
- }
- }
-
- if (!cl->isPrimitive())
- JCL->getClasses()->map.insert(std::make_pair(cl->name, cl));
-
-}
-
-extern "C" void vmjcGetClassArray(JnjvmClassLoader* JCL, ClassArray** ptr,
- const UTF8* name) {
- JCL->hashUTF8->insert(name);
- *ptr = JCL->constructArray(name);
-}
-
-extern "C" void vmjcAddUTF8(JnjvmClassLoader* JCL, const UTF8* val) {
- JCL->hashUTF8->insert(val);
-}
-
-extern "C" void vmjcAddString(JnjvmClassLoader* JCL, JavaString* val) {
- JCL->strings->addString(JCL, val);
-}
-
-extern "C" intptr_t vmjcNativeLoader(JavaMethod* meth) {
- bool j3 = false;
- const UTF8* jniConsClName = meth->classDef->name;
- const UTF8* jniConsName = meth->name;
- const UTF8* jniConsType = meth->type;
- sint32 clen = jniConsClName->size;
- sint32 mnlen = jniConsName->size;
- sint32 mtlen = jniConsType->size;
-
- mvm::ThreadAllocator threadAllocator;
- char* buf = (char*)threadAllocator.Allocate(
- 3 + JNI_NAME_PRE_LEN + 1 + ((mnlen + clen + mtlen) << 3));
- intptr_t res = meth->classDef->classLoader->nativeLookup(meth, j3, buf);
- assert(res && "Could not find required native method");
- return res;
-}
-
-VMClassLoader* VMClassLoader::allocate(Jnjvm *vm) {
- VMClassLoader* res = 0;
- llvm_gcroot(res, 0);
- res = (VMClassLoader*)gc::operator new(sizeof(VMClassLoader), vm->VMClassLoader__VT);
- return res;
-}
-
-bool VMClassLoader::isVMClassLoader(Jnjvm *vm, JavaObject* obj) {
- llvm_gcroot(obj, 0);
- // not safe: must verify that obj belongs to a jvm
- return obj->getVirtualTable() == vm->VMClassLoader__VT;
-}
-
-extern "C" void staticCallback() {
- fprintf(stderr, "Implement me");
- abort();
-}
diff --git a/vmkit/lib/J3/VMCore/JnjvmClassLoader.h b/vmkit/lib/J3/VMCore/JnjvmClassLoader.h
deleted file mode 100644
index 82e3f9c..0000000
--- a/vmkit/lib/J3/VMCore/JnjvmClassLoader.h
+++ /dev/null
@@ -1,438 +0,0 @@
-//===-- JnjvmClassLoader.h - Jnjvm representation of a class loader -------===//
-//
-// The VMKit project
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-
-#ifndef JNJVM_CLASSLOADER_H
-#define JNJVM_CLASSLOADER_H
-
-#include <map>
-#include <vector>
-
-#include "types.h"
-
-
-#include "mvm/Allocator.h"
-
-#include "JavaObject.h"
-#include "JnjvmConfig.h"
-#include "UTF8.h"
-
-namespace j3 {
-
-class UserClass;
-class UserClassArray;
-class ClassBytes;
-class ClassMap;
-class Classpath;
-class UserCommonClass;
-class JavaCompiler;
-class JavaMethod;
-class JavaObject;
-class JavaString;
-class Jnjvm;
-class JnjvmBootstrapLoader;
-class JnjvmClassLoader;
-class Signdef;
-class SignMap;
-class StringList;
-class Typedef;
-class TypeMap;
-class VMClassLoader;
-class ZipArchive;
-
-
-/// JnjvmClassLoader - Runtime representation of a class loader. It contains
-/// its own tables (signatures, UTF8, types) which are mapped to a single
-/// table for non-isolate environments.
-///
-class JnjvmClassLoader : public mvm::PermanentObject {
-public:
- /// vm - my vm
- ///
- Jnjvm* vm;
-
-private:
- /// javaLoder - The Java representation of the class loader. Null for the
- /// bootstrap class loader.
- ///
- JavaObject* javaLoader;
-
- /// internalLoad - Load the class with the given name.
- ///
- virtual UserClass* internalLoad(const UTF8* utf8, bool doResolve,
- JavaString* strName);
-
- /// internalConstructType - Hashes a Typedef, an internal representation of
- /// a class still not loaded.
- ///
- Typedef* internalConstructType(const UTF8 * name);
-
- /// JnjvmClassLoader - Allocate a user-defined class loader. Called on
- /// first use of a Java class loader.
- ///
- JnjvmClassLoader(mvm::BumpPtrAllocator& Alloc, JavaObject* loader, VMClassLoader* vmdata, Jnjvm* vm);
-
- /// lookupComponentName - Try to find the component name of the given array
- /// name. If the component name is not in the table of UTF8s and holder
- /// is null, the function returns 0.
- ///
- const UTF8* lookupComponentName(const UTF8* name, UTF8* holder, bool& prim);
-
-protected:
-
- friend class Jnjvm;
- JnjvmClassLoader(mvm::BumpPtrAllocator& Alloc, Jnjvm* v) : allocator(Alloc) { vm = v; }
-
- /// TheCompiler - The Java compiler for this class loader.
- ///
- JavaCompiler* TheCompiler;
-
- /// classes - The classes this class loader has loaded.
- ///
- ClassMap* classes;
-
- /// javaTypes - Tables of Typedef defined by this class loader.
- ///
- TypeMap* javaTypes;
-
- /// javaSignatures - Tables of Signdef defined by this class loader.
- ///
- SignMap* javaSignatures;
-
- /// lock - Lock when loading classes.
- ///
- mvm::LockRecursive lock;
-
-public:
-
- /// allocator - Reference to the memory allocator, which will allocate UTF8s,
- /// signatures and types.
- ///
- mvm::BumpPtrAllocator& allocator;
-
- /// getClasses - Returns the classes this class loader has loaded.
- ///
- ClassMap* getClasses() const { return classes; }
-
- /// hashUTF8 - Tables of UTF8s defined by this class loader.
- ///
- UTF8Map* hashUTF8;
-
- /// getCompiler - Get the Java compiler of this class loader.
- ///
- JavaCompiler* getCompiler() const { return TheCompiler; }
-
- /// setCompiler - Set the compiler of classes loaded by this class loader.
- ///
- void setCompiler(JavaCompiler* Comp);
-
- /// tracer - Traces a JnjvmClassLoader for GC.
- ///
- virtual void tracer(uintptr_t closure);
-
- /// getJnjvmLoaderFromJavaObject - Return the Jnjvm runtime representation
- /// of the given class loader.
- ///
- static JnjvmClassLoader* getJnjvmLoaderFromJavaObject(JavaObject*, Jnjvm *vm);
-
- /// getJavaClassLoader - Return the Java representation of this class loader.
- ///
- JavaObject* getJavaClassLoader() const {
- return javaLoader;
- }
-
- /// getJavaClassLoaderPtr - Return a pointer to the Java representation of
- /// this class loader.
- ///
- JavaObject** getJavaClassLoaderPtr() {
- return &javaLoader;
- }
-
- /// loadName - Loads the class of the given name.
- ///
- UserClass* loadName(const UTF8* name, bool doResolve, bool doThrow,
- JavaString* strName);
-
- /// loadClassFromUTF8 - Lookup a class from an UTF8 name and load it.
- ///
- UserCommonClass* loadClassFromUserUTF8(const UTF8* utf8,
- bool doResolve, bool doThrow,
- JavaString* strName);
-
- /// loadClassFromAsciiz - Lookup a class from an asciiz name and load it.
- ///
- UserCommonClass* loadClassFromAsciiz(const char* name,
- bool doResolve, bool doThrow);
-
- /// loadClassFromJavaString - Lookup a class from a Java String and load it.
- ///
- UserCommonClass* loadClassFromJavaString(JavaString* str,
- bool doResolve, bool doThrow);
-
- /// lookupClassFromJavaString - Finds the class of the given string name in
- /// the class loader's table. Do not inline this function, because it
- /// does an alloca and is called by Classpath functions.
- ///
- UserCommonClass* lookupClassFromJavaString(JavaString* str)
- __attribute__ ((noinline));
-
- /// lookupClass - Finds the class of the given name in the class loader's
- /// table.
- ///
- UserCommonClass* lookupClass(const UTF8* utf8);
-
- /// lookupClassOrArray - Finds the class of the given name in the class
- /// loader's table. If the class has not been loaded, and if it's an
- /// array whose base class is loaded, then this function loads the array class
- /// and returns it.
- ///
- UserCommonClass* lookupClassOrArray(const UTF8* utf8);
-
- /// constructArray - Hashes a runtime representation of a class with
- /// the given name.
- ///
- UserClassArray* constructArray(const UTF8* name);
- UserClassArray* constructArray(const UTF8* name, UserCommonClass* base);
-
- UserCommonClass* loadBaseClass(const UTF8* name, uint32 start, uint32 len);
-
- /// constructClass - Hashes a runtime representation of a class with
- /// the given name.
- ///
- UserClass* constructClass(const UTF8* name, ClassBytes* bytes);
-
- /// constructType - Hashes a Typedef, an internal representation of a class
- /// still not loaded.
- ///
- Typedef* constructType(const UTF8 * name);
-
- /// constructSign - Hashes a Signdef, a method signature.
- ///
- Signdef* constructSign(const UTF8 * name);
-
- /// asciizConstructUTF8 - Hashes an UTF8 created from the given asciiz.
- ///
- const UTF8* asciizConstructUTF8(const char* asciiz);
-
- /// readerConstructUTF8 - Hashes an UTF8 created from the given Unicode
- /// buffer.
- ///
- const UTF8* readerConstructUTF8(const uint16* buf, uint32 size);
-
- /// ~JnjvmClassLoader - Destroy the loader: destroy the tables, JIT module and
- /// module provider.
- ///
- virtual ~JnjvmClassLoader();
-
- /// loadClass - The user class that defines the loadClass method.
- ///
- UserClass* loadClass;
-
- /// loadClassMethod - The loadClass defined by this class loader.
- ///
- JavaMethod* loadClassMethod;
-
- /// constructArrayName - Construct an array name based on a class name
- /// and the number of dimensions.
- const UTF8* constructArrayName(uint32 steps, const UTF8* className);
-
- /// UTF8ToStr - Constructs a Java string out of the UTF8.
- ///
- virtual JavaString** UTF8ToStr(const UTF8* utf8);
-
- /// Strings hashed by this classloader.
- ///
- StringList* strings;
-
- /// nativeLibs - Native libraries (e.g. '.so') loaded by this class loader.
- ///
- std::vector<void*> nativeLibs;
-
- /// loadInLib - Loads a native function out of the native libraries loaded
- /// by this class loader. The last argument tells if the returned method
- /// is defined in j3.
- ///
- intptr_t loadInLib(const char* buf, bool& j3);
-
- /// loadInLib - Loads a native function out of the given native library.
- ///
- intptr_t loadInLib(const char* buf, void* handle);
-
- /// loadLib - Loads the library with the given name.
- ///
- void* loadLib(const char* buf);
-
- /// nativeLookup - Lookup in the class loader a function pointer for the
- /// method. Also set in the j3 parameter is the function is defined in
- /// JnJVM.
- ///
- intptr_t nativeLookup(JavaMethod* meth, bool& j3, char* buf);
-
- /// insertAllMethodsInVM - Insert all methods defined by this class loader
- /// in the VM.
- ///
- void insertAllMethodsInVM();
-
- /// loadLibFromJar - Try to load the shared library compiled by vmjc with
- /// this jar file.
- ///
- void loadLibFromJar(const char* name, const char* file);
-
- /// loadLibFromFile - Try to load the shared library compiled by vmjc with
- /// this class file.
- ///
- void loadLibFromFile(const char* name);
-
- /// loadClassFromSelf - Load the main class if we are an executable.
- ///
- Class* loadClassFromSelf(const char* name);
-
- friend class Class;
-};
-
-/// JnjvmBootstrapLoader - This class is for the bootstrap class loader, which
-/// loads base classes, ie glibj.zip or rt.jar and -Xbootclasspath.
-///
-class JnjvmBootstrapLoader : public JnjvmClassLoader {
-private:
- /// internalLoad - Load the class with the given name.
- ///
- virtual UserClass* internalLoad(const UTF8* utf8, bool doResolve,
- JavaString* strName);
-
- /// bootClasspath - List of paths for the base classes.
- ///
- std::vector<const char*> bootClasspath;
-
- /// bootArchives - List of .zip or .jar files that contain base classes.
- ///
- std::vector<ZipArchive*> bootArchives;
-
- /// openName - Opens a file of the given name and returns it as an array
- /// of byte.
- ///
- ClassBytes* openName(const UTF8* utf8);
-
-public:
-
- /// tracer - Traces instances of this class.
- ///
- virtual void tracer(uintptr_t closure);
-
- /// libClasspathEnv - The paths for dynamic libraries of Classpath, separated
- /// by ':'.
- ///
- const char* libClasspathEnv;
-
- /// bootClasspathEnv - The path for base classes, seperated by '.'.
- ///
- const char* bootClasspathEnv;
-
- /// analyseClasspathEnv - Analyse the paths for base classes.
- ///
- void analyseClasspathEnv(const char*);
-
- /// createBootstrapLoader - Creates the bootstrap loader, first thing
- /// to do before any execution of a JVM.
- ///
- JnjvmBootstrapLoader(mvm::BumpPtrAllocator& Alloc, Jnjvm* vm, JavaCompiler* Comp);
-
- /// nativeHandle - Non-null handle if boot classes were static compiled in
- /// a dynamic library
- ///
- void* nativeHandle;
-
- virtual ~JnjvmBootstrapLoader();
-
- friend class ClArgumentsInfo;
-};
-
-/// VMClassLoader - The vmdata object that will be placed in and will only
-/// be referenced by the java.lang.Classloader Java object. Having a
-/// separate class between VMClassLoader and JnjvmClassLoader allows to
-/// have a JnjvmClassLoader non-GC object. Also the finalizer of this class
-/// will delete the internal class loader and we do not have to implement
-/// hacks in the java.lang.Classloader finalizer.
-class VMClassLoader : public JavaObject {
-private:
-
- /// JCL - The internal class loader.
- ///
- JnjvmClassLoader* JCL;
-
-public:
-
- /// Allocate a VMClassLoader
- ///
- static VMClassLoader* allocate(Jnjvm *vm);
-
- /// Is the object a VMClassLoader object?
- ///
- static bool isVMClassLoader(Jnjvm *vm, JavaObject* obj);
-
- /// staticTracer - Trace the internal class loader.
- ///
- static void staticTracer(VMClassLoader* obj, uintptr_t closure) {
- llvm_gcroot(obj, 0);
- if (obj->JCL != NULL) obj->JCL->tracer(closure);
- }
-
- /// ~VMClassLoader - Delete the internal class loader.
- ///
- static void staticDestructor(VMClassLoader* obj) {
- llvm_gcroot(obj, 0);
- if (obj->JCL != NULL) {
- obj->JCL->~JnjvmClassLoader();
- delete &(obj->JCL->allocator);
- }
- }
-
- /// getClassLoader - Get the internal class loader.
- ///
- JnjvmClassLoader* getClassLoader() {
- return JCL;
- }
-
- friend class JnjvmClassLoader;
-};
-
-#define MAXIMUM_STRINGS 100
-
-class StringList : public mvm::PermanentObject {
- friend class JnjvmClassLoader;
- friend class Jnjvm;
-
-private:
- StringList* prev;
- uint32_t length;
- JavaString* strings[MAXIMUM_STRINGS];
-
-public:
- StringList() {
- prev = 0;
- length = 0;
- }
-
- JavaString** addString(JnjvmClassLoader* JCL, JavaString* obj) {
- llvm_gcroot(obj, 0);
- if (length == MAXIMUM_STRINGS) {
- StringList* next = new(JCL->allocator, "StringList") StringList();
- next->prev = this;
- JCL->strings = next;
- return next->addString(JCL, obj);
- } else {
- strings[length] = obj;
- return &strings[length++];
- }
- }
-};
-
-} // end namespace j3
-
-#endif // JNJVM_CLASSLOADER_H
diff --git a/vmkit/lib/J3/VMCore/JnjvmConfig.h b/vmkit/lib/J3/VMCore/JnjvmConfig.h
deleted file mode 100644
index 14fbc78..0000000
--- a/vmkit/lib/J3/VMCore/JnjvmConfig.h
+++ /dev/null
@@ -1,34 +0,0 @@
-//===---------- JnjvmConfig.h - Jnjvm configuration file ------------------===//
-//
-// The VMKit project
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-
-#ifndef JNJVM_CONFIG_H
-#define JNJVM_CONFIG_H
-
-namespace j3 {
-
-class ClassArray;
-class ClassPrimitive;
-class Class;
-class CommonClass;
-class JavaConstantPool;
-
-#define UserClassArray ClassArray
-#define UserClassPrimitive ClassPrimitive
-#define UserClass Class
-#define UserCommonClass CommonClass
-#define UserConstantPool JavaConstantPool
-
-}
-#define ISOLATE_STATIC static
-
-
-#define NR_ISOLATES 1
-
-#endif // JNJVM_CONFIG_H
diff --git a/vmkit/lib/J3/VMCore/LinkJavaRuntime.h b/vmkit/lib/J3/VMCore/LinkJavaRuntime.h
deleted file mode 100644
index ac17916..0000000
--- a/vmkit/lib/J3/VMCore/LinkJavaRuntime.h
+++ /dev/null
@@ -1,108 +0,0 @@
-//===--------------------- LinkJavaRuntime.h ------------------------------===//
-//=== ------------- Reference all runtime functions -----------------------===//
-//
-// The VMKit project
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#ifndef JNJVM_LINK_JAVA_RUNTIME_H
-#define JNJVM_LINK_JAVA_RUNTIME_H
-
-
-namespace j3 {
- class JavaObject;
- class UserClass;
- class UserClassArray;
- class UserCommonClass;
- class UserConstantPool;
- class JavaVirtualTable;
- class JavaMethod;
- class Jnjvm;
-}
-
-namespace mvm {
- class KnownFrame;
-}
-
-using namespace j3;
-
-extern "C" void* j3InterfaceLookup(UserClass* caller, uint32 index);
-extern "C" void* j3VirtualFieldLookup(UserClass* caller, uint32 index);
-extern "C" void* j3StaticFieldLookup(UserClass* caller, uint32 index);
-extern "C" void* j3VirtualTableLookup(UserClass* caller, uint32 index, ...);
-extern "C" void* j3StringLookup(UserClass* cl, uint32 index);
-extern "C" void* j3ClassLookup(UserClass* caller, uint32 index);
-extern "C" UserCommonClass* j3RuntimeInitialiseClass(UserClass* cl);
-extern "C" JavaObject* j3RuntimeDelegatee(UserCommonClass* cl);
-extern "C" JavaArray* j3MultiCallNew(UserClassArray* cl, uint32 len, ...);
-extern "C" UserClassArray* j3GetArrayClass(UserCommonClass*,
- UserClassArray**);
-extern "C" void j3EndJNI(uint32**);
-extern "C" void* j3StartJNI(uint32*, uint32**, mvm::KnownFrame*);
-extern "C" void j3JavaObjectAquire(JavaObject* obj);
-extern "C" void j3JavaObjectRelease(JavaObject* obj);
-extern "C" void j3ThrowException(JavaObject* obj);
-extern "C" JavaObject* j3NullPointerException();
-extern "C" JavaObject* j3NegativeArraySizeException(sint32 val);
-extern "C" JavaObject* j3OutOfMemoryError(sint32 val);
-extern "C" JavaObject* j3StackOverflowError();
-extern "C" JavaObject* j3ArithmeticException();
-extern "C" JavaObject* j3ClassCastException(JavaObject* obj,
- UserCommonClass* cl);
-extern "C" JavaObject* j3IndexOutOfBoundsException(JavaObject* obj,
- sint32 index);
-extern "C" JavaObject* j3ArrayStoreException(JavaVirtualTable* VT);
-extern "C" void j3ThrowExceptionFromJIT();
-extern "C" void j3PrintMethodStart(JavaMethod* meth);
-extern "C" void j3PrintMethodEnd(JavaMethod* meth);
-extern "C" void j3PrintExecution(uint32 opcode, uint32 index,
- JavaMethod* meth);
-
-
-namespace force_linker {
- struct ForceRuntimeLinking {
- ForceRuntimeLinking() {
- // We must reference the passes in such a way that compilers will not
- // delete it all as dead code, even with whole program optimization,
- // yet is effectively a NO-OP. As the compiler isn't smart enough
- // to know that getenv() never returns -1, this will do the job.
- if (std::getenv("bar") != (char*) -1)
- return;
-
- (void) j3InterfaceLookup(0, 0);
- (void) j3VirtualFieldLookup(0, 0);
- (void) j3StaticFieldLookup(0, 0);
- (void) j3VirtualTableLookup(0, 0);
- (void) j3ClassLookup(0, 0);
- (void) j3RuntimeInitialiseClass(0);
- (void) j3RuntimeDelegatee(0);
- (void) j3MultiCallNew(0, 0);
- (void) j3GetArrayClass(0, 0);
- (void) j3EndJNI(0);
- (void) j3StartJNI(0, 0, 0);
- (void) j3JavaObjectAquire(0);
- (void) j3JavaObjectRelease(0);
- (void) j3ThrowException(0);
- (void) j3NullPointerException();
- (void) j3NegativeArraySizeException(0);
- (void) j3OutOfMemoryError(0);
- (void) j3StackOverflowError();
- (void) j3ArithmeticException();
- (void) j3ClassCastException(0, 0);
- (void) j3IndexOutOfBoundsException(0, 0);
- (void) j3ArrayStoreException(0);
- (void) j3ThrowExceptionFromJIT();
- (void) j3PrintMethodStart(0);
- (void) j3PrintMethodEnd(0);
- (void) j3PrintExecution(0, 0, 0);
- (void) j3StringLookup(0, 0);
- }
- } ForcePassLinking; // Force link by creating a global definition.
-}
-
-
-
-#endif //JNJVM_LINK_JAVA_RUNTIME_H
diff --git a/vmkit/lib/J3/VMCore/LockedMap.cpp b/vmkit/lib/J3/VMCore/LockedMap.cpp
deleted file mode 100644
index 8fa78f1..0000000
--- a/vmkit/lib/J3/VMCore/LockedMap.cpp
+++ /dev/null
@@ -1,26 +0,0 @@
-//===------- LockedMap.cpp - Implementation of the UTF8 map ---------------===//
-//
-// The VMKit project
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#include <map>
-
-#include "JavaArray.h"
-#include "JavaClass.h"
-#include "JavaString.h"
-#include "JavaTypes.h"
-#include "LockedMap.h"
-#include "Zip.h"
-
-#include <cstring>
-
-using namespace j3;
-
-void StringMap::insert(JavaString* str) {
- llvm_gcroot(str, 0);
- map.insert(std::make_pair(JavaString::getValue(str), str));
-}
diff --git a/vmkit/lib/J3/VMCore/LockedMap.h b/vmkit/lib/J3/VMCore/LockedMap.h
deleted file mode 100644
index bfa969c..0000000
--- a/vmkit/lib/J3/VMCore/LockedMap.h
+++ /dev/null
@@ -1,213 +0,0 @@
-//===------- LockedMap.h - A thread-safe map implementation ---------------===//
-//
-// The VMKit project
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-//
-// This file defines thread-safe maps that must be deallocated by the owning
-// object. For example a class loader is responsible for deallocating the
-// types stored in a TypeMap.
-//
-//===----------------------------------------------------------------------===//
-
-#ifndef JNJVM_LOCKED_MAP_H
-#define JNJVM_LOCKED_MAP_H
-
-#include <map>
-
-#include <cstring>
-
-#include "types.h"
-
-#include "mvm/Allocator.h"
-#include "mvm/Threads/Locks.h"
-#include "UTF8.h"
-
-#include "JavaArray.h" // for comparing UTF8s
-
-namespace j3 {
-
-class JavaString;
-class JnjvmClassLoader;
-class Signdef;
-class Typedef;
-class UserCommonClass;
-class UserClassArray;
-
-struct ltutf8
-{
- bool operator()(const UTF8* s1, const UTF8* s2) const
- {
- return s1->lessThan(s2);
- }
-};
-
-struct ltarray16
-{
- bool operator()(const ArrayUInt16* s1, const ArrayUInt16* s2) const
- {
- llvm_gcroot(s1, 0);
- llvm_gcroot(s2, 0);
- if (ArrayUInt16::getSize(s1) < ArrayUInt16::getSize(s2)) return true;
- else if (ArrayUInt16::getSize(s1) > ArrayUInt16::getSize(s2)) return false;
- else return memcmp((const char*)ArrayUInt16::getElements(s1),
- (const char*)ArrayUInt16::getElements(s2),
- ArrayUInt16::getSize(s1) * sizeof(uint16)) < 0;
- }
-};
-
- class MapNoGC {
- public:
- static void gcroot(void* val, void* unused)
- __attribute__ ((always_inline)) {}
-
- };
-
- class MapWithGC {
- public:
- static void gcroot(void* val, void* unused)
- __attribute__ ((always_inline)) {
- llvm_gcroot(val, unused);
- }
-
- };
-
-
-template<class Key, class Container, class Compare, class Meta, class TLock,
- class IsGC>
-class LockedMap : public mvm::PermanentObject {
-public:
- typedef typename std::map<const Key, Container, Compare>::iterator iterator;
- typedef Container (*funcCreate)(Key& V, Meta meta);
-
- TLock lock;
- std::map<const Key, Container, Compare,
- gc_allocator<std::pair<const Key, Container> > > map;
-
- inline Container lookupOrCreate(Key& V, Meta meta, funcCreate func) {
- Container res = 0;
- IsGC::gcroot(res, 0);
- IsGC::gcroot((void*)V, 0);
- lock.lock();
- iterator End = map.end();
- iterator I = map.find(V);
- if (I == End) {
- res = func(V, meta);
- map.insert(std::make_pair(V, res));
- lock.unlock();
- return res;
- } else {
- lock.unlock();
- return ((Container)(I->second));
- }
- }
-
- inline void remove(Key V) {
- IsGC::gcroot(V, 0);
- lock.lock();
- map.erase(V);
- lock.unlock();
- }
-
- inline void remove(Key V, Container C) {
- IsGC::gcroot(C, 0);
- IsGC::gcroot(V, 0);
- lock.lock();
- removeUnlocked(V, C);
- lock.unlock();
- }
-
- inline void removeUnlocked(Key V, Container C) {
- IsGC::gcroot(C, 0);
- IsGC::gcroot((void*)V, 0);
- iterator End = map.end();
- iterator I = map.find(V);
-
- if (I != End && I->second == C)
- map.erase(I);
- }
-
- inline Container lookup(Key V) {
- IsGC::gcroot((void*)V, 0);
- lock.lock();
- iterator End = map.end();
- iterator I = map.find(V);
- lock.unlock();
- return I != End ? ((Container)(I->second)) : 0;
- }
-
- inline void hash(Key k, Container c) {
- IsGC::gcroot(c, 0);
- IsGC::gcroot(k, 0);
- lock.lock();
- map.insert(std::make_pair(k, c));
- lock.unlock();
- }
-
- ~LockedMap() {}
-};
-
-class ClassMap :
- public LockedMap<const UTF8*, UserCommonClass*, ltutf8, JnjvmClassLoader*,
- mvm::LockRecursive, MapNoGC > {
-
-#ifdef USE_GC_BOEHM
-public:
- void* operator new(size_t sz, mvm::BumpPtrAllocator& allocator) {
- return GC_MALLOC(sz);
- }
-#endif
-};
-
-class StringMap :
- public LockedMap<const ArrayUInt16*, JavaString*, ltarray16, Jnjvm*,
- mvm::LockNormal, MapWithGC> {
-
-public:
- void insert(JavaString* str);
-
-};
-
-class TypeMap : public mvm::PermanentObject {
-public:
- mvm::LockNormal lock;
-
- std::map<const UTF8*, Typedef*, ltutf8> map;
- typedef std::map<const UTF8*, Typedef*, ltutf8>::iterator iterator;
-
- inline Typedef* lookup(const UTF8* V) {
- iterator End = map.end();
- iterator I = map.find(V);
- return I != End ? I->second : 0;
- }
-
- inline void hash(const UTF8* k, Typedef* c) {
- map.insert(std::make_pair(k, c));
- }
-};
-
-class SignMap : public mvm::PermanentObject {
-public:
- mvm::LockNormal lock;
-
- std::map<const UTF8*, Signdef*, ltutf8> map;
- typedef std::map<const UTF8*, Signdef*, ltutf8>::iterator iterator;
-
- inline Signdef* lookup(const UTF8* V) {
- iterator End = map.end();
- iterator I = map.find(V);
- return I != End ? I->second : 0;
- }
-
- inline void hash(const UTF8* k, Signdef* c) {
- map.insert(std::make_pair(k, c));
- }
-
-};
-
-} // end namespace j3
-
-#endif
diff --git a/vmkit/lib/J3/VMCore/Makefile b/vmkit/lib/J3/VMCore/Makefile
deleted file mode 100644
index 10f4bcc..0000000
--- a/vmkit/lib/J3/VMCore/Makefile
+++ /dev/null
@@ -1,23 +0,0 @@
-##===- lib/JnJVM/VMCore/Makefile ---------------------------*- Makefile -*-===##
-#
-# The vmkit project
-#
-# This file is distributed under the University of Illinois Open Source
-# License. See LICENSE.TXT for details.
-#
-##===----------------------------------------------------------------------===##
-LEVEL = ../../..
-
-include $(LEVEL)/Makefile.config
-
-ifeq ($(WITH_LLVM_GCC), 1)
- MODULE_NAME = J3
-else
- LIBRARYNAME = J3
-endif
-
-
-include $(LEVEL)/Makefile.common
-
-CXX.Flags += -I$(PROJ_OBJ_DIR)/../Classpath -I$(PROJ_OBJ_DIR)/../LLVMRuntime -I$(PROJ_SRC_DIR)/../Classpath $(CLASSPATH_FLAGS) -I$(PROJ_SRC_DIR)/../../../include/j3
-
diff --git a/vmkit/lib/J3/VMCore/Reader.cpp b/vmkit/lib/J3/VMCore/Reader.cpp
deleted file mode 100644
index 785e4d4..0000000
--- a/vmkit/lib/J3/VMCore/Reader.cpp
+++ /dev/null
@@ -1,68 +0,0 @@
-//===--------------- Reader.cpp - Open and read files ---------------------===//
-//
-// The VMKit project
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#include <cstdio>
-#include <cstring>
-
-#include "types.h"
-
-#include "JnjvmClassLoader.h"
-#include "Reader.h"
-#include "Zip.h"
-
-using namespace j3;
-
-const int Reader::SeekSet = SEEK_SET;
-const int Reader::SeekCur = SEEK_CUR;
-const int Reader::SeekEnd = SEEK_END;
-
-ClassBytes* Reader::openFile(JnjvmClassLoader* loader, const char* path) {
- ClassBytes* res = NULL;
- FILE* fp = fopen(path, "r");
- if (fp != 0) {
- fseek(fp, 0, SeekEnd);
- long nbb = ftell(fp);
- fseek(fp, 0, SeekSet);
- res = new (loader->allocator, nbb) ClassBytes(nbb);
- if (fread(res->elements, nbb, 1, fp) == 0) {
- fprintf(stderr, "fread error\n");
- abort();
- }
- fclose(fp);
- }
- return res;
-}
-
-ClassBytes* Reader::openZip(JnjvmClassLoader* loader, ZipArchive* archive,
- const char* filename) {
- ClassBytes* res = 0;
- ZipFile* file = archive->getFile(filename);
- if (file != 0) {
- res = new (loader->allocator, file->ucsize) ClassBytes(file->ucsize);
- if (archive->readFile(res, file) != 0) {
- return res;
- }
- }
- return NULL;
-}
-
-void Reader::seek(uint32 pos, int from) {
- uint32 n = 0;
- uint32 start = min;
- uint32 end = max;
-
- if (from == SeekCur) n = cursor + pos;
- else if (from == SeekSet) n = start + pos;
- else if (from == SeekEnd) n = end + pos;
-
-
- assert(n >= start && n <= end && "out of range");
-
- cursor = n;
-}
diff --git a/vmkit/lib/J3/VMCore/Reader.h b/vmkit/lib/J3/VMCore/Reader.h
deleted file mode 100644
index 0fd9890..0000000
--- a/vmkit/lib/J3/VMCore/Reader.h
+++ /dev/null
@@ -1,159 +0,0 @@
-//===----------------- Reader.h - Open and read files ---------------------===//
-//
-// The VMKit project
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#ifndef JNJVM_READER_H
-#define JNJVM_READER_H
-
-#include "types.h"
-
-#include "JavaArray.h"
-#include "JavaClass.h"
-
-namespace j3 {
-
-class JnjvmBootstrapLoader;
-class JnjvmClassLoader;
-class ZipArchive;
-
-
-class ClassBytes {
- public:
- ClassBytes(int l) {
- size = l;
- }
-
- void* operator new(size_t sz, mvm::BumpPtrAllocator& allocator, int n) {
- return allocator.Allocate(sizeof(uint32_t) + n * sizeof(uint8_t),
- "Class bytes");
- }
-
- uint32_t size;
- uint8_t elements[1];
-};
-
-class Reader {
-public:
- // bytes - Pointer to a reference array. The array is not manipulated directly
- // in order to support copying GC.
- ClassBytes* bytes;
- uint32 min;
- uint32 cursor;
- uint32 max;
-
- Reader(Attribut* attr, ClassBytes* bytes) {
- this->bytes = bytes;
- this->cursor = attr->start;
- this->min = attr->start;
- this->max = attr->start + attr->nbb;
- }
-
- Reader(Reader& r, uint32 nbb) {
- bytes = r.bytes;
- cursor = r.cursor;
- min = r.min;
- max = min + nbb;
- }
-
- static double readDouble(int first, int second) {
- int values[2];
- double res[1];
-#if defined(__PPC__)
- values[0] = second;
- values[1] = first;
-#else
- values[0] = first;
- values[1] = second;
-#endif
- memcpy(res, values, 8);
- return res[0];
- }
-
-
- static sint64 readLong(int first, int second) {
- int values[2];
- sint64 res[1];
-#if defined(__PPC__)
- values[0] = second;
- values[1] = first;
-#else
- values[0] = first;
- values[1] = second;
-#endif
- memcpy(res, values, 8);
- return res[0];
- }
-
- static const int SeekSet;
- static const int SeekCur;
- static const int SeekEnd;
-
- static ClassBytes* openFile(JnjvmClassLoader* loader, const char* path);
- static ClassBytes* openZip(JnjvmClassLoader* loader, ZipArchive* archive,
- const char* filename);
-
- uint8 readU1() {
- ++cursor;
- return bytes->elements[cursor - 1];
- }
-
- sint8 readS1() {
- ++cursor;
- return bytes->elements[cursor - 1];
- }
-
- uint16 readU2() {
- uint16 tmp = ((uint16)(readU1())) << 8;
- return tmp | ((uint16)(readU1()));
- }
-
- sint16 readS2() {
- sint16 tmp = ((sint16)(readS1())) << 8;
- return tmp | ((sint16)(readU1()));
- }
-
- uint32 readU4() {
- uint32 tmp = ((uint32)(readU2())) << 16;
- return tmp | ((uint32)(readU2()));
- }
-
- sint32 readS4() {
- sint32 tmp = ((sint32)(readS2())) << 16;
- return tmp | ((sint32)(readU2()));
- }
-
- uint64 readU8() {
- uint64 tmp = ((uint64)(readU4())) << 32;
- return tmp | ((uint64)(readU4()));
- }
-
- sint64 readS8() {
- sint64 tmp = ((sint64)(readS4())) << 32;
- return tmp | ((sint64)(readU4()));
- }
-
- Reader(ClassBytes* array, uint32 start = 0, uint32 end = 0) {
- if (!end) end = array->size;
- this->bytes = array;
- this->cursor = start;
- this->min = start;
- this->max = start + end;
- }
-
-
- unsigned int tell() {
- return cursor - min;
- }
-
- void seek(uint32 pos, int from);
-
-};
-
-} // end namespace j3
-
-#endif
diff --git a/vmkit/lib/J3/VMCore/UTF8.h b/vmkit/lib/J3/VMCore/UTF8.h
deleted file mode 100644
index 2b9da32..0000000
--- a/vmkit/lib/J3/VMCore/UTF8.h
+++ /dev/null
@@ -1,64 +0,0 @@
-//===------------------- UTF8.h - Utilities for UTF8 ----------------------===//
-//
-// The VMKit project
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#ifndef _JNJVM_UTF8_H_
-#define _JNJVM_UTF8_H_
-
-#include "types.h"
-
-#include "mvm/UTF8.h"
-#include "mvm/PrintBuffer.h"
-
-namespace j3 {
- using mvm::UTF8;
- using mvm::UTF8Map;
-
-/// UTF8Buffer - Helper class to create char* buffers suitable for
-/// printf.
-///
-class UTF8Buffer : public mvm::PrintBuffer {
-public:
- /// UTF8Buffer - Create a buffer with the following UTF8.
- UTF8Buffer(const UTF8* val) : mvm::PrintBuffer(val) {}
-
- /// toCompileName - Change the utf8 following JNI conventions.
- ///
- UTF8Buffer* toCompileName() {
- const char *buffer = cString();
- uint32 len = strlen(buffer);
- char* newBuffer = new char[(len << 1) + 1];
- uint32 j = 0;
- for (uint32 i = 0; i < len; ++i) {
- if (buffer[i] == '/') {
- newBuffer[j++] = '_';
- } else if (buffer[i] == '_') {
- newBuffer[j++] = '_';
- newBuffer[j++] = '1';
- } else if (buffer[i] == ';') {
- newBuffer[j++] = '_';
- newBuffer[j++] = '2';
- } else if (buffer[i] == '[') {
- newBuffer[j++] = '_';
- newBuffer[j++] = '3';
- } else if (buffer[i] == '$') {
- newBuffer[j++] = '_';
- newBuffer[j++] = '4';
- } else {
- newBuffer[j++] = buffer[i];
- }
- }
- newBuffer[j] = 0;
- replaceWith(newBuffer);
- return this;
- }
-};
-
-}
-
-#endif
diff --git a/vmkit/lib/J3/VMCore/VirtualTables.cpp b/vmkit/lib/J3/VMCore/VirtualTables.cpp
deleted file mode 100644
index 0410b14..0000000
--- a/vmkit/lib/J3/VMCore/VirtualTables.cpp
+++ /dev/null
@@ -1,326 +0,0 @@
-//===------ VirtualTables.cpp - Virtual methods for J3 objects ------------===//
-//
-// The VMKit project
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-//
-// This file contains GC specific tracing functions. It is used by the
-// GCMmap2 garbage collector and may be of use for other GCs. Boehm GC does
-// not use these functions.
-//
-// The file is divided into four parts:
-// (1) Declaration of internal GC classes.
-// (2) Tracing Java objects: regular object, native array, object array.
-// (3) Tracing a class loader, which involves tracing the Java objects
-// referenced by classes.
-// (4) Tracing the roots of a program: the JVM and the threads.
-//
-//===----------------------------------------------------------------------===//
-
-#include "ClasspathReflect.h"
-#include "JavaArray.h"
-#include "JavaClass.h"
-#include "JavaObject.h"
-#include "JavaString.h"
-#include "JavaThread.h"
-#include "JavaUpcalls.h"
-#include "Jnjvm.h"
-#include "JnjvmClassLoader.h"
-#include "LockedMap.h"
-#include "Zip.h"
-
-using namespace j3;
-
-//===----------------------------------------------------------------------===//
-// List of classes that will be GC-allocated. One should try to keep this
-// list as minimal as possible, and a GC class must be defined only if
-// absolutely necessary. If there is an easy way to avoid it, do it! Only
-// Java classes should be GC classes.
-// Having many GC classes gives more work to the GC for the scanning phase
-// and for the relocation phase (for copying collectors).
-//
-// In J3, there is only one internal gc object, the class loader.
-// We decided that this was the best solution because
-// otherwise it would involve hacks on the java.lang.Classloader class.
-// Therefore, we create a new GC class with a finalize method that will
-// delete the internal class loader when the Java object class loader is
-// not reachable anymore. This also relies on the java.lang.Classloader class
-// referencing an object of type VMClassLoader (this is the case in GNU
-// Classpath with the vmdata field).
-//===----------------------------------------------------------------------===//
-
-void Jnjvm::initialiseInternalVTs() {
- VMClassLoader__VT = (mvm::VirtualTable*)allocator.Allocate(sizeof(mvm::VirtualTable), "Virtual table");
- VMClassLoader__VT->destructor = (uintptr_t)VMClassLoader::staticDestructor;
- VMClassLoader__VT->operatorDelete = (uintptr_t)VMClassLoader::staticDestructor;
- VMClassLoader__VT->tracer = (uintptr_t)VMClassLoader::staticTracer;
- VMClassLoader__VT->vm = this;
-}
-
-//===----------------------------------------------------------------------===//
-// Trace methods for Java objects. There are four types of objects:
-// (1) java.lang.Object and primitive arrays: no need to trace anything.
-// (2) Object whose class is not an array: needs to trace the classloader, and
-// all the virtual fields.
-// (3) Object whose class is an array of objects: needs to trace the class
-// loader and all elements in the array.
-// (4) Objects that extend java.lang.ref.Reference: must trace the class loader
-// and all the fields except the referent.
-//===----------------------------------------------------------------------===//
-
-/// Scanning java.lang.Object and primitive arrays.
-extern "C" void JavaObjectTracer(JavaObject* obj, uintptr_t closure) {
-}
-
-/// Method for scanning regular objects.
-extern "C" void RegularObjectTracer(JavaObject* obj, uintptr_t closure) {
- Class* cl = JavaObject::getClass(obj)->asClass();
- assert(cl && "Not a class in regular tracer");
- mvm::Collector::markAndTraceRoot(
- cl->classLoader->getJavaClassLoaderPtr(), closure);
-
- while (cl->super != 0) {
- for (uint32 i = 0; i < cl->nbVirtualFields; ++i) {
- JavaField& field = cl->virtualFields[i];
- if (field.isReference()) {
- JavaObject** ptr = field.getInstanceObjectFieldPtr(obj);
- mvm::Collector::markAndTrace(obj, ptr, closure);
- }
- }
- cl = cl->super;
- }
-}
-
-/// Method for scanning an array whose elements are JavaObjects. This method is
-/// called for all non-native Java arrays.
-extern "C" void ArrayObjectTracer(ArrayObject* obj, uintptr_t closure) {
- CommonClass* cl = JavaObject::getClass(obj);
- assert(cl && "No class");
- mvm::Collector::markAndTraceRoot(
- cl->classLoader->getJavaClassLoaderPtr(), closure);
-
-
- for (sint32 i = 0; i < ArrayObject::getSize(obj); i++) {
- if (ArrayObject::getElement(obj, i) != NULL) {
- mvm::Collector::markAndTrace(
- obj, ArrayObject::getElements(obj) + i, closure);
- }
- }
-}
-
-/// Method for scanning Java java.lang.ref.Reference objects.
-extern "C" void ReferenceObjectTracer(
- JavaObjectReference* obj, uintptr_t closure) {
- Class* cl = JavaObject::getClass(obj)->asClass();
- assert(cl && "Not a class in reference tracer");
- mvm::Collector::markAndTraceRoot(
- cl->classLoader->getJavaClassLoaderPtr(), closure);
-
- bool found = false;
- while (cl->super != 0) {
- for (uint32 i = 0; i < cl->nbVirtualFields; ++i) {
- JavaField& field = cl->virtualFields[i];
- if (field.isReference()) {
- JavaObject** ptr = field.getInstanceObjectFieldPtr(obj);
- if (ptr != JavaObjectReference::getReferentPtr(obj)) {
- mvm::Collector::markAndTrace(obj, ptr, closure);
- } else {
- found = true;
- }
- }
- }
- cl = cl->super;
- }
- assert(found && "No referent in a reference");
-}
-
-//===----------------------------------------------------------------------===//
-// Support for scanning Java objects referenced by classes. All classes must
-// trace:
-// (1) The classloader of the parents (super and interfaces) as well as its
-// own class loader.
-// (2) The delegatee object (java.lang.Class) if it exists.
-//
-// Additionaly, non-primitive and non-array classes must trace:
-// (3) The static instance.
-//===----------------------------------------------------------------------===//
-
-void CommonClass::tracer(uintptr_t closure) {
-
- if (super != NULL && super->classLoader != NULL) {
- JavaObject** Obj = super->classLoader->getJavaClassLoaderPtr();
- if (*Obj != NULL) mvm::Collector::markAndTraceRoot(Obj, closure);
-
- for (uint32 i = 0; i < nbInterfaces; ++i) {
- if (interfaces[i]->classLoader) {
- JavaObject** Obj = interfaces[i]->classLoader->getJavaClassLoaderPtr();
- if (*Obj != NULL) mvm::Collector::markAndTraceRoot(Obj, closure);
- }
- }
- }
-
- if (classLoader != NULL) {
- mvm::Collector::markAndTraceRoot(
- classLoader->getJavaClassLoaderPtr(), closure);
- }
-
- for (uint32 i = 0; i < NR_ISOLATES; ++i) {
- if (delegatee[i] != NULL) {
- mvm::Collector::markAndTraceRoot(delegatee + i, closure);
- }
- }
-}
-
-void Class::tracer(uintptr_t closure) {
- CommonClass::tracer(closure);
-
- for (uint32 i = 0; i < NR_ISOLATES; ++i) {
- TaskClassMirror &M = IsolateInfo[i];
- if (M.staticInstance != NULL) {
- for (uint32 i = 0; i < nbStaticFields; ++i) {
- JavaField& field = staticFields[i];
- if (field.isReference()) {
- JavaObject** ptr = field.getStaticObjectFieldPtr();
- mvm::Collector::markAndTraceRoot(ptr, closure);
- }
- }
- }
- }
-}
-
-//===----------------------------------------------------------------------===//
-// Support for scanning a classloader. A classloader must trace:
-// (1) All the classes it has loaded (located in the classmap).
-// (2) All the class it has initiated loading and therefore references (located
-// in the classmap).
-// (3) All the strings referenced in class files.
-//
-// The class loader does not need to trace its java.lang.Classloader Java object
-// because if we end up here, this means that the Java object is already being
-// scanned. Only the Java object traces the class loader.
-//
-// Additionaly, the bootstrap loader must trace:
-// (4) The delegatees of native array classes. Since these classes are not in
-// the class map and they are not GC-allocated, we must trace the objects
-// referenced by the delegatees.
-//===----------------------------------------------------------------------===//
-
-void JnjvmClassLoader::tracer(uintptr_t closure) {
-
- for (ClassMap::iterator i = classes->map.begin(), e = classes->map.end();
- i!= e; ++i) {
- CommonClass* cl = i->second;
- if (cl->isClass()) cl->asClass()->tracer(closure);
- else cl->tracer(closure);
- }
-
- StringList* end = strings;
- while (end != NULL) {
- for (uint32 i = 0; i < end->length; ++i) {
- JavaString** obj = end->strings + i;
- mvm::Collector::markAndTraceRoot(obj, closure);
- }
- end = end->prev;
- }
-
- mvm::Collector::markAndTraceRoot(&javaLoader, closure);
-}
-
-void JnjvmBootstrapLoader::tracer(uintptr_t closure) {
-
- JnjvmClassLoader::tracer(closure);
-}
-
-//===----------------------------------------------------------------------===//
-// Support for scanning the roots of a program: JVM and threads. The JVM
-// must trace:
-// (1) The bootstrap class loader: where core classes live.
-// (2) The applicative class loader: the JVM may be the ony one referencing it.
-// (3) Global references from JNI.
-//
-// The threads must trace:
-// (1) Their stack (already done by the GC in the case of GCMmap2 or Boehm)
-// (2) The java.lang.Thread delegate.
-//===----------------------------------------------------------------------===//
-
-
-void Jnjvm::tracer(uintptr_t closure) {
- // (1) Trace the bootrap loader.
- bootstrapLoader->tracer(closure);
-
- // (2) Trace the application class loader.
- if (appClassLoader != NULL) {
- mvm::Collector::markAndTraceRoot(
- appClassLoader->getJavaClassLoaderPtr(), closure);
- }
-
- // (3) Trace JNI global references.
- JNIGlobalReferences* start = &globalRefs;
- while (start != NULL) {
- for (uint32 i = 0; i < start->length; ++i) {
- JavaObject** obj = start->globalReferences + i;
- mvm::Collector::markAndTraceRoot(obj, closure);
- }
- start = start->next;
- }
-
- // (4) Trace the interned strings.
- for (StringMap::iterator i = hashStr.map.begin(), e = hashStr.map.end();
- i!= e; ++i) {
- JavaString** str = &(i->second);
- mvm::Collector::markAndTraceRoot(str, closure);
- ArrayUInt16** key = const_cast<ArrayUInt16**>(&(i->first));
- mvm::Collector::markAndTraceRoot(key, closure);
- }
-
- // (5) Trace the delegatees.
-#define TRACE_DELEGATEE(prim) \
- prim->tracer(closure);
-
- TRACE_DELEGATEE(upcalls->OfVoid);
- TRACE_DELEGATEE(upcalls->OfBool);
- TRACE_DELEGATEE(upcalls->OfByte);
- TRACE_DELEGATEE(upcalls->OfChar);
- TRACE_DELEGATEE(upcalls->OfShort);
- TRACE_DELEGATEE(upcalls->OfInt);
- TRACE_DELEGATEE(upcalls->OfFloat);
- TRACE_DELEGATEE(upcalls->OfLong);
- TRACE_DELEGATEE(upcalls->OfDouble);
-#undef TRACE_DELEGATEE
-
- // (6) Trace the locks and their associated object.
- uint32 i = 0;
- for (; i < mvm::LockSystem::GlobalSize; i++) {
- mvm::FatLock** array = lockSystem.LockTable[i];
- if (array == NULL) break;
- uint32 j = 0;
- for (; j < mvm::LockSystem::IndexSize; j++) {
- if (array[j] == NULL) break;
- mvm::FatLock* lock = array[j];
- mvm::Collector::markAndTraceRoot(lock->getAssociatedObjectPtr(), closure);
- }
- for (j = j + 1; j < mvm::LockSystem::IndexSize; j++) {
- assert(array[j] == NULL);
- }
- }
- for (i = i + 1; i < mvm::LockSystem::GlobalSize; i++) {
- assert(lockSystem.LockTable[i] == NULL);
- }
-}
-
-void JavaThread::tracer(uintptr_t closure) {
- mvm::Collector::markAndTraceRoot(&javaThread, closure);
- mvm::Collector::markAndTraceRoot(&vmThread, closure);
-
- JNILocalReferences* end = localJNIRefs;
- while (end != NULL) {
- for (uint32 i = 0; i < end->length; ++i) {
- mvm::gc** obj = end->localReferences + i;
- mvm::Collector::markAndTraceRoot(obj, closure);
- }
- end = end->prev;
- }
-}
diff --git a/vmkit/lib/J3/VMCore/Zip.cpp b/vmkit/lib/J3/VMCore/Zip.cpp
deleted file mode 100644
index 711034c..0000000
--- a/vmkit/lib/J3/VMCore/Zip.cpp
+++ /dev/null
@@ -1,240 +0,0 @@
-//===----------------- Zip.cpp - Interface with zlib ----------------------===//
-//
-// The VMKit project
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#include <zlib.h>
-
-#include "mvm/Allocator.h"
-
-#include "JavaArray.h"
-#include "Reader.h"
-#include "Zip.h"
-
-using namespace j3;
-
-ZipArchive::ZipArchive(ClassBytes* bytes, mvm::BumpPtrAllocator& A) : allocator(A) {
- this->bytes = bytes;
- findOfscd();
- if (ofscd > -1) addFiles();
-}
-
-ZipFile* ZipArchive::getFile(const char* filename) {
- table_iterator End = filetable.end();
- table_iterator I = filetable.find(filename);
- return I != End ? I->second : 0;
-}
-
-
-#define END_CENTRAL_DIRECTORY_FILE_HEADER_SIZE 18
-#define CENTRAL_DIRECTORY_FILE_HEADER_SIZE 42
-#define LOCAL_FILE_HEADER_SIZE 26
-
-#define C_FILENAME_LENGTH 24
-#define C_UCSIZE 20
-#define C_CSIZE 16
-#define C_EXTRA_FIELD_LENGTH 26
-#define C_FILE_COMMENT_LENGTH 28
-#define C_ROLH 38
-#define C_COMPRESSION_METHOD 6
-
-#define L_FILENAME_LENGTH 22
-#define L_EXTRA_FIELD_LENGTH 24
-
-#define E_OFFSET_START_CENTRAL_DIRECTORY 12
-#define HDR_ENDCENTRAL "PK\005\006"
-#define HDR_CENTRAL "PK\001\002"
-#define HDR_LOCAL "PK\003\004"
-#define PATH_SEPARATOR '/'
-#define ZIP_STORE 0
-#define ZIP_DEFLATE 8
-#define DEF_WBITS 15
-
-static uint32 readEndianDep4(Reader& reader) {
- uint8 one = reader.readU1();
- uint8 two = reader.readU1();
- uint8 three = reader.readU1();
- uint8 four = reader.readU1();
- return (one + (two << 8) + (three << 16) + (four << 24));
-}
-
-static uint16 readEndianDep2(Reader& reader) {
- uint8 one = reader.readU1();
- uint8 two = reader.readU1();
- return (one + (two << 8));
-}
-
-void ZipArchive::findOfscd() {
- sint32 curOffs = 0;
- sint32 minOffs = 0;
- sint32 st = END_CENTRAL_DIRECTORY_FILE_HEADER_SIZE + 4;
-
- Reader reader(bytes);
- curOffs = reader.max;
- if (curOffs >= (65535 + END_CENTRAL_DIRECTORY_FILE_HEADER_SIZE + 4)) {
- minOffs = curOffs - (65535 + END_CENTRAL_DIRECTORY_FILE_HEADER_SIZE + 4);
- } else {
- minOffs = 0;
- }
-
- while (curOffs > minOffs) {
- sint32 searchPos = 0;
- if (curOffs >= (1024 - st)) {
- curOffs = curOffs - (1024 - st);
- } else {
- curOffs = 0;
- }
- reader.cursor += curOffs;
-
- sint32 diff = reader.max - reader.cursor;
- sint32 temp = reader.cursor;
- if (diff > 1024) {
- searchPos = 1024;
- reader.cursor += 1024;
- } else {
- searchPos = diff;
- reader.cursor = reader.max;
- }
-
- if (searchPos >= st) {
- sint32 searchPtr = temp + (searchPos - st);
- while (searchPtr > temp) {
- if (bytes->elements[searchPtr] == 'P' &&
- !(memcmp(bytes->elements + searchPtr, HDR_ENDCENTRAL, 4))) {
- sint32 offset = searchPtr + 4 + E_OFFSET_START_CENTRAL_DIRECTORY;
- reader.cursor = offset;
- this->ofscd = readEndianDep4(reader);
- return;
- }
- }
- }
- }
- this->ofscd = -1;
-}
-
-void ZipArchive::addFiles() {
- sint32 temp = ofscd;
-
- Reader reader(bytes);
- reader.cursor = temp;
-
- while (true) {
- if (memcmp(bytes->elements + temp, HDR_CENTRAL, 4)) return;
- ZipFile* ptr = new(allocator, "ZipFile") ZipFile();
- reader.cursor = temp + 4 + C_COMPRESSION_METHOD;
- ptr->compressionMethod = readEndianDep2(reader);
-
- reader.cursor = temp + 4 + C_CSIZE;
-
- ptr->csize = readEndianDep4(reader);
- ptr->ucsize = readEndianDep4(reader);
- ptr->filenameLength = readEndianDep2(reader);
- ptr->extraFieldLength = readEndianDep2(reader);
- ptr->fileCommentLength = readEndianDep2(reader);
-
- reader.cursor = temp + 4 + C_ROLH;
- ptr->rolh = readEndianDep4(reader);
-
- temp = temp + 4 + CENTRAL_DIRECTORY_FILE_HEADER_SIZE;
-
- if ((ptr->filenameLength > 1024) ||
- (reader.max - temp) < ptr->filenameLength)
- return;
-
- ptr->filename = (char*)allocator.Allocate(ptr->filenameLength + 1,
- "Zip file name");
- memcpy(ptr->filename, bytes->elements + temp,
- ptr->filenameLength);
- ptr->filename[ptr->filenameLength] = 0;
-
- if (ptr->filename[ptr->filenameLength - 1] != PATH_SEPARATOR) {
- filetable.insert(std::make_pair(ptr->filename, ptr));
- }
-
- temp = temp + ptr->filenameLength + ptr->extraFieldLength +
- ptr->fileCommentLength;
- }
-}
-
-sint32 ZipArchive::readFile(ClassBytes* array, const ZipFile* file) {
- uint32 bytesLeft = 0;
- uint32 filenameLength = 0;
- uint32 extraFieldLength = 0;
- uint32 temp = 0;
-
- Reader reader(bytes);
- reader.cursor = file->rolh;
-
- if (!(memcmp(bytes->elements + file->rolh, HDR_LOCAL, 4))) {
- reader.cursor += 4;
- temp = reader.cursor;
- reader.cursor += L_FILENAME_LENGTH;
- filenameLength = readEndianDep2(reader);
- extraFieldLength = readEndianDep2(reader);
-
- reader.cursor =
- temp + extraFieldLength + filenameLength + LOCAL_FILE_HEADER_SIZE;
-
- if (file->compressionMethod == ZIP_STORE) {
- memcpy(array->elements, bytes->elements + reader.cursor, file->ucsize);
- return 1;
- } else if (file->compressionMethod == ZIP_DEFLATE) {
- z_stream stre;
- sint32 err = 0;
-
- bytesLeft = file->csize;
- stre.next_out = (Bytef*)array->elements;
- stre.avail_out = file->ucsize;
- stre.zalloc = 0;
- stre.zfree = 0;
-
- err = inflateInit2_(&stre, - DEF_WBITS, zlib_version, sizeof(z_stream));
-
- if (err != Z_OK) {
- return 0;
- }
-
- while (bytesLeft) {
- uint32 size = 0;
- stre.next_in = bytes->elements + reader.cursor;
- if (bytesLeft > 1024) size = 1024;
- else size = bytesLeft;
-
- uint32 diff = reader.max - reader.cursor;
- if (diff < size) {
- stre.avail_in = diff;
- reader.cursor = reader.max;
- } else {
- stre.avail_in = size;
- reader.cursor += size;
- }
-
- if (bytesLeft > size) {
- err = inflate(&stre, Z_PARTIAL_FLUSH);
- } else {
- err = inflate(&stre, Z_FINISH);
- }
-
- bytesLeft = bytesLeft - size;
- }
-
- inflateEnd(&stre);
-
- if ((err != Z_STREAM_END) &&
- (bytesLeft || err != Z_BUF_ERROR || stre.avail_out)) {
- return 0;
- } else {
- return 1;
- }
- } else {
- return 0;
- }
- } else {
- return 0;
- }
- return 0;
-}
diff --git a/vmkit/lib/J3/VMCore/Zip.h b/vmkit/lib/J3/VMCore/Zip.h
deleted file mode 100644
index ae7ae87..0000000
--- a/vmkit/lib/J3/VMCore/Zip.h
+++ /dev/null
@@ -1,81 +0,0 @@
-//===----------------- Zip.h - Interface with zlib ------------------------===//
-//
-// The VMKit project
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#ifndef JNJVM_ZIP_H
-#define JNJVM_ZIP_H
-
-#include <map>
-
-#include "mvm/Allocator.h"
-
-namespace j3 {
-
-class classBytes;
-class JnjvmBootstrapLoader;
-
-struct ZipFile : public mvm::PermanentObject {
- char* filename;
- int ucsize;
- int csize;
- uint32 filenameLength;
- uint32 extraFieldLength;
- uint32 fileCommentLength;
- int rolh;
- int compressionMethod;
-};
-
-
-
-class ZipArchive : public mvm::PermanentObject {
-
- mvm::BumpPtrAllocator& allocator;
-
- struct ltstr
- {
- bool operator()(const char* s1, const char* s2) const
- {
- return strcmp(s1, s2) < 0;
- }
- };
-
- int ofscd;
-
-public:
- std::map<const char*, ZipFile*, ltstr> filetable;
- typedef std::map<const char*, ZipFile*, ltstr>::iterator table_iterator;
- ClassBytes* bytes;
-
-private:
-
- void findOfscd();
- void addFiles();
-
- void remove();
-
-public:
-
- ~ZipArchive() {
- for (table_iterator I = filetable.begin(), E = filetable.end(); I != E;
- ++I) {
- allocator.Deallocate((void*)I->first);
- I->second->~ZipFile();
- allocator.Deallocate((void*)I->second);
- }
- }
-
- int getOfscd() { return ofscd; }
- ZipArchive(ClassBytes* bytes, mvm::BumpPtrAllocator& allocator);
- ZipFile* getFile(const char* filename);
- int readFile(ClassBytes* array, const ZipFile* file);
-
-};
-
-} // end namespace j3
-
-#endif
diff --git a/vmkit/lib/Makefile b/vmkit/lib/Makefile
deleted file mode 100644
index cdf5162..0000000
--- a/vmkit/lib/Makefile
+++ /dev/null
@@ -1,24 +0,0 @@
-##===- lib/Makefile ----------------------------------------*- Makefile -*-===##
-#
-# The vmkit project
-#
-# This file is distributed under the University of Illinois Open Source
-# License. See LICENSE.TXT for details.
-#
-##===----------------------------------------------------------------------===##
-LEVEL = ..
-
-PARALLEL_DIRS = Mvm
-
-include $(LEVEL)/Makefile.config
-
-ifeq ($(WITH_J3), 1)
-PARALLEL_DIRS += J3
-endif
-
-ifeq ($(WITH_N3), 1)
-PARALLEL_DIRS += N3
-endif
-
-include $(LEVEL)/Makefile.common
-
diff --git a/vmkit/lib/Mvm/Allocator/Makefile b/vmkit/lib/Mvm/Allocator/Makefile
deleted file mode 100644
index 021ce12..0000000
--- a/vmkit/lib/Mvm/Allocator/Makefile
+++ /dev/null
@@ -1,20 +0,0 @@
-##===- lib/Mvm/Allocator/Makefile --------------------------*- Makefile -*-===##
-#
-# The vmkit project
-#
-# This file is distributed under the University of Illinois Open Source
-# License. See LICENSE.TXT for details.
-#
-##===----------------------------------------------------------------------===##
-LEVEL = ../../..
-
-include $(LEVEL)/Makefile.config
-
-ifeq ($(WITH_LLVM_GCC), 1)
- MODULE_NAME = Allocator
-else
- LIBRARYNAME = Allocator
-endif
-
-include $(LEVEL)/Makefile.common
-
diff --git a/vmkit/lib/Mvm/Allocator/README.txt b/vmkit/lib/Mvm/Allocator/README.txt
deleted file mode 100644
index 6983f52..0000000
--- a/vmkit/lib/Mvm/Allocator/README.txt
+++ /dev/null
@@ -1,130 +0,0 @@
-##############################################################################
-#
-# Micro-VM Allocator
-# by Charles Clément, corrected by Gaël Thomas.
-#
-##############################################################################
-
-
-I Memory layout
- 1 Exponantial area
- 2 Linear area
- 3 Mmap area
-II Structure
- 1 Referencing memory chunks
- 2 Harsh tables
-III Internal memory management
-
-I Memory layout
-#--------------
-
-Based on the size of the objects to allocate, the allocator chooses between
-three distincts area.
-i) The exponantial area for objects less than max_exp bytes
-ii) The linear area for x in max_exp < x < max_lin bytes
-iii) The mmap area for LIN bytes < x
-
-Max_exp and max_lin are actually defined to 32 and 8192 bytes.
-
-I.1 Exponantial area:
-Objects stored in that area are allocated 2^n bytes, the smallest power of two
-in which the object can fit.
-
--------------------------------------
-| Size to allocate | reserved space |
--------------------------------------
- 1 2
- 2 2
- 3 4
- 4 4
- {5,6,7,8} 8
- {9-16} 16
- {17-32} 32
-
--> Size of allocated chunk in this area grows exponantially.
-With max_exp = 32 bytes
-
-I.2 Linear area:
-In the linear area, the size needed to be allocated is rounded to the next
-max_exp multiple. This is to reduce memory loss, as otherwise, with the
-previous technique allocating 260 bytes would induce to occupy a 512 bytes
-area.
-
- ------------------------------------
- | 32 | 64 | 96 | 128 | ...
- ------------------------------------
-
-max_exp*1 *2 *3 *4
-
--> Size of allocated chunk in this area grows linearly.
-
-I.3 Mmap area:
-For objects larger than 2^13 (8192) bytes, a number of physical page is
-associated, thus a multiplier of 4096 bytes.
-
-
-II Descriptors
-#-------------
-
-II.1 Hash tables:
-
-In order to keep track of allocated memory adresses, we need to store the
-adresses that we allocated. This is a requirement for the garbage collector, as
-the compatibility with the C ABI implies that a memory reference is
-indistinguishable from a value. Hence, every page descriptor is inserted in a
-hash table when allocated.
-This has a limitation, as it is not possible to make the difference between a
-value in the heap that would point to an actual allocated space in memory if
-translated into a pointer.
-
-
-II.2 Referencing memory chunks:
-Here is the representation of an adress in memory :
-
- ----------------------------------------------------------
-Pointer: | Table Entry | Page Descriptor | Index |
- ----------------------------------------------------------
- | __ | |
- | | | | |
- | |__| | |
- | | | GCHashSet \|/ |
- | |__| __ __ __ __ __ __ |
- --->| |----->|__|__|__|__|__|__| |
- |__| | |
- | | | GCPage \|/
- |__| | __ __ __ __ __ __
- GCHash ---->|__|__|__|__|__|__| Headers
-
-
-Memory is separated in spaces. Each space contains memory chunk of the same
-size. When the allocator needs to allocate n bytes, it choose a memory space
-in an exponential, linear or mmaped space and round n to the size of this
-space. This technique is used to construct a performant hashtable of all
-allocated memory chunks, which is used to identify pointer during a collection
-(the garbage collector is only conservative).
-
-The first bits of a memory chunk pointer reference an entry in GCHash, and
-the next bits reference an entry in GCHashSet. Each entry in GCHashSet is a
-GCPage structure, which describes a set of contiguous pages (a memory space).
-
-The GCPage Class holds a field (GCChunkNode*)_headers containing the list to
-all headers of free chunks of the space. It also holds the size of the space
-in _chunk_nbb. This size is the rounded size (exp or linear) of all memory
-chunks managed in this space.
-
-_Note_:
-This is not the case for space allocated in the mmap area, whose page
-descriptor holds directly the header itself.
-
-A header is described by the class GCChunkNode. It holds the size _nbb_mark of
-memory chunks in the last 29 bits (the 3 last ones are used by the garbage
-collector to set the *color* of the chunk). GCChunkNode are stored in a
-circular double linked list.
-
-
-III Internal memory management
-#-----------------------------
-
-The allocator has to allocate its memmory structures itself. It is responsible
-to allocate the memory for the micro-vm and the structures needed to manage
-and access the allocated areas.
diff --git a/vmkit/lib/Mvm/Allocator/gcalloc.cpp b/vmkit/lib/Mvm/Allocator/gcalloc.cpp
deleted file mode 100644
index 4f97c0f..0000000
--- a/vmkit/lib/Mvm/Allocator/gcalloc.cpp
+++ /dev/null
@@ -1,136 +0,0 @@
-//===--------------- gcalloc.cc - Mvm allocator ---------------------------===//
-//
-// Mvm
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#include "gcalloc.h"
-#include "types.h"
-
-GCChunkNode *GCAllocator::alloc_headers(uintptr_t headers_nbb, void *base,
- uintptr_t depl, uintptr_t filled) {
- GCChunkNode *headers;
- uintptr_t rounded = GCMappedArea::round(headers_nbb);
-
- if(headers_nbb == rounded)
- headers = (GCChunkNode *)(new GCMappedArea(&headers_area, rounded))->area();
- else {
- headers = used_headers;
- used_headers = (GCChunkNode *)((uintptr_t)used_headers + headers_nbb);
- if(used_headers >= max_headers) {
- headers = (GCChunkNode *)(new GCMappedArea(&headers_area, used_headers_nbb))->area();
- used_headers = (GCChunkNode *)((uintptr_t)headers + headers_nbb);
- max_headers = (GCChunkNode *)((uintptr_t)headers + used_headers_nbb);
- }
- }
-
- register GCChunkNode *cur = headers;
- register GCChunkNode *lim = (GCChunkNode *)((uintptr_t)headers + headers_nbb);
- register GCChunkNode *max = lim - (1 + filled);
- for(;cur<max; cur++) {
- cur->initialise(cur+1, base);
- base = (void *)((uintptr_t)base + depl);
- }
- for(;cur<lim; cur++) {
- cur->initialise(0, base);
- base = (void *)((uintptr_t)base + depl);
- }
- return headers;
-}
-
-GCChunkNode *GCAllocator::alloc_list(GCFreeList *fl, uintptr_t n) {
- GCChunkNode *headers;
- uintptr_t area_nbb;
- void *area_ptr;
- GCPage *page;
-
- if(GCFreeListFinder::isMmaped(n)) {
- area_nbb = GCMappedArea::round(n);
-
- /* on alloue un Descripteur */
- page = new GCDescriptorMappedChunk(&normal_area, area_nbb, area_nbb);
- area_ptr = page->area();
-
- headers = page->headers();
- } else {
- uintptr_t chunk_nbb = fl->chunk_nbb();
-
- /* on alloue un Descripteur */
- page = new GCPage(&normal_area, area_nbb = fl->area_nbb(), chunk_nbb);
-
- area_ptr = page->area();
-
- /* on alloue des headers */
- headers = alloc_headers(fl->headers_nbb(), area_ptr, chunk_nbb, fl->filled());
-
- page->headers(headers);
- }
-
- /* on hash notre nouveau chunk */
- GCHash::hash_unprotected(page, area_ptr, area_nbb, area_nbb);
-
- fl->list(headers);
- return headers;
-}
-
-#define min(a, b) ((a) < (b) ? (a) : (b))
-#define max(a, b) ((a) < (b) ? (b) : (a))
-
-GCFreeListFinder::GCFreeListFinder() {
- unsigned int i, j, m;
- GCFreeList *cur;
-
- for(i=0; i<=min_exp; i++)
- exp_lists[i] = _exp_lists;
- _exp_lists[0].initialise(min_exp, 128*min_exp);
-
- for(i=min_exp_log, cur=_exp_lists+1; i<max_exp_log; i++, cur++) {
- m = 1 << (i + 1);
- cur->initialise(m, 512*m);
- for(j=1<<i; j<m; j++)
- exp_lists[j+1] = cur;
- }
-
- for(i=0;i<nb_lin; i++) {
- m = ((i+1)<<lin_step_log) + max_exp;
- lin_lists[i].initialise(m, min(128*m, 65536));
- }
-
- // for(i=0; i<max_lin+2; i++)
- // printf("%d => %d\n", i, find(i)->chunk_nbb());
-}
-
-
-GCAllocator::GCAllocator() {
- used_headers = 0;
- max_headers = 0;
- GCHash::initialise();
-}
-
-GCAllocator::~GCAllocator() {
- GCMappedArea *cur;
-
- for(cur=normal_area.next(); cur!=&normal_area; cur=cur->next())
- delete cur->munmap();
-
- for(cur=headers_area.next(); cur!=&headers_area; cur=cur->next())
- delete cur->munmap();
-
- for(cur=mapped_area.next(); cur!=&mapped_area; cur=cur->next())
- delete cur->munmap();
- GCHash::unlink();
-}
-
-void *GCAllocator::operator new(uintptr_t req) {
- uintptr_t nbb = GCMappedArea::round(req);
- GCAllocator *res = (GCAllocator *)GCMappedArea::do_mmap(nbb);
- res->my_size = nbb;
- return res;
-}
-
-void GCAllocator::operator delete(void *ptr) {
- GCMappedArea::do_munmap(ptr, ((GCAllocator *)ptr)->my_size);
-}
diff --git a/vmkit/lib/Mvm/Allocator/gcalloc.h b/vmkit/lib/Mvm/Allocator/gcalloc.h
deleted file mode 100644
index 4c03271..0000000
--- a/vmkit/lib/Mvm/Allocator/gcalloc.h
+++ /dev/null
@@ -1,204 +0,0 @@
-//===---------------- gcalloc.h - Mvm allocator ---------------------------===//
-//
-// Mvm
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#ifndef _GC_ALLOC_H_
-#define _GC_ALLOC_H_
-
-#include <string.h> /* memset */
-
-#include "gcchunk.h"
-#include "types.h"
-
-class GCFreeList {
- GCChunkNode *_list;
- uintptr_t _chunk_nbb;
- uintptr_t _area_nbb;
- uintptr_t _nb_chunks;
- uintptr_t _headers_nbb;
- uintptr_t _filled;
-public:
- inline GCFreeList() { _chunk_nbb = 0; _nb_chunks = 1; }
-
- inline void initialise(uintptr_t n, uintptr_t area) {
- _list = 0;
- _chunk_nbb = n;
- _area_nbb = GCMappedArea::round(area); /* taille en pages utilisée pour une free-list */
- _nb_chunks = _area_nbb/_chunk_nbb; /* nombre de type que je peux caser la dedans */
- /* est-ce qu'il reste de la place derière ? */
- _filled = (_nb_chunks * _chunk_nbb) == _area_nbb ? 0 : 1;
- /* j'utilise un "faux header" à 0 pour completer ce truc */
- _headers_nbb = (_nb_chunks + _filled)*sizeof(GCChunkNode);
- }
-
- inline GCChunkNode *list() { return _list; }
- inline void list(GCChunkNode *l) { _list = l; }
- inline uintptr_t nb_chunks() { return _nb_chunks; }
- inline uintptr_t chunk_nbb() { return _chunk_nbb; }
- inline uintptr_t area_nbb() { return _area_nbb; }
- inline uintptr_t headers_nbb() { return _headers_nbb; }
- inline uintptr_t filled() { return _filled; }
-
- inline void reject(GCChunkNode *header) {
- header->next(_list);
- _list = header;
- }
-};
-
-class GCFreeListFinder {
- /* trois zones distinctes: exponentielle/lineaire/mmap */
- static const unsigned int min_exp_log = 0; /* 0 -> 4 => 4 */
- static const unsigned int max_exp_log = 5; /* 4 -> 32 en exponentielle */
- static const unsigned int max_lin_log = 13; /* 32 -> 128 en linéaire */
- static const unsigned int lin_step_log = 4; /* par pas de 4 */
- static const unsigned int min_exp = 1 << min_exp_log;
- static const unsigned int max_exp = 1 << max_exp_log;
- static const unsigned int max_lin = 1 << max_lin_log;
- static const unsigned int nb_exp = max_exp_log - min_exp_log + 1;
- static const unsigned int nb_lin = (max_lin - max_exp)>>lin_step_log;
-
- GCFreeList _exp_lists[nb_exp];
- GCFreeList *exp_lists[max_exp+1];
- GCFreeList lin_lists[nb_lin];
- GCFreeList mmap_list;
-
- inline uintptr_t linEntry(uintptr_t n) { return (n - max_exp - 1)>>lin_step_log; }
-public:
- GCFreeListFinder();
-
- static inline bool isMmaped(uintptr_t n) { return n>max_lin; }
-
- inline GCFreeList *find(uintptr_t n) {
- return isMmaped(n) ? &mmap_list : (n>max_exp) ? lin_lists + linEntry(n) : exp_lists[n];
- }
-};
-
-class GCAllocator {
- static const unsigned int used_headers_nbb = (PAGE_SIZE + (4096*sizeof(GCChunkNode)) - 1) & -PAGE_SIZE;
-
- uintptr_t my_size;
- GCFreeListFinder undefined_finder;
- GCFreeListFinder zero_filled_finder;
-
- GCMappedArea normal_area; /* area pour les petit chunk */
- GCMappedArea mapped_area; /* pour les gros */
- GCMappedArea headers_area; /* liste des mmap des headers */
- GCChunkNode *used_headers; /* une liste de headers pour les prochaines alloc_list */
- GCChunkNode *max_headers; /* la limite */
-
- GCChunkNode *alloc_headers(uintptr_t, void *, uintptr_t, uintptr_t);
- GCChunkNode *alloc_list(GCFreeList *, uintptr_t);
-public:
- GCAllocator();
- ~GCAllocator();
-
- void *operator new(uintptr_t);
- void operator delete(void *);
-
- inline GCPage *o2page(void *ptr) { return GCHash::get(ptr); }
-
- inline GCChunkNode *alloc_chunk(uintptr_t n, bool isCol, unsigned int m) {
- GCFreeList *fl = undefined_finder.find(n);
- register GCChunkNode *res = fl->list();
-
- if(!res)
- res = alloc_list(fl, n);
-
- fl->list(res->next());
- res->nbb(n, isCol, m);
-
- return res;
- }
-
- inline void reject_chunk(GCPage *page, GCChunkNode *header) {
- GCFreeList *fl = undefined_finder.find(page->chunk_nbb());
-
- if(fl->chunk_nbb()) {
- // printf("0 Filled %p with %d bytes\n", header->chunk(), header->nbb());
- memset(header->chunk(), 0, header->nbb());
- header->free();
- fl->reject(header);
- } else {
- GCHash::hash_unprotected(page, page->area(), page->nbb(), 0);
- page->reject();
- delete (GCPage *)(page->munmap());
- }
- }
-
- inline void reject_chunk(GCChunkNode *header) {
- reject_chunk(o2page(header->chunk()), header);
- }
-
- inline GCChunkNode *stupid_realloc_chunk(GCChunkNode *old_header, uintptr_t new_nbb) {
- GCChunkNode *new_header = alloc_chunk(new_nbb, old_header->isCollectable(), old_header->mark());
- uintptr_t old = old_header->nbb();
- uintptr_t nbb = old < new_nbb ? old : new_nbb;
- memcpy(new_header->chunk(), old_header->chunk(), nbb);
- return new_header;
- }
-
- inline GCChunkNode *realloc_chunk(GCPage *page, GCChunkNode *old_header, uintptr_t new_nbb) {
- GCChunkNode *new_header = old_header;
- uintptr_t max_nbb = page->chunk_nbb();
-
- if(GCFreeListFinder::isMmaped(max_nbb))
- if(GCFreeListFinder::isMmaped(new_nbb)) {
- /* le plus compliqué, on essaye de faire un mremap d'un petit bout... */
- uintptr_t rounded = GCMappedArea::round(new_nbb);
- uintptr_t old_nbb = page->nbb();
- signed int depl = rounded - page->nbb();
- if(depl) {
- if(page->mremap(rounded) == -1) /* perdu */
- return new_header = stupid_realloc_chunk(old_header, new_nbb);
- else {
- if(depl > 0)
- GCHash::hash_unprotected(page, (void *)((uintptr_t)page->area() + old_nbb), depl, depl);
- else
- GCHash::hash_unprotected(page, (void *)((uintptr_t)page->area() + rounded), -depl, 0);
- }
- }
- page->chunk_nbb(rounded);
- old_header->nbb(new_nbb);
- } else
- new_header = stupid_realloc_chunk(old_header, new_nbb);
- else
- if(new_nbb <= max_nbb)
- old_header->nbb(new_nbb);
- else
- new_header = stupid_realloc_chunk(old_header, new_nbb);
- return new_header;
- }
-
- inline void *alloc(uintptr_t sz) { return alloc_chunk(sz, 0, 0)->chunk(); }
-
- inline void free(void *ptr) {
- GCPage *page = o2page(ptr);
- GCChunkNode *header = page->o2node(ptr, GCChunkNode::maskNotCollectable);
-
- if(!header)
- gcfatal("%p isn't an object", ptr);
-
- reject_chunk(page, header);
- }
-
- inline void *realloc(void *ptr, uintptr_t nbb) {
- GCPage *page = o2page(ptr);
- GCChunkNode *header = page->o2node(ptr, GCChunkNode::maskNotCollectable);
-
- if(!header)
- gcfatal("%p isn't an object", header);
-
- register GCChunkNode *new_header = realloc_chunk(page, header, nbb);
- if(new_header != header)
- reject_chunk(page, header);
-
- return new_header->chunk();
- }
-};
-
-#endif
diff --git a/vmkit/lib/Mvm/Allocator/gcchunk.cpp b/vmkit/lib/Mvm/Allocator/gcchunk.cpp
deleted file mode 100644
index 4c01eef..0000000
--- a/vmkit/lib/Mvm/Allocator/gcchunk.cpp
+++ /dev/null
@@ -1,114 +0,0 @@
-//===---------------- gcchunk.cc - Mvm allocator --------------------------===//
-//
-// Mvm
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#include "gcchunk.h"
-
-
-GCHashSet *GCHash::sets[GCHashConst::nb_set_per_hash];
-unsigned int GCHash::used[GCHashConst::nb_set_per_hash];
-GCHashSet GCHash::empty;
-bool GCHash::inited = 0;
-size_t GCHash::nb_link = 0;
-
-GCChunkNode GCPage::empty;
-
-GCPage GCHashSet::empty;
-
-void GCHashSet::hash(GCPage *d, void *base, size_t nbb, size_t nbb_map, unsigned int *c) {
- register unsigned int entry = GCHashConst::desc_entry(base);
- register unsigned int pbase = entry << PAGE_SHIFT;
- register unsigned int top_del = (pbase + nbb) >> PAGE_SHIFT;
- register unsigned int top_add = (pbase + nbb_map) >> PAGE_SHIFT;
-
- // printf(" %p Hash from %d to %d and to %d\n", this, entry, top_add, top_del);
- for(; entry<top_add; entry++) {
- pages[entry] = d;
- (*c)++;
- }
- for(; entry<top_del; entry++) {
- pages[entry] = ∅
- (*c)--;
- }
-}
-
-void GCHash::hash_unprotected(GCPage *desc, void *base, unsigned int nbb, unsigned int nbb_map) {
- uintptr_t entry = GCHashConst::set_entry(base);
- uintptr_t cur_sz = GCHashConst::set_entry_2_ptr(entry + 1) - (uintptr_t)base; /* taille restante */
- cur_sz = ((cur_sz < nbb) ? cur_sz : nbb); /* on prends le min avec nbb */
-
- // printf("Hash %p (%p %p %d) in entry %d with %d/%d\n", desc, desc->area(), base, desc->nbb(), entry, cur_sz, nbb_map);
- while(cur_sz) {
- if(sets[entry] == &empty)
- sets[entry] = new GCHashSet();
-
- sets[entry]->hash(desc, base, cur_sz, (nbb_map > cur_sz) ? cur_sz : nbb_map, used + entry);
-
- if(!used[entry]) {
- delete sets[entry];
- sets[entry] = ∅
- }
- entry++;
- base = (void *)((uintptr_t)base + cur_sz);
- nbb -= cur_sz;
- nbb_map = (nbb_map < cur_sz) ? 0 : nbb_map - cur_sz;
- cur_sz = (nbb < GCHashConst::set_nbb) ? nbb : GCHashConst::set_nbb;
- }
-}
-
-void GCPage::initialise() {
- empty.initialise(0, 0);
-}
-
-GCHashSet::GCHashSet() {
- unsigned int i;
-
- for(i=0; i<GCHashConst::nb_desc_per_set; i++)
- pages[i] = ∅
-}
-
-void GCHash::initialise() {
- if(!inited) {
- inited = 1;
- GCMinAlloc::initialise();
-
- unsigned int i;
-
- for(i=0; i<GCHashConst::nb_set_per_hash; i++) {
- sets[i] = ∅
- used[i] = 0;
- }
- GCPage::initialise();
- }
- nb_link++;
-}
-
-void GCHash::destroy() {
- if(inited) {
- if(nb_link)
- gcwarning2("Can't destroy GC hash map: you have clients connected on it\n");
- else {
- inited = 0;
- unsigned int i;
-
- for(i=0; i<GCHashConst::nb_set_per_hash; i++)
- if(sets[i] != &empty)
- delete sets[i];
-
- GCMinAlloc::destroy();
- }
- }
-}
-
-void *GCHashSet::operator new(size_t sz) {
- return (void *)GCMappedArea::do_mmap(sz);
-}
-
-void GCHashSet::operator delete(void *ptr, size_t sz) {
- GCMappedArea::do_munmap(ptr, sz);
-}
diff --git a/vmkit/lib/Mvm/Allocator/gcchunk.h b/vmkit/lib/Mvm/Allocator/gcchunk.h
deleted file mode 100644
index ec3761c..0000000
--- a/vmkit/lib/Mvm/Allocator/gcchunk.h
+++ /dev/null
@@ -1,215 +0,0 @@
-//===---------------- gcchunk.h - Mvm allocator ---------------------------===//
-//
-// Mvm
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#ifndef _GC_CHUNK_H_
-#define _GC_CHUNK_H_
-
-//#include "mvm/VirtualMachine.h"
-//#include "mvm/GC.h"
-
-#include "gcmapper.h"
-#include "types.h"
-
-namespace mvm {
- class gcRoot;
-}
-
-using namespace mvm;
-
-/* description d'un bout de mémoire */
-class GCChunkNode {
- GCChunkNode *_prev; /* bit 0-1: l'age, les autres: le previous */
- GCChunkNode *_next;
- void * _chunk;
- uintptr_t _nbb_mark; /* nbb = 0 <=> ce chunk est libre */
- /* bit 0-2: la marque */
- /* bit 3: est-on collectable */
-public:
- static const signed int maskCollectable = 8;
- static const signed int maskNotCollectable = 0;
-
- inline GCChunkNode() {}
- inline ~GCChunkNode() {}
-
- inline gcRoot * chunk() { return (gcRoot*)_chunk; }
-
- inline GCChunkNode * next() { return _next; }
- inline void next(GCChunkNode *n) { _next = n; }
-
- inline GCChunkNode * prev() { return _prev; }
- inline GCChunkNode * prev(GCChunkNode *p) { return _prev = p; }
-
- inline void free() { _nbb_mark = 0; }
-
- inline void nbb(uintptr_t n, bool isCol, int m) { _nbb_mark = (n << 4) | ((isCol & 0x1) << 3) | m; }
- inline void nbb(uintptr_t n) { _nbb_mark = (n << 4) | (_nbb_mark & 0xf); }
- inline uintptr_t nbb() { return _nbb_mark >> 4; }
-
- /* pas de verification de debordement!!!! */
- inline void _mark(unsigned int m) { _nbb_mark = m | (_nbb_mark & -8); }
- inline unsigned int mark() { return _nbb_mark & 7; }
-
- inline signed int isCollectable() { return _nbb_mark & 8; }
-
- inline void initialise(GCChunkNode *n, void *c) {
- _chunk = c;
- _next = n;
- _nbb_mark = 0;
- }
-
- /* pour faire une amorce de liste */
- inline void alone() { _prev = _next = this; }
-
- /* ajoute this à p */
- inline void append(GCChunkNode *p) {
- _prev = p;
- _next = p->_next;
- p->_next = this;
- _next->_prev = this;
- }
-
- /* ajoute this à p */
- inline void prepend(GCChunkNode *p) {
- _next = p;
- _prev = p->_prev;
- p->_prev = this;
- _prev->_next = this;
- }
-
- /* enleve this de sa liste */
- inline void remove() {
- _next->_prev = _prev;
- _prev->_next = _next;
- }
-
- /* place la liste de p dans this. Ecrase celle de p */
- inline void attrape(GCChunkNode *l) {
- if(l == l->_next)
- alone();
- else {
- (_next = l->_next)->_prev = this;
- (_prev = l->_prev)->_next = this;
- l->alone();
- }
- }
-
- /* ajoute la liste de l dans this */
- inline void eat(GCChunkNode *l) {
- if(l != l->_next) {
- (_next->_prev = l->_prev)->_next = _next;
- (_next = l->_next)->_prev = this;
- l->alone();
- }
- }
-};
-
-/* entete de description de zone mémoire */
-/* une zone est un ensemble de bouts de mémoire de même taille, contigues, aligné sur des pages */
-class GCPage : public GCMappedArea {
- static GCChunkNode empty;
-
- GCChunkNode *_headers;
- uintptr_t _chunk_nbb;
-public:
- static void initialise();
-
- inline GCPage() {
- GCMappedArea::initialise(0, 0);
- _headers = ∅
- _chunk_nbb = ((unsigned int)-1) >> 1; /* on évite le /0 */
- }
-
- inline GCPage(GCMappedArea *p, uintptr_t mapped_nbb, uintptr_t cnbb)
- : GCMappedArea(p, mapped_nbb) {
- _chunk_nbb = cnbb;
- }
-
- inline ~GCPage() {} /* FAIRE LE UNMAP A LA MAIN!!!!! */
-
- inline uintptr_t chunk_nbb() { return _chunk_nbb; }
- inline void chunk_nbb(uintptr_t n) { _chunk_nbb = n; }
- inline GCChunkNode *headers() { return _headers; }
- inline void headers(GCChunkNode *h) { _headers = h;; }
-
- inline GCChunkNode *o2node(void *ptr, signed int mask) {
- register uintptr_t entry = ((uintptr_t)ptr - (uintptr_t)area())/_chunk_nbb;
- register GCChunkNode *res = _headers + entry;
- return ((uintptr_t)ptr - (uintptr_t)res->chunk() < res->nbb())
- && (res->isCollectable() == mask)
- ? res : 0;
- }
-
- inline gcRoot *o2header(void *ptr, signed int mask) {
- register uintptr_t entry = ((uintptr_t)ptr - (uintptr_t)area())/_chunk_nbb;
- register GCChunkNode *res = _headers + entry;
- return ((uintptr_t)ptr - (uintptr_t)res->chunk() < res->nbb())
- && (res->isCollectable() == mask)
- ? res->chunk() : 0;
- }
-};
-
-class GCDescriptorMappedChunk : public GCPage {
- GCChunkNode header;
-public:
- inline GCDescriptorMappedChunk(GCMappedArea *p, uintptr_t mapped_nbb, uintptr_t cnbb)
- : GCPage(p, mapped_nbb, cnbb) {
- header.initialise(0, area());
- headers(&header);
- }
-};
-
-class GCHashConst {
-public:
- static const unsigned int desc_bits = PAGE_SHIFT;
- static const unsigned int set_bits = 10;
- static const unsigned int hash_bits = (32 - set_bits - desc_bits);
- static const unsigned int nb_desc_per_set = 1 << set_bits;
- static const unsigned int nb_set_per_hash = 1 << hash_bits;
- static const unsigned int set_nbb = 1 << (set_bits + desc_bits);
-
- static uintptr_t desc_entry(void * ptr) { return ((uintptr_t)ptr >> desc_bits) & (( 1 << set_bits) - 1); }
- static uintptr_t set_entry(void *ptr) { return (uintptr_t)ptr >> (set_bits + desc_bits); }
- static uintptr_t set_entry_2_ptr(uintptr_t entry) { return entry << (set_bits + desc_bits); }
-};
-
-class GCHashSet {
- static GCPage empty;
-
- GCPage *pages[GCHashConst::nb_desc_per_set];
-public:
- void *operator new(uintptr_t);
- void operator delete(void *, uintptr_t);
-
- GCHashSet();
-
- void hash(GCPage *, void *, uintptr_t, uintptr_t, unsigned int *);
-
- inline GCPage *get(void *ptr) { return pages[GCHashConst::desc_entry(ptr)]; }
-};
-
-class GCHash {
- static GCHashSet *sets[GCHashConst::nb_set_per_hash];
- static unsigned int used[GCHashConst::nb_set_per_hash];
- static GCHashSet empty;
- static bool inited;
- static uintptr_t nb_link;
-
-public:
- static void unlink() { nb_link--; }
- static void initialise();
- static void destroy();
-
- static void hash_unprotected(GCPage *p, void *base, unsigned int nbb, unsigned int nbb_map);
- //void hash(GCPage *p) { hash(p, p->area(), p->nbb(), p->nbb()); }
- //void unhash(GCPage *p) { hash(p, p->area(), p->nbb(), 0); }
-
- static inline GCPage *get(void *ptr) { return sets[GCHashConst::set_entry(ptr)]->get(ptr); }
-};
-
-#endif
diff --git a/vmkit/lib/Mvm/Allocator/gcerror.cpp b/vmkit/lib/Mvm/Allocator/gcerror.cpp
deleted file mode 100644
index 56a7635..0000000
--- a/vmkit/lib/Mvm/Allocator/gcerror.cpp
+++ /dev/null
@@ -1,36 +0,0 @@
-//===--------------- gcerror.cc - Mvm allocator ---------------------------===//
-//
-// Mvm
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#include "gcerror.h"
-#include <stdarg.h>
-#include "osdep.h"
-
-static void __gcfatal(const char *file, unsigned int l, const char *func, const char *msg, ...)
-{
- va_list va;
- va_start(va, msg);
- fprintf(stderr, "GC[error] in %s line %d (function %s)\n", file, l, func);
- vfprintf(stderr, msg, va);
- fprintf(stderr, "\n");
- va_end(va);
- exit(0);
-}
-
-static void _on_fatal() {}
-
-void (*_gcfatal)(const char *, unsigned int l, const char *, const char *, ...) = __gcfatal;
-void (*on_fatal)(void) = _on_fatal;
-
-static void _defaultOnMemoryError(unsigned int sz)
-{
- fprintf(stderr, "GC[error] out of memory for %d bytes\n", sz);
- exit(0);
-}
-
-void (*onMemoryError)(unsigned int) = _defaultOnMemoryError;
diff --git a/vmkit/lib/Mvm/Allocator/gcerror.h b/vmkit/lib/Mvm/Allocator/gcerror.h
deleted file mode 100644
index ca34886..0000000
--- a/vmkit/lib/Mvm/Allocator/gcerror.h
+++ /dev/null
@@ -1,38 +0,0 @@
-//===---------------- gcerror.h - Mvm allocator ---------------------------===//
-//
-// Mvm
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#ifndef _GC_ERROR_H_
-#define _GC_ERROR_H_
-
-
-extern void (*_gcfatal)(const char *, unsigned int l, const char *, const char *, ...);
-
-extern void (*on_fatal)(void);
-
-extern void (*onMemoryError)(unsigned int sz);
-
-#define gcfatal(msg, args...) do { \
- on_fatal(); \
- (*_gcfatal)(__FILE__, __LINE__, __PRETTY_FUNCTION__, msg, ##args); \
- } while(0)
-
-#define gcwarning(msg, args...) do { \
- printf("In %s (%s line %d):\n\t", __PRETTY_FUNCTION__, __FILE__, __LINE__); \
- printf(msg, ##args); \
- } while(0)
-
-#define gcwarning2(msg) do { \
- printf("In %s (%s line %d):\n\t", __PRETTY_FUNCTION__, __FILE__, __LINE__); \
- printf(msg); \
- } while(0)
-
-
-#endif
-
-
diff --git a/vmkit/lib/Mvm/Allocator/gcmapper.cpp b/vmkit/lib/Mvm/Allocator/gcmapper.cpp
deleted file mode 100644
index 1df399f..0000000
--- a/vmkit/lib/Mvm/Allocator/gcmapper.cpp
+++ /dev/null
@@ -1,138 +0,0 @@
-//===--------------- gcmapper.cc - Mvm allocator ---------------------------===//
-//
-// Mvm
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#include "gcmapper.h"
-#include <string.h>
-#include <sys/mman.h>
-#include <errno.h>
-#include <fcntl.h>
-#include <unistd.h>
-
-
-GCMinAllocStack GCMinAlloc::_stacks[GCMinAlloc::max_min_alloc >> log_step];
-GCMinAllocStack *GCMinAlloc::stacks[GCMinAlloc::max_min_alloc+1];
-GCMappedArea GCMinAlloc::base_area;
-
-
-
-#if defined(__MACH__)
-#define DO_MMAP(sz) mmap(0, sz, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON, -1, 0)
-#else
-#define DO_MMAP(sz) mmap(0, sz, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, 0, 0)
-#endif
-
-#define DO_MUNMAP(ptr, sz) munmap(ptr, sz)
-
-#if defined(__MACH__)
-static inline void* manual_mremap(void * addr, int old_size, int new_size, int flags)
-{
- void * res = addr;
- if (new_size < old_size)
- DO_MUNMAP((void*)((intptr_t)addr + new_size), old_size - new_size);
- else if (new_size > old_size)
- // Use of MAP_FIXED is discouraged...
- // res = mmap(addr, new_size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON, -1, MAP_FIXED);
- res=(void*)-1;
-
- return res;
-}
-#endif
-
-static inline void *do_mmap(size_t sz) {
- void *res = DO_MMAP(sz);
- //printf("mmap %d bytes at %d\n", sz, res);
- if(res == MAP_FAILED) {
- if (errno == ENOMEM)
- (*onMemoryError)(sz);
- else
- {
- gcfatal("unable to mmap %d bytes", sz);
- }
- }
- return res;
-}
-
-static inline void do_munmap(void *ptr, size_t sz) {
- // printf("munmap %d bytes at %p\n", sz, ptr);
- DO_MUNMAP(ptr, sz);
-}
-
-void *GCMappedArea::do_mmap(size_t sz) { return ::do_mmap(sz); }
-void GCMappedArea::do_munmap(void *ptr, size_t sz) { ::do_munmap(ptr, sz); }
-
-GCMappedArea *GCMappedArea::munmap() {
- ::do_munmap(_mapped_area, _mapped_nbb);
- return this;
-}
-
-GCMappedArea *GCMappedArea::mmap(size_t n) {
- _mapped_area = ::do_mmap(_mapped_nbb = n);
- return this;
-}
-
-int GCMappedArea::mremap(size_t n) {
-#if defined(__MACH__)
- void *res = manual_mremap(_mapped_area, _mapped_nbb, n, 0);
-#else
- void *res = ::mremap(_mapped_area, _mapped_nbb, n, 0);
-#endif
-
- if((intptr_t)res == -1)
- return -1;
- _mapped_area = res;
- _mapped_nbb = n;
- return 0;
-}
-
-void *GCMinAlloc::alloc_area(GCMinAllocStack *s) {
- GCMinAllocStack *area_stack = stacks[sizeof(GCMappedArea)];
- GCMappedArea *area = (GCMappedArea *)area_stack->alloc();
-
- if(!area) {
- /* pbm : on n'a vraiment plus rien :) */
- area = (GCMappedArea *)::do_mmap(PAGE_SIZE);
- area->initialise(area, PAGE_SIZE);
- area_stack->fill((uintptr_t)(area + 1), PAGE_SIZE - sizeof(GCMappedArea));
- area->append(&base_area);
- area = (GCMappedArea *)area_stack->alloc();
- }
- area->mmap(PAGE_SIZE);
- area->append(&base_area);
- s->fill((uintptr_t)area->area(), area->nbb());
-
- return s->alloc();
-}
-
-void GCMinAlloc::initialise() {
- unsigned int i, j, m;
- size_t nb_stacks = max_min_alloc >> log_step;
-
- stacks[0] = _stacks;
- for(i=0; i<nb_stacks; i++) {
- m = i<<log_step;
- _stacks[i].initialise(m + (1<<log_step));
- for(j=0; j<(1<<log_step); j++)
- stacks[m+j+1] = _stacks + i;
- }
-}
-
-void GCMinAlloc::destroy() {
- unsigned int nb_area, i;
- GCMappedArea *cur;
-
- for(nb_area=0, cur=base_area.next(); cur!=&base_area; cur=cur->next(), nb_area++) {}
-
- GCMappedArea* areas = (GCMappedArea*)alloca(sizeof(GCMappedArea) * nb_area);
-
- for(i=0, cur=base_area.next(); cur!=&base_area; cur=cur->next(), i++)
- areas[i] = *cur;
-
- for(i=0; i<nb_area; i++)
- areas[i].munmap();
-}
diff --git a/vmkit/lib/Mvm/Allocator/gcmapper.h b/vmkit/lib/Mvm/Allocator/gcmapper.h
deleted file mode 100644
index bb597c0..0000000
--- a/vmkit/lib/Mvm/Allocator/gcmapper.h
+++ /dev/null
@@ -1,147 +0,0 @@
-//===--------------- gcmapper.h - Mvm allocator ---------------------------===//
-//
-// Mvm
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#ifndef _GC_MAPPER_H_
-#define _GC_MAPPER_H_
-
-#include "gcerror.h"
-#include "osdep.h"
-#include "types.h"
-
-class GCMinAlloc;
-
-class GCMin {
-public:
- inline GCMin() {}
- inline ~GCMin() {}
- inline void *operator new(uintptr_t);
- inline void operator delete(void *, uintptr_t);
-};
-
-class GCMappedArea : public GCMin {
- GCMappedArea *_prev;
- GCMappedArea *_next;
- void *_mapped_area;
- uintptr_t _mapped_nbb;
-
-public:
- static uintptr_t round(uintptr_t n) { return (n + PAGE_SIZE - 1) & -PAGE_SIZE; }
-
- GCMappedArea *prev() { return _prev; }
- GCMappedArea *next() { return _next; }
-
- inline GCMappedArea() { _prev = _next = this; }
- inline explicit GCMappedArea(uintptr_t n) { _prev = _next = this; mmap(n); }
- inline GCMappedArea(GCMappedArea *p, uintptr_t n) { append(p); mmap(n); }
-
- inline void initialise(void *p, uintptr_t n) { _mapped_area = p; _mapped_nbb = n; }
- inline uintptr_t nbb() const { return _mapped_nbb; }
- inline void *area() { return _mapped_area; }
-
- inline void append(GCMappedArea *p) {
- _prev = p;
- _next = p->_next;
- p->_next = this;
- _next->_prev = this;
- }
-
- inline void reject() {
- _prev->_next = _next;
- _next->_prev = _prev;
- }
-
- GCMappedArea * munmap();
- GCMappedArea * mmap(uintptr_t sz);
- int mremap(uintptr_t sz);
-
- static void *do_mmap(uintptr_t sz);
- static void do_munmap(void *, uintptr_t sz);
-};
-
-class GCMinAllocStack {
- uintptr_t current;
- uintptr_t max;
- uintptr_t *free_list;
- unsigned short nbb;
-
-public:
- inline void initialise(uintptr_t n) { nbb = n; current = max = 0; free_list = 0; }
-
- inline void fill(uintptr_t st, uintptr_t n) {
- current = st;
- max = st + n;
- }
-
- inline void inject_free(void *ptr) {
- *((uintptr_t **)ptr) = free_list;
- free_list = (uintptr_t *)ptr;
- }
-
- inline void *alloc() {
- register uintptr_t res;
- if(free_list) {
- res = (uintptr_t)free_list;
- free_list = *((uintptr_t **)res);
- } else {
- res = current;
- current += nbb;
- if(current > max)
- return 0;
- }
-
- return (void*)res;
- }
-};
-
-class GCMinAlloc {
- static const uintptr_t log_max_min_alloc = 6; /* 64 octets */
- static const uintptr_t max_min_alloc = (1 << log_max_min_alloc);
- static const uintptr_t log_step = 2;
-
- /* piles d'allocations */
- static GCMinAllocStack _stacks[max_min_alloc >> log_step];
- static GCMinAllocStack *stacks[max_min_alloc+1];
-
- static GCMappedArea base_area;
-
- static void *alloc_area(GCMinAllocStack *s);
-
- inline GCMinAlloc() {} /* pas d'instance de ce truc */
-public:
- static void initialise();
- static void destroy();
-
- static inline void *minalloc(uintptr_t);
- static inline void minfree(void *, uintptr_t);
-};
-
-inline void *GCMinAlloc::minalloc(uintptr_t nbb) {
- GCMinAllocStack *s = stacks[nbb];
- void *res = s->alloc();
-
- if(!res)
- res = alloc_area(s);
- return res;
-}
-
-inline void GCMinAlloc::minfree(void *ptr, uintptr_t nbb) {
- stacks[nbb]->inject_free(ptr);
-}
-
-inline void *GCMin::operator new(uintptr_t nbb) {
- return GCMinAlloc::minalloc(nbb);
-}
-
-inline void GCMin::operator delete(void *ptr, uintptr_t nbb) {
- GCMinAlloc::minfree(ptr, nbb);
-}
-
-
-
-#endif
diff --git a/vmkit/lib/Mvm/Allocator/osdep.h b/vmkit/lib/Mvm/Allocator/osdep.h
deleted file mode 100644
index cd573e2..0000000
--- a/vmkit/lib/Mvm/Allocator/osdep.h
+++ /dev/null
@@ -1,24 +0,0 @@
-//===------------------ osdep.h - Mvm allocator ---------------------------===//
-//
-// Mvm
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#ifndef __OSDEP_H_
-#define __OSDEP_H_
-
-#include <sys/types.h>
-#include <stdarg.h>
-
-/* sys/pages.h ?? */
-#define PAGE_SHIFT 12
-#define PAGE_SIZE (1 << PAGE_SHIFT)
-
-#include <cstdio>
-#include <cstdlib>
-#include <cstring>
-
-#endif
diff --git a/vmkit/lib/Mvm/BoehmGC/Makefile b/vmkit/lib/Mvm/BoehmGC/Makefile
deleted file mode 100644
index 5fe6f3d..0000000
--- a/vmkit/lib/Mvm/BoehmGC/Makefile
+++ /dev/null
@@ -1,20 +0,0 @@
-##===- lib/Mvm/BoehmGC/Makefile ----------------------------*- Makefile -*-===##
-#
-# The vmkit project
-#
-# This file is distributed under the University of Illinois Open Source
-# License. See LICENSE.TXT for details.
-#
-##===----------------------------------------------------------------------===##
-LEVEL = ../../..
-
-include $(LEVEL)/Makefile.config
-
-ifeq ($(WITH_LLVM_GCC), 1)
- MODULE_NAME = BoehmGC
-else
- LIBRARYNAME = BoehmGC
-endif
-
-include $(LEVEL)/Makefile.common
-
diff --git a/vmkit/lib/Mvm/BoehmGC/MvmGC.h b/vmkit/lib/Mvm/BoehmGC/MvmGC.h
deleted file mode 100644
index f64d973..0000000
--- a/vmkit/lib/Mvm/BoehmGC/MvmGC.h
+++ /dev/null
@@ -1,145 +0,0 @@
-//===----------- MvmGC.h - Garbage Collection Interface -------------------===//
-//
-// The Micro Virtual Machine
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-
-#ifndef MVM_BOEHM_GC_H
-#define MVM_BOEHM_GC_H
-
-//#define GC_REDIRECT_TO_LOCAL
-#include <stdlib.h>
-#include <gc/gc_allocator.h>
-//#include "gc/gc_local_alloc.h"
-#include "gc/gc.h"
-
-#define STATIC_TRACER(type) staticTracer(type* obj)
-#define TRACER tracer()
-#define PARENT_TRACER tracer()
-#define MARK_AND_TRACE markAndTrace()
-#define CALL_TRACER tracer()
-
-namespace mvm {
- class Thread;
-}
-
-extern "C" void * GC_dlopen(const char *path, int mode) throw ();
-
-#define gc_new(Class) __gc_new(Class::VT) Class
-#define __gc_new new
-
-namespace mvm {
-class collectable : public gcRoot {
-public:
-
- void markAndTrace() const {}
-
- size_t objectSize() const {
- gc_header * res = (gc_header*)(GC_base((void*)this));
- return (GC_size(res) - sizeof(gc_header));
- }
-
- void* operator new(size_t sz, VirtualTable *VT) {
- gc_header * res = (gc_header*) GC_MALLOC(sz + sizeof(gc_header));
- res -> _XXX_vt= VT;
-
- destructor_t dest = res->getDestructor();
- if (dest)
- GC_register_finalizer_no_order(res, (void (*)(void*, void*))dest, NULL,
- NULL, NULL);
- return res->_2gc();
- }
-
- void* operator new(size_t sz) {
- return malloc(sz);
- }
-
- void operator delete(void * p) {
- //GC_FREE(p);
- }
-
- void* realloc(size_t n) {
- void * old = GC_base(this);
- gc_header * res = (gc_header*) GC_REALLOC(old, n + sizeof(gc_header));
- return res->_2gc();
- }
-
-};
-
-static int maxMem = 0;
-
-class Collector {
-public:
-
- static void initialise();
- static void destroy() {}
-
- static unsigned int enable(unsigned int n) {
- int old = GC_dont_gc;
- if(n)
- GC_enable();
- else
- GC_disable();
- return !old;
- }
-
- static void gcStats(size_t &no, size_t &nbb) {
- no = 0;
- nbb = GC_get_heap_size();
- }
-
- static void maybeCollect() {
- GC_collect_a_little();
- }
-
- static void collect(void) {
- GC_gcollect();
- }
-
- static void inject_my_thread(mvm::Thread*);
-
- static void remove_my_thread(mvm::Thread*) {}
- static Collector* allocate() { return 0; }
-
- static gc* begOf(const void *obj) {
- gc_header * a = (gc_header*)GC_base((void*)obj);
- if(a == NULL) return NULL;
- else return (gc*)a->_2gc();
- }
-
- inline static bool isObject(const void *o) {
- return begOf((void*)o);
- }
-
-
- static int getMaxMemory(void) { return maxMem; }
-
- static int getFreeMemory(void) {
- return GC_get_free_bytes();
- }
-
- static int getTotalMemory(void) {
- return GC_get_heap_size();
- }
-
- static void setMaxMemory(size_t size) {
- GC_set_max_heap_size(size);
- maxMem = size;
- }
-
- static void setMinMemory(size_t size) {
- if(GC_get_heap_size() < size)
- GC_expand_hp(size - GC_get_heap_size());
- }
-
- static bool isLive() {
- return true;
- }
-};
-}
-
-#endif
diff --git a/vmkit/lib/Mvm/BoehmGC/gc.cpp b/vmkit/lib/Mvm/BoehmGC/gc.cpp
deleted file mode 100644
index 876afc2..0000000
--- a/vmkit/lib/Mvm/BoehmGC/gc.cpp
+++ /dev/null
@@ -1,25 +0,0 @@
-//===------------ gc.cc - Boehm GC Garbage Collector ----------------------===//
-//
-// Mvm
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#include "mvm/GC.h"
-#include "mvm/Threads/Thread.h"
-
-using namespace mvm;
-
-void Collector::inject_my_thread(mvm::Thread* th) {
- GC_init();
-}
-
-void Collector::initialise() {
- GC_INIT();
-}
-
-extern "C" gc* gcmalloc(size_t sz, VirtualTable* VT) {
- return (gc*)gc::operator new(sz, VT);
-}
diff --git a/vmkit/lib/Mvm/CommonThread/CollectionRV.cpp b/vmkit/lib/Mvm/CommonThread/CollectionRV.cpp
deleted file mode 100644
index 1748c93..0000000
--- a/vmkit/lib/Mvm/CommonThread/CollectionRV.cpp
+++ /dev/null
@@ -1,251 +0,0 @@
-//===-------- CollectionRV.cpp - Rendez-vous for garbage collection -------===//
-//
-// The VMKit project
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#include <cassert>
-#include <signal.h>
-#include "mvm/VirtualMachine.h"
-#include "mvm/Threads/CollectionRV.h"
-#include "mvm/VMKit.h"
-#include "mvm/GC.h"
-
-#include "debug.h"
-
-using namespace mvm;
-
-void CollectionRV::another_mark() {
- VMKit *vmkit = mvm::Thread::get()->vmkit;
- assert(th->getLastSP() != NULL);
- assert(nbJoined < vmkit->NumberOfThreads);
- nbJoined++;
- if (nbJoined == vmkit->numberOfRunningThreads) {
- condInitiator.broadcast();
- }
-}
-
-void CollectionRV::waitEndOfRV() {
- mvm::Thread* th = mvm::Thread::get();
- assert(th->getLastSP() != NULL);
-
- while (th->doYield) {
- condEndRV.wait(&_lockRV);
- }
-}
-
-void CollectionRV::waitRV() {
- // Add myself.
- nbJoined++;
-
- while (nbJoined != mvm::Thread::get()->vmkit->numberOfRunningThreads) {
- condInitiator.wait(&_lockRV);
- }
-}
-
-void CooperativeCollectionRV::synchronize() {
- assert(nbJoined == 0);
- mvm::Thread* self = mvm::Thread::get();
- mvm::VMKit* vmkit = self->vmkit;
-
- for(Thread* cur=vmkit->runningThreads.next(); cur!=&vmkit->runningThreads; cur=cur->next()) {
- assert(!cur->doYield);
- cur->doYield = true;
- assert(!cur->joinedRV);
- }
-
- // The CAS is not necessary but it does a memory barrier.
- __sync_bool_compare_and_swap(&(self->joinedRV), false, true);
-
- // Lookup currently blocked threads.
- for(Thread* cur=vmkit->runningThreads.next(); cur!=&vmkit->runningThreads; cur=cur->next()) {
- if(cur->getLastSP() && cur != self) {
- nbJoined++;
- cur->joinedRV = true;
- }
- }
-
- // And wait for other threads to finish.
- waitRV();
-
- // Unlock, so that threads in uncooperative code that go back to cooperative
- // code can set back their lastSP.
- unlockRV();
-}
-
-
-#if defined(__MACH__)
-# define SIGGC SIGXCPU
-#else
-# define SIGGC SIGPWR
-#endif
-
-void UncooperativeCollectionRV::synchronize() {
- assert(nbJoined == 0);
- mvm::Thread* self = mvm::Thread::get();
- mvm::VMKit* vmkit = self->vmkit;
-
- // Lock thread lock, so that we can traverse the thread list safely. This will
- // be released on finishRV.
- for(Thread* cur=vmkit->runningThreads.next(); cur!=&vmkit->runningThreads; cur=cur->next()) {
- if(cur!=self) {
- int res = cur->kill(SIGGC);
- assert(!res && "Error on kill");
- }
- }
-
- // And wait for other threads to finish.
- waitRV();
-
- // Unlock, so that threads in uncooperative code that go back to cooperative
- // code can set back their lastSP.
- unlockRV();
-}
-
-
-void UncooperativeCollectionRV::join() {
- mvm::Thread* th = mvm::Thread::get();
- th->inRV = true;
-
- lockRV();
- void* old = th->getLastSP();
- th->setLastSP(FRAME_PTR());
- another_mark();
- waitEndOfRV();
- th->setLastSP(old);
- unlockRV();
-
- th->inRV = false;
-}
-
-void CooperativeCollectionRV::join() {
- mvm::Thread* th = mvm::Thread::get();
- assert(th->doYield && "No yield");
- assert((th->getLastSP() == NULL) && "SP present in cooperative code");
-
- th->inRV = true;
-
- lockRV();
- th->setLastSP(FRAME_PTR());
- th->joinedRV = true;
- another_mark();
- waitEndOfRV();
- th->setLastSP(0);
- unlockRV();
-
- th->inRV = false;
-}
-
-void CooperativeCollectionRV::joinBeforeUncooperative() {
- mvm::Thread* th = mvm::Thread::get();
- assert((th->getLastSP() != NULL) &&
- "SP not set before entering uncooperative code");
-
- th->inRV = true;
-
- lockRV();
- if (th->doYield) {
- if (!th->joinedRV) {
- th->joinedRV = true;
- another_mark();
- }
- waitEndOfRV();
- }
- unlockRV();
-
- th->inRV = false;
-}
-
-void CooperativeCollectionRV::joinAfterUncooperative(void* SP) {
- mvm::Thread* th = mvm::Thread::get();
- assert((th->getLastSP() == NULL) &&
- "SP set after entering uncooperative code");
-
- th->inRV = true;
-
- lockRV();
- if (th->doYield) {
- th->setLastSP(SP);
- if (!th->joinedRV) {
- th->joinedRV = true;
- another_mark();
- }
- waitEndOfRV();
- th->setLastSP(NULL);
- }
- unlockRV();
-
- th->inRV = false;
-}
-
-extern "C" void conditionalSafePoint() {
- mvm::Thread* th = mvm::Thread::get();
- th->vmkit->rendezvous.join();
-}
-
-void CooperativeCollectionRV::finishRV() {
- lockRV();
-
- mvm::Thread* initiator = mvm::Thread::get();
- mvm::VMKit* vmkit = initiator->vmkit;
-
- for(mvm::Thread* cur=vmkit->runningThreads.next(); cur!=&vmkit->runningThreads; cur=cur->next()) {
- assert(cur->doYield && "Inconsistent state");
- assert(cur->joinedRV && "Inconsistent state");
- cur->doYield = false;
- cur->joinedRV = false;
- }
-
- assert(nbJoined == initiator->vmkit->NumberOfThreads && "Inconsistent state");
- nbJoined = 0;
- condEndRV.broadcast();
- unlockRV();
- initiator->inRV = false;
-}
-
-void CooperativeCollectionRV::prepareForJoin() {
- /// nothing to do
-}
-
-void UncooperativeCollectionRV::finishRV() {
- lockRV();
- mvm::Thread* initiator = mvm::Thread::get();
- assert(nbJoined == initiator->vmkit->NumberOfThreads && "Inconsistent state");
- nbJoined = 0;
- condEndRV.broadcast();
- unlockRV();
- initiator->inRV = false;
-}
-
-void UncooperativeCollectionRV::joinAfterUncooperative(void* SP) {
- UNREACHABLE();
-}
-
-void UncooperativeCollectionRV::joinBeforeUncooperative() {
- UNREACHABLE();
-}
-
-static void siggcHandler(int) {
- mvm::Thread* th = mvm::Thread::get();
- th->vmkit->rendezvous.join();
-}
-
-void UncooperativeCollectionRV::prepareForJoin() {
- // Set the SIGGC handler for uncooperative rendezvous.
- struct sigaction sa;
- sigset_t mask;
- sigaction(SIGGC, 0, &sa);
- sigfillset(&mask);
- sa.sa_mask = mask;
- sa.sa_handler = siggcHandler;
- sa.sa_flags |= SA_RESTART;
- sigaction(SIGGC, &sa, NULL);
-
- if (nbJoined != 0) {
- // In uncooperative mode, we may have missed a signal.
- join();
- }
-}
diff --git a/vmkit/lib/Mvm/CommonThread/Makefile b/vmkit/lib/Mvm/CommonThread/Makefile
deleted file mode 100644
index 7ae1d33..0000000
--- a/vmkit/lib/Mvm/CommonThread/Makefile
+++ /dev/null
@@ -1,21 +0,0 @@
-##===- lib/Mvm/CommonThread/Makefile -----------------------*- Makefile -*-===##
-#
-# The vmkit project
-#
-# This file is distributed under the University of Illinois Open Source
-# License. See LICENSE.TXT for details.
-#
-##===----------------------------------------------------------------------===##
-LEVEL = ../../..
-
-include $(LEVEL)/Makefile.config
-
-ifeq ($(WITH_LLVM_GCC), 1)
- MODULE_NAME = CommonThread
-else
- LIBRARYNAME = CommonThread
-endif
-
-
-include $(LEVEL)/Makefile.common
-
diff --git a/vmkit/lib/Mvm/CommonThread/ObjectLocks.cpp b/vmkit/lib/Mvm/CommonThread/ObjectLocks.cpp
deleted file mode 100644
index 24b141a..0000000
--- a/vmkit/lib/Mvm/CommonThread/ObjectLocks.cpp
+++ /dev/null
@@ -1,537 +0,0 @@
-//===--------- ObjectLocks.cpp - Object-based locks -----------------------===//
-//
-// The VMKit project
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#include <cassert>
-
-#include "mvm/Threads/Cond.h"
-#include "mvm/Threads/Locks.h"
-#include "mvm/Threads/ObjectLocks.h"
-#include "mvm/Threads/Thread.h"
-#include "mvm/VirtualMachine.h"
-#include "mvm/GC.h"
-#include "cterror.h"
-#include <cerrno>
-#include <sys/time.h>
-#include <pthread.h>
-
-
-using namespace mvm;
-
-void ThinLock::overflowThinLock(gc* object, LockSystem& table) {
- llvm_gcroot(object, 0);
- FatLock* obj = table.allocate(object);
- uintptr_t ID = obj->getID();
- // 1 because we start at 0, and 1 for this lock request.
- obj->acquireAll(object, (ThinCountMask >> ThinCountShift) + 2);
- uintptr_t oldValue = 0;
- uintptr_t newValue = 0;
- uintptr_t yieldedValue = 0;
- do {
- oldValue = object->header;
- newValue = obj->getID() | (oldValue & NonLockBitsMask);
- assert(obj->associatedObject == object);
- yieldedValue = __sync_val_compare_and_swap(&(object->header), oldValue, newValue);
- } while (((object->header) & ~NonLockBitsMask) != ID);
- assert(obj->associatedObject == object);
-}
-
-/// initialise - Initialise the value of the lock.
-///
-void ThinLock::removeFatLock(FatLock* fatLock, LockSystem& table) {
- gc* object = fatLock->associatedObject;
- llvm_gcroot(object, 0);
- uintptr_t ID = fatLock->getID();
- uintptr_t oldValue = 0;
- uintptr_t newValue = 0;
- uintptr_t yieldedValue = 0;
- do {
- oldValue = object->header;
- newValue = oldValue & NonLockBitsMask;
- yieldedValue = __sync_val_compare_and_swap(&object->header, oldValue, newValue);
- } while (oldValue != yieldedValue);
- assert((oldValue & NonLockBitsMask) != ID);
- fatLock->associatedObject = NULL;
-}
-
-FatLock* ThinLock::changeToFatlock(gc* object, LockSystem& table) {
- llvm_gcroot(object, 0);
- if (!(object->header & FatMask)) {
- FatLock* obj = table.allocate(object);
- uint32 count = (object->header & ThinCountMask) >> ThinCountShift;
- obj->acquireAll(object, count + 1);
- uintptr_t oldValue = 0;
- uintptr_t newValue = 0;
- uintptr_t yieldedValue = 0;
- uintptr_t ID = obj->getID();
- do {
- oldValue = object->header;
- newValue = ID | (oldValue & NonLockBitsMask);
- assert(obj->associatedObject == object);
- yieldedValue = __sync_val_compare_and_swap(&(object->header), oldValue, newValue);
- } while (((object->header) & ~NonLockBitsMask) != ID);
- return obj;
- } else {
- FatLock* res = table.getFatLockFromID(object->header);
- assert(res && "Lock deallocated while held.");
- assert(res->associatedObject == object);
- return res;
- }
-}
-
-void printDebugMessage(gc* object, LockSystem& table) {
- llvm_gcroot(object, 0);
- fprintf(stderr,
- "WARNING: [%p] has been waiting really long for %p (header = %x)\n",
- (void*)mvm::Thread::get(),
- (void*)object,
- object->header);
- FatLock* obj = table.getFatLockFromID(object->header);
- if (obj != NULL) {
- fprintf(stderr,
- "WARNING: [%p] is waiting on fatlock %p. "
- "Its associated object is %p. The owner is %p\n",
- (void*)mvm::Thread::get(),
- (void*)obj,
- (void*)obj->getAssociatedObject(),
- (void*)obj->owner());
- }
-}
-
-void ThinLock::acquire(gc* object, LockSystem& table) {
- llvm_gcroot(object, 0);
- uint64_t id = mvm::Thread::get()->getThreadID();
- uintptr_t oldValue = 0;
- uintptr_t newValue = 0;
- uintptr_t yieldedValue = 0;
-
- if ((object->header & Thread::IDMask) == id) {
- assert(owner(object, table) && "Inconsistent lock");
- if ((object->header & ThinCountMask) != ThinCountMask) {
- uint32 count = object->header & ThinCountMask;
- do {
- oldValue = object->header;
- newValue = oldValue + ThinCountAdd;
- yieldedValue = __sync_val_compare_and_swap(&(object->header), oldValue, newValue);
- } while ((object->header & ThinCountMask) == count);
- } else {
- overflowThinLock(object, table);
- }
- assert(owner(object, table) && "Not owner after quitting acquire!");
- return;
- }
-
- do {
- oldValue = object->header & NonLockBitsMask;
- newValue = oldValue | id;
- yieldedValue = __sync_val_compare_and_swap(&(object->header), oldValue, newValue);
- } while ((object->header & ~NonLockBitsMask) == 0);
-
- if (((object->header) & ~NonLockBitsMask) == id) {
- assert(owner(object, table) && "Not owner after quitting acquire!");
- return;
- }
-
- // Simple counter to lively diagnose possible dead locks in this code.
- int counter = 0;
- while (true) {
- if (object->header & FatMask) {
- FatLock* obj = table.getFatLockFromID(object->header);
- if (obj != NULL) {
- if (obj->acquire(object)) {
- assert((object->header & FatMask) && "Inconsistent lock");
- assert((table.getFatLockFromID(object->header) == obj) && "Inconsistent lock");
- assert(owner(object, table) && "Not owner after acquring fat lock!");
- break;
- }
- }
- }
-
- counter++;
- if (counter == 1000) printDebugMessage(object, table);
-
- while (object->header & ~NonLockBitsMask) {
- if (object->header & FatMask) {
- break;
- } else {
- mvm::Thread::yield();
- }
- }
-
- if ((object->header & ~NonLockBitsMask) == 0) {
- FatLock* obj = table.allocate(object);
- obj->internalLock.lock();
- do {
- oldValue = object->header & NonLockBitsMask;
- newValue = oldValue | obj->getID();
- assert(obj->associatedObject == object);
- yieldedValue = __sync_val_compare_and_swap(&object->header, oldValue, newValue);
- } while ((object->header & ~NonLockBitsMask) == 0);
-
- if ((getFatLock(object, table) != obj)) {
- assert((object->header & ~NonLockBitsMask) != obj->getID());
- obj->internalLock.unlock();
- table.deallocate(obj);
- } else {
- assert((object->header & ~NonLockBitsMask) == obj->getID());
- assert(owner(object, table) && "Inconsistent lock");
- break;
- }
- }
- }
-
- assert(owner(object, table) && "Not owner after quitting acquire!");
-}
-
-/// release - Release the lock.
-void ThinLock::release(gc* object, LockSystem& table) {
- llvm_gcroot(object, 0);
- assert(owner(object, table) && "Not owner when entering release!");
- uint64 id = mvm::Thread::get()->getThreadID();
- uintptr_t oldValue = 0;
- uintptr_t newValue = 0;
- uintptr_t yieldedValue = 0;
- if ((object->header & ~NonLockBitsMask) == id) {
- do {
- oldValue = object->header;
- newValue = oldValue & NonLockBitsMask;
- yieldedValue = __sync_val_compare_and_swap(&object->header, oldValue, newValue);
- } while ((object->header & ~NonLockBitsMask) == id);
- } else if (object->header & FatMask) {
- FatLock* obj = table.getFatLockFromID(object->header);
- assert(obj && "Lock deallocated while held.");
- obj->release(object, table);
- } else {
- assert(((object->header & ThinCountMask) > 0) && "Inconsistent state");
- uint32 count = (object->header & ThinCountMask);
- do {
- oldValue = object->header;
- newValue = oldValue - ThinCountAdd;
- yieldedValue = __sync_val_compare_and_swap(&(object->header), oldValue, newValue);
- } while ((object->header & ThinCountMask) == count);
- }
-}
-
-/// owner - Returns true if the curren thread is the owner of this object's
-/// lock.
-bool ThinLock::owner(gc* object, LockSystem& table) {
- llvm_gcroot(object, 0);
- if (object->header & FatMask) {
- FatLock* obj = table.getFatLockFromID(object->header);
- if (obj != NULL) return obj->owner();
- } else {
- uint64 id = mvm::Thread::get()->getThreadID();
- if ((object->header & Thread::IDMask) == id) return true;
- }
- return false;
-}
-
-/// getFatLock - Get the fat lock is the lock is a fat lock, 0 otherwise.
-FatLock* ThinLock::getFatLock(gc* object, LockSystem& table) {
- llvm_gcroot(object, 0);
- if (object->header & FatMask) {
- return table.getFatLockFromID(object->header);
- } else {
- return NULL;
- }
-}
-
-void FatLock::acquireAll(gc* object, uint32 nb) {
- assert(associatedObject == object);
- llvm_gcroot(object, 0);
- internalLock.lockAll(nb);
-}
-
-bool FatLock::owner() {
- return internalLock.selfOwner();
-}
-
-mvm::Thread* FatLock::getOwner() {
- return internalLock.getOwner();
-}
-
-FatLock::FatLock(uint32_t i, gc* a) {
- llvm_gcroot(a, 0);
- assert(a != NULL);
- firstThread = NULL;
- index = i;
- associatedObject = a;
- waitingThreads = 0;
- lockingThreads = 0;
- nextFreeLock = NULL;
-}
-
-uintptr_t FatLock::getID() {
- return (index << ThinLock::NonLockBits) | ThinLock::FatMask;
-}
-
-void FatLock::release(gc* obj, LockSystem& table) {
- llvm_gcroot(obj, 0);
- assert(associatedObject && "No associated object when releasing");
- assert(associatedObject == obj && "Mismatch object in lock");
- if (!waitingThreads && !lockingThreads &&
- internalLock.recursionCount() == 1) {
- mvm::ThinLock::removeFatLock(this, table);
- table.deallocate(this);
- }
- internalLock.unlock();
-}
-
-/// acquire - Acquires the internalLock.
-///
-bool FatLock::acquire(gc* obj) {
- llvm_gcroot(obj, 0);
-
- spinLock.lock();
- lockingThreads++;
- spinLock.unlock();
-
- internalLock.lock();
-
- spinLock.lock();
- lockingThreads--;
- spinLock.unlock();
-
- if (associatedObject != obj) {
- internalLock.unlock();
- return false;
- }
- assert(obj->header & ThinLock::FatMask);
- assert((obj->header & ~ThinLock::NonLockBitsMask) == getID());
- return true;
-}
-
-
-void LockSystem::deallocate(FatLock* lock) {
- lock->associatedObject = NULL;
- threadLock.lock();
- lock->nextFreeLock = freeLock;
- freeLock = lock;
- threadLock.unlock();
-}
-
-LockSystem::LockSystem(mvm::BumpPtrAllocator& all) : allocator(all) {
- assert(ThinLock::ThinCountMask > 0);
- LockTable = (FatLock* **)
- allocator.Allocate(GlobalSize * sizeof(FatLock**), "Global LockTable");
- LockTable[0] = (FatLock**)
- allocator.Allocate(IndexSize * sizeof(FatLock*), "Index LockTable");
- currentIndex = 0;
- freeLock = NULL;
-}
-
-FatLock* LockSystem::allocate(gc* obj) {
- llvm_gcroot(obj, 0);
- FatLock* res = 0;
- threadLock.lock();
-
- // Try the freeLock list.
- if (freeLock != NULL) {
- res = freeLock;
- freeLock = res->nextFreeLock;
- res->nextFreeLock = 0;
- assert(res->associatedObject == NULL);
- threadLock.unlock();
- res->associatedObject = obj;
- } else {
- // Get an index.
- uint32_t index = currentIndex++;
- if (index == MaxLocks) {
- fprintf(stderr, "Ran out of space for allocating locks");
- abort();
- }
-
- FatLock** tab = LockTable[index >> BitIndex];
-
- VirtualMachine* vm = obj->getVirtualTable()->vm;
- if (tab == NULL) {
- tab = (FatLock**)vm->allocator.Allocate(
- IndexSize * sizeof(FatLock*), "Index LockTable");
- }
- threadLock.unlock();
-
- // Allocate the lock.
- res = new(vm->allocator, "Lock") FatLock(index, obj);
-
- // Add the lock to the table.
- uint32_t internalIndex = index & BitMask;
- tab[internalIndex] = res;
- }
-
- assert(res->associatedObject == obj);
- // Return the lock.
- return res;
-}
-
-
-FatLock* LockSystem::getFatLockFromID(uintptr_t ID) {
- if (ID & ThinLock::FatMask) {
- uint32_t index = (ID & ~ThinLock::FatMask) >> ThinLock::NonLockBits;
- FatLock* res = getLock(index);
- return res;
- } else {
- return NULL;
- }
-}
-
-
-
-bool LockingThread::wait(
- gc* self, LockSystem& table, struct timeval* info, bool timed) {
- llvm_gcroot(self, 0);
- assert(mvm::ThinLock::owner(self, table));
-
- FatLock* l = mvm::ThinLock::changeToFatlock(self, table);
- this->waitsOn = l;
- mvm::Cond& varcondThread = this->varcond;
-
- if (this->interruptFlag != 0) {
- this->interruptFlag = 0;
- this->waitsOn = 0;
- return true;
- }
-
- this->state = LockingThread::StateWaiting;
- if (l->firstThread) {
- assert(l->firstThread->prevWaiting && l->firstThread->nextWaiting &&
- "Inconsistent list");
- if (l->firstThread->nextWaiting == l->firstThread) {
- l->firstThread->nextWaiting = this;
- } else {
- l->firstThread->prevWaiting->nextWaiting = this;
- }
- this->prevWaiting = l->firstThread->prevWaiting;
- this->nextWaiting = l->firstThread;
- l->firstThread->prevWaiting = this;
- } else {
- l->firstThread = this;
- this->nextWaiting = this;
- this->prevWaiting = this;
- }
-
- assert(this->prevWaiting && this->nextWaiting && "Inconsistent list");
- assert(l->firstThread->prevWaiting && l->firstThread->nextWaiting &&
- "Inconsistent list");
-
- bool timeout = false;
-
- l->waitingThreads++;
-
- while (!this->interruptFlag && this->nextWaiting) {
- if (timed) {
- timeout = varcondThread.timedWait(&l->internalLock, info);
- if (timeout) break;
- } else {
- varcondThread.wait(&l->internalLock);
- }
- }
-
- l->waitingThreads--;
-
- assert((!l->firstThread || (l->firstThread->prevWaiting &&
- l->firstThread->nextWaiting)) && "Inconsistent list");
-
- bool interrupted = (this->interruptFlag != 0);
-
- if (interrupted || timeout) {
- if (this->nextWaiting) {
- assert(this->prevWaiting && "Inconsistent list");
- if (l->firstThread != this) {
- this->nextWaiting->prevWaiting = this->prevWaiting;
- this->prevWaiting->nextWaiting = this->nextWaiting;
- assert(l->firstThread->prevWaiting &&
- l->firstThread->nextWaiting && "Inconsistent list");
- } else if (this->nextWaiting == this) {
- l->firstThread = NULL;
- } else {
- l->firstThread = this->nextWaiting;
- l->firstThread->prevWaiting = this->prevWaiting;
- this->prevWaiting->nextWaiting = l->firstThread;
- assert(l->firstThread->prevWaiting &&
- l->firstThread->nextWaiting && "Inconsistent list");
- }
- this->nextWaiting = NULL;
- this->prevWaiting = NULL;
- } else {
- assert(!this->prevWaiting && "Inconstitent state");
- // Notify lost, notify someone else.
- notify(self, table);
- }
- } else {
- assert(!this->prevWaiting && !this->nextWaiting &&
- "Inconsistent state");
- }
-
- this->state = LockingThread::StateRunning;
- this->waitsOn = NULL;
-
- if (interrupted) {
- this->interruptFlag = 0;
- return true;
- }
-
- assert(mvm::ThinLock::owner(self, table) && "Not owner after wait");
- return false;
-}
-
-void LockingThread::notify(gc* self, LockSystem& table) {
- llvm_gcroot(self, 0);
- assert(mvm::ThinLock::owner(self, table));
- FatLock* l = mvm::ThinLock::getFatLock(self, table);
-
- if (l == NULL) return;
- LockingThread* cur = l->firstThread;
- if (cur == NULL) return;
-
- do {
- if (cur->interruptFlag != 0) {
- cur = cur->nextWaiting;
- } else {
- assert(cur->prevWaiting && cur->nextWaiting &&
- "Inconsistent list");
- if (cur != l->firstThread) {
- cur->prevWaiting->nextWaiting = cur->nextWaiting;
- cur->nextWaiting->prevWaiting = cur->prevWaiting;
- assert(l->firstThread->prevWaiting &&
- l->firstThread->nextWaiting && "Inconsistent list");
- } else if (cur->nextWaiting == cur) {
- l->firstThread = NULL;
- } else {
- l->firstThread = cur->nextWaiting;
- l->firstThread->prevWaiting = cur->prevWaiting;
- cur->prevWaiting->nextWaiting = l->firstThread;
- assert(l->firstThread->prevWaiting &&
- l->firstThread->nextWaiting && "Inconsistent list");
- }
- cur->prevWaiting = NULL;
- cur->nextWaiting = NULL;
- cur->varcond.signal();
- break;
- }
- } while (cur != l->firstThread);
-
- assert(mvm::ThinLock::owner(self, table) && "Not owner after notify");
-}
-
-void LockingThread::notifyAll(gc* self, LockSystem& table) {
- llvm_gcroot(self, 0);
- assert(mvm::ThinLock::owner(self, table));
- FatLock* l = mvm::ThinLock::getFatLock(self, table);
- if (l == NULL) return;
- LockingThread* cur = l->firstThread;
- if (cur == NULL) return;
- do {
- LockingThread* temp = cur->nextWaiting;
- cur->prevWaiting = NULL;
- cur->nextWaiting = NULL;
- cur->varcond.signal();
- cur = temp;
- } while (cur != l->firstThread);
- l->firstThread = NULL;
- assert(mvm::ThinLock::owner(self, table) && "Not owner after notifyAll");
-}
diff --git a/vmkit/lib/Mvm/CommonThread/Sigsegv.cpp b/vmkit/lib/Mvm/CommonThread/Sigsegv.cpp
deleted file mode 100644
index 3149ce9..0000000
--- a/vmkit/lib/Mvm/CommonThread/Sigsegv.cpp
+++ /dev/null
@@ -1,66 +0,0 @@
-//===----------- Sigsegv.cc - Sigsegv default handling --------------------===//
-//
-// The VMKit project
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-
-#include "mvm/VirtualMachine.h"
-#include "mvm/Threads/Thread.h"
-
-#include <csignal>
-#include <cstdio>
-
-using namespace mvm;
-
-#if defined(__MACH__) && defined(__i386__)
-#include "ucontext.h"
-#endif
-
-void sigsegvHandler(int n, siginfo_t *_info, void *context) {
- uintptr_t addr = (uintptr_t)_info->si_addr;
-#if defined(__i386__)
- struct frame {
- struct frame *caller;
- void *ip;
- };
-
- /* my frame */
- struct frame *fp;
- /* get it */
- asm ("mov %%ebp, %0" : "=&r"(fp));
- /* my caller */
- struct frame *caller = fp->caller;
- /* preserve my caller if I return from the handler */
- void *caller_ip = caller->ip;
-
-#if defined(__MACH__)
- //.gregs[REG_EIP]; /* just like it's on the stack.. */
- caller->ip = (void *)((ucontext_t*)context)->uc_mcontext->__ss.__eip;
-#else
- /* just like it's on the stack... */
- caller->ip = (void *)((ucontext_t*)context)->uc_mcontext.gregs[REG_EIP];
-#endif
-#endif
-
- mvm::Thread* th = mvm::Thread::get();
- if (addr > (uintptr_t)th->getThreadID() && addr < (uintptr_t)th->baseSP) {
- fprintf(stderr, "Stack overflow in VM code or in JNI code. If it is from\n"
- "the VM, it is either from the JIT, the GC or the runtime."
- "\nThis has to be fixed in the VM: VMKit makes sure that\n"
- "the bottom of the stack is always available when entering"
- "\nthe VM.\n");
- } else {
- fprintf(stderr, "Thread %p received a SIGSEGV: either the VM code or an external\n"
- "native method is bogus. Aborting...\n", (void*)th);
- }
- th->printBacktrace();
- abort();
-
-#if defined(__i386__)
- caller->ip = caller_ip; /* restore the caller ip */
-#endif
-}
diff --git a/vmkit/lib/Mvm/CommonThread/VMThreadData.cpp b/vmkit/lib/Mvm/CommonThread/VMThreadData.cpp
deleted file mode 100644
index 919d0f3..0000000
--- a/vmkit/lib/Mvm/CommonThread/VMThreadData.cpp
+++ /dev/null
@@ -1,4 +0,0 @@
-#include "mvm/Threads/Thread.h"
-#include "MutatorThread.h"
-
-using namespace mvm;
diff --git a/vmkit/lib/Mvm/CommonThread/cterror.cpp b/vmkit/lib/Mvm/CommonThread/cterror.cpp
deleted file mode 100644
index c2ca384..0000000
--- a/vmkit/lib/Mvm/CommonThread/cterror.cpp
+++ /dev/null
@@ -1,35 +0,0 @@
-//===-------------- cterror.cc - Mvm common threads -----------------------===//
-//
-// Mvm
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#include "cterror.h"
-#include <stdio.h>
-#include <stdarg.h>
-#include <errno.h>
-#include <string.h>
-#include <stdlib.h>
-
-void (*pgcdomsgf)(const char *, unsigned int l, const char *, const char *, ...) = _gcdomsgf;
-void (**gcdomsgf)(const char *, unsigned int l, const char *, const char *, ...) = &pgcdomsgf;
-
-const char *ctperror() {
- return strerror(errno);
-}
-
-void _gcdomsgf(const char *file, unsigned int l, const char *func, const char *msg, ...)
-{
- va_list va;
- va_start(va, msg);
- fprintf(stderr, "GC[error] in %s line %d (function %s)\n", file, l, func);
- vfprintf(stderr, msg, va);
- fprintf(stderr, "\n");
- va_end(va);
- exit(0);
-}
-
-
diff --git a/vmkit/lib/Mvm/CommonThread/cterror.h b/vmkit/lib/Mvm/CommonThread/cterror.h
deleted file mode 100644
index b201495..0000000
--- a/vmkit/lib/Mvm/CommonThread/cterror.h
+++ /dev/null
@@ -1,22 +0,0 @@
-//===---------------- cterror.h - Mvm common threads ----------------------===//
-//
-// Mvm
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#ifndef _CT_ERROR_H_
-#define _CT_ERROR_H_
-
-extern const char *ctperror();
-extern void _gcdomsgf(const char *file, unsigned int l, const char *func, const char *msg, ...);
-extern void (*pgcdomsgf)(const char *, unsigned int l, const char *, const char *, ...);
-extern void (**gcdomsgf)(const char *, unsigned int l, const char *, const char *, ...);
-
-#define ctfatal(msg) (*gcdomsgf)(__FILE__, __LINE__, __PRETTY_FUNCTION__, msg)
-
-#endif
-
-
diff --git a/vmkit/lib/Mvm/CommonThread/ctlock.cpp b/vmkit/lib/Mvm/CommonThread/ctlock.cpp
deleted file mode 100644
index 5b18612..0000000
--- a/vmkit/lib/Mvm/CommonThread/ctlock.cpp
+++ /dev/null
@@ -1,190 +0,0 @@
-//===--- ctlock.cc - Common threads implementation of locks ---------------===//
-//
-// The Micro Virtual Machine
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#include <cassert>
-
-#include "mvm/Threads/Cond.h"
-#include "mvm/Threads/Locks.h"
-#include "mvm/Threads/Thread.h"
-#include "mvm/VirtualMachine.h"
-#include "mvm/GC.h"
-#include "cterror.h"
-#include <cerrno>
-#include <sys/time.h>
-#include <pthread.h>
-
-
-using namespace mvm;
-
-Lock::Lock() {
- pthread_mutexattr_t attr;
-
- // Initialize the mutex attributes
- int errorcode = pthread_mutexattr_init(&attr);
- assert(errorcode == 0);
-
- // Initialize the mutex as a recursive mutex, if requested, or normal
- // otherwise.
- int kind = PTHREAD_MUTEX_NORMAL;
- errorcode = pthread_mutexattr_settype(&attr, kind);
- assert(errorcode == 0);
-
-#if !defined(__FreeBSD__) && !defined(__OpenBSD__) && !defined(__NetBSD__) && \
- !defined(__DragonFly__)
- // Make it a process local mutex
- errorcode = pthread_mutexattr_setpshared(&attr, PTHREAD_PROCESS_PRIVATE);
-#endif
-
- // Initialize the mutex
- errorcode = pthread_mutex_init(&internalLock, &attr);
- assert(errorcode == 0);
-
- // Destroy the attributes
- errorcode = pthread_mutexattr_destroy(&attr);
- assert(errorcode == 0);
-
- owner = 0;
-}
-
-Lock::~Lock() {
- pthread_mutex_destroy((pthread_mutex_t*)&internalLock);
-}
-
-bool Lock::selfOwner() {
- return owner == mvm::Thread::get();
-}
-
-mvm::Thread* Lock::getOwner() {
- return owner;
-}
-
-void LockNormal::lock() {
- Thread* th = Thread::get();
- th->enterUncooperativeCode();
- pthread_mutex_lock((pthread_mutex_t*)&internalLock);
- th->leaveUncooperativeCode();
- owner = th;
-}
-
-void LockNormal::unlock() {
- assert(selfOwner() && "Not owner when unlocking");
- owner = 0;
- pthread_mutex_unlock((pthread_mutex_t*)&internalLock);
-}
-
-void LockRecursive::lock() {
- if (!selfOwner()) {
- Thread* th = Thread::get();
- th->enterUncooperativeCode();
- pthread_mutex_lock((pthread_mutex_t*)&internalLock);
- th->leaveUncooperativeCode();
- owner = th;
- }
- ++n;
-}
-
-int LockRecursive::tryLock() {
- int res = 0;
- if (!selfOwner()) {
- res = pthread_mutex_trylock((pthread_mutex_t*)&internalLock);
- owner = mvm::Thread::get();
- }
- ++n;
- return res;
-}
-
-void LockRecursive::unlock() {
- assert(selfOwner() && "Not owner when unlocking");
- --n;
- if (n == 0) {
- owner = 0;
- pthread_mutex_unlock((pthread_mutex_t*)&internalLock);
- }
-}
-
-int LockRecursive::unlockAll() {
- assert(selfOwner() && "Not owner when unlocking all");
- int res = n;
- n = 0;
- owner = 0;
- pthread_mutex_unlock((pthread_mutex_t*)&internalLock);
- return res;
-}
-
-void LockRecursive::lockAll(int count) {
- if (selfOwner()) {
- n += count;
- } else {
- Thread* th = Thread::get();
- th->enterUncooperativeCode();
- pthread_mutex_lock((pthread_mutex_t*)&internalLock);
- th->leaveUncooperativeCode();
- owner = th;
- n = count;
- }
-}
-
-Cond::Cond() {
- int errorcode = pthread_cond_init((pthread_cond_t*)&internalCond, NULL);
- assert(errorcode == 0);
-}
-
-Cond::~Cond() {
- pthread_cond_destroy((pthread_cond_t*)&internalCond);
-}
-
-void Cond::broadcast() {
- pthread_cond_broadcast((pthread_cond_t*)&internalCond);
-}
-
-void Cond::wait(Lock* l) {
- assert(l->selfOwner());
- int n = l->unsafeUnlock();
-
- Thread* th = Thread::get();
- th->enterUncooperativeCode();
- int res = pthread_cond_wait((pthread_cond_t*)&internalCond,
- (pthread_mutex_t*)&(l->internalLock));
- th->leaveUncooperativeCode();
-
- assert(!res && "Error on wait");
- l->unsafeLock(n);
-}
-
-void Cond::signal() {
- pthread_cond_signal((pthread_cond_t*)&internalCond);
-}
-
-#define BILLION 1000000000
-int Cond::timedWait(Lock* l, struct timeval *ref) {
- struct timespec timeout;
- struct timeval now;
- gettimeofday(&now, NULL);
- timeout.tv_sec = now.tv_sec + ref->tv_sec;
- timeout.tv_nsec = (now.tv_usec + ref->tv_usec) * 1000;
- if (timeout.tv_nsec > BILLION) {
- timeout.tv_sec++;
- timeout.tv_nsec -= BILLION;
- }
-
- assert(l->selfOwner());
- int n = l->unsafeUnlock();
-
- Thread* th = Thread::get();
- th->enterUncooperativeCode();
- int res = pthread_cond_timedwait((pthread_cond_t*)&internalCond,
- (pthread_mutex_t*)&(l->internalLock),
- &timeout);
- th->leaveUncooperativeCode();
-
- assert((!res || res == ETIMEDOUT) && "Error on timed wait");
- l->unsafeLock(n);
-
- return res;
-}
diff --git a/vmkit/lib/Mvm/CommonThread/ctthread.cpp b/vmkit/lib/Mvm/CommonThread/ctthread.cpp
deleted file mode 100644
index 7d79f0e..0000000
--- a/vmkit/lib/Mvm/CommonThread/ctthread.cpp
+++ /dev/null
@@ -1,550 +0,0 @@
-//===---------- ctthread.cc - Thread implementation for VMKit -------------===//
-//
-// The VMKit project
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#include "debug.h"
-
-#include "mvm/GC.h"
-#include "mvm/MethodInfo.h"
-#include "mvm/VirtualMachine.h"
-#include "mvm/Threads/Cond.h"
-#include "mvm/Threads/Locks.h"
-#include "mvm/Threads/Thread.h"
-#include "mvm/VMKit.h"
-
-#include <cassert>
-#include <csetjmp>
-#include <cstdio>
-#include <ctime>
-#include <dlfcn.h>
-#include <errno.h>
-#include <pthread.h>
-#include <sys/mman.h>
-#include <sched.h>
-#include <signal.h>
-#include <unistd.h>
-
-using namespace mvm;
-
-Thread::Thread(VMKit* vmk) {
-#ifdef RUNTIME_DWARF_EXCEPTIONS
- internalPendingException = 0;
-#else
- lastExceptionBuffer = 0;
-#endif
- vmkit = vmk;
- lastKnownFrame = 0;
- pendingException = 0;
- allVmsData = 0;
- state = 0; // not daemon, not running
- vmk->registerPreparedThread(this);
-}
-
-void Thread::setDaemon() {
- if((state & THREAD_RUNNING) && !(state & THREAD_DAEMON))
- vmkit->nonDaemonThreadsManager.leaveNonDaemonMode();
- state |= THREAD_DAEMON;
-}
-
-void Thread::setNonDaemon() {
- if((state & THREAD_RUNNING) && (state & THREAD_DAEMON))
- vmkit->nonDaemonThreadsManager.enterNonDaemonMode();
- state &= ~THREAD_DAEMON;
-}
-
-void Thread::attach(VirtualMachine* vm) {
- vmData = allVmsData[vm->vmID];
-
- if(!vmData) {
- vmkit->vmkitLock();
- vmData = allVmsData[vm->vmID] = vm->buildVMThreadData(this);
- vmkit->vmkitUnlock();
- }
-}
-
-// must be protected by rendezvous.threadLock
-void Thread::reallocAllVmsData(int old, int n) {
- VMThreadData **newData = new VMThreadData*[n];
- if(old) {
- memcpy(newData, allVmsData, old*sizeof(VMThreadData*));
- VMThreadData **oldData = allVmsData;
- allVmsData = newData;
- delete oldData;
- } else
- allVmsData = newData;
- memset(allVmsData + old*sizeof(VMThreadData*), 0, (n-old)*sizeof(VMThreadData*));
-}
-
-void Thread::tracer(uintptr_t closure) {
- mvm::Collector::markAndTraceRoot(&pendingException, closure);
-
- // should we take the vmkit lock? I suppose that all the threads are suspended during the collection...
- for(size_t i=0; i<vmkit->vmsArraySize; i++)
- if(allVmsData[i]) {
- allVmsData[i]->tracer(closure);
- }
-}
-
-int Thread::kill(void* tid, int signo) {
- return pthread_kill((pthread_t)tid, signo);
-}
-
-int Thread::kill(int signo) {
- return pthread_kill((pthread_t)internalThreadID, signo);
-}
-
-void Thread::exit(int value) {
- pthread_exit((void*)value);
-}
-
-void Thread::yield(void) {
- Thread* th = mvm::Thread::get();
- if (th->isMvmThread()) {
- if (th->doYield && !th->inRV) {
- th->vmkit->rendezvous.join();
- }
- }
- sched_yield();
-}
-
-void Thread::joinRVBeforeEnter() {
- vmkit->rendezvous.joinBeforeUncooperative();
-}
-
-void Thread::joinRVAfterLeave(void* savedSP) {
- vmkit->rendezvous.joinAfterUncooperative(savedSP);
-}
-
-void Thread::startKnownFrame(KnownFrame& F) {
- // Get the caller of this function
- void** cur = (void**)FRAME_PTR();
- // Get the caller of the caller.
- cur = (void**)cur[0];
- F.previousFrame = lastKnownFrame;
- F.currentFP = cur;
- // This is used as a marker.
- F.currentIP = NULL;
- lastKnownFrame = &F;
-}
-
-void Thread::endKnownFrame() {
- assert(lastKnownFrame->currentIP == NULL);
- lastKnownFrame = lastKnownFrame->previousFrame;
-}
-
-void Thread::startUnknownFrame(KnownFrame& F) {
- // Get the caller of this function
- void** cur = (void**)FRAME_PTR();
- // Get the caller of the caller.
- cur = (void**)cur[0];
- F.previousFrame = lastKnownFrame;
- F.currentFP = cur;
- F.currentIP = FRAME_IP(cur);
- lastKnownFrame = &F;
-}
-
-void Thread::endUnknownFrame() {
- assert(lastKnownFrame->currentIP != NULL);
- lastKnownFrame = lastKnownFrame->previousFrame;
-}
-
-#if defined(__MACH__)
-#define SELF_HANDLE RTLD_DEFAULT
-#else
-#define SELF_HANDLE 0
-#endif
-
-Thread* Thread::setPendingException(gc *obj) {
- llvm_gcroot(obj, 0);
- assert(pendingException == 0 && "pending exception already there?");
- pendingException = obj;
- return this;
-}
-
-void Thread::throwIt() {
- assert(pendingException);
-
-#ifdef RUNTIME_DWARF_EXCEPTIONS
- // Use dlsym instead of getting the functions statically with extern "C"
- // because gcc compiles exceptions differently.
- typedef void* (*cxa_allocate_exception_type)(unsigned);
- typedef void (*cxa_throw_type)(void*, void*, void*);
-
- static cxa_allocate_exception_type cxa_allocate_exception =
- (cxa_allocate_exception_type)(uintptr_t)
- dlsym(SELF_HANDLE, "__cxa_allocate_exception");
-
- static cxa_throw_type cxa_throw =
- (cxa_throw_type)(uintptr_t)
- dlsym(SELF_HANDLE, "__cxa_throw");
-
- void* exc = cxa_allocate_exception(0);
- // 32 = sizeof(_Unwind_Exception) in libgcc...
- internalPendingException = (void*)((uintptr_t)exc - 32);
- cxa_throw(exc, 0, 0);
-#else
-#if defined(__MACH__)
- _longjmp(lastExceptionBuffer->buffer, 1);
-#else
- longjmp(lastExceptionBuffer->buffer, 1);
-#endif
-#endif
-}
-
-void Thread::printBacktrace() {
- StackWalker Walker(this);
-
- while (MethodInfo* MI = Walker.get()) {
- MI->print(Walker.ip, Walker.addr);
- ++Walker;
- }
-}
-
-void Thread::getFrameContext(void** buffer) {
- mvm::StackWalker Walker(this);
- uint32_t i = 0;
-
- while (void* ip = *Walker) {
- buffer[i++] = ip;
- ++Walker;
- }
-}
-
-uint32_t Thread::getFrameContextLength() {
- mvm::StackWalker Walker(this);
- uint32_t i = 0;
-
- while (*Walker) {
- ++i;
- ++Walker;
- }
- return i;
-}
-
-MethodInfo* StackWalker::get() {
- if (addr == thread->baseSP) return 0;
- ip = FRAME_IP(addr);
- bool isStub = ((unsigned char*)ip)[0] == 0xCE;
- if (isStub) ip = addr[2];
- return thread->vmkit->IPToMethodInfo(ip);
-}
-
-void* StackWalker::operator*() {
- if (addr == thread->baseSP) return 0;
- ip = FRAME_IP(addr);
- bool isStub = ((unsigned char*)ip)[0] == 0xCE;
- if (isStub) ip = addr[2];
- return ip;
-}
-
-void StackWalker::operator++() {
- if (addr != thread->baseSP) {
- assert((addr < thread->baseSP) && "Corrupted stack");
- assert((addr < addr[0]) && "Corrupted stack");
- if ((frame != NULL) && (addr == frame->currentFP)) {
- assert(frame->currentIP == NULL);
- frame = frame->previousFrame;
- assert(frame != NULL);
- assert(frame->currentIP != NULL);
- addr = (void**)frame->currentFP;
- frame = frame->previousFrame;
- } else {
- addr = (void**)addr[0];
- }
- }
-}
-
-StackWalker::StackWalker(mvm::Thread* th) {
- thread = th;
- frame = th->lastKnownFrame;
- if (mvm::Thread::get() == th) {
- addr = (void**)FRAME_PTR();
- addr = (void**)addr[0];
- } else {
- addr = (void**)th->waitOnSP();
- if (frame) {
- assert(frame->currentFP >= addr);
- }
- if (frame && (addr == frame->currentFP)) {
- frame = frame->previousFrame;
- assert((frame == NULL) || (frame->currentIP == NULL));
- }
- }
- assert(addr && "No address to start with");
-}
-
-
-#ifdef WITH_LLVM_GCC
-void Thread::scanStack(uintptr_t closure) {
- StackWalker Walker(this);
- while (MethodInfo* MI = Walker.get()) {
- MI->scan(closure, Walker.ip, Walker.addr);
- ++Walker;
- }
-}
-
-#else
-
-void Thread::scanStack(uintptr_t closure) {
- register unsigned int **max = (unsigned int**)(void*)this->baseSP;
- if (mvm::Thread::get() != this) {
- register unsigned int **cur = (unsigned int**)this->waitOnSP();
- for(; cur<max; cur++) Collector::scanObject((void**)cur, closure);
- } else {
- jmp_buf buf;
- setjmp(buf);
- register unsigned int **cur = (unsigned int**)&buf;
- for(; cur<max; cur++) Collector::scanObject((void**)cur, closure);
- }
-}
-#endif
-
-void Thread::enterUncooperativeCode(unsigned level) {
- if (isMvmThread()) {
- if (!inRV) {
- assert(!lastSP && "SP already set when entering uncooperative code");
- // Get the caller.
- void* temp = FRAME_PTR();
- // Make sure to at least get the caller of the caller.
- ++level;
- while (level--) temp = ((void**)temp)[0];
- // The cas is not necessary, but it does a memory barrier.
- __sync_bool_compare_and_swap(&lastSP, 0, temp);
- if (doYield) joinRVBeforeEnter();
- assert(lastSP && "No last SP when entering uncooperative code");
- }
- }
-}
-
-void Thread::enterUncooperativeCode(void* SP) {
- if (isMvmThread()) {
- if (!inRV) {
- assert(!lastSP && "SP already set when entering uncooperative code");
- // The cas is not necessary, but it does a memory barrier.
- __sync_bool_compare_and_swap(&lastSP, 0, SP);
- if (doYield) joinRVBeforeEnter();
- assert(lastSP && "No last SP when entering uncooperative code");
- }
- }
-}
-
-void Thread::leaveUncooperativeCode() {
- if (isMvmThread()) {
- if (!inRV) {
- assert(lastSP && "No last SP when leaving uncooperative code");
- void* savedSP = lastSP;
- // The cas is not necessary, but it does a memory barrier.
- __sync_bool_compare_and_swap(&lastSP, lastSP, 0);
- // A rendezvous has just been initiated, join it.
- if (doYield) joinRVAfterLeave(savedSP);
- assert(!lastSP && "SP has a value after leaving uncooperative code");
- }
- }
-}
-
-void* Thread::waitOnSP() {
- // First see if we can get lastSP directly.
- void* sp = lastSP;
- if (sp) return sp;
-
- // Then loop a fixed number of iterations to get lastSP.
- for (uint32 count = 0; count < 1000; ++count) {
- sp = lastSP;
- if (sp) return sp;
- }
-
- // Finally, yield until lastSP is not set.
- while ((sp = lastSP) == NULL) mvm::Thread::yield();
-
- assert(sp != NULL && "Still no sp");
- return sp;
-}
-
-
-uintptr_t Thread::baseAddr = 0;
-
-// These could be set at runtime.
-#define STACK_SIZE 0x100000
-#define NR_THREADS 255
-
-#if (__WORDSIZE == 64)
-#define START_ADDR 0x110000000
-#define END_ADDR 0x170000000
-#else
-#define START_ADDR 0x10000000
-#define END_ADDR 0x70000000
-#endif
-
-/// StackThreadManager - This class allocates all stacks for threads. Because
-/// we want fast access to thread local data, and can not rely on platform
-/// dependent thread local storage (eg pthread keys are inefficient, tls is
-/// specific to Linux), we put thread local data at the bottom of the
-/// stack. A simple mask computes the thread local data , based on the current
-/// stack pointer.
-//
-/// The stacks are allocated at boot time. They must all be in the memory range
-/// 0x?0000000 and Ox(?+1)0000000, so that the thread local data can be computed
-/// and threads have a unique ID.
-///
-class StackThreadManager {
-public:
- uintptr_t baseAddr;
- uint32 allocPtr;
- uint32 used[NR_THREADS];
- LockNormal stackLock;
-
- StackThreadManager() {
- baseAddr = 0;
- uintptr_t ptr = START_ADDR;
-
- // Do an mmap at a fixed address. If the mmap fails for a given address
- // use the next one.
- while (!baseAddr && ptr != END_ADDR) {
- ptr = ptr + 0x10000000;
-#if defined (__MACH__)
- uint32 flags = MAP_PRIVATE | MAP_ANON | MAP_FIXED;
-#else
- uint32 flags = MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED;
-#endif
- baseAddr = (uintptr_t)mmap((void*)ptr, STACK_SIZE * NR_THREADS,
- PROT_READ | PROT_WRITE, flags, -1, 0);
- if (baseAddr == (uintptr_t)MAP_FAILED) baseAddr = 0;
- }
- if (!baseAddr) {
- fprintf(stderr, "Can not allocate thread memory\n");
- abort();
- }
-
- // Protect the page after the first page. The first page contains thread
- // specific data. The second page has no access rights to catch stack
- // overflows.
- uint32 pagesize = getpagesize();
- for (uint32 i = 0; i < NR_THREADS; ++i) {
- uintptr_t addr = baseAddr + (i * STACK_SIZE) + pagesize;
- mprotect((void*)addr, pagesize, PROT_NONE);
- }
-
- memset((void*)used, 0, NR_THREADS * sizeof(uint32));
- allocPtr = 0;
- mvm::Thread::baseAddr = baseAddr;
- }
-
- uintptr_t allocate() {
- stackLock.lock();
- uint32 myIndex = 0;
- do {
- if (!used[myIndex]) {
- used[myIndex] = 1;
- break;
- }
- ++myIndex;
- } while (myIndex != NR_THREADS);
-
- stackLock.unlock();
-
- if (myIndex != NR_THREADS)
- return baseAddr + myIndex * STACK_SIZE;
-
- return 0;
- }
-
-};
-
-
-/// Static allocate a stack manager. In the future, this should be virtual
-/// machine specific.
-StackThreadManager TheStackManager;
-
-extern void sigsegvHandler(int, siginfo_t*, void*);
-
-/// internalThreadStart - The initial function called by a thread. Sets some
-/// thread specific data, registers the thread to the GC and calls the
-/// given routine of th.
-///
-void Thread::internalThreadStart(mvm::Thread* th) {
- th->baseSP = FRAME_PTR();
-
- // Set the SIGSEGV handler to diagnose errors.
- struct sigaction sa;
- sigset_t mask;
- sigfillset(&mask);
- sa.sa_flags = SA_SIGINFO;
- sa.sa_mask = mask;
- sa.sa_sigaction = sigsegvHandler;
- sigaction(SIGSEGV, &sa, NULL);
-
-
- assert(th->vmkit && "VM not set in a thread");
-
- th->vmkit->rendezvous.prepareForJoin();
- th->routine(th);
- th->state &= ~THREAD_RUNNING;
- if(!(th->state & THREAD_DAEMON))
- th->vmkit->nonDaemonThreadsManager.leaveNonDaemonMode();
- th->vmkit->unregisterRunningThread(th);
-}
-
-/// start - Called by the creator of the thread to run the new thread.
-/// The thread is in a detached state, because each virtual machine has
-/// its own way of waiting for created threads.
-int Thread::start(void (*fct)(mvm::Thread*)) {
- pthread_attr_t attributs;
- pthread_attr_init(&attributs);
- pthread_attr_setstack(&attributs, this, STACK_SIZE);
- routine = fct;
- // Make sure to add it in the list of threads before leaving this function:
- // the garbage collector wants to trace this thread.
- state |= THREAD_RUNNING;
- if(!(state & THREAD_DAEMON))
- vmkit->nonDaemonThreadsManager.enterNonDaemonMode();
- vmkit->registerRunningThread(this);
- int res = pthread_create((pthread_t*)(void*)(&internalThreadID), &attributs,
- (void* (*)(void *))internalThreadStart, this);
- pthread_detach((pthread_t)internalThreadID);
- pthread_attr_destroy(&attributs);
- return res;
-}
-
-/// operator new - Get a stack from the stack manager. The Thread object
-/// will be placed in the first page at the bottom of the stack. Hence
-/// Thread objects can not exceed a page.
-void* Thread::operator new(size_t sz) {
- assert(sz < (size_t)getpagesize() && "Thread local data too big");
- void* res = (void*)TheStackManager.allocate();
- // Give it a second chance.
- if (res == NULL) {
- Collector::collect();
- // Wait for the finalizer to have cleaned up the threads.
- while (res == NULL) {
- mvm::Thread::yield();
- res = (void*)TheStackManager.allocate();
- }
- }
- // Make sure the thread information is cleared.
- memset(res, 0, sz);
- return res;
-}
-
-void Thread::operator delete(void* th) {
- uintptr_t index = ((uintptr_t)th & Thread::IDMask);
- index = (index & ~TheStackManager.baseAddr) >> 20;
- TheStackManager.used[index] = 0;
-}
-
-Thread::~Thread() {
- // It seems like the pthread implementation in Linux is clearing with NULL
- // the stack of the thread. So we have to get the thread id before
- // calling pthread_join.
- void* thread_id = internalThreadID;
- if (thread_id != NULL) {
- // Wait for the thread to die.
- pthread_join((pthread_t)thread_id, NULL);
- }
- vmkit->unregisterPreparedThread(this);
-}
-
diff --git a/vmkit/lib/Mvm/Compiler/Disassembler.cpp b/vmkit/lib/Mvm/Compiler/Disassembler.cpp
deleted file mode 100644
index 8e94fa3..0000000
--- a/vmkit/lib/Mvm/Compiler/Disassembler.cpp
+++ /dev/null
@@ -1,91 +0,0 @@
-//===--------- Disassembler.cc - Intefarce to disassembler ----------------===//
-//
-// Micro Virtual Machine
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#include "mvm/JIT.h"
-
-#ifdef HAVE_DISASSEMBLER
-
-#if defined(__PPC__)
-extern "C"
-{
-# include <dis-asm.h>
-# include <bfd.h>
-}
-
-
-
-static struct disassemble_info info;
-static int initialised= 0;
-
-// this is the only function exported from this file
-
-int mvm::MvmModule::disassemble(unsigned int *addr)
-{
-
- if (!initialised)
- {
- INIT_DISASSEMBLE_INFO(info, stdout, fprintf);
- info.flavour= bfd_target_elf_flavour;
- info.arch= bfd_arch_powerpc;
- info.mach= bfd_mach_ppc_750; // generic(ish) == PPC G3
- info.endian= BFD_ENDIAN_BIG;
- info.buffer_length= 65536;
- }
- info.buffer= (bfd_byte *)addr;
- info.buffer_vma= (bfd_vma)(long)addr;
- return print_insn_big_powerpc((bfd_vma)(long)addr, &info);
-
-}
-
-#elif defined(__i386__)
-extern "C"
-{
-# include <bfd.h> // bfd types
-# include <dis-asm.h> // disassemble_info
- int print_insn_i386_att(bfd_vma, disassemble_info *);
-}
-
-
-static struct disassemble_info info;
-static int initialised= 0;
-
-
-int mvm::MvmModule::disassemble(unsigned int *addr)
-{
- if (!initialised)
- {
- INIT_DISASSEMBLE_INFO(info, stdout, fprintf);
- info.flavour= bfd_target_elf_flavour;
- info.arch= bfd_arch_i386;
- info.mach= bfd_mach_i386_i386;
- info.endian= BFD_ENDIAN_LITTLE;
- info.buffer_length= 65536;
- }
- info.buffer= (bfd_byte *)addr;
- info.buffer_vma= (bfd_vma)(long)addr;
- return print_insn_i386_att((bfd_vma)(long)addr, &info);
-}
-
-#else
-
-int mvm::MvmModule::disassemble(unsigned int* addr) {
- return 0;
-}
-
-#endif
-
-#else
-
-int mvm::MvmModule::disassemble(unsigned int* addr) {
- return 0;
-}
-
-#endif
-
-
diff --git a/vmkit/lib/Mvm/Compiler/EscapeAnalysis.cpp b/vmkit/lib/Mvm/Compiler/EscapeAnalysis.cpp
deleted file mode 100644
index 81bf078..0000000
--- a/vmkit/lib/Mvm/Compiler/EscapeAnalysis.cpp
+++ /dev/null
@@ -1,252 +0,0 @@
-//===------EscapeAnalysis.cpp - Simple LLVM escape analysis ---------------===//
-//
-// The VMKit project
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-
-#include "llvm/Constants.h"
-#include "llvm/Function.h"
-#include "llvm/GlobalVariable.h"
-#include "llvm/Module.h"
-#include "llvm/Pass.h"
-#include "llvm/Instructions.h"
-#include "llvm/Analysis/LoopInfo.h"
-#include "llvm/Support/CallSite.h"
-#include "llvm/Support/Compiler.h"
-#include "llvm/Support/Debug.h"
-#include "llvm/Support/raw_ostream.h"
-
-#include <cstddef>
-#include <map>
-
-#include "mvm/GC.h"
-
-using namespace llvm;
-using namespace mvm;
-
-namespace {
-
- class EscapeAnalysis : public FunctionPass {
- public:
- static char ID;
- uint64_t pageSize;
- EscapeAnalysis() : FunctionPass(ID) {
- pageSize = getpagesize();
- }
-
- virtual void getAnalysisUsage(AnalysisUsage &AU) const {
- AU.addRequired<LoopInfo>();
- }
-
- virtual bool runOnFunction(Function &F);
-
- private:
- bool processMalloc(Instruction* I, Value* Size, Value* VT, Loop* CurLoop);
- };
-
- char EscapeAnalysis::ID = 0;
- RegisterPass<EscapeAnalysis> X("EscapeAnalysis", "Escape Analysis Pass");
-
-bool EscapeAnalysis::runOnFunction(Function& F) {
- bool Changed = false;
- Function* Allocator = F.getParent()->getFunction("gcmalloc");
- if (!Allocator) return Changed;
-
- LoopInfo* LI = &getAnalysis<LoopInfo>();
-
- for (Function::iterator BI = F.begin(), BE = F.end(); BI != BE; BI++) {
- BasicBlock *Cur = BI;
-
- // Get the parent loop if there is one. If the allocation happens in a loop
- // we must make sure that the allocated value is not used outside of
- // the loop. If the allocation does not escape and it is only used inside
- // the loop, we will hoist the allocation in the pre-header of the loop.
- Loop* CurLoop = LI->getLoopFor(Cur);
- if (CurLoop) {
- Loop* NextLoop = CurLoop->getParentLoop();
- while (NextLoop) {
- CurLoop = NextLoop;
- NextLoop = CurLoop->getParentLoop();
- }
- }
-
- for (BasicBlock::iterator II = Cur->begin(), IE = Cur->end(); II != IE;) {
- Instruction *I = II;
- II++;
- if (I->getOpcode() != Instruction::Call &&
- I->getOpcode() != Instruction::Invoke) {
- continue;
- }
- CallSite Call(I);
- if (Call.getCalledValue() == Allocator) {
- if (CurLoop) {
- bool escapesLoop = false;
- for (Value::use_iterator U = I->use_begin(), E = I->use_end();
- U != E; ++U) {
- if (Instruction* II = dyn_cast<Instruction>(*U)) {
- BasicBlock* BBU = II->getParent();
- if (!CurLoop->contains(BBU)) {
- escapesLoop = true;
- break;
- }
- }
- }
-
- if (escapesLoop) continue;
- }
-
- if (CallInst *CI = dyn_cast<CallInst>(I)) {
- Changed |= processMalloc(CI, CI->getArgOperand(0), CI->getArgOperand(1),
- CurLoop);
- } else if (InvokeInst *CI = dyn_cast<InvokeInst>(I)) {
- Changed |= processMalloc(CI, CI->getArgOperand(0), CI->getArgOperand(1),
- CurLoop);
- }
- }
- }
- }
- return Changed;
-}
-
-
-
-
-static bool escapes(Value* Ins, std::map<Instruction*, bool>& visited) {
- for (Value::use_iterator I = Ins->use_begin(), E = Ins->use_end();
- I != E; ++I) {
- if (Instruction* II = dyn_cast<Instruction>(*I)) {
- if (II->getOpcode() == Instruction::Call ||
- II->getOpcode() == Instruction::Invoke) {
-
- CallSite CS(II);
- if (!CS.onlyReadsMemory()) return true;
-
- CallSite::arg_iterator B = CS.arg_begin(), E = CS.arg_end();
- for (CallSite::arg_iterator A = B; A != E; ++A) {
- if (A->get() == Ins &&
- !CS.paramHasAttr(A - B + 1, Attribute::NoCapture)) {
- return true;
- }
- }
-
- // We must also consider the value returned by the function.
- if (II->getType() == Ins->getType()) {
- if (escapes(II, visited)) return true;
- }
-
- } else if (dyn_cast<BitCastInst>(II)) {
- if (escapes(II, visited)) return true;
- } else if (StoreInst* SI = dyn_cast<StoreInst>(II)) {
- if (AllocaInst * AI = dyn_cast<AllocaInst>(SI->getOperand(1))) {
- if (!visited[AI]) {
- visited[AI] = true;
- if (escapes(AI, visited)) return true;
- }
- } else if (SI->getOperand(0) == Ins) {
- return true;
- }
- } else if (dyn_cast<LoadInst>(II)) {
- if (isa<PointerType>(II->getType())) {
- if (escapes(II, visited)) return true; // allocas
- }
- } else if (dyn_cast<GetElementPtrInst>(II)) {
- if (escapes(II, visited)) return true;
- } else if (dyn_cast<ReturnInst>(II)) {
- return true;
- } else if (dyn_cast<PHINode>(II)) {
- if (!visited[II]) {
- visited[II] = true;
- if (escapes(II, visited)) return true;
- }
- }
- } else {
- return true;
- }
- }
- return false;
-}
-
-bool EscapeAnalysis::processMalloc(Instruction* I, Value* Size, Value* VT,
- Loop* CurLoop) {
- Instruction* Alloc = I;
- LLVMContext& Context = Alloc->getParent()->getContext();
-
- ConstantInt* CI = dyn_cast<ConstantInt>(Size);
- bool hasFinalizer = true;
-
- if (CI) {
- if (ConstantExpr* CE = dyn_cast<ConstantExpr>(VT)) {
- if (ConstantInt* C = dyn_cast<ConstantInt>(CE->getOperand(0))) {
- VirtualTable* Table = (VirtualTable*)C->getZExtValue();
- hasFinalizer = (((void**)Table)[0] != 0);
- } else {
- GlobalVariable* GV = dyn_cast<GlobalVariable>(CE->getOperand(0));
- if (GV->hasInitializer()) {
- Constant* Init = GV->getInitializer();
- if (ConstantArray* CA = dyn_cast<ConstantArray>(Init)) {
- Constant* V = CA->getOperand(0);
- hasFinalizer = !V->isNullValue();
- }
- }
- }
- }
- } else {
- return false;
- }
-
- // The object does not have a finalizer and is never used. Remove the
- // allocation as it will not have side effects.
- if (!hasFinalizer && !Alloc->getNumUses()) {
- DEBUG(errs() << "Escape analysis removes instruction " << *Alloc << ": ");
- Alloc->eraseFromParent();
- return true;
- }
-
- uint64_t NSize = CI->getZExtValue();
- // If the class has a finalize method, do not stack allocate the object.
- if (NSize < pageSize && !hasFinalizer) {
- std::map<Instruction*, bool> visited;
- bool esc = escapes(Alloc, visited);
- if (!esc) {
-
- if (CurLoop) {
- // The object does not escape and is only used in the loop where it
- // is allocated. We hoist the allocation in the pre-header so that
- // we don't end up with tons of allocations on the stack.
- BasicBlock* BB = CurLoop->getLoopPreheader();
- assert(BB && "No Preheader!");
- DEBUG(errs() << "Escape analysis hoisting to " << BB->getNameStr());
- DEBUG(errs() << ": ");
- DEBUG(errs() << *Alloc);
- Alloc->removeFromParent();
- BB->getInstList().insert(BB->getTerminator(), Alloc);
- }
-
- AllocaInst* AI = new AllocaInst(Type::getInt8Ty(Context), Size, "",
- Alloc);
- BitCastInst* BI = new BitCastInst(AI, Alloc->getType(), "", Alloc);
- DEBUG(errs() << "escape");
- DEBUG(errs() << Alloc->getParent()->getParent()->getNameStr() << "\n");
- Alloc->replaceAllUsesWith(BI);
- // If it's an invoke, replace the invoke with a direct branch.
- if (InvokeInst *CI = dyn_cast<InvokeInst>(Alloc)) {
- BranchInst::Create(CI->getNormalDest(), Alloc);
- }
- Alloc->eraseFromParent();
- return true;
- }
- }
- return false;
-}
-}
-
-namespace mvm {
-FunctionPass* createEscapeAnalysisPass() {
- return new EscapeAnalysis();
-}
-
-}
diff --git a/vmkit/lib/Mvm/Compiler/InlineMalloc.cpp b/vmkit/lib/Mvm/Compiler/InlineMalloc.cpp
deleted file mode 100644
index fc89db3..0000000
--- a/vmkit/lib/Mvm/Compiler/InlineMalloc.cpp
+++ /dev/null
@@ -1,75 +0,0 @@
-//===------------- InlineMalloc.cpp - Inline allocations -----------------===//
-//
-// The VMKit project
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#include "llvm/Constants.h"
-#include "llvm/GlobalVariable.h"
-#include "llvm/Function.h"
-#include "llvm/Instructions.h"
-#include "llvm/Module.h"
-#include "llvm/Pass.h"
-#include "llvm/Support/CallSite.h"
-#include "llvm/Support/Debug.h"
-#include "llvm/Support/raw_ostream.h"
-#include "llvm/Transforms/Utils/Cloning.h"
-
-#include "mvm/JIT.h"
-
-using namespace llvm;
-
-namespace mvm {
-
- class InlineMalloc : public FunctionPass {
- public:
- static char ID;
- InlineMalloc() : FunctionPass(ID) {}
-
- virtual bool runOnFunction(Function &F);
- private:
- };
- char InlineMalloc::ID = 0;
-
-#if 0
- static RegisterPass<InlineMalloc> X("InlineMalloc",
- "Inline calls to gcmalloc");
-#endif
-
-
-bool InlineMalloc::runOnFunction(Function& F) {
- Function* Malloc = F.getParent()->getFunction("gcmalloc");
- if (!Malloc || Malloc->isDeclaration()) return false;
- bool Changed = false;
- for (Function::iterator BI = F.begin(), BE = F.end(); BI != BE; BI++) {
- BasicBlock *Cur = BI;
- for (BasicBlock::iterator II = Cur->begin(), IE = Cur->end(); II != IE;) {
- Instruction *I = II;
- II++;
- if (I->getOpcode() != Instruction::Call &&
- I->getOpcode() != Instruction::Invoke) {
- continue;
- }
- CallSite Call(I);
- Function* Temp = Call.getCalledFunction();
- if (Temp == Malloc) {
- if (dyn_cast<Constant>(Call.getArgument(0))) {
- InlineFunctionInfo IFI(NULL, mvm::MvmModule::TheTargetData);
- Changed |= InlineFunction(Call, IFI);
- break;
- }
- }
- }
- }
- return Changed;
-}
-
-
-FunctionPass* createInlineMallocPass() {
- return new InlineMalloc();
-}
-
-}
diff --git a/vmkit/lib/Mvm/Compiler/JIT.cpp b/vmkit/lib/Mvm/Compiler/JIT.cpp
deleted file mode 100644
index 8b8999f..0000000
--- a/vmkit/lib/Mvm/Compiler/JIT.cpp
+++ /dev/null
@@ -1,493 +0,0 @@
-//===---------------- JIT.cc - Initialize the JIT -------------------------===//
-//
-// The Micro Virtual Machine
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#include <llvm/CallingConv.h>
-#include <llvm/Constants.h>
-#include <llvm/DerivedTypes.h>
-#include <llvm/Instructions.h>
-#include <llvm/LinkAllPasses.h>
-#include <llvm/Linker.h>
-#include <llvm/LLVMContext.h>
-#include <llvm/Module.h>
-#include <llvm/PassManager.h>
-#include <llvm/Type.h>
-#include <llvm/Analysis/DebugInfo.h>
-#include <llvm/Analysis/LoopPass.h>
-#include <llvm/Analysis/Verifier.h>
-#include <llvm/Assembly/Parser.h>
-#include <llvm/CodeGen/GCStrategy.h>
-#include <llvm/CodeGen/JITCodeEmitter.h>
-#include <llvm/Config/config.h>
-#include <llvm/ExecutionEngine/ExecutionEngine.h>
-#include "llvm/ExecutionEngine/JITEventListener.h"
-#include "llvm/Support/CommandLine.h"
-#include <llvm/Support/Debug.h>
-#include <llvm/Support/IRReader.h>
-#include <llvm/Support/MutexGuard.h>
-#include <llvm/Support/PassNameParser.h>
-#include <llvm/Support/SourceMgr.h>
-#include <llvm/Target/TargetData.h>
-#include <llvm/Target/TargetMachine.h>
-#include <llvm/Target/TargetOptions.h>
-#include <llvm/Target/TargetSelect.h>
-#include <../lib/ExecutionEngine/JIT/JIT.h>
-
-#include "mvm/JIT.h"
-#include "mvm/Threads/Locks.h"
-#include "mvm/Threads/Thread.h"
-#include "mvm/VirtualMachine.h"
-#include "MutatorThread.h"
-#include "mvm/GC.h"
-#include "mvm/VMKit.h"
-
-#include <dlfcn.h>
-#include <sys/mman.h>
-
-#if defined(__MACH__)
-#define SELF_HANDLE RTLD_DEFAULT
-#else
-#define SELF_HANDLE 0
-#endif
-
-using namespace mvm;
-using namespace llvm;
-
-
-static cl::list<std::string>
-LoadBytecodeFiles("load-bc", cl::desc("Load bytecode file"), cl::ZeroOrMore,
- cl::CommaSeparated);
-
-cl::opt<bool> EmitDebugInfo("emit-debug-info",
- cl::desc("Emit debugging information"),
- cl::init(false));
-
-namespace mvm {
- namespace llvm_runtime {
- #include "LLVMRuntime.inc"
- }
- void linkVmkitGC();
-}
-
-const char* MvmModule::getHostTriple() {
- return LLVM_HOSTTRIPLE;
-}
-
-void MvmJITMethodInfo::print(void* ip, void* addr) {
- fprintf(stderr, "; %p (%p) in %s LLVM method\n", ip, addr,
- ((llvm::Function*)MetaInfo)->getName().data());
-}
-
-class MvmJITListener : public llvm::JITEventListener {
-public:
- virtual void NotifyFunctionEmitted(const Function &F,
- void *Code, size_t Size,
- const EmittedFunctionDetails &Details) {
- assert(F.getParent() == MvmModule::globalModule);
- assert(F.hasGC());
- // We know the last GC info is for this method.
- GCStrategy::iterator I = mvm::MvmModule::TheGCStrategy->end();
- I--;
- DEBUG(errs() << (*I)->getFunction().getName() << '\n');
- DEBUG(errs() << F.getName() << '\n');
- assert(&(*I)->getFunction() == &F &&
- "GC Info and method do not correspond");
- llvm::GCFunctionInfo* GFI = *I;
- JITMethodInfo* MI = new(*MvmModule::Allocator, "MvmJITMethodInfo")
- MvmJITMethodInfo(GFI, &F, MvmModule::executionEngine);
- MI->addToVMKit(mvm::Thread::get()->vmkit, (JIT*)MvmModule::executionEngine);
- }
-};
-
-void JITMethodInfo::addToVMKit(VMKit* vmkit, JIT* jit) {
- JITCodeEmitter* JCE = jit->getCodeEmitter();
- assert(GCInfo != NULL);
- for (GCFunctionInfo::iterator I = GCInfo->begin(), E = GCInfo->end();
- I != E;
- I++) {
- uintptr_t address = JCE->getLabelAddress(I->Label);
- assert(address != 0);
- vmkit->FunctionsCache.addMethodInfo(this, (void*)address);
- }
-}
-
-static MvmJITListener JITListener;
-
-void MvmModule::loadBytecodeFile(const std::string& str) {
- SMDiagnostic Err;
- Module* M = ParseIRFile(str, Err, globalModule->getContext());
- if (M) {
- M->setTargetTriple(getHostTriple());
- Linker::LinkModules(globalModule, M, 0);
- delete M;
- } else {
- Err.Print("load bytecode", errs());
- }
-}
-
-typedef void (*BootType)(uintptr_t Plan);
-typedef void (*BootHeapType)(intptr_t initial, intptr_t max);
-
-void MvmModule::initialise(CodeGenOpt::Level level, Module* M,
- TargetMachine* T) {
- mvm::linkVmkitGC();
-
- llvm_start_multithreaded();
-
- llvm::NoFramePointerElim = true;
- llvm::DisablePrettyStackTrace = true;
- llvm::JITEmitDebugInfo = EmitDebugInfo;
-#if DWARF_EXCEPTIONS
- llvm::JITExceptionHandling = true;
-#else
- llvm::JITExceptionHandling = false;
-#endif
-
- // Disable branch fold for accurate line numbers.
- const char* commands[2] = { "vmkit", "-disable-branch-fold" };
- llvm::cl::ParseCommandLineOptions(2, const_cast<char**>(commands));
-
- if (!M) {
- globalModule = new Module("bootstrap module", *(new LLVMContext()));
-
- InitializeNativeTarget();
-
- executionEngine = ExecutionEngine::createJIT(globalModule, 0,
- 0, level, false);
-
- Allocator = new BumpPtrAllocator();
- executionEngine->RegisterJITEventListener(&JITListener);
- std::string str =
- executionEngine->getTargetData()->getStringRepresentation();
- globalModule->setDataLayout(str);
- globalModule->setTargetTriple(getHostTriple());
-
- TheTargetData = executionEngine->getTargetData();
- } else {
- globalModule = M;
- TheTargetData = T->getTargetData();
- }
-
- //LLVMContext& Context = globalModule->getContext();
- //MetadataTypeKind = Context.getMDKindID("HighLevelType");
-
- for (std::vector<std::string>::iterator i = LoadBytecodeFiles.begin(),
- e = LoadBytecodeFiles.end(); i != e; ++i) {
- loadBytecodeFile(*i);
- }
-}
-
-BaseIntrinsics::BaseIntrinsics(llvm::Module* module) {
-
- module->setDataLayout(MvmModule::globalModule->getDataLayout());
- module->setTargetTriple(MvmModule::globalModule->getTargetTriple());
- LLVMContext& Context = module->getContext();
-
- typedef void (*init_inline_t)(llvm::Module* module);
- static const char* MMTkSymbol = "MMTk_InlineMethods";
- init_inline_t init_inline =
- (init_inline_t)(uintptr_t)dlsym(SELF_HANDLE, MMTkSymbol);
- if (init_inline != NULL) init_inline(module);
-
- mvm::llvm_runtime::makeLLVMModuleContents(module);
-
- // Type declaration
- ptrType = PointerType::getUnqual(Type::getInt8Ty(Context));
- ptr32Type = PointerType::getUnqual(Type::getInt32Ty(Context));
- ptrPtrType = PointerType::getUnqual(ptrType);
- pointerSizeType = module->getPointerSize() == Module::Pointer32 ?
- Type::getInt32Ty(Context) : Type::getInt64Ty(Context);
-
- // Constant declaration
- constantLongMinusOne = ConstantInt::get(Type::getInt64Ty(Context), (uint64_t)-1);
- constantLongZero = ConstantInt::get(Type::getInt64Ty(Context), 0);
- constantLongOne = ConstantInt::get(Type::getInt64Ty(Context), 1);
- constantZero = ConstantInt::get(Type::getInt32Ty(Context), 0);
- constantInt8Zero = ConstantInt::get(Type::getInt8Ty(Context), 0);
- constantOne = ConstantInt::get(Type::getInt32Ty(Context), 1);
- constantTwo = ConstantInt::get(Type::getInt32Ty(Context), 2);
- constantThree = ConstantInt::get(Type::getInt32Ty(Context), 3);
- constantFour = ConstantInt::get(Type::getInt32Ty(Context), 4);
- constantFive = ConstantInt::get(Type::getInt32Ty(Context), 5);
- constantSix = ConstantInt::get(Type::getInt32Ty(Context), 6);
- constantSeven = ConstantInt::get(Type::getInt32Ty(Context), 7);
- constantEight = ConstantInt::get(Type::getInt32Ty(Context), 8);
- constantMinusOne = ConstantInt::get(Type::getInt32Ty(Context), (uint64_t)-1);
- constantMinInt = ConstantInt::get(Type::getInt32Ty(Context), MinInt);
- constantMaxInt = ConstantInt::get(Type::getInt32Ty(Context), MaxInt);
- constantMinLong = ConstantInt::get(Type::getInt64Ty(Context), MinLong);
- constantMaxLong = ConstantInt::get(Type::getInt64Ty(Context), MaxLong);
- constantFloatZero = ConstantFP::get(Type::getFloatTy(Context), 0.0f);
- constantFloatOne = ConstantFP::get(Type::getFloatTy(Context), 1.0f);
- constantFloatTwo = ConstantFP::get(Type::getFloatTy(Context), 2.0f);
- constantDoubleZero = ConstantFP::get(Type::getDoubleTy(Context), 0.0);
- constantDoubleOne = ConstantFP::get(Type::getDoubleTy(Context), 1.0);
- constantMaxIntFloat = ConstantFP::get(Type::getFloatTy(Context), MaxIntFloat);
- constantMinIntFloat = ConstantFP::get(Type::getFloatTy(Context), MinIntFloat);
- constantMinLongFloat = ConstantFP::get(Type::getFloatTy(Context), MinLongFloat);
- constantMinLongDouble = ConstantFP::get(Type::getDoubleTy(Context), MinLongDouble);
- constantMaxLongFloat = ConstantFP::get(Type::getFloatTy(Context), MaxLongFloat);
- constantMaxIntDouble = ConstantFP::get(Type::getDoubleTy(Context), MaxIntDouble);
- constantMinIntDouble = ConstantFP::get(Type::getDoubleTy(Context), MinIntDouble);
- constantMaxLongDouble = ConstantFP::get(Type::getDoubleTy(Context), MaxLongDouble);
- constantMaxLongDouble = ConstantFP::get(Type::getDoubleTy(Context), MaxLongDouble);
- constantFloatInfinity = ConstantFP::get(Type::getFloatTy(Context), MaxFloat);
- constantFloatMinusInfinity = ConstantFP::get(Type::getFloatTy(Context), MinFloat);
- constantDoubleInfinity = ConstantFP::get(Type::getDoubleTy(Context), MaxDouble);
- constantDoubleMinusInfinity = ConstantFP::get(Type::getDoubleTy(Context), MinDouble);
- constantDoubleMinusZero = ConstantFP::get(Type::getDoubleTy(Context), -0.0);
- constantFloatMinusZero = ConstantFP::get(Type::getFloatTy(Context), -0.0f);
- constantThreadIDMask = ConstantInt::get(pointerSizeType, mvm::Thread::IDMask);
- constantStackOverflowMask =
- ConstantInt::get(pointerSizeType, mvm::Thread::StackOverflowMask);
- constantFatMask = ConstantInt::get(pointerSizeType,
- pointerSizeType == Type::getInt32Ty(Context) ? 0x80000000 : 0x8000000000000000LL);
- constantPtrOne = ConstantInt::get(pointerSizeType, 1);
- constantPtrZero = ConstantInt::get(pointerSizeType, 0);
-
- constantPtrNull = Constant::getNullValue(ptrType);
- constantPtrLogSize =
- ConstantInt::get(Type::getInt32Ty(Context), sizeof(void*) == 8 ? 3 : 2);
- arrayPtrType = PointerType::getUnqual(ArrayType::get(Type::getInt8Ty(Context), 0));
-
- printFloatLLVM = module->getFunction("printFloat");
- printDoubleLLVM = module->getFunction("printDouble");
- printLongLLVM = module->getFunction("printLong");
- printIntLLVM = module->getFunction("printInt");
- printObjectLLVM = module->getFunction("printObject");
-
- unwindResume = module->getFunction("_Unwind_Resume_or_Rethrow");
-
- llvmGetException = module->getFunction("llvm.eh.exception");
- exceptionSelector = module->getFunction("llvm.eh.selector");
-
- personality = module->getFunction("__gxx_personality_v0");
- exceptionEndCatch = module->getFunction("__cxa_end_catch");
- exceptionBeginCatch = module->getFunction("__cxa_begin_catch");
-
- func_llvm_sqrt_f64 = module->getFunction("llvm.sqrt.f64");
- func_llvm_sin_f64 = module->getFunction("llvm.sin.f64");
- func_llvm_cos_f64 = module->getFunction("llvm.cos.f64");
-
- func_llvm_tan_f64 = module->getFunction("tan");
- func_llvm_asin_f64 = module->getFunction("asin");
- func_llvm_acos_f64 = module->getFunction("acos");
- func_llvm_atan_f64 = module->getFunction("atan");
- func_llvm_exp_f64 = module->getFunction("exp");
- func_llvm_log_f64 = module->getFunction("log");
- func_llvm_ceil_f64 = module->getFunction("ceil");
- func_llvm_floor_f64 = module->getFunction("floor");
- func_llvm_cbrt_f64 = module->getFunction("cbrt");
- func_llvm_cosh_f64 = module->getFunction("cosh");
- func_llvm_expm1_f64 = module->getFunction("expm1");
- func_llvm_log10_f64 = module->getFunction("log10");
- func_llvm_log1p_f64 = module->getFunction("log1p");
- func_llvm_sinh_f64 = module->getFunction("sinh");
- func_llvm_tanh_f64 = module->getFunction("tanh");
- func_llvm_fabs_f64 = module->getFunction("fabs");
- func_llvm_rint_f64 = module->getFunction("rint");
-
- func_llvm_hypot_f64 = module->getFunction("hypot");
- func_llvm_pow_f64 = module->getFunction("pow");
- func_llvm_atan2_f64 = module->getFunction("atan2");
-
- func_llvm_fabs_f32 = module->getFunction("fabsf");
-
- setjmpLLVM = module->getFunction("setjmp");
-
- llvm_memcpy_i32 = module->getFunction("llvm.memcpy.i32");
- llvm_memset_i32 = module->getFunction("llvm.memset.i32");
- llvm_frameaddress = module->getFunction("llvm.frameaddress");
- llvm_gc_gcroot = module->getFunction("llvm.gcroot");
-
- llvm_atomic_lcs_i8 = module->getFunction("llvm.atomic.cmp.swap.i8.p0i8");
- llvm_atomic_lcs_i16 = module->getFunction("llvm.atomic.cmp.swap.i16.p0i16");
- llvm_atomic_lcs_i32 = module->getFunction("llvm.atomic.cmp.swap.i32.p0i32");
- llvm_atomic_lcs_i64 = module->getFunction("llvm.atomic.cmp.swap.i64.p0i64");
-
- llvm_atomic_lcs_ptr = pointerSizeType == Type::getInt32Ty(Context) ? llvm_atomic_lcs_i32 :
- llvm_atomic_lcs_i64;
-
- unconditionalSafePoint = module->getFunction("unconditionalSafePoint");
- conditionalSafePoint = module->getFunction("conditionalSafePoint");
- AllocateFunction = module->getFunction("gcmalloc");
- AllocateFunction->setGC("vmkit");
- assert(AllocateFunction && "No allocate function");
- AllocateUnresolvedFunction = module->getFunction("gcmallocUnresolved");
- assert(AllocateUnresolvedFunction && "No allocateUnresolved function");
- AddFinalizationCandidate = module->getFunction("addFinalizationCandidate");
- assert(AddFinalizationCandidate && "No addFinalizationCandidate function");
-
- VTType = PointerType::getUnqual(module->getTypeByName("VT"));
- MutatorThreadType = PointerType::getUnqual(module->getTypeByName("MutatorThread"));
-
- OffsetDoYieldInThreadConstant = ConstantInt::get(Type::getInt32Ty(Context), 1);
- OffsetCXXExceptionInThreadConstant = ConstantInt::get(Type::getInt32Ty(Context), 2);
- OffsetVMDataInThreadConstant = ConstantInt::get(Type::getInt32Ty(Context), 3);
- OffsetPendingExceptionInThreadConstant = ConstantInt::get(Type::getInt32Ty(Context), 4);
-
- OffsetThreadInMutatorThreadConstant = ConstantInt::get(Type::getInt32Ty(Context), 0);
-}
-
-const llvm::TargetData* MvmModule::TheTargetData;
-llvm::GCStrategy* MvmModule::TheGCStrategy;
-llvm::Module *MvmModule::globalModule;
-llvm::ExecutionEngine* MvmModule::executionEngine;
-mvm::LockRecursive MvmModule::protectEngine;
-mvm::BumpPtrAllocator* MvmModule::Allocator;
-//unsigned MvmModule::MetadataTypeKind;
-
-uint64 MvmModule::getTypeSize(const llvm::Type* type) {
- return TheTargetData->getTypeAllocSize(type);
-}
-
-void MvmModule::runPasses(llvm::Function* func,
- llvm::FunctionPassManager* pm) {
- // Take the lock because the pass manager will call materializeFunction.
- // Our implementation of materializeFunction requires that the lock is held
- // by the caller. This is due to LLVM's JIT subsystem where the call to
- // materializeFunction is guarded.
- pm->run(*func);
-}
-
-static void addPass(FunctionPassManager *PM, Pass *P) {
- // Add the pass to the pass manager...
- PM->add(P);
-}
-
-// This is equivalent to:
-// opt -simplifycfg -mem2reg -instcombine -jump-threading -simplifycfg
-// -scalarrepl -instcombine -condprop -simplifycfg -predsimplify
-// -reassociate -licm -loop-unswitch -indvars -loop-deletion -loop-unroll
-// -instcombine -gvn -sccp -simplifycfg -instcombine -condprop -dse -adce
-// -simplifycfg
-//
-static void AddStandardCompilePasses(FunctionPassManager* PM) {
-
- addPass(PM, createCFGSimplificationPass()); // Clean up disgusting code
- addPass(PM, createPromoteMemoryToRegisterPass());// Kill useless allocas
-
- addPass(PM, createInstructionCombiningPass()); // Cleanup for scalarrepl.
- addPass(PM, createScalarReplAggregatesPass()); // Break up aggregate allocas
- addPass(PM, createInstructionCombiningPass()); // Cleanup for scalarrepl.
- addPass(PM, createJumpThreadingPass()); // Thread jumps.
- addPass(PM, createCFGSimplificationPass()); // Merge & remove BBs
- addPass(PM, createInstructionCombiningPass()); // Combine silly seq's
-
- addPass(PM, createCFGSimplificationPass()); // Merge & remove BBs
- addPass(PM, createReassociatePass()); // Reassociate expressions
- addPass(PM, createLoopRotatePass()); // Rotate loops.
- addPass(PM, createLICMPass()); // Hoist loop invariants
- addPass(PM, createLoopUnswitchPass()); // Unswitch loops.
- addPass(PM, createInstructionCombiningPass());
- addPass(PM, createIndVarSimplifyPass()); // Canonicalize indvars
- addPass(PM, createLoopDeletionPass()); // Delete dead loops
- addPass(PM, createLoopUnrollPass()); // Unroll small loops*/
- addPass(PM, createInstructionCombiningPass()); // Clean up after the unroller
- addPass(PM, createGVNPass()); // Remove redundancies
- addPass(PM, createMemCpyOptPass()); // Remove memcpy / form memset
- addPass(PM, createSCCPPass()); // Constant prop with SCCP
-
- // Run instcombine after redundancy elimination to exploit opportunities
- // opened up by them.
- addPass(PM, createInstructionCombiningPass());
- addPass(PM, createJumpThreadingPass()); // Thread jumps
- addPass(PM, createDeadStoreEliminationPass()); // Delete dead stores
- addPass(PM, createAggressiveDCEPass()); // Delete dead instructions
- addPass(PM, createCFGSimplificationPass()); // Merge & remove BBs
-}
-
-static cl::opt<bool>
-DisableOptimizations("disable-opt",
- cl::desc("Do not run any optimization passes"));
-
-cl::opt<bool>
-StandardCompileOpts("std-compile-opts",
- cl::desc("Include the standard compile time optimizations"));
-
-// The OptimizationList is automatically populated with registered Passes by the
-// PassNameParser.
-//
-static llvm::cl::list<const llvm::PassInfo*, bool, llvm::PassNameParser>
-PassList(llvm::cl::desc("Optimizations available:"));
-
-namespace mvm {
- llvm::FunctionPass* createInlineMallocPass();
-}
-
-void MvmModule::addCommandLinePasses(FunctionPassManager* PM) {
- addPass(PM, new TargetData(*MvmModule::TheTargetData));
-
- addPass(PM, createVerifierPass()); // Verify that input is correct
-
-#ifdef WITH_MMTK
- addPass(PM, createCFGSimplificationPass()); // Clean up disgusting code
- addPass(PM, createInlineMallocPass());
-#endif
-
- // Create a new optimization pass for each one specified on the command line
- for (unsigned i = 0; i < PassList.size(); ++i) {
- // Check to see if -std-compile-opts was specified before this option. If
- // so, handle it.
- if (StandardCompileOpts &&
- StandardCompileOpts.getPosition() < PassList.getPosition(i)) {
- if (!DisableOptimizations) AddStandardCompilePasses(PM);
- StandardCompileOpts = false;
- }
-
- const PassInfo *PassInf = PassList[i];
- Pass *P = 0;
- if (PassInf->getNormalCtor())
- P = PassInf->getNormalCtor()();
- else
- errs() << "cannot create pass: "
- << PassInf->getPassName() << "\n";
- if (P) {
- bool isModulePass = (P->getPassKind() == PT_Module);
- if (isModulePass)
- errs() << "vmkit does not support module pass: "
- << PassInf->getPassName() << "\n";
- else addPass(PM, P);
-
- }
- }
-
- // If -std-compile-opts was specified at the end of the pass list, add them.
- if (StandardCompileOpts) {
- AddStandardCompilePasses(PM);
- }
- PM->doInitialization();
-}
-
-// We protect the creation of IR with the executionEngine lock because
-// codegen'ing a function may also create IR objects.
-void MvmModule::protectIR() {
- protectEngine.lock();
-}
-
-void MvmModule::unprotectIR() {
- protectEngine.unlock();
-}
-
-void JITMethodInfo::scan(uintptr_t closure, void* ip, void* addr) {
- if (GCInfo) {
- DEBUG(llvm::errs() << GCInfo->getFunction().getName() << '\n');
- // All safe points have the same informations currently in LLVM.
- llvm::GCFunctionInfo::iterator J = GCInfo->begin();
- //uintptr_t spaddr = (uintptr_t)addr + GFI->getFrameSize() + sizeof(void*);
- uintptr_t spaddr = ((uintptr_t*)addr)[0];
- for (llvm::GCFunctionInfo::live_iterator K = GCInfo->live_begin(J),
- KE = GCInfo->live_end(J); K != KE; ++K) {
- intptr_t obj = *(intptr_t*)(spaddr + K->StackOffset);
- // Verify that obj does not come from a JSR bytecode.
- if (!(obj & 1)) {
- Collector::scanObject((void**)(spaddr + K->StackOffset), closure);
- }
- }
- }
-}
diff --git a/vmkit/lib/Mvm/Compiler/LoopSafePoints.cpp b/vmkit/lib/Mvm/Compiler/LoopSafePoints.cpp
deleted file mode 100644
index 6155628..0000000
--- a/vmkit/lib/Mvm/Compiler/LoopSafePoints.cpp
+++ /dev/null
@@ -1,119 +0,0 @@
-//===------- LoopSafePoints.cpp - Add safe points in loop headers ---------===//
-//
-// The VMKit project
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-
-#include "llvm/Module.h"
-#include "llvm/Analysis/LoopPass.h"
-#include "llvm/Support/CallSite.h"
-#include "llvm/Support/Compiler.h"
-
-using namespace llvm;
-
-namespace {
-
- class LoopSafePoints : public LoopPass {
- public:
- static char ID;
-
- LoopSafePoints() : LoopPass(ID) {}
-
- virtual bool runOnLoop(Loop* L, LPPassManager& LPM);
-
- virtual void getAnalysisUsage(AnalysisUsage &AU) const {
- AU.addRequired<LoopInfo>();
- }
-
-
- private:
- void insertSafePoint(BasicBlock* BB, Function* SafeFunction,
- Value* YieldPtr, Loop* L, LoopInfo* LI);
- };
-
- char LoopSafePoints::ID = 0;
- RegisterPass<LoopSafePoints> X("LoopSafePoints",
- "Add safe points in loop headers");
-
-void LoopSafePoints::insertSafePoint(BasicBlock* BB, Function* SafeFunction,
- Value* YieldPtr, Loop* L, LoopInfo* LI) {
- Instruction* I = BB->getFirstNonPHI();
- BasicBlock* NBB = BB->splitBasicBlock(I);
- L->addBasicBlockToLoop(NBB, LI->getBase());
-
- NBB = NBB->getSinglePredecessor();
- I = NBB->getTerminator();
- BasicBlock* SU = (static_cast<BranchInst*>(I))->getSuccessor(0);
- I->eraseFromParent();
-
- Value* Ld = new LoadInst(YieldPtr, "", NBB);
- BasicBlock* yield = BasicBlock::Create(SafeFunction->getContext(), "",
- BB->getParent());
-
- BranchInst::Create(yield, SU, Ld, NBB);
-
- CallInst::Create(SafeFunction, "", yield);
- BranchInst::Create(SU, yield);
-
- L->addBasicBlockToLoop(yield, LI->getBase());
-}
-
-
-bool LoopSafePoints::runOnLoop(Loop* L, LPPassManager& LPM) {
-
- LoopInfo* LI = &getAnalysis<LoopInfo>();
- BasicBlock* Header = L->getHeader();
- Function *F = Header->getParent();
- Function* SafeFunction =
- F->getParent()->getFunction("conditionalSafePoint");
- if (!SafeFunction) return false;
-
- Value* YieldPtr = 0;
-
- // Lookup the yield pointer.
- for (Function::iterator BI = F->begin(), BE = F->end(); BI != BE; BI++) {
- BasicBlock *Cur = BI;
-
- for (BasicBlock::iterator II = Cur->begin(), IE = Cur->end(); II != IE;) {
- Instruction *I = II;
- II++;
- if (I->getOpcode() != Instruction::Call &&
- I->getOpcode() != Instruction::Invoke) {
- continue;
- }
-
- CallSite Call(I);
- if (Call.getCalledValue() == SafeFunction) {
- if (BasicBlock* Incoming = Cur->getSinglePredecessor()) {
- if (BranchInst* T = dyn_cast<BranchInst>(Incoming->getTerminator())) {
- if (LoadInst* LI = dyn_cast<LoadInst>(T->getCondition())) {
- YieldPtr = LI->getPointerOperand();
- break;
- }
- }
- }
- }
- }
- if (YieldPtr) break;
- }
-
- if (!YieldPtr) return false;
-
- insertSafePoint(Header, SafeFunction, YieldPtr, L, LI);
- return true;
-}
-
-}
-
-
-namespace mvm {
-
-LoopPass* createLoopSafePointsPass() {
- return new LoopSafePoints();
-}
-
-}
diff --git a/vmkit/lib/Mvm/Compiler/Makefile b/vmkit/lib/Mvm/Compiler/Makefile
deleted file mode 100644
index baea938..0000000
--- a/vmkit/lib/Mvm/Compiler/Makefile
+++ /dev/null
@@ -1,29 +0,0 @@
-##===- lib/Mvm/Runtime/Makefile ----------------------------*- Makefile -*-===##
-#
-# The vmkit project
-#
-# This file is distributed under the University of Illinois Open Source
-# License. See LICENSE.TXT for details.
-#
-##===----------------------------------------------------------------------===##
-LEVEL = ../../..
-
-include $(LEVEL)/Makefile.config
-
-ifeq ($(WITH_LLVM_GCC), 1)
- MODULE_NAME = MvmCompiler
-else
- LIBRARYNAME = MvmCompiler
-endif
-
-VMKIT_RUNTIME = $(PROJ_SRC_DIR)/mvm-runtime.ll
-
-ifeq ($(GC_MMTK), 1)
-VMKIT_RUNTIME += $(PROJ_SRC_DIR)/mvm-mmtk-thread.ll
-else
-VMKIT_RUNTIME += $(PROJ_SRC_DIR)/mvm-mmap2-thread.ll
-endif
-
-BUILT_SOURCES = LLVMRuntime.inc
-
-include $(LEVEL)/Makefile.common
diff --git a/vmkit/lib/Mvm/Compiler/VmkitGC.cpp b/vmkit/lib/Mvm/Compiler/VmkitGC.cpp
deleted file mode 100644
index a045980..0000000
--- a/vmkit/lib/Mvm/Compiler/VmkitGC.cpp
+++ /dev/null
@@ -1,35 +0,0 @@
-//===------- VmkitGC.cpp - GC for JIT-generated functions -----------------===//
-//
-// The VMKit project
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-
-#include "llvm/CodeGen/GCs.h"
-#include "llvm/CodeGen/GCStrategy.h"
-#include "llvm/Support/Compiler.h"
-
-#include "mvm/JIT.h"
-
-using namespace llvm;
-
-namespace {
- class VmkitGC : public GCStrategy {
- public:
- VmkitGC();
- };
-}
-
-namespace mvm {
- void linkVmkitGC() { }
-}
-
-static GCRegistry::Add<VmkitGC>
-X("vmkit", "VMKit GC for JIT-generated functions");
-
-VmkitGC::VmkitGC() {
- NeededSafePoints = 1 << GC::PostCall;
-}
diff --git a/vmkit/lib/Mvm/Compiler/mvm-mmap2-thread.ll b/vmkit/lib/Mvm/Compiler/mvm-mmap2-thread.ll
deleted file mode 100644
index ff4615c..0000000
--- a/vmkit/lib/Mvm/Compiler/mvm-mmap2-thread.ll
+++ /dev/null
@@ -1,2 +0,0 @@
-;;; Field 0: the thread
-%MutatorThread = type { %Thread }
diff --git a/vmkit/lib/Mvm/Compiler/mvm-mmtk-thread.ll b/vmkit/lib/Mvm/Compiler/mvm-mmtk-thread.ll
deleted file mode 100644
index 1c9ac19..0000000
--- a/vmkit/lib/Mvm/Compiler/mvm-mmtk-thread.ll
+++ /dev/null
@@ -1,7 +0,0 @@
-%BumpPtrAllocator = type { i32, i8*, i8*, i8*, i8*, i8*, i8*, i8* }
-
-;;; Field 0: the thread
-;;; field 1: allocator
-;;; field 2: MutatorContext
-;;; field 3: realRoutine
-%MutatorThread = type { %Thread, %BumpPtrAllocator, i8*, i8* }
diff --git a/vmkit/lib/Mvm/Compiler/mvm-runtime.ll b/vmkit/lib/Mvm/Compiler/mvm-runtime.ll
deleted file mode 100644
index a7c67e2..0000000
--- a/vmkit/lib/Mvm/Compiler/mvm-runtime.ll
+++ /dev/null
@@ -1,111 +0,0 @@
-;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
-;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; Common types ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
-;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
-
-;;; A virtual table is an array of function pointers.
-%VT = type [0 x i32 (...)*]
-
-%CircularBase = type { %VT*, %CircularBase*, %CircularBase* }
-
-;;; Field 0: the parent (circular base)
-;;; Field 1: bool doYield
-;;; field 2: void* lastExceptionBuffer/internalPendingException
-;;; field 3: void* vmData
-;;; field 4: gc* pendingException
-;;; field 5: VMkit* vmkit
-;;; Field 6: void* baseSP
-;;; Field 7: bool inRV
-;;; Field 8: bool joinedRV
-;;; Field 9: void* lastSP
-;;; Field 10: void* internalThreadID
-;;; field 11: void* routine
-;;; field 12: void* lastKnownFrame
-;;; field 13: void* allVMDatas
-;;; field 14: uint32 state
-%Thread = type { %CircularBase, i1, i8*, i8*, i8*, i8*, i8*, i1, i1, i8*, i8*, i8*, i8*, i8*, i32 }
-
-;;; field 0: VT
-;;; field 1: mvm::MutatorThread* mut
-;;; field 2: mvm::VirtualMachine* vm
-%VMThreadData = type { %VT*, %MutatorThread*, i8* }
-
-;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
-;;;;;;;;;;;;;;;;;;;;;;;;;;;;; Printing functions ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
-;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
-
-declare void @printFloat(float)
-declare void @printDouble(double)
-declare void @printLong(i64)
-declare void @printInt(i32)
-declare void @printObject(i8*)
-
-;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
-;;;;;;;;;;;;;;;;;;;;;;;;;;;;; Exceptions ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
-;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
-
-declare void @_Unwind_Resume_or_Rethrow(i8*)
-declare i8* @llvm.eh.exception() nounwind
-declare i32 @llvm.eh.selector.i32(i8*, i8*, ...) nounwind
-declare i64 @llvm.eh.selector.i64(i8*, i8*, ...) nounwind
-declare void @__gxx_personality_v0()
-declare i8* @__cxa_begin_catch(i8*)
-declare void @__cxa_end_catch()
-declare i32 @setjmp(i8*)
-
-;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
-;;;;;;;;;;;;;;;;;;;;;;;;;;;;; Math ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
-;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
-
-declare double @llvm.sqrt.f64(double) nounwind
-declare double @llvm.sin.f64(double) nounwind
-declare double @llvm.cos.f64(double) nounwind
-declare double @tan(double)
-declare double @asin(double)
-declare double @acos(double)
-declare double @atan(double)
-declare double @exp(double)
-declare double @log(double)
-declare double @ceil(double)
-declare double @floor(double)
-declare double @cbrt(double)
-declare double @cosh(double)
-declare double @expm1(double)
-declare double @log10(double)
-declare double @log1p(double)
-declare double @sinh(double)
-declare double @tanh(double)
-declare double @fabs(double)
-declare double @rint(double)
-declare double @hypot(double, double)
-declare double @pow(double, double)
-declare double @atan2(double, double)
-declare float @fabsf(float)
-
-;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
-;;;;;;;;;;;;;;;;;;;;;;;;;;;;; Memory ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
-;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
-
-declare void @llvm.memcpy.i32(i8 *, i8 *, i32, i32) nounwind
-declare void @llvm.memset.i32(i8 *, i8, i32, i32) nounwind
-declare i8* @llvm.frameaddress(i32) nounwind readnone
-
-;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
-;;;;;;;;;;;;;;;;;;;;;;;;;;;;; Atomic ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
-;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
-
-declare i8 @llvm.atomic.cmp.swap.i8.p0i8(i8*, i8, i8) nounwind
-declare i16 @llvm.atomic.cmp.swap.i16.p0i16(i16*, i16, i16) nounwind
-declare i32 @llvm.atomic.cmp.swap.i32.p0i32(i32*, i32, i32) nounwind
-declare i64 @llvm.atomic.cmp.swap.i64.p0i64(i64*, i64, i64) nounwind
-
-declare void @unconditionalSafePoint() nounwind
-declare void @conditionalSafePoint() nounwind
-
-;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
-;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; GC ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
-;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
-
-declare void @llvm.gcroot(i8**, i8*)
-declare i8* @gcmalloc(i32, i8*)
-declare i8* @gcmallocUnresolved(i32, i8*)
-declare void @addFinalizationCandidate(i8*)
diff --git a/vmkit/lib/Mvm/GCMmap2/Makefile b/vmkit/lib/Mvm/GCMmap2/Makefile
deleted file mode 100644
index fd33b56..0000000
--- a/vmkit/lib/Mvm/GCMmap2/Makefile
+++ /dev/null
@@ -1,21 +0,0 @@
-##===- lib/Mvm/GCMmap2/Makefile ----------------------------*- Makefile -*-===##
-#
-# The vmkit project
-#
-# This file is distributed under the University of Illinois Open Source
-# License. See LICENSE.TXT for details.
-#
-##===----------------------------------------------------------------------===##
-LEVEL = ../../..
-
-include $(LEVEL)/Makefile.config
-
-ifeq ($(WITH_LLVM_GCC), 1)
- MODULE_NAME = GCMmap2
-else
- LIBRARYNAME = GCMmap2
-endif
-
-include $(LEVEL)/Makefile.common
-
-CXX.Flags += -I$(PROJ_SRC_DIR)/../CommonThread -I$(PROJ_SRC_DIR)/../Allocator
diff --git a/vmkit/lib/Mvm/GCMmap2/MutatorThread.h b/vmkit/lib/Mvm/GCMmap2/MutatorThread.h
deleted file mode 100644
index 1a927e2..0000000
--- a/vmkit/lib/Mvm/GCMmap2/MutatorThread.h
+++ /dev/null
@@ -1,25 +0,0 @@
-//===--------- MutatorThread.h - Thread for GC ----------------------------===//
-//
-// The VMKit project
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-
-#ifndef MVM_MUTATOR_THREAD_H
-#define MVM_MUTATOR_THREAD_H
-
-#include "mvm/Threads/Thread.h"
-
-namespace mvm {
-
-class MutatorThread : public mvm::Thread {
-public:
- MutatorThread(VMKit* vmkit) : mvm::Thread(vmkit) {}
-};
-
-}
-
-#endif
diff --git a/vmkit/lib/Mvm/GCMmap2/MvmGC.h b/vmkit/lib/Mvm/GCMmap2/MvmGC.h
deleted file mode 100644
index 0bfd242..0000000
--- a/vmkit/lib/Mvm/GCMmap2/MvmGC.h
+++ /dev/null
@@ -1,300 +0,0 @@
-//===----------- MvmGC.h - Garbage Collection Interface -------------------===//
-//
-// The Micro Virtual Machine
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-
-#ifndef MVM_MMAP_GC_H
-#define MVM_MMAP_GC_H
-
-#include "types.h"
-#include "gcalloc.h"
-#include "mvm/VirtualMachine.h"
-
-#define gc_allocator std::allocator
-
-using namespace mvm;
-
-namespace mvm {
- class Thread;
- class VirtualMachine;
-
-class GCVirtualTable : public CommonVirtualTable {
-public:
- static uint32_t numberOfBaseFunctions() {
- return numberOfCommonEntries();
- }
-
- static uint32_t numberOfSpecializedTracers() {
- return 0;
- }
-};
-
-class Collector {
- friend class GCThread;
- friend class CollectionRV;
- static GCAllocator *allocator; /* The allocator */
- static SpinLock _globalLock; /* Global lock for allocation */
-
- static GCChunkNode *used_nodes; /* Used memory nodes */
- static GCChunkNode *unused_nodes; /* Unused memory nodes */
- static unsigned int current_mark;
-
- static int _collect_freq_auto; /* Collection frequency in gcmalloc/gcrealloc */
- static int _collect_freq_maybe; /* Collection frequency in maybeCollect */
- static int _since_last_collection; /* Bytes left since last collection */
- static bool _enable_auto; /* Automatic collection? */
- static bool _enable_maybe; /* Collection in maybeCollect()? */
- static bool _enable_collection; /* collection authorized? */
- static int status;
-
-
- enum { stat_collect, stat_alloc, stat_broken };
-
- static inline void lock() { _globalLock.lock(); }
- static inline void unlock() { _globalLock.unlock(); }
-
- /* Interface for collection, verifies enable_collect */
- static void collect_unprotect();
- /* The collection */
- static void do_collect();
-
- static inline GCChunkNode *o2node(const void *p) {
- if (!p) return 0;
- return GCHash::get(const_cast<void*>(p))->o2node(const_cast<void*>(p), GCChunkNode::maskCollectable);
- }
-
- static inline size_t real_nbb(GCChunkNode *n) {
- return n->nbb() - sizeof(gcRoot);
- }
-
-
-public:
- static void (*internMemoryError)(unsigned int);
-
- static int verbose;
-
- static bool isLive(void* ptr, uintptr_t closure) {
- GCChunkNode *node = o2node(ptr);
-
- if(node && isMarked(node)) return true;
- else return false;
- }
-
- static void scanObject(void** ptr, uintptr_t closure);
-
- static void initialise();
- static void destroy();
-
- static inline void *allocate_unprotected(size_t sz) {
- return allocator->alloc(sz);
- }
-
- static inline void free_unprotected(void *ptr) {
- allocator->free(ptr);
- }
-
- static inline void *begOf(const void *p) {
- GCChunkNode *node = o2node(p);
- if(node)
- return node->chunk();
- else
- return 0;
- }
-
- static void gcStats(size_t *no, size_t *nbb);
-
- static inline size_t objectSize(void *ptr) {
- GCChunkNode *node = o2node(ptr);
- return node ? real_nbb(node) : 0;
- }
-
- static inline void collect() {
- lock();
- collect_unprotect();
- unlock();
- }
-
- static inline void maybeCollect() {
- if(_enable_auto && (_since_last_collection <= (_collect_freq_auto - _collect_freq_maybe)))
- collect();
- }
-
- static inline void *gcmalloc(VirtualTable *vt, size_t n) {
-#if (__WORDSIZE == 64)
- void* res = malloc(n);
- memset(res, 0, n);
- ((void**)res)[0] = vt;
- return res;
-#else
- lock();
-
- _since_last_collection -= n;
- if(_enable_auto && (_since_last_collection <= 0)) {
- collect_unprotect();
- }
- register GCChunkNode *header = allocator->alloc_chunk(n, 1, current_mark & 1);
-
- header->append(used_nodes);
- register struct gcRoot *p = header->chunk();
- p->setVirtualTable(vt);
-
-
- unlock();
-
- if (((CommonVirtualTable*)vt)->destructor)
- mvm::Thread::get()->vmkit->addFinalizationCandidate((gc*)p);
-
-
- return p;
-#endif
- }
-
- static inline void *gcrealloc(void *ptr, size_t n) {
-#if (__WORDSIZE == 64)
- void* res = realloc(ptr, n);
- return res;
-#else
- lock();
-
- GCPage *desc = GCHash::get(ptr);
- GCChunkNode *node = desc->o2node(ptr, GCChunkNode::maskCollectable);
-
- if(!node)
- gcfatal("%p isn't a avalid object", ptr);
-
- size_t old_sz = node->nbb();
-
- _since_last_collection -= (n - old_sz);
-
- if(_enable_auto && (_since_last_collection <= 0)) {
- collect_unprotect();
- }
-
- GCChunkNode *res = allocator->realloc_chunk(desc, node, n);
-
- if(res != node) {
- res->append(used_nodes);
- mark(res);
- }
-
- gcRoot *obj = res->chunk();
-
- unlock();
- return obj;
-#endif
- }
-
- static inline unsigned int enable(unsigned int n) {
- register unsigned int old = _enable_collection;
- _enable_collection = n;
- return old;
- }
-
- static inline bool isMarked(GCChunkNode *node) {
- return node->mark() == (current_mark & 1);
- }
-
- static inline void mark(GCChunkNode *node) {
- node->_mark(current_mark & 1);
- }
-
- static inline void trace(GCChunkNode *node) {
- gcRoot *o = node->chunk();
- o->tracer(0);
- }
-
- static inline void markAndTrace(void* source, void *ptr, uintptr_t closure) {
- markAndTraceRoot(ptr, closure);
- }
-
- static inline void markAndTraceRoot(void *ptr, uintptr_t closure) {
- void* obj = *(void**)ptr;
- if (obj) {
- GCChunkNode *node = o2node(obj);
-
-#ifdef WITH_LLVM_GCC
- assert(node && "No node in precise mode");
- assert(obj == begOf(obj) && "Interior pointer");
-#endif
-
- if(node && !isMarked(node)) {
- mark(node);
- node->remove();
- node->prepend(used_nodes);
- }
- }
- }
-
- static int getMaxMemory() {
- return 0;
- }
-
- static int getFreeMemory() {
- return 0;
- }
-
- static int getTotalMemory() {
- return 0;
- }
-
- void setMaxMemory(size_t sz){
- }
-
- void setMinMemory(size_t sz){
- }
-
- static gc* retainForFinalize(gc* val, uintptr_t closure) {
- markAndTraceRoot(&val, closure);
- return val;
- }
-
- static gc* retainReferent(gc* val, uintptr_t closure) {
- markAndTraceRoot(&val, closure);
- return val;
- }
-
- static gc* getForwardedReference(gc* val, uintptr_t closure) {
- return val;
- }
-
- static gc* getForwardedReferent(gc* val, uintptr_t closure) {
- return val;
- }
-
- static gc* getForwardedFinalizable(gc* val, uintptr_t closure) {
- return val;
- }
-};
-
-class collectable : public gcRoot {
-public:
-
- size_t objectSize() const {
- return mvm::Collector::objectSize((void*)this);
- }
-
- void* operator new(size_t sz, VirtualTable *VT) {
- return mvm::Collector::gcmalloc(VT, sz);
- }
-
- void* operator new(size_t sz) {
- return malloc(sz);
- }
-
- void operator delete(void *) {
- gcfatal(0, "never call directly a destructor.....");
- }
-
- void* realloc(size_t n) {
- return mvm::Collector::gcrealloc(this, n);
- }
-
-};
-}
-
-#endif
diff --git a/vmkit/lib/Mvm/GCMmap2/ObjectHeader.h b/vmkit/lib/Mvm/GCMmap2/ObjectHeader.h
deleted file mode 100644
index 13436ce..0000000
--- a/vmkit/lib/Mvm/GCMmap2/ObjectHeader.h
+++ /dev/null
@@ -1,20 +0,0 @@
-//===----- ObjectHeader.h - Macros for describing an object header --------===//
-//
-// The VMKit project
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#ifndef MVM_OBJECT_HEADER_H
-#define MVM_OBJECT_HEADER_H
-
-#include <stdint.h>
-
-namespace mvm {
- static const uint32_t GCBits = 2;
- static const bool MovesObject = false;
-}
-
-#endif // MVM_OBJECT_HEADER_H
diff --git a/vmkit/lib/Mvm/GCMmap2/ctosdep.h b/vmkit/lib/Mvm/GCMmap2/ctosdep.h
deleted file mode 100644
index ab291ae..0000000
--- a/vmkit/lib/Mvm/GCMmap2/ctosdep.h
+++ /dev/null
@@ -1,26 +0,0 @@
-//===---------------- ctosdep.h - Mvm Garbage Collector -------------------===//
-//
-// Mvm
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#ifndef _CT_OSDEP_H_
-#define _CT_OSDEP_H_
-
-#include <sys/types.h>
-#include <cstdio>
-#include <cstdlib>
-
-#define tmalloc malloc
-#define tfree free
-
-class TObj {
-public:
- void *operator new(size_t sz) { return tmalloc(sz); }
- void operator delete(void *ptr, size_t sz) { return tfree(ptr); }
-};
-
-#endif
diff --git a/vmkit/lib/Mvm/GCMmap2/gc.cpp b/vmkit/lib/Mvm/GCMmap2/gc.cpp
deleted file mode 100644
index 9c0fd8c..0000000
--- a/vmkit/lib/Mvm/GCMmap2/gc.cpp
+++ /dev/null
@@ -1,52 +0,0 @@
-//===---------------- gc.cc - Mvm Garbage Collector -----------------------===//
-//
-// Mvm
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#include "mvm/Threads/Thread.h"
-#include "mvm/GC.h"
-
-using namespace mvm;
-
-
-extern "C" void MarkAndTrace(gc* gc, uintptr_t closure) {
- Collector::markAndTraceRoot(&gc, closure);
-}
-
-extern "C" void* gcmalloc(size_t sz, VirtualTable* VT) {
- void* res = Collector::gcmalloc(VT, sz);
- return res;
-}
-
-extern "C" void* gcmallocUnresolved(size_t sz, VirtualTable* VT) {
- void* res = 0;
- llvm_gcroot(res, 0);
- res = Collector::gcmalloc(VT, sz);
- return res;
-}
-
-extern "C" void addFinalizationCandidate(gc* obj) {
- // This is useless with GCmmap2, as the gcmalloc already did it.
-}
-
-void Collector::scanObject(void** val, uintptr_t closure) {
- void* obj = *val;
- if (obj) {
- GCChunkNode *node = o2node(obj);
-
-#ifdef WITH_LLVM_GCC
- assert(begOf(obj) == obj && "Interior pointer\n");
- assert(node && "No node in precise GC mode");
-#endif
-
- if (node && !Collector::isMarked(node)) {
- node->remove();
- node->append(Collector::used_nodes);
- Collector::mark(node);
- }
- }
-}
diff --git a/vmkit/lib/Mvm/GCMmap2/gccollector.cpp b/vmkit/lib/Mvm/GCMmap2/gccollector.cpp
deleted file mode 100644
index 3cca104..0000000
--- a/vmkit/lib/Mvm/GCMmap2/gccollector.cpp
+++ /dev/null
@@ -1,121 +0,0 @@
-//===----------- gccollector.cc - Mvm Garbage Collector -------------------===//
-//
-// Mvm
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#include "mvm/GC.h"
-#include "mvm/VMKit.h"
-#include "mvm/SystemThreads.h"
-
-using namespace mvm;
-
-GCAllocator *Collector::allocator = 0;
-SpinLock Collector::_globalLock;
-
-int Collector::status;
-
-GCChunkNode *Collector::used_nodes;
-GCChunkNode *Collector::unused_nodes;
-
-unsigned int Collector::current_mark;
-
-int Collector::_collect_freq_auto;
-int Collector::_collect_freq_maybe;
-int Collector::_since_last_collection;
-
-bool Collector::_enable_auto;
-bool Collector::_enable_maybe;
-bool Collector::_enable_collection;
-
-int Collector::verbose = 0;
-
-void Collector::do_collect() {
- GCChunkNode *cur;
- _since_last_collection = _collect_freq_auto;
-
- current_mark++;
-
- unused_nodes->attrape(used_nodes);
-
- mvm::Thread* th = mvm::Thread::get();
- if(th->startCollection()) {
-
- mvm::Thread* tcur = th;
-
- // (1) Trace VMKit.
- th->vmkit->tracer(0);
-
- // (2) Trace the threads.
- do {
- tcur->scanStack(0);
- tcur->tracer(0);
- tcur = (mvm::Thread*)tcur->next();
- } while (tcur != th);
-
- // (3) Trace stack objects.
- for(cur = used_nodes->next(); cur != used_nodes; cur = cur->next())
- trace(cur);
-
- // Go back to the previous node.
- cur = cur->prev();
-
- // (4) Trace the weak reference queue.
- th->vmkit->scanWeakReferencesQueue(0);
-
- // (5) Trace the soft reference queue.
- th->vmkit->scanSoftReferencesQueue(0);
-
- // (6) Trace the finalization queue.
- th->vmkit->scanFinalizationQueue(0);
-
- // (7) Trace the phantom reference queue.
- th->vmkit->scanPhantomReferencesQueue(0);
-
- // (8) Trace the new objects added by queues.
- for(cur = cur->next(); cur != used_nodes; cur = cur->next())
- trace(cur);
-
-
- // Finalize.
- GCChunkNode finalizable;
- finalizable.attrape(unused_nodes);
-
- // We have stopped collecting, go back to alloc state.
- status = stat_alloc;
-
- // Wake up all threads.
- th->vmkit->rendezvous.finishRV();
- th->vmkit->endCollection();
-
- // Kill unreachable objects.
- GCChunkNode *next = 0;
- for(cur=finalizable.next(); cur!=&finalizable; cur=next) {
- next = cur->next();
- allocator->reject_chunk(cur);
- }
- }
-
-}
-
-void Collector::collect_unprotect() {
- if(_enable_collection && (status == stat_alloc)) {
- status = stat_collect;
- do_collect();
- }
-}
-
-void Collector::gcStats(size_t *_no, size_t *_nbb) {
- register unsigned int n, tot;
- register GCChunkNode *cur;
- lock();
- for(n=0, tot=0, cur=used_nodes->next(); cur!=used_nodes; cur=cur->next(), n++)
- tot += cur->nbb();
- unlock();
- *_no = n;
- *_nbb = tot;
-}
-
diff --git a/vmkit/lib/Mvm/GCMmap2/gcinit.cpp b/vmkit/lib/Mvm/GCMmap2/gcinit.cpp
deleted file mode 100644
index 62bc702..0000000
--- a/vmkit/lib/Mvm/GCMmap2/gcinit.cpp
+++ /dev/null
@@ -1,45 +0,0 @@
-//===--------------- gcinit.cc - Mvm Garbage Collector -------------------===//
-//
-// Mvm
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#include "mvm/GC.h"
-
-using namespace mvm;
-
-static const size_t def_collect_freq_auto = 64*1024*1024;
-static const size_t def_collect_freq_maybe = 64*1024*1024;
-
-
-void Collector::initialise() {
-
- used_nodes = new GCChunkNode();
- unused_nodes = new GCChunkNode();
- allocator = new GCAllocator();
-
- used_nodes->alone();
- unused_nodes->alone();
-
- current_mark = 0;
- status = stat_alloc;
-
- _collect_freq_auto = def_collect_freq_auto;
- _collect_freq_maybe = def_collect_freq_maybe;
-
- _since_last_collection = _collect_freq_auto;
-
- _enable_auto = 1;
- _enable_collection = 1;
- _enable_maybe = 1;
-
-}
-
-void Collector::destroy() {
- delete allocator;
- allocator = 0;
-}
-
diff --git a/vmkit/lib/Mvm/JITGCPass/JITGCPass.cpp b/vmkit/lib/Mvm/JITGCPass/JITGCPass.cpp
deleted file mode 100644
index b71eb21..0000000
--- a/vmkit/lib/Mvm/JITGCPass/JITGCPass.cpp
+++ /dev/null
@@ -1,63 +0,0 @@
-//===------ JITGCPass.cpp - Put GC information in functions compiled ---------//
-//===----------------------- with llvm-gcc --------------------------------===//
-//
-// The VMKit project
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-
-#include "llvm/Intrinsics.h"
-#include "llvm/Module.h"
-#include "llvm/Pass.h"
-#include "llvm/Support/raw_ostream.h"
-
-using namespace llvm;
-
-namespace {
-
- class JITGCPass : public ModulePass {
- public:
- static char ID;
-
- JITGCPass() : ModulePass(ID) {}
-
- virtual bool runOnModule(Module& M);
-
- /// getAnalysisUsage - We do not modify anything.
- virtual void getAnalysisUsage(AnalysisUsage &AU) const {
- AU.setPreservesAll();
- }
-
- };
-
- char JITGCPass::ID = 0;
- RegisterPass<JITGCPass> X("JITGCPass",
- "Add GC information in files compiled with llvm-gcc");
-
-bool JITGCPass::runOnModule(Module& M) {
-
- Function* F = M.getFunction("__llvm_gcroot");
- if (F) {
- Function *gcrootFun = Intrinsic::getDeclaration(&M, Intrinsic::gcroot);
-
- F->replaceAllUsesWith(gcrootFun);
- F->eraseFromParent();
-
- for (Value::use_iterator I = gcrootFun->use_begin(),
- E = gcrootFun->use_end(); I != E; ++I) {
- if (Instruction* II = dyn_cast<Instruction>(*I)) {
- Function* F = II->getParent()->getParent();
- if (!F->hasGC()) F->setGC("vmkit");
- }
- }
-
- return true;
- }
-
- return false;
-}
-
-}
diff --git a/vmkit/lib/Mvm/JITGCPass/Makefile b/vmkit/lib/Mvm/JITGCPass/Makefile
deleted file mode 100644
index 13f56b2..0000000
--- a/vmkit/lib/Mvm/JITGCPass/Makefile
+++ /dev/null
@@ -1,16 +0,0 @@
-##===- lib/Mvm/StaticGCPass/Makefile -----------------------*- Makefile -*-===##
-#
-# The VMKit project
-#
-# This file is distributed under the University of Illinois Open Source
-# License. See LICENSE.TXT for details.
-#
-##===----------------------------------------------------------------------===##
-
-LEVEL = ../../..
-LIBRARYNAME = JITGCPass
-LOADABLE_MODULE = 1
-USEDLIBS =
-
-include $(LEVEL)/Makefile.common
-
diff --git a/vmkit/lib/Mvm/MMTk/Makefile b/vmkit/lib/Mvm/MMTk/Makefile
deleted file mode 100644
index f4f50a5..0000000
--- a/vmkit/lib/Mvm/MMTk/Makefile
+++ /dev/null
@@ -1,19 +0,0 @@
-##===- lib/Mvm/MMTk/Makefile -------------------------------*- Makefile -*-===##
-#
-# The vmkit project
-#
-# This file is distributed under the University of Illinois Open Source
-# License. See LICENSE.TXT for details.
-#
-##===----------------------------------------------------------------------===##
-LEVEL = ../../..
-
-include $(LEVEL)/Makefile.config
-
-ifeq ($(WITH_LLVM_GCC), 1)
- MODULE_NAME = MMTk
-else
- LIBRARYNAME = MMTk
-endif
-
-include $(LEVEL)/Makefile.common
diff --git a/vmkit/lib/Mvm/MMTk/MutatorThread.h b/vmkit/lib/Mvm/MMTk/MutatorThread.h
deleted file mode 100644
index d411f7b..0000000
--- a/vmkit/lib/Mvm/MMTk/MutatorThread.h
+++ /dev/null
@@ -1,46 +0,0 @@
-//===--------- MutatorThread.h - Thread for GC ----------------------------===//
-//
-// The VMKit project
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-
-#ifndef MVM_MUTATOR_THREAD_H
-#define MVM_MUTATOR_THREAD_H
-
-#include "mvm/Allocator.h"
-#include "mvm/Threads/Thread.h"
-
-namespace mvm {
-
-class MutatorThread : public mvm::Thread {
-public:
- MutatorThread(VMKit* vmkit) : mvm::Thread(vmkit) {
- MutatorContext = 0;
- }
- mvm::ThreadAllocator Allocator;
- uintptr_t MutatorContext;
-
- /// realRoutine - The function to invoke when the thread starts.
- ///
- void (*realRoutine)(mvm::Thread*);
-
- static void init(Thread* _th);
-
- static MutatorThread* get() {
- return (MutatorThread*)mvm::Thread::get();
- }
-
- virtual int start(void (*fct)(mvm::Thread*)) {
- realRoutine = fct;
- routine = init;
- return Thread::start(init);
- }
-};
-
-}
-
-#endif
diff --git a/vmkit/lib/Mvm/MMTk/MvmGC.cpp b/vmkit/lib/Mvm/MMTk/MvmGC.cpp
deleted file mode 100644
index 20f99d7..0000000
--- a/vmkit/lib/Mvm/MMTk/MvmGC.cpp
+++ /dev/null
@@ -1,118 +0,0 @@
-//===----------- MvmGC.cpp - Garbage Collection Interface -----------------===//
-//
-// The VMKit project
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#include "mvm/GC.h"
-#include "mvm/VMKit.h"
-#include "MutatorThread.h"
-#include "mvm/VirtualMachine.h"
-
-#include <set>
-
-using namespace mvm;
-
-static mvm::SpinLock lock;
-std::set<gc*> __InternalSet__;
-int Collector::verbose = 0;
-
-extern "C" void* gcmalloc(uint32_t sz, void* _VT) {
- gc* res = 0;
- VirtualTable* VT = (VirtualTable*)_VT;
- sz = llvm::RoundUpToAlignment(sz, sizeof(void*));
- res = (gc*)malloc(sz);
- memset(res, 0, sz);
-
- lock.acquire();
- __InternalSet__.insert(res);
- lock.release();
-
- res->setVirtualTable(VT);
- return res;
-}
-
-extern "C" void* gcmallocUnresolved(uint32_t sz, VirtualTable* VT) {
- gc* res = (gc*)gcmalloc(sz, VT);
- if (VT->destructor)
- mvm::Thread::get()->vmkit->addFinalizationCandidate(res);
- return res;
-}
-
-extern "C" void addFinalizationCandidate(gc* obj) {
- mvm::Thread::get()->vmkit->addFinalizationCandidate(obj);
-}
-
-extern "C" void* AllocateMagicArray(int32_t sz, void* length) {
- gc* res = (gc*)malloc(sz);
- memset(res, 0, sz);
- ((void**)res)[0] = length;
- return res;
-}
-
-void* Collector::begOf(gc* obj) {
- lock.acquire();
- std::set<gc*>::iterator I = __InternalSet__.find(obj);
- std::set<gc*>::iterator E = __InternalSet__.end();
- lock.release();
-
- if (I != E) return obj;
- return 0;
-}
-
-void MutatorThread::init(Thread* _th) {
- MutatorThread* th = (MutatorThread*)_th;
- th->realRoutine(_th);
-}
-
-bool Collector::isLive(gc* ptr, uintptr_t closure) {
- abort();
- return false;
-}
-
-void Collector::scanObject(void** ptr, uintptr_t closure) {
- abort();
-}
-
-void Collector::markAndTrace(void* source, void* ptr, uintptr_t closure) {
- abort();
-}
-
-void Collector::markAndTraceRoot(void* ptr, uintptr_t closure) {
- abort();
-}
-
-gc* Collector::retainForFinalize(gc* val, uintptr_t closure) {
- abort();
- return NULL;
-}
-
-gc* Collector::retainReferent(gc* val, uintptr_t closure) {
- abort();
- return NULL;
-}
-
-gc* Collector::getForwardedFinalizable(gc* val, uintptr_t closure) {
- abort();
- return NULL;
-}
-
-gc* Collector::getForwardedReference(gc* val, uintptr_t closure) {
- abort();
- return NULL;
-}
-
-gc* Collector::getForwardedReferent(gc* val, uintptr_t closure) {
- abort();
- return NULL;
-}
-
-void Collector::collect() {
- // Do nothing.
-}
-
-void Collector::initialise() {
-}
diff --git a/vmkit/lib/Mvm/MMTk/MvmGC.h b/vmkit/lib/Mvm/MMTk/MvmGC.h
deleted file mode 100644
index 4d0921d..0000000
--- a/vmkit/lib/Mvm/MMTk/MvmGC.h
+++ /dev/null
@@ -1,89 +0,0 @@
-//===----------- MvmGC.h - Garbage Collection Interface -------------------===//
-//
-// The VMKit project
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-
-#ifndef MVM_MMTK_GC_H
-#define MVM_MMTK_GC_H
-
-#include <cstdlib>
-
-#define gc_allocator std::allocator
-
-namespace mvm {
-
-class GCVirtualTable : public CommonVirtualTable {
-public:
- uintptr_t specializedTracers[1];
-
- static uint32_t numberOfBaseFunctions() {
- return numberOfCommonEntries() + 1;
- }
-
- static uint32_t numberOfSpecializedTracers() {
- return 1;
- }
-};
-
-extern "C" void* gcmallocUnresolved(uint32_t sz, VirtualTable* VT);
-
-class collectable : public gcRoot {
-public:
-
- size_t objectSize() const {
- abort();
- return 0;
- }
-
- void* operator new(size_t sz, VirtualTable *VT) {
- return gcmallocUnresolved(sz, VT);
- }
-
-};
-
-class Collector {
-public:
- static int verbose;
-
- static bool isLive(gc* ptr, uintptr_t closure) __attribute__ ((always_inline));
- static void scanObject(void** ptr, uintptr_t closure) __attribute__ ((always_inline));
- static void markAndTrace(void* source, void* ptr, uintptr_t closure) __attribute__ ((always_inline));
- static void markAndTraceRoot(void* ptr, uintptr_t closure) __attribute__ ((always_inline));
- static gc* retainForFinalize(gc* val, uintptr_t closure) __attribute__ ((always_inline));
- static gc* retainReferent(gc* val, uintptr_t closure) __attribute__ ((always_inline));
- static gc* getForwardedFinalizable(gc* val, uintptr_t closure) __attribute__ ((always_inline));
- static gc* getForwardedReference(gc* val, uintptr_t closure) __attribute__ ((always_inline));
- static gc* getForwardedReferent(gc* val, uintptr_t closure) __attribute__ ((always_inline));
-
- static void collect();
-
- static void initialise();
-
- static int getMaxMemory() {
- return 0;
- }
-
- static int getFreeMemory() {
- return 0;
- }
-
- static int getTotalMemory() {
- return 0;
- }
-
- void setMaxMemory(size_t sz){
- }
-
- void setMinMemory(size_t sz){
- }
-
- static void* begOf(gc*);
-};
-
-}
-#endif
diff --git a/vmkit/lib/Mvm/Makefile b/vmkit/lib/Mvm/Makefile
deleted file mode 100644
index d000d7f..0000000
--- a/vmkit/lib/Mvm/Makefile
+++ /dev/null
@@ -1,17 +0,0 @@
-##===- lib/Mvm/Makefile ------------------------------------*- Makefile -*-===##
-#
-# The vmkit project
-#
-# This file is distributed under the University of Illinois Open Source
-# License. See LICENSE.TXT for details.
-#
-##===----------------------------------------------------------------------===##
-LEVEL = ../..
-
-include $(LEVEL)/Makefile.config
-
-EXTRA_DIST = BoehmGC GCMmap2 MMTk
-
-DIRS = Allocator CommonThread $(GCLIB) Runtime Compiler StaticGCPass JITGCPass
-
-include $(LEVEL)/Makefile.common
diff --git a/vmkit/lib/Mvm/Runtime/LLVMAssembly.ll b/vmkit/lib/Mvm/Runtime/LLVMAssembly.ll
deleted file mode 100644
index 0a14780..0000000
--- a/vmkit/lib/Mvm/Runtime/LLVMAssembly.ll
+++ /dev/null
@@ -1,31 +0,0 @@
-;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
-;;;;;;;;;;;;;;;;;;;;;;;;;;;;; Atomic ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
-;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
-
-declare i8 @llvm.atomic.cmp.swap.i8.p0i8(i8*, i8, i8) nounwind
-declare i16 @llvm.atomic.cmp.swap.i16.p0i16(i16*, i16, i16) nounwind
-declare i32 @llvm.atomic.cmp.swap.i32.p0i32(i32*, i32, i32) nounwind
-
-;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
-;;;;;;;;;;;;;;;;;;;;;;;;;Helper functions for gcc < 4.2 ;;;;;;;;;;;;;;;;;;;;;;;;
-;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
-
-define i8 @llvm_atomic_cmp_swap_i8(i8* %ptr, i8 %cmp, i8 %swap)
-nounwind {
- %A = call i8 @llvm.atomic.cmp.swap.i8.p0i8( i8* %ptr, i8 %cmp, i8 %swap)
- ret i8 %A
-}
-
-define i16 @llvm_atomic_cmp_swap_i16(i16* %ptr, i16 %cmp, i16 %swap)
-nounwind {
- %A = call i16 @llvm.atomic.cmp.swap.i16.p0i16( i16* %ptr, i16 %cmp, i16 %swap)
- ret i16 %A
-}
-
-define i32 @llvm_atomic_cmp_swap_i32(i32* %ptr, i32 %cmp, i32 %swap)
-nounwind {
- %A = call i32 @llvm.atomic.cmp.swap.i32.p0i32(i32* %ptr, i32 %cmp, i32 %swap)
- ret i32 %A
-}
-
-
diff --git a/vmkit/lib/Mvm/Runtime/LLVMAssembly64.ll b/vmkit/lib/Mvm/Runtime/LLVMAssembly64.ll
deleted file mode 100644
index 8a7afd1..0000000
--- a/vmkit/lib/Mvm/Runtime/LLVMAssembly64.ll
+++ /dev/null
@@ -1,7 +0,0 @@
-declare i64 @llvm.atomic.cmp.swap.i64.p0i64(i64*, i64, i64) nounwind
-
-define i64 @llvm_atomic_cmp_swap_i64(i64* %ptr, i64 %cmp, i64 %swap)
-nounwind {
- %A = call i64 @llvm.atomic.cmp.swap.i64.p0i64( i64* %ptr, i64 %cmp, i64 %swap)
- ret i64 %A
-}
diff --git a/vmkit/lib/Mvm/Runtime/Makefile b/vmkit/lib/Mvm/Runtime/Makefile
deleted file mode 100644
index 02ee268..0000000
--- a/vmkit/lib/Mvm/Runtime/Makefile
+++ /dev/null
@@ -1,31 +0,0 @@
-##===- lib/Mvm/Runtime/Makefile ----------------------------*- Makefile -*-===##
-#
-# The vmkit project
-#
-# This file is distributed under the University of Illinois Open Source
-# License. See LICENSE.TXT for details.
-#
-##===----------------------------------------------------------------------===##
-LEVEL = ../../..
-
-include $(LEVEL)/Makefile.config
-
-ifeq ($(WITH_LLVM_GCC), 1)
-
- MODULE_NAME = Mvm
-
-else
- LIBRARYNAME = Mvm
-
- VMKIT_ASSEMBLY = $(PROJ_SRC_DIR)/LLVMAssembly.ll
- BUILT_SOURCES = LLVMAssembly.s
-
- ifeq ($(WITH_64), 1)
- VMKIT_ASSEMBLY += $(PROJ_SRC_DIR)/LLVMAssembly64.ll
- endif
-
- SOURCES = LLVMAssembly.s $(notdir $(wildcard $(PROJ_SRC_DIR)/*.cpp))
-
-endif
-
-include $(LEVEL)/Makefile.common
diff --git a/vmkit/lib/Mvm/Runtime/MethodInfo.cpp b/vmkit/lib/Mvm/Runtime/MethodInfo.cpp
deleted file mode 100644
index 12e7c70..0000000
--- a/vmkit/lib/Mvm/Runtime/MethodInfo.cpp
+++ /dev/null
@@ -1,145 +0,0 @@
-//===------- MethodInfo.cpp - Runtime information for methods -------------===//
-//
-// The VMKit project
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#include "mvm/Allocator.h"
-#include "mvm/MethodInfo.h"
-#include "mvm/VirtualMachine.h"
-#include "mvm/GC.h"
-#include "mvm/VMKit.h"
-
-#include <dlfcn.h>
-#include <map>
-
-#if defined(__MACH__)
-#define SELF_HANDLE RTLD_DEFAULT
-#else
-#define SELF_HANDLE 0
-#endif
-
-using namespace mvm;
-
-void CamlMethodInfo::scan(uintptr_t closure, void* ip, void* addr) {
- assert(CF != NULL);
- //uintptr_t spaddr = (uintptr_t)addr + CF->FrameSize + sizeof(void*);
- uintptr_t spaddr = ((uintptr_t*)addr)[0];
- for (uint16 i = 0; i < CF->NumLiveOffsets; ++i) {
- Collector::scanObject((void**)(spaddr + CF->LiveOffsets[i]), closure);
- }
-}
-
-void StaticCamlMethodInfo::print(void* ip, void* addr) {
- fprintf(stderr, "; %p (%p) in %s static method\n", ip, addr, name);
-}
-
-void DefaultMethodInfo::print(void* ip, void* addr) {
- Dl_info info;
- int res = dladdr(ip, &info);
- if (res != 0 && info.dli_sname != NULL) {
- fprintf(stderr, "; %p (%p) in %s\n", ip, addr, info.dli_sname);
- } else {
- fprintf(stderr, "; %p in Unknown method\n", ip);
- }
-}
-
-DefaultMethodInfo DefaultMethodInfo::DM;
-
-void DefaultMethodInfo::scan(uintptr_t closure, void* ip, void* addr) {
-}
-
-struct CamlFrames {
- uint16_t NumDescriptors;
- CamlFrame frames[1];
-};
-
-struct CamlFrameDecoder {
- CamlFrames* frames ;
- uint32 currentDescriptor;
- CamlFrame* currentFrame;
-
- CamlFrameDecoder(CamlFrames* frames) {
- this->frames = frames;
- currentDescriptor = 0;
- currentFrame = &(frames->frames[0]);
- }
-
- bool hasNext() {
- return currentDescriptor < frames->NumDescriptors;
- }
-
- void advance() {
- ++currentDescriptor;
- if (!hasNext()) return;
- currentFrame = (CamlFrame*) ((char*)currentFrame +
- (currentFrame->NumLiveOffsets % 2) * sizeof(uint16_t) +
- currentFrame->NumLiveOffsets * sizeof(uint16_t) +
- sizeof(void*) + sizeof(uint16_t) + sizeof(uint16_t));
- }
-
- CamlFrame* next() {
- assert(hasNext());
- CamlFrame* result = currentFrame;
- advance();
- return result;
- }
-};
-
-static BumpPtrAllocator* StaticAllocator = NULL;
-
-FunctionMap::FunctionMap() {
- CamlFrames* frames =
- (CamlFrames*)dlsym(SELF_HANDLE, "camlVmkitoptimized__frametable");
- if (frames == NULL) return;
-
- StaticAllocator = new BumpPtrAllocator();
- CamlFrameDecoder decoder(frames);
- Dl_info info;
- while (decoder.hasNext()) {
- CamlFrame* frame = decoder.next();
- int res = dladdr(frame->ReturnAddress, &info);
- assert(res != 0 && "No frame");
- StaticCamlMethodInfo* MI = new(*StaticAllocator, "StaticCamlMethodInfo")
- StaticCamlMethodInfo(frame, info.dli_sname);
- addMethodInfo(MI, frame->ReturnAddress);
- }
-}
-
-MethodInfo* FunctionMap::IPToMethodInfo(void* ip) {
- FunctionMapLock.acquire();
- std::map<void*, MethodInfo*>::iterator I = Functions.find(ip);
- MethodInfo* res = NULL;
- if (I != Functions.end()) {
- res = I->second;
- } else {
- res = &DefaultMethodInfo::DM;
- }
- FunctionMapLock.release();
- return res;
-}
-
-void FunctionMap::addMethodInfo(MethodInfo* meth, void* ip) {
- FunctionMapLock.acquire();
- Functions.insert(std::make_pair(ip, meth));
- FunctionMapLock.release();
-}
-
-
-void FunctionMap::removeMethodInfos(void* owner) {
- FunctionMapLock.acquire();
- std::map<void*, mvm::MethodInfo*>::iterator temp;
- for (std::map<void*, mvm::MethodInfo*>::iterator i = Functions.begin(),
- e = Functions.end(); i != e;) {
- mvm::MethodInfo* MI = i->second;
- temp = i;
- i++;
- if (MI->Owner == owner) {
- Functions.erase(temp);
- }
- }
- FunctionMapLock.release();
-}
diff --git a/vmkit/lib/Mvm/Runtime/PrintBuffer.cpp b/vmkit/lib/Mvm/Runtime/PrintBuffer.cpp
deleted file mode 100644
index e5751f5..0000000
--- a/vmkit/lib/Mvm/Runtime/PrintBuffer.cpp
+++ /dev/null
@@ -1,103 +0,0 @@
-//===--------- Object.cc - Common objects for vmlets ----------------------===//
-//
-// The Micro Virtual Machine
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#include <cstdio>
-#include <cstdlib>
-
-#include "mvm/GC.h"
-#include "mvm/PrintBuffer.h"
-
-using namespace mvm;
-
-extern "C" void printFloat(float f) {
- fprintf(stderr, "%f\n", f);
-}
-
-extern "C" void printDouble(double d) {
- fprintf(stderr, "%f\n", d);
-}
-
-extern "C" void printLong(sint64 l) {
- fprintf(stderr, "%lld\n", (long long int)l);
-}
-
-extern "C" void printInt(sint32 i) {
- fprintf(stderr, "%d\n", i);
-}
-
-extern "C" void printObject(void* ptr) {
- fprintf(stderr, "%p\n", ptr);
-}
-
-extern "C" void write_ptr(PrintBuffer* buf, void* obj) {
- buf->writePtr(obj);
-}
-
-extern "C" void write_int(PrintBuffer* buf, int a) {
- buf->writeS4(a);
-}
-
-extern "C" void write_str(PrintBuffer* buf, char* a) {
- buf->write(a);
-}
-
-void OldObject::default_print(const gc *o, PrintBuffer *buf) {
- llvm_gcroot(o, 0);
- buf->write("<OldObject@");
- buf->writePtr((void*)o);
- buf->write(">");
-}
-
-
-#if 0
-// old stuff
-
-class UTF8Builder {
- uint16 *buf;
- uint32 cur;
- uint32 size;
-
-public:
- UTF8Builder(size_t size) {
- size = (size < 4) ? 4 : size;
- this->buf = new uint16[size];
- this->size = size;
- }
-
- UTF8Builder *append(const UTF8 *utf8, uint32 start=0, uint32 length=0xffffffff) {
- length = length == 0xffffffff ? utf8->size : length;
- uint32 req = cur + length;
-
- if(req > size) {
- uint32 newSize = size<<1;
- while(req < newSize)
- newSize <<= 1;
- uint16 *newBuf = new uint16[newSize];
- memcpy(newBuf, buf, cur<<1);
- delete []buf;
- buf = newBuf;
- size = newSize;
- }
-
- memcpy(buf + cur, &utf8->elements + start, length<<1);
- cur = req;
-
- return this;
- }
-
- const UTF8 *toUTF8(UTF8Map *map) {
- return map->lookupOrCreateReader(buf, size);
- }
-
- ~UTF8Builder() {
- delete [] buf;
- }
-};
-
-#endif
diff --git a/vmkit/lib/Mvm/Runtime/SystemThreads.cpp b/vmkit/lib/Mvm/Runtime/SystemThreads.cpp
deleted file mode 100644
index 258a8cc..0000000
--- a/vmkit/lib/Mvm/Runtime/SystemThreads.cpp
+++ /dev/null
@@ -1,309 +0,0 @@
-#include "mvm/SystemThreads.h"
-#include "mvm/GC.h"
-#include "mvm/VirtualMachine.h"
-
-using namespace mvm;
-
-ReferenceThread::ReferenceThread(mvm::VMKit* vmkit) :
- MutatorThread(vmkit),
- WeakReferencesQueue(ReferenceQueue::WEAK),
- SoftReferencesQueue(ReferenceQueue::SOFT),
- PhantomReferencesQueue(ReferenceQueue::PHANTOM) {
-
- ToEnqueue = new mvm::gc*[INITIAL_QUEUE_SIZE];
- ToEnqueueLength = INITIAL_QUEUE_SIZE;
- ToEnqueueIndex = 0;
-
- setDaemon();
-}
-
-void ReferenceThread::addWeakReference(mvm::gc* ref) {
- llvm_gcroot(ref, 0);
- WeakReferencesQueue.addReference(ref);
-}
-
-void ReferenceThread::addSoftReference(mvm::gc* ref) {
- llvm_gcroot(ref, 0);
- SoftReferencesQueue.addReference(ref);
-}
-
-void ReferenceThread::addPhantomReference(mvm::gc* ref) {
- llvm_gcroot(ref, 0);
- PhantomReferencesQueue.addReference(ref);
-}
-
-mvm::gc** getReferent(mvm::gc* obj) {
- llvm_gcroot(obj, 0);
- mvm::VirtualMachine* vm = obj->getVirtualTable()->vm;
- mvm::Thread::get()->attach(vm);
- return vm->getReferent(obj);
-}
-
-void setReferent(mvm::gc* obj, mvm::gc* val) {
- llvm_gcroot(obj, 0);
- llvm_gcroot(val, 0);
- mvm::VirtualMachine* vm = obj->getVirtualTable()->vm;
- mvm::Thread::get()->attach(vm);
- vm->setReferent(obj, val);
-}
-
-void invokeEnqueue(mvm::gc* obj) {
- llvm_gcroot(obj, 0);
- TRY {
- mvm::VirtualMachine* vm = obj->getVirtualTable()->vm;
- mvm::Thread::get()->attach(vm);
-
- vm->enqueueReference(obj);
- } IGNORE;
- mvm::Thread::get()->clearPendingException();
-}
-
-void ReferenceThread::enqueueStart(ReferenceThread* th) {
- mvm::gc* res = NULL;
- llvm_gcroot(res, 0);
-
- while (true) {
- th->EnqueueLock.lock();
- while (th->ToEnqueueIndex == 0) {
- th->EnqueueCond.wait(&th->EnqueueLock);
- }
- th->EnqueueLock.unlock();
-
- while (true) {
- th->ToEnqueueLock.acquire();
- if (th->ToEnqueueIndex != 0) {
- res = th->ToEnqueue[th->ToEnqueueIndex - 1];
- --th->ToEnqueueIndex;
- }
- th->ToEnqueueLock.release();
- if (!res) break;
-
- invokeEnqueue(res);
- res = NULL;
- }
- }
-}
-
-
-void ReferenceThread::addToEnqueue(mvm::gc* obj) {
- llvm_gcroot(obj, 0);
- if (ToEnqueueIndex >= ToEnqueueLength) {
- uint32 newLength = ToEnqueueLength * GROW_FACTOR;
- mvm::gc** newQueue = new mvm::gc*[newLength];
- if (!newQueue) {
- fprintf(stderr, "I don't know how to handle reference overflow yet!\n");
- abort();
- }
- for (uint32 i = 0; i < ToEnqueueLength; ++i) {
- newQueue[i] = ToEnqueue[i];
- }
- delete[] ToEnqueue;
- ToEnqueue = newQueue;
- ToEnqueueLength = newLength;
- }
- ToEnqueue[ToEnqueueIndex++] = obj;
-}
-
-void ReferenceQueue::addReference(mvm::gc* ref) {
- llvm_gcroot(ref, 0);
- QueueLock.acquire();
- if (CurrentIndex >= QueueLength) {
- uint32 newLength = QueueLength * GROW_FACTOR;
- mvm::gc** newQueue = new mvm::gc*[newLength];
- memset(newQueue, 0, newLength * sizeof(mvm::gc*));
- if (!newQueue) {
- fprintf(stderr, "I don't know how to handle reference overflow yet!\n");
- abort();
- }
- for (uint32 i = 0; i < QueueLength; ++i) newQueue[i] = References[i];
- delete[] References;
- References = newQueue;
- QueueLength = newLength;
- }
- References[CurrentIndex++] = ref;
- QueueLock.release();
-}
-
-mvm::gc* ReferenceQueue::processReference(mvm::gc* reference, ReferenceThread* th, uintptr_t closure) {
- if (!mvm::Collector::isLive(reference, closure)) {
- setReferent(reference, 0);
- return NULL;
- }
-
- mvm::gc* referent = *(getReferent(reference));
-
- if (!referent) {
- return NULL;
- }
-
- if (semantics == SOFT) {
- // TODO: are we are out of memory? Consider that we always are for now.
- if (false) {
- mvm::Collector::retainReferent(referent, closure);
- }
- } else if (semantics == PHANTOM) {
- // Nothing to do.
- }
-
- mvm::gc* newReference =
- mvm::Collector::getForwardedReference(reference, closure);
- if (mvm::Collector::isLive(referent, closure)) {
- mvm::gc* newReferent = mvm::Collector::getForwardedReferent(referent, closure);
- setReferent(newReference, newReferent);
- return newReference;
- } else {
- setReferent(newReference, 0);
- th->addToEnqueue(newReference);
- return NULL;
- }
-}
-
-
-void ReferenceQueue::scan(ReferenceThread* th, uintptr_t closure) {
- uint32 NewIndex = 0;
-
- for (uint32 i = 0; i < CurrentIndex; ++i) {
- mvm::gc* obj = References[i];
- mvm::gc* res = processReference(obj, th, closure);
- if (res) References[NewIndex++] = res;
- }
-
- CurrentIndex = NewIndex;
-}
-
-void ReferenceThread::tracer(uintptr_t closure) {
- for (uint32 i = 0; i < ToEnqueueIndex; ++i) {
- mvm::Collector::markAndTraceRoot(ToEnqueue + i, closure);
- }
- MutatorThread::tracer(closure);
-}
-
-
-FinalizerThread::FinalizerThread(VMKit* vmkit) : MutatorThread(vmkit) {
- FinalizationQueue = new mvm::gc*[INITIAL_QUEUE_SIZE];
- QueueLength = INITIAL_QUEUE_SIZE;
- CurrentIndex = 0;
-
- ToBeFinalized = new mvm::gc*[INITIAL_QUEUE_SIZE];
- ToBeFinalizedLength = INITIAL_QUEUE_SIZE;
- CurrentFinalizedIndex = 0;
-
- setDaemon();
-}
-
-void FinalizerThread::growFinalizationQueue() {
- if (CurrentIndex >= QueueLength) {
- uint32 newLength = QueueLength * GROW_FACTOR;
- mvm::gc** newQueue = new mvm::gc*[newLength];
- if (!newQueue) {
- fprintf(stderr, "I don't know how to handle finalizer overflows yet!\n");
- abort();
- }
- for (uint32 i = 0; i < QueueLength; ++i) newQueue[i] = FinalizationQueue[i];
- delete[] FinalizationQueue;
- FinalizationQueue = newQueue;
- QueueLength = newLength;
- }
-}
-
-void FinalizerThread::growToBeFinalizedQueue() {
- if (CurrentFinalizedIndex >= ToBeFinalizedLength) {
- uint32 newLength = ToBeFinalizedLength * GROW_FACTOR;
- mvm::gc** newQueue = new mvm::gc*[newLength];
- if (!newQueue) {
- fprintf(stderr, "I don't know how to handle finalizer overflows yet!\n");
- abort();
- }
- for (uint32 i = 0; i < ToBeFinalizedLength; ++i) newQueue[i] = ToBeFinalized[i];
- delete[] ToBeFinalized;
- ToBeFinalized = newQueue;
- ToBeFinalizedLength = newLength;
- }
-}
-
-
-void FinalizerThread::addFinalizationCandidate(mvm::gc* obj) {
- llvm_gcroot(obj, 0);
- FinalizationQueueLock.acquire();
-
- if (CurrentIndex >= QueueLength) {
- growFinalizationQueue();
- }
-
- FinalizationQueue[CurrentIndex++] = obj;
- FinalizationQueueLock.release();
-}
-
-void FinalizerThread::scanFinalizationQueue(uintptr_t closure) {
- uint32 NewIndex = 0;
- for (uint32 i = 0; i < CurrentIndex; ++i) {
- mvm::gc* obj = FinalizationQueue[i];
-
- if (!mvm::Collector::isLive(obj, closure)) {
- obj = mvm::Collector::retainForFinalize(FinalizationQueue[i], closure);
-
- if (CurrentFinalizedIndex >= ToBeFinalizedLength)
- growToBeFinalizedQueue();
-
- /* Add to object table */
- ToBeFinalized[CurrentFinalizedIndex++] = obj;
- } else {
- FinalizationQueue[NewIndex++] =
- mvm::Collector::getForwardedFinalizable(obj, closure);
- }
- }
- CurrentIndex = NewIndex;
-}
-
-typedef void (*destructor_t)(void*);
-
-void invokeFinalize(mvm::gc* obj) {
- llvm_gcroot(obj, 0);
- TRY {
- llvm_gcroot(obj, 0);
- VirtualMachine* vm = obj->getVirtualTable()->vm;
- mvm::Thread::get()->attach(vm);
- vm->finalizeObject(obj);
- } IGNORE;
- mvm::Thread::get()->clearPendingException();
-}
-
-void FinalizerThread::finalizerStart(FinalizerThread* th) {
- mvm::gc* res = NULL;
- llvm_gcroot(res, 0);
-
- while (true) {
- th->FinalizationLock.lock();
- while (th->CurrentFinalizedIndex == 0) {
- th->FinalizationCond.wait(&th->FinalizationLock);
- }
- th->FinalizationLock.unlock();
-
- while (true) {
- th->FinalizationQueueLock.acquire();
- if (th->CurrentFinalizedIndex != 0) {
- res = th->ToBeFinalized[th->CurrentFinalizedIndex - 1];
- --th->CurrentFinalizedIndex;
- }
- th->FinalizationQueueLock.release();
- if (!res) break;
-
- mvm::VirtualTable* VT = res->getVirtualTable();
- ASSERT(VT->vm);
- if (VT->operatorDelete) {
- destructor_t dest = (destructor_t)VT->destructor;
- dest(res);
- } else {
- invokeFinalize(res);
- }
- res = NULL;
- }
- }
-}
-
-void FinalizerThread::tracer(uintptr_t closure) {
- for (uint32 i = 0; i < CurrentFinalizedIndex; ++i) {
- mvm::Collector::markAndTraceRoot(ToBeFinalized + i, closure);
- }
- MutatorThread::tracer(closure);
-}
diff --git a/vmkit/lib/Mvm/Runtime/UTF8.cpp b/vmkit/lib/Mvm/Runtime/UTF8.cpp
deleted file mode 100644
index a55d61b..0000000
--- a/vmkit/lib/Mvm/Runtime/UTF8.cpp
+++ /dev/null
@@ -1,165 +0,0 @@
-#include "mvm/Allocator.h"
-#include "mvm/UTF8.h"
-
-using namespace mvm;
-
-const UTF8* UTF8::extract(UTF8Map* map, uint32 start, uint32 end) const {
- uint32 len = end - start;
- ThreadAllocator allocator;
- uint16* buf = (uint16*)allocator.Allocate(sizeof(uint16) * len);
-
- for (uint32 i = 0; i < len; i++) {
- buf[i] = elements[i + start];
- }
-
- return map->lookupOrCreateReader(buf, len);
-}
-
-static uint32 asciizHasher(const char* asciiz, sint32 size) {
- uint32 r0 = 0, r1 = 0;
- for (sint32 i = 0; i < size; i++) {
- char c = asciiz[i];
- r0 += c;
- r1 ^= c;
- }
- return (r1 & 255) + ((r0 & 255) << 8);
-}
-
-uint32 UTF8::readerHasher(const uint16* buf, sint32 size) {
- uint32 r0 = 0, r1 = 0;
- for (sint32 i = 0; i < size; i++) {
- uint16 c = buf[i];
- r0 += c;
- r1 ^= c;
- }
- return (r1 & 255) + ((r0 & 255) << 8);
-}
-
-static bool asciizEqual(const UTF8* val, const char* asciiz, sint32 size) {
- sint32 len = val->size;
- if (len != size) return false;
- else {
- for (sint32 i = 0; i < len; i++) {
- if (asciiz[i] != val->elements[i]) return false;
- }
- return true;
- }
-}
-
-static bool readerEqual(const UTF8* val, const uint16* buf, sint32 size) {
- sint32 len = val->size;
- if (len != size) return false;
- else return !(memcmp(val->elements, buf, len * sizeof(uint16)));
-}
-
-void UTF8Map::replace(const UTF8* oldUTF8, const UTF8* newUTF8) {
- lock.lock();
- uint32 key = oldUTF8->hash();
- std::pair<UTF8Map::iterator, UTF8Map::iterator> p = map.equal_range(key);
-
- for (UTF8Map::iterator i = p.first; i != p.second; i++) {
- if (i->second == oldUTF8) {
- map.erase(i);
- break;
- }
- }
- map.insert(std::make_pair(key, newUTF8));
- lock.unlock();
-
-}
-
-const UTF8* UTF8Map::lookupOrCreateAsciiz(const char* asciiz) {
- sint32 size = strlen(asciiz);
- uint32 key = asciizHasher(asciiz, size);
- const UTF8* res = 0;
- lock.lock();
-
- std::pair<UTF8Map::iterator, UTF8Map::iterator> p = map.equal_range(key);
-
- for (UTF8Map::iterator i = p.first; i != p.second; i++) {
- if (asciizEqual(i->second, asciiz, size)) {
- res = i->second;
- break;
- }
- }
-
- if (res == 0) {
- UTF8* tmp = new(allocator, size) UTF8(size);
- for (sint32 i = 0; i < size; i++) {
- tmp->elements[i] = asciiz[i];
- }
- res = (const UTF8*)tmp;
- map.insert(std::make_pair(key, res));
- }
-
- lock.unlock();
- return res;
-}
-
-const UTF8* UTF8Map::lookupOrCreateReader(const uint16* buf, uint32 len) {
- sint32 size = (sint32)len;
- uint32 key = UTF8::readerHasher(buf, size);
- const UTF8* res = 0;
- lock.lock();
-
- std::pair<UTF8Map::iterator, UTF8Map::iterator> p = map.equal_range(key);
-
- for (UTF8Map::iterator i = p.first; i != p.second; i++) {
- if (readerEqual(i->second, buf, size)) {
- res = i->second;
- break;
- }
- }
-
- if (res == 0) {
- UTF8* tmp = new(allocator, size) UTF8(size);
- memcpy(tmp->elements, buf, len * sizeof(uint16));
- res = (const UTF8*)tmp;
- map.insert(std::make_pair(key, res));
- }
-
- lock.unlock();
- return res;
-}
-
-const UTF8* UTF8Map::lookupAsciiz(const char* asciiz) {
- sint32 size = strlen(asciiz);
- uint32 key = asciizHasher(asciiz, size);
- const UTF8* res = 0;
- lock.lock();
-
- std::pair<UTF8Map::iterator, UTF8Map::iterator> p = map.equal_range(key);
-
- for (UTF8Map::iterator i = p.first; i != p.second; i++) {
- if (asciizEqual(i->second, asciiz, size)) {
- res = i->second;
- break;
- }
- }
-
- lock.unlock();
- return res;
-}
-
-const UTF8* UTF8Map::lookupReader(const uint16* buf, uint32 len) {
- sint32 size = (sint32)len;
- uint32 key = UTF8::readerHasher(buf, size);
- const UTF8* res = 0;
- lock.lock();
-
- std::pair<UTF8Map::iterator, UTF8Map::iterator> p = map.equal_range(key);
-
- for (UTF8Map::iterator i = p.first; i != p.second; i++) {
- if (readerEqual(i->second, buf, size)) {
- res = i->second;
- break;
- }
- }
-
- lock.unlock();
- return res;
-}
-
-void UTF8Map::insert(const UTF8* val) {
- map.insert(std::make_pair(val->hash(), val));
-}
diff --git a/vmkit/lib/Mvm/Runtime/VMKit.cpp b/vmkit/lib/Mvm/Runtime/VMKit.cpp
deleted file mode 100644
index 4bd8fd1..0000000
--- a/vmkit/lib/Mvm/Runtime/VMKit.cpp
+++ /dev/null
@@ -1,273 +0,0 @@
-#include "mvm/VMKit.h"
-#include "mvm/VirtualMachine.h"
-#include "mvm/SystemThreads.h"
-#include "mvm/GC.h"
-#include "mvm/JIT.h"
-
-using namespace mvm;
-
-#if 0
-#define dprintf(...) do { printf("[%p] ", (void*)mvm::Thread::get()); printf(__VA_ARGS__); } while(0)
-#else
-#define dprintf(...)
-#endif
-
-static SpinLock initedLock;
-static bool inited = false;
-
-void VMKit::initialise(llvm::CodeGenOpt::Level level, llvm::Module* TheModule, llvm::TargetMachine* TheTarget) {
- initedLock.lock();
- if(!inited) {
- inited = true;
- mvm::MvmModule::initialise(level, TheModule, TheTarget);
- mvm::Collector::initialise();
- }
- initedLock.unlock();
-}
-
-VMKit::VMKit(mvm::BumpPtrAllocator &Alloc) : allocator(Alloc) {
- initialise();
-
- vms = 0;
- vmsArraySize = 0;
-}
-
-void VMKit::scanWeakReferencesQueue(uintptr_t closure) {
- if(referenceThread)
- referenceThread->WeakReferencesQueue.scan(referenceThread, closure);
-}
-
-void VMKit::scanSoftReferencesQueue(uintptr_t closure) {
- if(referenceThread)
- referenceThread->SoftReferencesQueue.scan(referenceThread, closure);
-}
-
-void VMKit::scanPhantomReferencesQueue(uintptr_t closure) {
- if(referenceThread)
- referenceThread->PhantomReferencesQueue.scan(referenceThread, closure);
-}
-
-void VMKit::scanFinalizationQueue(uintptr_t closure) {
- if(finalizerThread)
- finalizerThread->scanFinalizationQueue(closure);
-}
-
-FinalizerThread* VMKit::getAndAllocateFinalizerThread() {
- if(!finalizerThread) {
- vmkitLock();
- if(!finalizerThread) {
- finalizerThread = new FinalizerThread(this);
- finalizerThread->start((void (*)(mvm::Thread*))FinalizerThread::finalizerStart);
- }
- vmkitUnlock();
- }
- return finalizerThread;
-}
-
-ReferenceThread* VMKit::getAndAllocateReferenceThread() {
- if(!referenceThread) {
- vmkitLock();
- if(!referenceThread) {
- referenceThread = new ReferenceThread(this);
- referenceThread->start((void (*)(mvm::Thread*))ReferenceThread::enqueueStart);
- }
- vmkitUnlock();
- }
- return referenceThread;
-}
-
-void VMKit::addFinalizationCandidate(mvm::gc* object) {
- llvm_gcroot(object, 0);
- getAndAllocateFinalizerThread()->addFinalizationCandidate(object);
-}
-
-void VMKit::addWeakReference(mvm::gc* ref) {
- llvm_gcroot(ref, 0);
- getAndAllocateReferenceThread()->addWeakReference(ref);
-}
-
-void VMKit::addSoftReference(mvm::gc* ref) {
- llvm_gcroot(ref, 0);
- getAndAllocateReferenceThread()->addSoftReference(ref);
-}
-
-void VMKit::addPhantomReference(mvm::gc* ref) {
- llvm_gcroot(ref, 0);
- getAndAllocateReferenceThread()->addPhantomReference(ref);
-}
-
-void VMKit::tracer(uintptr_t closure) {
- // don't have to take the vmkitLock, already taken by the rendezvous.
- for(size_t i=0; i<vmsArraySize; i++)
- if(vms[i])
- vms[i]->tracer(closure);
-}
-
-bool VMKit::startCollection() {
- // do not take the lock here because if a gc is currently running, it could call enterUncooperativeCode
- // which will execute the gc and we will therefore recall the gc just behind. Stupid because the previous one
- // should have freed some memory
- rendezvous.startRV();
-
- if (mvm::Thread::get()->doYield) {
- rendezvous.cancelRV();
- rendezvous.join();
- return 0;
- } else {
- dprintf("Start collection\n");
- // Lock thread lock, so that we can traverse the vm and thread lists safely. This will be released on finishRV.
- vmkitLock();
-
- if(finalizerThread)
- finalizerThread->FinalizationQueueLock.acquire();
- if(referenceThread) {
- referenceThread->ToEnqueueLock.acquire();
- referenceThread->SoftReferencesQueue.acquire();
- referenceThread->WeakReferencesQueue.acquire();
- referenceThread->PhantomReferencesQueue.acquire();
- }
-
- // call first startCollection on each vm to avoid deadlock.
- // indeed, a vm could want to execute applicative code
- for(size_t i=0; i<vmsArraySize; i++)
- if(vms[i])
- vms[i]->startCollection();
-
- rendezvous.synchronize();
-
- return 1;
- }
-}
-
-void VMKit::endCollection() {
- dprintf("End collection\n");
-
- rendezvous.finishRV();
-
- for(size_t i=0; i<vmsArraySize; i++)
- if(vms[i])
- vms[i]->endCollection();
-
- if(finalizerThread) {
- finalizerThread->FinalizationQueueLock.release();
- finalizerThread->FinalizationCond.broadcast();
- }
-
- if(referenceThread) {
- referenceThread->ToEnqueueLock.release();
- referenceThread->SoftReferencesQueue.release();
- referenceThread->WeakReferencesQueue.release();
- referenceThread->PhantomReferencesQueue.release();
- referenceThread->EnqueueCond.broadcast();
- }
-
- vmkitUnlock();
-}
-
-size_t VMKit::addVM(VirtualMachine* vm) {
- dprintf("add vm: %p\n", vm);
- vmkitLock();
-
- for(size_t i=0; i<vmsArraySize; i++)
- if(!vms[i]) {
- vms[i] = vm;
- vmkitUnlock();
- return i;
- }
-
- int res = vmsArraySize;
- vmsArraySize = vmsArraySize ? (vmsArraySize<<1) : 1;
- // reallocate the vms
- VirtualMachine **newVms = new VirtualMachine*[vmsArraySize];
-
- memcpy(newVms, vms, res*sizeof(VirtualMachine*));
- memset(newVms + res*sizeof(VirtualMachine*), 0, (vmsArraySize-res)*sizeof(VirtualMachine*));
- newVms[res] = vm;
-
- VirtualMachine **oldVms = vms;
- vms = newVms; // vms must always contain valid data
- delete[] oldVms;
-
- // reallocate the allVMDatas
- for(Thread* cur=preparedThreads.next(); cur!=&preparedThreads; cur=cur->next()) {
- cur->reallocAllVmsData(res, vmsArraySize);
- }
-
- for(Thread* cur=runningThreads.next(); cur!=&runningThreads; cur=cur->next()) {
- cur->reallocAllVmsData(res, vmsArraySize);
- }
-
- vmkitUnlock();
-
- return res;
-}
-
-void VMKit::removeVM(size_t id) {
- dprintf("remove vm: %p\n", vm);
- // I think that we only should call this function when all the thread data are released
- vms[id] = 0;
-}
-
-void VMKit::registerPreparedThread(mvm::Thread* th) {
- dprintf("Create thread: %p\n", th);
- vmkitLock();
- th->appendTo(&preparedThreads);
- th->reallocAllVmsData(0, vmsArraySize);
- vmkitUnlock();
-}
-
-void VMKit::unregisterPreparedThread(mvm::Thread* th) {
- dprintf("Delete thread: %p\n", th);
- vmkitLock();
- th->remove();
- for(size_t i=0; i<vmsArraySize; i++)
- if(th->allVmsData[i])
- delete th->allVmsData[i];
- delete th->allVmsData;
- vmkitUnlock();
-}
-
-void VMKit::registerRunningThread(mvm::Thread* th) {
- dprintf("Register thread: %p\n", th);
- vmkitLock();
- numberOfRunningThreads++;
- th->remove();
- th->appendTo(&runningThreads);
- vmkitUnlock();
-}
-
-void VMKit::unregisterRunningThread(mvm::Thread* th) {
- dprintf("Unregister thread: %p\n", th);
- vmkitLock();
- numberOfRunningThreads--;
- th->remove();
- th->appendTo(&preparedThreads);
- vmkitUnlock();
-}
-
-void VMKit::waitNonDaemonThreads() {
- nonDaemonThreadsManager.waitNonDaemonThreads();
-}
-
-void NonDaemonThreadManager::leaveNonDaemonMode() {
- nonDaemonLock.lock();
- --nonDaemonThreads;
- if (nonDaemonThreads == 0) nonDaemonVar.signal();
- nonDaemonLock.unlock();
-}
-
-void NonDaemonThreadManager::enterNonDaemonMode() {
- nonDaemonLock.lock();
- ++nonDaemonThreads;
- nonDaemonLock.unlock();
-}
-
-void NonDaemonThreadManager::waitNonDaemonThreads() {
- nonDaemonLock.lock();
-
- while (nonDaemonThreads) {
- nonDaemonVar.wait(&nonDaemonLock);
- }
-
- nonDaemonLock.unlock();
-}
diff --git a/vmkit/lib/Mvm/Runtime/VirtualMachine.cpp b/vmkit/lib/Mvm/Runtime/VirtualMachine.cpp
deleted file mode 100644
index d4abf06..0000000
--- a/vmkit/lib/Mvm/Runtime/VirtualMachine.cpp
+++ /dev/null
@@ -1,44 +0,0 @@
-#include "mvm/VirtualMachine.h"
-#include "mvm/VMKit.h"
-#include "MutatorThread.h"
-
-using namespace mvm;
-
-VirtualMachine::VirtualMachine(mvm::BumpPtrAllocator &Alloc, mvm::VMKit* vmk) : allocator(Alloc) {
- vmkit = vmk;
- vmID = vmkit->addVM(this);
-}
-
-VirtualMachine::~VirtualMachine() {
- vmkit->removeVM(vmID);
-}
-
-class LauncherThread : public MutatorThread {
-public:
- void (*realStart)(VirtualMachine*, int, char**);
- VirtualMachine* vm;
- int argc;
- char** argv;
-
- LauncherThread(VMKit* vmkit, void (*s)(VirtualMachine*, int, char**), VirtualMachine* v, int ac, char** av) : MutatorThread(vmkit) {
- realStart = s;
- vm = v;
- argc = ac;
- argv = av;
- }
-
- static void launch(LauncherThread* th) {
- if(th->realStart)
- th->realStart(th->vm, th->argc, th->argv);
- else
- th->vm->runApplicationImpl(th->argc, th->argv);
- }
-};
-
-void VirtualMachine::runApplication(void (*starter)(VirtualMachine*, int, char**), int argc, char **argv) {
- (new LauncherThread(vmkit, starter, this, argc, argv))->start((void (*)(Thread*))LauncherThread::launch);
-}
-
-void VirtualMachine::runApplication(int argc, char** argv) {
- runApplication(0, argc, argv);
-}
diff --git a/vmkit/lib/Mvm/StaticGCPass/Makefile b/vmkit/lib/Mvm/StaticGCPass/Makefile
deleted file mode 100644
index b86f9dc..0000000
--- a/vmkit/lib/Mvm/StaticGCPass/Makefile
+++ /dev/null
@@ -1,16 +0,0 @@
-##===- lib/Mvm/StaticGCPass/Makefile -----------------------*- Makefile -*-===##
-#
-# The VMKit project
-#
-# This file is distributed under the University of Illinois Open Source
-# License. See LICENSE.TXT for details.
-#
-##===----------------------------------------------------------------------===##
-
-LEVEL = ../../..
-LIBRARYNAME = StaticGCPass
-LOADABLE_MODULE = 1
-USEDLIBS =
-
-include $(LEVEL)/Makefile.common
-
diff --git a/vmkit/lib/Mvm/StaticGCPass/StaticGCPass.cpp b/vmkit/lib/Mvm/StaticGCPass/StaticGCPass.cpp
deleted file mode 100644
index 956c6ad..0000000
--- a/vmkit/lib/Mvm/StaticGCPass/StaticGCPass.cpp
+++ /dev/null
@@ -1,77 +0,0 @@
-//===---- StaticGCPass.cpp - Put GC information in functions compiled --------//
-//===----------------------- with llvm-gcc --------------------------------===//
-//
-// The VMKit project
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-
-#include "llvm/Intrinsics.h"
-#include "llvm/Module.h"
-#include "llvm/Pass.h"
-#include "llvm/Support/raw_ostream.h"
-
-#include <cstdio>
-
-using namespace llvm;
-
-namespace {
-
- class StaticGCPass : public ModulePass {
- public:
- static char ID;
-
- StaticGCPass() : ModulePass(ID) {}
-
- virtual bool runOnModule(Module& M);
-
- /// getAnalysisUsage - We do not modify anything.
- virtual void getAnalysisUsage(AnalysisUsage &AU) const {
- AU.setPreservesAll();
- }
-
- };
-
- char StaticGCPass::ID = 0;
- RegisterPass<StaticGCPass> X("StaticGCPass",
- "Add GC information in files compiled with llvm-gcc");
-
-bool StaticGCPass::runOnModule(Module& M) {
-
- Function* F = M.getFunction("__llvm_gcroot");
- Function *gcrootFun = Intrinsic::getDeclaration(&M, Intrinsic::gcroot);
-
- if (F) {
- F->replaceAllUsesWith(gcrootFun);
- F->eraseFromParent();
- }
-
- bool error = false;
- for (Value::use_iterator I = gcrootFun->use_begin(),
- E = gcrootFun->use_end(); I != E; ++I) {
- if (Instruction* II = dyn_cast<Instruction>(*I)) {
- Function* F = II->getParent()->getParent();
- if (F->hasGC()) F->clearGC();
- F->setGC("ocaml");
- }
- }
-
- for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
- if (I->hasGC() && I->hasInternalLinkage()) {
- error = true;
- fprintf(stderr, "Method %s has static linkage but uses gc_root. "
- "Functions using gc_root should not have static linkage.\n",
- I->getName().data());
- }
- if (I->hasGC() && !strcmp(I->getGC(), "vmkit")) I->setGC("ocaml");
- }
-
- if (error) abort();
-
- return true;
-}
-
-}
diff --git a/vmkit/lib/N3/LLVMRuntime/Makefile b/vmkit/lib/N3/LLVMRuntime/Makefile
deleted file mode 100644
index 9eafc6f..0000000
--- a/vmkit/lib/N3/LLVMRuntime/Makefile
+++ /dev/null
@@ -1,16 +0,0 @@
-##===- lib/N3/LLVMRuntime/Makefile -------------------------*- Makefile -*-===##
-#
-# The vmkit project
-#
-# This file is distributed under the University of Illinois Open Source
-# License. See LICENSE.TXT for details.
-#
-##===----------------------------------------------------------------------===##
-LEVEL = ../../..
-
-include $(LEVEL)/Makefile.config
-
-VMKIT_RUNTIME = $(PROJ_SRC_ROOT)/lib/N3/LLVMRuntime/runtime.ll
-BUILT_SOURCES = LLVMRuntime.inc
-
-include $(LEVEL)/Makefile.common
diff --git a/vmkit/lib/N3/LLVMRuntime/runtime.ll b/vmkit/lib/N3/LLVMRuntime/runtime.ll
deleted file mode 100644
index 6410e5c..0000000
--- a/vmkit/lib/N3/LLVMRuntime/runtime.ll
+++ /dev/null
@@ -1,58 +0,0 @@
-%CLIObject = type {i8*, i8*, i8*}
-
-;;; Types for CLI arrays. A size of 0 means an undefined size.
-%CLIArray = type { %CLIObject, i32 }
-%ArrayBoolean = type { %CLIObject, i32, [0 x i8] }
-%ArrayUInt8 = type { %CLIObject, i32, [0 x i8] }
-%ArraySInt8 = type { %CLIObject, i32, [0 x i8] }
-%ArrayChar = type { %CLIObject, i32, [0 x i16] }
-%ArraySInt16 = type { %CLIObject, i32, [0 x i16] }
-%ArrayUInt16 = type { %CLIObject, i32, [0 x i16] }
-%ArraySInt32 = type { %CLIObject, i32, [0 x i32] }
-%ArrayUInt32 = type { %CLIObject, i32, [0 x i32] }
-%ArraySInt64 = type { %CLIObject, i32, [0 x i64] }
-%ArrayUInt64 = type { %CLIObject, i32, [0 x i64] }
-%ArrayIntPtr = type { %CLIObject, i32, [0 x i32*] }
-%ArrayUIntPtr = type { %CLIObject, i32, [0 x i32*] }
-%ArrayFloat = type { %CLIObject, i32, [0 x float] }
-%ArrayDouble = type { %CLIObject, i32, [0 x double] }
-%ArrayObject = type { %CLIObject, i32, [0 x %CLIObject*] }
-
-%CacheNode = type {i8*, i8*, i8*, i8*, i8*, i1}
-
-%Enveloppe = type {i8*, %CacheNode*, i8*, i8*}
-
-declare void @MarkAndTrace(%CLIObject*)
-declare void @CLIObjectTracer(%CLIObject*)
-
-declare %CLIObject* @initialiseClass(i8*)
-
-declare %CacheNode* @n3VirtualLookup(%CacheNode*, %CLIObject*)
-
-declare %CLIObject* @newArray(i8*, i32)
-declare %CLIObject* @newObject(i8*)
-declare %CLIObject* @newMultiArray(i8*)
-declare %CLIObject* @newString(i8*)
-
-declare %CLIObject* @initialiseObject(i8*, i32) readnone
-
-declare i32 @arrayLength(%CLIArray*) readnone
-
-declare void @n3NullPointerException()
-declare void @n3ClassCastException()
-declare void @indexOutOfBounds(%CLIObject*, i32)
-
-declare void @ThrowException(%CLIObject*)
-declare void @ClearException()
-declare i8* @GetCppException()
-declare %CLIObject* @GetCLIException()
-declare i1 @CompareException(i8*)
-
-declare i32 @n3InstanceOf(%CLIObject*, i8*)
-
-;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
-;;;;;;;;;;;;;;;;;;;;;;;;;;;;; Debugging methods ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
-;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
-
-declare void @n3PrintExecution(i32, i32)
-
diff --git a/vmkit/lib/N3/Makefile b/vmkit/lib/N3/Makefile
deleted file mode 100644
index 8f69ae8..0000000
--- a/vmkit/lib/N3/Makefile
+++ /dev/null
@@ -1,25 +0,0 @@
-##===- lib/Makefile ----------------------------------------*- Makefile -*-===##
-#
-# The vmkit project
-#
-# This file is distributed under the University of Illinois Open Source
-# License. See LICENSE.TXT for details.
-#
-##===----------------------------------------------------------------------===##
-LEVEL = ../..
-
-include $(LEVEL)/Makefile.config
-
-DIRS = LLVMRuntime VMCore
-
-ifeq ($(WITH_N3_MONO), 1)
- DIRS += Mono
-endif
-
-ifeq ($(WITH_N3_PNETLIB), 1)
- DIRS += PNetLib
-endif
-
-EXTRA_DIST = Mono PNetLib
-
-include $(LEVEL)/Makefile.common
diff --git a/vmkit/lib/N3/Mono/LICENSE.TXT b/vmkit/lib/N3/Mono/LICENSE.TXT
deleted file mode 100644
index 167da7b..0000000
--- a/vmkit/lib/N3/Mono/LICENSE.TXT
+++ /dev/null
@@ -1,22 +0,0 @@
---------------------------------------------------------------------------------
-VMKit Mono runtime
---------------------------------------------------------------------------------
-All files are licensed under the VMKit license with the following additions:
-
-vmkit/lib/N3/Mono/Mono.cpp
-
- This code is dual licensed under the LGPL or commercial licenses.
-
- The LGPL ensures that Mono can be used in most scenarios, but
- gives Novell the flexibility to relicense the code for embedded
- systems or commercial settings where the LGPL can not be used.
-
- Contact mono@novell.com for details on obtaining the Mono
- runtime under other terms.
-
- (C) 2008 Ximian, Inc. http://www.ximian.com
-
-vmkit/lib/N3/Mono/number-formatter.h
-
- This file is under the Mono License.
- (C) 2008 Ximian, Inc. http://www.ximian.com
diff --git a/vmkit/lib/N3/Mono/Makefile b/vmkit/lib/N3/Mono/Makefile
deleted file mode 100644
index 9105528..0000000
--- a/vmkit/lib/N3/Mono/Makefile
+++ /dev/null
@@ -1,24 +0,0 @@
-##===- lib/N3/Mono/Makefile --------------------------------*- Makefile -*-===##
-#
-# The vmkit project
-#
-# This file is distributed under the University of Illinois Open Source
-# License. See LICENSE.TXT for details.
-#
-##===----------------------------------------------------------------------===##
-LEVEL = ../../..
-
-include $(LEVEL)/Makefile.config
-
-ifeq ($(WITH_LLVM_GCC), 1)
- MODULE_NAME = Mono
-else
- LIBRARYNAME = Mono
-endif
-
-EXTRA_DIST = MonoPath.inc.in
-include $(LEVEL)/Makefile.common
-CXX.Flags += -I$(PROJ_SRC_DIR)/../VMCore
-
-CXX.Flags += `pkg-config --cflags glib-2.0 gthread-2.0`
-CXX.Flags += `pkg-config --cflags gmodule-2.0`
diff --git a/vmkit/lib/N3/Mono/Mono.cpp b/vmkit/lib/N3/Mono/Mono.cpp
deleted file mode 100644
index 9699a16..0000000
--- a/vmkit/lib/N3/Mono/Mono.cpp
+++ /dev/null
@@ -1,374 +0,0 @@
-//===-------------- Mono.cpp - The Mono interface -------------------------===//
-//
-// N3
-//
-// This file is licensed under the University of Illinois Open Source License
-// and the Mono License. See LICENSE.TXT for details.
-// The file also has the following additional copyright:
-//
-// (C) 2008 Ximian, Inc. http://www.ximian.com
-//
-//===----------------------------------------------------------------------===//
-
-#include "mvm/JIT.h"
-
-#include "Assembly.h"
-#include "MonoString.h"
-#include "MSCorlib.h"
-#include "N3.h"
-#include "Reader.h"
-#include "VMArray.h"
-#include "VMClass.h"
-#include "VMObject.h"
-#include "VMThread.h"
-
-#include <glib.h>
-
-#include "number-formatter.h"
-
-#include "MonoPath.inc"
-
-using namespace n3;
-
-extern "C" int System_Environment_get_Platform (void) {
-#if defined (PLATFORM_WIN32)
- /* Win32NT */
- return 2;
-#else
- /* Unix */
- return 128;
-#endif
-}
-
-static const char *encodings [] = {
- (char *) 1,
- "ascii", "us_ascii", "us", "ansi_x3.4_1968",
- "ansi_x3.4_1986", "cp367", "csascii", "ibm367",
- "iso_ir_6", "iso646_us", "iso_646.irv:1991",
- (char *) 2,
- "utf_7", "csunicode11utf7", "unicode_1_1_utf_7",
- "unicode_2_0_utf_7", "x_unicode_1_1_utf_7",
- "x_unicode_2_0_utf_7",
- (char *) 3,
- "utf_8", "unicode_1_1_utf_8", "unicode_2_0_utf_8",
- "x_unicode_1_1_utf_8", "x_unicode_2_0_utf_8",
- (char *) 4,
- "utf_16", "UTF_16LE", "ucs_2", "unicode",
- "iso_10646_ucs2",
- (char *) 5,
- "unicodefffe", "utf_16be",
- (char *) 6,
- "iso_8859_1",
- (char *) 0
-};
-
-/*
- * Returns the internal codepage, if the value of "int_code_page" is
- * 1 at entry, and we can not compute a suitable code page number,
- * returns the code page as a string
- */
-extern "C" MonoString*
-System_Text_Encoding_InternalCodePage (gint32 *int_code_page)
-{
- const char *cset;
- const char *p;
- char *c;
- char *codepage = NULL;
- int code;
- int want_name = *int_code_page;
- int i;
-
- *int_code_page = -1;
-
- g_get_charset (&cset);
- c = codepage = strdup (cset);
- for (c = codepage; *c; c++){
- if (isascii (*c) && isalpha (*c))
- *c = tolower (*c);
- if (*c == '-')
- *c = '_';
- }
- /* g_print ("charset: %s\n", cset); */
-
- /* handle some common aliases */
- p = encodings [0];
- code = 0;
- for (i = 0; p != 0; ){
- if ((gssize) p < 7){
- code = (gssize) p;
- p = encodings [++i];
- continue;
- }
- if (strcmp (p, codepage) == 0){
- *int_code_page = code;
- break;
- }
- p = encodings [++i];
- }
-
- if (strstr (codepage, "utf_8") != NULL)
- *int_code_page |= 0x10000000;
- free (codepage);
-
- if (want_name && *int_code_page == -1) {
- N3 *vm = (N3*)VMThread::get()->getVM();
- declare_gcroot(ArrayChar*, array_res) = vm->asciizToArray(cset);
- declare_gcroot(MonoString*, res) = (MonoString*)(vm->arrayToString(array_res));
- return res;
- } else
- return NULL;
-}
-
-extern "C" void System_Threading_Monitor_Monitor_exit(VMObject* obj) {
- // TODO: There's a bug in the bootstrap, see why
- llvm_gcroot(obj, 0);
- if (LockObj::owner(obj->lockObj)) VMObject::unlock(obj);
-}
-
-extern "C" bool System_Threading_Monitor_Monitor_try_enter(VMObject* obj, int ms) {
- llvm_gcroot(obj, 0);
- VMObject::aquire(obj);
- return true;
-}
-
-
-extern "C" void* System_IO_MonoIO_get_ConsoleError() {
- return (void*)stderr;
-}
-
-extern "C" void* System_IO_MonoIO_get_ConsoleOutput() {
- return (void*)stdout;
-}
-
-extern "C" void* System_IO_MonoIO_get_ConsoleInput() {
- return (void*)stdin;
-}
-
-enum MonoFileType {
- Unknown=0x0000,
- Disk=0x0001,
- Char=0x0002,
- Pipe=0x0003,
- Remote=0x8000
-};
-
-extern "C" MonoFileType System_IO_MonoIO_GetFileType(void* handle, int* error) {
- if (handle == (void*)stdin || handle == (void*)stdout || handle == (void*)stderr)
- return Char;
- else
- return Unknown;
-}
-
-extern "C" MonoString *
-System_Environment_get_NewLine (void)
-{
- N3 *vm = (N3*)VMThread::get()->getVM();
-#if defined (PLATFORM_WIN32)
- declare_gcroot(ArrayChar*, array) = vm->asciizToArray("\r\n");
-#else
- declare_gcroot(ArrayChar*, array) = vm->asciizToArray("\n");
-#endif
-
- declare_gcroot(MonoString*, res) = (MonoString*)vm->arrayToString(array);
- return res;
-}
-
-extern "C" void
-System_String_InternalCopyTo(MonoString* str, sint32 sindex, VMArray* dest, sint32 destIndex, sint32 count) {
- llvm_gcroot(str, 0);
- llvm_gcroot(dest, 0);
- declare_gcroot(const ArrayChar*, contents) = str->value;
- memcpy(&dest->elements[destIndex], &contents->elements[sindex], count * sizeof(uint16));
-}
-
-extern "C" uint16 System_String_get_Chars(MonoString* str, sint32 offset) {
- llvm_gcroot(str, 0);
- return str->value->elements[offset];
-}
-
-static sint32 byteLength(VMArray* array) {
- llvm_gcroot(array, 0);
- VMClassArray* cl = (VMClassArray*)array->classOf;
- VMCommonClass* base = cl->baseClass;
- uint32 size = base->naturalType->getPrimitiveSizeInBits() / 8;
- return array->size * size;
-}
-
-extern "C" bool System_Buffer_BlockCopyInternal (VMArray* src, int src_offset, VMArray* dest, int dest_offset, int count) {
- llvm_gcroot(src, 0);
- llvm_gcroot(dest, 0);
- uint8 *src_buf, *dest_buf;
-
- /* watch out for integer overflow */
- if ((src_offset > byteLength(src) - count) || (dest_offset > byteLength(dest) - count))
- return false;
-
- src_buf = (uint8 *)src->elements + src_offset;
- dest_buf = (uint8 *)dest->elements + dest_offset;
-
- if (src != dest)
- memcpy (dest_buf, src_buf, count);
- else
- memmove (dest_buf, src_buf, count); /* Source and dest are the same array */
-
- return true;
-
-}
-
-extern "C" sint32 System_Buffer_ByteLengthInternal(VMArray* array) {
- llvm_gcroot(array, 0);
- return byteLength(array);
-}
-
-extern "C" sint32
-System_IO_MonoIO_Write (void* handle, ArrayUInt8 *src,
- sint32 src_offset, sint32 count,
- sint32 *error)
-{
- llvm_gcroot(src, 0);
- char* buffer = (char*)alloca( 1024);//(count + 8) * sizeof(uint16));
- uint32 n = 0;
-
- *error = 0;
-
- if (src_offset + count > src->size)
- return 0;
-
- memcpy(buffer, (char*)&(src->elements[src_offset]), count);
- buffer[count] = 0;
- n = fprintf((FILE*)handle, buffer);
-
- return (sint32)n;
-}
-
-/* These parameters are "readonly" in corlib/System/NumberFormatter.cs */
-extern "C" void
-System_NumberFormatter_GetFormatterTables (guint64 const **mantissas,
- gint32 const **exponents,
- gunichar2 const **digitLowerTable,
- gunichar2 const **digitUpperTable,
- gint64 const **tenPowersList,
- gint32 const **decHexDigits)
-{
- *mantissas = Formatter_MantissaBitsTable;
- *exponents = Formatter_TensExponentTable;
- *digitLowerTable = Formatter_DigitLowerTable;
- *digitUpperTable = Formatter_DigitUpperTable;
- *tenPowersList = Formatter_TenPowersList;
- *decHexDigits = Formatter_DecHexDigits;
-}
-
-extern "C" VMObject* System_Threading_Thread_CurrentThread_internal() {
- declare_gcroot(VMObject*, appThread) = VMThread::get()->ooo_appThread;
- return appThread;
-}
-
-extern "C" VMObject*
-System_Threading_Thread_GetCachedCurrentCulture (VMObject *obj)
-{
- llvm_gcroot(obj, 0);
- return 0;
-}
-
-extern "C" VMObject*
-System_Threading_Thread_GetSerializedCurrentCulture (VMObject *obj)
-{
- llvm_gcroot(obj, 0);
- return 0;
-}
-
-extern "C" VMObject* System_Object_MemberwiseClone(VMObject* obj) {
- llvm_gcroot(obj, 0);
- uint64 size = obj->objectSize();
- declare_gcroot(VMObject*, res) = ((VMClass*)obj->classOf)->doNew();
- memcpy(res, obj, size);
- res->lockObj = 0;
- return res;
-}
-
-extern "C" bool
-System_Globalization_CultureInfo_construct_internal_locale_from_current_locale (VMObject *ci)
-{
- llvm_gcroot(ci, 0);
- return false;
-}
-
-extern "C" void
-System_Threading_Thread_SetCachedCurrentCulture (VMObject* thread, VMObject *culture)
-{
- llvm_gcroot(thread, 0);
- llvm_gcroot(culture, 0);
-}
-
-extern "C" void
-System_String__ctor(MonoString* str, ArrayChar* array, sint32 startIndex, sint32 count) {
- llvm_gcroot(str, 0);
- llvm_gcroot(array, 0);
- N3* vm = VMThread::get()->getVM();
- declare_gcroot(const ArrayChar*, value) = vm->bufToArray(&(array->elements[startIndex]), count);
- str->length = count;
- str->startChar = array->elements[startIndex];
- str->value = value;
-}
-
-extern "C" MonoString *
-System_String_InternalJoin (MonoString *separator, VMArray * value, sint32 sindex, sint32 count)
-{
- llvm_gcroot(separator, 0);
- llvm_gcroot(value, 0);
- declare_gcroot(MonoString*, current) = 0;
- sint32 length;
- sint32 pos;
- sint32 insertlen;
- sint32 destpos;
- sint32 srclen;
- const uint16 *insert;
- const uint16 *src;
- uint16 *dest;
-
- insert = separator->value->elements;
- insertlen = separator->length;
-
- length = 0;
- for (pos = sindex; pos != sindex + count; pos++) {
- current = (MonoString*)value->elements[pos];
- if (current != NULL)
- length += current->length;
-
- if (pos < sindex + count - 1)
- length += insertlen;
- }
-
- dest = (uint16*)alloca(length * sizeof(uint16));
- destpos = 0;
-
- for (pos = sindex; pos != sindex + count; pos++) {
- current = (MonoString*)value->elements[pos];
- if (current != NULL) {
- src = current->value->elements;
- srclen = current->length;
-
- memcpy (dest + destpos, src, srclen * sizeof(uint16));
- destpos += srclen;
- }
-
- if (pos < sindex + count - 1) {
- memcpy(dest + destpos, insert, insertlen * sizeof(uint16));
- destpos += insertlen;
- }
- }
-
- N3* vm = (N3*)VMThread::get()->getVM();
- declare_gcroot(const ArrayChar*, array) = vm->bufToArray(dest, length);
- declare_gcroot(MonoString*, res) = (MonoString*)vm->arrayToString(array);
- return res;
-}
-
-extern "C" MonoString *
-System_String_InternalAllocateStr (sint32 length)
-{
- declare_gcroot(MonoString*, str) = (MonoString*)MSCorlib::pString->doNew();
- str->length = length;
- return str;
-}
-
diff --git a/vmkit/lib/N3/Mono/MonoMSCorlib.cpp b/vmkit/lib/N3/Mono/MonoMSCorlib.cpp
deleted file mode 100644
index 26b2fa1..0000000
--- a/vmkit/lib/N3/Mono/MonoMSCorlib.cpp
+++ /dev/null
@@ -1,184 +0,0 @@
-//===----- MonoMSCorlib.cpp - The Mono MSCorlib implementation ------------===//
-//
-// N3
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-
-#include "mvm/JIT.h"
-
-#include "Assembly.h"
-#include "MSCorlib.h"
-#include "N3.h"
-#include "VMClass.h"
-#include "VMObject.h"
-#include "VMThread.h"
-
-using namespace n3;
-
-void MSCorlib::loadStringClass(N3* vm) {
- VMClass* type = (VMClass*)vm->coreAssembly->loadTypeFromName(
- vm->asciizToUTF8("String"),
- vm->asciizToUTF8("System"),
- false, false, false, true);
- MSCorlib::pString = type;
- MSCorlib::pObject->resolveType(true, false, NULL);
- MSCorlib::pObject->resolveVT();
- type->resolveType(true, false, NULL);
- type->resolveVT();
-
- uint64 size = mvm::MvmModule::getTypeSize(type->virtualType->getContainedType(0)) + sizeof(const UTF8*) + sizeof(llvm::GlobalVariable*);
- type->virtualInstance =
- (VMObject*)gc::operator new(size, VMObject::getN3VirtualTable(type->virtualInstance));
- VMObject::initialise(type->virtualInstance, type);
-}
-
-
-void MSCorlib::initialise(N3* vm) {
-
- VMClass* runtimeTypeHandle = 0;
- VMClass* realClrType = 0;
- #define INIT(var, nameSpace, name, type, prim) {\
- var = (VMClass*)vm->coreAssembly->loadTypeFromName( \
- vm->asciizToUTF8(name), \
- vm->asciizToUTF8(nameSpace),\
- false, false, false, true); \
- var->isPrimitive = prim; \
- if (type) { \
- var->naturalType = type; \
- var->virtualType = type; \
- }}
-
- INIT(MSCorlib::clrType, "System", "MonoType", 0, false);
- INIT(realClrType, "System", "Type", 0, false);
- INIT(runtimeTypeHandle, "System", "RuntimeTypeHandle", 0, false);
- /*
- INIT(MSCorlib::assemblyReflection, "System.Reflection", "Assembly", 0, false);
- INIT(MSCorlib::typedReference, "System", "TypedReference", 0, false);
- INIT(MSCorlib::propertyType, "System.Reflection", "ClrProperty", 0, false);
- INIT(MSCorlib::methodType, "System.Reflection", "ClrMethod", 0, false);
- INIT(MSCorlib::resourceStreamType, "System.Reflection", "ClrResourceStream", 0, false);*/
-#undef INIT
-
- {
- MSCorlib::clrType->resolveType(false, false, NULL);
- MSCorlib::typeClrType = realClrType->lookupField(vm->asciizToUTF8("_impl"), runtimeTypeHandle, false, false);
- }
-
-/*
- {
- MSCorlib::assemblyReflection->resolveType(false, false);
- std::vector<VMCommonClass*> args;
- args.push_back(MSCorlib::pVoid);
- args.push_back(MSCorlib::assemblyReflection);
- MSCorlib::ctorAssemblyReflection = MSCorlib::assemblyReflection->lookupMethod(vm->asciizToUTF8(".ctor"), args, false, false);
- MSCorlib::assemblyAssemblyReflection = MSCorlib::assemblyReflection->lookupField(vm->asciizToUTF8("privateData"), MSCorlib::pIntPtr, false, false);
- }
-
- {
- MSCorlib::propertyType->resolveType(false, false);
- std::vector<VMCommonClass*> args;
- args.push_back(MSCorlib::pVoid);
- args.push_back(MSCorlib::propertyType);
- MSCorlib::ctorPropertyType = MSCorlib::propertyType->lookupMethod(vm->asciizToUTF8(".ctor"), args, false, false);
- MSCorlib::propertyPropertyType = MSCorlib::propertyType->lookupField(vm->asciizToUTF8("privateData"), MSCorlib::pIntPtr, false, false);
- }
-
- {
- MSCorlib::methodType->resolveType(false, false);
- std::vector<VMCommonClass*> args;
- args.push_back(MSCorlib::pVoid);
- args.push_back(MSCorlib::methodType);
- MSCorlib::ctorMethodType = MSCorlib::methodType->lookupMethod(vm->asciizToUTF8(".ctor"), args, false, false);
- MSCorlib::methodMethodType = MSCorlib::methodType->lookupField(vm->asciizToUTF8("privateData"), MSCorlib::pIntPtr, false, false);
- }
-
- {
- MSCorlib::resourceStreamType->resolveType(false, false);
- std::vector<VMCommonClass*> args;
- args.push_back(MSCorlib::pVoid);
- args.push_back(MSCorlib::resourceStreamType);
- args.push_back(MSCorlib::pIntPtr);
- args.push_back(MSCorlib::pSInt64);
- args.push_back(MSCorlib::pSInt64);
- MSCorlib::ctorResourceStreamType = MSCorlib::resourceStreamType->lookupMethod(vm->asciizToUTF8(".ctor"), args, false, false);
- }
-
- VMCommonClass* voidPtr = vm->coreAssembly->constructPointer(MSCorlib::pVoid, 1);
-#define INIT(var, cl, type) {\
- cl->resolveType(false, false); \
- var = cl->lookupField(vm->asciizToUTF8("value_"), type, false, false); \
- }
-
- INIT(MSCorlib::ctorBoolean, MSCorlib::pBoolean, MSCorlib::pBoolean);
- INIT(MSCorlib::ctorUInt8, MSCorlib::pUInt8, MSCorlib::pUInt8);
- INIT(MSCorlib::ctorSInt8, MSCorlib::pSInt8, MSCorlib::pSInt8);
- INIT(MSCorlib::ctorChar, MSCorlib::pChar, MSCorlib::pChar);
- INIT(MSCorlib::ctorSInt16, MSCorlib::pSInt16, MSCorlib::pSInt16);
- INIT(MSCorlib::ctorUInt16, MSCorlib::pUInt16, MSCorlib::pUInt16);
- INIT(MSCorlib::ctorSInt32, MSCorlib::pSInt32, MSCorlib::pSInt32);
- INIT(MSCorlib::ctorUInt32, MSCorlib::pUInt32, MSCorlib::pUInt32);
- INIT(MSCorlib::ctorSInt64, MSCorlib::pSInt64, MSCorlib::pSInt64);
- INIT(MSCorlib::ctorUInt64, MSCorlib::pUInt64, MSCorlib::pUInt64);
- INIT(MSCorlib::ctorIntPtr, MSCorlib::pIntPtr, voidPtr);
- INIT(MSCorlib::ctorUIntPtr, MSCorlib::pUIntPtr, voidPtr);
- INIT(MSCorlib::ctorDouble, MSCorlib::pDouble, MSCorlib::pDouble);
- INIT(MSCorlib::ctorFloat, MSCorlib::pFloat, MSCorlib::pFloat);
-
-#undef INIT
-
- */
-}
-
-VMObject* Property::getPropertyDelegatee() {
- declare_gcroot(VMObject*, delegatee) = ooo_delegatee;
-
- if (!delegatee) {
- VMThread::get()->getVM()->error("implement me");
- }
-
- return delegatee;
-}
-
-VMObject* VMMethod::getMethodDelegatee() {
- declare_gcroot(VMObject*, delegatee) = ooo_delegatee;
-
- if (!delegatee) {
- VMThread::get()->getVM()->error("implement me");
- }
-
- return delegatee;
-}
-
-VMObject* VMCommonClass::getClassDelegatee() {
- declare_gcroot(VMObject*, delegatee) = ooo_delegatee;
-
- if (!delegatee) {
- ooo_delegatee = delegatee = MSCorlib::clrType->doNew();
- MSCorlib::typeClrType->setIntPtr(delegatee, (int*)this);
- }
-
- return delegatee;
-}
-
-VMObject* Assembly::getAssemblyDelegatee() {
- declare_gcroot(VMObject*, delegatee) = ooo_delegatee;
-
- if (!delegatee) {
- VMThread::get()->getVM()->error("implement me");
- }
-
- return delegatee;
-}
-
-void MSCorlib::loadBootstrap(N3* vm) {
- VMClass* cl = (VMClass*)vm->coreAssembly->loadTypeFromName(
- vm->asciizToUTF8("Thread"),
- vm->asciizToUTF8("System.Threading"),
- true, true, true, true);
- declare_gcroot(VMObject*, appThread) = cl->doNew();
- VMThread::get()->ooo_appThread = appThread;
-}
diff --git a/vmkit/lib/N3/Mono/MonoPath.inc.in b/vmkit/lib/N3/Mono/MonoPath.inc.in
deleted file mode 100644
index febbbcd..0000000
--- a/vmkit/lib/N3/Mono/MonoPath.inc.in
+++ /dev/null
@@ -1,15 +0,0 @@
-//===------ MonoPath.cpp - mscorlib.dll location for mono -----------------===//
-//
-// N3
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#include "MSCorlib.h"
-
-using namespace n3;
-
-const char* MSCorlib::libsPath = "@monopath@/";
-
diff --git a/vmkit/lib/N3/Mono/MonoString.cpp b/vmkit/lib/N3/Mono/MonoString.cpp
deleted file mode 100644
index 131431f..0000000
--- a/vmkit/lib/N3/Mono/MonoString.cpp
+++ /dev/null
@@ -1,58 +0,0 @@
-//===--- PNetString.cpp - Implementation of PNet string interface ---------===//
-//
-// N3
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#include "llvm/DerivedTypes.h"
-#include "llvm/GlobalVariable.h"
-#include "llvm/LLVMContext.h"
-
-#include "mvm/JIT.h"
-
-#include "CLIString.h"
-#include "MSCorlib.h"
-#include "N3.h"
-#include "MonoString.h"
-#include "VMArray.h"
-#include "VMClass.h"
-#include "VMThread.h"
-
-using namespace n3;
-using namespace llvm;
-
-
-CLIString* CLIString::stringDup(const ArrayChar* array, N3* vm) {
- llvm_gcroot(array, 0);
- declare_gcroot(MonoString*, obj) = (MonoString*)MSCorlib::pString->doNew();
- obj->length = array->size;
- if (array->size == 0) {
- obj->startChar = 0;
- } else {
- obj->startChar = array->elements[0];
- }
- obj->value = array;
- return obj;
-}
-
-GlobalVariable* CLIString::llvmVar(CLIString *self) {
- llvm_gcroot(self, 0);
- declare_gcroot(MonoString*, str) = (MonoString*)self;
- if (!str->_llvmVar) {
- N3* vm = VMThread::get()->getVM();
- if (!str->_llvmVar) {
- const Type* pty = PointerType::getUnqual(Type::getInt8Ty(getGlobalContext()));
- Module* Mod = vm->getLLVMModule();
- Constant* cons =
- ConstantExpr::getIntToPtr(ConstantInt::get(Type::getInt64Ty(getGlobalContext()), uint64_t (self)),
- pty);
- str->_llvmVar = new GlobalVariable(*Mod, pty, true,
- GlobalValue::ExternalLinkage,
- cons, "");
- }
- }
- return str->_llvmVar;
-}
diff --git a/vmkit/lib/N3/Mono/MonoString.h b/vmkit/lib/N3/Mono/MonoString.h
deleted file mode 100644
index e953d2c..0000000
--- a/vmkit/lib/N3/Mono/MonoString.h
+++ /dev/null
@@ -1,35 +0,0 @@
-//===---------- MonoString.h - String representation in Mono --------------===//
-//
-// N3
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#ifndef N3_MONO_STRING_H
-#define N3_MONO_STRING_H
-
-#include "llvm/GlobalVariable.h"
-
-#include "types.h"
-#include "mvm/PrintBuffer.h"
-
-#include "CLIString.h"
-
-namespace n3 {
-
-class MonoString : public CLIString {
-public:
-
- // !!! mono layout !!!
- sint32 length;
- uint8 startChar;
- const ArrayChar* value;
- llvm::GlobalVariable* _llvmVar;
-
-};
-
-} // end namespace n3
-
-#endif
diff --git a/vmkit/lib/N3/Mono/number-formatter.h b/vmkit/lib/N3/Mono/number-formatter.h
deleted file mode 100644
index 5ec0bc9..0000000
--- a/vmkit/lib/N3/Mono/number-formatter.h
+++ /dev/null
@@ -1,914 +0,0 @@
-/*
- * This file is under the Mono License.
- * (C) 2008 Ximian, Inc. http://www.ximian.com
- */
-
-#ifndef _MONO_METADATA_NUMBER_FORMATTER_H_
-#define _MONO_METADATA_NUMBER_FORMATTER_H_ 1
-
-static const guint64 Formatter_MantissaBitsTable [] = {
- 4556951262222748432ULL, 9113902524445496865ULL, 18227805048890993730ULL,
- 3645561009778198746ULL, 7291122019556397492ULL, 14582244039112794984ULL,
- 2916448807822558996ULL, 5832897615645117993ULL, 11665795231290235987ULL,
- 2333159046258047197ULL, 4666318092516094394ULL, 9332636185032188789ULL,
- 1866527237006437757ULL, 3733054474012875515ULL, 7466108948025751031ULL,
- 14932217896051502063ULL, 2986443579210300412ULL, 5972887158420600825ULL,
- 11945774316841201651ULL, 2389154863368240330ULL, 4778309726736480660ULL,
- 9556619453472961320ULL, 1911323890694592264ULL, 3822647781389184528ULL,
- 7645295562778369056ULL, 15290591125556738113ULL, 3058118225111347622ULL,
- 6116236450222695245ULL, 12232472900445390490ULL, 2446494580089078098ULL,
- 4892989160178156196ULL, 9785978320356312392ULL, 1957195664071262478ULL,
- 3914391328142524957ULL, 7828782656285049914ULL, 15657565312570099828ULL,
- 3131513062514019965ULL, 6263026125028039931ULL, 12526052250056079862ULL,
- 2505210450011215972ULL, 5010420900022431944ULL, 10020841800044863889ULL,
- 2004168360008972777ULL, 4008336720017945555ULL, 8016673440035891111ULL,
- 16033346880071782223ULL, 3206669376014356444ULL, 6413338752028712889ULL,
- 12826677504057425779ULL, 2565335500811485155ULL, 5130671001622970311ULL,
- 10261342003245940623ULL, 2052268400649188124ULL, 4104536801298376249ULL,
- 8209073602596752498ULL, 16418147205193504997ULL, 3283629441038700999ULL,
- 6567258882077401998ULL, 13134517764154803997ULL, 2626903552830960799ULL,
- 5253807105661921599ULL, 10507614211323843198ULL, 2101522842264768639ULL,
- 4203045684529537279ULL, 8406091369059074558ULL, 16812182738118149117ULL,
- 3362436547623629823ULL, 6724873095247259646ULL, 13449746190494519293ULL,
- 2689949238098903858ULL, 5379898476197807717ULL, 10759796952395615435ULL,
- 2151959390479123087ULL, 4303918780958246174ULL, 8607837561916492348ULL,
- 17215675123832984696ULL, 3443135024766596939ULL, 6886270049533193878ULL,
- 13772540099066387756ULL, 2754508019813277551ULL, 5509016039626555102ULL,
- 11018032079253110205ULL, 2203606415850622041ULL, 4407212831701244082ULL,
- 8814425663402488164ULL, 17628851326804976328ULL, 3525770265360995265ULL,
- 7051540530721990531ULL, 14103081061443981063ULL, 2820616212288796212ULL,
- 5641232424577592425ULL, 11282464849155184850ULL, 2256492969831036970ULL,
- 4512985939662073940ULL, 9025971879324147880ULL, 18051943758648295760ULL,
- 3610388751729659152ULL, 7220777503459318304ULL, 14441555006918636608ULL,
- 2888311001383727321ULL, 5776622002767454643ULL, 11553244005534909286ULL,
- 2310648801106981857ULL, 4621297602213963714ULL, 9242595204427927429ULL,
- 1848519040885585485ULL, 3697038081771170971ULL, 7394076163542341943ULL,
- 14788152327084683887ULL, 2957630465416936777ULL, 5915260930833873554ULL,
- 11830521861667747109ULL, 2366104372333549421ULL, 4732208744667098843ULL,
- 9464417489334197687ULL, 1892883497866839537ULL, 3785766995733679075ULL,
- 7571533991467358150ULL, 15143067982934716300ULL, 3028613596586943260ULL,
- 6057227193173886520ULL, 12114454386347773040ULL, 2422890877269554608ULL,
- 4845781754539109216ULL, 9691563509078218432ULL, 1938312701815643686ULL,
- 3876625403631287372ULL, 7753250807262574745ULL, 15506501614525149491ULL,
- 3101300322905029898ULL, 6202600645810059796ULL, 12405201291620119593ULL,
- 2481040258324023918ULL, 4962080516648047837ULL, 9924161033296095674ULL,
- 1984832206659219134ULL, 3969664413318438269ULL, 7939328826636876539ULL,
- 15878657653273753079ULL, 3175731530654750615ULL, 6351463061309501231ULL,
- 12702926122619002463ULL, 2540585224523800492ULL, 5081170449047600985ULL,
- 10162340898095201970ULL, 2032468179619040394ULL, 4064936359238080788ULL,
- 8129872718476161576ULL, 16259745436952323153ULL, 3251949087390464630ULL,
- 6503898174780929261ULL, 13007796349561858522ULL, 2601559269912371704ULL,
- 5203118539824743409ULL, 10406237079649486818ULL, 2081247415929897363ULL,
- 4162494831859794727ULL, 8324989663719589454ULL, 16649979327439178909ULL,
- 3329995865487835781ULL, 6659991730975671563ULL, 13319983461951343127ULL,
- 2663996692390268625ULL, 5327993384780537250ULL, 10655986769561074501ULL,
- 2131197353912214900ULL, 4262394707824429800ULL, 8524789415648859601ULL,
- 17049578831297719202ULL, 3409915766259543840ULL, 6819831532519087681ULL,
- 13639663065038175362ULL, 2727932613007635072ULL, 5455865226015270144ULL,
- 10911730452030540289ULL, 2182346090406108057ULL, 4364692180812216115ULL,
- 8729384361624432231ULL, 17458768723248864463ULL, 3491753744649772892ULL,
- 6983507489299545785ULL, 13967014978599091570ULL, 2793402995719818314ULL,
- 5586805991439636628ULL, 11173611982879273256ULL, 2234722396575854651ULL,
- 4469444793151709302ULL, 8938889586303418605ULL, 17877779172606837210ULL,
- 3575555834521367442ULL, 7151111669042734884ULL, 14302223338085469768ULL,
- 2860444667617093953ULL, 5720889335234187907ULL, 11441778670468375814ULL,
- 2288355734093675162ULL, 4576711468187350325ULL, 9153422936374700651ULL,
- 18306845872749401303ULL, 3661369174549880260ULL, 7322738349099760521ULL,
- 14645476698199521043ULL, 2929095339639904208ULL, 5858190679279808417ULL,
- 11716381358559616834ULL, 2343276271711923366ULL, 4686552543423846733ULL,
- 9373105086847693467ULL, 1874621017369538693ULL, 3749242034739077387ULL,
- 7498484069478154774ULL, 14996968138956309548ULL, 2999393627791261909ULL,
- 5998787255582523819ULL, 11997574511165047638ULL, 2399514902233009527ULL,
- 4799029804466019055ULL, 9598059608932038110ULL, 1919611921786407622ULL,
- 3839223843572815244ULL, 7678447687145630488ULL, 15356895374291260977ULL,
- 3071379074858252195ULL, 6142758149716504390ULL, 12285516299433008781ULL,
- 2457103259886601756ULL, 4914206519773203512ULL, 9828413039546407025ULL,
- 1965682607909281405ULL, 3931365215818562810ULL, 7862730431637125620ULL,
- 15725460863274251240ULL, 3145092172654850248ULL, 6290184345309700496ULL,
- 12580368690619400992ULL, 2516073738123880198ULL, 5032147476247760397ULL,
- 10064294952495520794ULL, 2012858990499104158ULL, 4025717980998208317ULL,
- 8051435961996416635ULL, 16102871923992833270ULL, 3220574384798566654ULL,
- 6441148769597133308ULL, 12882297539194266616ULL, 2576459507838853323ULL,
- 5152919015677706646ULL, 10305838031355413293ULL, 2061167606271082658ULL,
- 4122335212542165317ULL, 8244670425084330634ULL, 16489340850168661269ULL,
- 3297868170033732253ULL, 6595736340067464507ULL, 13191472680134929015ULL,
- 2638294536026985803ULL, 5276589072053971606ULL, 10553178144107943212ULL,
- 2110635628821588642ULL, 4221271257643177284ULL, 8442542515286354569ULL,
- 16885085030572709139ULL, 3377017006114541827ULL, 6754034012229083655ULL,
- 13508068024458167311ULL, 2701613604891633462ULL, 5403227209783266924ULL,
- 10806454419566533849ULL, 2161290883913306769ULL, 4322581767826613539ULL,
- 8645163535653227079ULL, 17290327071306454158ULL, 3458065414261290831ULL,
- 6916130828522581663ULL, 13832261657045163327ULL, 2766452331409032665ULL,
- 5532904662818065330ULL, 11065809325636130661ULL, 2213161865127226132ULL,
- 4426323730254452264ULL, 8852647460508904529ULL, 17705294921017809058ULL,
- 3541058984203561811ULL, 7082117968407123623ULL, 14164235936814247246ULL,
- 2832847187362849449ULL, 5665694374725698898ULL, 11331388749451397797ULL,
- 2266277749890279559ULL, 4532555499780559119ULL, 9065110999561118238ULL,
- 18130221999122236476ULL, 3626044399824447295ULL, 7252088799648894590ULL,
- 14504177599297789180ULL, 2900835519859557836ULL, 5801671039719115672ULL,
- 11603342079438231344ULL, 2320668415887646268ULL, 4641336831775292537ULL,
- 9282673663550585075ULL, 1856534732710117015ULL, 3713069465420234030ULL,
- 7426138930840468060ULL, 14852277861680936121ULL, 2970455572336187224ULL,
- 5940911144672374448ULL, 11881822289344748896ULL, 2376364457868949779ULL,
- 4752728915737899558ULL, 9505457831475799117ULL, 1901091566295159823ULL,
- 3802183132590319647ULL, 7604366265180639294ULL, 15208732530361278588ULL,
- 3041746506072255717ULL, 6083493012144511435ULL, 12166986024289022870ULL,
- 2433397204857804574ULL, 4866794409715609148ULL, 9733588819431218296ULL,
- 1946717763886243659ULL, 3893435527772487318ULL, 7786871055544974637ULL,
- 15573742111089949274ULL, 3114748422217989854ULL, 6229496844435979709ULL,
- 12458993688871959419ULL, 2491798737774391883ULL, 4983597475548783767ULL,
- 9967194951097567535ULL, 1993438990219513507ULL, 3986877980439027014ULL,
- 7973755960878054028ULL, 15947511921756108056ULL, 3189502384351221611ULL,
- 6379004768702443222ULL, 12758009537404886445ULL, 2551601907480977289ULL,
- 5103203814961954578ULL, 10206407629923909156ULL, 2041281525984781831ULL,
- 4082563051969563662ULL, 8165126103939127325ULL, 16330252207878254650ULL,
- 3266050441575650930ULL, 6532100883151301860ULL, 13064201766302603720ULL,
- 2612840353260520744ULL, 5225680706521041488ULL, 10451361413042082976ULL,
- 2090272282608416595ULL, 4180544565216833190ULL, 8361089130433666380ULL,
- 16722178260867332761ULL, 3344435652173466552ULL, 6688871304346933104ULL,
- 13377742608693866209ULL, 2675548521738773241ULL, 5351097043477546483ULL,
- 10702194086955092967ULL, 2140438817391018593ULL, 4280877634782037187ULL,
- 8561755269564074374ULL, 17123510539128148748ULL, 3424702107825629749ULL,
- 6849404215651259499ULL, 13698808431302518998ULL, 2739761686260503799ULL,
- 5479523372521007599ULL, 10959046745042015198ULL, 2191809349008403039ULL,
- 4383618698016806079ULL, 8767237396033612159ULL, 17534474792067224318ULL,
- 3506894958413444863ULL, 7013789916826889727ULL, 14027579833653779454ULL,
- 2805515966730755890ULL, 5611031933461511781ULL, 11222063866923023563ULL,
- 2244412773384604712ULL, 4488825546769209425ULL, 8977651093538418850ULL,
- 17955302187076837701ULL, 3591060437415367540ULL, 7182120874830735080ULL,
- 14364241749661470161ULL, 2872848349932294032ULL, 5745696699864588064ULL,
- 11491393399729176129ULL, 2298278679945835225ULL, 4596557359891670451ULL,
- 9193114719783340903ULL, 18386229439566681806ULL, 3677245887913336361ULL,
- 7354491775826672722ULL, 14708983551653345445ULL, 2941796710330669089ULL,
- 5883593420661338178ULL, 11767186841322676356ULL, 2353437368264535271ULL,
- 4706874736529070542ULL, 9413749473058141084ULL, 1882749894611628216ULL,
- 3765499789223256433ULL, 7530999578446512867ULL, 15061999156893025735ULL,
- 3012399831378605147ULL, 6024799662757210294ULL, 12049599325514420588ULL,
- 2409919865102884117ULL, 4819839730205768235ULL, 9639679460411536470ULL,
- 1927935892082307294ULL, 3855871784164614588ULL, 7711743568329229176ULL,
- 15423487136658458353ULL, 3084697427331691670ULL, 6169394854663383341ULL,
- 12338789709326766682ULL, 2467757941865353336ULL, 4935515883730706673ULL,
- 9871031767461413346ULL, 1974206353492282669ULL, 3948412706984565338ULL,
- 7896825413969130677ULL, 15793650827938261354ULL, 3158730165587652270ULL,
- 6317460331175304541ULL, 12634920662350609083ULL, 2526984132470121816ULL,
- 5053968264940243633ULL, 10107936529880487266ULL, 2021587305976097453ULL,
- 4043174611952194906ULL, 8086349223904389813ULL, 16172698447808779626ULL,
- 3234539689561755925ULL, 6469079379123511850ULL, 12938158758247023701ULL,
- 2587631751649404740ULL, 5175263503298809480ULL, 10350527006597618960ULL,
- 2070105401319523792ULL, 4140210802639047584ULL, 8280421605278095168ULL,
- 16560843210556190337ULL, 3312168642111238067ULL, 6624337284222476135ULL,
- 13248674568444952270ULL, 2649734913688990454ULL, 5299469827377980908ULL,
- 10598939654755961816ULL, 2119787930951192363ULL, 4239575861902384726ULL,
- 8479151723804769452ULL, 16958303447609538905ULL, 3391660689521907781ULL,
- 6783321379043815562ULL, 13566642758087631124ULL, 2713328551617526224ULL,
- 5426657103235052449ULL, 10853314206470104899ULL, 2170662841294020979ULL,
- 4341325682588041959ULL, 8682651365176083919ULL, 17365302730352167839ULL,
- 3473060546070433567ULL, 6946121092140867135ULL, 13892242184281734271ULL,
- 2778448436856346854ULL, 5556896873712693708ULL, 11113793747425387417ULL,
- 2222758749485077483ULL, 4445517498970154966ULL, 8891034997940309933ULL,
- 17782069995880619867ULL, 3556413999176123973ULL, 7112827998352247947ULL,
- 14225655996704495894ULL, 2845131199340899178ULL, 5690262398681798357ULL,
- 11380524797363596715ULL, 2276104959472719343ULL, 4552209918945438686ULL,
- 9104419837890877372ULL, 18208839675781754744ULL, 3641767935156350948ULL,
- 7283535870312701897ULL, 14567071740625403795ULL, 2913414348125080759ULL,
- 5826828696250161518ULL, 11653657392500323036ULL, 2330731478500064607ULL,
- 4661462957000129214ULL, 9322925914000258429ULL, 1864585182800051685ULL,
- 3729170365600103371ULL, 7458340731200206743ULL, 14916681462400413486ULL,
- 2983336292480082697ULL, 5966672584960165394ULL, 11933345169920330789ULL,
- 2386669033984066157ULL, 4773338067968132315ULL, 9546676135936264631ULL,
- 1909335227187252926ULL, 3818670454374505852ULL, 7637340908749011705ULL,
- 15274681817498023410ULL, 3054936363499604682ULL, 6109872726999209364ULL,
- 12219745453998418728ULL, 2443949090799683745ULL, 4887898181599367491ULL,
- 9775796363198734982ULL, 1955159272639746996ULL, 3910318545279493993ULL,
- 7820637090558987986ULL, 15641274181117975972ULL, 3128254836223595194ULL,
- 6256509672447190388ULL, 12513019344894380777ULL, 2502603868978876155ULL,
- 5005207737957752311ULL, 10010415475915504622ULL, 2002083095183100924ULL,
- 4004166190366201848ULL, 8008332380732403697ULL, 16016664761464807395ULL,
- 3203332952292961479ULL, 6406665904585922958ULL, 12813331809171845916ULL,
- 2562666361834369183ULL, 5125332723668738366ULL, 10250665447337476733ULL,
- 2050133089467495346ULL, 4100266178934990693ULL, 8200532357869981386ULL,
- 16401064715739962772ULL, 3280212943147992554ULL, 6560425886295985109ULL,
- 13120851772591970218ULL, 2624170354518394043ULL, 5248340709036788087ULL,
- 10496681418073576174ULL, 2099336283614715234ULL, 4198672567229430469ULL,
- 8397345134458860939ULL, 16794690268917721879ULL, 3358938053783544375ULL,
- 6717876107567088751ULL, 13435752215134177503ULL, 2687150443026835500ULL,
- 5374300886053671001ULL, 10748601772107342002ULL, 2149720354421468400ULL,
- 4299440708842936801ULL, 8598881417685873602ULL, 17197762835371747204ULL,
- 3439552567074349440ULL, 6879105134148698881ULL, 13758210268297397763ULL,
- 2751642053659479552ULL, 5503284107318959105ULL, 11006568214637918210ULL,
- 2201313642927583642ULL, 4402627285855167284ULL, 8805254571710334568ULL,
- 17610509143420669137ULL, 3522101828684133827ULL, 7044203657368267654ULL,
- 14088407314736535309ULL, 2817681462947307061ULL, 5635362925894614123ULL,
- 11270725851789228247ULL, 2254145170357845649ULL, 4508290340715691299ULL,
- 9016580681431382598ULL, 18033161362862765196ULL, 3606632272572553039ULL,
- 7213264545145106078ULL, 14426529090290212157ULL, 2885305818058042431ULL,
- 5770611636116084862ULL, 11541223272232169725ULL, 2308244654446433945ULL,
- 4616489308892867890ULL, 9232978617785735780ULL, 1846595723557147156ULL,
- 3693191447114294312ULL, 7386382894228588624ULL, 14772765788457177249ULL,
- 2954553157691435449ULL, 5909106315382870899ULL, 11818212630765741799ULL,
- 2363642526153148359ULL, 4727285052306296719ULL, 9454570104612593439ULL,
- 1890914020922518687ULL, 3781828041845037375ULL, 7563656083690074751ULL,
- 15127312167380149503ULL, 3025462433476029900ULL, 6050924866952059801ULL,
- 12101849733904119602ULL, 2420369946780823920ULL, 4840739893561647841ULL,
- 9681479787123295682ULL, 1936295957424659136ULL, 3872591914849318272ULL,
- 7745183829698636545ULL, 15490367659397273091ULL, 3098073531879454618ULL,
- 6196147063758909236ULL, 12392294127517818473ULL, 2478458825503563694ULL,
- 4956917651007127389ULL, 9913835302014254778ULL, 1982767060402850955ULL,
- 3965534120805701911ULL, 7931068241611403822ULL, 15862136483222807645ULL,
- 3172427296644561529ULL, 6344854593289123058ULL, 12689709186578246116ULL,
- 2537941837315649223ULL, 5075883674631298446ULL, 10151767349262596893ULL,
- 2030353469852519378ULL, 4060706939705038757ULL, 8121413879410077514ULL,
- 16242827758820155028ULL, 3248565551764031005ULL, 6497131103528062011ULL,
- 12994262207056124023ULL, 2598852441411224804ULL, 5197704882822449609ULL,
- 10395409765644899218ULL, 2079081953128979843ULL, 4158163906257959687ULL,
- 8316327812515919374ULL, 16632655625031838749ULL, 3326531125006367749ULL,
- 6653062250012735499ULL, 13306124500025470999ULL, 2661224900005094199ULL,
- 5322449800010188399ULL, 10644899600020376799ULL, 2128979920004075359ULL,
- 4257959840008150719ULL, 8515919680016301439ULL, 17031839360032602879ULL,
- 3406367872006520575ULL, 6812735744013041151ULL, 13625471488026082303ULL,
- 2725094297605216460ULL, 5450188595210432921ULL, 10900377190420865842ULL,
- 2180075438084173168ULL, 4360150876168346337ULL, 8720301752336692674ULL,
- 17440603504673385348ULL, 3488120700934677069ULL, 6976241401869354139ULL,
- 13952482803738708279ULL, 2790496560747741655ULL, 5580993121495483311ULL,
- 11161986242990966623ULL, 2232397248598193324ULL, 4464794497196386649ULL,
- 8929588994392773298ULL, 17859177988785546597ULL, 3571835597757109319ULL,
- 7143671195514218638ULL, 14287342391028437277ULL, 2857468478205687455ULL,
- 5714936956411374911ULL, 11429873912822749822ULL, 2285974782564549964ULL,
- 4571949565129099928ULL, 9143899130258199857ULL, 18287798260516399715ULL,
- 3657559652103279943ULL, 7315119304206559886ULL, 14630238608413119772ULL,
- 2926047721682623954ULL, 5852095443365247908ULL, 11704190886730495817ULL,
- 2340838177346099163ULL, 4681676354692198327ULL, 9363352709384396654ULL,
- 1872670541876879330ULL, 3745341083753758661ULL, 7490682167507517323ULL,
- 14981364335015034646ULL, 2996272867003006929ULL, 5992545734006013858ULL,
- 11985091468012027717ULL, 2397018293602405543ULL, 4794036587204811087ULL,
- 9588073174409622174ULL, 1917614634881924434ULL, 3835229269763848869ULL,
- 7670458539527697739ULL, 15340917079055395478ULL, 3068183415811079095ULL,
- 6136366831622158191ULL, 12272733663244316382ULL, 2454546732648863276ULL,
- 4909093465297726553ULL, 9818186930595453106ULL, 1963637386119090621ULL,
- 3927274772238181242ULL, 7854549544476362484ULL, 15709099088952724969ULL,
- 3141819817790544993ULL, 6283639635581089987ULL, 12567279271162179975ULL,
- 2513455854232435995ULL, 5026911708464871990ULL, 10053823416929743980ULL,
- 2010764683385948796ULL, 4021529366771897592ULL, 8043058733543795184ULL,
- 16086117467087590369ULL, 3217223493417518073ULL, 6434446986835036147ULL,
- 12868893973670072295ULL, 2573778794734014459ULL, 5147557589468028918ULL,
- 10295115178936057836ULL, 2059023035787211567ULL, 4118046071574423134ULL,
- 8236092143148846269ULL, 16472184286297692538ULL, 3294436857259538507ULL,
- 6588873714519077015ULL, 13177747429038154030ULL, 2635549485807630806ULL,
- 5271098971615261612ULL, 10542197943230523224ULL, 2108439588646104644ULL,
- 4216879177292209289ULL, 8433758354584418579ULL, 16867516709168837158ULL,
- 3373503341833767431ULL, 6747006683667534863ULL, 13494013367335069727ULL,
- 2698802673467013945ULL, 5397605346934027890ULL, 10795210693868055781ULL,
- 2159042138773611156ULL, 4318084277547222312ULL, 8636168555094444625ULL,
- 17272337110188889250ULL, 3454467422037777850ULL, 6908934844075555700ULL,
- 13817869688151111400ULL, 2763573937630222280ULL, 5527147875260444560ULL,
- 11054295750520889120ULL, 2210859150104177824ULL, 4421718300208355648ULL,
- 8843436600416711296ULL, 17686873200833422592ULL, 3537374640166684518ULL,
- 7074749280333369037ULL, 14149498560666738074ULL, 2829899712133347614ULL,
- 5659799424266695229ULL, 11319598848533390459ULL, 2263919769706678091ULL,
- 4527839539413356183ULL, 9055679078826712367ULL, 18111358157653424735ULL,
- 3622271631530684947ULL, 7244543263061369894ULL, 14489086526122739788ULL,
- 2897817305224547957ULL, 5795634610449095915ULL, 11591269220898191830ULL,
- 2318253844179638366ULL, 4636507688359276732ULL, 9273015376718553464ULL,
- 1854603075343710692ULL, 3709206150687421385ULL, 7418412301374842771ULL,
- 14836824602749685542ULL, 2967364920549937108ULL, 5934729841099874217ULL,
- 11869459682199748434ULL, 2373891936439949686ULL, 4747783872879899373ULL,
- 9495567745759798747ULL, 1899113549151959749ULL, 3798227098303919498ULL,
- 7596454196607838997ULL, 15192908393215677995ULL, 3038581678643135599ULL,
- 6077163357286271198ULL, 12154326714572542396ULL, 2430865342914508479ULL,
- 4861730685829016958ULL, 9723461371658033917ULL, 1944692274331606783ULL,
- 3889384548663213566ULL, 7778769097326427133ULL, 15557538194652854267ULL,
- 3111507638930570853ULL, 6223015277861141707ULL, 12446030555722283414ULL,
- 2489206111144456682ULL, 4978412222288913365ULL, 9956824444577826731ULL,
- 1991364888915565346ULL, 3982729777831130692ULL, 7965459555662261385ULL,
- 15930919111324522770ULL, 3186183822264904554ULL, 6372367644529809108ULL,
- 12744735289059618216ULL, 2548947057811923643ULL, 5097894115623847286ULL,
- 10195788231247694572ULL, 2039157646249538914ULL, 4078315292499077829ULL,
- 8156630584998155658ULL, 16313261169996311316ULL, 3262652233999262263ULL,
- 6525304467998524526ULL, 13050608935997049053ULL, 2610121787199409810ULL,
- 5220243574398819621ULL, 10440487148797639242ULL, 2088097429759527848ULL,
- 4176194859519055697ULL, 8352389719038111394ULL, 16704779438076222788ULL,
- 3340955887615244557ULL, 6681911775230489115ULL, 13363823550460978230ULL,
- 2672764710092195646ULL, 5345529420184391292ULL, 10691058840368782584ULL,
- 2138211768073756516ULL, 4276423536147513033ULL, 8552847072295026067ULL,
- 17105694144590052135ULL, 3421138828918010427ULL, 6842277657836020854ULL,
- 13684555315672041708ULL, 2736911063134408341ULL, 5473822126268816683ULL,
- 10947644252537633366ULL, 2189528850507526673ULL, 4379057701015053346ULL,
- 8758115402030106693ULL, 17516230804060213386ULL, 3503246160812042677ULL,
- 7006492321624085354ULL, 14012984643248170709ULL, 2802596928649634141ULL,
- 5605193857299268283ULL, 11210387714598536567ULL, 2242077542919707313ULL,
- 4484155085839414626ULL, 8968310171678829253ULL, 17936620343357658507ULL,
- 3587324068671531701ULL, 7174648137343063403ULL, 14349296274686126806ULL,
- 2869859254937225361ULL, 5739718509874450722ULL, 11479437019748901445ULL,
- 2295887403949780289ULL, 4591774807899560578ULL, 9183549615799121156ULL,
- 18367099231598242312ULL, 3673419846319648462ULL, 7346839692639296924ULL,
- 14693679385278593849ULL, 2938735877055718769ULL, 5877471754111437539ULL,
- 11754943508222875079ULL, 2350988701644575015ULL, 4701977403289150031ULL,
- 9403954806578300063ULL, 1880790961315660012ULL, 3761581922631320025ULL,
- 7523163845262640050ULL, 15046327690525280101ULL, 3009265538105056020ULL,
- 6018531076210112040ULL, 12037062152420224081ULL, 2407412430484044816ULL,
- 4814824860968089632ULL, 9629649721936179265ULL, 1925929944387235853ULL,
- 3851859888774471706ULL, 7703719777548943412ULL, 15407439555097886824ULL,
- 3081487911019577364ULL, 6162975822039154729ULL, 12325951644078309459ULL,
- 2465190328815661891ULL, 4930380657631323783ULL, 9860761315262647567ULL,
- 1972152263052529513ULL, 3944304526105059027ULL, 7888609052210118054ULL,
- 15777218104420236108ULL, 3155443620884047221ULL, 6310887241768094443ULL,
- 12621774483536188886ULL, 2524354896707237777ULL, 5048709793414475554ULL,
- 10097419586828951109ULL, 2019483917365790221ULL, 4038967834731580443ULL,
- 8077935669463160887ULL, 16155871338926321774ULL, 3231174267785264354ULL,
- 6462348535570528709ULL, 12924697071141057419ULL, 2584939414228211483ULL,
- 5169878828456422967ULL, 10339757656912845935ULL, 2067951531382569187ULL,
- 4135903062765138374ULL, 8271806125530276748ULL, 16543612251060553497ULL,
- 3308722450212110699ULL, 6617444900424221398ULL, 13234889800848442797ULL,
- 2646977960169688559ULL, 5293955920339377119ULL, 10587911840678754238ULL,
- 2117582368135750847ULL, 4235164736271501695ULL, 8470329472543003390ULL,
- 16940658945086006781ULL, 3388131789017201356ULL, 6776263578034402712ULL,
- 13552527156068805425ULL, 2710505431213761085ULL, 5421010862427522170ULL,
- 10842021724855044340ULL, 2168404344971008868ULL, 4336808689942017736ULL,
- 8673617379884035472ULL, 17347234759768070944ULL, 3469446951953614188ULL,
- 6938893903907228377ULL, 13877787807814456755ULL, 2775557561562891351ULL,
- 5551115123125782702ULL, 11102230246251565404ULL, 2220446049250313080ULL,
- 4440892098500626161ULL, 8881784197001252323ULL, 17763568394002504646ULL,
- 3552713678800500929ULL, 7105427357601001858ULL, 14210854715202003717ULL,
- 2842170943040400743ULL, 5684341886080801486ULL, 11368683772161602973ULL,
- 2273736754432320594ULL, 4547473508864641189ULL, 9094947017729282379ULL,
- 18189894035458564758ULL, 3637978807091712951ULL, 7275957614183425903ULL,
- 14551915228366851806ULL, 2910383045673370361ULL, 5820766091346740722ULL,
- 11641532182693481445ULL, 2328306436538696289ULL, 4656612873077392578ULL,
- 9313225746154785156ULL, 1862645149230957031ULL, 3725290298461914062ULL,
- 7450580596923828125ULL, 14901161193847656250ULL, 2980232238769531250ULL,
- 5960464477539062500ULL, 11920928955078125000ULL, 2384185791015625000ULL,
- 4768371582031250000ULL, 9536743164062500000ULL, 1907348632812500000ULL,
- 3814697265625000000ULL, 7629394531250000000ULL, 15258789062500000000ULL,
- 3051757812500000000ULL, 6103515625000000000ULL, 12207031250000000000ULL,
- 2441406250000000000ULL, 4882812500000000000ULL, 9765625000000000000ULL,
- 1953125000000000000ULL, 3906250000000000000ULL, 7812500000000000000ULL,
- 15625000000000000000ULL, 3125000000000000000ULL, 6250000000000000000ULL,
- 12500000000000000000ULL, 2500000000000000000ULL, 5000000000000000000ULL,
- 10000000000000000000ULL, 2000000000000000000ULL, 4000000000000000000ULL,
- 8000000000000000000ULL, 16000000000000000000ULL, 3200000000000000000ULL,
- 6400000000000000000ULL, 12800000000000000000ULL, 2560000000000000000ULL,
- 5120000000000000000ULL, 10240000000000000000ULL, 2048000000000000000ULL,
- 4096000000000000000ULL, 8192000000000000000ULL, 16384000000000000000ULL,
- 3276800000000000000ULL, 6553600000000000000ULL, 13107200000000000000ULL,
- 2621440000000000000ULL, 5242880000000000000ULL, 10485760000000000000ULL,
- 2097152000000000000ULL, 4194304000000000000ULL, 8388608000000000000ULL,
- 16777216000000000000ULL, 3355443200000000000ULL, 6710886400000000000ULL,
- 13421772800000000000ULL, 2684354560000000000ULL, 5368709120000000000ULL,
- 10737418240000000000ULL, 2147483648000000000ULL, 4294967296000000000ULL,
- 8589934592000000000ULL, 17179869184000000000ULL, 3435973836800000000ULL,
- 6871947673600000000ULL, 13743895347200000000ULL, 2748779069440000000ULL,
- 5497558138880000000ULL, 10995116277760000000ULL, 2199023255552000000ULL,
- 4398046511104000000ULL, 8796093022208000000ULL, 17592186044416000000ULL,
- 3518437208883200000ULL, 7036874417766400000ULL, 14073748835532800000ULL,
- 2814749767106560000ULL, 5629499534213120000ULL, 11258999068426240000ULL,
- 2251799813685248000ULL, 4503599627370496000ULL, 9007199254740992000ULL,
- 18014398509481984000ULL, 3602879701896396800ULL, 7205759403792793600ULL,
- 14411518807585587200ULL, 2882303761517117440ULL, 5764607523034234880ULL,
- 11529215046068469760ULL, 2305843009213693952ULL, 4611686018427387904ULL,
- 9223372036854775808ULL, 1844674407370955161ULL, 3689348814741910323ULL,
- 7378697629483820646ULL, 14757395258967641292ULL, 2951479051793528258ULL,
- 5902958103587056517ULL, 11805916207174113034ULL, 2361183241434822606ULL,
- 4722366482869645213ULL, 9444732965739290427ULL, 1888946593147858085ULL,
- 3777893186295716170ULL, 7555786372591432341ULL, 15111572745182864683ULL,
- 3022314549036572936ULL, 6044629098073145873ULL, 12089258196146291747ULL,
- 2417851639229258349ULL, 4835703278458516698ULL, 9671406556917033397ULL,
- 1934281311383406679ULL, 3868562622766813359ULL, 7737125245533626718ULL,
- 15474250491067253436ULL, 3094850098213450687ULL, 6189700196426901374ULL,
- 12379400392853802748ULL, 2475880078570760549ULL, 4951760157141521099ULL,
- 9903520314283042199ULL, 1980704062856608439ULL, 3961408125713216879ULL,
- 7922816251426433759ULL, 15845632502852867518ULL, 3169126500570573503ULL,
- 6338253001141147007ULL, 12676506002282294014ULL, 2535301200456458802ULL,
- 5070602400912917605ULL, 10141204801825835211ULL, 2028240960365167042ULL,
- 4056481920730334084ULL, 8112963841460668169ULL, 16225927682921336339ULL,
- 3245185536584267267ULL, 6490371073168534535ULL, 12980742146337069071ULL,
- 2596148429267413814ULL, 5192296858534827628ULL, 10384593717069655257ULL,
- 2076918743413931051ULL, 4153837486827862102ULL, 8307674973655724205ULL,
- 16615349947311448411ULL, 3323069989462289682ULL, 6646139978924579364ULL,
- 13292279957849158729ULL, 2658455991569831745ULL, 5316911983139663491ULL,
- 10633823966279326983ULL, 2126764793255865396ULL, 4253529586511730793ULL,
- 8507059173023461586ULL, 17014118346046923173ULL, 3402823669209384634ULL,
- 6805647338418769269ULL, 13611294676837538538ULL, 2722258935367507707ULL,
- 5444517870735015415ULL, 10889035741470030830ULL, 2177807148294006166ULL,
- 4355614296588012332ULL, 8711228593176024664ULL, 17422457186352049329ULL,
- 3484491437270409865ULL, 6968982874540819731ULL, 13937965749081639463ULL,
- 2787593149816327892ULL, 5575186299632655785ULL, 11150372599265311570ULL,
- 2230074519853062314ULL, 4460149039706124628ULL, 8920298079412249256ULL,
- 17840596158824498513ULL, 3568119231764899702ULL, 7136238463529799405ULL,
- 14272476927059598810ULL, 2854495385411919762ULL, 5708990770823839524ULL,
- 11417981541647679048ULL, 2283596308329535809ULL, 4567192616659071619ULL,
- 9134385233318143238ULL, 18268770466636286477ULL, 3653754093327257295ULL,
- 7307508186654514591ULL, 14615016373309029182ULL, 2923003274661805836ULL,
- 5846006549323611672ULL, 11692013098647223345ULL, 2338402619729444669ULL,
- 4676805239458889338ULL, 9353610478917778676ULL, 1870722095783555735ULL,
- 3741444191567111470ULL, 7482888383134222941ULL, 14965776766268445882ULL,
- 2993155353253689176ULL, 5986310706507378352ULL, 11972621413014756705ULL,
- 2394524282602951341ULL, 4789048565205902682ULL, 9578097130411805364ULL,
- 1915619426082361072ULL, 3831238852164722145ULL, 7662477704329444291ULL,
- 15324955408658888583ULL, 3064991081731777716ULL, 6129982163463555433ULL,
- 12259964326927110866ULL, 2451992865385422173ULL, 4903985730770844346ULL,
- 9807971461541688693ULL, 1961594292308337738ULL, 3923188584616675477ULL,
- 7846377169233350954ULL, 15692754338466701909ULL, 3138550867693340381ULL,
- 6277101735386680763ULL, 12554203470773361527ULL, 2510840694154672305ULL,
- 5021681388309344611ULL, 10043362776618689222ULL, 2008672555323737844ULL,
- 4017345110647475688ULL, 8034690221294951377ULL, 16069380442589902755ULL,
- 3213876088517980551ULL, 6427752177035961102ULL, 12855504354071922204ULL,
- 2571100870814384440ULL, 5142201741628768881ULL, 10284403483257537763ULL,
- 2056880696651507552ULL, 4113761393303015105ULL, 8227522786606030210ULL,
- 16455045573212060421ULL, 3291009114642412084ULL, 6582018229284824168ULL,
- 13164036458569648337ULL, 2632807291713929667ULL, 5265614583427859334ULL,
- 10531229166855718669ULL, 2106245833371143733ULL, 4212491666742287467ULL,
- 8424983333484574935ULL, 16849966666969149871ULL, 3369993333393829974ULL,
- 6739986666787659948ULL, 13479973333575319897ULL, 2695994666715063979ULL,
- 5391989333430127958ULL, 10783978666860255917ULL, 2156795733372051183ULL,
- 4313591466744102367ULL, 8627182933488204734ULL, 17254365866976409468ULL,
- 3450873173395281893ULL, 6901746346790563787ULL, 13803492693581127574ULL,
- 2760698538716225514ULL, 5521397077432451029ULL, 11042794154864902059ULL,
- 2208558830972980411ULL, 4417117661945960823ULL, 8834235323891921647ULL,
- 17668470647783843295ULL, 3533694129556768659ULL, 7067388259113537318ULL,
- 14134776518227074636ULL, 2826955303645414927ULL, 5653910607290829854ULL,
- 11307821214581659709ULL, 2261564242916331941ULL, 4523128485832663883ULL,
- 9046256971665327767ULL, 18092513943330655534ULL, 3618502788666131106ULL,
- 7237005577332262213ULL, 14474011154664524427ULL, 2894802230932904885ULL,
- 5789604461865809771ULL, 11579208923731619542ULL, 2315841784746323908ULL,
- 4631683569492647816ULL, 9263367138985295633ULL, 1852673427797059126ULL,
- 3705346855594118253ULL, 7410693711188236507ULL, 14821387422376473014ULL,
- 2964277484475294602ULL, 5928554968950589205ULL, 11857109937901178411ULL,
- 2371421987580235682ULL, 4742843975160471364ULL, 9485687950320942729ULL,
- 1897137590064188545ULL, 3794275180128377091ULL, 7588550360256754183ULL,
- 15177100720513508366ULL, 3035420144102701673ULL, 6070840288205403346ULL,
- 12141680576410806693ULL, 2428336115282161338ULL, 4856672230564322677ULL,
- 9713344461128645354ULL, 1942668892225729070ULL, 3885337784451458141ULL,
- 7770675568902916283ULL, 15541351137805832567ULL, 3108270227561166513ULL,
- 6216540455122333026ULL, 12433080910244666053ULL, 2486616182048933210ULL,
- 4973232364097866421ULL, 9946464728195732843ULL, 1989292945639146568ULL,
- 3978585891278293137ULL, 7957171782556586274ULL, 15914343565113172548ULL,
- 3182868713022634509ULL, 6365737426045269019ULL, 12731474852090538039ULL,
- 2546294970418107607ULL, 5092589940836215215ULL, 10185179881672430431ULL,
- 2037035976334486086ULL, 4074071952668972172ULL, 8148143905337944345ULL,
- 16296287810675888690ULL, 3259257562135177738ULL, 6518515124270355476ULL,
- 13037030248540710952ULL, 2607406049708142190ULL, 5214812099416284380ULL,
- 10429624198832568761ULL, 2085924839766513752ULL, 4171849679533027504ULL,
- 8343699359066055009ULL, 16687398718132110018ULL, 3337479743626422003ULL,
- 6674959487252844007ULL, 13349918974505688014ULL, 2669983794901137602ULL,
- 5339967589802275205ULL, 10679935179604550411ULL, 2135987035920910082ULL,
- 4271974071841820164ULL, 8543948143683640329ULL, 17087896287367280659ULL,
- 3417579257473456131ULL, 6835158514946912263ULL, 13670317029893824527ULL,
- 2734063405978764905ULL, 5468126811957529810ULL, 10936253623915059621ULL,
- 2187250724783011924ULL, 4374501449566023848ULL, 8749002899132047697ULL,
- 17498005798264095394ULL, 3499601159652819078ULL, 6999202319305638157ULL,
- 13998404638611276315ULL, 2799680927722255263ULL, 5599361855444510526ULL,
- 11198723710889021052ULL, 2239744742177804210ULL, 4479489484355608421ULL,
- 8958978968711216842ULL, 17917957937422433684ULL, 3583591587484486736ULL,
- 7167183174968973473ULL, 14334366349937946947ULL, 2866873269987589389ULL,
- 5733746539975178779ULL, 11467493079950357558ULL, 2293498615990071511ULL,
- 4586997231980143023ULL, 9173994463960286046ULL, 18347988927920572092ULL,
- 3669597785584114418ULL, 7339195571168228837ULL, 14678391142336457674ULL,
- 2935678228467291534ULL, 5871356456934583069ULL, 11742712913869166139ULL,
- 2348542582773833227ULL, 4697085165547666455ULL, 9394170331095332911ULL,
- 1878834066219066582ULL, 3757668132438133164ULL, 7515336264876266329ULL,
- 15030672529752532658ULL, 3006134505950506531ULL, 6012269011901013063ULL,
- 12024538023802026126ULL, 2404907604760405225ULL, 4809815209520810450ULL,
- 9619630419041620901ULL, 1923926083808324180ULL, 3847852167616648360ULL,
- 7695704335233296721ULL, 15391408670466593442ULL, 3078281734093318688ULL,
- 6156563468186637376ULL, 12313126936373274753ULL, 2462625387274654950ULL,
- 4925250774549309901ULL, 9850501549098619803ULL, 1970100309819723960ULL,
- 3940200619639447921ULL, 7880401239278895842ULL, 15760802478557791684ULL,
- 3152160495711558336ULL, 6304320991423116673ULL, 12608641982846233347ULL,
- 2521728396569246669ULL, 5043456793138493339ULL, 10086913586276986678ULL,
- 2017382717255397335ULL, 4034765434510794671ULL, 8069530869021589342ULL,
- 16139061738043178685ULL, 3227812347608635737ULL, 6455624695217271474ULL,
- 12911249390434542948ULL, 2582249878086908589ULL, 5164499756173817179ULL,
- 10328999512347634358ULL, 2065799902469526871ULL, 4131599804939053743ULL,
- 8263199609878107486ULL, 16526399219756214973ULL, 3305279843951242994ULL,
- 6610559687902485989ULL, 13221119375804971979ULL, 2644223875160994395ULL,
- 5288447750321988791ULL, 10576895500643977583ULL, 2115379100128795516ULL,
- 4230758200257591033ULL, 8461516400515182066ULL, 16923032801030364133ULL,
- 3384606560206072826ULL, 6769213120412145653ULL, 13538426240824291306ULL,
- 2707685248164858261ULL, 5415370496329716522ULL, 10830740992659433045ULL,
- 2166148198531886609ULL, 4332296397063773218ULL, 8664592794127546436ULL,
- 17329185588255092872ULL, 3465837117651018574ULL, 6931674235302037148ULL,
- 13863348470604074297ULL, 2772669694120814859ULL, 5545339388241629719ULL,
- 11090678776483259438ULL, 2218135755296651887ULL, 4436271510593303775ULL,
- 8872543021186607550ULL, 17745086042373215101ULL, 3549017208474643020ULL,
- 7098034416949286040ULL, 14196068833898572081ULL, 2839213766779714416ULL,
- 5678427533559428832ULL, 11356855067118857664ULL, 2271371013423771532ULL,
- 4542742026847543065ULL, 9085484053695086131ULL, 18170968107390172263ULL,
- 3634193621478034452ULL, 7268387242956068905ULL, 14536774485912137810ULL,
- 2907354897182427562ULL, 5814709794364855124ULL, 11629419588729710248ULL,
- 2325883917745942049ULL, 4651767835491884099ULL, 9303535670983768199ULL,
- 1860707134196753639ULL, 3721414268393507279ULL, 7442828536787014559ULL,
- 14885657073574029118ULL, 2977131414714805823ULL, 5954262829429611647ULL,
- 11908525658859223294ULL, 2381705131771844658ULL, 4763410263543689317ULL,
- 9526820527087378635ULL, 1905364105417475727ULL, 3810728210834951454ULL,
- 7621456421669902908ULL, 15242912843339805817ULL, 3048582568667961163ULL,
- 6097165137335922326ULL, 12194330274671844653ULL, 2438866054934368930ULL,
- 4877732109868737861ULL, 9755464219737475723ULL, 1951092843947495144ULL,
- 3902185687894990289ULL, 7804371375789980578ULL, 15608742751579961156ULL,
- 3121748550315992231ULL, 6243497100631984462ULL, 12486994201263968925ULL,
- 2497398840252793785ULL, 4994797680505587570ULL, 9989595361011175140ULL,
- 1997919072202235028ULL, 3995838144404470056ULL, 7991676288808940112ULL,
- 15983352577617880224ULL, 3196670515523576044ULL, 6393341031047152089ULL,
- 12786682062094304179ULL, 2557336412418860835ULL, 5114672824837721671ULL,
- 10229345649675443343ULL, 2045869129935088668ULL, 4091738259870177337ULL,
- 8183476519740354675ULL, 16366953039480709350ULL, 3273390607896141870ULL,
- 6546781215792283740ULL, 13093562431584567480ULL, 2618712486316913496ULL,
- 5237424972633826992ULL, 10474849945267653984ULL, 2094969989053530796ULL,
- 4189939978107061593ULL, 8379879956214123187ULL, 16759759912428246374ULL,
- 3351951982485649274ULL, 6703903964971298549ULL, 13407807929942597099ULL,
- 2681561585988519419ULL, 5363123171977038839ULL, 10726246343954077679ULL,
- 2145249268790815535ULL, 4290498537581631071ULL, 8580997075163262143ULL,
- 17161994150326524287ULL, 3432398830065304857ULL, 6864797660130609714ULL,
- 13729595320261219429ULL, 2745919064052243885ULL, 5491838128104487771ULL,
- 10983676256208975543ULL, 2196735251241795108ULL, 4393470502483590217ULL,
- 8786941004967180435ULL, 17573882009934360870ULL, 3514776401986872174ULL,
- 7029552803973744348ULL, 14059105607947488696ULL, 2811821121589497739ULL,
- 5623642243178995478ULL, 11247284486357990957ULL, 2249456897271598191ULL,
- 4498913794543196382ULL, 8997827589086392765ULL, 17995655178172785531ULL,
- 3599131035634557106ULL, 7198262071269114212ULL, 14396524142538228424ULL,
- 2879304828507645684ULL, 5758609657015291369ULL, 11517219314030582739ULL,
- 2303443862806116547ULL, 4606887725612233095ULL, 9213775451224466191ULL,
- 18427550902448932383ULL, 3685510180489786476ULL, 7371020360979572953ULL,
- 14742040721959145907ULL, 2948408144391829181ULL, 5896816288783658362ULL,
- 11793632577567316725ULL, 2358726515513463345ULL, 4717453031026926690ULL,
- 9434906062053853380ULL, 1886981212410770676ULL, 3773962424821541352ULL,
- 7547924849643082704ULL, 15095849699286165408ULL, 3019169939857233081ULL,
- 6038339879714466163ULL, 12076679759428932327ULL, 2415335951885786465ULL,
- 4830671903771572930ULL, 9661343807543145861ULL, 1932268761508629172ULL,
- 3864537523017258344ULL, 7729075046034516689ULL, 15458150092069033378ULL,
- 3091630018413806675ULL, 6183260036827613351ULL, 12366520073655226703ULL,
- 2473304014731045340ULL, 4946608029462090681ULL, 9893216058924181362ULL,
- 1978643211784836272ULL, 3957286423569672544ULL, 7914572847139345089ULL,
- 15829145694278690179ULL, 3165829138855738035ULL, 6331658277711476071ULL,
- 12663316555422952143ULL, 2532663311084590428ULL, 5065326622169180857ULL,
- 10130653244338361715ULL, 2026130648867672343ULL, 4052261297735344686ULL,
- 8104522595470689372ULL, 16209045190941378744ULL, 3241809038188275748ULL,
- 6483618076376551497ULL, 12967236152753102995ULL, 2593447230550620599ULL,
- 5186894461101241198ULL, 10373788922202482396ULL, 2074757784440496479ULL,
- 4149515568880992958ULL, 8299031137761985917ULL, 16598062275523971834ULL,
- 3319612455104794366ULL, 6639224910209588733ULL, 13278449820419177467ULL,
- 2655689964083835493ULL, 5311379928167670986ULL, 10622759856335341973ULL,
- 2124551971267068394ULL, 4249103942534136789ULL, 8498207885068273579ULL,
- 16996415770136547158ULL, 3399283154027309431ULL, 6798566308054618863ULL,
- 13597132616109237726ULL, 2719426523221847545ULL, 5438853046443695090ULL,
- 10877706092887390181ULL, 2175541218577478036ULL, 4351082437154956072ULL,
- 8702164874309912144ULL, 17404329748619824289ULL, 3480865949723964857ULL,
- 6961731899447929715ULL, 13923463798895859431ULL, 2784692759779171886ULL,
- 5569385519558343772ULL, 11138771039116687545ULL, 2227754207823337509ULL,
- 4455508415646675018ULL, 8911016831293350036ULL, 17822033662586700072ULL,
- 3564406732517340014ULL, 7128813465034680029ULL, 14257626930069360058ULL,
- 2851525386013872011ULL, 5703050772027744023ULL, 11406101544055488046ULL,
- 2281220308811097609ULL, 4562440617622195218ULL, 9124881235244390437ULL,
- 18249762470488780874ULL, 3649952494097756174ULL, 7299904988195512349ULL,
- 14599809976391024699ULL, 2919961995278204939ULL, 5839923990556409879ULL,
- 11679847981112819759ULL, 2335969596222563951ULL, 4671939192445127903ULL,
- 9343878384890255807ULL, 1868775676978051161ULL, 3737551353956102323ULL,
- 7475102707912204646ULL, 14950205415824409292ULL, 2990041083164881858ULL,
- 5980082166329763716ULL, 11960164332659527433ULL, 2392032866531905486ULL,
- 4784065733063810973ULL, 9568131466127621947ULL, 1913626293225524389ULL,
- 3827252586451048778ULL, 7654505172902097557ULL, 15309010345804195115ULL,
- 3061802069160839023ULL, 6123604138321678046ULL, 12247208276643356092ULL,
- 2449441655328671218ULL, 4898883310657342436ULL, 9797766621314684873ULL,
- 1959553324262936974ULL, 3919106648525873949ULL, 7838213297051747899ULL,
- 15676426594103495798ULL, 3135285318820699159ULL, 6270570637641398319ULL,
- 12541141275282796638ULL, 2508228255056559327ULL, 5016456510113118655ULL,
- 10032913020226237310ULL, 2006582604045247462ULL, 4013165208090494924ULL,
- 8026330416180989848ULL, 16052660832361979697ULL, 3210532166472395939ULL,
- 6421064332944791878ULL, 12842128665889583757ULL, 2568425733177916751ULL,
- 5136851466355833503ULL, 10273702932711667006ULL, 2054740586542333401ULL,
- 4109481173084666802ULL, 8218962346169333605ULL, 16437924692338667210ULL,
- 3287584938467733442ULL, 6575169876935466884ULL, 13150339753870933768ULL,
- 2630067950774186753ULL, 5260135901548373507ULL, 10520271803096747014ULL,
- 2104054360619349402ULL, 4208108721238698805ULL, 8416217442477397611ULL,
- 16832434884954795223ULL, 3366486976990959044ULL, 6732973953981918089ULL,
- 13465947907963836178ULL, 2693189581592767235ULL, 5386379163185534471ULL,
- 10772758326371068942ULL, 2154551665274213788ULL, 4309103330548427577ULL,
- 8618206661096855154ULL, 17236413322193710308ULL, 3447282664438742061ULL,
- 6894565328877484123ULL, 13789130657754968246ULL, 2757826131550993649ULL,
- 5515652263101987298ULL, 11031304526203974597ULL, 2206260905240794919ULL,
- 4412521810481589838ULL, 8825043620963179677ULL, 17650087241926359355ULL,
- 3530017448385271871ULL, 7060034896770543742ULL, 14120069793541087484ULL,
- 2824013958708217496ULL, 5648027917416434993ULL, 11296055834832869987ULL,
- 2259211166966573997ULL, 4518422333933147995ULL, 9036844667866295990ULL,
- 18073689335732591980ULL, 3614737867146518396ULL, 7229475734293036792ULL,
- 14458951468586073584ULL, 2891790293717214716ULL, 5783580587434429433ULL,
- 11567161174868858867ULL, 2313432234973771773ULL, 4626864469947543547ULL,
- 9253728939895087094ULL, 1850745787979017418ULL, 3701491575958034837ULL,
- 7402983151916069675ULL, 14805966303832139350ULL, 2961193260766427870ULL,
- 5922386521532855740ULL, 11844773043065711480ULL, 2368954608613142296ULL,
- 4737909217226284592ULL, 9475818434452569184ULL, 1895163686890513836ULL,
- 3790327373781027673ULL, 7580654747562055347ULL, 15161309495124110694ULL,
- 3032261899024822138ULL, 6064523798049644277ULL, 12129047596099288555ULL,
- 2425809519219857711ULL, 4851619038439715422ULL, 9703238076879430844ULL,
- 1940647615375886168ULL, 3881295230751772337ULL, 7762590461503544675ULL,
- 15525180923007089351ULL, 3105036184601417870ULL, 6210072369202835740ULL,
- 12420144738405671481ULL, 2484028947681134296ULL, 4968057895362268592ULL,
- 9936115790724537184ULL, 1987223158144907436ULL, 3974446316289814873ULL,
- 7948892632579629747ULL, 15897785265159259495ULL, 3179557053031851899ULL,
- 6359114106063703798ULL, 12718228212127407596ULL, 2543645642425481519ULL,
- 5087291284850963038ULL, 10174582569701926077ULL, 2034916513940385215ULL,
- 4069833027880770430ULL, 8139666055761540861ULL, 16279332111523081723ULL,
- 3255866422304616344ULL, 6511732844609232689ULL, 13023465689218465379ULL,
- 2604693137843693075ULL, 5209386275687386151ULL, 10418772551374772303ULL,
- 2083754510274954460ULL, 4167509020549908921ULL, 8335018041099817842ULL,
- 16670036082199635685ULL, 3334007216439927137ULL, 6668014432879854274ULL,
- 13336028865759708548ULL, 2667205773151941709ULL, 5334411546303883419ULL,
- 10668823092607766838ULL, 2133764618521553367ULL, 4267529237043106735ULL,
- 8535058474086213470ULL, 17070116948172426941ULL, 3414023389634485388ULL,
- 6828046779268970776ULL, 13656093558537941553ULL, 2731218711707588310ULL,
- 5462437423415176621ULL, 10924874846830353242ULL, 2184974969366070648ULL,
- 4369949938732141297ULL, 8739899877464282594ULL, 17479799754928565188ULL,
- 3495959950985713037ULL, 6991919901971426075ULL, 13983839803942852150ULL,
- 2796767960788570430ULL, 5593535921577140860ULL, 11187071843154281720ULL,
- 2237414368630856344ULL, 4474828737261712688ULL, 8949657474523425376ULL,
- 17899314949046850752ULL, 3579862989809370150ULL, 7159725979618740301ULL,
- 14319451959237480602ULL, 2863890391847496120ULL, 5727780783694992240ULL,
- 11455561567389984481ULL, 2291112313477996896ULL, 4582224626955993792ULL,
- 9164449253911987585ULL, 18328898507823975170ULL, 3665779701564795034ULL,
- 7331559403129590068ULL, 14663118806259180136ULL, 2932623761251836027ULL,
- 5865247522503672054ULL, 11730495045007344109ULL, 2346099009001468821ULL,
- 4692198018002937643ULL, 9384396036005875287ULL, 1876879207201175057ULL,
- 3753758414402350114ULL, 7507516828804700229ULL, 15015033657609400459ULL,
- 3003006731521880091ULL, 6006013463043760183ULL, 12012026926087520367ULL,
- 2402405385217504073ULL, 4804810770435008147ULL, 9609621540870016294ULL,
- 1921924308174003258ULL, 3843848616348006517ULL, 7687697232696013035ULL,
- 15375394465392026070ULL, 3075078893078405214ULL, 6150157786156810428ULL,
- 12300315572313620856ULL, 2460063114462724171ULL, 4920126228925448342ULL,
- 9840252457850896685ULL, 1968050491570179337ULL, 3936100983140358674ULL,
- 7872201966280717348ULL, 15744403932561434696ULL, 3148880786512286939ULL,
- 6297761573024573878ULL, 12595523146049147757ULL, 2519104629209829551ULL,
- 5038209258419659102ULL, 10076418516839318205ULL, 2015283703367863641ULL,
- 4030567406735727282ULL, 8061134813471454564ULL, 16122269626942909129ULL,
- 3224453925388581825ULL, 6448907850777163651ULL, 12897815701554327303ULL,
- 2579563140310865460ULL, 5159126280621730921ULL, 10318252561243461842ULL,
- 2063650512248692368ULL, 4127301024497384737ULL, 8254602048994769474ULL,
- 16509204097989538948ULL, 3301840819597907789ULL, 6603681639195815579ULL,
- 13207363278391631158ULL, 2641472655678326231ULL, 5282945311356652463ULL,
- 10565890622713304927ULL, 2113178124542660985ULL, 4226356249085321970ULL,
- 8452712498170643941ULL, 16905424996341287883ULL, 3381084999268257576ULL,
- 6762169998536515153ULL, 13524339997073030306ULL, 2704867999414606061ULL,
- 5409735998829212122ULL, 10819471997658424245ULL, 2163894399531684849ULL,
- 4327788799063369698ULL, 8655577598126739396ULL, 17311155196253478792ULL,
- 3462231039250695758ULL, 6924462078501391516ULL, 13848924157002783033ULL,
- 2769784831400556606ULL, 5539569662801113213ULL, 11079139325602226427ULL,
- 2215827865120445285ULL, 4431655730240890570ULL, 8863311460481781141ULL,
- 17726622920963562283ULL, 3545324584192712456ULL, 7090649168385424913ULL,
- 14181298336770849826ULL, 2836259667354169965ULL, 5672519334708339930ULL,
- 11345038669416679861ULL, 2269007733883335972ULL, 4538015467766671944ULL,
- 9076030935533343889ULL, 18152061871066687778ULL, 3630412374213337555ULL,
- 7260824748426675111ULL, 14521649496853350222ULL, 2904329899370670044ULL,
- 5808659798741340089ULL, 11617319597482680178ULL, 2323463919496536035ULL,
- 4646927838993072071ULL, 9293855677986144142ULL, 1858771135597228828ULL,
- 3717542271194457656ULL, 7435084542388915313ULL, 14870169084777830627ULL,
- 2974033816955566125ULL, 5948067633911132251ULL, 11896135267822264502ULL,
- 2379227053564452900ULL, 4758454107128905800ULL, 9516908214257811601ULL,
- 1903381642851562320ULL, 3806763285703124640ULL, 7613526571406249281ULL,
- 15227053142812498563ULL, 3045410628562499712ULL, 6090821257124999425ULL,
- 12181642514249998850ULL, 2436328502849999770ULL, 4872657005699999540ULL,
- 9745314011399999080ULL, 1949062802279999816ULL, 3898125604559999632ULL,
- 7796251209119999264ULL, 15592502418239998528ULL, 3118500483647999705ULL,
- 6237000967295999411ULL, 12474001934591998822ULL, 2494800386918399764ULL,
- 4989600773836799529ULL, 9979201547673599058ULL, 1995840309534719811ULL,
- 3991680619069439623ULL, 7983361238138879246ULL, 15966722476277758493ULL,
- 3193344495255551698ULL, 6386688990511103397ULL, 12773377981022206794ULL,
- 2554675596204441358ULL, 5109351192408882717ULL, 10218702384817765435ULL,
- 2043740476963553087ULL, 4087480953927106174ULL, 8174961907854212348ULL,
- 16349923815708424697ULL, 3269984763141684939ULL, 6539969526283369878ULL,
- 13079939052566739757ULL, 2615987810513347951ULL, 5231975621026695903ULL,
- 10463951242053391806ULL, 2092790248410678361ULL, 4185580496821356722ULL,
- 8371160993642713444ULL, 16742321987285426889ULL, 3348464397457085377ULL,
- 6696928794914170755ULL, 13393857589828341511ULL, 2678771517965668302ULL,
- 5357543035931336604ULL, 10715086071862673209ULL, 2143017214372534641ULL,
- 4286034428745069283ULL, 8572068857490138567ULL, 17144137714980277135ULL,
- 3428827542996055427ULL, 6857655085992110854ULL, 13715310171984221708ULL,
- 2743062034396844341ULL, 5486124068793688683ULL, 10972248137587377366ULL,
- 2194449627517475473ULL, 4388899255034950946ULL, 8777798510069901893ULL,
- 17555597020139803786ULL, 3511119404027960757ULL, 7022238808055921514ULL,
- 14044477616111843029ULL, 2808895523222368605ULL, 5617791046444737211ULL,
- 11235582092889474423ULL, 2247116418577894884ULL, 4494232837155789769ULL,
- 8988465674311579538ULL, 17976931348623159077ULL, 3595386269724631815ULL,
- 7190772539449263630ULL, 14381545078898527261ULL, 2876309015779705452ULL,
- 5752618031559410904ULL, 11505236063118821809ULL, 2301047212623764361ULL,
- 4602094425247528723ULL, 9204188850495057447ULL, 18408377700990114895ULL,
- 3681675540198022979ULL, 7363351080396045958ULL,
-};
-
-static const gint32 Formatter_TensExponentTable [] = {
- -323, -323, -323, -322, -322, -322, -321, -321, -321, -320, -320, -320,
- -319, -319, -319, -319, -318, -318, -318, -317, -317, -317, -316, -316,
- -316, -316, -315, -315, -315, -314, -314, -314, -313, -313, -313, -313,
- -312, -312, -312, -311, -311, -311, -310, -310, -310, -310, -309, -309,
- -309, -308, -308, -308, -307, -307, -307, -307, -306, -306, -306, -305,
- -305, -305, -304, -304, -304, -304, -303, -303, -303, -302, -302, -302,
- -301, -301, -301, -301, -300, -300, -300, -299, -299, -299, -298, -298,
- -298, -298, -297, -297, -297, -296, -296, -296, -295, -295, -295, -295,
- -294, -294, -294, -293, -293, -293, -292, -292, -292, -291, -291, -291,
- -291, -290, -290, -290, -289, -289, -289, -288, -288, -288, -288, -287,
- -287, -287, -286, -286, -286, -285, -285, -285, -285, -284, -284, -284,
- -283, -283, -283, -282, -282, -282, -282, -281, -281, -281, -280, -280,
- -280, -279, -279, -279, -279, -278, -278, -278, -277, -277, -277, -276,
- -276, -276, -276, -275, -275, -275, -274, -274, -274, -273, -273, -273,
- -273, -272, -272, -272, -271, -271, -271, -270, -270, -270, -270, -269,
- -269, -269, -268, -268, -268, -267, -267, -267, -267, -266, -266, -266,
- -265, -265, -265, -264, -264, -264, -264, -263, -263, -263, -262, -262,
- -262, -261, -261, -261, -260, -260, -260, -260, -259, -259, -259, -258,
- -258, -258, -257, -257, -257, -257, -256, -256, -256, -255, -255, -255,
- -254, -254, -254, -254, -253, -253, -253, -252, -252, -252, -251, -251,
- -251, -251, -250, -250, -250, -249, -249, -249, -248, -248, -248, -248,
- -247, -247, -247, -246, -246, -246, -245, -245, -245, -245, -244, -244,
- -244, -243, -243, -243, -242, -242, -242, -242, -241, -241, -241, -240,
- -240, -240, -239, -239, -239, -239, -238, -238, -238, -237, -237, -237,
- -236, -236, -236, -236, -235, -235, -235, -234, -234, -234, -233, -233,
- -233, -232, -232, -232, -232, -231, -231, -231, -230, -230, -230, -229,
- -229, -229, -229, -228, -228, -228, -227, -227, -227, -226, -226, -226,
- -226, -225, -225, -225, -224, -224, -224, -223, -223, -223, -223, -222,
- -222, -222, -221, -221, -221, -220, -220, -220, -220, -219, -219, -219,
- -218, -218, -218, -217, -217, -217, -217, -216, -216, -216, -215, -215,
- -215, -214, -214, -214, -214, -213, -213, -213, -212, -212, -212, -211,
- -211, -211, -211, -210, -210, -210, -209, -209, -209, -208, -208, -208,
- -208, -207, -207, -207, -206, -206, -206, -205, -205, -205, -205, -204,
- -204, -204, -203, -203, -203, -202, -202, -202, -201, -201, -201, -201,
- -200, -200, -200, -199, -199, -199, -198, -198, -198, -198, -197, -197,
- -197, -196, -196, -196, -195, -195, -195, -195, -194, -194, -194, -193,
- -193, -193, -192, -192, -192, -192, -191, -191, -191, -190, -190, -190,
- -189, -189, -189, -189, -188, -188, -188, -187, -187, -187, -186, -186,
- -186, -186, -185, -185, -185, -184, -184, -184, -183, -183, -183, -183,
- -182, -182, -182, -181, -181, -181, -180, -180, -180, -180, -179, -179,
- -179, -178, -178, -178, -177, -177, -177, -177, -176, -176, -176, -175,
- -175, -175, -174, -174, -174, -173, -173, -173, -173, -172, -172, -172,
- -171, -171, -171, -170, -170, -170, -170, -169, -169, -169, -168, -168,
- -168, -167, -167, -167, -167, -166, -166, -166, -165, -165, -165, -164,
- -164, -164, -164, -163, -163, -163, -162, -162, -162, -161, -161, -161,
- -161, -160, -160, -160, -159, -159, -159, -158, -158, -158, -158, -157,
- -157, -157, -156, -156, -156, -155, -155, -155, -155, -154, -154, -154,
- -153, -153, -153, -152, -152, -152, -152, -151, -151, -151, -150, -150,
- -150, -149, -149, -149, -149, -148, -148, -148, -147, -147, -147, -146,
- -146, -146, -145, -145, -145, -145, -144, -144, -144, -143, -143, -143,
- -142, -142, -142, -142, -141, -141, -141, -140, -140, -140, -139, -139,
- -139, -139, -138, -138, -138, -137, -137, -137, -136, -136, -136, -136,
- -135, -135, -135, -134, -134, -134, -133, -133, -133, -133, -132, -132,
- -132, -131, -131, -131, -130, -130, -130, -130, -129, -129, -129, -128,
- -128, -128, -127, -127, -127, -127, -126, -126, -126, -125, -125, -125,
- -124, -124, -124, -124, -123, -123, -123, -122, -122, -122, -121, -121,
- -121, -121, -120, -120, -120, -119, -119, -119, -118, -118, -118, -118,
- -117, -117, -117, -116, -116, -116, -115, -115, -115, -114, -114, -114,
- -114, -113, -113, -113, -112, -112, -112, -111, -111, -111, -111, -110,
- -110, -110, -109, -109, -109, -108, -108, -108, -108, -107, -107, -107,
- -106, -106, -106, -105, -105, -105, -105, -104, -104, -104, -103, -103,
- -103, -102, -102, -102, -102, -101, -101, -101, -100, -100, -100, -99,
- -99, -99, -99, -98, -98, -98, -97, -97, -97, -96, -96, -96,
- -96, -95, -95, -95, -94, -94, -94, -93, -93, -93, -93, -92,
- -92, -92, -91, -91, -91, -90, -90, -90, -90, -89, -89, -89,
- -88, -88, -88, -87, -87, -87, -86, -86, -86, -86, -85, -85,
- -85, -84, -84, -84, -83, -83, -83, -83, -82, -82, -82, -81,
- -81, -81, -80, -80, -80, -80, -79, -79, -79, -78, -78, -78,
- -77, -77, -77, -77, -76, -76, -76, -75, -75, -75, -74, -74,
- -74, -74, -73, -73, -73, -72, -72, -72, -71, -71, -71, -71,
- -70, -70, -70, -69, -69, -69, -68, -68, -68, -68, -67, -67,
- -67, -66, -66, -66, -65, -65, -65, -65, -64, -64, -64, -63,
- -63, -63, -62, -62, -62, -62, -61, -61, -61, -60, -60, -60,
- -59, -59, -59, -59, -58, -58, -58, -57, -57, -57, -56, -56,
- -56, -55, -55, -55, -55, -54, -54, -54, -53, -53, -53, -52,
- -52, -52, -52, -51, -51, -51, -50, -50, -50, -49, -49, -49,
- -49, -48, -48, -48, -47, -47, -47, -46, -46, -46, -46, -45,
- -45, -45, -44, -44, -44, -43, -43, -43, -43, -42, -42, -42,
- -41, -41, -41, -40, -40, -40, -40, -39, -39, -39, -38, -38,
- -38, -37, -37, -37, -37, -36, -36, -36, -35, -35, -35, -34,
- -34, -34, -34, -33, -33, -33, -32, -32, -32, -31, -31, -31,
- -31, -30, -30, -30, -29, -29, -29, -28, -28, -28, -27, -27,
- -27, -27, -26, -26, -26, -25, -25, -25, -24, -24, -24, -24,
- -23, -23, -23, -22, -22, -22, -21, -21, -21, -21, -20, -20,
- -20, -19, -19, -19, -18, -18, -18, -18, -17, -17, -17, -16,
- -16, -16, -15, -15, -15, -15, -14, -14, -14, -13, -13, -13,
- -12, -12, -12, -12, -11, -11, -11, -10, -10, -10, -9, -9,
- -9, -9, -8, -8, -8, -7, -7, -7, -6, -6, -6, -6,
- -5, -5, -5, -4, -4, -4, -3, -3, -3, -3, -2, -2,
- -2, -1, -1, -1, 0, 0, 0, 1, 1, 1, 1, 2,
- 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5,
- 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 9, 9,
- 9, 10, 10, 10, 10, 11, 11, 11, 12, 12, 12, 13,
- 13, 13, 13, 14, 14, 14, 15, 15, 15, 16, 16, 16,
- 16, 17, 17, 17, 18, 18, 18, 19, 19, 19, 19, 20,
- 20, 20, 21, 21, 21, 22, 22, 22, 22, 23, 23, 23,
- 24, 24, 24, 25, 25, 25, 25, 26, 26, 26, 27, 27,
- 27, 28, 28, 28, 28, 29, 29, 29, 30, 30, 30, 31,
- 31, 31, 32, 32, 32, 32, 33, 33, 33, 34, 34, 34,
- 35, 35, 35, 35, 36, 36, 36, 37, 37, 37, 38, 38,
- 38, 38, 39, 39, 39, 40, 40, 40, 41, 41, 41, 41,
- 42, 42, 42, 43, 43, 43, 44, 44, 44, 44, 45, 45,
- 45, 46, 46, 46, 47, 47, 47, 47, 48, 48, 48, 49,
- 49, 49, 50, 50, 50, 50, 51, 51, 51, 52, 52, 52,
- 53, 53, 53, 53, 54, 54, 54, 55, 55, 55, 56, 56,
- 56, 56, 57, 57, 57, 58, 58, 58, 59, 59, 59, 60,
- 60, 60, 60, 61, 61, 61, 62, 62, 62, 63, 63, 63,
- 63, 64, 64, 64, 65, 65, 65, 66, 66, 66, 66, 67,
- 67, 67, 68, 68, 68, 69, 69, 69, 69, 70, 70, 70,
- 71, 71, 71, 72, 72, 72, 72, 73, 73, 73, 74, 74,
- 74, 75, 75, 75, 75, 76, 76, 76, 77, 77, 77, 78,
- 78, 78, 78, 79, 79, 79, 80, 80, 80, 81, 81, 81,
- 81, 82, 82, 82, 83, 83, 83, 84, 84, 84, 84, 85,
- 85, 85, 86, 86, 86, 87, 87, 87, 87, 88, 88, 88,
- 89, 89, 89, 90, 90, 90, 91, 91, 91, 91, 92, 92,
- 92, 93, 93, 93, 94, 94, 94, 94, 95, 95, 95, 96,
- 96, 96, 97, 97, 97, 97, 98, 98, 98, 99, 99, 99,
- 100, 100, 100, 100, 101, 101, 101, 102, 102, 102, 103, 103,
- 103, 103, 104, 104, 104, 105, 105, 105, 106, 106, 106, 106,
- 107, 107, 107, 108, 108, 108, 109, 109, 109, 109, 110, 110,
- 110, 111, 111, 111, 112, 112, 112, 112, 113, 113, 113, 114,
- 114, 114, 115, 115, 115, 115, 116, 116, 116, 117, 117, 117,
- 118, 118, 118, 119, 119, 119, 119, 120, 120, 120, 121, 121,
- 121, 122, 122, 122, 122, 123, 123, 123, 124, 124, 124, 125,
- 125, 125, 125, 126, 126, 126, 127, 127, 127, 128, 128, 128,
- 128, 129, 129, 129, 130, 130, 130, 131, 131, 131, 131, 132,
- 132, 132, 133, 133, 133, 134, 134, 134, 134, 135, 135, 135,
- 136, 136, 136, 137, 137, 137, 137, 138, 138, 138, 139, 139,
- 139, 140, 140, 140, 140, 141, 141, 141, 142, 142, 142, 143,
- 143, 143, 143, 144, 144, 144, 145, 145, 145, 146, 146, 146,
- 146, 147, 147, 147, 148, 148, 148, 149, 149, 149, 150, 150,
- 150, 150, 151, 151, 151, 152, 152, 152, 153, 153, 153, 153,
- 154, 154, 154, 155, 155, 155, 156, 156, 156, 156, 157, 157,
- 157, 158, 158, 158, 159, 159, 159, 159, 160, 160, 160, 161,
- 161, 161, 162, 162, 162, 162, 163, 163, 163, 164, 164, 164,
- 165, 165, 165, 165, 166, 166, 166, 167, 167, 167, 168, 168,
- 168, 168, 169, 169, 169, 170, 170, 170, 171, 171, 171, 171,
- 172, 172, 172, 173, 173, 173, 174, 174, 174, 174, 175, 175,
- 175, 176, 176, 176, 177, 177, 177, 178, 178, 178, 178, 179,
- 179, 179, 180, 180, 180, 181, 181, 181, 181, 182, 182, 182,
- 183, 183, 183, 184, 184, 184, 184, 185, 185, 185, 186, 186,
- 186, 187, 187, 187, 187, 188, 188, 188, 189, 189, 189, 190,
- 190, 190, 190, 191, 191, 191, 192, 192, 192, 193, 193, 193,
- 193, 194, 194, 194, 195, 195, 195, 196, 196, 196, 196, 197,
- 197, 197, 198, 198, 198, 199, 199, 199, 199, 200, 200, 200,
- 201, 201, 201, 202, 202, 202, 202, 203, 203, 203, 204, 204,
- 204, 205, 205, 205, 206, 206, 206, 206, 207, 207, 207, 208,
- 208, 208, 209, 209, 209, 209, 210, 210, 210, 211, 211, 211,
- 212, 212, 212, 212, 213, 213, 213, 214, 214, 214, 215, 215,
- 215, 215, 216, 216, 216, 217, 217, 217, 218, 218, 218, 218,
- 219, 219, 219, 220, 220, 220, 221, 221, 221, 221, 222, 222,
- 222, 223, 223, 223, 224, 224, 224, 224, 225, 225, 225, 226,
- 226, 226, 227, 227, 227, 227, 228, 228, 228, 229, 229, 229,
- 230, 230, 230, 230, 231, 231, 231, 232, 232, 232, 233, 233,
- 233, 233, 234, 234, 234, 235, 235, 235, 236, 236, 236, 237,
- 237, 237, 237, 238, 238, 238, 239, 239, 239, 240, 240, 240,
- 240, 241, 241, 241, 242, 242, 242, 243, 243, 243, 243, 244,
- 244, 244, 245, 245, 245, 246, 246, 246, 246, 247, 247, 247,
- 248, 248, 248, 249, 249, 249, 249, 250, 250, 250, 251, 251,
- 251, 252, 252, 252, 252, 253, 253, 253, 254, 254, 254, 255,
- 255, 255, 255, 256, 256, 256, 257, 257, 257, 258, 258, 258,
- 258, 259, 259, 259, 260, 260, 260, 261, 261, 261, 261, 262,
- 262, 262, 263, 263, 263, 264, 264, 264, 265, 265, 265, 265,
- 266, 266, 266, 267, 267, 267, 268, 268, 268, 268, 269, 269,
- 269, 270, 270, 270, 271, 271, 271, 271, 272, 272, 272, 273,
- 273, 273, 274, 274, 274, 274, 275, 275, 275, 276, 276, 276,
- 277, 277, 277, 277, 278, 278, 278, 279, 279, 279, 280, 280,
- 280, 280, 281, 281, 281, 282, 282, 282, 283, 283, 283, 283,
- 284, 284, 284, 285, 285, 285, 286, 286, 286, 286, 287, 287,
- 287, 288, 288, 288, 289, 289, 289, 289, 290, 290, 290, 291,
- 291, 291, 292, 292, 292, 292, 293, 293,
-};
-
-static const gunichar2 Formatter_DigitLowerTable [] = {
- '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
-};
-
-static const gunichar2 Formatter_DigitUpperTable [] = {
- '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
-};
-
-static gint64 Formatter_TenPowersList [] = {
- 1LL,
- 10LL,
- 100LL,
- 1000LL,
- 10000LL,
- 100000LL,
- 1000000LL,
- 10000000LL,
- 100000000LL,
- 1000000000LL,
- 10000000000LL,
- 100000000000LL,
- 1000000000000LL,
- 10000000000000LL,
- 100000000000000LL,
- 1000000000000000LL,
- 10000000000000000LL,
- 100000000000000000LL,
- 1000000000000000000LL,
-};
-
-// DecHexDigits s a translation table from a decimal number to its
-// digits hexadecimal representation (e.g. DecHexDigits [34] = 0x34).
-static gint32 Formatter_DecHexDigits [] = {
- 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09,
- 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19,
- 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29,
- 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39,
- 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49,
- 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59,
- 0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69,
- 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79,
- 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89,
- 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99,
-};
-
-#endif
diff --git a/vmkit/lib/N3/PNetLib/LICENSE.TXT b/vmkit/lib/N3/PNetLib/LICENSE.TXT
deleted file mode 100644
index 0cfe1a9..0000000
--- a/vmkit/lib/N3/PNetLib/LICENSE.TXT
+++ /dev/null
@@ -1,22 +0,0 @@
---------------------------------------------------------------------------------
-VMKit PNetLib runtime
---------------------------------------------------------------------------------
-All files are licensed under the VMKit license with the following additions:
-
-vmkit/lib/N3/PNetLib/PNetLib.cpp
-
- Copyright (C) 2001, 2002, 2003 Southern Storm Software, Pty Ltd.
-
- This program is free software; you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
- the Free Software Foundation; either version 2 of the License, or
- (at your option) any later version.
-
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU General Public License for more details.
-
- You should have received a copy of the GNU General Public License
- along with this program; if not, write to the Free Software
- Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
diff --git a/vmkit/lib/N3/PNetLib/Makefile b/vmkit/lib/N3/PNetLib/Makefile
deleted file mode 100644
index a79f67b..0000000
--- a/vmkit/lib/N3/PNetLib/Makefile
+++ /dev/null
@@ -1,21 +0,0 @@
-##===- lib/N3/PNetLib/Makefile -----------------------------*- Makefile -*-===##
-#
-# The vmkit project
-#
-# This file is distributed under the University of Illinois Open Source
-# License. See LICENSE.TXT for details.
-#
-##===----------------------------------------------------------------------===##
-LEVEL = ../../..
-
-include $(LEVEL)/Makefile.config
-
-ifeq ($(WITH_LLVM_GCC), 1)
- MODULE_NAME = PNetLib
-else
- LIBRARYNAME = PNetLib
-endif
-
-EXTRA_DIST = PNetPath.inc.in
-include $(LEVEL)/Makefile.common
-CXX.Flags += -I$(PROJ_SRC_DIR)/../VMCore
diff --git a/vmkit/lib/N3/PNetLib/PNetLib.cpp b/vmkit/lib/N3/PNetLib/PNetLib.cpp
deleted file mode 100644
index d0ccf07..0000000
--- a/vmkit/lib/N3/PNetLib/PNetLib.cpp
+++ /dev/null
@@ -1,1123 +0,0 @@
-//===--------------- PNetLib.cpp - PNetLib interface ----------------------===//
-//
-// N3
-//
-// This file is distributed under the University of Illinois Open Source
-// License with the following additions:
-//
-// Copyright (C) 2001, 2002, 2003 Southern Storm Software, Pty Ltd.
-//
-// This program is free software; you can redistribute it and/or modify
-// it under the terms of the GNU General Public License as published by
-// the Free Software Foundation; either version 2 of the License, or
-// (at your option) any later version.
-//
-// This program is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU General Public License
-// along with this program; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-//
-// See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#include <math.h>
-
-#include <dlfcn.h>
-#include <stdio.h>
-
-#include "mvm/JIT.h"
-
-#include "Assembly.h"
-#include "CLIAccess.h"
-#include "CLIJit.h"
-#include "PNetString.h"
-#include "NativeUtil.h"
-#include "MSCorlib.h"
-#include "N3.h"
-#include "PNetLib.h"
-#include "Reader.h"
-#include "VMArray.h"
-#include "VMClass.h"
-#include "VMObject.h"
-#include "VMThread.h"
-#include "CLIString.h"
-
-#include "PNetPath.inc"
-
-#include "llvm/LLVMContext.h"
-
-using namespace n3;
-
-#define IL_CONSOLE_NORMAL 0
-
-
-#define MEMBER_TYPES_CONSTRUCTOR 0x1
-#define MEMBER_TYPES_EVENT 0x2
-#define MEMBER_TYPES_FIELD 0x4
-#define MEMBER_TYPES_METHOD 0x8
-#define MEMBER_TYPES_PROPERTY 0x10
-#define MEMBER_TYPES_TYPEINFO 0x20
-#define MEMBER_TYPES_CUSTOM 0x40
-#define MEMBER_TYPES_NESTEDTYPE 0x80
-#define MEMBER_TYPES_ALL 0xBF
-
-#define METHOD_SEMANTIC_ATTRIBUTES_SETTER 0x1
-#define METHOD_SEMANTIC_ATTRIBUTES_GETTER 0x2
-#define METHOD_SEMANTIC_ATTRIBUTES_OTHER 0x4
-#define METHOD_SEMANTIC_ATTRIBUTES_ADDON 0x8
-#define METHOD_SEMANTIC_ATTRIBUTES_REMOVEON 0x10
-#define METHOD_SEMANTIC_ATTRIBUTES_FIRE 0x20
-
-
-extern "C" {
-extern uint32 ILGetCodePage(void);
-extern uint32 ILGetCultureID(void);
-extern char* ILGetCultureName(void);
-extern sint32 ILAnsiGetMaxByteCount(sint32);
-extern sint32 ILConsoleWriteChar(sint32);
-extern uint32 ILConsoleGetMode(void);
-extern sint32 ILAnsiGetBytes(uint16*, sint32, uint8*, sint32);
-extern void _IL_Stdio_StdFlush(void*, sint32);
-extern char ILGetUnicodeCategory(sint32);
-extern sint64 _IL_TimeMethods_GetCurrentTime(void*);
-extern uint32 ILUnicodeStringToLower(void*, void*, uint32);
-extern sint32 ILUnicodeStringCompareIgnoreCase(void*, void*, sint32);
-extern sint32 ILUnicodeStringCompareNoIgnoreCase(void*, void*, sint32);
-
-#include "mvm/Config/config.h"
-// PNET wants this
-void *GC_run_thread(void *(*thread_func)(void *), void *arg){ return 0; }
-#if not(USE_GC_BOEHM)
-int GC_invoke_finalizers (void) { return 0; }
-int GC_should_invoke_finalizers (void) { return 0; }
-void GC_register_finalizer_no_order(void*, void (*)(void*, void*), void*, void (**)(void*, void*), void**) { return; }
-void GC_gcollect(void) {}
-void* GC_malloc_uncollectable(size_t) { return 0; }
-void GC_exclude_static_roots(void*, void*) {}
-void GC_free(void*) {}
-void GC_malloc_explicitly_typed(void) {}
-size_t GC_get_heap_size(void) {return 0;}
-int GC_register_disappearing_link(void**) { return 0; }
-int GC_general_register_disappearing_link(void**, void*) { return 0; }
-int GC_pthread_sigmask(int, const sigset_t*, sigset_t*) { return 0; }
-int GC_pthread_detach(pthread_t) { return 0; }
-int GC_pthread_create(pthread_t*, const pthread_attr_t*, void* (*)(void*), void*) { return 0; }
-void* GC_malloc(size_t) { return 0; }
-void GC_make_descriptor(void) {}
-int GC_unregister_disappearing_link(void**) { return 0; }
-void (*GC_finalizer_notifier)(void);
-int GC_java_finalization;
-int GC_finalize_on_demand;
-void GC_set_max_heap_size(size_t) {}
-void* GC_malloc_atomic(size_t) { return 0; }
-#endif
-
-// Fake termcap symbols
-void tigetstr(void) {
- abort();
-}
-void tgetstr(void) {
- abort();
-}
-void setupterm(void) {
- abort();
-}
-void tigetnum(void) {
- abort();
-}
-void tgetnum(void) {
- abort();
-}
-void tigetflag(void) {
- abort();
-}
-void tparm(void) {
- abort();
-}
-void tgetent(void) {
- abort();
-}
-void tputs(void) {
- abort();
-}
-void tgoto(void) {
- abort();
-}
-void tgetflag(void) {
- abort();
-}
-}
-
-
-
-extern "C" uint32 System_Text_DefaultEncoding_InternalCodePage() {
- return ILGetCodePage();
-}
-
-extern "C" uint32 System_Globalization_CultureInfo_InternalCultureID() {
- return ILGetCultureID();
-}
-
-extern "C" VMObject* System_Globalization_CultureInfo_InternalCultureName() {
- char* val = ILGetCultureName();
- N3* vm = (N3*)(VMThread::get()->getVM());
- declare_gcroot(ArrayChar*, array) = 0;
-
- if (val) {
- array = vm->asciizToArray(val);
- free(val);
- } else {
- array = vm->asciizToArray("iv");
- }
- declare_gcroot(VMObject*, res) = vm->arrayToString(array);
- return res;
-}
-
-static const ArrayChar* newBuilder(N3* vm, PNetString* value, uint32 length) {
- llvm_gcroot(value, 0);
- uint32 valueLength = value ? value->length : 0;
- declare_gcroot(const ArrayChar*, array) = value ? value->value : 0;
- uint32 roundLength = (7 + length) & 0xfffffff8;
- uint16* buf = (uint16*)alloca(roundLength * sizeof(uint16));
- uint32 strLength = 0;
-
- if (value != 0) {
- if (valueLength <= roundLength) {
- memcpy(buf, array->elements, valueLength * sizeof(uint16));
- strLength = valueLength;
- } else {
- memcpy(buf, array->elements, roundLength * sizeof(uint16));
- strLength = roundLength;
- }
- }
-
- declare_gcroot(ArrayChar*, array_res) = vm->bufToArray(buf, strLength);
- return array_res;
-}
-
-extern "C" VMObject* System_String_NewBuilder(PNetString* value,
- uint32 length) {
- llvm_gcroot(value, 0);
- N3* vm = (N3*)(VMThread::get()->getVM());
- declare_gcroot(PNetString*, str) = (PNetString*)vm->arrayToString(newBuilder(vm, value, length));
- return str;
-}
-
-extern "C" VMObject* Platform_SysCharInfo_GetNewLine() {
- N3* vm = (N3*)(VMThread::get()->getVM());
- declare_gcroot(ArrayChar*, array) = vm->asciizToArray("\n");
- declare_gcroot(VMObject*, res) = vm->arrayToString(array);
- return res;
-}
-
-extern "C" void System_String_CopyToChecked(PNetString* str, sint32 sstart,
- ArrayChar* dest, sint32 dstart,
- sint32 count) {
- llvm_gcroot(str, 0);
- llvm_gcroot(dest, 0);
- declare_gcroot(const ArrayChar*, value) = str->value;
- memcpy(&dest->elements[dstart], &value->elements[sstart], count << 1);
-}
-
-extern "C" sint32 System_Text_DefaultEncoding_InternalGetMaxByteCount(sint32 val) {
- return ILAnsiGetMaxByteCount(val);
-}
-
-extern "C" void Platform_Stdio_StdWrite(sint32 fd, ArrayUInt8* value,
- sint32 index, sint32 count) {
- llvm_gcroot(value, 0);
- if (fd == 1) {
- if (ILConsoleGetMode() == IL_CONSOLE_NORMAL) {
- fwrite(&value->elements[index], 1, count, stdout);
- } else {
- char* buf = (char*)(&value->elements[index]);
- while (count > 0) {
- ILConsoleWriteChar(*buf);
- ++buf;
- --count;
- }
- fflush(stdout);
- }
- } else {
- fwrite(&value->elements[index], 1, count, stderr);
- }
-}
-
-extern "C" sint32 System_Text_DefaultEncoding_InternalGetBytes(ArrayChar* chars,
- sint32 charIndex, sint32 charCount, ArrayUInt8* bytes, sint32 byteIndex) {
- llvm_gcroot(chars, 0);
- llvm_gcroot(bytes, 0);
- return ILAnsiGetBytes(&chars->elements[charIndex], charCount, &bytes->elements[byteIndex], bytes->size - byteIndex);
-}
-
-extern "C" void Platform_Stdio_StdFlush(sint32 fd) {
- _IL_Stdio_StdFlush(0, fd);
-}
-
-extern "C" VMObject* System_Reflection_ClrType_GetElementType(VMObject* Klass) {
- llvm_gcroot(Klass, 0);
- VMCommonClass* cl = (VMCommonClass*)MSCorlib::typeClrType->getIntPtr(Klass);
- if (!cl->isArray) {
- VMThread::get()->getVM()->error("implement me");
- return 0;
- } else {
- declare_gcroot(VMObject *, delegatee) = ((VMClassArray*)cl)->baseClass->getClassDelegatee();
- return delegatee;
- }
-}
-
-extern "C" PNetString* System_String_NewString(uint32 size) {
- declare_gcroot(PNetString*, str) = (PNetString*)MSCorlib::pString->doNew();
- str->length = size;
- return str;
-}
-
-extern "C" void System_String_Copy_3(PNetString* dest, sint32 pos,
- PNetString* src) {
- llvm_gcroot(dest, 0);
- llvm_gcroot(src, 0);
- declare_gcroot(ArrayChar*, arr) = (ArrayChar*)MSCorlib::arrayChar->doNew(pos + src->value->size);
-
- for (sint32 i = 0; i < pos; ++i) {
- arr->elements[i] = dest->value->elements[i];
- }
-
- for (sint32 i = 0; i < src->length; ++i) {
- arr->elements[pos + i] = src->value->elements[i];
- }
-
- dest->value = arr;
- dest->length = dest->value->size;
-}
-
-extern "C" void System_String_Copy_5(PNetString* dest, sint32 destPos,
- PNetString* src, sint32 srcPos,
- sint32 length) {
- llvm_gcroot(dest, 0);
- llvm_gcroot(src, 0);
- declare_gcroot(const ArrayChar*, arraySrc) = src->value;
-
- // printf("Copy %p %p %d %d %d (%p %d)\n", (void *)dest, (void *)src, destPos, srcPos, length, (void *)dest->value, dest->length);
-
- if(destPos == 0 && srcPos == 0 && length == src->length) {
- dest->value = arraySrc;
- dest->length = length;
- } else {
- sint32 top = destPos + length;
- uint16 *buf = (uint16*)alloca((top < dest->length ? dest->length : top) * sizeof(uint16));
-
- if(destPos)
- memcpy(buf, dest->value->elements, destPos * sizeof(uint16));
-
- memcpy(buf + destPos, src->value->elements + srcPos, length * sizeof(uint16));
-
- if(top <= dest->length)
- memcpy(buf + top, dest->value->elements + top, (dest->length - top) * sizeof(uint16));
- else
- dest->length = top;
-
- declare_gcroot(ArrayChar*, array) = VMThread::get()->getVM()->bufToArray(buf, dest->length);
- dest->value = array;
- }
- // printf("---> %s\n", mvm::PrintBuffer(VMThread::get()->getVM()->arrayToUTF8(dest->value)).cString());
-}
-
-extern "C" void System_Threading_Monitor_Enter(VMObject* obj) {
- llvm_gcroot(obj, 0);
- // obj->aquire();
-}
-
-extern "C" void System_Threading_Monitor_Exit(VMObject* obj) {
- llvm_gcroot(obj, 0);
- // obj->unlock();
-}
-
-
-extern "C" bool System_String_Equals(PNetString* str1, PNetString* str2) {
- llvm_gcroot(str1, 0);
- llvm_gcroot(str2, 0);
- declare_gcroot(const ArrayChar*, a1) = str1->value;
- declare_gcroot(const ArrayChar*, a2) = str2->value;
- return a1 == a2;
-}
-
-extern "C" sint32 Platform_SysCharInfo_GetUnicodeCategory(char c) {
- return ILGetUnicodeCategory(c);
-}
-
-extern "C" uint16 System_String_GetChar(PNetString* str, sint32 index) {
- llvm_gcroot(str, 0);
- return str->value->elements[index];
-}
-
-extern "C" sint32 System_String_IndexOf(PNetString* str, uint16 value,
- sint32 startIndex, sint32 count) {
- llvm_gcroot(str, 0);
- if (startIndex < 0) {
- VMThread::get()->getVM()->error("shoud throw arg range");
- }
-
- if ((count < 0) || (str->length - startIndex < count)) {
- VMThread::get()->getVM()->error("shoud throw arg range");
- }
-
- sint32 i = startIndex;
- declare_gcroot(const ArrayChar*, array) = str->value;
- while (i < startIndex + count) {
- if (array->elements[i] == value) return i;
- else ++i;
- }
-
- return -1;
-}
-
-extern "C" sint32 System_String_GetHashCode(PNetString* str) {
- llvm_gcroot(str, 0);
- sint32 hash = 0;
- declare_gcroot(const ArrayChar*, array) = str->value;
- for (sint32 i = 0; i < array->size; ++i) {
- hash += ((hash << 5) + array->elements[i]);
- }
- return hash;
-}
-
-extern "C" VMObject* System_Text_StringBuilder_Insert_System_Text_StringBuilder_System_Int32_System_Char(
- StringBuilder* obj,
- sint32 index,
- uint16 value) {
- llvm_gcroot(obj, 0);
- N3* vm = (N3*)(VMThread::get()->getVM());
- declare_gcroot(PNetString*, buildString) = obj->buildString;
- declare_gcroot(const ArrayChar*, array) = buildString->value;
- sint32 strLength = buildString->length;
- sint32 length = (index + 1) > strLength ? index + 1 : strLength + 1;
- uint16* buf = (uint16*)alloca(length * sizeof(uint16));
-
- if (index != 0) {
- memcpy(buf, array->elements, index * sizeof(uint16));
- }
-
- if (strLength > index) {
- memcpy(&(buf[index + 1]), &(array->elements[index]),
- (strLength - index) * sizeof(uint16));
- }
-
- buf[index] = value;
- declare_gcroot(ArrayChar*, array_res) = vm->bufToArray(buf, length);
- declare_gcroot(PNetString*, str) = (PNetString*)vm->arrayToString(array_res);
- obj->buildString = str;
-
- return obj;
-}
-
-extern "C" VMObject* System_Text_StringBuilder_Insert_System_Text_StringBuilder_System_Int32_System_String(
- StringBuilder* obj,
- sint32 index,
- PNetString* str) {
- llvm_gcroot(obj, 0);
- llvm_gcroot(str, 0);
- N3* vm = (N3*)(VMThread::get()->getVM());
- declare_gcroot(PNetString*, buildString) = obj->buildString;
- declare_gcroot(const ArrayChar*, strArray) = str->value;
- declare_gcroot(const ArrayChar*, buildArray) = buildString->value;
- sint32 strLength = str->length;
- sint32 buildLength = buildString->length;
- sint32 length = strLength + buildLength;
- uint16* buf = (uint16*)alloca(length * sizeof(uint16));
-
- if (index != 0) {
- memcpy(buf, buildArray->elements, index * sizeof(uint16));
- }
-
- if (strLength != 0) {
- memcpy(&(buf[index]), strArray->elements, strLength * sizeof(uint16));
- }
-
- if (buildLength - index > 0) {
- memcpy(&(buf[strLength + index]), &(buildArray->elements[index]),
- (buildLength - index) * sizeof(uint16));
- }
-
- declare_gcroot(ArrayChar*, array_res) = vm->bufToArray(buf, length);
- declare_gcroot(PNetString*, val) = (PNetString*)vm->arrayToString(array_res);
- obj->buildString = val;
-
- return obj;
-}
-
-extern "C" VMObject* System_Text_StringBuilder_Append_System_Text_StringBuilder_System_Char(
- StringBuilder* obj,
- uint16 value) {
- llvm_gcroot(obj, 0);
- N3* vm = (N3*)(VMThread::get()->getVM());
- declare_gcroot(PNetString*, buildString) = obj->buildString;
- declare_gcroot(const ArrayChar*, array) = buildString->value;
- sint32 length = buildString->length;
- uint16* buf = (uint16*)alloca((length + 1) * sizeof(uint16));
-
- memcpy(buf, array->elements, length * sizeof(uint16));
-
- buf[length] = value;
- declare_gcroot(ArrayChar*, array_res) = vm->bufToArray(buf, length + 1);
- declare_gcroot(PNetString*, val) = (PNetString*)vm->arrayToString(array_res);
- obj->buildString = val;
- return obj;
-}
-
-
-extern "C" VMObject* System_Text_StringBuilder_Append_System_Text_StringBuilder_System_String(
- StringBuilder* obj,
- PNetString* str) {
- llvm_gcroot(obj, 0);
- llvm_gcroot(str, 0);
- N3* vm = (N3*)(VMThread::get()->getVM());
- declare_gcroot(PNetString*, buildString) = obj->buildString;
- declare_gcroot(const ArrayChar*, buildArray) = buildString->value;
- declare_gcroot(const ArrayChar*, strArray) = str->value;
- sint32 buildLength = buildString->length;
- sint32 strLength = str->length;
- sint32 length = buildLength + strLength;
- uint16* buf = (uint16*)alloca(length * sizeof(uint16));
-
- memcpy(buf, buildArray->elements, buildLength * sizeof(uint16));
- memcpy(&(buf[buildLength]), strArray->elements, strLength * sizeof(uint16));
-
- declare_gcroot(ArrayChar*, array_res) = vm->bufToArray(buf, length);
- declare_gcroot(PNetString*, val) = (PNetString*)vm->arrayToString(array_res);
- obj->buildString = val;
- return obj;
-}
-
-extern "C" sint32 System_String_FindInRange(PNetString* obj, sint32 srcFirst,
- sint32 srcLast, sint32 step,
- PNetString* dest) {
- llvm_gcroot(obj, 0);
- llvm_gcroot(dest, 0);
- uint16* buf1 = (uint16*)&(obj->value->elements[srcFirst]);
- uint16* buf2 = (uint16*)(dest->value->elements);
- sint32 destLength = dest->length;
- sint32 size = destLength * sizeof(uint16);
-
- if (step > 0) {
- if (destLength == 1) {
- while (srcFirst <= srcLast) {
- if (buf1[0] == buf2[0]) {
- return srcFirst;
- } else {
- buf1 = &(buf1[1]);
- ++srcFirst;
- }
- }
- } else {
- while (srcFirst <= srcLast) {
- if ((buf1[0] == buf2[0]) && !memcmp(buf1, buf2, size)) {
- return srcFirst;
- } else {
- buf1 = &(buf1[1]);
- ++srcFirst;
- }
- }
- }
- } else {
- if (destLength == 1) {
- while (srcFirst >= srcLast) {
- if (buf1[0] == buf2[0]) {
- return srcFirst;
- } else {
- buf1 = buf1 - 1;
- --srcFirst;
- }
- }
- } else {
- while (srcFirst >= srcLast) {
- if ((buf1[0] == buf2[0]) && !memcmp(buf1, buf2, size)) {
- return srcFirst;
- } else {
- buf1 = buf1 - 1;
- --srcFirst;
- }
- }
- }
- }
- return -1;
-}
-
-extern "C" VMObject* System_Reflection_Assembly_LoadFromName(PNetString* str, sint32 & error, VMObject* parent) {
- llvm_gcroot(str, 0);
- llvm_gcroot(parent, 0);
- N3* vm = (N3*)(VMThread::get()->getVM());
- declare_gcroot(const ArrayChar*, value) = str->value;
- Assembly* ass = vm->constructAssembly(vm->arrayToUTF8(value));
-
- if(!ass->resolve(1, "dll"))
- vm->error("unfound assembly %s\n", mvm::PrintBuffer(value).cString());
-
- error = 0;
- declare_gcroot(VMObject*, delegatee) = ass->getAssemblyDelegatee();
- return delegatee;
-}
-
-extern "C" PNetString* System_String_Concat_2(PNetString* str1, PNetString* str2) {
- llvm_gcroot(str1, 0);
- llvm_gcroot(str2, 0);
- N3* vm = (N3*)(VMThread::get()->getVM());
- declare_gcroot(const ArrayChar*, a1) = str1->value;
- declare_gcroot(const ArrayChar*, a2) = str2->value;
- sint32 len1 = str1->length;
- sint32 len2 = str2->length;
- uint16* buf = (uint16*)alloca((len1 + len2) * sizeof(uint16));
-
- memcpy(buf, a1->elements, len1 * sizeof(uint16));
- memcpy(&(buf[len1]), a2->elements, len2 * sizeof(uint16));
-
- declare_gcroot(ArrayChar*, array_res) = vm->bufToArray(buf, len1 + len2);
- declare_gcroot(PNetString*, val) = (PNetString*)vm->arrayToString(array_res);
-
- return val;
-}
-
-extern "C" PNetString* System_String_Concat_3(PNetString* str1, PNetString* str2, PNetString* str3) {
- llvm_gcroot(str1, 0);
- llvm_gcroot(str2, 0);
- llvm_gcroot(str3, 0);
- N3* vm = (N3*)(VMThread::get()->getVM());
- declare_gcroot(const ArrayChar*, a1) = str1->value;
- declare_gcroot(const ArrayChar*, a2) = str2->value;
- declare_gcroot(const ArrayChar*, a3) = str3->value;
- sint32 len1 = str1->length;
- sint32 len2 = str2->length;
- sint32 len3 = str3->length;
- uint16* buf = (uint16*)alloca((len1 + len2 + len3) * sizeof(uint16));
-
- memcpy(buf, a1->elements, len1 * sizeof(uint16));
- memcpy(&(buf[len1]), a2->elements, len2 * sizeof(uint16));
- memcpy(&(buf[len1 + len2]), a3->elements, len3 * sizeof(uint16));
-
- declare_gcroot(ArrayChar*, array_res) = vm->bufToArray(buf, len1 + len2 + len3);
- declare_gcroot(PNetString*, val) = (PNetString*)vm->arrayToString(array_res);
-
- return val;
-}
-
-extern "C" void System_String_RemoveSpace(PNetString* str, sint32 index, sint32 length) {
- llvm_gcroot(str, 0);
- declare_gcroot(const ArrayChar*, array) = str->value;
- sint32 strLength = str->length;
- uint16* buf = (uint16*)alloca(strLength * sizeof(uint16));
- sint32 j = index;
-
- if (index != 0) {
- memcpy(buf, array->elements, index * sizeof(uint16));
- }
-
- // 32 is space
- for (sint32 i = 0; i < length; ++i) {
- uint16 cur = array->elements[index + i];
- if (cur != 32) {
- buf[j] = cur;
- } else {
- ++j;
- }
- }
-
- if (strLength > (index + length)) {
- memcpy(&(buf[j]), &(array->elements[index + length]), (strLength - (index + length)) * sizeof(uint16));
- }
-
- declare_gcroot(const ArrayChar*, res) = VMThread::get()->getVM()->bufToArray(buf, j);
- str->value = res;
- str->length = j;
-}
-
-extern "C" void System_String__ctor_3(PNetString* str, uint16 ch, sint32 count) {
- llvm_gcroot(str, 0);
- declare_gcroot(ArrayChar*, array) = (ArrayChar*)MSCorlib::arrayChar->doNew(count);
- for (sint32 i = 0; i < count; ++i) {
- array->elements[i] = ch;
- }
-
- str->value = array;
- str->length = array->size;
- str->capacity = array->size;
-}
-
-extern "C" int64_t Platform_TimeMethods_GetCurrentTime() {
- return _IL_TimeMethods_GetCurrentTime(0);
-}
-
-#define ASSEMBLY_VALUE(obj) ((Assembly**)obj)[3]
-
-void* sys_memrchr(const void* s, int c, size_t n) {
- unsigned char* m = (unsigned char*) s + n;
- for (;;) {
- if (!(n--)) return NULL;
- else if (*m-- == (unsigned char)c) return (void*)(m+1);
- }
-}
-
-extern "C" VMObject* System_Reflection_Assembly_GetType(VMObject* obj, PNetString* str, bool onError, bool ignoreCase) {
- llvm_gcroot(obj, 0);
- llvm_gcroot(str, 0);
- Assembly* ass = ASSEMBLY_VALUE(obj);
- declare_gcroot(const ArrayChar*, array) = str->value;
- mvm::PrintBuffer pb(array);
- char* asciiz = pb.cString();
- char* index = (char*)sys_memrchr(asciiz, '.', strlen(asciiz));
- N3* vm = ass->vm;
-
- index[0] = 0;
- ++index;
- VMCommonClass* cl = ass->loadTypeFromName(vm->asciizToUTF8(index), vm->asciizToUTF8(asciiz), true, true, true, onError);
- if (!cl) VMThread::get()->getVM()->error("implement me");
- declare_gcroot(VMObject *, delegatee) = cl->getClassDelegatee();
- return delegatee;
-}
-
-static bool parameterMatch(std::vector<VMCommonClass*> params, ArrayObject* types, bool virt) {
- llvm_gcroot(types, 0);
- uint32 v = virt ? 1 : 0;
- if (types->size + v + 1 != params.size()) return false;
- for (sint32 i = 0; i < types->size; ++i) {
- VMCommonClass* cur = (VMCommonClass*)MSCorlib::typeClrType->getIntPtr(types->elements[i]);
- if (cur != params[i + 1 + v]) return false;
- }
- return true;
-}
-
-extern "C" VMObject* System_Reflection_ClrType_GetMemberImpl(VMObject* Type, PNetString* str, sint32 memberTypes, sint32 bindingFlags, VMObject* binder,
- sint32 callingConventions, ArrayObject* types, VMObject* modifiers) {
- llvm_gcroot(Type, 0);
- llvm_gcroot(str, 0);
- llvm_gcroot(binder, 0);
- llvm_gcroot(types, 0);
- llvm_gcroot(modifiers, 0);
- VMCommonClass* type = (VMCommonClass*)MSCorlib::typeClrType->getIntPtr(Type);
- N3* vm = (N3*)(VMThread::get()->getVM());
- const UTF8* name = vm->arrayToUTF8(str->value);
- if (memberTypes == MEMBER_TYPES_PROPERTY) {
- std::vector<Property*, gc_allocator<Property*> > properties =
- type->properties;
- Property *res = 0;
- for (std::vector<Property*, gc_allocator<Property*> >::iterator i = properties.begin(),
- e = properties.end(); i!= e; ++i) {
- if ((*i)->name == name) {
- res = *i;
- break;
- }
- }
- if (res == 0) VMThread::get()->getVM()->error("implement me");
- declare_gcroot(VMObject*, prop_res) = res->getPropertyDelegatee();
- return prop_res;
- } else if (memberTypes == MEMBER_TYPES_METHOD) {
- std::vector<VMMethod*> virtualMethods = type->virtualMethods;
- std::vector<VMMethod*> staticMethods = type->staticMethods;
-
- for (std::vector<VMMethod*>::iterator i = virtualMethods.begin(),
- e = virtualMethods.end(); i!= e; ++i) {
- VMMethod* meth = *i;
- if (meth->name == name) {
- if (parameterMatch(meth->parameters, types, true)) {
- declare_gcroot(VMObject*, meth_res) = meth->getMethodDelegatee();
- return meth_res;
- }
- }
- }
-
- for (std::vector<VMMethod*>::iterator i = staticMethods.begin(),
- e = staticMethods.end(); i!= e; ++i) {
- VMMethod* meth = *i;
- if (meth->name == name) {
- if (parameterMatch(meth->parameters, types, false)) {
- declare_gcroot(VMObject*, meth_res) = meth->getMethodDelegatee();
- return meth_res;
- }
- }
- }
-
- } else {
- VMThread::get()->getVM()->error("implement me");
- }
- return 0;
-}
-
-extern "C" VMObject* System_Reflection_ClrHelpers_GetSemantics(uintptr_t item, uint32 attributes, bool nonPublic) {
- if (attributes == METHOD_SEMANTIC_ATTRIBUTES_GETTER) {
- Property* prop = (Property*)item;
- mvm::PrintBuffer _asciiz(prop->name);
- const char* asciiz = _asciiz.cString();
- char* buf = (char*)alloca(strlen(asciiz) + 5);
- sprintf(buf, "get_%s", asciiz);
- N3* vm = VMThread::get()->getVM();
- VMMethod* meth = prop->type->lookupMethod(vm->asciizToUTF8(buf), prop->parameters, true, false);
- assert(meth);
- declare_gcroot(VMObject*, res) = meth->getMethodDelegatee();
- return res;
- } else {
- VMThread::get()->getVM()->error("implement me: GetSemantics: %d", attributes);
- return 0;
- }
-}
-
-static void decapsulePrimitive(VMObject* arg, const llvm::Type* type, std::vector<llvm::GenericValue>& args) {
- llvm_gcroot(arg, 0);
-
- if (type == llvm::Type::getInt1Ty(llvm::getGlobalContext())) {
- llvm::GenericValue gv;
- gv.IntVal = llvm::APInt(1, (bool)((uint32*)arg)[VALUE_OFFSET]);
- args.push_back(gv);
- } else if (type == llvm::Type::getInt8Ty(llvm::getGlobalContext())) {
- llvm::GenericValue gv;
- gv.IntVal = llvm::APInt(8, (uint8)((uint32*)arg)[VALUE_OFFSET]);
- args.push_back(gv);
- } else if (type == llvm::Type::getInt16Ty(llvm::getGlobalContext())) {
- llvm::GenericValue gv;
- gv.IntVal = llvm::APInt(16, (uint16)((uint32*)arg)[VALUE_OFFSET]);
- args.push_back(gv);
- } else if (type == llvm::Type::getInt32Ty(llvm::getGlobalContext())) {
- llvm::GenericValue gv;
- gv.IntVal = llvm::APInt(32, (uint32)((uint32*)arg)[VALUE_OFFSET]);
- args.push_back(gv);
- } else if (type == llvm::Type::getInt64Ty(llvm::getGlobalContext())) {
- llvm::GenericValue gv;
- uint32* ptr = &((uint32*)arg)[VALUE_OFFSET];
- gv.IntVal = llvm::APInt(64, ((uint64*)ptr)[0]);
- args.push_back(gv);
- } else if (type == llvm::Type::getFloatTy(llvm::getGlobalContext())) {
- llvm::GenericValue gv;
- float* ptr = &((float*)arg)[VALUE_OFFSET];
- gv.FloatVal = ((float*)ptr)[0];
- args.push_back(gv);
- } else if (type == llvm::Type::getDoubleTy(llvm::getGlobalContext())) {
- llvm::GenericValue gv;
- uint32* ptr = &((uint32*)arg)[VALUE_OFFSET];
- gv.DoubleVal = ((double*)ptr)[0];
- args.push_back(gv);
- } else if (type == llvm::PointerType::getUnqual(llvm::Type::getInt8Ty(llvm::getGlobalContext()))) {
- llvm::GenericValue gv(((void**)arg)[VALUE_OFFSET]);
- args.push_back(gv);
- } else {
- VMThread::get()->getVM()->error("implement me");
- }
-}
-
-extern "C" VMObject* System_Reflection_ClrMethod_Invoke(VMObject* Method, VMObject* obj, sint32 invokeAttr, VMObject* binder, ArrayObject* args, VMObject* culture) {
- llvm_gcroot(Method, 0);
- llvm_gcroot(obj, 0);
- llvm_gcroot(binder, 0);
- llvm_gcroot(args, 0);
- llvm_gcroot(culture, 0);
-
- VMMethod* meth = (VMMethod*)MSCorlib::methodMethodType->getIntPtr(Method);
- meth->getSignature(NULL);
- meth->compiledPtr(NULL);
- llvm::Function* func = CLIJit::compile(meth->classDef, meth);
- VMClass* type = meth->classDef;
- type->resolveStatic(true, NULL);
- uint32 virt = meth->virt;
-
- if ((obj != 0) && virt) {
- if (!(obj->classOf->isAssignableFrom(type))) {
- VMThread::get()->getVM()->illegalArgumentException(mvm::PrintBuffer(meth->name).cString());
- }
- verifyNull(obj);
- }
-
- std::vector<llvm::GenericValue> gvargs;
- uint32 index = 0;
-
- llvm::Function::arg_iterator i = func->arg_begin();
- llvm::Function::arg_iterator e = func->arg_end();
- if (virt) {
- llvm::GenericValue gv(obj);
- gvargs.push_back(gv);
- ++i;
- }
-
- for ( ;i != e; ++i, ++index) {
- const llvm::Type* type = i->getType();
- if (llvm::isa<llvm::PointerType>(type) && type != llvm::PointerType::getUnqual(llvm::Type::getInt8Ty(llvm::getGlobalContext()))) {
- llvm::GenericValue gv(args->elements[index]);
- gvargs.push_back(gv);
- } else {
- decapsulePrimitive(args->elements[index], type, gvargs);
- }
- }
-
- llvm::GenericValue gv;
- try{
- gv = meth->compileToNative()->invokeGeneric(gvargs);
- }catch(...) {
- assert(0);
- }
-
- declare_gcroot(VMObject*, res) = 0;
- VMCommonClass* retType = meth->parameters[0];
-
-#define CONSTRUCT_RES(name, type, gv_extractor) \
- else if(retType == MSCorlib::p##name) { \
- res = MSCorlib::p##name->doNew(); \
- MSCorlib::ctor##name->set##name(res, (type)gv.gv_extractor); \
- }
-
- if (retType == MSCorlib::pVoid) {
- res = MSCorlib::pVoid->doNew();
- } ON_PRIMITIVES(CONSTRUCT_RES, _F_NTE) else {
- if (retType->super == MSCorlib::pValue || retType->super == MSCorlib::pEnum)
- VMThread::get()->getVM()->error("implement me");
- res = (VMObject*)gv.PointerVal;
- }
-
- return res;
-}
-
-
-static VMObject* createResourceStream(Assembly* ass, sint32 posn) {
- uint32 resSize = ass->resSize;
- uint32 resRva = ass->resRva;
- Section* textSection = ass->textSection;
- uint32 sectionLen = resSize;
- uint32 section = 0;
- uint32 start = 0;
- uint32 length = 0;
- uint32 pad = 0;
-
- Reader* reader = ass->newReader(ass->bytes);
- section = textSection->rawAddress + (resRva - textSection->virtualAddress);
-
- reader->seek(section, Reader::SeekSet);
- while (posn > 0) {
- if (sectionLen < 4) return 0;
- length = reader->readU4();
- if (length > (sectionLen - 4)) return 0;
- if ((length % 4) != 0) {
- pad = 4 - (length % 4);
- } else {
- pad = 0;
- }
- start = start + length + pad + 4;
- section = section + length + pad + 4;
- reader->seek(section + length + pad + 4, Reader::SeekSet);
- sectionLen = sectionLen - (length + pad + 4);
- posn = posn - 1;
- }
-
- start = start + 4;
- if (sectionLen < 4) return 0;
- length = reader->readU4();
- if (length > (sectionLen - 4)) return 0;
-
- declare_gcroot(VMObject*, res) = MSCorlib::resourceStreamType->doNew();
- MSCorlib::ctorResourceStreamType->compileToNative()->invokeVoid(res, ass, (uint64)start, (uint64)length);
-
- return res;
-}
-
-extern "C" VMObject* System_Reflection_Assembly_GetManifestResourceStream(VMObject* Ass, PNetString* str) {
- llvm_gcroot(Ass, 0);
- llvm_gcroot(str, 0);
- Assembly* ass = (Assembly*)MSCorlib::assemblyAssemblyReflection->getIntPtr(Ass);
- N3* vm = (N3*)(VMThread::get()->getVM());
- declare_gcroot(const ArrayChar*, array) = str->value;
- const UTF8* id = vm->arrayToUTF8(array);
- Header* header = ass->CLIHeader;
- uint32 stringOffset = header->stringStream->realOffset;
- Table* manTable = header->tables[CONSTANT_ManifestResource];
- uint32 manRows = manTable->rowsNumber;
- sint32 pos = -1;
- uint32 i = 0;
-
- while ((pos == -1) && (i < manRows)) {
- uint32 nameOffset = manTable->readIndexInRow(i + 1, CONSTANT_MANIFEST_RESOURCE_NAME, ass->bytes);
- const UTF8* name = ass->readString(vm, stringOffset + nameOffset);
-
- if (name == id) {
- pos = i;
- } else {
- ++i;
- }
- }
-
- if (pos != -1) {
- declare_gcroot(VMObject*, res) = createResourceStream(ass, pos);
- return res;
- } else {
- return 0;
- }
-}
-
-
-extern "C" ArrayObject* System_Reflection_ClrHelpers_GetCustomAttributes(Assembly* ass, VMCommonClass* clrTypePrivate, bool inherit) {
- declare_gcroot(ArrayObject*, res) = ass->getCustomAttributes(clrTypePrivate->token, clrTypePrivate);
- return res;
-}
-
-extern "C" VMObject* System_Globalization_TextInfo_ToLower(VMObject* obj, PNetString* str) {
- llvm_gcroot(obj, 0);
- llvm_gcroot(str, 0);
- verifyNull(str);
- declare_gcroot(const ArrayChar*, array) = str->value;
- uint32 length = str->length;
-
- uint16* buf = (uint16*)alloca(length * sizeof(uint16));
-
- N3* vm = VMThread::get()->getVM();
-
- memcpy(buf, array->elements, length * sizeof(uint16));
- ILUnicodeStringToLower((void*)buf, (void*)array->elements, length);
- declare_gcroot(const ArrayChar*, res) = vm->bufToArray(buf, length);
- declare_gcroot(VMObject*, res_str) = vm->arrayToString(res);
- return res_str;
-}
-
-extern "C" VMObject* System_String_Replace(PNetString* str, uint16 c1, uint16 c2) {
- llvm_gcroot(str, 0);
- declare_gcroot(const ArrayChar*, array) = str->value;
- uint32 length = str->length;
- if ((c1 == c2) || length == 0) return str;
-
- uint16* buf = (uint16*)alloca(length * sizeof(uint16));
- memcpy(buf, array->elements, length * sizeof(uint16));
- for (uint32 i = 0; i < length; ++i) {
- if (buf[i] == c1) buf[i] = c2;
- }
-
- N3* vm = (N3*)VMThread::get()->getVM();
- declare_gcroot(const ArrayChar*, res) = vm->bufToArray(buf, length);
- declare_gcroot(VMObject*, res_str) = vm->arrayToString(res);
- return res_str;
-}
-
-extern "C" uint32 System_Reflection_ClrResourceStream_ResourceRead(Assembly* assembly, uint64 position, ArrayUInt8* buffer, uint32 offset, uint32 count) {
- llvm_gcroot(buffer, 0);
- uint32 resRva = assembly->resRva;
- ByteCode* bytes = assembly->bytes;
- Section* textSection = assembly->textSection;
- uint32 section = 0;
-
- section = textSection->rawAddress + (resRva - textSection->virtualAddress);
- memcpy(&(buffer->elements[offset]), &(bytes->elements[section + position]), count);
-
- return count;
-}
-
-extern "C" sint32 System_String_CompareInternal(PNetString* strA, sint32 indexA, sint32 lengthA, PNetString* strB, sint32 indexB, sint32 lengthB, bool ignoreCase) {
- llvm_gcroot(strA, 0);
- llvm_gcroot(strB, 0);
-
- if (strA == 0) {
- if (strB == 0) {
- return 0;
- }
- return -1;
- } else if (strB == 0) {
- return 1;
- } else {
- sint32 cmp = 0;
- if (lengthA >= lengthB) {
- if (ignoreCase) {
- cmp = ILUnicodeStringCompareIgnoreCase((void*)&(strA->value->elements[indexA]), (void*)&(strB->value->elements[indexB]), lengthB);
- } else {
- cmp = ILUnicodeStringCompareNoIgnoreCase((void*)&(strA->value->elements[indexA]), (void*)&(strB->value->elements[indexB]), lengthB);
- }
-
- if (cmp != 0) return cmp;
- else if (lengthA > lengthB) return 1;
- else return 0;
- } else {
- if (ignoreCase) {
- cmp = ILUnicodeStringCompareIgnoreCase((void*)&(strA->value->elements[indexA]), (void*)&(strB->value->elements[indexB]), lengthA);
- } else {
- cmp = ILUnicodeStringCompareNoIgnoreCase((void*)&(strA->value->elements[indexA]), (void*)&(strB->value->elements[indexB]), lengthA);
- }
-
- if (cmp != 0) return cmp;
- else return -1;
- }
- }
-}
-
-extern "C" void System_String_CharFill(PNetString* str, sint32 start, sint32 count, char ch) {
- llvm_gcroot(str, 0);
- declare_gcroot(const ArrayChar*, array) = str->value;
- sint32 length = start + count;
- uint16* buf = (uint16*)alloca(length * sizeof(uint16));
-
- memcpy(buf, array->elements, start * sizeof(uint16));
- for (sint32 i = 0; i < count; ++i) {
- buf[i + start] = ch;
- }
-
- N3* vm = VMThread::get()->getVM();
- declare_gcroot(const ArrayChar*, val) = vm->bufToArray(buf, length);
- str->value = val;
- str->length = length;
-}
-
-
-extern "C" sint32 System_String_InternalOrdinal(PNetString *strA, sint32 indexA, sint32 lengthA,
- PNetString *strB, sint32 indexB, sint32 lengthB) {
- llvm_gcroot(strA, 0);
- llvm_gcroot(strB, 0);
- const uint16 *bufA;
- const uint16 *bufB;
-
- /* Handle the easy cases first */
- if(!strA)
- {
- if(!strB)
- {
- return 0;
- }
- else
- {
- return -1;
- }
- }
- else if(!strB)
- {
- return 1;
- }
-
- /* Compare the two strings */
- bufA = &(strA->value->elements[indexA]);
- bufB = &(strB->value->elements[indexB]);
- while(lengthA > 0 && lengthB > 0)
- {
- if(*bufA < *bufB)
- {
- return -1;
- }
- else if(*bufA > *bufB)
- {
- return 1;
- }
- ++bufA;
- ++bufB;
- --lengthA;
- --lengthB;
- }
-
- /* Determine the ordering based on the tail sections */
- if(lengthA > 0)
- {
- return 1;
- }
- else if(lengthB > 0)
- {
- return -1;
- }
- else
- {
- return 0;
- }
-}
-
-extern "C" VMObject* System_Threading_Thread_InternalCurrentThread() {
- declare_gcroot(VMObject*, appThread) = VMThread::get()->ooo_appThread;
- return appThread;
-}
diff --git a/vmkit/lib/N3/PNetLib/PNetLib.h b/vmkit/lib/N3/PNetLib/PNetLib.h
deleted file mode 100644
index 4ce21ca..0000000
--- a/vmkit/lib/N3/PNetLib/PNetLib.h
+++ /dev/null
@@ -1,30 +0,0 @@
-//===----------------- PNetLib.h - PNetLib interface ----------------------===//
-//
-// N3
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-
-#ifndef N3_PNETLIB_H
-#define N3_PNETLIB_H
-
-#include "VMObject.h"
-
-
-namespace n3 {
-
-class PNetString;
-
-class StringBuilder : public VMObject {
-public:
- PNetString* buildString;
- sint32 maxCapactiy;
- sint32 needsCopy;
-};
-
-}
-
-#endif
diff --git a/vmkit/lib/N3/PNetLib/PNetMSCorlib.cpp b/vmkit/lib/N3/PNetLib/PNetMSCorlib.cpp
deleted file mode 100644
index 1625006..0000000
--- a/vmkit/lib/N3/PNetLib/PNetMSCorlib.cpp
+++ /dev/null
@@ -1,202 +0,0 @@
-//===----- PNetMSCorlib.cpp - The Pnet MSCorlib implementation ------------===//
-//
-// N3
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-
-#include "mvm/JIT.h"
-
-#include "Assembly.h"
-#include "MSCorlib.h"
-#include "N3.h"
-#include "VMClass.h"
-#include "VMObject.h"
-#include "VMThread.h"
-
-using namespace n3;
-
-void MSCorlib::loadStringClass(N3* vm) {
- VMClass* type = (VMClass*)vm->coreAssembly->loadTypeFromName(
- vm->asciizToUTF8("String"),
- vm->asciizToUTF8("System"),
- false, false, false, true);
- MSCorlib::pString = type;
- MSCorlib::pObject->resolveType(true, false, NULL);
- MSCorlib::pObject->resolveVT();
- type->resolveType(true, false, NULL);
- type->resolveVT();
-
- uint64 size = mvm::MvmModule::getTypeSize(type->virtualType->getContainedType(0)) + sizeof(const UTF8*) + sizeof(llvm::GlobalVariable*);
- type->virtualInstance =
- (VMObject*)gc::operator new(size, VMObject::getN3VirtualTable(type->virtualInstance));
- VMObject::initialise(type->virtualInstance, type);
-}
-
-
-void MSCorlib::initialise(N3* vm) {
- #define INIT(var, nameSpace, name, type, prim) {\
- var = (VMClass*)vm->coreAssembly->loadTypeFromName( \
- vm->asciizToUTF8(name), \
- vm->asciizToUTF8(nameSpace),\
- false, false, false, true); \
- var->isPrimitive = prim; \
- if (type) { \
- var->naturalType = type; \
- var->virtualType = type; \
- }}
-
- INIT(MSCorlib::clrType, "System.Reflection", "ClrType", 0, false);
- INIT(MSCorlib::assemblyReflection, "System.Reflection", "Assembly", 0, false);
- INIT(MSCorlib::typedReference, "System", "TypedReference", 0, false);
- INIT(MSCorlib::propertyType, "System.Reflection", "ClrProperty", 0, false);
- INIT(MSCorlib::methodType, "System.Reflection", "ClrMethod", 0, false);
- INIT(MSCorlib::resourceStreamType, "System.Reflection", "ClrResourceStream", 0, false);
-
-#undef INIT
-
- {
- MSCorlib::clrType->resolveType(false, false, NULL);
- std::vector<VMCommonClass*> args;
- args.push_back(MSCorlib::pVoid);
- args.push_back(MSCorlib::clrType);
- MSCorlib::ctorClrType = MSCorlib::clrType->lookupMethod(vm->asciizToUTF8(".ctor"), args, false, false);
- MSCorlib::typeClrType = MSCorlib::clrType->lookupField(vm->asciizToUTF8("privateData"), MSCorlib::pIntPtr, false, false);
- }
-
- {
- MSCorlib::assemblyReflection->resolveType(false, false, NULL);
- std::vector<VMCommonClass*> args;
- args.push_back(MSCorlib::pVoid);
- args.push_back(MSCorlib::assemblyReflection);
- MSCorlib::ctorAssemblyReflection = MSCorlib::assemblyReflection->lookupMethod(vm->asciizToUTF8(".ctor"), args, false, false);
- MSCorlib::assemblyAssemblyReflection = MSCorlib::assemblyReflection->lookupField(vm->asciizToUTF8("privateData"), MSCorlib::pIntPtr, false, false);
- }
-
- {
- MSCorlib::propertyType->resolveType(false, false, NULL);
- std::vector<VMCommonClass*> args;
- args.push_back(MSCorlib::pVoid);
- args.push_back(MSCorlib::propertyType);
- MSCorlib::ctorPropertyType = MSCorlib::propertyType->lookupMethod(vm->asciizToUTF8(".ctor"), args, false, false);
- MSCorlib::propertyPropertyType = MSCorlib::propertyType->lookupField(vm->asciizToUTF8("privateData"), MSCorlib::pIntPtr, false, false);
- }
-
- {
- MSCorlib::methodType->resolveType(false, false, NULL);
- std::vector<VMCommonClass*> args;
- args.push_back(MSCorlib::pVoid);
- args.push_back(MSCorlib::methodType);
- MSCorlib::ctorMethodType = MSCorlib::methodType->lookupMethod(vm->asciizToUTF8(".ctor"), args, false, false);
- MSCorlib::methodMethodType = MSCorlib::methodType->lookupField(vm->asciizToUTF8("privateData"), MSCorlib::pIntPtr, false, false);
- }
-
- {
- MSCorlib::resourceStreamType->resolveType(false, false, NULL);
- std::vector<VMCommonClass*> args;
- args.push_back(MSCorlib::pVoid);
- args.push_back(MSCorlib::resourceStreamType);
- args.push_back(MSCorlib::pIntPtr);
- args.push_back(MSCorlib::pSInt64);
- args.push_back(MSCorlib::pSInt64);
- MSCorlib::ctorResourceStreamType = MSCorlib::resourceStreamType->lookupMethod(vm->asciizToUTF8(".ctor"), args, false, false);
- }
-
- VMCommonClass* voidPtr = vm->coreAssembly->constructPointer(MSCorlib::pVoid, 1);
-#define INIT(var, cl, type) {\
- cl->resolveType(false, false, NULL); \
- var = cl->lookupField(vm->asciizToUTF8("value_"), type, false, false); \
- }
-
- INIT(MSCorlib::ctorBoolean, MSCorlib::pBoolean, MSCorlib::pBoolean);
- INIT(MSCorlib::ctorUInt8, MSCorlib::pUInt8, MSCorlib::pUInt8);
- INIT(MSCorlib::ctorSInt8, MSCorlib::pSInt8, MSCorlib::pSInt8);
- INIT(MSCorlib::ctorChar, MSCorlib::pChar, MSCorlib::pChar);
- INIT(MSCorlib::ctorSInt16, MSCorlib::pSInt16, MSCorlib::pSInt16);
- INIT(MSCorlib::ctorUInt16, MSCorlib::pUInt16, MSCorlib::pUInt16);
- INIT(MSCorlib::ctorSInt32, MSCorlib::pSInt32, MSCorlib::pSInt32);
- INIT(MSCorlib::ctorUInt32, MSCorlib::pUInt32, MSCorlib::pUInt32);
- INIT(MSCorlib::ctorSInt64, MSCorlib::pSInt64, MSCorlib::pSInt64);
- INIT(MSCorlib::ctorUInt64, MSCorlib::pUInt64, MSCorlib::pUInt64);
- INIT(MSCorlib::ctorIntPtr, MSCorlib::pIntPtr, voidPtr);
- INIT(MSCorlib::ctorUIntPtr, MSCorlib::pUIntPtr, voidPtr);
- INIT(MSCorlib::ctorDouble, MSCorlib::pDouble, MSCorlib::pDouble);
- INIT(MSCorlib::ctorFloat, MSCorlib::pFloat, MSCorlib::pFloat);
-
-#undef INIT
-
-
-}
-
-VMObject* Property::getPropertyDelegatee() {
- declare_gcroot(VMObject*, delegatee) = ooo_delegatee;
-
- if (!delegatee) {
- ooo_delegatee = delegatee = MSCorlib::propertyType->doNew();
- MSCorlib::ctorPropertyType->compileToNative()->invokeVoid(delegatee);
- MSCorlib::propertyPropertyType->setIntPtr(delegatee, (int*)this);
- }
-
- return delegatee;
-}
-
-VMObject* VMMethod::getMethodDelegatee() {
- declare_gcroot(VMObject*, delegatee) = ooo_delegatee;
-
- if (!delegatee) {
- ooo_delegatee = delegatee = MSCorlib::methodType->doNew();
- MSCorlib::ctorMethodType->compileToNative()->invokeVoid(delegatee);
- MSCorlib::methodMethodType->setIntPtr(delegatee, (int*)this);
- }
-
- return delegatee;
-}
-
-VMObject* VMCommonClass::getClassDelegatee() {
- declare_gcroot(VMObject*, delegatee) = ooo_delegatee;
-
- if (!delegatee) {
- ooo_delegatee = delegatee = MSCorlib::clrType->doNew();
- MSCorlib::ctorClrType->compileToNative()->invokeVoid(delegatee);
- MSCorlib::typeClrType->setIntPtr(delegatee, (int*)this);
- }
-
- return delegatee;
-}
-
-VMObject* Assembly::getAssemblyDelegatee() {
- declare_gcroot(VMObject*, delegatee) = ooo_delegatee;
-
- if (!delegatee) {
- ooo_delegatee = delegatee = MSCorlib::assemblyReflection->doNew();
- MSCorlib::ctorAssemblyReflection->compileToNative()->invokeVoid(delegatee);
- MSCorlib::assemblyAssemblyReflection->setIntPtr(delegatee, (int*)this);
- }
-
- return delegatee;
-}
-
-static void mapInitialThread(N3* vm) {
- VMClass* cl = (VMClass*)vm->coreAssembly->loadTypeFromName(
- vm->asciizToUTF8("Thread"),
- vm->asciizToUTF8("System.Threading"),
- true, true, true, true);
- declare_gcroot(VMObject*, appThread) = cl->doNew();
-
- std::vector<VMCommonClass*> args;
- args.push_back(MSCorlib::pVoid);
- args.push_back(cl);
- args.push_back(MSCorlib::pIntPtr);
- VMMethod* ctor = cl->lookupMethod(vm->asciizToUTF8(".ctor"), args,
- false, false);
- VMThread* myth = VMThread::get();
- ctor->compileToNative()->invokeVoid(appThread, myth);
- myth->ooo_appThread = appThread;
-}
-
-void MSCorlib::loadBootstrap(N3* vm) {
- mapInitialThread(vm);
-}
diff --git a/vmkit/lib/N3/PNetLib/PNetPath.inc.in b/vmkit/lib/N3/PNetLib/PNetPath.inc.in
deleted file mode 100644
index 2a8216c..0000000
--- a/vmkit/lib/N3/PNetLib/PNetPath.inc.in
+++ /dev/null
@@ -1,15 +0,0 @@
-//===---------- PNetPath.h - Configuration for pnetlib --------------------===//
-//
-// N3
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#include "MSCorlib.h"
-
-using namespace n3;
-
-const char* MSCorlib::libsPath = "@pnetlibpath@/";
-
diff --git a/vmkit/lib/N3/PNetLib/PNetString.cpp b/vmkit/lib/N3/PNetLib/PNetString.cpp
deleted file mode 100644
index 5fe4a7b..0000000
--- a/vmkit/lib/N3/PNetLib/PNetString.cpp
+++ /dev/null
@@ -1,58 +0,0 @@
-//===--- PNetString.cpp - Implementation of PNet string interface ---------===//
-//
-// N3
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#include "llvm/DerivedTypes.h"
-#include "llvm/GlobalVariable.h"
-#include "llvm/LLVMContext.h"
-
-#include "mvm/JIT.h"
-
-#include "CLIString.h"
-#include "MSCorlib.h"
-#include "N3.h"
-#include "PNetString.h"
-#include "VMArray.h"
-#include "VMClass.h"
-#include "VMThread.h"
-
-using namespace n3;
-using namespace llvm;
-
-
-CLIString* CLIString::stringDup(const ArrayChar* array, N3* vm) {
- llvm_gcroot(array, 0);
- declare_gcroot(PNetString*, obj) = (PNetString*)MSCorlib::pString->doNew();
- obj->capacity = array->size;
- obj->length = array->size;
- if (array->size == 0) {
- obj->firstChar = 0;
- } else {
- obj->firstChar = array->elements[0];
- }
- obj->value = array;
- return obj;
-}
-
-GlobalVariable* CLIString::llvmVar(CLIString *self) {
- llvm_gcroot(self, 0);
- declare_gcroot(PNetString*, str) = (PNetString*)self;
- if (!str->_llvmVar) {
- N3* vm = VMThread::get()->getVM();
- if (!str->_llvmVar) {
- const Type* pty = PointerType::getUnqual(Type::getInt8Ty(getGlobalContext()));
- Constant* cons =
- ConstantExpr::getIntToPtr(ConstantInt::get(Type::getInt64Ty(getGlobalContext()), uint64_t (self)),
- pty);
- str->_llvmVar = new GlobalVariable(*(vm->getLLVMModule()), pty, true,
- GlobalValue::ExternalLinkage,
- cons, "");
- }
- }
- return str->_llvmVar;
-}
diff --git a/vmkit/lib/N3/PNetLib/PNetString.h b/vmkit/lib/N3/PNetLib/PNetString.h
deleted file mode 100644
index b779a52..0000000
--- a/vmkit/lib/N3/PNetLib/PNetString.h
+++ /dev/null
@@ -1,38 +0,0 @@
-//===---------- PNetString.h - String representation in PNet --------------===//
-//
-// N3
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#ifndef N3_PNET_STRING_H
-#define N3_PNET_STRING_H
-
-#include "llvm/GlobalVariable.h"
-
-#include "types.h"
-#include "mvm/PrintBuffer.h"
-
-#include "CLIString.h"
-
-namespace n3 {
-
-class ArrayChar;
-
-class PNetString : public CLIString {
-public:
-
- // !!! pnetlib layout !!!
- sint32 capacity;
- sint32 length;
- uint8 firstChar;
- const ArrayChar* value;
- llvm::GlobalVariable* _llvmVar;
-
-};
-
-} // end namespace n3
-
-#endif
diff --git a/vmkit/lib/N3/VMCore/Assembly.cpp b/vmkit/lib/N3/VMCore/Assembly.cpp
deleted file mode 100644
index 0f98130..0000000
--- a/vmkit/lib/N3/VMCore/Assembly.cpp
+++ /dev/null
@@ -1,1930 +0,0 @@
-//===--------- Assembly.cpp - Definition of an assembly -------------------===//
-//
-// N3
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#include <vector>
-
-#include "N3Debug.h"
-#include "types.h"
-
-#include "Assembly.h"
-#include "CLIAccess.h"
-#include "LockedMap.h"
-#include "MSCorlib.h"
-#include "N3.h"
-#include "Reader.h"
-#include "VMClass.h"
-#include "VMObject.h"
-#include "VMThread.h"
-
-using namespace n3;
-
-
-#define DEF_TABLE_MASK(name, nb, ...) \
- static void name(uint32 index, \
- std::vector<Table*, gc_allocator<Table*> >& tables, \
- uint32 heapSizes) { \
- Table* table = tables[index]; \
- uint32 rowSize = 0; \
- uint32 bitmask = 0; \
- __VA_ARGS__; \
- table->count = nb; \
- table->sizeMask = bitmask; \
- table->rowSize = rowSize; \
- }
-
-
-DEF_TABLE_MASK(METHOD_Module, 5,
- INT16(CONSTANT_MODULE_GENERATION)
- STRING(CONSTANT_MODULE_NAME)
- GUID(CONSTANT_MODULE_MVID)
- GUID(CONSTANT_MODULE_ENCID)
- GUID(CONSTANT_MODULE_ENCBASEID))
-
-DEF_TABLE_MASK(METHOD_TypeRef, 3,
- RESOLUTION_SCOPE(CONSTANT_TYPEREF_RESOLUTION_SCOPE)
- STRING(CONSTANT_TYPEREF_NAME)
- STRING(CONSTANT_TYPEREF_NAMESPACE))
-
-DEF_TABLE_MASK(METHOD_TypeDef, 6,
- INT32(CONSTANT_TYPEDEF_FLAGS)
- STRING(CONSTANT_TYPEDEF_NAME)
- STRING(CONSTANT_TYPEDEF_NAMESPACE)
- TYPEDEF_OR_REF(CONSTANT_TYPEDEF_EXTENDS)
- TABLE(CONSTANT_Field, CONSTANT_TYPEDEF_FIELDLIST)
- TABLE(CONSTANT_MethodDef, CONSTANT_TYPEDEF_METHODLIST))
-
-DEF_TABLE_MASK(METHOD_MethodDef, 6,
- INT32(CONSTANT_METHODDEF_RVA)
- INT16(CONSTANT_METHODDEF_IMPLFLAGS)
- INT16(CONSTANT_METHODDEF_FLAGS)
- STRING(CONSTANT_METHODDEF_NAME)
- BLOB(CONSTANT_METHODDEF_SIGNATURE)
- TABLE(CONSTANT_Param, CONSTANT_METHODDEF_PARAMLIST))
-
-DEF_TABLE_MASK(METHOD_Param, 3,
- INT16(CONSTANT_PARAM_FLAGS)
- INT16(CONSTANT_PARAM_SEQUENCE)
- STRING(CONSTANT_PARAM_NAME))
-
-DEF_TABLE_MASK(METHOD_MemberRef, 3,
- MEMBER_REF_PARENT(CONSTANT_MEMBERREF_CLASS)
- STRING(CONSTANT_MEMBERREF_NAME)
- BLOB(CONSTANT_MEMBERREF_SIGNATURE))
-
-DEF_TABLE_MASK(METHOD_CustomAttribute, 3,
- HAS_CUSTOM_ATTRIBUTE(CONSTANT_CUSTOM_ATTRIBUTE_PARENT)
- CUSTOM_ATTRIBUTE_TYPE(CONSTANT_CUSTOM_ATTRIBUTE_TYPE)
- BLOB(CONSTANT_CUSTOM_ATTRIBUTE_VALUE))
-
-DEF_TABLE_MASK(METHOD_StandaloneSig, 1,
- BLOB(CONSTANT_STANDALONE_SIG_SIGNATURE))
-
-DEF_TABLE_MASK(METHOD_TypeSpec, 1,
- BLOB(CONSTANT_TYPESPEC_SIGNATURE))
-
-DEF_TABLE_MASK(METHOD_Assembly, 9,
- INT32(CONSTANT_ASSEMBLY_HASH_ALG_ID)
- INT16(CONSTANT_ASSEMBLY_MAJOR)
- INT16(CONSTANT_ASSEMBLY_MINOR)
- INT16(CONSTANT_ASSEMBLY_BUILD)
- INT16(CONSTANT_ASSEMBLY_REVISION)
- INT32(CONSTANT_ASSEMBLY_FLAGS)
- BLOB(CONSTANT_ASSEMBLY_PUBLIC_KEY)
- STRING(CONSTANT_ASSEMBLY_NAME)
- STRING(CONSTANT_ASSEMBLY_CULTURE))
-
-DEF_TABLE_MASK(METHOD_AssemblyRef, 9,
- INT16(CONSTANT_ASSEMBLY_REF_MAJOR)
- INT16(CONSTANT_ASSEMBLY_REF_MINOR)
- INT16(CONSTANT_ASSEMBLY_REF_BUILD)
- INT16(CONSTANT_ASSEMBLY_REF_REVISION)
- INT32(CONSTANT_ASSEMBLY_REF_FLAGS)
- BLOB(CONSTANT_ASSEMBLY_REF_PUBLIC_KEY)
- STRING(CONSTANT_ASSEMBLY_REF_NAME)
- STRING(CONSTANT_ASSEMBLY_REF_CULTURE)
- BLOB(CONSTANT_ASSEMBLY_REF_HASH_VALUE))
-
-DEF_TABLE_MASK(METHOD_Field, 3,
- INT16(CONSTANT_FIELD_FLAGS)
- STRING(CONSTANT_FIELD_NAME)
- BLOB(CONSTANT_FIELD_SIGNATURE))
-
-DEF_TABLE_MASK(METHOD_InterfaceImpl, 2,
- TABLE(CONSTANT_TypeDef, CONSTANT_INTERFACE_IMPL_CLASS)
- TYPEDEF_OR_REF(CONSTANT_INTERFACE_IMPL_INTERFACE))
-
-DEF_TABLE_MASK(METHOD_NestedClass, 2,
- TABLE(CONSTANT_TypeDef, CONSTANT_NESTED_CLASS_NESTED_CLASS)
- TABLE(CONSTANT_TypeDef, CONSTANT_NESTED_CLASS_ENCLOSING_CLASS))
-
-DEF_TABLE_MASK(METHOD_MethodSpec, 2,
- METHODDEF_OR_REF(CONSTANT_METHOD_SPEC_METHOD)
- BLOB(CONSTANT_METHOD_SPEC_INSTANTIATION))
-
-DEF_TABLE_MASK(METHOD_GenericParamConstraint, 2,
- TABLE(CONSTANT_GenericParam, CONSTANT_GENERIC_PARAM_CONSTRAINT_OWNER)
- TYPEDEF_OR_REF(CONSTANT_GENERIC_PARAM_CONSTRAINT_CONSTRAINT))
-
-DEF_TABLE_MASK(METHOD_Constant, 3,
- INT16(CONSTANT_CONSTANT_TYPE)
- HAS_CONSTANT(CONSTANT_CONSTANT_PARENT)
- BLOB(CONSTANT_CONSTANT_VALUE))
-
-DEF_TABLE_MASK(METHOD_FieldMarshal, 2,
- HAS_FIELD_MARSHAL(CONSTANT_FIELD_MARSHAL_PARENT)
- BLOB(CONSTANT_FIELD_MARSHAL_NATIVE_TYPE))
-
-DEF_TABLE_MASK(METHOD_DeclSecurity, 3,
- INT16(CONSTANT_DECL_SECURITY_ACTION)
- HAS_DECL_SECURITY(CONSTANT_DECL_SECURITY_PARENT)
- BLOB(CONSTANT_DECL_SECURITY_PERMISSION_SET))
-
-DEF_TABLE_MASK(METHOD_ClassLayout, 3,
- INT16(CONSTANT_CLASS_LAYOUT_PACKING_SIZE)
- INT32(CONSTANT_CLASS_LAYOUT_CLASS_SIZE)
- TABLE(CONSTANT_TypeDef, CONSTANT_CLASS_LAYOUT_PARENT))
-
-DEF_TABLE_MASK(METHOD_FieldLayout, 2,
- INT32(CONSTANT_FIELD_LAYOUT_OFFSET)
- TABLE(CONSTANT_Field, CONSTANT_FIELD_LAYOUT_FIELD))
-
-DEF_TABLE_MASK(METHOD_EventMap, 2,
- TABLE(CONSTANT_TypeDef, CONSTANT_EVENT_MAP_PARENT)
- TABLE(CONSTANT_Event, CONSTANT_EVEN_MAP_EVENT_LIST))
-
-DEF_TABLE_MASK(METHOD_Event, 3,
- INT16(CONSTANT_EVENT_EVENT_FLAGS)
- STRING(CONSTANT_EVENT_NAME)
- TYPEDEF_OR_REF(CONSTANT_EVENT_TYPE))
-
-DEF_TABLE_MASK(METHOD_PropertyMap, 2,
- TABLE(CONSTANT_TypeDef, CONSTANT_PROPERTY_MAP_PARENT)
- TABLE(CONSTANT_Property, CONSTANT_PROPERTY_MAP_PROPERTY_LIST))
-
-DEF_TABLE_MASK(METHOD_Property, 3,
- INT16(CONSTANT_PROPERTY_FLAGS)
- STRING(CONSTANT_PROPERTY_NAME)
- BLOB(CONSTANT_PROPERTY_TYPE))
-
-DEF_TABLE_MASK(METHOD_MethodSemantics, 3,
- INT16(CONSTANT_METHOD_SEMANTICS_SEMANTICS)
- TABLE(CONSTANT_MethodDef, CONSTANT_METHOD_SEMANTICS_METHOD)
- HAS_SEMANTICS(CONSTANT_METHOD_SEMANTICS_ASSOCIATION))
-
-DEF_TABLE_MASK(METHOD_MethodImpl, 3,
- TABLE(CONSTANT_TypeDef, CONSTANT_METHOD_IMPL_CLASS)
- METHODDEF_OR_REF(CONSTANT_METHOD_IMPL_METHOD_BODY)
- METHODDEF_OR_REF(CONSTANT_METHOD_IMPL_METHOD_DECLARATION))
-
-DEF_TABLE_MASK(METHOD_ModuleRef, 1,
- STRING(CONSTANT_MODULE_REF_NAME))
-
-DEF_TABLE_MASK(METHOD_ImplMap, 4,
- INT16(CONSTANT_IMPL_MAP_MAPPING_FLAGS)
- MEMBER_FORWARDED(CONSTANT_IMPL_MAP_MEMBER_FORWARDED)
- STRING(CONSTANT_IMPL_MAP_IMPORT_NAME)
- TABLE(CONSTANT_ModuleRef, CONSTANT_IMPL_MAP_IMPORT_SCOPE))
-
-DEF_TABLE_MASK(METHOD_FieldRva, 2,
- INT32(CONSTANT_FIELD_RVA_RVA)
- TABLE(CONSTANT_Field, CONSTANT_FIELD_RVA_FIELD))
-
-DEF_TABLE_MASK(METHOD_ManifestResource, 4,
- INT32(CONSTANT_MANIFEST_RESOURCE_OFFSET)
- INT32(CONSTANT_MANIFEST_RESOURCE_FLAGS)
- STRING(CONSTANT_MANIFEST_RESOURCE_NAME)
- IMPLEMENTATION(CONSTANT_MANIFEST_RESOURCE_IMPLEMENTATION))
-
-DEF_TABLE_MASK(METHOD_AssemblyProcessor, 1,
- INT32(CONSTANT_ASSEMBLY_PROCESSOR_PROCESSOR))
-
-DEF_TABLE_MASK(METHOD_AssemblyOS, 3,
- INT32(CONSTANT_ASSEMBLY_OS_PLATFORM_ID)
- INT32(CONSTANT_ASSEMBLY_OS_MAJOR_VERSION)
- INT32(CONSTANT_ASSEMBLY_OS_MINOR_VERSION))
-
-DEF_TABLE_MASK(METHOD_File, 3,
- INT32(CONSTANT_FILE_FLAGS)
- STRING(CONSTANT_FILE_NAME)
- BLOB(CONSTANT_FILE_HASH_VALUE))
-
-DEF_TABLE_MASK(METHOD_GenericParam, 4,
- INT16(CONSTANT_GENERIC_PARAM_NUMBER)
- INT16(CONSTANT_GENERIC_PARAM_FLAGS)
- TYPE_OR_METHODDEF(CONSTANT_GENERIC_PARAM_OWNER)
- STRING(CONSTANT_GENERIC_PARAM_NAME))
-
-void Header::print(mvm::PrintBuffer* buf) const {
- buf->write("Header<>");
-}
-
-void Section::print(mvm::PrintBuffer* buf) const {
- buf->write("Section<>");
-}
-
-void Table::print(mvm::PrintBuffer* buf) const {
- buf->write("Table<>");
-}
-
-void Stream::print(mvm::PrintBuffer* buf) const {
- buf->write("Table<>");
-}
-
-void Assembly::print(mvm::PrintBuffer* buf) const {
- buf->write("Assembly<");
- name->print(buf);
- buf->write(">");
-}
-
-static VMCommonClass* arrayDup(ClassNameCmp &cmp, Assembly* ass) {
- VMClassArray* cl = new(ass->allocator, "VMClassArray") VMClassArray();
- cl->initialise(ass->vm, true);
- cl->name = cmp.name;
- cl->nameSpace = cmp.nameSpace;
- cl->super = VMClassArray::SuperArray;
- cl->interfaces = VMClassArray::InterfacesArray;
- cl->virtualMethods = VMClassArray::VirtualMethodsArray;
- cl->staticMethods = VMClassArray::StaticMethodsArray;
- cl->virtualFields = VMClassArray::VirtualFieldsArray;
- cl->staticFields = VMClassArray::StaticFieldsArray;
- cl->depth = 1;
- cl->display.push_back(VMClassArray::SuperArray);
- cl->display.push_back(cl);
- cl->status = loaded;
- cl->assembly = ass;
- return cl;
-}
-
-VMClassArray* Assembly::constructArray(VMCommonClass* base, uint32 dims) {
- if (this != base->assembly)
- return base->assembly->constructArray(base, dims);
-
- ClassNameCmp CC(VMClassArray::constructArrayName(base->name, dims),
- base->nameSpace);
- VMClassArray* cl = (VMClassArray*)(loadedNameClasses->lookupOrCreate(CC, this, arrayDup));
- if (!cl->baseClass) {
- cl->dims = dims;
- if (dims > 1)
- cl->baseClass = constructArray(base, dims - 1);
- else
- cl->baseClass = base;
- }
- return cl;
-}
-
-static VMCommonClass* pointerDup(ClassNameCmp &cmp, Assembly* ass) {
- VMClassPointer* cl = new(ass->allocator, "VMClassPointer") VMClassPointer();
- cl->initialise(ass->vm, false);
- cl->isPointer = true;
- cl->name = cmp.name;
- cl->nameSpace = cmp.nameSpace;
- cl->depth = 0;
- cl->display.push_back(cl);
- cl->status = loaded;
- cl->assembly = ass;
- return cl;
-}
-
-VMClassPointer* Assembly::constructPointer(VMCommonClass* base, uint32 dims) {
- if (this != base->assembly)
- return base->assembly->constructPointer(base, dims);
-
- ClassNameCmp CC(VMClassPointer::constructPointerName(base->name, dims),
- base->nameSpace);
- VMClassPointer* cl = (VMClassPointer*)(loadedNameClasses->lookupOrCreate(CC, this, pointerDup));
- if (!cl->baseClass) {
- cl->dims = dims;
- cl->baseClass = base;
- }
- return cl;
-}
-
-VMClassArray* Assembly::constructArray(const UTF8* name, const UTF8* nameSpace,
- uint32 dims) {
- assert(this == ((N3*)VMThread::get()->getVM())->coreAssembly);
- ClassNameCmp CC(VMClassArray::constructArrayName(name, dims),
- nameSpace);
- VMClassArray* cl = (VMClassArray*)(loadedNameClasses->lookupOrCreate(CC, this, arrayDup));
- cl->dims = dims;
- return cl;
-}
-
-static VMCommonClass* classDup(ClassNameCmp &cmp, Assembly* ass) {
- VMClass* cl = new(ass->allocator, "VMClass") VMClass();
- cl->initialise(ass->vm, false);
- cl->name = cmp.name;
- cl->nameSpace = cmp.nameSpace;
- cl->virtualTracer = 0;
- cl->staticInstance = 0;
- cl->virtualInstance = 0;
- cl->virtualType = 0;
- cl->super = 0;
- cl->status = hashed;
- cl->assembly = ass;
- return cl;
-}
-
-VMClass* Assembly::constructClass(const UTF8* name,
- const UTF8* nameSpace, uint32 token) {
- ClassNameCmp CC(name, nameSpace);
- VMClass* cl = (VMClass*)loadedNameClasses->lookupOrCreate(CC, this, classDup);
- loadedTokenClasses->lookupOrCreate(token, cl);
- cl->token = token;
- return cl;
-}
-
-static VMCommonClass* genClassDup(ClassNameCmp &cmp, Assembly* ass) {
- VMClass* cl = new(ass->allocator, "VMGenericClass") VMGenericClass();
- cl->initialise(ass->vm, false);
- cl->name = cmp.name;
- cl->nameSpace = cmp.nameSpace;
- cl->virtualTracer = 0;
- cl->staticInstance = 0;
- cl->virtualInstance = 0;
- cl->virtualType = 0;
- cl->super = 0;
- cl->status = hashed;
- cl->assembly = ass;
- return cl;
-}
-
-VMGenericClass* Assembly::constructGenericClass(const UTF8* name,
- const UTF8* nameSpace, std::vector<VMCommonClass*> genArgs, uint32 token) {
- uint32 size = name->size + 2;
- sint32 i = 0;
- for (std::vector<VMCommonClass*>::iterator it = genArgs.begin(), e = genArgs.end(); it!= e; ++it) {
- size += (*it)->name->size + 1;
- }
- uint16* buf = (uint16*) alloca(sizeof(uint16) * size);
- for (i = 0; i < name->size; i++) {
- buf[i] = name->elements[i];
- }
- buf[i++] = '<';
- for (std::vector<VMCommonClass*>::iterator it = genArgs.begin(), e = genArgs.end(); it!= e; ++it) {
- for (int j = 0; j < (*it)->name->size; i++, j++) {
- buf[i] = (*it)->name->elements[j];
- }
- buf[i++] = ',';
- }
- buf[i] = '>';
- const UTF8* genName = VMThread::get()->getVM()->bufToUTF8(buf, size);
- //printf("%s\n", mvm::PrintBuffer(genName).cString());
-
- ClassNameCmp CC(genName, nameSpace);
- VMGenericClass* cl = (VMGenericClass*) loadedNameClasses->lookupOrCreate(CC, this, genClassDup);
-
- cl->genericParams = genArgs; // TODO GC safe?
- cl->token = token;
-
- return cl;
-}
-
-static VMField* fieldDup(uint32& key, Assembly* ass) {
- VMField* field = new(ass->allocator, "VMField") VMField();
- field->token = key;
- return field;
-}
-
-VMField* Assembly::constructField(VMClass* cl, const UTF8* name,
- VMCommonClass* signature,
- uint32 token, VMGenericClass* genClass, VMGenericMethod* genMethod) {
- VMField* field;
-
- if (genClass == 0) {
- // we are not reading a generic class
- field = loadedTokenFields->lookupOrCreate(token, this, fieldDup);
- } else {
- // we are reading a generic class, don't add a reference
- // to the loadedTokenFields map
- field = fieldDup(token, this);
- }
-
- field->classDef = cl;
- field->signature = signature;
- field->name = name;
-
- return field;
-}
-
-static VMMethod* methodDup(uint32& key, Assembly* ass) {
- VMMethod* meth = new(ass->allocator, "VMMethod") VMMethod();
- meth->token = key;
- meth->canBeInlined = false;
- return meth;
-}
-
-static VMGenericMethod* genMethodDup(uint32& key, Assembly* ass) {
- VMGenericMethod* meth = new(ass->allocator, "VMGenericMethod") VMGenericMethod();
- meth->token = key;
- meth->canBeInlined = false;
- return meth;
-}
-
-VMMethod* Assembly::constructMethod(VMClass* cl, const UTF8* name,
- uint32 token, bool generic,
- std::vector<VMCommonClass*>* genMethodInstantiation, VMGenericClass* genClass) {
- VMMethod* meth;
-
- if (genClass == 0 && generic == false) {
- // we are not reading a generic class
- meth = loadedTokenMethods->lookupOrCreate(token, this, methodDup);
- } else {
- // we are reading a generic class or a generic method, don't add a reference
- // to the loadedTokenMethods map
- meth = methodDup(token, this);
-
- if (generic) {
- // we are reading a generic method
- if (genMethodInstantiation == NULL) {
- cl->genericMethods.push_back(meth);
- } else {
- VMGenericMethod* genMethod = genMethodDup(token, this);
- genMethod->genericParams = *genMethodInstantiation;
- meth = genMethod;
- if (isStatic(meth->flags)) {
- cl->staticMethods.push_back(meth);
- } else {
- cl->virtualMethods.push_back(meth);
- }
- }
- }
- }
-
- meth->classDef = cl;
- meth->_signature = 0;
- meth->name = name;
-
- return meth;
-}
-
-Assembly::Assembly(mvm::BumpPtrAllocator &allocator, N3 *vm, const UTF8 *name) : allocator(allocator) {
- this->lockVar = new mvm::LockRecursive();
- this->loadedNameClasses = new(allocator, "ClassNameMap") ClassNameMap();
- this->loadedTokenClasses = new(allocator, "ClassTokenMap") ClassTokenMap();
- this->loadedTokenMethods = new(allocator, "MethodTokenMap") MethodTokenMap();
- this->loadedTokenFields = new(allocator, "FieldTokenMap") FieldTokenMap();
-
- this->assemblyRefs = 0;
- this->isRead = false;
- this->vm = vm;
- this->name = name;
-}
-
-static void unimplemented(uint32 index,
- std::vector<Table*, gc_allocator<Table*> >& tables,
- uint32 heapSizes) {
- VMThread::get()->getVM()->error("Unknown table %x", index);
-}
-
-maskVector_t Assembly::maskVector[64] = {
- METHOD_Module, // 0x00
- METHOD_TypeRef, // 0x01
- METHOD_TypeDef, // 0x02
- unimplemented, // 0x03
- METHOD_Field, // 0x04
- unimplemented, // 0x05
- METHOD_MethodDef, // 0x06
- unimplemented, // 0x07
- METHOD_Param, // 0x08
- METHOD_InterfaceImpl, // 0x09
- METHOD_MemberRef, // 0x0A
- METHOD_Constant, // 0x0B
- METHOD_CustomAttribute, // 0x0C
- METHOD_FieldMarshal, // 0x0D
- METHOD_DeclSecurity, // 0x0E
- METHOD_ClassLayout, // 0x1F
- METHOD_FieldLayout, // 0x10
- METHOD_StandaloneSig, // 0x11
- METHOD_EventMap, // 0x12
- unimplemented, // 0x13
- METHOD_Event, // 0x14
- METHOD_PropertyMap, // 0x15
- unimplemented, // 0x16
- METHOD_Property, // 0x17
- METHOD_MethodSemantics, // 0x18
- METHOD_MethodImpl, // 0x19
- METHOD_ModuleRef, // 0x1A
- METHOD_TypeSpec, // 0x1B
- METHOD_ImplMap, // 0x1C
- METHOD_FieldRva, // 0x1D
- unimplemented, // 0x1E
- unimplemented, // 0x1F
- METHOD_Assembly, // 0x20
- METHOD_AssemblyProcessor, // 0x21
- METHOD_AssemblyOS, // 0x22
- METHOD_AssemblyRef, // 0x23
- unimplemented, // 0x24
- unimplemented, // 0x25
- METHOD_File, // 0x26
- unimplemented, // 0x27
- METHOD_ManifestResource, // 0x28
- METHOD_NestedClass, // 0x29
- METHOD_GenericParam, // 0x2A
- METHOD_MethodSpec, // 0x2B
- METHOD_GenericParamConstraint,// 0x2C
- unimplemented,
- unimplemented,
- unimplemented,
- unimplemented,
- unimplemented,
- unimplemented,
- unimplemented,
- unimplemented,
- unimplemented,
- unimplemented,
- unimplemented,
- unimplemented,
- unimplemented,
- unimplemented,
- unimplemented,
- unimplemented,
- unimplemented,
- unimplemented,
- unimplemented
-};
-
-const char* Assembly::maskVectorName[64] = {
- "METHOD_Module", // 0x00
- "METHOD_TypeRef", // 0x01
- "METHOD_TypeDef", // 0x02
- "unimplemented", // 0x03
- "METHOD_Field", // 0x04
- "unimplemented", // 0x05
- "METHOD_MethodDef", // 0x06
- "unimplemented", // 0x07
- "METHOD_Param", // 0x08
- "METHOD_InterfaceImpl", // 0x09
- "METHOD_MemberRef", // 0x0A
- "METHOD_Constant", // 0x0B
- "METHOD_CustomAttribute", // 0x0C
- "METHOD_FieldMarshal", // 0x0D
- "METHOD_DeclSecurity", // 0x0E
- "METHOD_ClassLayout", // 0x1F
- "METHOD_FieldLayout", // 0x10
- "METHOD_StandaloneSig", // 0x11
- "METHOD_EventMap", // 0x12
- "unimplemented", // 0x13
- "METHOD_Event", // 0x14
- "METHOD_PropertyMap", // 0x15
- "unimplemented", // 0x16
- "METHOD_Property", // 0x17
- "METHOD_MethodSemantics", // 0x18
- "METHOD_MethodImpl", // 0x19
- "METHOD_ModuleRef", // 0x1A
- "METHOD_TypeSpec", // 0x1B
- "METHOD_ImplMap", // 0x1C
- "METHOD_FieldRva", // 0x1D
- "unimplemented", // 0x1E
- "unimplemented", // 0x1F
- "METHOD_Assembly", // 0x20
- "METHOD_AssemblyProcessor", // 0x21
- "METHOD_AssemblyOS", // 0x22
- "METHOD_AssemblyRef", // 0x23
- "unimplemented", // 0x24
- "unimplemented", // 0x25
- "METHOD_File", // 0x26
- "unimplemented", // 0x27
- "METHOD_ManifestResource", // 0x28
- "METHOD_NestedClass", // 0x29
- "METHOD_GenericParam", // 0x2A
- "METHOD_MethodSpec", // 0x2B
- "METHOD_GenericParamConstraint", // 0x2C
- "unimplemented",
- "unimplemented",
- "unimplemented",
- "unimplemented",
- "unimplemented",
- "unimplemented",
- "unimplemented",
- "unimplemented",
- "unimplemented",
- "unimplemented",
- "unimplemented",
- "unimplemented",
- "unimplemented",
- "unimplemented",
- "unimplemented",
- "unimplemented",
- "unimplemented",
- "unimplemented",
- "unimplemented"
-};
-
-#define EXTRACT_SIZE(bitmask, index) \
- (1 + (3 & (bitmask >> (index << 1))))
-
-void Table::readRow(uint32* result, uint32 row, ByteCode* array) {
- uint32 rowOffset = offset + ((row - 1) * rowSize);
- for (uint32 i = 0; i < count; ++i) {
- uint32 size = EXTRACT_SIZE(sizeMask, i);
- switch(size) {
- case 1: VMThread::get()->getVM()->error("implement me"); break;
- case 2: result[i] = READ_U2(array, rowOffset); break;
- case 4: result[i] = READ_U4(array, rowOffset); break;
- default: VMThread::get()->getVM()->error("unknown size %d", size); break;
- }
- }
-}
-
-uint32 Table::readIndexInRow(uint32 row, uint32 index, ByteCode* array) {
- uint32 indexOffset = offset + ((row - 1) * rowSize);
- for (uint32 i = 0; i < index; ++i) {
- indexOffset += EXTRACT_SIZE(sizeMask, i);
- }
-
- uint32 size = EXTRACT_SIZE(sizeMask, index);
-
- switch(size) {
- case 1: VMThread::get()->getVM()->error("implement me"); break;
- case 2: return READ_U2(array, indexOffset);
- case 4: return READ_U4(array, indexOffset);
- default: VMThread::get()->getVM()->error("unknown size %d", size); break;
- }
-
- // unreachable
- return 0;
-}
-
-void Section::read(Reader* reader, N3* vm) {
- name = (char*) malloc(SECTION_NAME_LENGTH);
- memcpy(name, &(reader->bytes->elements[reader->cursor]),
- SECTION_NAME_LENGTH);
- reader->cursor += SECTION_NAME_LENGTH;
-
- virtualSize = reader->readU4();
- virtualAddress = reader->readU4();
- rawSize = reader->readU4();
- rawAddress = reader->readU4();
- relocAddress = reader->readU4();
- lineNumbers = reader->readU4();
- relocationsNumber = reader->readU2();
- lineNumbersNumber = reader->readU2();
- characteristics = reader->readU4();
-}
-
-void Header::read(mvm::BumpPtrAllocator &allocator, Reader* reader, N3* vm) {
- uint32 start = reader->cursor;
- signature = reader->readU4();
- major = reader->readU2();
- minor = reader->readU2();
- reserved = reader->readU4();
- versionLength = reader->readU4();
- versionName = Assembly::readUTF8(vm, versionLength, reader);
- flags = reader->readU2();
- nbStreams = reader->readU2();
-
- for (uint32 i = 0; i < nbStreams; ++i) {
- uint32 offset = reader->readU4();
- uint32 size = reader->readU4();
- uint32 len =
- strlen((char*)(&(reader->bytes->elements[reader->cursor])));
-
- Stream* stream = new(allocator, "Stream") Stream();
- char* str = (char*)malloc(len + 1);
- memcpy(str, &(reader->bytes->elements[reader->cursor]), len + 1);
- reader->cursor += (len + (4 - (len % 4)));
-
- stream->realOffset = start + offset;
- stream->size = size;
- stream->name = str;
-
- if (!(strcmp(str, "#~"))) tildStream = stream;
- else if (!(strcmp(str, "#Strings"))) stringStream = stream;
- else if (!(strcmp(str, "#US"))) usStream = stream;
- else if (!(strcmp(str, "#Blob"))) blobStream = stream;
- else if (!(strcmp(str, "#GUID"))) guidStream = stream;
- else VMThread::get()->getVM()->error("invalid stream %s", str);
- }
-}
-
-const ArrayChar* Assembly::readUTF16(N3* vm, uint32 len,
- Reader* reader) {
- declare_gcroot(const ArrayChar*, res) = readUTF16(vm, len, reader->bytes, reader->cursor);
- return res;
-}
-
-const ArrayChar* Assembly::readUTF16(N3* vm, uint32 len,
- ByteCode* bytes, uint32 &offset) {
- uint32 realLen = len >> 1;
- uint16* buf = (uint16*)alloca(len);
- uint32 i = 0;
- while (i < realLen) {
- uint16 cur = READ_U2(bytes, offset);
- buf[i] = cur;
- ++i;
- }
- declare_gcroot(ArrayChar*, res) = vm->bufToArray(buf, realLen);
- return res;
-}
-
-const UTF8* Assembly::readUTF8(N3* vm, uint32 len, Reader* reader) {
- return readUTF8(vm, len, reader->bytes, reader->cursor);
-}
-
-const UTF8* Assembly::readUTF8(N3* vm, uint32 len,
- ByteCode* bytes, uint32 &offset) {
- uint16* buf = (uint16*)alloca(len * sizeof(uint16));
- uint32 n = 0;
- uint32 i = 0;
-
- while (i < len) {
- uint32 cur = READ_U1(bytes, offset);
- if (cur & 0x80) {
- uint32 y = READ_U1(bytes, offset);
- if (cur & 0x20) {
- uint32 z = READ_U1(bytes, offset);
- cur = ((cur & 0x0F) << 12) +
- ((y & 0x3F) << 6) +
- (z & 0x3F);
- i += 3;
- } else {
- cur = ((cur & 0x1F) << 6) +
- (y & 0x3F);
- i += 2;
- }
- } else {
- ++i;
- }
- buf[n] = ((uint16)cur);
- ++n;
- }
-
- const UTF8* utf8 = vm->bufToUTF8(buf, n);
-
- return utf8;
-}
-
-const UTF8* Assembly::readString(N3* vm, uint32 offset) {
- uint32 end = offset;
- uint32 cur = 0;
- while ((cur = READ_U1(bytes, end)) != 0) {}
- return readUTF8(vm, (end - 1 - offset), bytes, offset);
-}
-
-void Assembly::readTables(Reader* reader) {
- //uint32 reserved1 =
- reader->readU4();
- //uint8 major =
- reader->readU1();
- //uint8 minor =
- reader->readU1();
- uint8 heapSizes = reader->readU1();
- //uint8 reserved2 =
- reader->readU1();
- uint32 validLow = reader->readU4();
- uint32 validHigh = reader->readU4();
- //uint32 sortedLow =
- reader->readU4();
- //uint32 sortedHigh =
- reader->readU4();
- uint32 tableNumber = 0;
- uint32 offset = 0;
-
- for (uint32 i = 0; i < 32; ++i) {
- Table* table = new(allocator, "Table") Table();
- if ((1 << i) & validLow) {
- table->rowsNumber = reader->readU4();
- ++tableNumber;
- } else {
- table->rowsNumber = 0;
- }
- CLIHeader->tables.push_back(table);
- }
-
- for (uint32 i = 0; i < 32; ++i) {
- Table* table = new(allocator, "Table") Table();
- if ((1 << i) & validHigh) {
- table->rowsNumber = reader->readU4();
- ++tableNumber;
- } else {
- table->rowsNumber = 0;
- }
- CLIHeader->tables.push_back(table);
- }
-
- offset = reader->cursor;
-
- uint32 index = 0;
- for (std::vector<Table*, gc_allocator<Table*> >::iterator i =
- CLIHeader->tables.begin(),
- e = CLIHeader->tables.end(); i != e; ++i, ++index) {
- Table* table = (*i);
- if (table->rowsNumber) {
- maskVector[index](index, CLIHeader->tables, heapSizes);
- table->offset = offset;
- offset += (table->rowsNumber * table->rowSize);
- }
- }
-}
-
-Reader *Assembly::newReader(ByteCode* array, uint32 start, uint32 end) {
- return new(allocator, "Reader") Reader(array, start, end);
-}
-
-int Assembly::resolve(int doResolve, const char *ext) {
- if(!bytes)
- open(ext);
-
- if(bytes && doResolve && !isRead) {
- lockVar->lock();
- if(!isRead) {
- Reader* reader = newReader(bytes);
- PRINT_DEBUG(N3_LOAD, 1, LIGHT_GREEN, "Reading %s::%s", mvm::PrintBuffer(vm).cString(),
- mvm::PrintBuffer(this).cString());
-
- textSection = new(allocator, "Section") Section();
- rsrcSection = new(allocator, "Section") Section();
- relocSection = new(allocator, "Section") Section();
-
- reader->seek(TEXT_SECTION_HEADER, Reader::SeekSet);
- textSection->read(reader, vm);
- rsrcSection->read(reader, vm);
- relocSection->read(reader, vm);
-
- reader->seek(CLI_HEADER, Reader::SeekSet);
- CLIHeaderLocation = reader->readU4();
- reader->seek(textSection->rawAddress +
- (CLIHeaderLocation - textSection->virtualAddress),
- Reader::SeekSet);
-
- cb = reader->readU4();
- major = reader->readU2();
- minor = reader->readU2();
- mdRva = reader->readU4();
- mdSize = reader->readU4();
- flags = reader->readU4();
- entryPoint = reader->readU4();
- resRva = reader->readU4();
- resSize = reader->readU4();
-
- reader->seek(textSection->rawAddress + (mdRva - textSection->virtualAddress),
- Reader::SeekSet);
-
- CLIHeader = new (allocator, "Header") Header();
- CLIHeader->read(allocator, reader, vm);
-
- reader->seek(CLIHeader->tildStream->realOffset, Reader::SeekSet);
-
- readTables(reader);
-
- isRead = 1;
- }
- lockVar->unlock();
- }
-
- return bytes ? (doResolve ? isRead : 1) : 0;
-}
-
-int Assembly::open(const char *ext) {
- lockVar->lock();
- mvm::PrintBuffer _asciiz = mvm::PrintBuffer(name);
- const char* asciiz = _asciiz.cString();
- uint32 alen = strlen(asciiz);
-
- uint32 idx = 0;
-
- while ((bytes == 0) && (idx < vm->assemblyPath.size())) {
- const char* cur = vm->assemblyPath[idx];
- uint32 strLen = strlen(cur);
- char* buf = (char*)alloca(strLen + alen + 16);
-
- if (ext != 0) {
- sprintf(buf, "%s%s.%s", cur, asciiz, ext);
- } else {
- sprintf(buf, "%s%s", cur, asciiz);
- }
-
- bytes = Reader::openFile(allocator, buf);
- ++idx;
- }
- lockVar->unlock();
-
- return bytes ? 1 : 0;
-}
-
-uint32 Assembly::getTypeDefTokenFromMethod(uint32 token) {
- uint32 index = token & 0xffff;
- Table* typeTable = CLIHeader->tables[CONSTANT_TypeDef];
- uint32 nbRows = typeTable->rowsNumber;
- bool found = false;
- uint32 i = 0;
-
- while (!found && (i < nbRows - 1)) {
-
- uint32 myId = typeTable->readIndexInRow(i + 1, CONSTANT_TYPEDEF_METHODLIST,
- bytes);
- uint32 nextId = typeTable->readIndexInRow(i + 2, CONSTANT_TYPEDEF_METHODLIST,
- bytes);
-
- if (index < nextId && index >= myId) {
- found = true;
- } else {
- ++i;
- }
- }
-
- return i + 1 + (CONSTANT_TypeDef << 24);
-}
-
-VMCommonClass* Assembly::readTypeSpec(N3* vm, uint32 index, VMGenericClass* genClass, VMGenericMethod* genMethod) {
- uint32 blobOffset = CLIHeader->blobStream->realOffset;
- Table* typeTable = CLIHeader->tables[CONSTANT_TypeSpec];
- uint32* typeArray = (uint32*)alloca(sizeof(uint32) * typeTable->rowSize);
- typeTable->readRow(typeArray, index, bytes);
-
- uint32 signOffset = typeArray[CONSTANT_TYPESPEC_SIGNATURE];
-
- uint32 offset = blobOffset + signOffset;
- return extractTypeInSignature(offset, genClass, genMethod);
-
-}
-
-VMCommonClass* Assembly::lookupClassFromName(const UTF8* name,
- const UTF8* nameSpace) {
- ClassNameCmp CC(name, nameSpace);
- return loadedNameClasses->lookup(CC);
-}
-
-VMCommonClass* Assembly::lookupClassFromToken(uint32 token) {
- return loadedTokenClasses->lookup(token);
-}
-
-VMMethod* Assembly::lookupMethodFromToken(uint32 token) {
- return loadedTokenMethods->lookup(token);
-}
-VMField* Assembly::lookupFieldFromToken(uint32 token) {
- return loadedTokenFields->lookup(token);
-}
-
-
-
-VMCommonClass* Assembly::getClassFromName(N3* vm, const UTF8* name,
- const UTF8* nameSpace) {
- VMCommonClass* type = lookupClassFromName(name, nameSpace);
-
- if (type == 0) {
- Table* typeTable = CLIHeader->tables[CONSTANT_TypeDef];
- uint32 nb = typeTable->rowsNumber;
- uint32 stringOffset = CLIHeader->stringStream->realOffset;
-
- for (uint32 i = 0; i < nb; ++i) {
- uint32 value = typeTable->readIndexInRow(i + 1, CONSTANT_TYPEDEF_NAME, bytes);
- const UTF8* curName = readString(vm, stringOffset + value);
- if (name == curName) {
- uint32 value = typeTable->readIndexInRow(i + 1,
- CONSTANT_TYPEDEF_NAMESPACE,
- bytes);
- const UTF8* curNameSpace = readString(vm, stringOffset + value);
- if (curNameSpace == nameSpace) {
- return readTypeDef(vm, i + 1);
- }
- }
- }
- }
-
- return type;
-}
-
-Assembly* Assembly::readAssemblyRef(N3* vm, uint32 index) {
- if (assemblyRefs == 0) {
- uint32 size = sizeof(Assembly*)*
- CLIHeader->tables[CONSTANT_AssemblyRef]->rowsNumber;
- assemblyRefs = (Assembly**)malloc(size);
- memset(assemblyRefs, 0, size);
- }
- Assembly* ref = assemblyRefs[index - 1];
- if (ref == 0) {
- uint32 stringOffset = CLIHeader->stringStream->realOffset;
- Table* assTable = CLIHeader->tables[CONSTANT_AssemblyRef];
- uint32* assArray = (uint32*)alloca(sizeof(uint32) * assTable->rowSize);
- assTable->readRow(assArray, index, bytes);
- const UTF8* name =
- readString(vm, stringOffset + assArray[CONSTANT_ASSEMBLY_REF_NAME]);
-
- ref = vm->constructAssembly(name);
-
- if(!ref->resolve(1, "dll"))
- VMThread::get()->getVM()->error("implement me");
-
- assemblyRefs[index - 1] = ref;
- }
- return ref;
-}
-
-VMCommonClass* Assembly::readTypeRef(N3* vm, uint32 index) {
- uint32 stringOffset = CLIHeader->stringStream->realOffset;
-
- Table* typeTable = CLIHeader->tables[CONSTANT_TypeRef];
- uint32* typeArray = (uint32*)alloca(sizeof(uint32) * typeTable->rowSize);
-
- typeTable->readRow(typeArray, index, bytes);
-
- uint32 resScope = typeArray[CONSTANT_TYPEREF_RESOLUTION_SCOPE];
- uint32 name = typeArray[CONSTANT_TYPEREF_NAME];
- uint32 nameSpace = typeArray[CONSTANT_TYPEREF_NAMESPACE];
-
-
- uint32 val = resScope & 3;
- uint32 entry = resScope >> 2;
- VMCommonClass* type = 0;
-
- switch (val) {
- case 0: VMThread::get()->getVM()->error("implement me %d %d", val, entry); break;
- case 1: VMThread::get()->getVM()->error("implement me %d, %d", val, entry); break;
- case 2: {
- Assembly* refAssembly = readAssemblyRef(vm, entry);
- type = refAssembly->getClassFromName(vm, readString(vm, stringOffset + name),
- readString(vm, stringOffset + nameSpace));
- break;
- }
- case 3: VMThread::get()->getVM()->error("implement me %d %d",val, entry); break;
- default:
- VMThread::get()->getVM()->error("unkknown resolution scope %x", val);
- break;
- }
- return type;
-}
-
-VMClass* Assembly::readTypeDef(N3* vm, uint32 index) {
- return readTypeDef(vm, index, (std::vector<VMCommonClass*>) 0);
-}
-
-VMClass* Assembly::readTypeDef(N3* vm, uint32 index, std::vector<VMCommonClass*> genArgs) {
- uint32 token = (CONSTANT_TypeDef << 24) + index;
- uint32 stringOffset = CLIHeader->stringStream->realOffset;
-
- Table* typeTable = CLIHeader->tables[CONSTANT_TypeDef];
- uint32* typeArray = (uint32*)alloca(sizeof(uint32) * typeTable->rowSize);
-
- typeTable->readRow(typeArray, index, bytes);
-
- uint32 flags = typeArray[CONSTANT_TYPEDEF_FLAGS];
- uint32 name = typeArray[CONSTANT_TYPEDEF_NAME];
- uint32 nameSpace = typeArray[CONSTANT_TYPEDEF_NAMESPACE];
- uint32 extends = typeArray[CONSTANT_TYPEDEF_EXTENDS];
- //uint32 fieldList = typeArray[CONSTANT_TYPEDEF_FIELDLIST];
- //uint32 methodList = typeArray[CONSTANT_TYPEDEF_METHODLIST];
-
- //Table* fieldTable = CLIHeader->tables[CONSTANT_Field];
- //uint32 fieldSize = fieldTable->rowsNumber;
- //Table* methodTable = CLIHeader->tables[CONSTANT_MethodDef];
- //uint32 methodSize = methodTable->rowsNumber;
-
- VMClass* type;
-
- if (genArgs == (std::vector<VMCommonClass*>) 0) {
- type = constructClass(readString(vm, name + stringOffset),
- readString(vm, nameSpace + stringOffset),
- token);
- } else {
- // generic type
- type = constructGenericClass(readString(vm, name + stringOffset),
- readString(vm, nameSpace + stringOffset),
- genArgs, token);
- }
-
- type->vm = vm;
-
- uint32 val = 3 & extends;
- uint32 entry = extends >> 2;
-
- switch (val) {
- case 0: {
- type->superToken = entry + (CONSTANT_TypeDef << 24);
- break;
- }
- case 1: {
- type->superToken = entry + (CONSTANT_TypeRef << 24);
- break;
- }
- case 2: {
- VMThread::get()->getVM()->error("implement me");
- break;
- }
- default: {
- VMThread::get()->getVM()->error("implement me");
- break;
- }
- }
-
- getInterfacesFromTokenType(type->interfacesToken, token);
- type->flags = flags;
-
- return type;
-}
-
-void Assembly::getInterfacesFromTokenType(std::vector<uint32>& tokens,
- uint32 token) {
- uint32 index = token & 0xffff;
- Table* interfacesTable = CLIHeader->tables[CONSTANT_InterfaceImpl];
- uint32 nbRows = interfacesTable->rowsNumber;
-
- for (uint32 i = 0; i < nbRows; ++i) {
- uint32 interfaceId =
- interfacesTable->readIndexInRow(i + 1, CONSTANT_INTERFACE_IMPL_CLASS,
- bytes);
- if (interfaceId == index) {
- uint32 cl = interfacesTable->readIndexInRow(i + 1,
- CONSTANT_INTERFACE_IMPL_INTERFACE,
- bytes);
- uint32 table = cl & 3;
- uint32 interfaceToken = cl >> 2;
-
- switch (table) {
- case 0: interfaceToken += (CONSTANT_TypeDef << 24); break;
- case 1: interfaceToken += (CONSTANT_TypeRef << 24); break;
- case 2: interfaceToken += (CONSTANT_TypeSpec << 24); break;
- default: VMThread::get()->getVM()->error("unknown table %x", table); break;
- }
- tokens.push_back(interfaceToken);
- }
- }
-}
-
-VMCommonClass* Assembly::loadType(N3* vm, uint32 token, bool resolve,
- bool resolveStatic, bool clinit, bool dothrow, VMGenericClass* genClass, VMGenericMethod* genMethod) {
- return loadType(vm, token, resolve, resolveStatic, clinit, dothrow, (std::vector<VMCommonClass*>) 0, genClass, genMethod);
-}
-
-
-VMCommonClass* Assembly::loadType(N3* vm, uint32 token, bool resolve,
- bool resolveStatic, bool clinit, bool dothrow,
- std::vector<VMCommonClass*> genArgs, VMGenericClass* genClass, VMGenericMethod* genMethod) {
-
- VMCommonClass* type = lookupClassFromToken(token);
- if (!type || type->status == hashed) {
- uint32 table = token >> 24;
- uint32 index = token & 0xffff;
-
- if (table == CONSTANT_TypeDef) {
- type = readTypeDef(vm, index, genArgs);
- } else if (table == CONSTANT_TypeRef) {
- type = readTypeRef(vm, index);
- } else if (table == CONSTANT_TypeSpec) {
- type = readTypeSpec(vm, index, genClass, genMethod);
- } else {
- VMThread::get()->getVM()->error("implement me %x", token);
- }
- }
-
- if (type == 0) VMThread::get()->getVM()->error("implement me");
- if (type->status == hashed) {
- type->aquire();
- if (type->status == hashed) {
- type->status = loaded;
- }
- type->release();
- }
-
- if (resolve) type->resolveType(resolveStatic, clinit, genMethod);
-
- return type;
-}
-
-void Assembly::readClass(VMCommonClass* cl, VMGenericMethod* genMethod) {
- uint32 index = cl->token & 0xffff;
- Table* typeTable = CLIHeader->tables[CONSTANT_TypeDef];
- uint32 typeSize = typeTable->rowsNumber;
- uint32* typeArray = (uint32*)alloca(sizeof(uint32) * typeTable->rowSize);
- typeTable->readRow(typeArray, index, bytes);
-
- uint32 fieldList = typeArray[CONSTANT_TYPEDEF_FIELDLIST];
- uint32 methodList = typeArray[CONSTANT_TYPEDEF_METHODLIST];
-
- Table* fieldTable = CLIHeader->tables[CONSTANT_Field];
- uint32 fieldSize = fieldTable->rowsNumber;
- Table* methodTable = CLIHeader->tables[CONSTANT_MethodDef];
- uint32 methodSize = methodTable->rowsNumber;
-
- getProperties(cl, static_cast<VMGenericClass*>(cl), genMethod);
-
- if (methodList && methodTable != 0 && methodList <= methodSize) {
- uint32 endMethod = (index == typeSize) ?
- methodSize + 1 :
- typeTable->readIndexInRow(index + 1, CONSTANT_TYPEDEF_METHODLIST,
- bytes);
-
- uint32 nbMethods = endMethod - methodList;
-
- for (uint32 i = 0; i < nbMethods; ++i) {
- VMMethod* meth = readMethodDef(i + methodList, cl, NULL, static_cast<VMGenericClass*>(cl));
-
- if (meth != NULL) {
- if (isStatic(meth->flags)) {
- cl->staticMethods.push_back(meth);
- } else {
- cl->virtualMethods.push_back(meth);
- }
- }
- }
- }
-
- if (fieldList && fieldTable != 0 && fieldList <= fieldSize) {
- uint32 endField = (index == typeSize) ?
- fieldSize + 1 :
- typeTable->readIndexInRow(index + 1, CONSTANT_TYPEDEF_FIELDLIST, bytes);
-
- uint32 nbFields = endField - fieldList;
-
- for (uint32 i = 0; i < nbFields; ++i) {
- VMField* field = readField(i + fieldList, cl, static_cast<VMGenericClass*>(cl), genMethod);
- if (isStatic(field->flags)) {
- cl->staticFields.push_back(field);
- } else {
- cl->virtualFields.push_back(field);
- }
- }
- }
-}
-
-void Assembly::readCustomAttributes(uint32 offset, std::vector<llvm::GenericValue>& args, VMMethod* meth) {
- uncompressSignature(offset);
- uint16 prolog = READ_U2(bytes, offset);
-
- if (prolog != 0x1) VMThread::get()->getVM()->error("unknown prolog");
-
- uint32 start = meth->virt ? 1 : 0;
-
- for (uint32 i = start + 1; i < meth->parameters.size(); ++i) {
- if (meth->parameters[i] == MSCorlib::pSInt32) {
- llvm::GenericValue gv;
- gv.IntVal = llvm::APInt(32, READ_U4(bytes, offset));
- args.push_back(gv);
- } else {
- VMThread::get()->getVM()->error("implement me");
- }
- }
-
-}
-
-ArrayObject* Assembly::getCustomAttributes(uint32 token, VMCommonClass* cl) {
- Table* attrTable = CLIHeader->tables[CONSTANT_CustomAttribute];
- uint32 attrSize = attrTable->rowsNumber;
- uint32* attrArray = (uint32*)alloca(sizeof(uint32) * attrTable->rowSize);
- std::vector<VMObject*> vec;
-
- for (uint32 i = 0; i < attrSize; ++i) {
- attrTable->readRow(attrArray, i + 1, bytes);
- uint32 meth = attrArray[CONSTANT_CUSTOM_ATTRIBUTE_TYPE];
- uint32 table = meth & 7;
- uint32 index = meth >> 3;
- VMMethod* cons = 0;
-
- switch(table) {
- default:
- VMThread::get()->getVM()->error("implement me");
- break;
- case 2:
- cons = getMethodFromToken(index + (CONSTANT_MethodDef << 24), NULL, NULL);
- break;
- case 3:
- cons = getMethodFromToken(index + (CONSTANT_MemberRef << 24), NULL, NULL);
- break;
- }
-
- if (cl == cons->classDef) {
- uint32 blobOffset = CLIHeader->blobStream->realOffset;
- std::vector<llvm::GenericValue> args;
- declare_gcroot(VMObject*, obj) = cons->classDef->doNew();
- args.push_back(llvm::GenericValue(obj));
- readCustomAttributes(blobOffset + attrArray[CONSTANT_CUSTOM_ATTRIBUTE_VALUE], args, cons);
-
- cons->compileToNative()->invokeGeneric(args);
- vec.push_back(obj);
- }
- }
-
- declare_gcroot(ArrayObject*, res) = (ArrayObject*)MSCorlib::arrayObject->doNew(vec.size());
- for (uint32 i = 0; i < vec.size(); ++i)
- res->elements[i] = vec[i];
-
- return res;
-}
-
-void Assembly::getProperties(VMCommonClass* cl, VMGenericClass* genClass, VMGenericMethod *genMethod) {
- uint32 index = cl->token & 0xffff;
- Table* mapTable = CLIHeader->tables[CONSTANT_PropertyMap];
- uint32 mapSize = mapTable->rowsNumber;
-
- Table* propertyTable = CLIHeader->tables[CONSTANT_Property];
- uint32 propertySize = propertyTable->rowsNumber;
-
- uint32 propertyList = 0;
- uint32 i = 0;
-
- while (!propertyList && i != mapSize) {
- uint32 parent = mapTable->readIndexInRow(i + 1,
- CONSTANT_PROPERTY_MAP_PARENT, bytes);
- if (parent == index) {
- propertyList = mapTable->readIndexInRow(i + 1,
- CONSTANT_PROPERTY_MAP_PROPERTY_LIST, bytes);
- } else {
- ++i;
- }
- }
-
- if (propertyList && propertyTable != 0 && propertyList <= propertySize) {
- uint32 endProperty = (i + 1 == mapSize) ?
- propertySize + 1 :
- mapTable->readIndexInRow(i + 2, CONSTANT_PROPERTY_MAP_PROPERTY_LIST,
- bytes);
- uint32 nbProperties = endProperty - propertyList;
-
- for (uint32 j = 0; j < nbProperties; ++j) {
- cl->properties.push_back(readProperty(j + propertyList, cl, genClass, genMethod));
- }
-
- }
-}
-
-Property* Assembly::readProperty(uint32 index, VMCommonClass* cl, VMGenericClass* genClass, VMGenericMethod* genMethod) {
- uint32 stringOffset = CLIHeader->stringStream->realOffset;
- uint32 blobOffset = CLIHeader->blobStream->realOffset;
-
- Table* propTable = CLIHeader->tables[CONSTANT_Property];
- uint32* propArray = (uint32*)alloca(sizeof(uint32) * propTable->rowSize);
-
- propTable->readRow(propArray, index, bytes);
-
- uint32 flags = propArray[CONSTANT_PROPERTY_FLAGS];
- uint32 nameIndex = propArray[CONSTANT_PROPERTY_NAME];
- uint32 type = propArray[CONSTANT_PROPERTY_TYPE];
-
- Property* prop = new(allocator, "Property") Property();
- prop->name = readString(VMThread::get()->getVM(), stringOffset + nameIndex);
- prop->flags = flags;
- prop->type = cl;
- uint32 offset = blobOffset + type;
- prop->virt = extractMethodSignature(offset, cl, prop->parameters, genClass, genMethod);
- return prop;
-}
-
-VMMethod* Assembly::readMethodDef(uint32 index, VMCommonClass* cl,
- std::vector<VMCommonClass*>* genMethodInstantiation, VMGenericClass* genClass) {
- uint32 token = index + (CONSTANT_MethodDef << 24);
- uint32 stringOffset = CLIHeader->stringStream->realOffset;
- uint32 blobOffset = CLIHeader->blobStream->realOffset;
-
- Table* paramTable = CLIHeader->tables[CONSTANT_Param];
- uint32 paramSize = paramTable->rowsNumber;
-
- Table* methTable = CLIHeader->tables[CONSTANT_MethodDef];
- uint32 methodSize = methTable->rowsNumber;
- uint32* methArray = (uint32*)alloca(sizeof(uint32) * methTable->rowSize);
-
- methTable->readRow(methArray, index, bytes);
-
- uint32 rva = methArray[CONSTANT_METHODDEF_RVA];
- uint32 implFlags = methArray[CONSTANT_METHODDEF_IMPLFLAGS];
- uint32 flags = methArray[CONSTANT_METHODDEF_FLAGS];
- uint32 name = methArray[CONSTANT_METHODDEF_NAME];
- uint32 signature = methArray[CONSTANT_METHODDEF_SIGNATURE];
- uint32 paramList = methArray[CONSTANT_METHODDEF_PARAMLIST];
-
- uint32 offset = blobOffset + signature;
-
- VMMethod* meth =
- constructMethod((VMClass*)cl, readString(cl->vm, (name + stringOffset)),
- token, isGenericMethod(offset), genMethodInstantiation, genClass);
-
- offset = blobOffset + signature;
-
- meth->virt = extractMethodSignature(offset, cl, meth->parameters, genClass,
- static_cast<VMGenericMethod*> (meth));
-
- meth->flags = flags;
- meth->implFlags = implFlags;
-
- if (rva) {
- meth->offsetInTextSection = textSection->rawAddress +
- (rva - textSection->virtualAddress);
- } else {
- meth->offsetInTextSection = 0;
- }
-
- if (paramList && paramTable != 0 && paramList <= paramSize) {
- uint32 endParam = (index == methodSize) ?
- paramSize + 1 :
- methTable->readIndexInRow(index + 1, CONSTANT_METHODDEF_PARAMLIST,
- bytes);
-
- uint32 nbParams = endParam - paramList;
-
- for (uint32 j = 0; j < nbParams; ++j) {
- meth->params.push_back(readParam(j + paramList, meth));
- }
- }
-
- return meth;
-}
-
-VMField* Assembly::readField(uint32 index, VMCommonClass* cl, VMGenericClass* genClass, VMGenericMethod* genMethod) {
- uint32 token = index + (CONSTANT_Field << 24);
- uint32 stringOffset = CLIHeader->stringStream->realOffset;
- uint32 blobOffset = CLIHeader->blobStream->realOffset;
-
- Table* fieldTable = CLIHeader->tables[CONSTANT_Field];
- uint32* fieldArray = (uint32*)alloca(sizeof(uint32) * fieldTable->rowSize);
-
- fieldTable->readRow(fieldArray, index, bytes);
-
- uint32 flags = fieldArray[CONSTANT_FIELD_FLAGS];
- uint32 name = fieldArray[CONSTANT_FIELD_NAME];
- uint32 signature = fieldArray[CONSTANT_FIELD_SIGNATURE];
-
- uint32 offset = blobOffset + signature;
- VMField* field = constructField((VMClass*) cl, readString(cl->vm, (name
- + stringOffset)), extractFieldSignature(offset, genClass, genMethod),
- token, genClass, genMethod);
- field->flags = flags;
-
- return field;
-}
-
-Param* Assembly::readParam(uint32 index, VMMethod* meth) {
- uint32 stringOffset = CLIHeader->stringStream->realOffset;
-
- Table* paramTable = CLIHeader->tables[CONSTANT_Param];
- uint32* paramArray = (uint32*)alloca(sizeof(uint32) * paramTable->rowSize);
-
- paramTable->readRow(paramArray, index, bytes);
-
- uint32 flags = paramArray[CONSTANT_PARAM_FLAGS];
- uint32 name = paramArray[CONSTANT_PARAM_NAME];
- uint32 sequence = paramArray[CONSTANT_PARAM_SEQUENCE];
-
- Param* param = new(allocator, "Param") Param();
- param->flags = flags;
- param->sequence = sequence;
- param->name = readString(meth->classDef->vm, stringOffset + name);
- param->method = meth;
-
- return param;
-}
-
-VMCommonClass* Assembly::loadTypeFromName(const UTF8* name,
- const UTF8* nameSpace,
- bool resolve, bool unify,
- bool clinit, bool dothrow) {
- VMCommonClass* cl = lookupClassFromName(name, nameSpace);
- if (cl == 0 || cl->status == hashed) {
- cl = getClassFromName(((N3*)VMThread::get()->getVM()), name, nameSpace);
-
- if (cl == 0) VMThread::get()->getVM()->error("implement me");
-
- if (cl->status == hashed) {
- cl->aquire();
- if (cl->status == hashed) {
- cl->status = loaded;
- }
- cl->release();
- }
- }
-
- if (resolve) cl->resolveType(unify, clinit, NULL);
-
- return cl;
-}
-
-void Assembly::readSignature(uint32 localVarSig,
- std::vector<VMCommonClass*>& locals, VMGenericClass* genClass, VMGenericMethod* genMethod) {
- uint32 table = localVarSig >> 24;
- uint32 index = localVarSig & 0xffff;
- if (table != CONSTANT_StandaloneSig) {
- VMThread::get()->getVM()->error("locals do not point to a StandAloneSig table");
- }
- Table* signatures = CLIHeader->tables[CONSTANT_StandaloneSig];
- uint32* array = (uint32*)alloca(sizeof(uint32) * signatures->rowSize);
- signatures->readRow(array, index, bytes);
-
- uint32 blobOffset = CLIHeader->blobStream->realOffset;
- uint32 blobEntry = blobOffset + array[CONSTANT_STANDALONE_SIG_SIGNATURE];
-
-
- localVarSignature(blobEntry, locals, genClass, genMethod);
-}
-
-VMField* Assembly::getFieldFromToken(uint32 token, bool stat, VMGenericClass* genClass, VMGenericMethod* genMethod) {
- VMField* field = lookupFieldFromToken(token);
- if (!field) {
- uint32 table = token >> 24;
- switch (table) {
- case CONSTANT_Field : {
- uint32 typeToken = getTypedefTokenFromField(token);
- uint32 newTable = typeToken >> 24;
- switch (newTable) {
- case CONSTANT_TypeDef : {
- loadType((N3*)(VMThread::get()->getVM()), typeToken, true, true, false,
- true, genClass, genMethod);
- field = lookupFieldFromToken(token);
- if (!field) {
- VMThread::get()->getVM()->error("implement me");
- }
- break;
- }
- default : {
- VMThread::get()->getVM()->error("implement me");
- }
- }
- break;
- }
-
- case CONSTANT_MemberRef : {
- field = readMemberRefAsField(token, stat, genClass, genMethod);
- break;
- }
-
- default : {
- VMThread::get()->getVM()->error("implement me");
- }
- }
- }
- field->classDef->resolveType(stat, false, genMethod);
- return field;
-}
-
-uint32 Assembly::getTypedefTokenFromField(uint32 token) {
- uint32 index = token & 0xffff;
- Table* typeTable = CLIHeader->tables[CONSTANT_TypeDef];
- uint32 nbRows = typeTable->rowsNumber;
-
- bool found = false;
- uint32 i = 0;
-
- while (!found && i < nbRows - 1) {
- uint32 myId = typeTable->readIndexInRow(i + 1, CONSTANT_TYPEDEF_FIELDLIST, bytes);
- uint32 nextId = typeTable->readIndexInRow(i + 2, CONSTANT_TYPEDEF_FIELDLIST, bytes);
-
- if ((index < nextId) && (index >= myId)) {
- found = true;
- } else {
- ++i;
- }
- }
-
- return i + 1 + (CONSTANT_TypeDef << 24);
-}
-
-uint32 Assembly::getExplicitLayout(uint32 token) {
- uint32 index = token & 0xffff;
- Table* layoutTable = CLIHeader->tables[CONSTANT_ClassLayout];
- uint32 tableSize = layoutTable->rowsNumber;
-
- bool found = false;
- uint32 i = 0;
- uint32 size = 0;
-
- while (!found && i != tableSize) {
- uint32 parent = layoutTable->readIndexInRow(i + 1,
- CONSTANT_CLASS_LAYOUT_PARENT, bytes);
- if (parent == index) {
- found = true;
- size = layoutTable->readIndexInRow(i + 1,
- CONSTANT_CLASS_LAYOUT_CLASS_SIZE, bytes);
- }
- ++i;
- }
-
- if (!found)
- VMThread::get()->getVM()->error("implement me");
-
- return size;
-}
-
-VMField* Assembly::readMemberRefAsField(uint32 token, bool stat, VMGenericClass* genClass, VMGenericMethod* genMethod) {
- uint32 index = token & 0xffff;
- Table* memberTable = CLIHeader->tables[CONSTANT_MemberRef];
- uint32* memberArray = (uint32*)alloca(sizeof(uint32) * memberTable->rowSize);
-
- memberTable->readRow(memberArray, index, bytes);
-
- uint32 stringOffset = CLIHeader->stringStream->realOffset;
- uint32 blobOffset = CLIHeader->blobStream->realOffset;
-
- const UTF8* name = readString((N3*)(VMThread::get()->getVM()), stringOffset +
- memberArray[CONSTANT_MEMBERREF_NAME]);
-
-
- uint32 value = memberArray[CONSTANT_MEMBERREF_CLASS];
- uint32 table = value & 7;
- index = value >> 3;
-
- VMCommonClass* type = NULL;
-
- switch (table) {
- case 0 : {
- uint32 typeToken = index + (CONSTANT_TypeDef << 24);
- type = loadType(((N3*)VMThread::get()->getVM()), typeToken,
- true, false, false, true, genClass, genMethod);
- break;
- }
-
- case 1 : {
- uint32 typeToken = index + (CONSTANT_TypeRef << 24);
- type = loadType(((N3*)VMThread::get()->getVM()), typeToken,
- true, false, false, true, genClass, genMethod);
- break;
- }
-
- case 2:
- case 3: VMThread::get()->getVM()->error("implement me"); break;
- case 4: {
- uint32 typeToken = index + (CONSTANT_TypeSpec << 24);
- type = loadType(((N3*)VMThread::get()->getVM()), typeToken,
- true, false, false, true, genClass, genMethod);
- break;
- }
- default:
- VMThread::get()->getVM()->error("unknown MemberRefParent tag %d", table);
-
- }
-
- uint32 offset = blobOffset + memberArray[CONSTANT_MEMBERREF_SIGNATURE];
-
- VMGenericClass* genericClass = static_cast<VMGenericClass*> (type);
-
- if (genericClass) {
- VMCommonClass* signature = extractFieldSignature(offset, genericClass,
- genMethod);
- VMField* field = type->lookupField(name, signature, stat, true);
- return field;
- } else {
- VMCommonClass* signature = extractFieldSignature(offset, genClass, genMethod);
- VMField* field = type->lookupField(name, signature, stat, true);
- return field;
- }
-
-}
-
-
-VMMethod* Assembly::getMethodFromToken(uint32 token, VMGenericClass* genClass, VMGenericMethod* genMethod) {
- VMMethod* meth = lookupMethodFromToken(token);
-
- if (!meth) {
- uint32 table = token >> 24;
- switch (table) {
- case CONSTANT_MethodDef : {
- uint32 typeToken = getTypedefTokenFromMethod(token);
- uint32 newTable = typeToken >> 24;
- switch (newTable) {
- case CONSTANT_TypeDef : {
- loadType((N3*)(VMThread::get()->getVM()), typeToken, true, true, false,
- true, genClass, genMethod);
- meth = lookupMethodFromToken(token);
- if (!meth) {
- VMThread::get()->getVM()->error("implement me");
- }
- break;
- }
- default : {
- VMThread::get()->getVM()->error("implement me");
- }
- }
- break;
- }
-
- case CONSTANT_MemberRef : {
- meth = readMemberRefAsMethod(token, NULL, genClass, genMethod);
- break;
- }
-
- case CONSTANT_MethodSpec : {
- meth = readMethodSpec(token, genClass, genMethod);
- break;
- }
-
- default : {
- VMThread::get()->getVM()->error("implement me");
- }
- }
- }
-
- meth->getSignature(genMethod);
-
- return meth;
-}
-
-uint32 Assembly::getTypedefTokenFromMethod(uint32 token) {
- uint32 index = token & 0xffff;
- Table* typeTable = CLIHeader->tables[CONSTANT_TypeDef];
- uint32 nbRows = typeTable->rowsNumber;
-
- bool found = false;
- uint32 i = 0;
-
- while (!found && i < nbRows - 1) {
- uint32 myId = typeTable->readIndexInRow(i + 1, CONSTANT_TYPEDEF_METHODLIST, bytes);
- uint32 nextId = typeTable->readIndexInRow(i + 2, CONSTANT_TYPEDEF_METHODLIST, bytes);
-
- if ((index < nextId) && (index >= myId)) {
- found = true;
- } else {
- ++i;
- }
- }
-
- return i + 1 + (CONSTANT_TypeDef << 24);
-}
-
-VMMethod *Assembly::instantiateGenericMethod(
- std::vector<VMCommonClass*> *genArgs, VMCommonClass *type,
- const UTF8 *& name, std::vector<VMCommonClass*> & args, uint32 token,
- bool virt, VMGenericClass* genClass) {
- VMMethod *meth = NULL;
-
- if (genArgs != NULL) {
- VMClass* cl = static_cast<VMClass*> (type);
-
- if (cl == NULL) {
- VMThread::get()->getVM()->error(
- "Only instances of generic classes are allowed.");
- }
-
- // search for matching signature
- for (uint i = 0; i < cl->genericMethods.size(); ++i) {
- VMMethod* genMethod = cl->genericMethods.at(i);
-
- if ((name != genMethod->name) || !genMethod->signatureEqualsGeneric(
- args)) {
- continue;
- }
-
- // use found token to create instance of generic method
- meth = readMethodDef(genMethod->token & 0xFFFFFF, type, genArgs, genClass);
- meth->token = token;
- }
- } else {
- meth = type->lookupMethod(name, args, !virt, true);
- }
-
- return meth;
-}
-
-VMMethod* Assembly::readMemberRefAsMethod(uint32 token, std::vector<VMCommonClass*>* genArgs, VMGenericClass* genClass, VMGenericMethod* genMethod) {
- uint32 index = token & 0xffff;
- Table* memberTable = CLIHeader->tables[CONSTANT_MemberRef];
- uint32* memberArray = (uint32*)alloca(sizeof(uint32) * memberTable->rowSize);
-
- memberTable->readRow(memberArray, index, bytes);
-
- uint32 stringOffset = CLIHeader->stringStream->realOffset;
- uint32 blobOffset = CLIHeader->blobStream->realOffset;
-
- const UTF8* name = readString((N3*)(VMThread::get()->getVM()), stringOffset +
- memberArray[CONSTANT_MEMBERREF_NAME]);
-
- uint32 offset = blobOffset + memberArray[CONSTANT_MEMBERREF_SIGNATURE];
- std::vector<VMCommonClass*> args;
-
-
- uint32 value = memberArray[CONSTANT_MEMBERREF_CLASS];
- uint32 table = value & 7;
- index = value >> 3;
-
- switch (table) {
- case 0 : {
- uint32 typeToken = index + (CONSTANT_TypeDef << 24);
- VMCommonClass* type = loadType(((N3*)(VMThread::get()->getVM())), typeToken, true, false, false, true, genClass, genMethod);
- bool virt = extractMethodSignature(offset, type, args, genClass, genMethod);
- VMMethod *meth = instantiateGenericMethod(genArgs, type, name, args, token, virt, genClass);
- return meth;
- }
-
- case 1 : {
- uint32 typeToken = index + (CONSTANT_TypeRef << 24);
- VMCommonClass* type = loadType(((N3*)VMThread::get()->getVM()), typeToken,
- true, false, false, true, genClass, genMethod);
- bool virt = extractMethodSignature(offset, type, args, genClass, genMethod);
- VMMethod *meth = instantiateGenericMethod(genArgs, type, name, args, token, virt, genClass);
- return meth;
- }
-
- case 2:
- case 3: VMThread::get()->getVM()->error("implement me %d", table); break;
- case 4: {
- VMClass* type = (VMClass*) readTypeSpec(vm, index, genClass, genMethod);
-
- VMGenericClass* genClass = static_cast<VMGenericClass*> (type);
-
- if (genClass) {
- type->resolveType(false, false, genMethod);
-
- bool virt = extractMethodSignature(offset, type, args, genClass, genMethod);
- VMMethod* meth = instantiateGenericMethod(genArgs, type, name, args,
- token, virt, genClass);
-
- return meth;
- } else {
- type->resolveType(false, false, genMethod);
-
- VMMethod* meth = new(allocator, "VMMethod") VMMethod() ;
- bool virt = extractMethodSignature(offset, type, args, genClass, genMethod);
- bool structReturn = false;
- const llvm::FunctionType* signature = VMMethod::resolveSignature(args,
- virt, structReturn, genMethod);
- meth->_signature = signature;
- meth->classDef = type;
- meth->name = name;
- meth->virt = virt;
- meth->structReturn = structReturn;
- meth->parameters = args; // TODO check whether this fix is correct
- return meth;
- }
- }
- default:
- VMThread::get()->getVM()->error("unknown MemberRefParent tag %d", table);
-
- }
-
- return 0;
-}
-
-VMMethod* Assembly::readMethodSpec(uint32 token, VMGenericClass* genClass, VMGenericMethod* genMethod) {
- uint32 index = token & 0xffff;
- uint32 blobOffset = CLIHeader->blobStream->realOffset;
-
- Table* methodTable = CLIHeader->tables[CONSTANT_MethodSpec];
- uint32* methodArray = (uint32*) alloca(sizeof(uint32) * methodTable->rowSize);
-
- methodTable->readRow(methodArray, index, bytes);
-
- uint32 method = methodArray[CONSTANT_METHOD_SPEC_METHOD];
- uint32 instantiation = methodArray[CONSTANT_METHOD_SPEC_INSTANTIATION];
-
- uint32 offset = blobOffset + instantiation;
-
- std::vector<VMCommonClass*> genArgs;
- methodSpecSignature(offset, genArgs, genClass, genMethod);
-
- uint32 table = method & 1;
- index = method >> 1;
-
- uint32 methodToken;
-
- switch (table) {
- case 0 : {
- methodToken = index + (CONSTANT_MethodDef << 24);
- VMThread::get()->getVM()->error("implement me");
- break;
- }
- case 1 : {
- methodToken = index + (CONSTANT_MemberRef << 24);
- return readMemberRefAsMethod(methodToken, &genArgs, genClass, genMethod);
- }
- default:
- VMThread::get()->getVM()->error("Invalid MethodSpec!");
- }
-
- return NULL;
-}
-
-const ArrayChar* Assembly::readUserString(uint32 token) {
- uint32 offset = CLIHeader->usStream->realOffset + token;
-
- uint8 size = READ_U1(bytes, offset);
- if (size >> 7) {
- if ((size >> 6) == 3) {
- uint32 size1 = READ_U1(bytes, offset);
- uint32 size2 = READ_U1(bytes, offset);
- uint32 size3 = READ_U1(bytes, offset);
- size = ((size ^ 0xc0) << 24) + (size1 << 16) + (size2 << 8) + size3;
- } else {
- size = ((size ^ 0x80) << 8) + READ_U1(bytes, offset);
- }
- }
-
- declare_gcroot(const ArrayChar*, res) = readUTF16((N3*)(VMThread::get()->getVM()), size, bytes, offset);
- return res;
-}
-
-uint32 Assembly::getRVAFromField(uint32 token) {
-
- uint32 index = token & 0xffff;
- Table* rvaTable = CLIHeader->tables[CONSTANT_FieldRVA];
- uint32 rvaSize = rvaTable->rowsNumber;
-
- uint32 i = 0;
- bool found = false;
-
- while (!found && i != rvaSize) {
- uint32 fieldId = rvaTable->readIndexInRow(i + 1, CONSTANT_FIELD_RVA_FIELD,
- bytes);
- if (fieldId == index) {
- found = true;
- } else {
- ++i;
- }
- }
- if (!found) {
- return 0;
- } else {
- return rvaTable->readIndexInRow(i + 1, CONSTANT_FIELD_RVA_RVA, bytes);
- }
-}
-
diff --git a/vmkit/lib/N3/VMCore/Assembly.h b/vmkit/lib/N3/VMCore/Assembly.h
deleted file mode 100644
index 93f2c6c..0000000
--- a/vmkit/lib/N3/VMCore/Assembly.h
+++ /dev/null
@@ -1,737 +0,0 @@
-//===---------- Assembly.h - Definition of an assembly --------------------===//
-//
-// N3
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-
-#ifndef N3_ASSEMBLY_H
-#define N3_ASSEMBLY_H
-
-#include <vector>
-
-#include "types.h"
-
-#include "mvm/Object.h"
-#include "mvm/Threads/Locks.h"
-#include "mvm/Threads/Cond.h"
-
-#include "llvm/DerivedTypes.h"
-#include "llvm/Type.h"
-
-#include "VMArray.h"
-
-namespace llvm {
- class GenericValue;
-}
-
-namespace mvm {
- class UTF8;
- class UTF8Map;
-}
-
-namespace n3 {
-
-using mvm::UTF8;
-using mvm::UTF8Map;
-
-class ArrayChar;
-class ArrayObject;
-class Assembly;
-class ClassNameMap;
-class ClassTokenMap;
-class FieldTokenMap;
-class MethodTokenMap;
-class N3;
-class Param;
-class Property;
-class Reader;
-class VMClass;
-class VMGenericClass;
-class VMClassArray;
-class VMClassPointer;
-class VMCommonClass;
-class VMField;
-class VMMethod;
-class VMObject;
-class VMGenericClass;
-class VMGenericMethod;
-class ByteCode;
-
-class Section : public mvm::PermanentObject {
-public:
- virtual void print(mvm::PrintBuffer* buf) const;
-
- char* name;
- uint32 virtualSize;
- uint32 virtualAddress;
- uint32 rawSize;
- uint32 rawAddress;
- uint32 relocAddress;
- uint32 lineNumbers;
- uint32 relocationsNumber;
- uint32 lineNumbersNumber;
- uint32 characteristics;
-
- void read(Reader* reader, N3* vm);
-};
-
-class Stream : public mvm::PermanentObject {
-public:
- virtual void print(mvm::PrintBuffer* buf) const;
-
- char* name;
- uint32 realOffset;
- uint32 size;
-};
-
-class Table : public mvm::PermanentObject {
-public:
- virtual void print(mvm::PrintBuffer* buf) const;
-
- uint32 offset;
- uint32 rowsNumber;
- uint32 rowSize;
- uint32 count;
- uint32 sizeMask;
-
- void readRow(uint32* result, uint32 row, ByteCode* array);
- uint32 readIndexInRow(uint32 row, uint32 index, ByteCode* array);
-
-};
-
-
-class Header : public mvm::PermanentObject {
-public:
- virtual void print(mvm::PrintBuffer* buf) const;
-
- uint32 signature;
- uint32 major;
- uint32 minor;
- uint32 reserved;
- uint32 versionLength;
- uint32 flags;
- uint32 nbStreams;
-
- const UTF8* versionName;
- Stream* tildStream;
- Stream* stringStream;
- Stream* usStream;
- Stream* blobStream;
- Stream* guidStream;
- std::vector<Table*, gc_allocator<Table*> > tables;
-
- void read(mvm::BumpPtrAllocator &allocator, Reader* reader, N3* vm);
-};
-
-typedef void (*maskVector_t)(uint32 index,
- std::vector<Table*, gc_allocator<Table*> >& tables,
- uint32 heapSizes);
-
-typedef VMCommonClass* (*signatureVector_t)(uint32 op, Assembly* ass,
- uint32& offset, VMGenericClass* genClass, VMGenericMethod* genMethod);
-
-class Assembly : public mvm::PermanentObject {
-public:
- virtual void print(mvm::PrintBuffer* buf) const;
- virtual void TRACER;
-
- VMClassPointer* constructPointer(VMCommonClass* base, uint32 dims);
- VMClassArray* constructArray(VMCommonClass* base, uint32 dims);
- VMClassArray* constructArray(const UTF8* name, const UTF8* nameSpace,
- uint32 dims);
- VMClass* constructClass(const UTF8* name,
- const UTF8* nameSpace, uint32 token);
- VMGenericClass* constructGenericClass(const UTF8* name,
- const UTF8* nameSpace,
- std::vector<VMCommonClass*> genArgs,
- uint32 token);
- VMField* constructField(VMClass* cl, const UTF8* name,
- VMCommonClass* signature, uint32 token, VMGenericClass* genClass, VMGenericMethod* genMethod);
- VMMethod* constructMethod(VMClass* cl, const UTF8* name,
- uint32 token, bool generic, std::vector<VMCommonClass*>* genMethodInstantiation, VMGenericClass* genClass);
- VMCommonClass* lookupClassFromName(const UTF8* name, const UTF8* nameSpace);
- VMCommonClass* lookupClassFromToken(uint32 token);
- VMMethod* lookupMethodFromToken(uint32 token);
- VMField* lookupFieldFromToken(uint32 token);
-
- VMObject* getAssemblyDelegatee();
-
- ClassNameMap* loadedNameClasses;
- ClassTokenMap* loadedTokenClasses;
- MethodTokenMap* loadedTokenMethods;
- FieldTokenMap* loadedTokenFields;
-
- N3* vm;
- mvm::Lock* lockVar;
- mvm::Cond* condVar;
- const UTF8* name;
- ByteCode* bytes;
- Section* textSection;
- Section* rsrcSection;
- Section* relocSection;
- Header* CLIHeader;
- VMObject* ooo_delegatee;
- Assembly** assemblyRefs;
-
- uint32 CLIHeaderLocation;
- volatile bool isRead;
- uint32 cb;
- uint32 major;
- uint32 minor;
- uint32 mdRva;
- uint32 mdSize;
- uint32 flags;
- uint32 entryPoint;
- uint32 resRva;
- uint32 resSize;
-
- mvm::BumpPtrAllocator &allocator;
-
- Assembly(mvm::BumpPtrAllocator &Alloc, N3 *vm, const UTF8* name);
-
- int open(const char *ext);
- int resolve(int doResolve, const char *ext);
-
- static const UTF8* readUTF8(N3* vm, uint32 len, Reader* reader);
- static const UTF8* readUTF8(N3* vm, uint32 len, ByteCode* bytes, uint32& offset);
- static const ArrayChar* readUTF16(N3* vm, uint32 len, Reader* reader);
- static const ArrayChar* readUTF16(N3* vm, uint32 len, ByteCode* bytes, uint32& offset);
- const UTF8* readString(N3* vm, uint32 offset);
- void readTables(Reader* reader);
-
- static maskVector_t maskVector[64];
- static const char* maskVectorName[64];
- static signatureVector_t signatureVector[0x46];
- static const char* signatureNames[0x46];
-
-
- Reader *newReader(ByteCode* array, uint32 start = 0, uint32 end = 0);
-
- uint32 uncompressSignature(uint32& offset);
- uint32 getTypeDefTokenFromMethod(uint32 token);
- VMCommonClass* loadType(N3* vm, uint32 token, bool resolveFunc, bool resolve,
- bool clinit, bool dothrow, VMGenericClass* genClass, VMGenericMethod* genMethod);
- VMCommonClass* loadType(N3* vm, uint32 token, bool resolveFunc, bool resolve,
- bool clinit, bool dothrow, std::vector<VMCommonClass*> genArgs, VMGenericClass* genClass, VMGenericMethod* genMethod);
-
- VMCommonClass* loadTypeFromName(const UTF8* name, const UTF8* nameSpace,
- bool resolveFunc, bool resolve,
- bool clinit, bool dothrow);
- void readClass(VMCommonClass* cl, VMGenericMethod* genMethod);
- void getProperties(VMCommonClass* cl, VMGenericClass* genClass, VMGenericMethod* genMethod);
- Property* readProperty(uint32 index, VMCommonClass* cl, VMGenericClass* genClass, VMGenericMethod* genMethod);
- VMMethod* readMethodDef(uint32 index, VMCommonClass* cl,
- std::vector<VMCommonClass*>* genMethodInstantiation, VMGenericClass* genClass);
- VMMethod* readMethodSpec(uint32 token, VMGenericClass* genClass, VMGenericMethod* genMethod);
- VMField* readField(uint32 index, VMCommonClass* cl, VMGenericClass* genClass, VMGenericMethod* genMethod);
- Param* readParam(uint32 index, VMMethod* meth);
- VMClass* readTypeDef(N3* vm, uint32 index);
- VMClass* readTypeDef(N3* vm, uint32 index, std::vector<VMCommonClass*> genArgs);
- VMCommonClass* readTypeSpec(N3* vm, uint32 index, VMGenericClass* genClass, VMGenericMethod* genMethod);
- Assembly* readAssemblyRef(N3* vm, uint32 index);
- VMCommonClass* readTypeRef(N3* vm, uint32 index);
- void readSignature(uint32 offset, std::vector<VMCommonClass*>& locals, VMGenericClass* genClass, VMGenericMethod* genMethod);
-
- void getInterfacesFromTokenType(std::vector<uint32>& tokens, uint32 token);
-
- bool extractMethodSignature(uint32& offset, VMCommonClass* cl,
- std::vector<VMCommonClass*> ¶ms, VMGenericClass* genClass, VMGenericMethod* genMethod);
- bool isGenericMethod(uint32& offset);
- void localVarSignature(uint32& offset,
- std::vector<VMCommonClass*>& locals, VMGenericClass* genClass, VMGenericMethod* genMethod);
- void methodSpecSignature(uint32& offset,
- std::vector<VMCommonClass*>& genArgs, VMGenericClass* genClass, VMGenericMethod* genMethod);
- VMCommonClass* extractFieldSignature(uint32& offset, VMGenericClass* genClass, VMGenericMethod* genMethod);
- VMCommonClass* extractTypeInSignature(uint32& offset, VMGenericClass* genClass, VMGenericMethod* genMethod);
- VMCommonClass* exploreType(uint32& offset, VMGenericClass* genClass, VMGenericMethod* genMethod);
-
- VMCommonClass* getClassFromName(N3* vm, const UTF8* name, const UTF8* nameSpace);
-
- VMField* getFieldFromToken(uint32 token, bool stat, VMGenericClass* genClass, VMGenericMethod* genMethod);
- uint32 getTypedefTokenFromField(uint32 token);
- VMField* readMemberRefAsField(uint32 token, bool stat, VMGenericClass* genClass, VMGenericMethod* genMethod);
-
- VMMethod* getMethodFromToken(uint32 token, VMGenericClass* genClass, VMGenericMethod* genMethod);
- uint32 getTypedefTokenFromMethod(uint32 token);
- VMMethod* readMemberRefAsMethod(uint32 token, std::vector<VMCommonClass*>* genArgs, VMGenericClass* genClass, VMGenericMethod* genMethod);
-
- const ArrayChar* readUserString(uint32 token);
- uint32 getExplicitLayout(uint32 token);
- uint32 getRVAFromField(uint32 token);
-
- static Assembly* getCallingAssembly();
- static Assembly* getExecutingAssembly();
-
- void readCustomAttributes(uint32 offset, std::vector<llvm::GenericValue>& args, VMMethod* meth);
- ArrayObject* getCustomAttributes(uint32 token, VMCommonClass* cl);
-private:
- VMMethod *instantiateGenericMethod(std::vector<VMCommonClass*> *genArgs, VMCommonClass *type, const UTF8 *& name, std::vector<VMCommonClass*> & args, uint32 token, bool virt, VMGenericClass* genClass);
-
-};
-
-
-#define CONSTANT_Assembly 0x20
-#define CONSTANT_AssemblyOS 0x22
-#define CONSTANT_AssemblyProcessor 0x21
-#define CONSTANT_AssemblyRef 0x23
-#define CONSTANT_AssemblyRefOS 0x25
-#define CONSTANT_AssemblyRefProcessor 0x24
-#define CONSTANT_ClassLayout 0x0F
-#define CONSTANT_Constant 0x0B
-#define CONSTANT_CustomAttribute 0x0C
-#define CONSTANT_DeclSecurity 0x0E
-#define CONSTANT_EventMap 0x12
-#define CONSTANT_Event 0x14
-#define CONSTANT_ExportedType 0x27
-#define CONSTANT_Field 0x04
-#define CONSTANT_FieldLayout 0x10
-#define CONSTANT_FieldMarshal 0x0D
-#define CONSTANT_FieldRVA 0x1D
-#define CONSTANT_File 0x26
-#define CONSTANT_GenericParam 0x2A
-#define CONSTANT_GenericParamConstraint 0x2C
-#define CONSTANT_ImplMap 0x1C
-#define CONSTANT_InterfaceImpl 0x09
-#define CONSTANT_ManifestResource 0x28
-#define CONSTANT_MemberRef 0x0A
-#define CONSTANT_MethodDef 0x06
-#define CONSTANT_MethodImpl 0x19
-#define CONSTANT_MethodSemantics 0x18
-#define CONSTANT_MethodSpec 0x2B
-#define CONSTANT_Module 0x00
-#define CONSTANT_ModuleRef 0x1A
-#define CONSTANT_NestedClass 0x29
-#define CONSTANT_Param 0x08
-#define CONSTANT_Property 0x17
-#define CONSTANT_PropertyMap 0x15
-#define CONSTANT_StandaloneSig 0x11
-#define CONSTANT_TypeDef 0x02
-#define CONSTANT_TypeRef 0x01
-#define CONSTANT_TypeSpec 0x1B
-
-
-#define CONSTANT_HasThis 0x20
-#define CONSTANT_ExplicitThis 0x40
-#define CONSTANT_Default 0x0
-#define CONSTANT_Vararg 0x5
-#define CONSTANT_C 0x1
-#define CONSTANT_StdCall 0x2
-#define CONSTANT_ThisCall 0x3
-#define CONSTANT_FastCall 0x4
-#define CONSTANT_Generic 0x10
-#define CONSTANT_Sentinel 0x41
-
-
-#define CONSTANT_CorILMethod_TinyFormat 0x2
-#define CONSTANT_CorILMethod_FatFormat 0x3
-#define CONSTANT_CorILMethod_MoreSects 0x8
-#define CONSTANT_CorILMethod_InitLocals 0x10
-#define CONSTANT_CorILMethod_Sect_FatFormat 0x40
-#define CONSTANT_COR_ILEXCEPTION_CLAUSE_EXCEPTION 0x0000
-#define CONSTANT_COR_ILEXCEPTION_CLAUSE_FILTER 0x0001
-#define CONSTANT_COR_ILEXCEPTION_CLAUSE_FINALLY 0x0002
-#define CONSTANT_COR_ILEXCEPTION_CLAUSE_FAULT 0x0004
-
-
-#define CLI_HEADER 0x168
-#define TEXT_SECTION_HEADER 0x178
-#define RSRC_SECTION_HEADER 0x178
-#define RELOC_SECTION_HEADER 0x178
-#define SECTION_NAME_LENGTH 8
-#define TABLE_MAX 64
-#define NB_TABLES 41
-
-#define INT16(offset) \
- rowSize += 2; \
- bitmask = bitmask | (1 << (offset << 1));
-
-#define INT32(offset) \
- rowSize += 4; \
- bitmask = bitmask | (3 << (offset << 1));
-
-
-#define STRING(offset) { \
- uint32 fieldSize = 0; \
- if (heapSizes & 0x01) { \
- fieldSize = 4; \
- } else { \
- fieldSize = 2; \
- } \
- rowSize += fieldSize; \
- bitmask = bitmask | ((fieldSize - 1) << (offset << 1)); \
-}
-
-#define GUID(offset) { \
- uint32 fieldSize = 0; \
- if (heapSizes & 0x02) { \
- fieldSize = 4; \
- } else { \
- fieldSize = 2; \
- } \
- rowSize += fieldSize; \
- bitmask = bitmask | ((fieldSize - 1) << (offset << 1)); \
-}
-
-#define BLOB(offset) { \
- uint32 fieldSize = 0; \
- if (heapSizes & 0x04) { \
- fieldSize = 4; \
- } else { \
- fieldSize = 2; \
- } \
- rowSize += fieldSize; \
- bitmask = bitmask | ((fieldSize - 1) << (offset << 1)); \
-}
-
-#define TABLE(table, offset) { \
- uint32 fieldSize = 0; \
- if (tables[table]->rowsNumber < 0x10000) { \
- fieldSize = 2; \
- } else { \
- fieldSize = 4; \
- } \
- rowSize += fieldSize; \
- bitmask = bitmask | ((fieldSize - 1) << (offset << 1)); \
-}
-
-
-#define TYPEDEF_OR_REF(offset) { \
- uint32 fieldSize = 0; \
- if (tables[CONSTANT_TypeDef]->rowsNumber < 0x4000 && \
- tables[CONSTANT_TypeRef]->rowsNumber < 0x4000 && \
- tables[CONSTANT_TypeSpec]->rowsNumber < 0x4000) { \
- fieldSize = 2; \
- } else { \
- fieldSize = 4; \
- } \
- rowSize += fieldSize; \
- bitmask = bitmask | ((fieldSize - 1) << (offset << 1)); \
-}
-
-
-#define HAS_CONSTANT(offset) { \
- uint32 fieldSize = 0; \
- if (tables[CONSTANT_Field]->rowsNumber < 0x4000 && \
- tables[CONSTANT_Param]->rowsNumber < 0x4000 && \
- tables[CONSTANT_Property]->rowsNumber < 0x4000) { \
- fieldSize = 2; \
- } else { \
- fieldSize = 4; \
- } \
- rowSize += fieldSize; \
- bitmask = bitmask | ((fieldSize - 1) << (offset << 1)); \
-}
-
-#define HAS_CUSTOM_ATTRIBUTE(offset) { \
- uint32 fieldSize = 0; \
- if (tables[CONSTANT_MethodDef]->rowsNumber < 0x800 && \
- tables[CONSTANT_Field]->rowsNumber < 0x800 && \
- tables[CONSTANT_TypeRef]->rowsNumber < 0x800 && \
- tables[CONSTANT_TypeDef]->rowsNumber < 0x800 && \
- tables[CONSTANT_Param]->rowsNumber < 0x800 && \
- tables[CONSTANT_InterfaceImpl]->rowsNumber < 0x800 && \
- tables[CONSTANT_MemberRef]->rowsNumber < 0x800 && \
- tables[CONSTANT_Module]->rowsNumber < 0x800 && \
- tables[CONSTANT_DeclSecurity]->rowsNumber < 0x800 && \
- tables[CONSTANT_Property]->rowsNumber < 0x800 && \
- tables[CONSTANT_Event]->rowsNumber < 0x800 && \
- tables[CONSTANT_StandaloneSig]->rowsNumber < 0x800 && \
- tables[CONSTANT_ModuleRef]->rowsNumber < 0x800 && \
- tables[CONSTANT_TypeSpec]->rowsNumber < 0x800 && \
- tables[CONSTANT_Assembly]->rowsNumber < 0x800 && \
- tables[CONSTANT_AssemblyRef]->rowsNumber < 0x800 && \
- tables[CONSTANT_File]->rowsNumber < 0x800 && \
- tables[CONSTANT_ExportedType]->rowsNumber < 0x800 && \
- tables[CONSTANT_ManifestResource]->rowsNumber < 0x800) { \
- fieldSize = 2; \
- } else { \
- fieldSize = 4; \
- } \
- rowSize += fieldSize; \
- bitmask = bitmask | ((fieldSize - 1) << (offset << 1)); \
-}
-
-#define HAS_FIELD_MARSHAL(offset) { \
- uint32 fieldSize = 0; \
- if (tables[CONSTANT_Field]->rowsNumber < 0x8000 && \
- tables[CONSTANT_Param]->rowsNumber < 0x8000) { \
- fieldSize = 2; \
- } else { \
- fieldSize = 4; \
- } \
- rowSize += fieldSize; \
- bitmask = bitmask | ((fieldSize - 1) << (offset << 1)); \
-}
-
-#define HAS_DECL_SECURITY(offset) { \
- uint32 fieldSize = 0; \
- if (tables[CONSTANT_TypeDef]->rowsNumber < 0x4000 && \
- tables[CONSTANT_MethodDef]->rowsNumber < 0x4000 && \
- tables[CONSTANT_Assembly]->rowsNumber < 0x4000) { \
- fieldSize = 2; \
- } else { \
- fieldSize = 4; \
- } \
- rowSize += fieldSize; \
- bitmask = bitmask | ((fieldSize - 1) << (offset << 1)); \
-}
-
-#define MEMBER_REF_PARENT(offset) { \
- uint32 fieldSize = 0; \
- if (tables[CONSTANT_TypeDef]->rowsNumber < 0x2000 && \
- tables[CONSTANT_TypeRef]->rowsNumber < 0x2000 && \
- tables[CONSTANT_ModuleRef]->rowsNumber < 0x2000 && \
- tables[CONSTANT_MethodDef]->rowsNumber < 0x2000 && \
- tables[CONSTANT_TypeSpec]->rowsNumber < 0x2000) { \
- fieldSize = 2; \
- } else { \
- fieldSize = 4; \
- } \
- rowSize += fieldSize; \
- bitmask = bitmask | ((fieldSize - 1) << (offset << 1)); \
-}
-
-#define HAS_SEMANTICS(offset) { \
- uint32 fieldSize = 0; \
- if (tables[CONSTANT_Event]->rowsNumber < 0x8000 && \
- tables[CONSTANT_Property]->rowsNumber < 0x8000) { \
- fieldSize = 2; \
- } else { \
- fieldSize = 4; \
- } \
- rowSize += fieldSize; \
- bitmask = bitmask | ((fieldSize - 1) << (offset << 1)); \
-}
-
-#define METHODDEF_OR_REF(offset) { \
- uint32 fieldSize = 0; \
- if (tables[CONSTANT_MethodDef]->rowsNumber < 0x8000 && \
- tables[CONSTANT_MemberRef]->rowsNumber < 0x8000) { \
- fieldSize = 2; \
- } else { \
- fieldSize = 4; \
- } \
- rowSize += fieldSize; \
- bitmask = bitmask | ((fieldSize - 1) << (offset << 1)); \
-}
-
-#define MEMBER_FORWARDED(offset) { \
- uint32 fieldSize = 0; \
- if (tables[CONSTANT_Field]->rowsNumber < 0x8000 && \
- tables[CONSTANT_MethodDef]->rowsNumber < 0x8000) { \
- fieldSize = 2; \
- } else { \
- fieldSize = 4; \
- } \
- rowSize += fieldSize; \
- bitmask = bitmask | ((fieldSize - 1) << (offset << 1)); \
-}
-
-#define IMPLEMENTATION(offset) { \
- uint32 fieldSize = 0; \
- if (tables[CONSTANT_File]->rowsNumber < 0x4000 && \
- tables[CONSTANT_AssemblyRef]->rowsNumber < 0x4000 && \
- tables[CONSTANT_ExportedType]->rowsNumber < 0x4000) { \
- fieldSize = 2; \
- } else { \
- fieldSize = 4; \
- } \
- rowSize += fieldSize; \
- bitmask = bitmask | ((fieldSize - 1) << (offset << 1)); \
-}
-
-// Some encodings are not used here
-#define CUSTOM_ATTRIBUTE_TYPE(offset) { \
- uint32 fieldSize = 0; \
- if (tables[CONSTANT_MethodDef]->rowsNumber < 0x2000 && \
- tables[CONSTANT_MemberRef]->rowsNumber < 0x2000) { \
- fieldSize = 2; \
- } else { \
- fieldSize = 4; \
- } \
- rowSize += fieldSize; \
- bitmask = bitmask | ((fieldSize - 1) << (offset << 1)); \
-}
-
-#define RESOLUTION_SCOPE(offset) { \
- uint32 fieldSize = 0; \
- if (tables[CONSTANT_Module]->rowsNumber < 0x4000 && \
- tables[CONSTANT_ModuleRef]->rowsNumber < 0x4000 && \
- tables[CONSTANT_AssemblyRef]->rowsNumber < 0x4000 && \
- tables[CONSTANT_TypeRef]->rowsNumber < 0x4000) { \
- fieldSize = 2; \
- } else { \
- fieldSize = 4; \
- } \
- rowSize += fieldSize; \
- bitmask = bitmask | ((fieldSize - 1) << (offset << 1)); \
-}
-
-#define TYPE_OR_METHODDEF(offset) { \
- uint32 fieldSize = 0; \
- if (tables[CONSTANT_TypeDef]->rowsNumber < 0x8000 && \
- tables[CONSTANT_MethodDef]->rowsNumber < 0x8000) { \
- fieldSize = 2; \
- } else { \
- fieldSize = 4; \
- } \
- rowSize += fieldSize; \
- bitmask = bitmask | ((fieldSize - 1) << (offset << 1)); \
-}
-
-
-#define CONSTANT_MODULE_GENERATION 0
-#define CONSTANT_MODULE_NAME 1
-#define CONSTANT_MODULE_MVID 2
-#define CONSTANT_MODULE_ENCID 3
-#define CONSTANT_MODULE_ENCBASEID 4
-
-
-#define CONSTANT_TYPEREF_RESOLUTION_SCOPE 0
-#define CONSTANT_TYPEREF_NAME 1
-#define CONSTANT_TYPEREF_NAMESPACE 2
-
-#define CONSTANT_TYPEDEF_FLAGS 0
-#define CONSTANT_TYPEDEF_NAME 1
-#define CONSTANT_TYPEDEF_NAMESPACE 2
-#define CONSTANT_TYPEDEF_EXTENDS 3
-#define CONSTANT_TYPEDEF_FIELDLIST 4
-#define CONSTANT_TYPEDEF_METHODLIST 5
-
-#define CONSTANT_METHODDEF_RVA 0
-#define CONSTANT_METHODDEF_IMPLFLAGS 1
-#define CONSTANT_METHODDEF_FLAGS 2
-#define CONSTANT_METHODDEF_NAME 3
-#define CONSTANT_METHODDEF_SIGNATURE 4
-#define CONSTANT_METHODDEF_PARAMLIST 5
-
-#define CONSTANT_PARAM_FLAGS 0
-#define CONSTANT_PARAM_SEQUENCE 1
-#define CONSTANT_PARAM_NAME 2
-
-#define CONSTANT_MEMBERREF_CLASS 0
-#define CONSTANT_MEMBERREF_NAME 1
-#define CONSTANT_MEMBERREF_SIGNATURE 2
-
-#define CONSTANT_CUSTOM_ATTRIBUTE_PARENT 0
-#define CONSTANT_CUSTOM_ATTRIBUTE_TYPE 1
-#define CONSTANT_CUSTOM_ATTRIBUTE_VALUE 2
-
-#define CONSTANT_STANDALONE_SIG_SIGNATURE 0
-
-#define CONSTANT_TYPESPEC_SIGNATURE 0
-
-#define CONSTANT_ASSEMBLY_HASH_ALG_ID 0
-#define CONSTANT_ASSEMBLY_MAJOR 1
-#define CONSTANT_ASSEMBLY_MINOR 2
-#define CONSTANT_ASSEMBLY_BUILD 3
-#define CONSTANT_ASSEMBLY_REVISION 4
-#define CONSTANT_ASSEMBLY_FLAGS 5
-#define CONSTANT_ASSEMBLY_PUBLIC_KEY 6
-#define CONSTANT_ASSEMBLY_NAME 7
-#define CONSTANT_ASSEMBLY_CULTURE 8
-
-#define CONSTANT_ASSEMBLY_REF_MAJOR 0
-#define CONSTANT_ASSEMBLY_REF_MINOR 1
-#define CONSTANT_ASSEMBLY_REF_BUILD 2
-#define CONSTANT_ASSEMBLY_REF_REVISION 3
-#define CONSTANT_ASSEMBLY_REF_FLAGS 4
-#define CONSTANT_ASSEMBLY_REF_PUBLIC_KEY 5
-#define CONSTANT_ASSEMBLY_REF_NAME 6
-#define CONSTANT_ASSEMBLY_REF_CULTURE 7
-#define CONSTANT_ASSEMBLY_REF_HASH_VALUE 8
-
-#define CONSTANT_FIELD_FLAGS 0
-#define CONSTANT_FIELD_NAME 1
-#define CONSTANT_FIELD_SIGNATURE 2
-
-#define CONSTANT_INTERFACE_IMPL_CLASS 0
-#define CONSTANT_INTERFACE_IMPL_INTERFACE 1
-
-#define CONSTANT_NESTED_CLASS_NESTED_CLASS 0
-#define CONSTANT_NESTED_CLASS_ENCLOSING_CLASS 1
-
-#define CONSTANT_METHOD_SPEC_METHOD 0
-#define CONSTANT_METHOD_SPEC_INSTANTIATION 1
-
-#define CONSTANT_GENERIC_PARAM_CONSTRAINT_OWNER 0
-#define CONSTANT_GENERIC_PARAM_CONSTRAINT_CONSTRAINT 1
-
-#define CONSTANT_CONSTANT_TYPE 0
-#define CONSTANT_CONSTANT_PARENT 1
-#define CONSTANT_CONSTANT_VALUE 2
-
-#define CONSTANT_FIELD_MARSHAL_PARENT 0
-#define CONSTANT_FIELD_MARSHAL_NATIVE_TYPE 1
-
-#define CONSTANT_DECL_SECURITY_ACTION 0
-#define CONSTANT_DECL_SECURITY_PARENT 1
-#define CONSTANT_DECL_SECURITY_PERMISSION_SET 2
-
-#define CONSTANT_CLASS_LAYOUT_PACKING_SIZE 0
-#define CONSTANT_CLASS_LAYOUT_CLASS_SIZE 1
-#define CONSTANT_CLASS_LAYOUT_PARENT 2
-
-#define CONSTANT_FIELD_LAYOUT_OFFSET 0
-#define CONSTANT_FIELD_LAYOUT_FIELD 1
-
-#define CONSTANT_EVENT_MAP_PARENT 0
-#define CONSTANT_EVEN_MAP_EVENT_LIST 1
-
-#define CONSTANT_EVENT_EVENT_FLAGS 0
-#define CONSTANT_EVENT_NAME 1
-#define CONSTANT_EVENT_TYPE 2
-
-#define CONSTANT_PROPERTY_MAP_PARENT 0
-#define CONSTANT_PROPERTY_MAP_PROPERTY_LIST 1
-
-#define CONSTANT_PROPERTY_FLAGS 0
-#define CONSTANT_PROPERTY_NAME 1
-#define CONSTANT_PROPERTY_TYPE 2
-
-#define CONSTANT_METHOD_SEMANTICS_SEMANTICS 0
-#define CONSTANT_METHOD_SEMANTICS_METHOD 1
-#define CONSTANT_METHOD_SEMANTICS_ASSOCIATION 2
-
-#define CONSTANT_METHOD_IMPL_CLASS 0
-#define CONSTANT_METHOD_IMPL_METHOD_BODY 1
-#define CONSTANT_METHOD_IMPL_METHOD_DECLARATION 2
-
-#define CONSTANT_MODULE_REF_NAME 0
-
-#define CONSTANT_IMPL_MAP_MAPPING_FLAGS 0
-#define CONSTANT_IMPL_MAP_MEMBER_FORWARDED 1
-#define CONSTANT_IMPL_MAP_IMPORT_NAME 2
-#define CONSTANT_IMPL_MAP_IMPORT_SCOPE 3
-
-#define CONSTANT_FIELD_RVA_RVA 0
-#define CONSTANT_FIELD_RVA_FIELD 1
-
-#define CONSTANT_MANIFEST_RESOURCE_OFFSET 0
-#define CONSTANT_MANIFEST_RESOURCE_FLAGS 1
-#define CONSTANT_MANIFEST_RESOURCE_NAME 2
-#define CONSTANT_MANIFEST_RESOURCE_IMPLEMENTATION 3
-
-#define CONSTANT_ASSEMBLY_PROCESSOR_PROCESSOR 0
-
-#define CONSTANT_ASSEMBLY_OS_PLATFORM_ID 0
-#define CONSTANT_ASSEMBLY_OS_MAJOR_VERSION 1
-#define CONSTANT_ASSEMBLY_OS_MINOR_VERSION 2
-
-#define CONSTANT_FILE_FLAGS 0
-#define CONSTANT_FILE_NAME 1
-#define CONSTANT_FILE_HASH_VALUE 2
-
-#define CONSTANT_GENERIC_PARAM_NUMBER 0
-#define CONSTANT_GENERIC_PARAM_FLAGS 1
-#define CONSTANT_GENERIC_PARAM_OWNER 2
-#define CONSTANT_GENERIC_PARAM_NAME 3
-
-} // end namespace n3
-
-#endif
-
diff --git a/vmkit/lib/N3/VMCore/CLIAccess.h b/vmkit/lib/N3/VMCore/CLIAccess.h
deleted file mode 100644
index 45c6fdb..0000000
--- a/vmkit/lib/N3/VMCore/CLIAccess.h
+++ /dev/null
@@ -1,41 +0,0 @@
-//===------------- CLIAccess.h - CLI access description -------------------===//
-//
-// N3
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#ifndef N3_CLI_ACCESS_H
-#define N3_CLI_ACCESS_H
-
-namespace n3 {
-
-#define ACC_STATIC 0x0010
-#define ACC_VIRTUAL 0x0040
-#define ACC_INTERFACE 0x0020
-#define ACC_INTERNAL 0x1000
-#define ACC_SYNCHRO 0x0020
-
-#define EXPLICIT_LAYOUT 0x00000010
-
-#define MK_VERIFIER(name, flag) \
- inline bool name(unsigned int param) { \
- return (flag & param) != 0; \
- } \
-
-MK_VERIFIER(isStatic, ACC_STATIC)
-MK_VERIFIER(isVirtual, ACC_VIRTUAL)
-MK_VERIFIER(isInterface, ACC_INTERFACE)
-MK_VERIFIER(isInternal, ACC_INTERNAL)
-MK_VERIFIER(isSynchro, ACC_SYNCHRO)
-
-MK_VERIFIER(hasExplicitLayout, EXPLICIT_LAYOUT)
-
-
-#undef MK_VERIFIER
-
-} // end namespace n3
-
-#endif
diff --git a/vmkit/lib/N3/VMCore/CLIJit.cpp b/vmkit/lib/N3/VMCore/CLIJit.cpp
deleted file mode 100644
index f24c0ca..0000000
--- a/vmkit/lib/N3/VMCore/CLIJit.cpp
+++ /dev/null
@@ -1,1795 +0,0 @@
-//===------------ CLIJit.cpp - CLI just in time compiler ------------------===//
-//
-// N3
-//
-// This file is distributed under the University Of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#include "mvm/JIT.h"
-
-#include "Assembly.h"
-#include "CLIAccess.h"
-#include "CLIJit.h"
-#include "MSCorlib.h"
-#include "NativeUtil.h"
-#include "N3.h"
-#include "N3ModuleProvider.h"
-#include "Reader.h"
-#include "VMArray.h"
-#include "VMCache.h"
-#include "VMClass.h"
-#include "VMThread.h"
-#include "N3MetaType.h"
-
-#include <llvm/CallingConv.h>
-#include <llvm/Constants.h>
-#include <llvm/DerivedTypes.h>
-#include <llvm/Function.h>
-#include <llvm/Instructions.h>
-#include <llvm/LinkAllPasses.h>
-#include <llvm/LLVMContext.h>
-#include <llvm/Module.h>
-#include <llvm/Type.h>
-#include <llvm/Analysis/LoopPass.h>
-#include <llvm/Support/CFG.h>
-#include <llvm/Support/MutexGuard.h>
-
-#include "N3Debug.h"
-
-#include "types.h"
-
-using namespace llvm;
-using namespace n3;
-
-void ExceptionBlockDesc::print(mvm::PrintBuffer* buf) const {
- buf->write("Exception<>");
-}
-
-#ifdef WITH_TRACER
-// for structs
-static void traceStruct(VMCommonClass* cl, BasicBlock* block, Value* arg) {
-#ifdef MULTIPLE_GC
- Value* GC = ++(block->getParent()->arg_begin());
-#endif
-
- for (std::vector<VMField*>::iterator i = cl->virtualFields.begin(),
- e = cl->virtualFields.end(); i!= e; ++i) {
-
- VMField* field = *i;
- if (field->signature->super == MSCorlib::pValue) {
- if (!field->signature->isPrimitive) {
- Value* ptr = GetElementPtrInst::Create(arg, field->offset, "",
- block);
- traceStruct(field->signature, block, ptr);
- } else if (field->signature == MSCorlib::pIntPtr ||
- field->signature == MSCorlib::pUIntPtr) {
- Value* valCast = new BitCastInst(arg, VMObject::llvmType, "", block);
-#ifdef MULTIPLE_GC
- std::vector<Value*> Args;
- Args.push_back(valCast);
- Args.push_back(GC);
- CallInst::Create(CLIJit::markAndTraceLLVM, Args.begin(), Args.end(),
- "", block);
-#else
- CallInst::Create(CLIJit::markAndTraceLLVM, valCast, "", block);
-#endif
- }
- } else if (field->signature->super != MSCorlib::pEnum) {
- Value* valCast = new BitCastInst(arg, VMObject::llvmType, "", block);
-#ifdef MULTIPLE_GC
- std::vector<Value*> Args;
- Args.push_back(valCast);
- Args.push_back(GC);
- CallInst::Create(CLIJit::markAndTraceLLVM, Args.begin(), Args.end(),
- "", block);
-#else
- CallInst::Create(CLIJit::markAndTraceLLVM, valCast, "", block);
-#endif
- }
- }
-}
-
-
-// Always classes
-static void traceClass(VMCommonClass* cl, BasicBlock* block, Value* arg,
- std::vector<VMField*>& fields, bool boxed = false) {
-#ifdef MULTIPLE_GC
- Value* GC = ++(block->getParent()->arg_begin());
-#endif
-
- Constant* zero = cl->vm->module->constantZero;
- for (std::vector<VMField*>::iterator i = fields.begin(),
- e = fields.end(); i!= e; ++i) {
- VMField* field = *i;
- if (field->signature->super == MSCorlib::pValue) {
- std::vector<Value*> args; //size = 2
- args.push_back(zero);
- if (boxed) {
- ConstantInt* CI = dyn_cast<ConstantInt>(field->offset);
- args.push_back(ConstantInt::get(Type::getInt32Ty(getGlobalContext()), CI->getValue() + 1));
- } else {
- args.push_back(field->offset);
- }
- Value* ptr = GetElementPtrInst::Create(arg, args.begin(), args.end(), "",
- block);
- traceStruct(field->signature, block, ptr);
- } else if (field->signature->super != MSCorlib::pEnum) {
- std::vector<Value*> args; //size = 2
- args.push_back(zero);
- if (boxed) {
- ConstantInt* CI = dyn_cast<ConstantInt>(field->offset);
- args.push_back(ConstantInt::get(Type::getInt32Ty(getGlobalContext()), CI->getValue() + 1));
- } else {
- args.push_back(field->offset);
- }
- Value* ptr = GetElementPtrInst::Create(arg, args.begin(), args.end(), "",
- block);
- Value* val = new LoadInst(ptr, "", block);
- Value* valCast = new BitCastInst(val, VMObject::llvmType, "", block);
-#ifdef MULTIPLE_GC
- std::vector<Value*> Args;
- Args.push_back(valCast);
- Args.push_back(GC);
- CallInst::Create(CLIJit::markAndTraceLLVM, Args.begin(), Args.end(),
- "", block);
-#else
- CallInst::Create(CLIJit::markAndTraceLLVM, valCast, "", block);
-#endif
- }
- }
-}
-#endif
-
-
-N3VirtualTable* CLIJit::makeArrayVT(VMClassArray* cl) {
- VMClass *super = (VMClass*)cl->super;
- N3VirtualTable * res =
- new(cl->assembly->allocator, super->vtSize) N3VirtualTable(VMObject::getN3VirtualTable(super->virtualInstance), super->vtSize);
-
-#ifdef WITH_TRACER
- Function* func = Function::Create(markAndTraceLLVMType,
- GlobalValue::ExternalLinkage,
- "markAndTraceObject",
- cl->vm->getLLVMModule());
- Argument* arg = func->arg_begin();
-#ifdef MULTIPLE_GC
- Argument* GC = ++(func->arg_begin());
-#endif
- // Constant Definitions
- Constant* const_int32_8 = cl->vm->module->constantZero;
- Constant* const_int32_9 = cl->vm->module->constantOne;
- Constant* const_int32_10 = cl->vm->module->constantTwo;
-
-
- // Function Definitions
-
- {
- BasicBlock* label_entry = BasicBlock::Create(getGlobalContext(), "entry",func,0);
- BasicBlock* label_bb = BasicBlock::Create(getGlobalContext(), "bb",func,0);
- BasicBlock* label_return = BasicBlock::Create(getGlobalContext(), "return",func,0);
-
- Value* ptr_v = new BitCastInst(arg, cl->naturalType, "", label_entry);
-
- // Block entry (label_entry)
- std::vector<Value*> ptr_tmp918_indices;
- ptr_tmp918_indices.push_back(const_int32_8);
- ptr_tmp918_indices.push_back(const_int32_9);
- Instruction* ptr_tmp918 =
- GetElementPtrInst::Create(ptr_v, ptr_tmp918_indices.begin(),
- ptr_tmp918_indices.end(), "tmp918",
- label_entry);
- LoadInst* int32_tmp1019 = new LoadInst(ptr_tmp918, "tmp1019", false,
- label_entry);
-
- ICmpInst* int1_tmp1221 = new ICmpInst(*label_entry, ICmpInst::ICMP_SGT,
- int32_tmp1019,
- const_int32_8, "tmp1221");
-
- BranchInst::Create(label_bb, label_return, int1_tmp1221, label_entry);
-
- // Block bb (label_bb)
- Argument* fwdref_12 = new Argument(IntegerType::get(getGlobalContext(), 32));
- PHINode* int32_i_015_0 = PHINode::Create(Type::getInt32Ty(getGlobalContext()), "i.015.0",
- label_bb);
- int32_i_015_0->reserveOperandSpace(2);
- int32_i_015_0->addIncoming(fwdref_12, label_bb);
- int32_i_015_0->addIncoming(const_int32_8, label_entry);
-
- std::vector<Value*> ptr_tmp3_indices;
- ptr_tmp3_indices.push_back(const_int32_8);
- ptr_tmp3_indices.push_back(const_int32_10);
- ptr_tmp3_indices.push_back(int32_i_015_0);
- Instruction* ptr_tmp3 =
- GetElementPtrInst::Create(ptr_v, ptr_tmp3_indices.begin(),
- ptr_tmp3_indices.end(), "tmp3", label_bb);
-
- if (cl->baseClass->super == MSCorlib::pValue) {
- traceStruct(cl->baseClass, label_bb, ptr_tmp3);
- } else if (cl->baseClass->super != MSCorlib::pEnum) {
- LoadInst* ptr_tmp4 = new LoadInst(ptr_tmp3, "tmp4", false, label_bb);
- Value* arg = new BitCastInst(ptr_tmp4, VMObject::llvmType, "", label_bb);
-#ifdef MULTIPLE_GC
- std::vector<Value*> Args;
- Args.push_back(arg);
- Args.push_back(GC);
- CallInst::Create(markAndTraceLLVM, Args.begin(), Args.end(), "",
- label_bb);
-#else
- CallInst::Create(markAndTraceLLVM, arg, "", label_bb);
-#endif
- }
- BinaryOperator* int32_tmp6 =
- BinaryOperator::Create(Instruction::Add, int32_i_015_0, const_int32_9,
- "tmp6", label_bb);
- LoadInst* int32_tmp10 = new LoadInst(ptr_tmp918, "tmp10", false, label_bb);
- ICmpInst* int1_tmp12 = new ICmpInst(*label_bb, ICmpInst::ICMP_SGT,
- int32_tmp10, int32_tmp6, "tmp12");
- BranchInst::Create(label_bb, label_return, int1_tmp12, label_bb);
-
- // Block return (label_return)
- ReturnInst::Create(getGlobalContext(), label_return);
-
- // Resolve Forward References
- fwdref_12->replaceAllUsesWith(int32_tmp6); delete fwdref_12;
-
- }
-
- void* tracer = mvm::MvmModule::executionEngine->getPointerToGlobal(func);
- ((void**)res)[VT_TRACER_OFFSET] = tracer;
- cl->virtualTracer = func;
-#endif
-
-#define CASE_ARRAY(name, type) \
- if(cl->baseClass == MSCorlib::p##name) { \
- ((void**)res)[VT_PRINT_OFFSET] = ((void **)(unsigned int)Array##name::do_print); \
- } else
-
- ON_TYPES(CASE_ARRAY, _F_NT) {}
-
-#undef CASE_ARRAY
-
- return res;
-}
-
-N3VirtualTable* CLIJit::makeVT(VMClass* cl, bool stat) {
- int n = N3VirtualTable::baseVtSize();
- N3VirtualTable * res =
- stat ?
- new(cl->assembly->allocator, n) N3VirtualTable((uintptr_t)0,
- (uintptr_t)0,
- (uintptr_t)VMObject::_trace,
- (uintptr_t)VMObject::_print,
- (uintptr_t)mvm::Object::default_hashCode) :
- (cl->super ?
- new(cl->assembly->allocator, cl->vtSize) N3VirtualTable(VMObject::getN3VirtualTable(((VMClass *)cl->super)->virtualInstance),
- n,
- cl->vtSize) :
- new(cl->assembly->allocator, cl->vtSize) N3VirtualTable((uintptr_t)0,
- (uintptr_t)0,
- (uintptr_t)VMObject::_trace,
- (uintptr_t)VMObject::_print,
- (uintptr_t)mvm::Object::default_hashCode));
-
-
-#ifdef WITH_TRACER
- const Type* type = stat ? cl->staticType : cl->virtualType;
- std::vector<VMField*> &fields = stat ? cl->staticFields : cl->virtualFields;
-
- Function* func = Function::Create(markAndTraceLLVMType,
- GlobalValue::ExternalLinkage,
- "markAndTraceObject",
- cl->vm->getLLVMModule());
-
- Argument* arg = func->arg_begin();
-#ifdef MULTIPLE_GC
- Argument* GC = ++(func->arg_begin());
-#endif
- BasicBlock* block = BasicBlock::Create(getGlobalContext(), "", func);
- llvm::Value* realArg = new BitCastInst(arg, type, "", block);
-
-#ifdef MULTIPLE_GC
- std::vector<Value*> Args;
- Args.push_back(arg);
- Args.push_back(GC);
- if (stat || cl->super == 0) {
- CallInst::Create(vmObjectTracerLLVM, Args.begin(), Args.end(), "", block);
- } else {
- CallInst::Create(((VMClass*)cl->super)->virtualTracer, Args.begin(),
- Args.end(), "", block);
- }
-#else
- if (stat || cl->super == 0) {
- CallInst::Create(vmObjectTracerLLVM, arg, "", block);
- } else {
- CallInst::Create(((VMClass*)cl->super)->virtualTracer, arg, "", block);
- }
-#endif
-
- traceClass(cl, block, realArg, fields, (cl->super == MSCorlib::pValue && !stat));
- ReturnInst::Create(getGlobalContext(), block);
-
- void* tracer = mvm::MvmModule::executionEngine->getPointerToGlobal(func);
- ((void**)res)[VT_TRACER_OFFSET] = tracer;
-
- if (!stat) {
- cl->virtualTracer = func;
- } else {
- cl->staticTracer = func;
- }
-#endif
-
- return res;
-}
-
-BasicBlock* CLIJit::createBasicBlock(const char* name) {
- return BasicBlock::Create(getGlobalContext(), name, llvmFunction);
-}
-
-void CLIJit::setCurrentBlock(BasicBlock* newBlock) {
-
- std::vector<Value*> newStack;
- uint32 index = 0;
- for (BasicBlock::iterator i = newBlock->begin(), e = newBlock->end(); i != e;
- ++i, ++index) {
- if (!(isa<PHINode>(i))) {
- break;
- } else {
- newStack.push_back(i);
- }
- }
-
- stack = newStack;
- currentBlock = newBlock;
-}
-
-extern void convertValue(Value*& val, const Type* t1, BasicBlock* currentBlock);
-
-static void testPHINodes(BasicBlock* dest, BasicBlock* insert, CLIJit* jit) {
- if(dest->empty()) {
- for (std::vector<Value*>::iterator i = jit->stack.begin(),
- e = jit->stack.end(); i!= e; ++i) {
- Value* cur = (*i);
- PHINode* node = PHINode::Create(cur->getType(), "", dest);
- node->addIncoming(cur, insert);
- }
- } else {
- std::vector<Value*>::iterator stackit = jit->stack.begin();
- for (BasicBlock::iterator i = dest->begin(), e = dest->end(); i != e;
- ++i) {
- if (!(isa<PHINode>(i))) {
- break;
- } else {
- Instruction* ins = i;
- Value* cur = (*stackit);
- convertValue(cur, ins->getType(), insert);
- ((PHINode*)ins)->addIncoming(cur, insert);
- ++stackit;
- }
- }
- }
-}
-
-void CLIJit::branch(llvm::BasicBlock* dest, llvm::BasicBlock* insert) {
- testPHINodes(dest, insert, this);
- BranchInst::Create(dest, insert);
-}
-
-void CLIJit::branch(llvm::Value* test, llvm::BasicBlock* ifTrue,
- llvm::BasicBlock* ifFalse, llvm::BasicBlock* insert) {
- testPHINodes(ifTrue, insert, this);
- testPHINodes(ifFalse, insert, this);
- BranchInst::Create(ifTrue, ifFalse, test, insert);
-}
-
-Value* CLIJit::pop() {
- assert(stack.size());
- Value* ret = top();
- stack.pop_back();
- return ret;
-}
-
-Value* CLIJit::top() {
- return stack.back();
-}
-
-void CLIJit::push(Value* val) {
- assert(val);
- stack.push_back(val);
-}
-
-Value* CLIJit::changeType(Value* val, const Type* type) {
- const Type* valType = val->getType();
- if (type->isIntegerTy()) {
- if (valType == PointerType::getUnqual(type)) {
- // in cast it's a struct
- val = new LoadInst(val, "", currentBlock);
- }
- else if (type->getPrimitiveSizeInBits() <
- valType->getPrimitiveSizeInBits()) {
- val = new TruncInst(val, type, "", currentBlock);
- } else {
- val = new SExtInst(val, type, "", currentBlock);
- }
- } else if (type == Type::getFloatTy(getGlobalContext())) {
- val = new FPTruncInst(val, type, "", currentBlock);
- } else if (type == Type::getDoubleTy(getGlobalContext())) {
- val = new FPExtInst(val, type, "", currentBlock);
- } else {
- val = new BitCastInst(val, type, "", currentBlock);
- }
- return val;
-}
-
-void CLIJit::makeArgs(const FunctionType* type, std::vector<Value*>& Args,
- bool structReturn) {
- uint32 size = type->getNumParams();
- Value** args = (Value**)alloca(sizeof(Value*) * size);
- sint32 index = size - 1;
- FunctionType::param_iterator e = type->param_end();
- e--;
- if (structReturn) { e--; index--; size--; }
- for (; index >= 0; --e, --index) {
- const Type* argType = (*e);
- Value* val = pop();
- if (val->getType() != argType) {
- val = changeType(val, argType);
- }
- args[index] = val;
- }
-
- for (uint32 i = 0; i < size; ++i) {
- Args.push_back(args[i]);
- }
-}
-
-Instruction* CLIJit::lowerMathOps(VMMethod* meth,
- std::vector<Value*>& args) {
-
- if (meth->name == N3::sqrt) {
- return CallInst::Create(module->func_llvm_sqrt_f64, args[0], "tmp1",
- currentBlock);
- } else if (meth->name == N3::sin) {
- return CallInst::Create(module->func_llvm_sin_f64, args[0], "tmp1",
- currentBlock);
- } else if (meth->name == N3::cos) {
- return CallInst::Create(module->func_llvm_cos_f64, args[0], "tmp1",
- currentBlock);
- } else if (meth->name == N3::exp) {
- return CallInst::Create(module->func_llvm_exp_f64, args[0], "tmp1",
- currentBlock);
- } else if (meth->name == N3::log) {
- return CallInst::Create(module->func_llvm_log_f64, args[0], "tmp1",
- currentBlock);
- } else if (meth->name == N3::floor) {
- return CallInst::Create(module->func_llvm_floor_f64, args[0], "tmp1",
- currentBlock);
- } else if (meth->name == N3::log10) {
- return CallInst::Create(module->func_llvm_log10_f64, args[0], "tmp1",
- currentBlock);
- } else if (meth->name == N3::pow) {
- Instruction* val = CallInst::Create(module->func_llvm_pow_f64,
- args.begin(), args.end(), "tmp1",
- currentBlock);
- return val;
- }
- return 0;
-
-}
-
-Instruction* CLIJit::invokeInline(VMMethod* meth,
- std::vector<Value*>& args, VMGenericClass* genClass, VMGenericMethod* genMethod) {
- mvm::BumpPtrAllocator *a = new mvm::BumpPtrAllocator();
- CLIJit* jit = new(*a, "CLIJit") CLIJit(*a);
- jit->module = meth->classDef->vm->module;
- jit->compilingClass = meth->classDef;
- jit->compilingMethod = meth;
-
- jit->unifiedUnreachable = unifiedUnreachable;
- jit->inlineMethods = inlineMethods;
- jit->inlineMethods[meth] = true;
- Instruction* ret = jit->inlineCompile(llvmFunction, currentBlock,
- currentExceptionBlock, args, static_cast<VMGenericClass*>(jit->compilingClass), genMethod);
- inlineMethods[meth] = false;
-
- delete a;
- return ret;
-}
-
-
-void CLIJit::invoke(uint32 value, VMGenericClass* genClass, VMGenericMethod* genMethod) {
- VMMethod* meth = compilingClass->assembly->getMethodFromToken(value, genClass, genMethod);
-
- if (meth->classDef->isArray) {
- uint8 func = 0;
- N3* vm = VMThread::get()->getVM();
- if (meth->name == vm->asciizToUTF8("Set")) {
- func = 0;
- } else if (meth->name == vm->asciizToUTF8("Get")) {
- func = 1;
- } else if (meth->name == vm->asciizToUTF8("Address")) {
- func = 2;
- } else {
- vm->error("implement me %s", mvm::PrintBuffer(meth->name).cString());
- }
-
- VMClassArray* type = (VMClassArray*)meth->classDef;
- uint32 dims = type->dims;
- Value** args = (Value**)alloca(sizeof(Value*) * dims);
- Value* val = 0;
- if (func == 0) {
- val = pop();
- }
- for (sint32 i = dims - 1; i >= 0 ; --i) {
- args[i] = pop();
- }
- Value* obj = pop();
- VMClassArray* base = type;
- for (uint32 v = 0; v < dims; ++v) {
- std::vector<Value*> Args;
- Args.push_back(module->constantZero);
- Args.push_back(module->constantTwo);
- Args.push_back(args[v]);
- obj = verifyAndComputePtr(obj, args[v], base->naturalType, true);
- if (v != dims - 1) {
- base = (VMClassArray*)base->baseClass;
- obj = new LoadInst(obj, "", currentBlock);
- }
- }
-
- if (func == 0) {
- new StoreInst(val, obj, false, currentBlock);
- } else if (func == 1) {
- push(new LoadInst(obj, "", currentBlock));
- } else {
- push(obj);
- }
- return;
- }
-
- std::vector<Value*> Args;
- const llvm::FunctionType* type = meth->getSignature(genMethod);
- makeArgs(type, Args, meth->structReturn);
-
- if (meth->classDef->nameSpace == N3::system &&
- meth->classDef->name == N3::math) {
- Value* val = lowerMathOps(meth, Args);
- if (val) {
- push(val);
- return;
- }
- } else if (meth->classDef->nameSpace == N3::system &&
- meth->classDef->name == N3::doubleName) {
- if (meth->name == N3::isNan) {
- push(new FCmpInst(*currentBlock, FCmpInst::FCMP_UNO, Args[0],
- module->constantDoubleZero, "tmp1"));
- return;
- } else if (meth->name == N3::testInfinity) {
- BasicBlock* endBlock = createBasicBlock("end test infinity");
- BasicBlock* minusInfinity = createBasicBlock("- infinity");
- BasicBlock* noInfinity = createBasicBlock("no infinity");
- PHINode* node = PHINode::Create(Type::getInt32Ty(getGlobalContext()), "", endBlock);
- node->addIncoming(module->constantOne, currentBlock);
- node->addIncoming(module->constantMinusOne, minusInfinity);
- node->addIncoming(module->constantZero, noInfinity);
- Value* val1 = new FCmpInst(*currentBlock, FCmpInst::FCMP_OEQ, Args[0],
- module->constantDoubleInfinity, "tmp1");
- BranchInst::Create(endBlock, minusInfinity, val1, currentBlock);
- Value* val2 = new FCmpInst(*minusInfinity, FCmpInst::FCMP_OEQ, Args[0],
- module->constantDoubleMinusInfinity, "tmp1");
- BranchInst::Create(endBlock, noInfinity, val2, minusInfinity);
- BranchInst::Create(endBlock, noInfinity);
- currentBlock = endBlock;
- push(node);
- return;
- }
- } else if (meth->classDef->nameSpace == N3::system &&
- meth->classDef->name == N3::floatName) {
- if (meth->name == N3::isNan) {
- push(new FCmpInst(*currentBlock, FCmpInst::FCMP_UNO, Args[0],
- module->constantFloatZero, "tmp1"));
- return;
- } else if (meth->name == N3::testInfinity) {
- BasicBlock* endBlock = createBasicBlock("end test infinity");
- BasicBlock* minusInfinity = createBasicBlock("- infinity");
- BasicBlock* noInfinity = createBasicBlock("no infinity");
- PHINode* node = PHINode::Create(Type::getInt32Ty(getGlobalContext()), "", endBlock);
- node->addIncoming(module->constantOne, currentBlock);
- node->addIncoming(module->constantMinusOne, minusInfinity);
- node->addIncoming(module->constantZero, noInfinity);
- Value* val1 = new FCmpInst(*currentBlock, FCmpInst::FCMP_OEQ, Args[0],
- module->constantFloatInfinity, "tmp1");
- BranchInst::Create(endBlock, minusInfinity, val1, currentBlock);
- Value* val2 = new FCmpInst(*minusInfinity, FCmpInst::FCMP_OEQ, Args[0],
- module->constantFloatMinusInfinity, "tmp1");
- BranchInst::Create(endBlock, noInfinity, val2, minusInfinity);
- BranchInst::Create(endBlock, noInfinity);
- currentBlock = endBlock;
- push(node);
- return;
- }
- }
-
- Value* res = 0;
- if (meth && meth->canBeInlined && meth != compilingMethod &&
- inlineMethods[meth] == 0) {
- res = invokeInline(meth, Args, genClass, genMethod);
- } else {
- Function* func = meth->compiledPtr(genMethod);
-
- res = invoke(func, Args, "", currentBlock, meth->structReturn);
- }
- if (meth->parameters[0] != MSCorlib::pVoid) {
- push(res);
- }
-}
-
-void CLIJit::invokeNew(uint32 value, VMGenericClass* genClass, VMGenericMethod* genMethod) {
- Assembly* ass = compilingClass->assembly;
- VMMethod* meth = ass->getMethodFromToken(value, genClass, genMethod);
- VMClass* type = meth->classDef;
- const FunctionType* funcType = meth->getSignature(genMethod);
-
- Value* obj = 0;
- if (type->isPointer) {
- VMThread::get()->getVM()->error("implement me %s", mvm::PrintBuffer(type).cString());
- } else if (type->isArray) {
- VMClassArray* arrayType = (VMClassArray*)type;
- Value* valCl = new LoadInst(arrayType->llvmVar(), "", currentBlock);
- Value** args = (Value**)alloca(sizeof(Value*) * (arrayType->dims + 1));
- args[0] = valCl;
-
- for (int cur = arrayType->dims; cur > 0; --cur)
- args[cur] = pop();
-
- std::vector<Value*> Args;
- for (uint32 v = 0; v < arrayType->dims + 1; ++v) {
- Args.push_back(args[v]);
- }
- push(invoke(arrayMultiConsLLVM, Args, "", currentBlock, false));
- return;
-
- } else if (type->super == MSCorlib::pValue || type->super == MSCorlib::pEnum) {
- obj = new AllocaInst(type->naturalType, "", currentBlock);
- uint64 size = mvm::MvmModule::getTypeSize(type->naturalType);
-
- std::vector<Value*> params;
- params.push_back(new BitCastInst(obj, module->ptrType, "", currentBlock));
- params.push_back(module->constantInt8Zero);
- params.push_back(ConstantInt::get(Type::getInt32Ty(getGlobalContext()), size));
- params.push_back(module->constantZero);
- CallInst::Create(module->llvm_memset_i32, params.begin(), params.end(),
- "", currentBlock);
- } else {
- Value* var = new LoadInst(type->llvmVar(), "", currentBlock);
- Value* val = CallInst::Create(objConsLLVM, var, "", currentBlock);
- obj = new BitCastInst(val, type->naturalType, "", currentBlock);
- }
-
- std::vector<Value*>::iterator i = stack.end();
- uint32 nbParams = funcType->getNumParams();
- while (--nbParams) --i;
- stack.insert(i, obj);
-
- std::vector<Value*> Args;
- makeArgs(funcType, Args, meth->structReturn);
- if (meth && meth->canBeInlined && meth != compilingMethod &&
- inlineMethods[meth] == 0) {
- invokeInline(meth, Args, genClass, genMethod);
- } else {
- Function* func = meth->compiledPtr(genMethod);
-
- invoke(func, Args, "", currentBlock, meth->structReturn);
- }
-
- if ((type->super == MSCorlib::pValue || type->super == MSCorlib::pEnum) &&
- type->virtualFields.size() == 1) {
- push(new LoadInst(obj, "", currentBlock));
- } else {
- push(obj);
- }
-}
-
-llvm::Value* CLIJit::getVirtualField(uint32 value, VMGenericClass* genClass, VMGenericMethod* genMethod) {
- VMField* field = compilingClass->assembly->getFieldFromToken(value, false, genClass, genMethod);
- Value* obj = pop();
- if ((field->classDef->super == MSCorlib::pValue ||
- field->classDef->super == MSCorlib::pEnum) &&
- field->classDef->virtualFields.size() == 1){
- // struct!
- return obj;
- } else {
- if (field->classDef->super != MSCorlib::pValue &&
- field->classDef->super != MSCorlib::pEnum) {
- obj = new BitCastInst(obj, field->classDef->naturalType, "",
- currentBlock);
- }
- std::vector<Value*> args;
- args.push_back(module->constantZero);
- args.push_back(field->offset);
- Value* ptr = GetElementPtrInst::Create(obj, args.begin(), args.end(), "",
- currentBlock);
- return ptr;
- }
-}
-
-llvm::Value* CLIJit::getStaticField(uint32 value, VMGenericClass* genClass, VMGenericMethod* genMethod) {
- VMField* field = compilingClass->assembly->getFieldFromToken(value, true, genClass, genMethod);
- VMCommonClass* cl = field->classDef;
- cl->resolveType(true, false, genMethod);
- Value* arg = new LoadInst(cl->llvmVar(), "", currentBlock);
- Value* call = invoke(initialiseClassLLVM, arg, "", currentBlock, false);
- Value* staticCl = new BitCastInst(call, cl->staticType, "", currentBlock);
-
- std::vector<Value*> args;
- args.push_back(module->constantZero);
- args.push_back(field->offset);
- Value* ptr = GetElementPtrInst::Create(staticCl, args.begin(), args.end(), "",
- currentBlock);
-
- return ptr;
-
-}
-
-void CLIJit::setVirtualField(uint32 value, bool isVolatile, VMGenericClass* genClass, VMGenericMethod* genMethod) {
- VMField* field = compilingClass->assembly->getFieldFromToken(value, false, genClass, genMethod);
- Value* val = pop();
- Value* obj = pop();
- const Type* valType = val->getType();
-
- Value* ptr = 0;
- const Type* type = obj->getType();
- if ((field->classDef->super == MSCorlib::pValue ||
- field->classDef->super == MSCorlib::pEnum) &&
- field->classDef->virtualFields.size() == 1){
- // struct!
- ptr = obj;
- } else {
- if (field->classDef->super != MSCorlib::pValue &&
- field->classDef->super != MSCorlib::pEnum) {
- obj = new BitCastInst(obj, field->classDef->naturalType, "", currentBlock);
- }
- std::vector<Value*> args;
- args.push_back(module->constantZero);
- args.push_back(field->offset);
- ptr = GetElementPtrInst::Create(obj, args.begin(), args.end(), "",
- currentBlock);
- }
-
- if (field->signature->super == MSCorlib::pValue &&
- field->signature->virtualFields.size() > 1) {
- uint64 size = mvm::MvmModule::getTypeSize(field->signature->naturalType);
-
- std::vector<Value*> params;
- params.push_back(new BitCastInst(ptr, PointerType::getUnqual(Type::getInt8Ty(getGlobalContext())), "", currentBlock));
- params.push_back(new BitCastInst(val, PointerType::getUnqual(Type::getInt8Ty(getGlobalContext())), "", currentBlock));
- params.push_back(ConstantInt::get(Type::getInt32Ty(getGlobalContext()), size));
- params.push_back(module->constantZero);
- CallInst::Create(module->llvm_memcpy_i32, params.begin(), params.end(), "", currentBlock);
-
- } else {
- type = field->signature->naturalType;
- if (val == constantVMObjectNull) {
- val = Constant::getNullValue(type);
- } else if (type != valType) {
- val = changeType(val, type);
- }
-
- new StoreInst(val, ptr, isVolatile, currentBlock);
- }
-}
-
-void CLIJit::setStaticField(uint32 value, bool isVolatile, VMGenericClass* genClass, VMGenericMethod* genMethod) {
- VMField* field = compilingClass->assembly->getFieldFromToken(value, true, genClass, genMethod);
-
- VMCommonClass* cl = field->classDef;
- Value* arg = new LoadInst(cl->llvmVar(), "", currentBlock);
- Value* call = invoke(initialiseClassLLVM, arg, "", currentBlock, false);
- Value* staticCl = new BitCastInst(call, cl->staticType, "", currentBlock);
-
- std::vector<Value*> args;
- args.push_back(module->constantZero);
- args.push_back(field->offset);
- Value* ptr = GetElementPtrInst::Create(staticCl, args.begin(), args.end(), "",
- currentBlock);
- Value* val = pop();
- const Type* type = field->signature->naturalType;
- const Type* valType = val->getType();
- if (val == constantVMObjectNull) {
- val = Constant::getNullValue(type);
- } else if (type != valType) {
- val = changeType(val, type);
- }
- new StoreInst(val, ptr, isVolatile, currentBlock);
-}
-
-void CLIJit::JITVerifyNull(Value* obj) {
- CLIJit* jit = this;
- Constant* zero = Constant::getNullValue(obj->getType());
- Value* test = new ICmpInst(*jit->currentBlock, ICmpInst::ICMP_EQ, obj,
- zero, "");
-
- BasicBlock* exit = jit->createBasicBlock("verifyNullExit");
- BasicBlock* cont = jit->createBasicBlock("verifyNullCont");
-
- BranchInst::Create(exit, cont, test, jit->currentBlock);
-
- std::vector<Value*> args;
- if (currentExceptionBlock != endExceptionBlock) {
- InvokeInst::Create(CLIJit::nullPointerExceptionLLVM, unifiedUnreachable,
- currentExceptionBlock, args.begin(),
- args.end(), "", exit);
- } else {
- CallInst::Create(CLIJit::nullPointerExceptionLLVM, args.begin(),
- args.end(), "", exit);
- new UnreachableInst(getGlobalContext(), exit);
- }
-
-
- jit->currentBlock = cont;
-}
-
-llvm::Value* CLIJit::verifyAndComputePtr(llvm::Value* obj, llvm::Value* index,
- const llvm::Type* arrayType,
- bool verif) {
- JITVerifyNull(obj);
-
- if (index->getType() != Type::getInt32Ty(getGlobalContext())) {
- index = changeType(index, Type::getInt32Ty(getGlobalContext()));
- }
-
- if (true) {
- Value* size = arraySize(obj);
-
- Value* cmp = new ICmpInst(*currentBlock, ICmpInst::ICMP_SLT, index,
- size, "");
-
- BasicBlock* ifTrue = createBasicBlock("true verifyAndComputePtr");
- BasicBlock* ifFalse = createBasicBlock("false verifyAndComputePtr");
-
- branch(cmp, ifTrue, ifFalse, currentBlock);
-
- std::vector<Value*>args;
- args.push_back(new BitCastInst(obj, VMObject::llvmType, "", ifFalse));
- args.push_back(index);
- if (currentExceptionBlock != endExceptionBlock) {
- InvokeInst::Create(CLIJit::indexOutOfBoundsExceptionLLVM,
- unifiedUnreachable,
- currentExceptionBlock, args.begin(),
- args.end(), "", ifFalse);
- } else {
- CallInst::Create(CLIJit::indexOutOfBoundsExceptionLLVM, args.begin(),
- args.end(), "", ifFalse);
- new UnreachableInst(getGlobalContext(), ifFalse);
- }
-
- currentBlock = ifTrue;
- }
-
- Constant* zero = module->constantZero;
- Value* val = new BitCastInst(obj, arrayType, "", currentBlock);
-
- std::vector<Value*> indexes; //[3];
- indexes.push_back(zero);
- indexes.push_back(VMArray::elementsOffset());
- indexes.push_back(index);
- Value* ptr = GetElementPtrInst::Create(val, indexes.begin(), indexes.end(),
- "", currentBlock);
-
- return ptr;
-
-}
-
-Constant* VMArray::sizeOffset() {
- return VMThread::get()->getVM()->module->constantOne;
-}
-
-Constant* VMArray::elementsOffset() {
- return VMThread::get()->getVM()->module->constantTwo;
-}
-
-Value* CLIJit::arraySize(Value* array) {
- if (array->getType() != VMArray::llvmType) {
- array = new BitCastInst(array, VMArray::llvmType, "", currentBlock);
- }
- return CallInst::Create(arrayLengthLLVM, array, "", currentBlock);
- /*
- std::vector<Value*> args; //size= 2
- args.push_back(module->constantZero);
- args.push_back(VMArray::sizeOffset());
- Value* ptr = GetElementPtrInst::Create(array, args.begin(), args.end(),
- "", currentBlock);
- return new LoadInst(ptr, "", currentBlock);*/
-}
-
-Function* CLIJit::createDelegate() {
- Function* func = llvmFunction = compilingMethod->methPtr;
- Function::arg_iterator i = func->arg_begin()++, e = func->arg_end();
- Value* obj = i++;
- Value* target = i++;
- Value* handle = i++;
- assert(i == e);
-
- BasicBlock* entry = createBasicBlock("entry");
- obj = new BitCastInst(obj, MSCorlib::pDelegate->virtualType, "", entry);
- std::vector<Value*> elts;
- elts.push_back(module->constantZero);
- elts.push_back(module->constantOne);
- Value* targetPtr = GetElementPtrInst::Create(obj, elts.begin(), elts.end(),
- "", entry);
-
- elts.pop_back();
- elts.push_back(module->constantTwo);
- Value* handlePtr = GetElementPtrInst::Create(obj, elts.begin(), elts.end(),
- "", entry);
-
- new StoreInst(target, targetPtr, false, entry);
- new StoreInst(handle, handlePtr, false, entry);
- ReturnInst::Create(getGlobalContext(), entry);
-
- return func;
-}
-Function* CLIJit::invokeDelegate() {
- VMThread::get()->getVM()->error("implement me");
- return 0;
-}
-
-Function* CLIJit::compileIntern() {
- PRINT_DEBUG(N3_COMPILE, 1, COLOR_NORMAL, "intern compile %s\n",
- mvm::PrintBuffer(compilingMethod).cString());
-
- if (compilingClass->subclassOf(MSCorlib::pDelegate)) {
- const UTF8* name = compilingMethod->name;
- if (name == N3::ctorName) return createDelegate();
- else if (name == N3::invokeName) return invokeDelegate();
- else VMThread::get()->getVM()->error("implement me");
- } else {
- VMThread::get()->getVM()->error("implement me %s", mvm::PrintBuffer(compilingClass).cString());
- }
- return 0;
-}
-
-Function* CLIJit::compileNative(VMGenericMethod* genMethod) {
- PRINT_DEBUG(N3_COMPILE, 1, COLOR_NORMAL, "native compile %s\n",
- mvm::PrintBuffer(compilingMethod).cString());
-
- const FunctionType *funcType = compilingMethod->getSignature(genMethod);
-
- Function* func = llvmFunction = compilingMethod->methPtr;
- currentBlock = createBasicBlock("start");
- // TODO
- /*endExceptionBlock = createBasicBlock("exceptionBlock");
- endBlock = createBasicBlock("end");
- new UnwindInst(endExceptionBlock);*/
-
- uint32 nargs = func->arg_size();
- std::vector<Value*> nativeArgs;
-
- uint32 index = 0;
- for (Function::arg_iterator i = func->arg_begin();
- index < nargs; ++i, ++index) {
- nativeArgs.push_back(i);
- }
-
- void* natPtr = NativeUtil::nativeLookup(compilingClass, compilingMethod);
-
- Value* valPtr =
- ConstantExpr::getIntToPtr(ConstantInt::get(Type::getInt64Ty(getGlobalContext()), (uint64)natPtr),
- PointerType::getUnqual(funcType));
-
- Value* result = CallInst::Create(valPtr, nativeArgs.begin(),
- nativeArgs.end(), "", currentBlock);
-
-
- if (result->getType() != Type::getVoidTy(getGlobalContext()))
- ReturnInst::Create(getGlobalContext(), result, currentBlock);
- else
- ReturnInst::Create(getGlobalContext(), currentBlock);
-
-
- return llvmFunction;
-}
-
-uint32 CLIJit::readExceptionTable(uint32 offset, bool fat, VMGenericClass* genClass, VMGenericMethod* genMethod) {
- Assembly* ass = compilingClass->assembly;
- ByteCode* bytes = ass->bytes;
- uint32 nbe = 0;
- if (fat) {
- nbe = (READ_U3(bytes, offset) - 4) / 24;
- } else {
- nbe = (READ_U1(bytes, offset) - 4) / 12;
- READ_U2(bytes, offset);
- }
-
- if (nbe) {
- supplLocal = new AllocaInst(VMObject::llvmType, "exceptionVar",
- currentBlock);
- }
-
- BasicBlock* realEndExceptionBlock = endExceptionBlock;
- // TODO synchronized
-
- for (uint32 i = 0; i < nbe; ++i) {
- ExceptionBlockDesc* ex = new(allocator, "ExceptionBlockDesc") ExceptionBlockDesc();
- uint32 flags = 0;
- uint32 classToken = 0;
- if (fat) {
- flags = READ_U4(bytes, offset);
- ex->tryOffset = READ_U4(bytes, offset);
- ex->tryLength = READ_U4(bytes, offset);
- ex->handlerOffset = READ_U4(bytes, offset);
- ex->handlerLength = READ_U4(bytes, offset);
- classToken = READ_U4(bytes, offset);
- } else {
- flags = READ_U2(bytes, offset);
- ex->tryOffset = READ_U2(bytes, offset);
- ex->tryLength = READ_U1(bytes, offset);
- ex->handlerOffset = READ_U2(bytes, offset);
- ex->handlerLength = READ_U1(bytes, offset);
- classToken = READ_U4(bytes, offset);
- }
-
- if (!(opcodeInfos[ex->handlerOffset].newBlock)) {
- opcodeInfos[ex->handlerOffset].newBlock =
- createBasicBlock("handlerException");
- }
-
- ex->handler = opcodeInfos[ex->handlerOffset].newBlock;
-
- if (flags == CONSTANT_COR_ILEXCEPTION_CLAUSE_EXCEPTION) {
- ex->test = createBasicBlock("testException");
- if (classToken) {
- ex->catchClass = ass->loadType((N3*)VMThread::get()->getVM(), classToken,
- true, false, false, true, genClass, genMethod);
- } else {
- ex->catchClass = MSCorlib::pException;
- }
- opcodeInfos[ex->handlerOffset].reqSuppl = true;
- exceptions.push_back(ex);
-
- for (uint16 i = ex->tryOffset; i < ex->tryOffset + ex->tryLength; ++i) {
- if (opcodeInfos[i].exceptionBlock == endExceptionBlock) {
- opcodeInfos[i].exceptionBlock = ex->test;
- }
- }
-
- } else if (flags == CONSTANT_COR_ILEXCEPTION_CLAUSE_FINALLY) {
- ex->catchClass = 0;
- finallyHandlers.push_back(ex);
- } else {
- VMThread::get()->getVM()->error("implement me");
- }
- }
-
- bool first = true;
- for (std::vector<ExceptionBlockDesc*>::iterator i = exceptions.begin(),
- e = exceptions.end(); i!= e; ++i) {
-
- ExceptionBlockDesc* cur = *i;
- ExceptionBlockDesc* next = 0;
- if (i + 1 != e) {
- next = *(i + 1);
- }
-
- if (first) {
- cur->realTest = createBasicBlock("realTestException");
- } else {
- cur->realTest = cur->test;
- }
-
- if (next && cur->tryOffset == next->tryOffset &&
- cur->tryOffset + cur->tryLength == next->tryOffset + next->tryLength)
- first = false;
- else
- first = true;
-
- }
-
- for (std::vector<ExceptionBlockDesc*>::iterator i = exceptions.begin(),
- e = exceptions.end(); i!= e; ++i) {
-
- ExceptionBlockDesc* cur = *i;
- ExceptionBlockDesc* next = 0;
- BasicBlock* bbNext = 0;
- if (i + 1 != e) {
- next = *(i + 1);
- if (cur->tryOffset >= next->tryOffset &&
- cur->tryOffset + cur->tryLength <=
- next->tryOffset + next->tryLength) {
- bbNext = realEndExceptionBlock;
- } else {
- bbNext = next->realTest;
- }
- } else {
- bbNext = realEndExceptionBlock;
- }
-
- if (cur->realTest != cur->test) {
- const PointerType* PointerTy_0 = module->ptrType;
- std::vector<Value*> int32_eh_select_params;
- Instruction* ptr_eh_ptr = CallInst::Create(module->llvmGetException,
- "eh_ptr", cur->test);
- int32_eh_select_params.push_back(ptr_eh_ptr);
- Constant* C = ConstantExpr::getCast(Instruction::BitCast,
- module->personality, PointerTy_0);
- int32_eh_select_params.push_back(C);
- int32_eh_select_params.push_back(module->constantPtrNull);
- CallInst::Create(module->exceptionSelector,
- int32_eh_select_params.begin(),
- int32_eh_select_params.end(), "eh_select", cur->test);
- BranchInst::Create(cur->realTest, cur->test);
- }
-
- Value* cl = new LoadInst(cur->catchClass->llvmVar(), "", cur->realTest);
- Value* cmp = CallInst::Create(compareExceptionLLVM, cl, "", cur->realTest);
- BranchInst::Create(cur->handler, bbNext, cmp, cur->realTest);
-
- if (cur->handler->empty()) {
- Value* cpp = CallInst::Create(getCppExceptionLLVM, "", cur->handler);
- Value* exc = CallInst::Create(getCLIExceptionLLVM, "", cur->handler);
- CallInst::Create(clearExceptionLLVM, "", cur->handler);
- CallInst::Create(module->exceptionBeginCatch, cpp, "tmp8",
- cur->handler);
- std::vector<Value*> void_28_params;
- CallInst::Create(module->exceptionEndCatch, void_28_params.begin(),
- void_28_params.end(), "", cur->handler);
- new StoreInst(exc, supplLocal, false, cur->handler);
-
- for (uint16 i = cur->tryOffset; i < cur->tryOffset + cur->tryLength;
- ++i) {
- opcodeInfos[i].exception = exc;
- }
- }
-
- }
-
- return nbe;
-
-}
-
-#if N3_EXECUTE > 1
-static void printArgs(std::vector<llvm::Value*> args, BasicBlock* insertAt) {
- N3 *vm = VMThread::get()->getVM();
-
- for (std::vector<llvm::Value*>::iterator i = args.begin(),
- e = args.end(); i!= e; ++i) {
- llvm::Value* arg = *i;
- const llvm::Type* type = arg->getType();
- if (type == Type::getInt8Ty(getGlobalContext()) || type == Type::getInt16Ty(getGlobalContext()) || type == Type::getInt1Ty(getGlobalContext())) {
- CallInst::Create(vm->module->printIntLLVM, new ZExtInst(arg, Type::getInt32Ty(getGlobalContext()), "", insertAt), "", insertAt);
- } else if (type == Type::getInt32Ty(getGlobalContext())) {
- CallInst::Create(vm->module->printIntLLVM, arg, "", insertAt);
- } else if (type == Type::getInt64Ty(getGlobalContext())) {
- CallInst::Create(vm->module->printLongLLVM, arg, "", insertAt);
- } else if (type == Type::getFloatTy(getGlobalContext())) {
- CallInst::Create(vm->module->printFloatLLVM, arg, "", insertAt);
- } else if (type == Type::getDoubleTy(getGlobalContext())) {
- CallInst::Create(vm->module->printDoubleLLVM, arg, "", insertAt);
- } else {
- CallInst::Create(vm->module->printIntLLVM, new PtrToIntInst(arg, Type::getInt32Ty(getGlobalContext()), "", insertAt), "", insertAt);
- }
- }
-
-}
-#endif
-
-Function* CLIJit::compileFatOrTiny(VMGenericClass* genClass, VMGenericMethod* genMethod) {
- PRINT_DEBUG(N3_COMPILE, 1, COLOR_NORMAL, "tiny or fat compile %s\n",
- mvm::PrintBuffer(compilingMethod).cString());
- uint32 offset = compilingMethod->offsetInTextSection;
- ByteCode* bytes = compilingClass->assembly->bytes;
- uint8 header = READ_U1(bytes, offset);
- bool tiny = false;
- uint32 localVarSig = 0;
- uint32 maxStack = 0;
- uint32 codeLen = 0;
- uint32 nbe = 0;
-
- if ((header & 3) == CONSTANT_CorILMethod_TinyFormat) {
- tiny = true;
- codeLen = (header & 0xfffc) >> 2;
- } else if ((header & 3) != CONSTANT_CorILMethod_FatFormat) {
- VMThread::get()->getVM()->error("unknown Method Format");
- } else {
- header += (READ_U1(bytes, offset) << 8); //header
- maxStack = READ_U2(bytes, offset);
- codeLen = READ_U4(bytes, offset);
- localVarSig = READ_U4(bytes, offset);
- }
-
-
- /* TODO Synchronize
- bool synchro = isSynchro(compilingMethod->flags);
- */
-
- const FunctionType *funcType = compilingMethod->getSignature(genMethod);
-
- Function* func = llvmFunction = compilingMethod->methPtr;
- currentBlock = createBasicBlock("start");
- endExceptionBlock = createBasicBlock("exceptionBlock");
- unifiedUnreachable = createBasicBlock("unifiedUnreachable");
-
-
- opcodeInfos = (Opinfo*)alloca(codeLen * sizeof(Opinfo));
- memset(opcodeInfos, 0, codeLen * sizeof(Opinfo));
- for (uint32 i = 0; i < codeLen; ++i) {
- opcodeInfos[i].exceptionBlock = endExceptionBlock;
- }
-
- if (!tiny) {
- if (header & CONSTANT_CorILMethod_MoreSects) {
- uint32 excpOffset = 0;
- if ((codeLen % 4) == 0) {
- excpOffset = offset + codeLen;
- } else {
- excpOffset = offset + codeLen + (4 - (codeLen % 4));
- }
-
- uint8 flags = READ_U1(bytes, excpOffset);
- nbe = readExceptionTable(excpOffset,
- flags & CONSTANT_CorILMethod_Sect_FatFormat, genClass, genMethod);
- }
- }
-
- for (Function::arg_iterator i = func->arg_begin(), e = func->arg_end();
- i != e; ++i) {
-
- const Type* cur = i->getType();
-
- AllocaInst* alloc = new AllocaInst(cur, "", currentBlock);
- new StoreInst(i, alloc, false, currentBlock);
- arguments.push_back(alloc);
- }
-
- if (localVarSig) {
- std::vector<VMCommonClass*> temp;
- compilingClass->assembly->readSignature(localVarSig, temp, genClass, genMethod);
-
- for (std::vector<VMCommonClass*>::iterator i = temp.begin(),
- e = temp.end(); i!= e; ++i) {
- VMCommonClass* cl = *i;
- cl->resolveType(false, false, genMethod);
- AllocaInst* alloc = new AllocaInst(cl->naturalType, "", currentBlock);
- if (cl->naturalType->isSingleValueType()) {
- new StoreInst(Constant::getNullValue(cl->naturalType), alloc, false,
- currentBlock);
- } else {
- uint64 size = mvm::MvmModule::getTypeSize(cl->naturalType);
-
- std::vector<Value*> params;
- params.push_back(new BitCastInst(alloc, module->ptrType, "",
- currentBlock));
- params.push_back(module->constantInt8Zero);
- params.push_back(ConstantInt::get(Type::getInt32Ty(getGlobalContext()), size));
- params.push_back(module->constantZero);
- CallInst::Create(module->llvm_memset_i32, params.begin(),
- params.end(), "", currentBlock);
-
- }
- locals.push_back(alloc);
- }
- }
-
- exploreOpcodes(&compilingClass->assembly->bytes->elements[offset], codeLen);
-
- endBlock = createBasicBlock("end");
-
- const Type* endType = funcType->getReturnType();
- if (endType != Type::getVoidTy(getGlobalContext())) {
- endNode = PHINode::Create(endType, "", endBlock);
- } else if (compilingMethod->structReturn) {
- const Type* lastType =
- funcType->getContainedType(funcType->getNumContainedTypes() - 1);
- endNode = PHINode::Create(lastType, "", endBlock);
- }
-
- compileOpcodes(&compilingClass->assembly->bytes->elements[offset], codeLen, genClass, genMethod);
-
- currentBlock = endBlock;
- pred_iterator PI = pred_begin(endBlock);
- pred_iterator PE = pred_end(endBlock);
- if (PI == PE) {
- endBlock->eraseFromParent();
- } else {
- if (endType != Type::getVoidTy(getGlobalContext())) {
-#if N3_EXECUTE > 1
- std::vector<Value*> args;
- args.push_back(endNode);
- printArgs(args, endBlock);
-#endif
- ReturnInst::Create(getGlobalContext(), endNode, endBlock);
- } else if (compilingMethod->structReturn) {
- const Type* lastType =
- funcType->getContainedType(funcType->getNumContainedTypes() - 1);
- uint64 size = mvm::MvmModule::getTypeSize(lastType->getContainedType(0));
- Value* obj = --llvmFunction->arg_end();
- std::vector<Value*> params;
- params.push_back(new BitCastInst(obj, module->ptrType, "",
- currentBlock));
- params.push_back(new BitCastInst(endNode, module->ptrType, "",
- currentBlock));
- params.push_back(ConstantInt::get(Type::getInt32Ty(getGlobalContext()), size));
- params.push_back(module->constantFour);
- CallInst::Create(module->llvm_memcpy_i32, params.begin(), params.end(),
- "", currentBlock);
- ReturnInst::Create(getGlobalContext(), currentBlock);
- } else {
- ReturnInst::Create(getGlobalContext(), endBlock);
- }
- }
-
- PI = pred_begin(endExceptionBlock);
- PE = pred_end(endExceptionBlock);
- if (PI == PE) {
- endExceptionBlock->eraseFromParent();
- } else {
- CallInst* ptr_eh_ptr = CallInst::Create(getCppExceptionLLVM, "eh_ptr",
- endExceptionBlock);
- CallInst::Create(module->unwindResume, ptr_eh_ptr, "", endExceptionBlock);
- new UnreachableInst(getGlobalContext(), endExceptionBlock);
- }
-
- PI = pred_begin(unifiedUnreachable);
- PE = pred_end(unifiedUnreachable);
- if (PI == PE) {
- unifiedUnreachable->eraseFromParent();
- } else {
- new UnreachableInst(getGlobalContext(), unifiedUnreachable);
- }
-
- mvm::MvmModule::runPasses(llvmFunction, VMThread::get()->perFunctionPasses);
-
- if (nbe == 0 && codeLen < 50) {
- PRINT_DEBUG(N3_COMPILE, 1, COLOR_NORMAL, "%s can be inlined\n",
- mvm::PrintBuffer(compilingMethod).cString());
- compilingMethod->canBeInlined = true;
- }
-
- return llvmFunction;
-}
-
-Instruction* CLIJit::inlineCompile(Function* parentFunction, BasicBlock*& curBB,
- BasicBlock* endExBlock,
- std::vector<Value*>& args, VMGenericClass* genClass, VMGenericMethod* genMethod) {
-
- PRINT_DEBUG(N3_COMPILE, 1, COLOR_NORMAL, "tiny or fat inline compile %s\n",
- mvm::PrintBuffer(compilingMethod).cString());
- uint32 offset = compilingMethod->offsetInTextSection;
- ByteCode* bytes = compilingClass->assembly->bytes;
- uint8 header = READ_U1(bytes, offset);
- bool tiny = false;
- uint32 localVarSig = 0;
- uint32 maxStack = 0;
- uint32 codeLen = 0;
-
- if ((header & 3) == CONSTANT_CorILMethod_TinyFormat) {
- tiny = true;
- codeLen = (header & 0xfffc) >> 2;
- } else if ((header & 3) != CONSTANT_CorILMethod_FatFormat) {
- VMThread::get()->getVM()->error("unknown Method Format");
- } else {
- header += (READ_U1(bytes, offset) << 8); //header
- maxStack = READ_U2(bytes, offset);
- codeLen = READ_U4(bytes, offset);
- localVarSig = READ_U4(bytes, offset);
- }
-
-
- /* TODO Synchronize
- bool synchro = isSynchro(compilingMethod->flags);
- */
-
- const FunctionType *funcType = compilingMethod->getSignature(genMethod);
-
- llvmFunction = parentFunction;
- currentBlock = curBB;
- endExceptionBlock = 0;
-
-
- opcodeInfos = (Opinfo*)alloca(codeLen * sizeof(Opinfo));
- memset(opcodeInfos, 0, codeLen * sizeof(Opinfo));
- for (uint32 i = 0; i < codeLen; ++i) {
- opcodeInfos[i].exceptionBlock = endExBlock;
- }
-
- if (!tiny) {
- if (header & CONSTANT_CorILMethod_MoreSects) {
- assert(0 && "inlining a function with exceptions!");
- uint32 excpOffset = 0;
- if ((codeLen % 4) == 0) {
- excpOffset = offset + codeLen;
- } else {
- excpOffset = offset + codeLen + (4 - (codeLen % 4));
- }
-
- uint8 flags = READ_U1(bytes, excpOffset);
- readExceptionTable(excpOffset,
- flags & CONSTANT_CorILMethod_Sect_FatFormat, genClass, genMethod);
- }
- }
-
- for (std::vector<Value*>::iterator i = args.begin(), e = args.end();
- i != e; ++i) {
-
- const Type* cur = (*i)->getType();
-
- AllocaInst* alloc = new AllocaInst(cur, "", currentBlock);
- new StoreInst(*i, alloc, false, currentBlock);
- arguments.push_back(alloc);
- }
-
- if (localVarSig) {
- std::vector<VMCommonClass*> temp;
- compilingClass->assembly->readSignature(localVarSig, temp, genClass, genMethod);
-
- for (std::vector<VMCommonClass*>::iterator i = temp.begin(),
- e = temp.end(); i!= e; ++i) {
- VMCommonClass* cl = *i;
- cl->resolveType(false, false, genMethod);
- AllocaInst* alloc = new AllocaInst(cl->naturalType, "", currentBlock);
- if (cl->naturalType->isSingleValueType()) {
- new StoreInst(Constant::getNullValue(cl->naturalType), alloc, false,
- currentBlock);
- } else {
- uint64 size = mvm::MvmModule::getTypeSize(cl->naturalType);
-
- std::vector<Value*> params;
- params.push_back(new BitCastInst(alloc, module->ptrType, "",
- currentBlock));
- params.push_back(module->constantInt8Zero);
- params.push_back(ConstantInt::get(Type::getInt32Ty(getGlobalContext()), size));
- params.push_back(module->constantZero);
- CallInst::Create(module->llvm_memset_i32, params.begin(),
- params.end(), "", currentBlock);
-
- }
- locals.push_back(alloc);
- }
- }
-
- exploreOpcodes(&compilingClass->assembly->bytes->elements[offset], codeLen);
-
- endBlock = createBasicBlock("end");
-
- const Type* endType = funcType->getReturnType();
- if (endType != Type::getVoidTy(getGlobalContext())) {
- endNode = PHINode::Create(endType, "", endBlock);
- } else if (compilingMethod->structReturn) {
- const Type* lastType =
- funcType->getContainedType(funcType->getNumContainedTypes() - 1);
- endNode = PHINode::Create(lastType, "", endBlock);
- }
-
- compileOpcodes(&compilingClass->assembly->bytes->elements[offset], codeLen, genClass, genMethod);
-
- curBB = endBlock;
-
- PRINT_DEBUG(N3_COMPILE, 1, COLOR_NORMAL,
- "end tiny or fat inline compile %s\n",
- mvm::PrintBuffer(compilingMethod).cString());
-
- return endNode;
-}
-
-
-Function* CLIJit::compile(VMClass* cl, VMMethod* meth) {
- mvm::BumpPtrAllocator *a = new mvm::BumpPtrAllocator();
- CLIJit* jit = new(*a, "CLIJit") CLIJit(*a);
- jit->compilingClass = cl;
- jit->compilingMethod = meth;
- jit->module = cl->vm->module;
- Function* func;
- meth->getSignature(static_cast<VMGenericMethod*>(meth));
-
- if (isInternal(meth->implFlags)) {
- func = jit->compileNative(static_cast<VMGenericMethod*>(meth));
- } else if (meth->offsetInTextSection == 0) {
- func = jit->compileIntern();
- } else {
- func = jit->compileFatOrTiny(static_cast<VMGenericClass*>(cl), static_cast<VMGenericMethod*>(meth));
- }
-
- delete a;
- // printf("Compiling: %s\n", mvm::PrintBuffer(meth).cString());
- return func;
-}
-
-
-llvm::Function *VMMethod::compiledPtr(VMGenericMethod* genMethod) {
- if (methPtr != 0) return methPtr;
- else {
- classDef->aquire();
- if (methPtr == 0) {
- methPtr = Function::Create(getSignature(genMethod), GlobalValue::ExternalWeakLinkage,
- mvm::PrintBuffer(this).cString(), classDef->vm->getLLVMModule());
- classDef->vm->functions->hash(methPtr, this);
- }
- classDef->release();
- return methPtr;
- }
-}
-
-VMMethod* CLIJit::getMethod(llvm::Function* F) {
- VMMethod* meth = VMThread::get()->getVM()->functions->lookup(F);
- return meth;
-}
-
-void VMField::initField(VMObject* obj) {
- VMField* field = this;
- Constant* offset = field->offset;
- const TargetData* targetData = mvm::MvmModule::executionEngine->getTargetData();
- bool stat = isStatic(field->flags);
- const Type* clType = stat ? field->classDef->staticType :
- field->classDef->virtualType;
-
- const StructLayout* sl =
- targetData->getStructLayout((StructType*)(clType->getContainedType(0)));
- uint64 ptrOffset = sl->getElementOffset(dyn_cast<ConstantInt>(offset)->getZExtValue());
-
- field->ptrOffset = ptrOffset;
-
-}
-
-void CLIJit::initialise() {
-}
-
-void CLIJit::initialiseAppDomain(N3* vm) {
- mvm::MvmModule::protectEngine.lock();
- mvm::MvmModule::executionEngine->addModule(vm->getLLVMModule());
- mvm::MvmModule::protectEngine.unlock();
-}
-
-namespace n3 {
- namespace llvm_runtime {
- #include "LLVMRuntime.inc"
- }
-}
-
-
-void CLIJit::initialiseBootstrapVM(N3* vm) {
- Module* module = vm->getLLVMModule();
- mvm::MvmModule::protectEngine.lock();
- mvm::MvmModule::executionEngine->addModule(module);
- mvm::MvmModule::protectEngine.unlock();
-
- n3::llvm_runtime::makeLLVMModuleContents(module);
-
- VMObject::llvmType =
- PointerType::getUnqual(module->getTypeByName("CLIObject"));
- VMArray::llvmType =
- PointerType::getUnqual(module->getTypeByName("CLIArray"));
- CacheNode::llvmType =
- PointerType::getUnqual(module->getTypeByName("CacheNode"));
- Enveloppe::llvmType =
- PointerType::getUnqual(module->getTypeByName("Enveloppe"));
-
-#define GET_LLVM_ARRAY_TYPE(name, type) \
- Array##name::llvmType = \
- PointerType::getUnqual(module->getTypeByName("Array"#name)); \
-
- ON_TYPES(GET_LLVM_ARRAY_TYPE, _F_NT)
-
-#undef GET_LLVM_ARRAY_TYPE
-
-#ifdef WITH_TRACER
- markAndTraceLLVM = module->getFunction("MarkAndTrace");
- markAndTraceLLVMType = markAndTraceLLVM->getFunctionType();
- vmObjectTracerLLVM = module->getFunction("CLIObjectTracer");
-#endif
-
-
- initialiseClassLLVM = module->getFunction("initialiseClass");
- virtualLookupLLVM = module->getFunction("n3VirtualLookup");
-
- arrayConsLLVM = module->getFunction("newArray");
- objConsLLVM = module->getFunction("newObject");
- newStringLLVM = module->getFunction("newString");
- objInitLLVM = module->getFunction("initialiseObject");
- arrayMultiConsLLVM = module->getFunction("newMultiArray");
- arrayLengthLLVM = module->getFunction("arrayLength");
- instanceOfLLVM = module->getFunction("n3InstanceOf");
-
- nullPointerExceptionLLVM = module->getFunction("n3NullPointerException");
- classCastExceptionLLVM = module->getFunction("n3ClassCastException");
- indexOutOfBoundsExceptionLLVM = module->getFunction("indexOutOfBounds");
-
-
- throwExceptionLLVM = module->getFunction("ThrowException");
- clearExceptionLLVM = module->getFunction("ClearException");
- compareExceptionLLVM = module->getFunction("CompareException");
- getCppExceptionLLVM = module->getFunction("GetCppException");
- getCLIExceptionLLVM = module->getFunction("GetCLIException");
-
-
- printExecutionLLVM = module->getFunction("n3PrintExecution");
-
-
-
- constantVMObjectNull = Constant::getNullValue(VMObject::llvmType);
-}
-
-Constant* CLIJit::constantVMObjectNull;
-
-
-Value* CLIJit::invoke(Value *F, std::vector<llvm::Value*> args,
- const char* Name,
- BasicBlock *InsertAtEnd, bool structReturn) {
-#if N3_EXECUTE > 1
- printArgs(args, InsertAtEnd);
-#endif
-
- Value* ret = 0;
- if (structReturn) {
- const Type* funcType = F->getType();
- if (isa<PointerType>(funcType)) {
- funcType = funcType->getContainedType(0);
- }
- const Type* lastType = funcType->getContainedType(funcType->getNumContainedTypes() - 1);
- ret = new AllocaInst(lastType->getContainedType(0), "", InsertAtEnd);
- args.push_back(ret);
- }
- Value* val = 0;
- // means: is there a handler for me?
- if (currentExceptionBlock != endExceptionBlock) {
- BasicBlock* ifNormal = createBasicBlock("no exception block");
- currentBlock = ifNormal;
- val = InvokeInst::Create(F, ifNormal, currentExceptionBlock, args.begin(),
- args.end(), Name, InsertAtEnd);
- } else {
- val = CallInst::Create(F, args.begin(), args.end(), Name, InsertAtEnd);
- }
- if (ret) return ret;
- else return val;
-}
-
-Value* CLIJit::invoke(Value *F, Value* arg1, const char* Name,
- BasicBlock *InsertAtEnd, bool structReturn) {
-
- std::vector<Value*> args;
- args.push_back(arg1);
-#if N3_EXECUTE > 1
- printArgs(args, InsertAtEnd);
-#endif
- Value* ret = 0;
- if (structReturn) {
- const Type* funcType = F->getType();
- if (isa<PointerType>(funcType)) {
- funcType = funcType->getContainedType(0);
- }
- const Type* lastType = funcType->getContainedType(funcType->getNumContainedTypes() - 1);
- ret = new AllocaInst(lastType->getContainedType(0), "", InsertAtEnd);
- args.push_back(ret);
- }
-
- Value* val = 0;
- // means: is there a handler for me?
- if (currentExceptionBlock != endExceptionBlock) {
- BasicBlock* ifNormal = createBasicBlock("no exception block");
- currentBlock = ifNormal;
- val = InvokeInst::Create(F, ifNormal, currentExceptionBlock, args.begin(),
- args.end(), Name, InsertAtEnd);
- } else {
- val = CallInst::Create(F, args.begin(), args.end(), Name, InsertAtEnd);
- }
-
- if (ret) return ret;
- else return val;
-}
-
-Value* CLIJit::invoke(Value *F, Value* arg1, Value* arg2,
- const char* Name, BasicBlock *InsertAtEnd,
- bool structReturn) {
-
- std::vector<Value*> args;
- args.push_back(arg1);
- args.push_back(arg2);
-#if N3_EXECUTE > 1
- printArgs(args, InsertAtEnd);
-#endif
-
- Value* ret = 0;
- if (structReturn) {
- const Type* funcType = F->getType();
- if (isa<PointerType>(funcType)) {
- funcType = funcType->getContainedType(0);
- }
- const Type* lastType = funcType->getContainedType(funcType->getNumContainedTypes() - 1);
- ret = new AllocaInst(lastType->getContainedType(0), "", InsertAtEnd);
- args.push_back(ret);
- }
-
- Value* val = 0;
- // means: is there a handler for me?
- if (currentExceptionBlock != endExceptionBlock) {
- BasicBlock* ifNormal = createBasicBlock("no exception block");
- currentBlock = ifNormal;
- val = InvokeInst::Create(F, ifNormal, currentExceptionBlock, args.begin(),
- args.end(), Name, InsertAtEnd);
- } else {
- val = CallInst::Create(F, args.begin(), args.end(), Name, InsertAtEnd);
- }
- if (ret) return ret;
- else return val;
-}
-
-Value* CLIJit::invoke(Value *F, const char* Name,
- BasicBlock *InsertAtEnd, bool structReturn) {
-
- std::vector<Value*> args;
- Value* ret = 0;
- if (structReturn) {
- const Type* funcType = F->getType();
- if (isa<PointerType>(funcType)) {
- funcType = funcType->getContainedType(0);
- }
- const Type* lastType = funcType->getContainedType(funcType->getNumContainedTypes() - 1);
- ret = new AllocaInst(lastType->getContainedType(0), "", InsertAtEnd);
- args.push_back(ret);
- }
-
- Value* val = 0;
- // means: is there a handler for me?
- if (currentExceptionBlock != endExceptionBlock) {
- BasicBlock* ifNormal = createBasicBlock("no exception block");
- currentBlock = ifNormal;
- val = InvokeInst::Create(F, ifNormal, currentExceptionBlock, args.begin(),
- args.end(), Name, InsertAtEnd);
- } else {
- val = CallInst::Create(F, args.begin(), args.end(), Name, InsertAtEnd);
- }
- if (ret) return ret;
- else return val;
-}
-
-
-
-
-namespace mvm {
-llvm::FunctionPass* createEscapeAnalysisPass(llvm::Function*, llvm::Function*);
-llvm::FunctionPass* createLowerArrayLengthPass();
-}
-
-
-static void addPass(FunctionPassManager *PM, Pass *P) {
- // Add the pass to the pass manager...
- PM->add(P);
-}
-
-void AddStandardCompilePasses(FunctionPassManager *PM) {
- llvm::MutexGuard locked(mvm::MvmModule::executionEngine->lock);
- // LLVM does not allow calling functions from other modules in verifier
- //PM->add(llvm::createVerifierPass()); // Verify that input is correct
-
- addPass(PM, createCFGSimplificationPass()); // Clean up disgusting code
- addPass(PM, createPromoteMemoryToRegisterPass());// Kill useless allocas
-
- addPass(PM, createInstructionCombiningPass()); // Cleanup for scalarrepl.
- addPass(PM, createJumpThreadingPass()); // Thread jumps.
- addPass(PM, createCFGSimplificationPass()); // Merge & remove BBs
- addPass(PM, createScalarReplAggregatesPass()); // Break up aggregate allocas
- addPass(PM, createInstructionCombiningPass()); // Combine silly seq's
-
- addPass(PM, createCFGSimplificationPass()); // Merge & remove BBs
- addPass(PM, createReassociatePass()); // Reassociate expressions
- addPass(PM, createLICMPass()); // Hoist loop invariants
-
- addPass(PM, createLoopUnswitchPass()); // Unswitch loops.
- addPass(PM, createIndVarSimplifyPass()); // Canonicalize indvars
- addPass(PM, createLoopDeletionPass()); // Delete dead loops
- addPass(PM, createLoopUnrollPass()); // Unroll small loops*/
- addPass(PM, createInstructionCombiningPass()); // Clean up after the unroller
- addPass(PM, createGVNPass()); // Remove redundancies
- addPass(PM, createSCCPPass()); // Constant prop with SCCP
- addPass(PM, createCFGSimplificationPass()); // Merge & remove BBs
-
- // Run instcombine after redundancy elimination to exploit opportunities
- // opened up by them.
- addPass(PM, createInstructionCombiningPass());
-
- addPass(PM, createDeadStoreEliminationPass()); // Delete dead stores
- addPass(PM, createAggressiveDCEPass()); // Delete dead instructions
- addPass(PM, createCFGSimplificationPass()); // Merge & remove BBs
-
- addPass(PM, mvm::createLowerArrayLengthPass());
-}
diff --git a/vmkit/lib/N3/VMCore/CLIJit.h b/vmkit/lib/N3/VMCore/CLIJit.h
deleted file mode 100644
index d0d68e4..0000000
--- a/vmkit/lib/N3/VMCore/CLIJit.h
+++ /dev/null
@@ -1,493 +0,0 @@
-//===------------- CLIJit.h - CLI just in time compiler -------------------===//
-//
-// N3
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#ifndef N3_CLIJit_H
-#define N3_CLIJit_H
-
-#include "mvm/JIT.h"
-#include "mvm/Object.h"
-#include "mvm/PrintBuffer.h"
-#include "mvm/Threads/Locks.h"
-
-#include "llvm/BasicBlock.h"
-#include "llvm/DerivedTypes.h"
-#include "llvm/Function.h"
-#include "llvm/Instructions.h"
-#include "llvm/PassManager.h"
-#include "llvm/Type.h"
-#include "llvm/ExecutionEngine/ExecutionEngine.h"
-#include "llvm/ExecutionEngine/GenericValue.h"
-#include "llvm/Target/TargetData.h"
-
-#include "types.h"
-
-namespace n3 {
-
-class CacheNode;
-class N3;
-class N3ModuleProvider;
-class VMClass;
-class VMClassArray;
-class VMCommonClass;
-class VMMethod;
-class VMObject;
-class VMGenericClass;
-class VMGenericMethod;
-class N3VirtualTable;
-
-class ExceptionBlockDesc : public mvm::PermanentObject {
-public:
- uint32 tryOffset;
- uint32 tryLength;
- uint32 handlerOffset;
- uint32 handlerLength;
- VMCommonClass* catchClass;
- llvm::BasicBlock* test;
- llvm::BasicBlock* realTest;
- llvm::BasicBlock* handler;
-
- virtual void print(mvm::PrintBuffer* buf) const;
-};
-
-class Opinfo {
-public:
- llvm::BasicBlock* newBlock;
- llvm::BasicBlock* exceptionBlock;
- bool reqSuppl;
- llvm::Value* exception;
-
- virtual void print(mvm::PrintBuffer* buf) const {
- buf->write("Opinfo");
- }
-};
-
-
-class CLIJit : public mvm::PermanentObject {
-public:
- mvm::BumpPtrAllocator &allocator;
-
- CLIJit(mvm::BumpPtrAllocator &a) : allocator(a) {}
-
- virtual void print(mvm::PrintBuffer* buf) const {
- buf->write("CLIJit");
- }
-
- static const char* OpcodeNames[0xE1];
- static const char* OpcodeNamesFE[0x23];
-
- static N3VirtualTable* makeVT(VMClass* cl, bool isStatic);
- static N3VirtualTable* makeArrayVT(VMClassArray* cl);
-
- static void printExecution(char*, n3::VMMethod*);
- void compileOpcodes(uint8*, uint32, VMGenericClass* genClass, VMGenericMethod* genMethod);
- void exploreOpcodes(uint8*, uint32);
-
- llvm::Function* llvmFunction;
- VMMethod* compilingMethod;
- VMClass* compilingClass;
- mvm::BaseIntrinsics* module;
-
- std::vector<llvm::Value*> arguments;
- std::vector<llvm::Value*> locals;
-
- // end function
- llvm::BasicBlock* endBlock;
- llvm::PHINode* endNode;
-
- // block manipulation
- llvm::BasicBlock* currentBlock;
- llvm::BasicBlock* createBasicBlock(const char* name = "");
- void setCurrentBlock(llvm::BasicBlock* block);
-
- // branches
- void branch(llvm::Value* test, llvm::BasicBlock* ifTrue,
- llvm::BasicBlock* ifFalse, llvm::BasicBlock* insert);
- void branch(llvm::BasicBlock* where, llvm::BasicBlock* insert);
-
- // stack manipulation
- std::vector<llvm::Value*> stack;
- void push(llvm::Value*);
- llvm::Value* pop();
- llvm::Value* top();
-
- // exceptions
- llvm::BasicBlock* endExceptionBlock;
- llvm::BasicBlock* currentExceptionBlock;
- llvm::BasicBlock* unifiedUnreachable;
- std::vector<ExceptionBlockDesc*> exceptions;
- std::vector<ExceptionBlockDesc*> finallyHandlers;
-
- uint32 readExceptionTable(uint32 offset, bool fat, VMGenericClass* genClass, VMGenericMethod* genMethod);
- std::vector<llvm::BasicBlock*> leaves;
- llvm::Value* supplLocal;
-
- // calls
- void invoke(uint32 value, VMGenericClass* genClass, VMGenericMethod* genMethod);
- void invokeInterfaceOrVirtual(uint32 value, VMGenericClass* genClass, VMGenericMethod* genMethod);
- void invokeNew(uint32 value, VMGenericClass* genClass, VMGenericMethod* genMethod);
- llvm::Value* getVirtualField(uint32 value, VMGenericClass* genClass, VMGenericMethod* genMethod);
- llvm::Value* getStaticField(uint32 value, VMGenericClass* genClass, VMGenericMethod* genMethod);
- void setVirtualField(uint32 value, bool isVolatile, VMGenericClass* genClass, VMGenericMethod* genMethod);
- void setStaticField(uint32 value, bool isVolatile, VMGenericClass* genClass, VMGenericMethod* genMethod);
-
- void JITVerifyNull(llvm::Value* obj);
-
- // array manipulation
- llvm::Value* verifyAndComputePtr(llvm::Value* obj, llvm::Value* index,
- const llvm::Type* arrayType,
- bool verif = true);
- llvm::Value* arraySize(llvm::Value* obj);
-
- Opinfo* opcodeInfos;
-
- static llvm::Function* printExecutionLLVM;
- static llvm::Function* indexOutOfBoundsExceptionLLVM;
- static llvm::Function* nullPointerExceptionLLVM;
- static llvm::Function* initialiseClassLLVM;
- static llvm::Function* throwExceptionLLVM;
- static llvm::Function* clearExceptionLLVM;
- static llvm::Function* compareExceptionLLVM;
- static llvm::Function* classCastExceptionLLVM;
- static llvm::Function* newStringLLVM;
- static llvm::Function* arrayLengthLLVM;
-
- static llvm::Function* compile(VMClass* cl, VMMethod* meth);
-
-#ifdef WITH_TRACER
- static llvm::Function* markAndTraceLLVM;
- static const llvm::FunctionType* markAndTraceLLVMType;
-#endif
- static llvm::Function* vmObjectTracerLLVM;
- static llvm::Function* arrayConsLLVM;
- static llvm::Function* arrayMultiConsLLVM;
- static llvm::Function* objConsLLVM;
- static llvm::Function* objInitLLVM;
- static llvm::Function* instanceOfLLVM;
- static llvm::Function* getCppExceptionLLVM;
- static llvm::Function* getCLIExceptionLLVM;
-
- static void initialise();
- static void initialiseAppDomain(N3* vm);
- static void initialiseBootstrapVM(N3* vm);
-
- llvm::Function* compileNative(VMGenericMethod* genMethod);
- llvm::Function* compileFatOrTiny(VMGenericClass* genClass, VMGenericMethod* genMethod);
- llvm::Function* compileIntern();
-
- llvm::Function* createDelegate();
- llvm::Function* invokeDelegate();
-
- llvm::Value* invoke(llvm::Value *F, std::vector<llvm::Value*> args,
- const char* Name,
- llvm::BasicBlock *InsertAtEnd, bool structReturn);
- // Alternate CallInst ctors w/ two actuals, w/ one actual and no
- // actuals, respectively.
- llvm::Value* invoke(llvm::Value *F, llvm::Value *Actual1,
- llvm::Value *Actual2, const char* Name,
- llvm::BasicBlock *InsertAtEnd, bool structReturn);
- llvm::Value* invoke(llvm::Value *F, llvm::Value *Actual1,
- const char* Name, llvm::BasicBlock *InsertAtEnd,
- bool structReturn);
- llvm::Value* invoke(llvm::Value *F, const char* Name,
- llvm::BasicBlock *InsertAtEnd, bool structReturn);
-
- void makeArgs(const llvm::FunctionType* type,
- std::vector<llvm::Value*>& Args, bool structReturn);
- llvm::Value* changeType(llvm::Value* val, const llvm::Type* type);
-
- static llvm::Function* virtualLookupLLVM;
-
- llvm::Instruction* lowerMathOps(VMMethod* meth,
- std::vector<llvm::Value*>& args);
-
- static llvm::Constant* constantVMObjectNull;
-
- llvm::Instruction* inlineCompile(llvm::Function* parentFunction,
- llvm::BasicBlock*& curBB,
- llvm::BasicBlock* endExBlock,
- std::vector<llvm::Value*>& args, VMGenericClass* genClass, VMGenericMethod* genMethod);
-
- std::map<VMMethod*, bool> inlineMethods;
-
- llvm::Instruction* invokeInline(VMMethod* meth,
- std::vector<llvm::Value*>& args, VMGenericClass* genClass, VMGenericMethod* genMethod);
-
- static VMMethod* getMethod(llvm::Function* F);
-};
-
-enum Opcode {
- NOP = 0x00,
- BREAK = 0x01,
- LDARG_0 = 0x02,
- LDARG_1 = 0x03,
- LDARG_2 = 0x04,
- LDARG_3 = 0x05,
- LDLOC_0 = 0x06,
- LDLOC_1 = 0x07,
- LDLOC_2 = 0x08,
- LDLOC_3 = 0x09,
- STLOC_0 = 0x0A,
- STLOC_1 = 0x0B,
- STLOC_2 = 0x0C,
- STLOC_3 = 0x0D,
- LDARG_S = 0x0E,
- LDARGA_S = 0x0F,
- STARG_S = 0x10,
- LDLOC_S = 0x11,
- LDLOCA_S = 0x12,
- STLOC_S = 0x13,
- LDNULL = 0x14,
- LDC_I4_M1 = 0x15,
- LDC_I4_0 = 0x16,
- LDC_I4_1 = 0x17,
- LDC_I4_2 = 0x18,
- LDC_I4_3 = 0x19,
- LDC_I4_4 = 0x1A,
- LDC_I4_5 = 0x1B,
- LDC_I4_6 = 0x1C,
- LDC_I4_7 = 0x1D,
- LDC_I4_8 = 0x1E,
- LDC_I4_S = 0x1F,
- LDC_I4 = 0x20,
- LDC_I8 = 0x21,
- LDC_R4 = 0x22,
- LDC_R8 = 0x23,
- UNUSED99 = 0x24,
- DUP = 0x25,
- POP = 0x26,
- JMP = 0x27,
- CALL = 0x28,
- CALLI = 0x29,
- RET = 0x2A,
- BR_S = 0x2B,
- BRFALSE_S = 0x2C,
- BRTRUE_S = 0x2D,
- BEQ_S = 0x2E,
- BGE_S = 0x2F,
- BGT_S = 0x30,
- BLE_S = 0x31,
- BLT_S = 0x32,
- BNE_UN_S = 0x33,
- BGE_UN_S = 0x34,
- BGT_UN_S = 0x35,
- BLE_UN_S = 0x36,
- BLT_UN_S = 0x37,
- BR = 0x38,
- BRFALSE = 0x39,
- BRTRUE = 0x3A,
- BEQ = 0x3B,
- BGE = 0x3C,
- BGT = 0x3D,
- BLE = 0x3E,
- BLT = 0x3F,
- BNE_UN = 0x40,
- BGE_UN = 0x41,
- BGT_UN = 0x42,
- BLE_UN = 0x43,
- BLT_UN = 0x44,
- SWITCH = 0x45,
- LDIND_I1 = 0x46,
- LDIND_U1 = 0x47,
- LDIND_I2 = 0x48,
- LDIND_U2 = 0x49,
- LDIND_I4 = 0x4A,
- LDIND_U4 = 0x4B,
- LDIND_I8 = 0x4C,
- LDIND_I = 0x4D,
- LDIND_R4 = 0x4E,
- LDIND_R8 = 0x4F,
- LDIND_REF = 0x50,
- STIND_REF = 0x51,
- STIND_I1 = 0x52,
- STIND_I2 = 0x53,
- STIND_I4 = 0x54,
- STIND_I8 = 0x55,
- STIND_R4 = 0x56,
- STIND_R8 = 0x57,
- ADD = 0x58,
- SUB = 0x59,
- MUL = 0x5A,
- DIV = 0x5B,
- DIV_UN = 0x5C,
- REM = 0x5D,
- REM_UN = 0x5E,
- AND = 0x5F,
- OR = 0x60,
- XOR = 0x61,
- SHL = 0x62,
- SHR = 0x63,
- SHR_UN = 0x64,
- NEG = 0x65,
- NOT = 0x66,
- CONV_I1 = 0x67,
- CONV_I2 = 0x68,
- CONV_I4 = 0x69,
- CONV_I8 = 0x6A,
- CONV_R4 = 0x6B,
- CONV_R8 = 0x6C,
- CONV_U4 = 0x6D,
- CONV_U8 = 0x6E,
- CALLVIRT = 0x6F,
- CPOBJ = 0x70,
- LDOBJ = 0x71,
- LDSTR = 0x72,
- NEWOBJ = 0x73,
- CASTCLASS = 0x74,
- ISINST = 0x75,
- CONV_R_UN = 0x76,
- UNUSED58 = 0x77,
- UNUSED1 = 0x78,
- UNBOX = 0x79,
- THROW = 0x7A,
- LDFLD = 0x7B,
- LDFLDA = 0x7C,
- STFLD = 0x7D,
- LDSFLD = 0x7E,
- LDSFLDA = 0x7F,
- STSFLD = 0x80,
- STOBJ = 0x81,
- CONV_OVF_I1_UN = 0x82,
- CONV_OVF_I2_UN = 0x83,
- CONV_OVF_I4_UN = 0x84,
- CONV_OVF_I8_UN = 0x85,
- CONV_OVF_U1_UN = 0x86,
- CONV_OVF_U2_UN = 0x87,
- CONV_OVF_U4_UN = 0x88,
- CONV_OVF_U8_UN = 0x89,
- CONV_OVF_I_UN = 0x8A,
- CONV_OVF_U_UN = 0x8B,
- BOX = 0x8C,
- NEWARR = 0x8D,
- LDLEN = 0x8E,
- LDELEMA = 0x8F,
- LDELEM_I1 = 0x90,
- LDELEM_U1 = 0x91,
- LDELEM_I2 = 0x92,
- LDELEM_U2 = 0x93,
- LDELEM_I4 = 0x94,
- LDELEM_U4 = 0x95,
- LDELEM_I8 = 0x96,
- LDELEM_I = 0x97,
- LDELEM_R4 = 0x98,
- LDELEM_R8 = 0x99,
- LDELEM_REF = 0x9A,
- STELEM_I = 0x9B,
- STELEM_I1 = 0x9C,
- STELEM_I2 = 0x9D,
- STELEM_I4 = 0x9E,
- STELEM_I8 = 0x9F,
- STELEM_R4 = 0xA0,
- STELEM_R8 = 0xA1,
- STELEM_REF = 0xA2,
- LDELEM = 0xA3,
- STELEM = 0xA4,
- UNBOX_ANY = 0xA5,
- UNUSED5 = 0xA6,
- UNUSED6 = 0xA7,
- UNUSED7 = 0xA8,
- UNUSED8 = 0xA9,
- UNUSED9 = 0xAA,
- UNUSED10 = 0xAB,
- UNUSED11 = 0xAC,
- UNUSED12 = 0xAD,
- UNUSED13 = 0xAE,
- UNUSED14 = 0xAF,
- UNUSED15 = 0xB0,
- UNUSED16 = 0xB1,
- UNUSED17 = 0xB2,
- CONV_OVF_I1 = 0xB3,
- CONV_OVF_U1 = 0xB4,
- CONV_OVF_I2 = 0xB5,
- CONV_OVF_U2 = 0xB6,
- CONV_OVF_I4 = 0xB7,
- CONV_OVF_U4 = 0xB8,
- CONV_OVF_I8 = 0xB9,
- CONV_OVF_U8 = 0xBA,
- UNUSED50 = 0xBB,
- UNUSED18 = 0xBC,
- UNUSED19 = 0xBD,
- UNUSED20 = 0xBE,
- UNUSED21 = 0xBF,
- UNUSED22 = 0xC0,
- UNUSED23 = 0xC1,
- REFANYVAL = 0xC2,
- CKFINITE = 0xC3,
- UNUSED24 = 0xC4,
- UNUSED25 = 0xC5,
- MKREFANY = 0xC6,
- UNUSED59 = 0xC7,
- UNUSED60 = 0xC8,
- UNUSED61 = 0xC9,
- UNUSED62 = 0xCA,
- UNUSED63 = 0xCB,
- UNUSED64 = 0xCC,
- UNUSED65 = 0xCD,
- UNUSED66 = 0xCE,
- UNUSED67 = 0xCF,
- LDTOKEN = 0xD0,
- CONV_U2 = 0xD1,
- CONV_U1 = 0xD2,
- CONV_I = 0xD3,
- CONV_OVF_I = 0xD4,
- CONV_OVF_U = 0xD5,
- ADD_OVF = 0xD6,
- ADD_OVF_UN = 0xD7,
- MUL_OVF = 0xD8,
- MUL_OVF_UN = 0xD9,
- SUB_OVF = 0xDA,
- SUB_OVF_UN = 0xDB,
- ENDFINALLY = 0xDC,
- LEAVE = 0xDD,
- LEAVE_S = 0xDE,
- STIND_I = 0xDF,
- CONV_U = 0xE0
-};
-
-enum OpcodeFE {
- ARGLIST = 0x00,
- CEQ = 0x01,
- CGT = 0x02,
- CGT_UN = 0x03,
- CLT = 0x04,
- CLT_UN = 0x05,
- LDFTN = 0x06,
- LDVIRTFTN = 0x07,
- UNUSED56 = 0x08,
- LDARG = 0x09,
- LDARGA = 0x0A,
- STARG = 0x0B,
- LDLOC = 0x0C,
- LDLOCA = 0x0D,
- STLOC = 0x0E,
- LOCALLOC = 0x0F,
- UNUSED57 = 0x10,
- ENDFILTER = 0x11,
- UNALIGNED_ = 0x12,
- VOLATILE_ = 0x13,
- TAIL_ = 0x14,
- INITOBJ = 0x15,
- CONSTRAINED_ = 0x16,
- CPBLK = 0x17,
- INITBLK = 0x18,
- NO_ = 0x19,
- RETHROW = 0x1A,
- UNUSED = 0x1B,
- SIZEOF = 0x1C,
- REFANYTYPE = 0x1D,
- READONLY_ = 0x1E,
- UNUSED53 = 0x1F,
- UNUSED54 = 0x20,
- UNUSED55 = 0x21,
- UNUSED70 = 0x22
-};
-
-
-} // end namespace n3
-
-#endif
diff --git a/vmkit/lib/N3/VMCore/CLIJitMeta.cpp b/vmkit/lib/N3/VMCore/CLIJitMeta.cpp
deleted file mode 100644
index 414b911..0000000
--- a/vmkit/lib/N3/VMCore/CLIJitMeta.cpp
+++ /dev/null
@@ -1,323 +0,0 @@
-//===------ CLIJitMeta.cpp - CLI class/method/field operators -------------===//
-//
-// N3
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#include <stdarg.h>
-
-#include "llvm/ExecutionEngine/GenericValue.h"
-#include "llvm/GlobalVariable.h"
-#include "llvm/LLVMContext.h"
-
-#include "types.h"
-
-#include "mvm/JIT.h"
-
-#include "CLIAccess.h"
-#include "CLIJit.h"
-#include "CLIString.h"
-#include "N3.h"
-#include "VMClass.h"
-#include "VMObject.h"
-#include "VMThread.h"
-
-using namespace n3;
-using namespace llvm;
-
-// TODO: MUST CHECK the type!
-// if (llvm::isa<check>(signature->naturalType)) {
-// if (signature->naturalType == Type::getFloatTy(getGlobalContext())) {
-
-#define IMPLEMENTS_VMFIELD_ASSESSORS(name, type, do_root) \
- void VMField::set##name(VMObject* obj, type val) { \
- llvm_gcroot(obj, 0); \
- do_root(val, 0); \
- \
- if (classDef->status < ready) \
- classDef->resolveType(true, true, NULL); \
- \
- *(type*)((char *)obj + ptrOffset) = val; \
- \
- return; \
- } \
- \
- type VMField::get##name(VMObject* obj) { \
- llvm_gcroot(obj, 0); \
- if (classDef->status < ready) \
- classDef->resolveType(true, true, NULL); \
- \
- type res; \
- do_root(res, 0); \
- res = *(type *)((char *)obj + ptrOffset); \
- return res; \
- }
-
-ON_TYPES(IMPLEMENTS_VMFIELD_ASSESSORS, _F_NTR)
-
-#undef IMPLEMENTS_VMFIELD_ASSESSORS
-
-GenericValue VMMethod::invokeGeneric(std::vector<llvm::GenericValue>& args) {
- // at this step, we must not launch the gc because objects arguments are somewhere in the stack a copying collector
- // can not know where they are
- assert(code); // compiling a method can trigger a gc
- return mvm::MvmModule::executionEngine->runFunction(methPtr, args);
-}
-
-GenericValue VMMethod::invokeGeneric(va_list ap) {
- Function* func = methPtr;
- std::vector<GenericValue> args;
- for (Function::arg_iterator i = func->arg_begin(), e = func->arg_end();
- i != e; ++i) {
- const Type* cur = i->getType();
- if (cur == Type::getInt8Ty(getGlobalContext())) {
- GenericValue gv;
- gv.IntVal = APInt(8, va_arg(ap, int));
- args.push_back(gv);
- } else if (cur == Type::getInt16Ty(getGlobalContext())) {
- GenericValue gv;
- gv.IntVal = APInt(16, va_arg(ap, int));
- args.push_back(gv);
- } else if (cur == Type::getInt32Ty(getGlobalContext())) {
- GenericValue gv;
- gv.IntVal = APInt(32, va_arg(ap, int));
- args.push_back(gv);
- } else if (cur == Type::getInt64Ty(getGlobalContext())) {
- GenericValue gv1;
- gv1.IntVal = APInt(64, va_arg(ap, uint64));
- args.push_back(gv1);
- } else if (cur == Type::getDoubleTy(getGlobalContext())) {
- GenericValue gv1;
- gv1.DoubleVal = va_arg(ap, double);
- args.push_back(gv1);
- } else if (cur == Type::getFloatTy(getGlobalContext())) {
- GenericValue gv;
- gv.FloatVal = (float)(va_arg(ap, double));
- args.push_back(gv);
- } else {
- GenericValue gv(va_arg(ap, VMObject*));
- args.push_back(gv);
- }
- }
-
- return invokeGeneric(args);
-}
-
-GenericValue VMMethod::invokeGeneric(...) {
- va_list ap;
- va_start(ap, this);
- GenericValue res = invokeGeneric(ap);
- va_end(ap);
- return res;
-}
-
-#define DEFINE_INVOKE(name, type, extractor) \
- type VMMethod::invoke##name(...) { \
- va_list ap; \
- va_start(ap, this); \
- GenericValue res = invokeGeneric(ap); \
- va_end(ap); \
- return (type)res.extractor; \
- }
-
-ON_TYPES(DEFINE_INVOKE, _F_NTE)
-
-#undef DEFINE_INVOKE
-
-#define DEFINE_INVOKE_VOID(name, type, extractor) \
- type VMMethod::invoke##name(...) { \
- va_list ap; \
- va_start(ap, this); \
- invokeGeneric(ap); \
- va_end(ap); \
- }
-
-ON_VOID(DEFINE_INVOKE_VOID, _F_NTE)
-
-#undef DEFINE_INVOKE_VOID
-
-
-// // mettre en param un Function *
-// // materializeFunction avant
-// GenericValue VMMethod::operator()(va_list ap) {
-
-// if (classDef->status < ready)
-// classDef->resolveType(true, true, NULL);
-
-// Function* func = compiledPtr(NULL);
-
-// std::vector<GenericValue> args;
-// for (Function::arg_iterator i = func->arg_begin(), e = func->arg_end();
-// i != e; ++i) {
-// const Type* type = i->getType();
-// if (type == Type::getInt8Ty(getGlobalContext())) {
-// GenericValue gv;
-// gv.IntVal = APInt(8, va_arg(ap, int));
-// args.push_back(gv);
-// } else if (type == Type::getInt16Ty(getGlobalContext())) {
-// GenericValue gv;
-// gv.IntVal = APInt(16, va_arg(ap, int));
-// args.push_back(gv);
-// } else if (type == Type::getInt32Ty(getGlobalContext())) {
-// GenericValue gv;
-// gv.IntVal = APInt(32, va_arg(ap, int));
-// args.push_back(gv);
-// } else if (type == Type::getInt64Ty(getGlobalContext())) {
-// GenericValue gv1;
-// gv1.IntVal = APInt(64, va_arg(ap, uint64));
-// args.push_back(gv1);
-// } else if (type == Type::getDoubleTy(getGlobalContext())) {
-// GenericValue gv1;
-// gv1.DoubleVal = va_arg(ap, double);
-// args.push_back(gv1);
-// } else if (type == Type::getFloatTy(getGlobalContext())) {
-// GenericValue gv;
-// gv.FloatVal = (float)(va_arg(ap, double));
-// args.push_back(gv);
-// } else {
-// GenericValue gv(va_arg(ap, VMObject*));
-// args.push_back(gv);
-// }
-// }
-
-// return mvm::MvmModule::executionEngine->runFunction(func, args);
-// }
-
-// GenericValue VMMethod::operator()(VMObject* obj, va_list ap) {
-
-// if (classDef->status < ready)
-// classDef->resolveType(true, true, NULL);
-
-// Function* func = compiledPtr(NULL);
-
-// std::vector<GenericValue> args;
-// GenericValue object(obj);
-// args.push_back(object);
-
-// for (Function::arg_iterator i = ++(func->arg_begin()), e = func->arg_end();
-// i != e; ++i) {
-// const Type* type = i->getType();
-// if (type == Type::getInt8Ty(getGlobalContext())) {
-// GenericValue gv;
-// gv.IntVal = APInt(8, va_arg(ap, int));
-// args.push_back(gv);
-// } else if (type == Type::getInt16Ty(getGlobalContext())) {
-// GenericValue gv;
-// gv.IntVal = APInt(16, va_arg(ap, int));
-// args.push_back(gv);
-// } else if (type == Type::getInt32Ty(getGlobalContext())) {
-// GenericValue gv;
-// gv.IntVal = APInt(32, va_arg(ap, int));
-// args.push_back(gv);
-// } else if (type == Type::getInt64Ty(getGlobalContext())) {
-// GenericValue gv1;
-// gv1.IntVal = APInt(64, va_arg(ap, uint64));
-// args.push_back(gv1);
-// } else if (type == Type::getDoubleTy(getGlobalContext())) {
-// GenericValue gv1;
-// gv1.DoubleVal = va_arg(ap, double);
-// args.push_back(gv1);
-// } else if (type == Type::getFloatTy(getGlobalContext())) {
-// GenericValue gv;
-// gv.FloatVal = (float)(va_arg(ap, double));
-// args.push_back(gv);
-// } else {
-// GenericValue gv(va_arg(ap, VMObject*));
-// args.push_back(gv);
-// }
-// }
-
-// return mvm::MvmModule::executionEngine->runFunction(func, args);
-// }
-
-
-// GenericValue VMMethod::operator()(...) {
-// va_list ap;
-// va_start(ap, this);
-// GenericValue ret = (*this)(ap);
-// va_end(ap);
-// return ret;
-// }
-
-// GenericValue VMMethod::run(...) {
-// va_list ap;
-// va_start(ap, this);
-// GenericValue ret = (*this)(ap);
-// va_end(ap);
-// return ret;
-// }
-
-// GenericValue VMMethod::operator()(std::vector<GenericValue>& args) {
-
-// if (classDef->status < ready)
-// classDef->resolveType(true, true, NULL);
-
-// Function* func = compiledPtr(NULL);
-// return mvm::MvmModule::executionEngine->runFunction(func, args);
-// }
-
-GlobalVariable* VMCommonClass::llvmVar() {
- if (!_llvmVar) {
- aquire();
- if (!_llvmVar) {
- Module* Mod = vm->getLLVMModule();
- const Type* pty = PointerType::getUnqual(Type::getInt8Ty(getGlobalContext()));
- Constant* cons =
- ConstantExpr::getIntToPtr(ConstantInt::get(Type::getInt64Ty(getGlobalContext()), uint64_t (this)),
- pty);
-
- _llvmVar = new GlobalVariable(*Mod, pty, true,
- GlobalValue::ExternalLinkage,
- cons, "");
-
- }
- release();
- }
- return _llvmVar;
-}
-
-GlobalVariable* VMField::llvmVar() {
- if (!_llvmVar) {
- classDef->aquire();
- if (!_llvmVar) {
- const Type* pty = PointerType::getUnqual(Type::getInt8Ty(getGlobalContext()));
- Module* Mod = classDef->vm->getLLVMModule();
- Constant* cons =
- ConstantExpr::getIntToPtr(ConstantInt::get(Type::getInt64Ty(getGlobalContext()), uint64_t (this)),
- pty);
-
- _llvmVar = new GlobalVariable(*Mod, pty, true,
- GlobalValue::ExternalLinkage,
- cons, "");
- }
- classDef->release();
- }
- return _llvmVar;
-}
-
-GlobalVariable* VMMethod::llvmVar() {
- if (!_llvmVar) {
- classDef->aquire();
- if (!_llvmVar) {
- Module* Mod = classDef->vm->getLLVMModule();
- const Type* pty = PointerType::getUnqual(Type::getInt8Ty(getGlobalContext()));
- Constant* cons =
- ConstantExpr::getIntToPtr(ConstantInt::get(Type::getInt64Ty(getGlobalContext()), uint64_t (this)),
- pty);
-
- _llvmVar = new GlobalVariable(*Mod, pty, true,
- GlobalValue::ExternalLinkage,
- cons, "");
-
- }
- classDef->release();
- }
- return _llvmVar;
-}
-
-Constant* VMObject::classOffset() {
- return VMThread::get()->getVM()->module->constantOne;
-}
diff --git a/vmkit/lib/N3/VMCore/CLIRuntimeJIT.cpp b/vmkit/lib/N3/VMCore/CLIRuntimeJIT.cpp
deleted file mode 100644
index a3aeb6b..0000000
--- a/vmkit/lib/N3/VMCore/CLIRuntimeJIT.cpp
+++ /dev/null
@@ -1,195 +0,0 @@
-//===--- CLIRuntimeJIT.cpp - Runtime functions for the JIT compiled code --===//
-//
-// The vmkit project
-//
-// This file is distributed under the University Of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-
-#include <cstdio>
-
-#include "llvm/DerivedTypes.h"
-#include "llvm/Instructions.h"
-#include "llvm/ExecutionEngine/ExecutionEngine.h"
-
-#include "mvm/JIT.h"
-#include "mvm/Object.h"
-#include "mvm/PrintBuffer.h"
-#include "mvm/Threads/Locks.h"
-
-#include "CLIString.h"
-#include "MSCorlib.h"
-#include "N3.h"
-#include "VMArray.h"
-#include "VMCache.h"
-#include "VMClass.h"
-#include "VMObject.h"
-#include "VMThread.h"
-#include "Assembly.h"
-
-#include "mvm/GC/GC.h"
-
-#include <cstdarg>
-
-using namespace n3;
-using namespace llvm;
-
-extern "C" VMObject* initialiseClass(VMClass* cl) {
- cl->clinitClass(NULL);
- return cl->staticInstance;
-}
-
-extern "C" void n3ClassCastException() {
- fflush(stdout);
- assert(0 && "implement class cast exception");
-}
-
-extern "C" void n3NullPointerException() {
- fflush(stdout);
- assert(0 && "implement null pointer exception");
-}
-
-extern "C" void indexOutOfBounds() {
- fflush(stdout);
- assert(0 && "implement index out of bounds exception");
-}
-
-extern "C" VMObject* newString(const ArrayChar* utf8) {
- N3 *vm = (N3*)VMThread::get()->getVM();
- declare_gcroot(VMObject*, res) = vm->arrayToString(utf8);
- return res;
-}
-
-extern "C" bool n3InstanceOf(VMObject* obj, VMCommonClass* cl) {
- return VMObject::instanceOf(obj, cl);
-}
-
-extern "C" void* GetCppException() {
- return VMThread::getCppException();
-}
-
-extern "C" void ThrowException(VMObject* obj) {
- return VMThread::throwException(obj);
-}
-
-extern "C" VMObject* GetCLIException() {
- declare_gcroot(VMObject*, res) = VMThread::getCLIException();
- return res;
-}
-
-extern "C" bool CompareException(VMClass* cl) {
- return VMThread::compareException(cl);
-}
-
-extern "C" void ClearException() {
- return VMThread::get()->clearException();
-}
-
-static VMObject* doMultiNewIntern(VMClassArray* cl, uint32 dim, sint32* buf) {
- if (dim <= 0) VMThread::get()->getVM()->error("Can't happen");
- sint32 n = buf[0];
- if (n < 0) VMThread::get()->getVM()->negativeArraySizeException(n);
-
- declare_gcroot(VMArray*, res) = (VMArray*)cl->doNew(n);
- if (dim > 1) {
- VMCommonClass* base = cl->baseClass;
- if (n > 0) {
- for (sint32 i = 0; i < n; ++i) {
- res->elements[i] = doMultiNewIntern((VMClassArray*)base, dim - 1, &(buf[1]));
- }
- }
- for (uint32 i = 1; i < dim; ++i) {
- if (buf[i] < 0) VMThread::get()->getVM()->negativeArraySizeException(buf[i]);
- }
- }
- return res;
-}
-
-extern "C" VMObject* doMultiNew(VMClassArray* cl, ...) {
- sint32* dimSizes = (sint32*)alloca(cl->dims * sizeof(sint32));
- va_list ap;
- va_start(ap, cl);
- for (uint32 i = 0; i < cl->dims; ++i) {
- dimSizes[i] = va_arg(ap, sint32);
- }
- va_end(ap);
- return doMultiNewIntern(cl, cl->dims, dimSizes);
-}
-
-extern "C" CacheNode* n3VirtualLookup(CacheNode* cache, VMObject *obj) {
- Enveloppe* enveloppe = cache->enveloppe;
- VMCommonClass* ocl = obj->classOf;
- VMMethod* orig = enveloppe->originalMethod;
-
- CacheNode* rcache = 0;
- CacheNode* tmp = enveloppe->firstCache;
- CacheNode* last = tmp;
- enveloppe->cacheLock->lock();
-
- while (tmp) {
- if (ocl == tmp->lastCible) {
- rcache = tmp;
- break;
- } else {
- last = tmp;
- tmp = tmp->next;
- }
- }
-
- if (!rcache) {
- VMMethod* dmeth = ocl->lookupMethodDontThrow(orig->name,
- orig->parameters,
- false, true);
- if (dmeth == 0) {
- mvm::PrintBuffer _methAsciiz(orig->name);
- mvm::PrintBuffer _nameAsciiz(orig->classDef->name);
- mvm::PrintBuffer _nameSpaceAsciiz(orig->classDef->nameSpace);
- const char* methAsciiz = _methAsciiz.cString();
- const char* nameAsciiz = _nameAsciiz.cString();
- const char* nameSpaceAsciiz = _nameSpaceAsciiz.cString();
-
- char *buf = (char*)alloca(3 + strlen(methAsciiz) +
- strlen(nameAsciiz) +
- strlen(nameSpaceAsciiz));
- sprintf(buf, "%s.%s.%s", nameSpaceAsciiz, nameAsciiz, methAsciiz);
- const UTF8* newName = VMThread::get()->getVM()->asciizToUTF8(buf);
- dmeth = ocl->lookupMethod(newName, orig->parameters, false, true);
- }
-
- if (cache->methPtr) {
- rcache = CacheNode::allocate(orig->classDef->assembly->allocator);
- rcache->enveloppe = enveloppe;
- } else {
- rcache = cache;
- }
-
- Function* func = dmeth->compiledPtr(NULL);
- rcache->methPtr = mvm::MvmModule::executionEngine->getPointerToGlobal(func);
- rcache->lastCible = (VMClass*)ocl;
- rcache->box = (dmeth->classDef->super == MSCorlib::pValue);
- }
-
- if (enveloppe->firstCache != rcache) {
- CacheNode *f = enveloppe->firstCache;
- enveloppe->firstCache = rcache;
- last->next = rcache->next;
- rcache->next = f;
-
- }
-
- enveloppe->cacheLock->unlock();
-
- return rcache;
-}
-
-extern "C" VMObject* newObject(VMClass* cl) {
- declare_gcroot(VMObject*, res) = cl->doNew();
- return res;
-}
-
-extern "C" VMObject* newArray(VMClassArray* cl, sint32 nb) {
- declare_gcroot(VMObject*, res) = cl->doNew(nb);
- return res;
-}
diff --git a/vmkit/lib/N3/VMCore/CLISignature.cpp b/vmkit/lib/N3/VMCore/CLISignature.cpp
deleted file mode 100644
index 1ed5899..0000000
--- a/vmkit/lib/N3/VMCore/CLISignature.cpp
+++ /dev/null
@@ -1,549 +0,0 @@
-//===--------- CLISignature.cpp - Reads CLI signatures --------------------===//
-//
-// N3
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-
-#include "Assembly.h"
-#include "MSCorlib.h"
-#include "N3.h"
-#include "Reader.h"
-#include "VMClass.h"
-#include "VMThread.h"
-
-#include "SignatureNames.def"
-
-using namespace n3;
-
-// ECMA 335: page 150 23.1.16 Element types used in signatures
-
-
-static VMCommonClass* METHOD_ElementTypeEnd(uint32 op, Assembly* ass,
- uint32& offset, VMGenericClass* genClass, VMGenericMethod* genMethod) {
- VMThread::get()->getVM()->error("implement me");
- return 0;
-}
-
-static VMCommonClass* METHOD_ElementTypeVoid(uint32 op, Assembly* ass,
- uint32& offset, VMGenericClass* genClass, VMGenericMethod* genMethod) {
- return MSCorlib::pVoid;
-}
-
-static VMCommonClass* METHOD_ElementTypeBoolean(uint32 op, Assembly* ass,
- uint32& offset, VMGenericClass* genClass, VMGenericMethod* genMethod) {
- return MSCorlib::pBoolean;
-}
-
-static VMCommonClass* METHOD_ElementTypeChar(uint32 op, Assembly* ass,
- uint32& offset, VMGenericClass* genClass, VMGenericMethod* genMethod) {
- return MSCorlib::pChar;
-}
-
-static VMCommonClass* METHOD_ElementTypeI1(uint32 op, Assembly* ass,
- uint32& offset, VMGenericClass* genClass, VMGenericMethod* genMethod) {
- return MSCorlib::pSInt8;
-}
-
-static VMCommonClass* METHOD_ElementTypeU1(uint32 op, Assembly* ass,
- uint32& offset, VMGenericClass* genClass, VMGenericMethod* genMethod) {
- return MSCorlib::pUInt8;
-}
-
-static VMCommonClass* METHOD_ElementTypeI2(uint32 op, Assembly* ass,
- uint32& offset, VMGenericClass* genClass, VMGenericMethod* genMethod) {
- return MSCorlib::pSInt16;
-}
-
-static VMCommonClass* METHOD_ElementTypeU2(uint32 op, Assembly* ass,
- uint32& offset, VMGenericClass* genClass, VMGenericMethod* genMethod) {
- return MSCorlib::pUInt16;
-}
-
-static VMCommonClass* METHOD_ElementTypeI4(uint32 op, Assembly* ass,
- uint32& offset, VMGenericClass* genClass, VMGenericMethod* genMethod) {
- return MSCorlib::pSInt32;
-}
-
-static VMCommonClass* METHOD_ElementTypeU4(uint32 op, Assembly* ass,
- uint32& offset, VMGenericClass* genClass, VMGenericMethod* genMethod) {
- return MSCorlib::pUInt32;
-}
-
-static VMCommonClass* METHOD_ElementTypeI8(uint32 op, Assembly* ass,
- uint32& offset, VMGenericClass* genClass, VMGenericMethod* genMethod) {
- return MSCorlib::pSInt64;
-}
-
-static VMCommonClass* METHOD_ElementTypeU8(uint32 op, Assembly* ass,
- uint32& offset, VMGenericClass* genClass, VMGenericMethod* genMethod) {
- return MSCorlib::pUInt64;
-}
-
-static VMCommonClass* METHOD_ElementTypeR4(uint32 op, Assembly* ass,
- uint32& offset, VMGenericClass* genClass, VMGenericMethod* genMethod) {
- return MSCorlib::pFloat;
-}
-
-static VMCommonClass* METHOD_ElementTypeR8(uint32 op, Assembly* ass,
- uint32& offset, VMGenericClass* genClass, VMGenericMethod* genMethod) {
- return MSCorlib::pDouble;
-}
-
-static VMCommonClass* METHOD_ElementTypeString(uint32 op, Assembly* ass,
- uint32& offset, VMGenericClass* genClass, VMGenericMethod* genMethod) {
- return MSCorlib::pString;
-}
-
-static VMCommonClass* METHOD_ElementTypePtr(uint32 op, Assembly* ass,
- uint32& offset, VMGenericClass* genClass, VMGenericMethod* genMethod) {
- VMCommonClass* contains = ass->exploreType(offset, genClass, genMethod);
- return ass->constructPointer(contains, 1);
-}
-
-static VMCommonClass* METHOD_ElementTypeByRef(uint32 op, Assembly* ass,
- uint32& offset, VMGenericClass* genClass, VMGenericMethod* genMethod) {
- VMCommonClass* contains = ass->exploreType(offset, genClass, genMethod);
- return ass->constructPointer(contains, 1);
-}
-
-static VMCommonClass* METHOD_ElementTypeValueType(uint32 op, Assembly* ass,
- uint32& offset, VMGenericClass* genClass, VMGenericMethod* genMethod) {
- uint32 value = ass->uncompressSignature(offset);
- uint32 table = value & 3;
- uint32 index = value >> 2;
- uint32 token = 0;
-
- switch (table) {
- case 0:
- table = CONSTANT_TypeDef;
- break;
- case 1:
- table = CONSTANT_TypeRef;
- break;
- case 2:
- table = CONSTANT_TypeSpec;
- break;
- default:
- VMThread::get()->getVM()->error("unknown TypeDefOrRefEncoded %d", index);
- break;
- }
-
- token = (table << 24) + index;
- VMCommonClass* cl = ass->loadType((N3*) (VMThread::get()->getVM()), token, false,
- false, false, true, genClass, genMethod);
- return cl;
-}
-
-static VMCommonClass* METHOD_ElementTypeClass(uint32 op, Assembly* ass,
- uint32& offset, VMGenericClass* genClass, VMGenericMethod* genMethod) {
- uint32 value = ass->uncompressSignature(offset);
- uint32 table = value & 3;
- uint32 index = value >> 2;
- uint32 token = 0;
-
- switch (table) {
- case 0:
- table = CONSTANT_TypeDef;
- break;
- case 1:
- table = CONSTANT_TypeRef;
- break;
- case 2:
- table = CONSTANT_TypeSpec;
- break;
- default:
- VMThread::get()->getVM()->error("unknown TypeDefOrRefEncoded %d", index);
- break;
- }
-
- token = (table << 24) + index;
- VMCommonClass* cl = ass->loadType((N3*) (VMThread::get()->getVM()), token, false,
- false, false, true, genClass, genMethod);
- return cl;
-}
-
-static VMCommonClass* METHOD_ElementTypeVar(uint32 op, Assembly* ass,
- uint32& offset, VMGenericClass* genClass, VMGenericMethod* genMethod) {
- uint32 number = ass->uncompressSignature(offset);
-
- assert(genClass != NULL && "Current Generic Class not set!");
-
- return genClass->genericParams[number];
-}
-
-static VMCommonClass* METHOD_ElementTypeArray(uint32 op, Assembly* ass,
- uint32& offset, VMGenericClass* genClass, VMGenericMethod* genMethod) {
- VMCommonClass* cl = ass->exploreType(offset, genClass, genMethod);
- uint32 rank = ass->uncompressSignature(offset);
- uint32 numSizes = ass->uncompressSignature(offset);
-
- if (numSizes != 0) {
- printf("type = %s\n", mvm::PrintBuffer(cl).cString());
- VMThread::get()->getVM()->error("implement me");
- }
-
- for (uint32 i = 0; i < numSizes; ++i) {
- ass->uncompressSignature(offset);
- }
-
- uint32 numObounds = ass->uncompressSignature(offset);
- if (numObounds != 0)
- VMThread::get()->getVM()->error("implement me");
-
- for (uint32 i = 0; i < numObounds; ++i) {
- ass->uncompressSignature(offset);
- }
-
- VMClassArray* array = ass->constructArray(cl, rank);
- return array;
-}
-
-static VMCommonClass* METHOD_ElementTypeGenericInst(uint32 op, Assembly* ass,
- uint32& offset, VMGenericClass* genClass, VMGenericMethod* genMethod) {
- // offset points to (CLASS | VALUETYPE) TypeDefOrRefEncoded
-
- // skip generic type definition
- offset++; // this is (CLASS | VALUETYPE)
-
- // save starting offset for later use
- uint32 genericTypeOffset = offset;
-
- ass->uncompressSignature(offset); // TypeDefOrRefEncoded
-
- //VMCommonClass* cl = ass->exploreType(offset);
-
- uint32 argCount = ass->uncompressSignature(offset);
-
- std::vector<VMCommonClass*> args;
-
- // Get generic arguments.
- for (uint32 i = 0; i < argCount; ++i) {
- args.push_back(ass->exploreType(offset, genClass, genMethod));
- }
-
- // save offset
- uint32 endOffset = offset;
- // restore starting offset
- offset = genericTypeOffset;
-
- // TypeDefOrRefEncoded
- uint32 value = ass->uncompressSignature(offset);
- uint32 table = value & 3;
- uint32 index = value >> 2;
- uint32 token = 0;
-
- switch (table) {
- case 0:
- table = CONSTANT_TypeDef;
- break;
- case 1:
- table = CONSTANT_TypeRef;
- break;
- case 2:
- table = CONSTANT_TypeSpec;
- break;
- default:
- VMThread::get()->getVM()->error("unknown TypeDefOrRefEncoded %d", index);
- break;
- }
-
- token = (table << 24) + index;
- VMCommonClass* cl = ass->loadType((N3*) (VMThread::get()->getVM()), token, false,
- false, false, true, args, genClass, genMethod);
- // restore endOffset
- offset = endOffset;
-
- return cl;
-}
-
-static VMCommonClass* METHOD_ElementTypeTypedByRef(uint32 op, Assembly* ass,
- uint32& offset, VMGenericClass* genClass, VMGenericMethod* genMethod) {
- return MSCorlib::typedReference;
-}
-
-static VMCommonClass* METHOD_ElementTypeI(uint32 op, Assembly* ass,
- uint32& offset, VMGenericClass* genClass, VMGenericMethod* genMethod) {
- return MSCorlib::pIntPtr;
-}
-
-static VMCommonClass* METHOD_ElementTypeU(uint32 op, Assembly* ass,
- uint32& offset, VMGenericClass* genClass, VMGenericMethod* genMethod) {
- return MSCorlib::pUIntPtr;
-}
-
-static VMCommonClass* METHOD_ElementTypeFnptr(uint32 op, Assembly* ass,
- uint32& offset, VMGenericClass* genClass, VMGenericMethod* genMethod) {
- VMThread::get()->getVM()->error("implement me");
- return 0;
-}
-
-static VMCommonClass* METHOD_ElementTypeObject(uint32 op, Assembly* ass,
- uint32& offset, VMGenericClass* genClass, VMGenericMethod* genMethod) {
- return MSCorlib::pObject;
-}
-
-static VMCommonClass* METHOD_ElementTypeSzarray(uint32 op, Assembly* ass,
- uint32& offset, VMGenericClass* genClass, VMGenericMethod* genMethod) {
- VMCommonClass* contains = ass->exploreType(offset, genClass, genMethod);
- VMClassArray* res = ass->constructArray(contains, 1);
- return res;
-}
-
-static VMCommonClass* METHOD_ElementTypeMvar(uint32 op, Assembly* ass,
- uint32& offset, VMGenericClass* genClass, VMGenericMethod *currGenericMethod) {
- uint32 number = ass->uncompressSignature(offset);
-
- if (currGenericMethod == NULL) {
- // when reading in signatures which contain references to generic arguments
- // of generic methods we need create a placeholder for each of them,
- // this is done by creating a dummy VMClass which has the assembly field
- // set to NULL, the token field is used to store the generic argument number
- VMClass* cl = new(ass->allocator, "VMClass") VMClass();
- cl->token = number;
- cl->assembly = ass;
- cl->nameSpace = ass->name;
- char *tmp = (char *) alloca(100);
- snprintf(tmp, 100, "!!%d", number);
- cl->name = VMThread::get()->getVM()->asciizToUTF8(tmp);
- return cl;
- } else {
- return currGenericMethod->genericParams[number];
- }
-}
-
-static VMCommonClass* METHOD_ElementTypeCmodReqd(uint32 op, Assembly* ass,
- uint32& offset, VMGenericClass* genClass, VMGenericMethod* genMethod) {
- VMThread::get()->getVM()->error("implement me");
- return 0;
-}
-
-static VMCommonClass* METHOD_ElementTypeCmodOpt(uint32 op, Assembly* ass,
- uint32& offset, VMGenericClass* genClass, VMGenericMethod* genMethod) {
- VMThread::get()->getVM()->error("implement me");
- return 0;
-}
-
-static VMCommonClass* METHOD_ElementTypeInternal(uint32 op, Assembly* ass,
- uint32& offset, VMGenericClass* genClass, VMGenericMethod* genMethod) {
- VMThread::get()->getVM()->error("implement me");
- return 0;
-}
-
-static VMCommonClass* METHOD_ElementTypeModifier(uint32 op, Assembly* ass,
- uint32& offset, VMGenericClass* genClass, VMGenericMethod* genMethod) {
- VMThread::get()->getVM()->error("implement me");
- return 0;
-}
-
-static VMCommonClass* METHOD_ElementTypeSentinel(uint32 op, Assembly* ass,
- uint32& offset, VMGenericClass* genClass, VMGenericMethod* genMethod) {
- VMThread::get()->getVM()->error("implement me");
- return 0;
-}
-
-static VMCommonClass* METHOD_ElementTypePinned(uint32 op, Assembly* ass,
- uint32& offset, VMGenericClass* genClass, VMGenericMethod* genMethod) {
- return 0;
-}
-
-static VMCommonClass* unimplemented(uint32 op, Assembly* ass, uint32& offset,
- VMGenericClass* genClass, VMGenericMethod* genMethod) {
- VMThread::get()->getVM()->error("unknown signature");
- return 0;
-}
-
-signatureVector_t Assembly::signatureVector[0x46] = { METHOD_ElementTypeEnd, // 0x00
- METHOD_ElementTypeVoid, // 0x01
- METHOD_ElementTypeBoolean, // 0x02
- METHOD_ElementTypeChar, // 0x03
- METHOD_ElementTypeI1, // 0x04
- METHOD_ElementTypeU1, // 0x05
- METHOD_ElementTypeI2, // 0x06
- METHOD_ElementTypeU2, // 0x07
- METHOD_ElementTypeI4, // 0x08
- METHOD_ElementTypeU4, // 0x09
- METHOD_ElementTypeI8, // 0x0A
- METHOD_ElementTypeU8, // 0x0B
- METHOD_ElementTypeR4, // 0x0C
- METHOD_ElementTypeR8, // 0x0D
- METHOD_ElementTypeString, // 0x0E
- METHOD_ElementTypePtr, // 0x1F
- METHOD_ElementTypeByRef, // 0x10
- METHOD_ElementTypeValueType, // 0x11
- METHOD_ElementTypeClass, // 0x12
- METHOD_ElementTypeVar, // 0x13
- METHOD_ElementTypeArray, // 0x14
- METHOD_ElementTypeGenericInst, // 0x15
- METHOD_ElementTypeTypedByRef, // 0x16
- unimplemented, // 0x17
- METHOD_ElementTypeI, // 0x18
- METHOD_ElementTypeU, // 0x19
- unimplemented, // 0x1A
- METHOD_ElementTypeFnptr, // 0x1B
- METHOD_ElementTypeObject, // 0x1C
- METHOD_ElementTypeSzarray, // 0x1D
- METHOD_ElementTypeMvar, // 0x1E
- METHOD_ElementTypeCmodReqd, // 0x1F
- METHOD_ElementTypeCmodOpt, // 0x20
- METHOD_ElementTypeInternal, // 0x21
- METHOD_ElementTypeModifier, // 0x22
- unimplemented, // 0x23
- unimplemented, // 0x24
- unimplemented, // 0x25
- unimplemented, // 0x26
- unimplemented, // 0x27
- unimplemented, // 0x28
- unimplemented, // 0x29
- unimplemented, // 0x2A
- unimplemented, // 0x2B
- unimplemented, // 0x2C
- unimplemented, // 0x2D
- unimplemented, // 0x2E
- unimplemented, // 0x2F
- unimplemented, // 0x30
- unimplemented, // 0x31
- unimplemented, // 0x32
- unimplemented, // 0x33
- unimplemented, // 0x34
- unimplemented, // 0x35
- unimplemented, // 0x36
- unimplemented, // 0x37
- unimplemented, // 0x38
- unimplemented, // 0x39
- unimplemented, // 0x3A
- unimplemented, // 0x3B
- unimplemented, // 0x3C
- unimplemented, // 0x3D
- unimplemented, // 0x3E
- unimplemented, // 0x3F
- unimplemented, // 0x40
- METHOD_ElementTypeSentinel, // 0x41
- unimplemented, // 0x42
- unimplemented, // 0x43
- unimplemented, // 0x44
- METHOD_ElementTypePinned // 0x45
- };
-
-bool Assembly::extractMethodSignature(uint32& offset, VMCommonClass* cl,
- std::vector<VMCommonClass*>& types, VMGenericClass* genClass, VMGenericMethod* genMethod) {
- //uint32 count =
- uncompressSignature(offset);
- uint32 call = uncompressSignature(offset);
-
- if (call & CONSTANT_Generic) {
- //uint32 genArgCount =
- uncompressSignature(offset);
- }
-
- uint32 paramCount = uncompressSignature(offset);
-
- uint32 hasThis = call & CONSTANT_HasThis ? 1 : 0;
- uint32 realCount = paramCount + hasThis;
-
- VMCommonClass* ret = exploreType(offset, genClass, genMethod);
- types.push_back(ret);
-
- if (hasThis) {
- types.push_back(cl);
- }
-
- for (uint32 i = hasThis; i < realCount; ++i) {
- VMCommonClass* cur = exploreType(offset, genClass, genMethod);
- types.push_back(cur);
- }
-
- return hasThis != 0;
-}
-
-// checks whether the MethodDefSig at offset contains generic parameters
-bool Assembly::isGenericMethod(uint32& offset) {
- uncompressSignature(offset); // count
-
- uint32 callingConvention = READ_U1(bytes, offset);
-
- return callingConvention & CONSTANT_Generic ? true : false;
-}
-
-void Assembly::methodSpecSignature(uint32& offset,
- std::vector<VMCommonClass*>& genArgs, VMGenericClass* genClass, VMGenericMethod* genMethod) {
- uncompressSignature(offset); // count
- uint32 genericSig = uncompressSignature(offset);
-
- if (genericSig != 0x0a) {
- VMThread::get()->getVM()->error("unknown methodSpec sig %x", genericSig);
- }
-
- uint32 genArgCount = uncompressSignature(offset);
-
- for (uint32 i = 0; i < genArgCount; i++) {
- genArgs.push_back(exploreType(offset, genClass, genMethod));
- }
-}
-
-void Assembly::localVarSignature(uint32& offset,
- std::vector<VMCommonClass*>& locals, VMGenericClass* genClass, VMGenericMethod* genMethod) {
- //uint32 count =
- uncompressSignature(offset);
- uint32 localSig = uncompressSignature(offset);
- uint32 nbLocals = uncompressSignature(offset);
-
- if (localSig != 0x7) {
- VMThread::get()->getVM()->error("unknown local sig %x", localSig);
- }
-
- for (uint32 i = 0; i < nbLocals; ++i) {
- VMCommonClass* cl = exploreType(offset, genClass, genMethod);
- if (!cl)
- --i; // PINNED
- else
- locals.push_back(cl);
- }
-}
-
-VMCommonClass* Assembly::extractFieldSignature(uint32& offset, VMGenericClass* genClass, VMGenericMethod* genMethod) {
- //uint32 count =
- uncompressSignature(offset);
- uint32 fieldSig = uncompressSignature(offset);
-
- if (fieldSig != 0x6) {
- VMThread::get()->getVM()->error("unknown field sig %x", fieldSig);
- }
-
- // TODO implement support for custom modifiers
- // see ECMA 335 23.2.4, 23.2.7
-
- return exploreType(offset, genClass, genMethod);
-
-}
-
-VMCommonClass* Assembly::extractTypeInSignature(uint32& offset, VMGenericClass* genClass, VMGenericMethod* genMethod) {
- //uint32 count =
- uncompressSignature(offset);
- return exploreType(offset, genClass, genMethod);
-}
-
-VMCommonClass* Assembly::exploreType(uint32& offset, VMGenericClass* genClass, VMGenericMethod* genMethod) {
- uint32 op = READ_U1(bytes, offset);
- assert(op < 0x46 && "unknown signature type");
- return (signatureVector[op]) (op, this, offset, genClass, genMethod);
-}
-
-uint32 Assembly::uncompressSignature(uint32& offset) {
- uint32 value = READ_U1(bytes, offset);
-
- if ((value & 0x80) == 0) {
- return value;
- } else if ((value & 0x40) == 0) {
- uint32 val2 = READ_U1(bytes, offset);
- return (((value & 0x3f) << 8) | val2);
- } else {
- uint32 val2 = READ_U1(bytes, offset);
- uint32 val3 = READ_U1(bytes, offset);
- uint32 val4 = READ_U1(bytes, offset);
- return ((value & 0x1f) << 24) | (val2 << 16) | (val3 << 8) | val4;
- }
-}
diff --git a/vmkit/lib/N3/VMCore/CLIString.h b/vmkit/lib/N3/VMCore/CLIString.h
deleted file mode 100644
index 69747c0..0000000
--- a/vmkit/lib/N3/VMCore/CLIString.h
+++ /dev/null
@@ -1,40 +0,0 @@
-//===----- CLIString.h - Internal correspondance with CLI Strings ---------===//
-//
-// N3
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#ifndef N3_CLI_STRING_H
-#define N3_CLI_STRING_H
-
-#include "llvm/GlobalVariable.h"
-
-#include "types.h"
-#include "mvm/PrintBuffer.h"
-
-#include "VMObject.h"
-
-namespace n3 {
-
-class N3;
-class ArrayChar;
-
-class CLIString : public VMObject {
- CLIString() {}
-public:
- virtual void print(mvm::PrintBuffer* buf) const {
- buf->write("CLI string");
- }
-
- static llvm::GlobalVariable* llvmVar(CLIString *self);
-
-
- static CLIString* stringDup(const ArrayChar* array, N3* vm);
-};
-
-} // end namespace jnjvm
-
-#endif
diff --git a/vmkit/lib/N3/VMCore/LinkN3Runtime.h b/vmkit/lib/N3/VMCore/LinkN3Runtime.h
deleted file mode 100644
index 9ddf026..0000000
--- a/vmkit/lib/N3/VMCore/LinkN3Runtime.h
+++ /dev/null
@@ -1,76 +0,0 @@
-//===----------------------- LinkN3Runtime.h ------------------------------===//
-//=== ------------- Reference all runtime functions -----------------------===//
-//
-// The VMKit project
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#ifndef JNJVM_LINK_N3_RUNTIME_H
-#define JNJVM_LINK_N3_RUNTIME_H
-
-namespace mvm {
- class UTF8;
-}
-
-namespace n3 {
- using mvm::UTF8;
- class CacheNode;
- class VMClass;
- class VMClassArray;
- class VMCommonClass;
- class VMObject;
-}
-
-using namespace n3;
-
-
-extern "C" VMObject* initialiseClass(VMClass* cl);
-extern "C" void n3ClassCastException();
-extern "C" void n3NullPointerException();
-extern "C" void indexOutOfBounds();
-extern "C" VMObject* newString(const UTF8* utf8);
-extern "C" bool n3InstanceOf(VMObject* obj, VMCommonClass* cl);
-extern "C" void* GetCppException();
-extern "C" void ThrowException(VMObject* obj);
-extern "C" VMObject* GetCLIException();
-extern "C" bool CompareException(VMClass* cl);
-extern "C" void ClearException();
-extern "C" VMObject* doMultiNew(VMClassArray* cl, ...);
-extern "C" CacheNode* n3VirtualLookup(CacheNode* cache, VMObject *obj);
-extern "C" VMObject* newObject(VMClass* cl);
-extern "C" VMObject* newArray(VMClassArray* cl, sint32 nb);
-
-namespace {
- struct ForceRuntimeLinking {
- ForceRuntimeLinking() {
- // We must reference the passes in such a way that compilers will not
- // delete it all as dead code, even with whole program optimization,
- // yet is effectively a NO-OP. As the compiler isn't smart enough
- // to know that getenv() never returns -1, this will do the job.
- if (std::getenv("bar") != (char*) -1)
- return;
- (void) initialiseClass(0);
- (void) n3ClassCastException();
- (void )n3NullPointerException();
- (void) indexOutOfBounds();
- (void) newString(0);
- (void) n3InstanceOf(0, 0);
- (void) GetCppException();
- (void) ThrowException(0);
- (void) GetCLIException();
- (void) CompareException(0);
- (void) ClearException();
- (void) doMultiNew(0);
- (void) n3VirtualLookup(0, 0);
- (void) newObject(0);
- (void) newArray(0, 0);
- }
- } ForcePassLinking; // Force link by creating a global definition.
-}
-
-
-
-#endif //JNJVM_LINK_N3_RUNTIME_H
diff --git a/vmkit/lib/N3/VMCore/LockedMap.cpp b/vmkit/lib/N3/VMCore/LockedMap.cpp
deleted file mode 100644
index 57c77bc..0000000
--- a/vmkit/lib/N3/VMCore/LockedMap.cpp
+++ /dev/null
@@ -1,21 +0,0 @@
-//===------- LockedMap.cpp - Implementation of the UTF8 map ---------------===//
-//
-// N3
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#include <map>
-
-#include "Assembly.h"
-#include "LockedMap.h"
-#include "MSCorlib.h"
-#include "N3.h"
-#include "VMArray.h"
-#include "VMClass.h"
-
-#include <string.h>
-
-using namespace n3;
diff --git a/vmkit/lib/N3/VMCore/LockedMap.h b/vmkit/lib/N3/VMCore/LockedMap.h
deleted file mode 100644
index 25d2564..0000000
--- a/vmkit/lib/N3/VMCore/LockedMap.h
+++ /dev/null
@@ -1,164 +0,0 @@
-//===------- LockedMap.h - A thread-safe map implementation ---------------===//
-//
-// N3
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#ifndef N3_LOCKED_MAP_H
-#define N3_LOCKED_MAP_H
-
-#include <map>
-
-
-#include <string.h>
-
-#include "mvm/Object.h"
-#include "mvm/PrintBuffer.h"
-#include "mvm/Threads/Locks.h"
-
-#include "types.h"
-
-#include "CLIString.h"
-#include "VMArray.h"
-
-#include "UTF8.h"
-
-namespace n3 {
-
-class Assembly;
-class N3;
-class VMClass;
-class VMCommonClass;
-class VMField;
-class VMObject;
-class VMMethod;
-class VMField;
-
-template<class Key, class Container, class Compare, class Upcall>
-class LockedMap : public mvm::PermanentObject {
-public:
-
- typedef typename std::map<const Key, Container*, Compare>::iterator iterator;
- typedef Container* (*funcCreate)(Key& V, Upcall* ass);
-
- mvm::Lock *lock;
- std::map<Key, Container*, Compare,
- gc_allocator<std::pair<const Key, Container*> > > map;
-
- LockedMap(mvm::Lock *lock) {
- this->lock = lock;
- }
-
- inline Container* lookupOrCreate(Key& V, Upcall* ass, funcCreate func) {
- lock->lock();
- iterator End = map.end();
- iterator I = map.find(V);
- if (I == End) {
- Container* res = func(V, ass);
- map.insert(std::make_pair(V, res));
- lock->unlock();
- return res;
- } else {
- lock->unlock();
- return ((Container*)(I->second));
- }
- }
-
- inline Container* lookupOrCreate(Key&V, Container* C) {
- lock->lock();
- iterator End = map.end();
- iterator I = map.find(V);
- if (I == End) {
- map.insert(std::make_pair(V, C));
- lock->unlock();
- return C;
- } else {
- lock->unlock();
- return ((Container*)(I->second));
- }
- }
-
- inline Container* lookup(Key& V) {
- lock->lock();
- iterator End = map.end();
- iterator I = map.find(V);
- lock->unlock();
- return I != End ? ((Container*)(I->second)) : 0;
- }
-
- inline void hash(Key& k, Container* c) {
- lock->lock();
- map.insert(std::make_pair(k, c));
- lock->unlock();
- }
-
- virtual void tracer() {
- //lock->MARK_AND_TRACE;
- for (iterator i = map.begin(), e = map.end(); i!= e; ++i) {
- i->second->tracer();
- }
- }
-
- virtual void print(mvm::PrintBuffer* buf) const {
- buf->write("Hashtable<>");
- }
-
-};
-
-class ClassNameCmp {
-public:
- const UTF8* name;
- const UTF8* nameSpace;
-
- ClassNameCmp(const UTF8* u, const UTF8* n) : name(u), nameSpace(n) {}
-
- inline bool operator<(const ClassNameCmp &cmp) const {
- if (name < cmp.name) return true;
- else if (name > cmp.name) return false;
- else return nameSpace < cmp.nameSpace;
- }
-};
-
-
-class ClassNameMap : public LockedMap<ClassNameCmp, VMCommonClass, std::less<ClassNameCmp>, Assembly > {
-public:
- ClassNameMap() : LockedMap<ClassNameCmp, VMCommonClass, std::less<ClassNameCmp>, Assembly >(new mvm::LockNormal()) {}
-};
-
-class ClassTokenMap : public LockedMap<uint32, VMCommonClass, std::less<uint32>, Assembly > {
-public:
- ClassTokenMap() : LockedMap<uint32, VMCommonClass, std::less<uint32>, Assembly >(new mvm::LockNormal()) {}
-};
-
-class FieldTokenMap : public LockedMap<uint32, VMField, std::less<uint32>, Assembly > {
-public:
- FieldTokenMap() : LockedMap<uint32, VMField, std::less<uint32>, Assembly >(new mvm::LockNormal()) {}
-};
-
-class MethodTokenMap : public LockedMap<uint32, VMMethod, std::less<uint32>, Assembly > {
-public:
- MethodTokenMap() : LockedMap<uint32, VMMethod, std::less<uint32>, Assembly >(new mvm::LockNormal()) {}
-};
-
-class AssemblyMap : public LockedMap<const UTF8*, Assembly, std::less<const UTF8*>, N3 > {
-public:
- AssemblyMap() : LockedMap<const UTF8*, Assembly, std::less<const UTF8*>, N3 >(new mvm::LockNormal()) {}
-};
-
-
-class StringMap : public LockedMap<const UTF8*, CLIString, std::less<const UTF8*>, N3 > {
-public:
- StringMap() : LockedMap<const UTF8*, CLIString, std::less<const UTF8*>, N3 >(new mvm::LockRecursive()) {}
-};
-
-class FunctionMap : public LockedMap<llvm::Function*, VMMethod, std::less<llvm::Function*>, N3 > {
-public:
- FunctionMap() : LockedMap<llvm::Function*, VMMethod, std::less<llvm::Function*>, N3 >(new mvm::LockNormal()) {}
-};
-
-} // end namespace n3
-
-#endif
diff --git a/vmkit/lib/N3/VMCore/LowerArrayLength.cpp b/vmkit/lib/N3/VMCore/LowerArrayLength.cpp
deleted file mode 100644
index 6617cc3..0000000
--- a/vmkit/lib/N3/VMCore/LowerArrayLength.cpp
+++ /dev/null
@@ -1,70 +0,0 @@
-//===------- LowerArrayLength.cpp - Lowers array length calls -------------===//
-//
-// N3
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#include "llvm/Function.h"
-#include "llvm/Instructions.h"
-#include "llvm/LLVMContext.h"
-#include "llvm/Pass.h"
-#include "llvm/Support/Compiler.h"
-#include "llvm/Support/Debug.h"
-
-#include "mvm/JIT.h"
-
-#include "VMArray.h"
-#include "CLIJit.h"
-
-using namespace llvm;
-
-namespace mvm {
-
- class VISIBILITY_HIDDEN LowerArrayLength : public FunctionPass {
- public:
- static char ID;
- LowerArrayLength() : FunctionPass((intptr_t)&ID) { }
-
- virtual bool runOnFunction(Function &F);
- private:
- };
- char LowerArrayLength::ID = 0;
- static RegisterPass<LowerArrayLength> X("LowerArrayLength", "Lower Array length");
-
-bool LowerArrayLength::runOnFunction(Function& F) {
- bool Changed = false;
- for (Function::iterator BI = F.begin(), BE = F.end(); BI != BE; BI++) {
- BasicBlock *Cur = BI;
-
- for (BasicBlock::iterator II = Cur->begin(), IE = Cur->end(); II != IE; ) {
- Instruction *I = II;
- II++;
- if (CallInst *CI = dyn_cast<CallInst>(I)) {
- if (CI->getOperand(0) == n3::CLIJit::arrayLengthLLVM) {
- Changed = true;
- Value* val = CI->getOperand(1); // get the array
- std::vector<Value*> args; //size= 2
- args.push_back(ConstantInt::get(Type::getInt32Ty(getGlobalContext()), 0));
- args.push_back(n3::VMArray::sizeOffset());
- Value* ptr = GetElementPtrInst::Create(val, args.begin(), args.end(),
- "", CI);
- Value* load = new LoadInst(ptr, "", CI);
- CI->replaceAllUsesWith(load);
- CI->eraseFromParent();
- }
- }
- }
- }
-
- return Changed;
-}
-
-LowerArrayLength* createLowerArrayLengthPass() {
- return new LowerArrayLength();
-}
-
-}
-
diff --git a/vmkit/lib/N3/VMCore/MSCorlib.h b/vmkit/lib/N3/VMCore/MSCorlib.h
deleted file mode 100644
index 19d07ae..0000000
--- a/vmkit/lib/N3/VMCore/MSCorlib.h
+++ /dev/null
@@ -1,74 +0,0 @@
-//===------------- MSCorlib.h - The MSCorlib interface --------------------===//
-//
-// N3
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#ifndef N3_MSCORLIB_H
-#define N3_MSCORLIB_H
-
-#include "N3MetaType.h"
-
-namespace n3 {
-
-class N3;
-class VMClass;
-class VMClassArray;
-class VMField;
-class VMMethod;
-
-class MSCorlib {
-public:
- static void initialise(N3* vm);
- static void loadStringClass(N3* vm);
- static void loadBootstrap(N3* vm);
-
- static const char* libsPath;
-
- static VMMethod* ctorClrType;
- static VMClass* clrType;
- static VMField* typeClrType;
-
- static VMMethod* ctorAssemblyReflection;
- static VMClass* assemblyReflection;
- static VMClass* typedReference;
- static VMField* assemblyAssemblyReflection;
- static VMClass* propertyType;
- static VMClass* methodType;
-
- static VMMethod* ctorPropertyType;
- static VMMethod* ctorMethodType;
- static VMField* propertyPropertyType;
- static VMField* methodMethodType;
-
- static VMClass* resourceStreamType;
- static VMMethod* ctorResourceStreamType;
-
-#define DEF_TYPE(name, type) \
- static VMClass* p##name;
-
-#define DEF_ARRAY_AND_TYPE(name, type) \
- DEF_TYPE(name, type) \
- static VMClassArray* array##name; \
- static VMField* ctor##name;
-
- ON_TYPES(DEF_ARRAY_AND_TYPE, _F_NT)
- ON_STRING(DEF_ARRAY_AND_TYPE, _F_NT)
- ON_VOID(DEF_TYPE, _F_NT)
-
-#undef DEF_ARRAY_AND_TYPE
-#undef DEF_TYPE
-
- static VMClass* pValue;
- static VMClass* pEnum;
- static VMClass* pArray;
- static VMClass* pDelegate;
- static VMClass* pException;
-};
-
-} // end namespace n3
-
-#endif // N3_MSCORLIB_H
diff --git a/vmkit/lib/N3/VMCore/MSCorlib.inc b/vmkit/lib/N3/VMCore/MSCorlib.inc
deleted file mode 100644
index 4dc3ed5..0000000
--- a/vmkit/lib/N3/VMCore/MSCorlib.inc
+++ /dev/null
@@ -1,234 +0,0 @@
-//===------------- MSCorlib.cpp - mscorlib interface ----------------------===//
-//
-// N3
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#include <math.h>
-
-#include <dlfcn.h>
-#include <stdio.h>
-
-#include "mvm/JIT.h"
-
-#include "Assembly.h"
-#include "CLIAccess.h"
-#include "CLIJit.h"
-#include "NativeUtil.h"
-#include "MSCorlib.h"
-#include "N3.h"
-#include "Reader.h"
-#include "VMArray.h"
-#include "VMClass.h"
-#include "VMObject.h"
-#include "VMThread.h"
-
-using namespace n3;
-
-extern "C" void System_Runtime_CompilerServices_RuntimeHelpers_InitializeArray(
- VMArray* array, VMField* field) {
- if (!array || !field) return;
-
- VMClass* type = field->classDef;
- VMClassArray* ts = (VMClassArray*)array->classOf;
- VMCommonClass* bs = ts->baseClass;
- Assembly* ass = type->assembly;
-
- uint32 rva = ass->getRVAFromField(field->token);
- Section* inSection = 0;
-
- if (rva >= ass->rsrcSection->virtualAddress && rva < ass->rsrcSection->virtualAddress + ass->rsrcSection->virtualSize)
- inSection = ass->rsrcSection;
- if (rva >= ass->textSection->virtualAddress && rva < ass->textSection->virtualAddress + ass->textSection->virtualSize)
- inSection = ass->textSection;
- if (rva >= ass->relocSection->virtualAddress && rva < ass->relocSection->virtualAddress + ass->relocSection->virtualSize)
- inSection = ass->relocSection;
-
- uint32 size = array->size;
- uint32 offset = inSection->rawAddress + (rva - inSection->virtualAddress);
- ByteCode* bytes = ass->bytes;
-
- if (bs == MSCorlib::pChar) {
- for (uint32 i = 0; i < size; ++i) {
- ((ArrayUInt16*)array)->elements[i] = READ_U2(bytes, offset);
- }
- } else if (bs == MSCorlib::pSInt32) {
- for (uint32 i = 0; i < size; ++i) {
- ((ArraySInt32*)array)->elements[i] = READ_U4(bytes, offset);
- }
- } else if (bs == MSCorlib::pDouble) {
- for (uint32 i = 0; i < size; ++i) {
- ((ArrayDouble*)array)->elements[i] = READ_U8(bytes, offset);
- }
- } else {
- VMThread::get()->getVM()->error("implement me");
- }
-}
-
-extern "C" VMObject* System_Type_GetTypeFromHandle(VMCommonClass* cl) {
- return cl->getClassDelegatee();
-}
-
-
-extern "C" VMObject* System_Reflection_Assembly_GetCallingAssembly() {
- // Call to this function.
- void** cur = (void**)__builtin_frame_address(0);
-
- // Stub from CLI to native.
- cur = (void**)cur[0];
-
- // The CLI function.
- cur = (void**)cur[0];
-
- // The caller of the CLI function;
- cur = (void**)cur[0];
-
- // TODO: implement me
- abort();
- VMMethod* meth = NULL; //vm->IPToMethod<VMMethod>(FRAME_IP(cur));
-
- assert(meth && "Wrong stack");
-
- return meth->classDef->assembly->getAssemblyDelegatee();
-}
-
-extern "C" VMObject* System_Reflection_Assembly_GetExecutingAssembly() {
- // Call to this function.
- void** cur = (void**)__builtin_frame_address(0);
-
- // Stub from CLI to native.
- cur = (void**)cur[0];
-
- // The CLI function.
- cur = (void**)cur[0];
-
- // TODO: implement me
- abort();
- VMMethod* meth = NULL; //vm->IPToMethod<VMMethod>(FRAME_IP(cur));
- assert(meth && "Wrong stack");
- return meth->classDef->assembly->getAssemblyDelegatee();
-}
-
-extern "C" void System_Reflection_Assembly_LoadFromFile() {
- VMThread::get()->getVM()->error("implement me");
-}
-
-extern "C" void System_Array_InternalCopy(VMArray* src, sint32 sstart,
- VMArray* dst, sint32 dstart,
- sint32 len) {
- N3* vm = (N3*)(VMThread::get()->getVM());
- verifyNull(src);
- verifyNull(dst);
-
- if (!(src->classOf->isArray && dst->classOf->isArray)) {
- vm->arrayStoreException();
- }
-
- VMClassArray* ts = (VMClassArray*)src->classOf;
- VMClassArray* td = (VMClassArray*)dst->classOf;
- VMCommonClass* dstType = td->baseClass;
- VMCommonClass* srcType = ts->baseClass;
-
- if (len > src->size) {
- vm->indexOutOfBounds(src, len);
- } else if (len > dst->size) {
- vm->indexOutOfBounds(dst, len);
- } else if (len + sstart > src->size) {
- vm->indexOutOfBounds(src, len + sstart);
- } else if (len + dstart > dst->size) {
- vm->indexOutOfBounds(dst, len + dstart);
- } else if (dstart < 0) {
- vm->indexOutOfBounds(dst, dstart);
- } else if (sstart < 0) {
- vm->indexOutOfBounds(src, sstart);
- } else if (len < 0) {
- vm->indexOutOfBounds(src, len);
- }
-
- bool doThrow = false;
-
- if (srcType->super == MSCorlib::pValue && srcType != dstType) {
- vm->arrayStoreException();
- } else if (srcType->super != MSCorlib::pValue && srcType->super != MSCorlib::pEnum) {
- sint32 i = sstart;
- while (i < sstart + len && !doThrow) {
- VMObject* cur = ((ArrayObject*)src)->elements[i];
- if (cur) {
- if (!(cur->classOf->isAssignableFrom(dstType))) {
- doThrow = true;
- len = i;
- }
- }
- ++i;
- }
- }
-
-
- uint32 size = srcType->naturalType->getPrimitiveSizeInBits() / 8;
- if (size == 0) size = sizeof(void*);
- void* ptrDst = (void*)((int64_t)(dst->elements) + size * dstart);
- void* ptrSrc = (void*)((int64_t)(src->elements) + size * sstart);
- memmove(ptrDst, ptrSrc, size * len);
-
- if (doThrow)
- vm->arrayStoreException();
-
-}
-
-extern "C" sint32 System_Array_GetRank(VMObject* arr) {
- verifyNull(arr);
- if (arr->classOf->isArray) {
- return ((VMClassArray*)(arr->classOf))->dims;
- } else {
- VMThread::get()->getVM()->error("implement me");
- return 0;
- }
-}
-
-extern "C" sint32 System_Array_GetLength(VMObject* arr) {
- verifyNull(arr);
- if (arr->classOf->isArray) {
- return ((VMArray*)arr)->size;
- } else {
- VMThread::get()->getVM()->error("implement me");
- return 0;
- }
-}
-
-extern "C" sint32 System_Array_GetLowerBound(VMObject* arr, sint32 dim) {
- return 0;
-}
-
-extern "C" VMObject* System_Object_GetType(VMObject* obj) {
- verifyNull(obj);
- return obj->classOf->getClassDelegatee();
-}
-
-extern "C" double System_Decimal_ToDouble(void* ptr) {
- VMThread::get()->getVM()->error("implement me");
- return 0.0;
-}
-
-extern "C" double System_Math_Log10(double val) {
- return log10(val);
-}
-
-extern "C" double System_Math_Floor(double val) {
- return floor(val);
-}
-
-extern "C" void System_GC_Collect() {
-#ifdef MULTIPLE_GC
- VMThread::get()->GC->collect();
-#else
- mvm::Collector::collect();
-#endif
-}
-
-extern "C" void System_GC_SuppressFinalize(VMObject* obj) {
- // TODO: implement me
-}
-
diff --git a/vmkit/lib/N3/VMCore/Makefile b/vmkit/lib/N3/VMCore/Makefile
deleted file mode 100644
index 409df93..0000000
--- a/vmkit/lib/N3/VMCore/Makefile
+++ /dev/null
@@ -1,23 +0,0 @@
-##===- lib/N3/VMCore/Makefile ------------------------------*- Makefile -*-===##
-#
-# The vmkit project
-#
-# This file is distributed under the University of Illinois Open Source
-# License. See LICENSE.TXT for details.
-#
-##===----------------------------------------------------------------------===##
-LEVEL = ../../..
-
-EXTRA_DIST = MSCorlib.inc
-
-include $(LEVEL)/Makefile.config
-
-ifeq ($(WITH_LLVM_GCC), 1)
- MODULE_NAME = N3
-else
- LIBRARYNAME = N3
-endif
-
-include $(LEVEL)/Makefile.common
-
-CXX.Flags += -I$(PROJ_OBJ_DIR)/../LLVMRuntime
diff --git a/vmkit/lib/N3/VMCore/N3.cpp b/vmkit/lib/N3/VMCore/N3.cpp
deleted file mode 100644
index d195821..0000000
--- a/vmkit/lib/N3/VMCore/N3.cpp
+++ /dev/null
@@ -1,381 +0,0 @@
-//===--------------- N3.cpp - The N3 virtual machine ----------------------===//
-//
-// N3
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-
-#include <vector>
-#include <stdarg.h>
-
-#include "llvm/Function.h"
-#include "llvm/Module.h"
-#include "llvm/LLVMContext.h"
-#include "llvm/Support/CommandLine.h"
-
-#include "mvm/Object.h"
-#include "mvm/PrintBuffer.h"
-#include "mvm/Threads/Cond.h"
-#include "mvm/Threads/Locks.h"
-#include "mvm/JIT.h"
-
-#include "types.h"
-
-#include "Assembly.h"
-#include "LinkN3Runtime.h"
-#include "LockedMap.h"
-#include "MSCorlib.h"
-#include "N3.h"
-#include "N3ModuleProvider.h"
-#include "Reader.h"
-#include "VMArray.h"
-#include "VMClass.h"
-#include "VMObject.h"
-#include "VMThread.h"
-#include "CLIJit.h"
-#include "CLIString.h"
-
-
-using namespace n3;
-
-#define DECLARE_EXCEPTION(EXCP) \
- const char* N3::EXCP = #EXCP
-
-DECLARE_EXCEPTION(SystemException);
-DECLARE_EXCEPTION(OverFlowException);
-DECLARE_EXCEPTION(OutOfMemoryException);
-DECLARE_EXCEPTION(IndexOutOfRangeException);
-DECLARE_EXCEPTION(NullReferenceException);
-DECLARE_EXCEPTION(SynchronizationLocException);
-DECLARE_EXCEPTION(ThreadInterruptedException);
-DECLARE_EXCEPTION(MissingMethodException);
-DECLARE_EXCEPTION(MissingFieldException);
-DECLARE_EXCEPTION(ArrayTypeMismatchException);
-DECLARE_EXCEPTION(ArgumentException);
-
-/*
-DECLARE_EXCEPTION(ArithmeticException);
-DECLARE_EXCEPTION(InvocationTargetException);
-DECLARE_EXCEPTION(ArrayStoreException);
-DECLARE_EXCEPTION(ClassCastException);
-DECLARE_EXCEPTION(ArrayIndexOutOfBoundsException);
-DECLARE_EXCEPTION(SecurityException);
-DECLARE_EXCEPTION(ClassFormatError);
-DECLARE_EXCEPTION(ClassCircularityError);
-DECLARE_EXCEPTION(NoClassDefFoundError);
-DECLARE_EXCEPTION(UnsupportedClassVersionError);
-DECLARE_EXCEPTION(NoSuchFieldError);
-DECLARE_EXCEPTION(NoSuchMethodError);
-DECLARE_EXCEPTION(InstantiationError);
-DECLARE_EXCEPTION(IllegalAccessError);
-DECLARE_EXCEPTION(IllegalAccessException);
-DECLARE_EXCEPTION(VerifyError);
-DECLARE_EXCEPTION(ExceptionInInitializerError);
-DECLARE_EXCEPTION(LinkageError);
-DECLARE_EXCEPTION(AbstractMethodError);
-DECLARE_EXCEPTION(UnsatisfiedLinkError);
-DECLARE_EXCEPTION(InternalError);
-DECLARE_EXCEPTION(StackOverflowError);
-DECLARE_EXCEPTION(ClassNotFoundException);
-*/
-
-#undef DECLARE_EXCEPTION
-
-void ThreadSystem::print(mvm::PrintBuffer* buf) const {
- buf->write("ThreadSystem<>");
-}
-
-ThreadSystem::ThreadSystem() {
- nonDaemonThreads = 1;
- nonDaemonLock = new mvm::LockNormal();
- nonDaemonVar = new mvm::Cond();
-}
-
-N3::N3(mvm::BumpPtrAllocator &allocator, const char *name) : mvm::VirtualMachine(allocator) {
- this->module = 0;
- this->TheModuleProvider = 0;
- this->name = name;
-
- this->scanner = new mvm::UnpreciseStackScanner();
- this->LLVMModule = new llvm::Module(name, llvm::getGlobalContext());
- this->module = new mvm::BaseIntrinsics(this->LLVMModule);
-
- this->LLVMModule->setDataLayout(mvm::MvmModule::executionEngine->getTargetData()->getStringRepresentation());
- this->protectModule = new mvm::LockNormal();
-
- this->functions = new(allocator, "FunctionMap") FunctionMap();
- this->loadedAssemblies = new(allocator, "AssemblyMap") AssemblyMap();
-
- this->TheModuleProvider = new N3ModuleProvider(this->LLVMModule, this->functions);
-}
-
-N3::~N3() {
- delete module;
- delete TheModuleProvider;
-}
-
-void N3::error(const char* className, const char* fmt, va_list ap) {
- fprintf(stderr, "Internal exception of type %s during bootstrap: ", className);
- vfprintf(stderr, fmt, ap);
- throw 1;
-}
-
-void N3::indexOutOfBounds(const VMObject* obj, sint32 entry) {
- error(IndexOutOfRangeException, "%d", entry);
-}
-
-void N3::negativeArraySizeException(sint32 size) {
- error(OverFlowException, "%d", size);
-}
-
-void N3::nullPointerException(const char* fmt, ...) {
- va_list ap;
- va_start(ap, fmt);
- error(NullReferenceException, fmt, va_arg(ap, char*));
-}
-
-
-void N3::illegalMonitorStateException(const VMObject* obj) {
- error(SynchronizationLocException, "");
-}
-
-void N3::interruptedException(const VMObject* obj) {
- error(ThreadInterruptedException, "");
-}
-
-void N3::outOfMemoryError(sint32 n) {
- error(OutOfMemoryException, "");
-}
-
-void N3::arrayStoreException() {
- error(ArrayTypeMismatchException, "");
-}
-
-void N3::illegalArgumentException(const char* name) {
- error(ArgumentException, name);
-}
-
-void N3::unknownError(const char* fmt, ...) {
- va_list ap;
- va_start(ap, fmt);
- error(SystemException, fmt, ap);
-}
-
-void N3::error(const char* fmt, ...) {
- va_list ap;
- va_start(ap, fmt);
- error(SystemException, fmt, ap);
-}
-
-void N3::error(const char* name, const char* fmt, ...) {
- va_list ap;
- va_start(ap, fmt);
- error(name, fmt, ap);
-}
-
-
-
-
-using namespace n3;
-
-void N3::print(mvm::PrintBuffer* buf) const {
- buf->write("N3 virtual machine<>");
-}
-
-static Assembly* assemblyDup(const UTF8*& name, N3* vm) {
- mvm::BumpPtrAllocator *a = new mvm::BumpPtrAllocator();
- return new(*a, "Assembly") Assembly(*a, vm, name);
-}
-
-Assembly* N3::constructAssembly(const UTF8* name) {
- return loadedAssemblies->lookupOrCreate(name, this, assemblyDup);
-}
-
-Assembly* N3::lookupAssembly(const UTF8* name) {
- return loadedAssemblies->lookup(name);
-}
-
-VMMethod* N3::lookupFunction(Function* F) {
- return functions->lookup(F);
-}
-
-
-N3* N3::allocateBootstrap() {
- mvm::BumpPtrAllocator *a = new mvm::BumpPtrAllocator();
- N3 *vm= new(*a, "VM") N3(*a, "bootstrapN3");
-
- vm->hashUTF8 = new(vm->allocator, "UTF8Map") UTF8Map(vm->allocator);
-
- CLIJit::initialiseBootstrapVM(vm);
-
- return vm;
-}
-
-
-N3* N3::allocate(const char* name, N3* parent) {
- mvm::BumpPtrAllocator *a = new mvm::BumpPtrAllocator();
- N3 *vm= new(*a, "VM") N3(*a, name);
-
- vm->hashUTF8 = parent->hashUTF8;
-
- vm->threadSystem = new(*a, "ThreadSystem") ThreadSystem();
-
- vm->assemblyPath = parent->assemblyPath;
- vm->coreAssembly = parent->coreAssembly;
- vm->loadedAssemblies->hash(parent->coreAssembly->name, parent->coreAssembly);
-
- CLIJit::initialiseAppDomain(vm);
-
- return vm;
-}
-
-void ClArgumentsInfo::nyi() {
- fprintf(stdout, "Not yet implemented\n");
-}
-
-void ClArgumentsInfo::printVersion() {
- fprintf(stdout, "N3 -- a VVM implementation of the Common Language Infrastructure\n");
-}
-
-void ClArgumentsInfo::printInformation() {
- fprintf(stdout,
- "Usage: n3 [-options] assembly [args...] \n"
- "No option is available\n");
-}
-
-void ClArgumentsInfo::readArgs(int argc, char** argv, N3* n3) {
- assembly = 0;
- appArgumentsPos = 0;
- sint32 i = 1;
- if (i == argc) printInformation();
- while (i < argc) {
- char* cur = argv[i];
- if (cur[0] == '-') {
- } else {
- assembly = cur;
- appArgumentsPos = i;
- return;
- }
- ++i;
- }
-}
-
-
-void N3::waitForExit() {
- threadSystem->nonDaemonLock->lock();
-
- while (threadSystem->nonDaemonThreads) {
- threadSystem->nonDaemonVar->wait(threadSystem->nonDaemonLock);
- }
-
- threadSystem->nonDaemonLock->unlock();
-
- return;
-}
-
-void N3::executeAssembly(const char* _name, ArrayObject* args) {
- const UTF8* name = asciizToUTF8(_name);
- Assembly* assembly = constructAssembly(name);
-
- if(!assembly->resolve(1, 0))
- error("Can not find assembly %s", _name);
- else {
- uint32 entryPoint = assembly->entryPoint;
- uint32 table = entryPoint >> 24;
- if (table != CONSTANT_MethodDef) {
- error("Entry point does not point to a method");
- } else {
- uint32 typeToken = assembly->getTypeDefTokenFromMethod(entryPoint);
- assembly->loadType(this, typeToken, true, true, true ,true, NULL, NULL);
- VMMethod* mainMeth = assembly->lookupMethodFromToken(entryPoint);
- mainMeth->compileToNative()->invokeGeneric(args);
- }
- }
-}
-
-void N3::runMain(int argc, char** argv) {
- ClArgumentsInfo& info = argumentsInfo;
-
- info.readArgs(argc, argv, this);
- if (info.assembly) {
- info.argv = argv + info.appArgumentsPos - 1;
- info.argc = argc - info.appArgumentsPos + 1;
-
-
- bootstrapThread = VMThread::TheThread;
- bootstrapThread->MyVM = this;
- bootstrapThread->start((void (*)(mvm::Thread*))mainCLIStart);
-
- } else {
- --(threadSystem->nonDaemonThreads);
- }
-}
-
-void N3::mainCLIStart(VMThread* th) {
- N3* vm = (N3*)th->getVM();
- MSCorlib::loadBootstrap(vm);
-
- ClArgumentsInfo& info = vm->argumentsInfo;
- declare_gcroot(ArrayObject*, args) = (ArrayObject*)MSCorlib::arrayString->doNew(info.argc-2);
- for (int i = 2; i < info.argc; ++i) {
- declare_gcroot(ArrayChar*, arg_array) = vm->asciizToArray(info.argv[i]);
- declare_gcroot(VMObject*, arg) = vm->arrayToString(arg_array);
- args->elements[i - 2] = arg;
- }
-
- try{
- vm->executeAssembly(info.assembly, args);
- }catch(...) {
- declare_gcroot(VMObject*, exc) = th->ooo_pendingException;
- printf("N3 caught %s\n", mvm::PrintBuffer(exc).cString());
- }
-
- vm->threadSystem->nonDaemonLock->lock();
- --(vm->threadSystem->nonDaemonThreads);
- if (vm->threadSystem->nonDaemonThreads == 0)
- vm->threadSystem->nonDaemonVar->signal();
- vm->threadSystem->nonDaemonLock->unlock();
-}
-
-
-
-ArrayChar* N3::asciizToArray(const char* asciiz) {
- uint32 len = strlen(asciiz);
- declare_gcroot(ArrayChar*, res) = (ArrayChar*)MSCorlib::arrayChar->doNew(len);
- for(uint32 i=0; i<len; i++)
- res->elements[i] = asciiz[i];
- return res;
-}
-
-ArrayChar* N3::bufToArray(const uint16* buf, uint32 size) {
- declare_gcroot(ArrayChar*, res) = (ArrayChar*)MSCorlib::arrayChar->doNew(size);
- memcpy(res->elements, buf, size<<1);
- return res;
-}
-
-ArrayChar* N3::UTF8ToArray(const UTF8 *utf8) {
- declare_gcroot(ArrayChar*, res) = bufToArray(utf8->elements, utf8->size);
- return res;
-}
-
-const UTF8* N3::asciizToUTF8(const char* asciiz) {
- return hashUTF8->lookupOrCreateAsciiz(asciiz);
-}
-
-const UTF8* N3::bufToUTF8(const uint16* buf, uint32 len) {
- return hashUTF8->lookupOrCreateReader(buf, len);
-}
-
-const UTF8* N3::arrayToUTF8(const ArrayChar *array) {
- return bufToUTF8(array->elements, array->size);
-}
-
-CLIString *N3::arrayToString(const ArrayChar *array) {
- declare_gcroot(CLIString*, res) = (CLIString*)CLIString::stringDup(array, this);
- return res;
-}
-
-#include "MSCorlib.inc"
diff --git a/vmkit/lib/N3/VMCore/N3.h b/vmkit/lib/N3/VMCore/N3.h
deleted file mode 100644
index 6be69a5..0000000
--- a/vmkit/lib/N3/VMCore/N3.h
+++ /dev/null
@@ -1,221 +0,0 @@
-//===---------------- N3.h - The N3 virtual machine -----------------------===//
-//
-// N3
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-
-#ifndef N3_N3_H
-#define N3_N3_H
-
-#include "types.h"
-
-#include <vector>
-
-#include "llvm/Function.h"
-
-#include "mvm/JIT.h"
-#include "mvm/Object.h"
-#include "mvm/PrintBuffer.h"
-#include "mvm/Threads/Cond.h"
-#include "mvm/Threads/Locks.h"
-
-#include "types.h"
-
-namespace mvm {
- class UTF8;
- class UTF8Map;
-}
-
-namespace n3 {
-using mvm::UTF8;
-using mvm::UTF8Map;
-class ArrayObject;
-class Assembly;
-class AssemblyMap;
-class N3;
-class N3ModuleProvider;
-class StringMap;
-class VMClass;
-class VMClassArray;
-class VMCommonClass;
-class VMField;
-class VMMethod;
-class FunctionMap;
-class N3ModuleProvider;
-class VMMethod;
-class VMObject;
-class VMThread;
-class ArrayChar;
-class CLIString;
-
-class ThreadSystem : public mvm::PermanentObject {
-public:
- ThreadSystem();
-
- uint16 nonDaemonThreads;
- mvm::Lock* nonDaemonLock;
- mvm::Cond* nonDaemonVar;
-
- virtual void print(mvm::PrintBuffer* buf) const;
-};
-
-class ClArgumentsInfo {
-public:
- int argc;
- char** argv;
- uint32 appArgumentsPos;
- char* assembly;
-
- void readArgs(int argc, char** argv, N3 *vm);
-
- void printInformation();
- void nyi();
- void printVersion();
-};
-
-
-class N3 : public mvm::VirtualMachine {
-public:
- // instance fields
- const char* name;
-
- ClArgumentsInfo argumentsInfo;
- AssemblyMap* loadedAssemblies;
- std::vector<const char*> assemblyPath;
- Assembly* coreAssembly;
-
- ThreadSystem* threadSystem;
- VMThread* bootstrapThread;
-
- UTF8Map* hashUTF8;
-
- mvm::Lock* protectModule;
- FunctionMap* functions;
-
- mvm::BaseIntrinsics* module;
- llvm::Module* LLVMModule;
- N3ModuleProvider* TheModuleProvider;
-
- // constructors / destructors
- N3(mvm::BumpPtrAllocator &allocator, const char *name);
- ~N3();
-
- // virtual methods
- virtual void print(mvm::PrintBuffer* buf) const;
- virtual void TRACER;
- virtual void runApplication(int argc, char** argv);
- virtual void compile(const char* name);
- virtual void waitForExit();
-
- // non virtual methods
- void executeAssembly(const char* name, ArrayObject* args);
- void runMain(int argc, char** argv);
-
- VMMethod* lookupFunction(llvm::Function* F);
-
- llvm::Module* getLLVMModule() { return LLVMModule; }
-
- Assembly* constructAssembly(const UTF8* name);
- Assembly* lookupAssembly(const UTF8* name);
-
- // usefull string, uint16 and utf8 functions
-
- ArrayChar* asciizToArray(const char *asciiz);
- ArrayChar* bufToArray(const uint16 *buf, uint32 len);
- ArrayChar* UTF8ToArray(const UTF8 *utf8);
- const UTF8* asciizToUTF8(const char *asciiz);
- const UTF8* bufToUTF8(const uint16 *buf, uint32 len);
- const UTF8* arrayToUTF8(const ArrayChar *array);
- CLIString* arrayToString(const ArrayChar *array);
-
- /*
- void illegalAccessException(const char* msg);
- void initializerError(const VMObject* excp);
- void invocationTargetException(const VMObject* obj);
- void classCastException(const char* msg);
- void errorWithExcp(const char* className, const VMObject* excp);*/
- void illegalArgumentException(const char* msg);
- void arrayStoreException();
- void illegalMonitorStateException(const VMObject* obj);
- void interruptedException(const VMObject* obj);
- void nullPointerException(const char* fmt, ...);
- void outOfMemoryError(sint32 n);
- void indexOutOfBounds(const VMObject* obj, sint32 entry);
- void negativeArraySizeException(int size);
- void unknownError(const char* fmt, ...);
-
- void error(const char* fmt, ...);
- void error(const char* className, const char* fmt, ...);
- void error(const char* className, const char* fmt, va_list ap);
-
- // static fields
- static N3* bootstrapVM;
-
- static const UTF8* clinitName;
- static const UTF8* ctorName;
- static const UTF8* invokeName;
- static const UTF8* math;
- static const UTF8* system;
- static const UTF8* sqrt;
- static const UTF8* sin;
- static const UTF8* cos;
- static const UTF8* exp;
- static const UTF8* log;
- static const UTF8* floor;
- static const UTF8* log10;
- static const UTF8* isNan;
- static const UTF8* pow;
- static const UTF8* floatName;
- static const UTF8* doubleName;
- static const UTF8* testInfinity;
-
- // Exceptions name
- static const char* SystemException;
- static const char* OverFlowException;
- static const char* OutOfMemoryException;
- static const char* IndexOutOfRangeException;
- static const char* SynchronizationLocException;
- static const char* NullReferenceException;
- static const char* ThreadInterruptedException;
- static const char* MissingMethodException;
- static const char* MissingFieldException;
- static const char* ArrayTypeMismatchException;
- static const char* ArgumentException;
- /*static const char* ArithmeticException;
- static const char* ClassNotFoundException;
- static const char* InvocationTargetException;
- static const char* ClassCastException;
- static const char* ArrayIndexOutOfBoundsException;
- static const char* SecurityException;
- static const char* ClassFormatError;
- static const char* ClassCircularityError;
- static const char* NoClassDefFoundError;
- static const char* UnsupportedClassVersionError;
- static const char* NoSuchFieldError;
- static const char* NoSuchMethodError;
- static const char* InstantiationError;
- static const char* IllegalAccessError;
- static const char* IllegalAccessException;
- static const char* VerifyError;
- static const char* ExceptionInInitializerError;
- static const char* LinkageError;
- static const char* AbstractMethodError;
- static const char* UnsatisfiedLinkError;
- static const char* InternalError;
- static const char* StackOverflowError;
- */
- // Exceptions
-
- // static methods
- static N3* allocateBootstrap();
- static N3* allocate(const char* name, N3* parent);
- static void mainCLIStart(VMThread* th);
-};
-
-} // end namespace n3
-
-#endif
diff --git a/vmkit/lib/N3/VMCore/N3Debug.h b/vmkit/lib/N3/VMCore/N3Debug.h
deleted file mode 100644
index 6b3338f..0000000
--- a/vmkit/lib/N3/VMCore/N3Debug.h
+++ /dev/null
@@ -1,20 +0,0 @@
-#ifndef _N3_DEBUG_H_
-#define _N3_DEBUG_H_
-
-#if 0
-#define DEBUG 1
-#define WITH_COLOR 1
-#define N3_COMPILE 2
-#define N3_EXECUTE 2
-#define N3_LOAD 1
-#else
-#define DEBUG 0
-#define WITH_COLOR 0
-#define N3_COMPILE 0
-#define N3_EXECUTE 0
-#define N3_LOAD 0
-#endif
-
-#include "debug.h"
-
-#endif
diff --git a/vmkit/lib/N3/VMCore/N3Initialise.cpp b/vmkit/lib/N3/VMCore/N3Initialise.cpp
deleted file mode 100644
index b3c66f2..0000000
--- a/vmkit/lib/N3/VMCore/N3Initialise.cpp
+++ /dev/null
@@ -1,251 +0,0 @@
-//===----------- N3Initialise.cpp - Initialization of N3 ------------------===//
-//
-// N3
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-
-#include <vector>
-
-#include "llvm/LLVMContext.h"
-
-#include "mvm/CompilationUnit.h"
-#include "mvm/JIT.h"
-#include "mvm/Threads/Locks.h"
-
-#include "Assembly.h"
-#include "CLIString.h"
-#include "CLIJit.h"
-#include "LockedMap.h"
-#include "NativeUtil.h"
-#include "MSCorlib.h"
-#include "N3.h"
-#include "N3ModuleProvider.h"
-#include "Reader.h"
-#include "VMArray.h"
-#include "VMCache.h"
-#include "VMClass.h"
-#include "VMObject.h"
-#include "VMThread.h"
-
-using namespace n3;
-
-N3* N3::bootstrapVM = 0;
-mvm::Lock* VMObject::globalLock = 0;
-
-VMCommonClass* VMClassArray::SuperArray = 0;
-std::vector<VMClass*> VMClassArray::InterfacesArray;
-std::vector<VMMethod*> VMClassArray::VirtualMethodsArray;
-std::vector<VMMethod*> VMClassArray::StaticMethodsArray;
-std::vector<VMField*> VMClassArray::VirtualFieldsArray;
-std::vector<VMField*> VMClassArray::StaticFieldsArray;
-
-#define DEF_TYPE(name, type) \
- VMClass *MSCorlib::p##name = 0;
-
-#define DEF_ARRAY_LLVM_TYPE(name, type) \
- const llvm::Type* Array##name::llvmType = 0;
-
-#define DEF_ARRAY_AND_TYPE(name, type) \
- DEF_TYPE(name, type) \
- VMClassArray *MSCorlib::array##name = 0; \
- VMField* MSCorlib::ctor##name = 0;
-
-ON_TYPES(DEF_ARRAY_AND_TYPE, _F_NT)
-ON_TYPES(DEF_ARRAY_LLVM_TYPE, _F_NT)
-ON_STRING(DEF_ARRAY_AND_TYPE, _F_NT)
-ON_VOID(DEF_TYPE, _F_NT)
-
-#undef DEF_ARRAY_LLVM_TYPE
-#undef DEF_TYPE
-#undef DEF_ARRAY_AND_TYPE
-
-VMClass* MSCorlib::pValue = 0;
-VMClass* MSCorlib::pEnum = 0;
-VMClass* MSCorlib::pArray = 0;
-VMClass* MSCorlib::pDelegate = 0;
-VMClass* MSCorlib::pException = 0;
-
-
-const llvm::Type* VMArray::llvmType;
-const llvm::Type* VMObject::llvmType;
-const llvm::Type* Enveloppe::llvmType;
-const llvm::Type* CacheNode::llvmType;
-
-VMMethod* MSCorlib::ctorPropertyType;
-VMMethod* MSCorlib::ctorMethodType;
-VMMethod* MSCorlib::ctorClrType;
-VMClass* MSCorlib::clrType;
-VMField* MSCorlib::typeClrType;
-VMField* MSCorlib::propertyPropertyType;
-VMField* MSCorlib::methodMethodType;
-VMMethod* MSCorlib::ctorAssemblyReflection;
-VMClass* MSCorlib::assemblyReflection;
-VMClass* MSCorlib::typedReference;
-VMField* MSCorlib::assemblyAssemblyReflection;
-VMClass* MSCorlib::propertyType;
-VMClass* MSCorlib::methodType;
-VMClass* MSCorlib::resourceStreamType;
-VMMethod* MSCorlib::ctorResourceStreamType;
-
-const UTF8* N3::clinitName = 0;
-const UTF8* N3::ctorName = 0;
-const UTF8* N3::invokeName = 0;
-const UTF8* N3::math = 0;
-const UTF8* N3::system = 0;
-const UTF8* N3::sqrt = 0;
-const UTF8* N3::sin = 0;
-const UTF8* N3::cos = 0;
-const UTF8* N3::exp = 0;
-const UTF8* N3::log = 0;
-const UTF8* N3::floor = 0;
-const UTF8* N3::log10 = 0;
-const UTF8* N3::isNan = 0;
-const UTF8* N3::pow = 0;
-const UTF8* N3::floatName = 0;
-const UTF8* N3::doubleName = 0;
-const UTF8* N3::testInfinity = 0;
-
-llvm::Function* CLIJit::printExecutionLLVM;
-llvm::Function* CLIJit::indexOutOfBoundsExceptionLLVM;
-llvm::Function* CLIJit::nullPointerExceptionLLVM;
-llvm::Function* CLIJit::classCastExceptionLLVM;
-llvm::Function* CLIJit::clearExceptionLLVM;
-llvm::Function* CLIJit::compareExceptionLLVM;
-llvm::Function* CLIJit::arrayLengthLLVM;
-
-#ifdef WITH_TRACER
-llvm::Function* CLIJit::markAndTraceLLVM;
-const llvm::FunctionType* CLIJit::markAndTraceLLVMType;
-#endif
-llvm::Function* CLIJit::vmObjectTracerLLVM;
-llvm::Function* CLIJit::initialiseClassLLVM;
-llvm::Function* CLIJit::virtualLookupLLVM;
-llvm::Function* CLIJit::arrayConsLLVM;
-llvm::Function* CLIJit::arrayMultiConsLLVM;
-llvm::Function* CLIJit::objConsLLVM;
-llvm::Function* CLIJit::objInitLLVM;
-llvm::Function* CLIJit::throwExceptionLLVM;
-llvm::Function* CLIJit::instanceOfLLVM;
-llvm::Function* CLIJit::getCLIExceptionLLVM;
-llvm::Function* CLIJit::getCppExceptionLLVM;
-llvm::Function* CLIJit::newStringLLVM;
-
-static void initialiseVT() {
-}
-
-VMThread* VMThread::TheThread = 0;
-
-static void initialiseStatics() {
- CLIJit::initialise();
-
- VMObject::globalLock = new mvm::LockNormal();
-
- N3* vm = N3::bootstrapVM = N3::allocateBootstrap();
- VMThread::TheThread = new VMThread(0, vm);
-
- vm->assemblyPath.push_back("");
- vm->assemblyPath.push_back(MSCorlib::libsPath);
-
- Assembly* ass = vm->constructAssembly(vm->asciizToUTF8("mscorlib"));
-
- if(!ass->resolve(1, "dll"))
- VMThread::get()->getVM()->error("can not load mscorlib.dll. Abort");
-
- vm->coreAssembly = ass;
-
-#define INIT(var, nameSpace, name, type, prim) {\
- var = (VMClass*)vm->coreAssembly->loadTypeFromName( \
- vm->asciizToUTF8(name), \
- vm->asciizToUTF8(nameSpace),\
- false, false, false, true); \
- var->isPrimitive = prim; \
- if (type) { \
- var->naturalType = type; \
- var->virtualType = type; \
- }}
-
- assert(VMObject::llvmType);
-
- INIT(MSCorlib::pObject, "System", "Object", VMObject::llvmType, false);
- INIT(MSCorlib::pValue, "System", "ValueType", 0, false);
- INIT(MSCorlib::pVoid, "System", "Void", llvm::Type::getVoidTy(getGlobalContext()), true);
- INIT(MSCorlib::pBoolean, "System", "Boolean", llvm::Type::getInt1Ty(getGlobalContext()), true);
- INIT(MSCorlib::pUInt8, "System", "Byte", llvm::Type::getInt8Ty(getGlobalContext()), true);
- INIT(MSCorlib::pSInt8, "System", "SByte", llvm::Type::getInt8Ty(getGlobalContext()), true);
- INIT(MSCorlib::pChar, "System", "Char", llvm::Type::getInt16Ty(getGlobalContext()), true);
- INIT(MSCorlib::pSInt16, "System", "Int16", llvm::Type::getInt16Ty(getGlobalContext()), true);
- INIT(MSCorlib::pUInt16, "System", "UInt16", llvm::Type::getInt16Ty(getGlobalContext()), true);
- INIT(MSCorlib::pSInt32, "System", "Int32", llvm::Type::getInt32Ty(getGlobalContext()), true);
- INIT(MSCorlib::pUInt32, "System", "UInt32", llvm::Type::getInt32Ty(getGlobalContext()), true);
- INIT(MSCorlib::pSInt64, "System", "Int64", llvm::Type::getInt64Ty(getGlobalContext()), true);
- INIT(MSCorlib::pUInt64, "System", "UInt64", llvm::Type::getInt64Ty(getGlobalContext()), true);
- INIT(MSCorlib::pIntPtr, "System", "IntPtr", llvm::PointerType::getUnqual(llvm::Type::getInt8Ty(getGlobalContext())), true);
- INIT(MSCorlib::pUIntPtr, "System", "UIntPtr", llvm::PointerType::getUnqual(llvm::Type::getInt8Ty(getGlobalContext())), true);
- INIT(MSCorlib::pDouble, "System", "Double", llvm::Type::getDoubleTy(getGlobalContext()), true);
- INIT(MSCorlib::pFloat, "System", "Single", llvm::Type::getFloatTy(getGlobalContext()), true);
- INIT(MSCorlib::pEnum, "System", "Enum", llvm::Type::getInt32Ty(getGlobalContext()), true);
- INIT(MSCorlib::pArray, "System", "Array", 0, true);
- INIT(MSCorlib::pException,"System", "Exception", 0, false);
- INIT(MSCorlib::pDelegate, "System", "Delegate", 0, false);
-
-#undef INIT
-
- VMClassArray::SuperArray = MSCorlib::pArray;
-
- MSCorlib::loadStringClass(vm);
-
-#define BUILD_ARRAY(name, type) \
- MSCorlib::array##name = ass->constructArray(MSCorlib::p##name, 1);
-
- ON_TYPES(BUILD_ARRAY, _F_NT);
- ON_STRING(BUILD_ARRAY, _F_NT);
-
- N3::clinitName = vm->asciizToUTF8(".cctor");
- N3::ctorName = vm->asciizToUTF8(".ctor");
- N3::invokeName = vm->asciizToUTF8("Invoke");
- N3::math = vm->asciizToUTF8("Math");
- N3::system = vm->asciizToUTF8("System");
- N3::sqrt = vm->asciizToUTF8("Sqrt");
- N3::sin = vm->asciizToUTF8("Sin");
- N3::cos = vm->asciizToUTF8("Cos");
- N3::exp = vm->asciizToUTF8("Exp");
- N3::log = vm->asciizToUTF8("Log");
- N3::floor = vm->asciizToUTF8("Floor");
- N3::log10 = vm->asciizToUTF8("Log10");
- N3::isNan = vm->asciizToUTF8("IsNaN");
- N3::pow = vm->asciizToUTF8("Pow");
- N3::floatName = vm->asciizToUTF8("Float");
- N3::doubleName = vm->asciizToUTF8("Double");
- N3::testInfinity = vm->asciizToUTF8("TestInfinity");
-
- MSCorlib::pArray->resolveType(1, 0, 0);
- MSCorlib::pArray->resolveVT();
-
- MSCorlib::initialise(vm);
-}
-
-
-mvm::CompilationUnit* mvm::VirtualMachine::initialiseCLIVM() {
- if (!N3::bootstrapVM) {
- initialiseVT();
- initialiseStatics();
- }
- return 0;
-}
-
-void N3::runApplication(int argc, char** argv) {
- ((N3*)this)->runMain(argc, argv);
-}
-
-void N3::compile(const char* argv) {
- assert(0 && "This virtual machine does not perform static compilation yet!\n");
-}
-
-mvm::VirtualMachine* mvm::VirtualMachine::createCLIVM(mvm::CompilationUnit* C) {
- N3* vm = N3::allocate("", N3::bootstrapVM);
- return vm;
-}
diff --git a/vmkit/lib/N3/VMCore/N3MetaType.h b/vmkit/lib/N3/VMCore/N3MetaType.h
deleted file mode 100644
index 71ba81b..0000000
--- a/vmkit/lib/N3/VMCore/N3MetaType.h
+++ /dev/null
@@ -1,44 +0,0 @@
-#ifndef _N3_META_TYPE_H_
-#define _N3_META_TYPE_H_
-
-#define do_nothing(obj, val)
-
-#define _APP(A, B) A(B)
-
-#define ON_PRIMITIVES(_, _F) \
- _APP(_, _F(Boolean, bool, IntVal.getBoolValue(), do_nothing, writeBool, "Array<", " ", ">")) \
- _APP(_, _F(UInt8, uint8, IntVal.getZExtValue(), do_nothing, writeS4, "Array<", " ", ">")) \
- _APP(_, _F(SInt8, sint8, IntVal.getSExtValue(), do_nothing, writeS4, "Array<", " ", ">")) \
- _APP(_, _F(Char, uint16, IntVal.getZExtValue(), do_nothing, writeChar, "", "", "")) \
- _APP(_, _F(UInt16, uint16, IntVal.getZExtValue(), do_nothing, writeS4, "Array<", " ", ">")) \
- _APP(_, _F(SInt16, sint16, IntVal.getSExtValue(), do_nothing, writeS4, "Array<", " ", ">")) \
- _APP(_, _F(UInt32, uint32, IntVal.getZExtValue(), do_nothing, writeS4, "Array<", " ", ">")) \
- _APP(_, _F(SInt32, sint32, IntVal.getSExtValue(), do_nothing, writeS4, "Array<", " ", ">")) \
- _APP(_, _F(UInt64, uint64, IntVal.getZExtValue(), do_nothing, writeS8, "Array<", " ", ">")) \
- _APP(_, _F(SInt64, sint64, IntVal.getSExtValue(), do_nothing, writeS8, "Array<", " ", ">")) \
- _APP(_, _F(UIntPtr, uint*, PointerVal, do_nothing, writePtr, "Array<", " ", ">")) \
- _APP(_, _F(IntPtr, int*, PointerVal, do_nothing, writePtr, "Array<", " ", ">")) \
- _APP(_, _F(Float, float, FloatVal, do_nothing, writeFP, "Array<", " ", ">")) \
- _APP(_, _F(Double, double, DoubleVal, do_nothing, writeFP, "Array<", " ", ">"))
-
-#define ON_VOID(_, _F) \
- _APP(_, _F(Void, void, abort(), do_nothing, abort(), "", "", ""))
-
-#define ON_OBJECT(_, _F) \
- _APP(_, _F(Object, VMObject*, PointerVal, llvm_gcroot, writeObj, "Array<", " ", ">"))
-
-#define ON_STRING(_, _F) \
- _APP(_, _F(String, uint16*, PointerVal, llvm_gcroot, writeObj, "", "", ""))
-
-#define ON_TYPES(_, _F) \
- ON_PRIMITIVES(_, _F) \
- ON_OBJECT(_, _F)
-
-#define _F_NT( name, type, gv_extractor, do_root, writer, pre, sep, post) name, type
-#define _F_NTR( name, type, gv_extractor, do_root, writer, pre, sep, post) name, type, do_root
-#define _F_NTE( name, type, gv_extractor, do_root, writer, pre, sep, post) name, type, gv_extractor
-#define _F_NTRW(name, type, gv_extractor, do_root, writer, pre, sep, post) name, type, do_root, writer, pre, sep, post
-#define _F_ALL( name, type, gv_extractor, do_root, writer, pre, sep, post) name, type, gv_extractor, writer, do_root, pre, sep, post
-
-
-#endif
diff --git a/vmkit/lib/N3/VMCore/N3ModuleProvider.cpp b/vmkit/lib/N3/VMCore/N3ModuleProvider.cpp
deleted file mode 100644
index 41da8a8..0000000
--- a/vmkit/lib/N3/VMCore/N3ModuleProvider.cpp
+++ /dev/null
@@ -1,44 +0,0 @@
-//===------ N3ModuleProvider.cpp - LLVM Module Provider for N3 ------------===//
-//
-// N3
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#include <llvm/Module.h>
-#include <llvm/GVMaterializer.h>
-
-#include "mvm/JIT.h"
-
-#include "Assembly.h"
-#include "CLIJit.h"
-#include "N3ModuleProvider.h"
-#include "VMClass.h"
-#include "VMThread.h"
-#include "N3.h"
-
-using namespace llvm;
-using namespace n3;
-
-
-bool N3ModuleProvider::Materialize(GlobalValue *GV, std::string *ErrInfo) {
- Function* F = dyn_cast<Function>(GV);
- assert(F && "Not a function.");
- if (F->getLinkage() == GlobalValue::ExternalLinkage) return false;
- if (!F->empty()) return false;
- VMMethod* meth = functions->lookup(F);
-
- if (!meth) {
- // VT methods
- return false;
- } else {
- meth->compileToNative();
- return false;
- }
-}
-
-bool N3ModuleProvider::isMaterializable(const llvm::GlobalValue* GV) const {
- return GV->getLinkage() == GlobalValue::ExternalWeakLinkage;
-}
diff --git a/vmkit/lib/N3/VMCore/N3ModuleProvider.h b/vmkit/lib/N3/VMCore/N3ModuleProvider.h
deleted file mode 100644
index a07fcee..0000000
--- a/vmkit/lib/N3/VMCore/N3ModuleProvider.h
+++ /dev/null
@@ -1,47 +0,0 @@
-//===-------- N3ModuleProvider.h - LLVM Module Provider for N3 ------------===//
-//
-// N3
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#ifndef N3_MODULE_PROVIDER_H
-#define N3_MODULE_PROVIDER_H
-
-#include <llvm/GVMaterializer.h>
-#include <llvm/Module.h>
-
-#include "LockedMap.h"
-
-using namespace llvm;
-
-namespace n3 {
-
-class N3ModuleProvider : public GVMaterializer {
-public:
- FunctionMap* functions;
- Module* TheModule;
-
- N3ModuleProvider(Module *m, FunctionMap* f) {
- TheModule = m;
- m->setMaterializer(this);
- functions = f;
- }
-
- bool Materialize(GlobalValue *GV, std::string *ErrInfo = 0);
- virtual bool isMaterializable(const llvm::GlobalValue*) const;
- virtual bool isDematerializable(const llvm::GlobalValue*) const {
- return false;
- }
- virtual bool MaterializeModule(llvm::Module*, std::string*) { return true; }
-
- VMMethod* lookupFunction(Function* F) {
- return functions->lookup(F);
- }
-};
-
-} // End n3 namespace
-
-#endif
diff --git a/vmkit/lib/N3/VMCore/NativeUtil.cpp b/vmkit/lib/N3/VMCore/NativeUtil.cpp
deleted file mode 100644
index 85af2f2..0000000
--- a/vmkit/lib/N3/VMCore/NativeUtil.cpp
+++ /dev/null
@@ -1,85 +0,0 @@
-//===------- NativeUtil.cpp - Methods to call native functions --------------===//
-//
-// N3
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#include <dlfcn.h>
-#include <string.h>
-
-#include "llvm/DerivedTypes.h"
-
-#include "NativeUtil.h"
-#include "N3.h"
-#include "VMArray.h"
-#include "VMClass.h"
-#include "VMThread.h"
-
-using namespace n3;
-
-static void cliToInternal(char* buf) {
- uint32 i = 0;
- while (buf[i] != 0) {
- if (buf[i] == '.') buf[i] = '_';
- ++i;
- }
-}
-
-static void* makeFull(VMCommonClass* cl, VMMethod* meth) {
- char* buf = (char*)alloca(4096);
- sprintf(buf,
- "%s_%s_%s",
- mvm::PrintBuffer(cl->nameSpace).cString(),
- mvm::PrintBuffer(cl->name).cString(),
- mvm::PrintBuffer(meth->name).cString());
-
- std::vector<VMCommonClass*>::iterator i = meth->parameters.begin(),
- e = meth->parameters.end();
-
- // Remove return type;
- ++i;
- for ( ; i!= e; ++i) {
- VMCommonClass* cl = *i;
- sprintf(buf, "%s_%s_%s", buf, mvm::PrintBuffer(cl->nameSpace).cString(), mvm::PrintBuffer(cl->name).cString());
- }
-
- cliToInternal(buf);
- void* res = dlsym(0, buf);
-
- if (!res) {
- VMThread::get()->getVM()->error("unable to find native method %s",
- mvm::PrintBuffer(meth).cString());
- }
-
- return res;
-}
-
-void* NativeUtil::nativeLookup(VMCommonClass* cl, VMMethod* meth) {
- mvm::PrintBuffer _name(cl->name);
- mvm::PrintBuffer _nameSpace(cl->nameSpace);
- mvm::PrintBuffer _methName(meth->name);
- char* name = _name.cString();
- char* nameSpace = _nameSpace.cString();
- char* methName = _methName.cString();
-
- char* buf = (char*)alloca(6 + strlen(name) + strlen(nameSpace) +
- strlen(methName));
- sprintf(buf, "%s_%s_%s", nameSpace, name, methName);
- cliToInternal(buf);
- void* res = dlsym(0, buf);
- if (!res) {
- buf = (char*)alloca(6 + strlen(name) + strlen(nameSpace) +
- strlen(methName) + 10);
- sprintf(buf, "%s_%s_%s_%d", nameSpace, name, methName,
- meth->getSignature(NULL)->getNumParams());
- cliToInternal(buf);
- res = dlsym(0, buf);
- if (!res) {
- return makeFull(cl, meth);
- }
- }
- return res;
-}
diff --git a/vmkit/lib/N3/VMCore/NativeUtil.h b/vmkit/lib/N3/VMCore/NativeUtil.h
deleted file mode 100644
index 5051863..0000000
--- a/vmkit/lib/N3/VMCore/NativeUtil.h
+++ /dev/null
@@ -1,26 +0,0 @@
-//===------- NativeUtil.h - Methods to call native functions --------------===//
-//
-// N3
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#ifndef N3_NATIVE_UTIL_H
-#define N3_NATIVE_UTIL_H
-
-namespace n3 {
-
-class VMCommonClass;
-class VMMethod;
-
-class NativeUtil {
-public:
-
- static void* nativeLookup(VMCommonClass* cl, VMMethod* meth);
-};
-
-}
-
-#endif
diff --git a/vmkit/lib/N3/VMCore/OpcodeNames.def b/vmkit/lib/N3/VMCore/OpcodeNames.def
deleted file mode 100644
index 8c59296..0000000
--- a/vmkit/lib/N3/VMCore/OpcodeNames.def
+++ /dev/null
@@ -1,279 +0,0 @@
-//===-------------- OpcodeNames.def - Name of opcodes ---------------------===//
-//
-// N3
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#ifndef OPCODE_NAMES_DEF
-#define OPCODE_NAMES_DEF
-
-const char* n3::CLIJit::OpcodeNames[0xE1] = {
- "nop", // 0x00
- "break", // 0x01
- "ldarg.0", // 0x02
- "ldarg.1", // 0x03
- "ldarg.2", // 0x04
- "ldarg.3", // 0x05
- "ldloc.0", // 0x06
- "ldloc.1", // 0x07
- "ldloc.2", // 0x08
- "ldloc.3", // 0x09
- "stloc.0", // 0x0A
- "stloc.1", // 0x0B
- "stloc.2", // 0x0C
- "stloc.3", // 0x0D
- "ldarg.s", // 0x0E
- "ldarga.s", // 0x0F
- "starg.s", // 0x10
- "ldloc.s", // 0x11
- "ldloca.s", // 0x12
- "stloc.s", // 0x13
- "ldnull", // 0x14
- "ldc.i4.m1", // 0x15
- "ldc.i4.0", // 0x16
- "ldc.i4.1", // 0x17
- "ldc.i4.2", // 0x18
- "ldc.i4.3", // 0x19
- "ldc.i4.4", // 0x1A
- "ldc.i4.5", // 0x1B
- "ldc.i4.6", // 0x1C
- "ldc.i4.7", // 0x1D
- "ldc.i4.8", // 0x1E
- "ldc.i4.s", // 0x1F
- "ldc.i4", // 0x20
- "ldc.i8", // 0x21
- "ldc.r4", // 0x22
- "ldc.r8", // 0x23
- "unused99", // 0x24
- "dup", // 0x25
- "pop", // 0x26
- "jmp", // 0x27
- "call", // 0x28
- "calli", // 0x29
- "ret", // 0x2A
- "br.s", // 0x2B
- "brfalse.s", // 0x2C
- "brtrue.s", // 0x2D
- "beq.s", // 0x2E
- "bge.s", // 0x2F
- "bgt.s", // 0x30
- "ble.s", // 0x31
- "blt.s", // 0x32
- "bne.un.s", // 0x33
- "bge.un.s", // 0x34
- "bgt.un.s", // 0x35
- "ble.un.s", // 0x36
- "blt.un.s", // 0x37
- "br", // 0x38
- "brfalse", // 0x39
- "brtrue", // 0x3A
- "beq", // 0x3B
- "bge", // 0x3C
- "bgt", // 0x3D
- "ble", // 0x3E
- "blt", // 0x3F
- "bne.un", // 0x40
- "bge.un", // 0x41
- "bgt.un", // 0x42
- "ble.un", // 0x43
- "blt.un", // 0x44
- "switch", // 0x45
- "ldind.i1", // 0x46
- "ldind.u1", // 0x47
- "ldind.i2", // 0x48
- "ldind.u2", // 0x49
- "ldind.i4", // 0x4A
- "ldind.u4", // 0x4B
- "ldind.i8", // 0x4C
- "ldind.i", // 0x4D
- "ldind.r4", // 0x4E
- "ldind.r8", // 0x4F
- "ldind.ref", // 0x50
- "stind.ref", // 0x51
- "stind.i1", // 0x52
- "stind.i2", // 0x53
- "stind.i4", // 0x54
- "stind.i8", // 0x55
- "stind.r4", // 0x56
- "stind.r8", // 0x57
- "add", // 0x58
- "sub", // 0x59
- "mul", // 0x5A
- "div", // 0x5B
- "div.un", // 0x5C
- "rem", // 0x5D
- "rem.un", // 0x5E
- "and", // 0x5F
- "or", // 0x60
- "xor", // 0x61
- "shl", // 0x62
- "shr", // 0x63
- "shr.un", // 0x64
- "neg", // 0x65
- "not", // 0x66
- "conv.i1", // 0x67
- "conv.i2", // 0x68
- "conv.i4", // 0x69
- "conv.i8", // 0x6A
- "conv.r4", // 0x6B
- "conv.r8", // 0x6C
- "conv.u4", // 0x6D
- "conv.u8", // 0x6E
- "callvirt", // 0x6F
- "cpobj", // 0x70
- "ldobj", // 0x71
- "ldstr", // 0x72
- "newobj", // 0x73
- "castclass", // 0x74
- "isinst", // 0x75
- "conv.r.un", // 0x76
- "unused58", // 0x77
- "unused1", // 0x78
- "unbox", // 0x79
- "throw", // 0x7A
- "ldfld", // 0x7B
- "ldflda", // 0x7C
- "stfld", // 0x7D
- "ldsfld", // 0x7E
- "ldsflda", // 0x7F
- "stsfld", // 0x80
- "stobj", // 0x81
- "conv.ovf.i1.un", // 0x82
- "conv.ovf.i2.un", // 0x83
- "conv.ovf.i4.un", // 0x84
- "conv.ovf.i8.un", // 0x85
- "conv.ovf.u1.un", // 0x86
- "conv.ovf.u2.un", // 0x87
- "conv.ovf.u4.un", // 0x88
- "conv.ovf.u8.un", // 0x89
- "conv.ovf.i.un", // 0x8A
- "conv.ovf.u.un", // 0x8B
- "box", // 0x8C
- "newarr", // 0x8D
- "ldlen", // 0x8E
- "ldelema", // 0x8F
- "ldelem.i1", // 0x90
- "ldelem.u1", // 0x91
- "ldelem.i2", // 0x92
- "ldelem.u2", // 0x93
- "ldelem.i4", // 0x94
- "ldelem.u4", // 0x95
- "ldelem.i8", // 0x96
- "ldelem.i", // 0x97
- "ldelem.r4", // 0x98
- "ldelem.r8", // 0x99
- "ldelem.ref", // 0x9A
- "stelem.i", // 0x9B
- "stelem.i1", // 0x9C
- "stelem.i2", // 0x9D
- "stelem.i4", // 0x9E
- "stelem.i8", // 0x9F
- "stelem.r4", // 0xA0
- "stelem.r8", // 0xA1
- "stelem.ref", // 0xA2
- "ldelem", // 0xA3
- "stelem", // 0xA4
- "unbox.any", // 0xA5
- "unused5", // 0xA6
- "unused6", // 0xA7
- "unused7", // 0xA8
- "unused8", // 0xA9
- "unused9", // 0xAA
- "unused10", // 0xAB
- "unused11", // 0xAC
- "unused12", // 0xAD
- "unused13", // 0xAE
- "unused14", // 0xAF
- "unused15", // 0xB0
- "unused16", // 0xB1
- "unused17", // 0xB2
- "conv.ovf.i1", // 0xB3
- "conv.ovf.u1", // 0xB4
- "conv.ovf.i2", // 0xB5
- "conv.ovf.u2", // 0xB6
- "conv.ovf.i4", // 0xB7
- "conv.ovf.u4", // 0xB8
- "conv.ovf.i8", // 0xB9
- "conv.ovf.u8", // 0xBA
- "unused50", // 0xBB
- "unused18", // 0xBC
- "unused19", // 0xBD
- "unused20", // 0xBE
- "unused21", // 0xBF
- "unused22", // 0xC0
- "unused23", // 0xC1
- "refanyval", // 0xC2
- "ckfinite", // 0xC3
- "unused24", // 0xC4
- "unused25", // 0xC5
- "mkrefany", // 0xC6
- "unused59", // 0xC7
- "unused60", // 0xC8
- "unused61", // 0xC9
- "unused62", // 0xCA
- "unused63", // 0xCB
- "unused64", // 0xCC
- "unused65", // 0xCD
- "unused66", // 0xCE
- "unused67", // 0xCF
- "ldtoken", // 0xD0
- "conv.u2", // 0xD1
- "conv.u1", // 0xD2
- "conv.i", // 0xD3
- "conv.ovf.i", // 0xD4
- "conv.ovf.u", // 0xD5
- "add.ovf", // 0xD6
- "add.ovf.un", // 0xD7
- "mul.ovf", // 0xD8
- "mul.ovf.un", // 0xD9
- "sub.ovf", // 0xDA
- "sub.ovf.un", // 0xDB
- "endfinally", // 0xDC
- "leave", // 0xDD
- "leave.s", // 0xDE
- "stind.i", // 0xDF
- "conv.u" // 0xE0
-};
-
-const char* n3::CLIJit::OpcodeNamesFE[0x23] = {
- "arglist", // 0x00
- "ceq", // 0x01
- "cgt", // 0x02
- "cgt.un", // 0x03
- "clt", // 0x04
- "clt.un", // 0x05
- "ldftn", // 0x06
- "ldvirtftn", // 0x07
- "unused56", // 0x08
- "ldarg", // 0x09
- "ldarga", // 0x0A
- "starg", // 0x0B
- "ldloc", // 0x0C
- "ldloca", // 0x0D
- "stloc", // 0x0E
- "localloc", // 0x0F
- "unused57", // 0x10
- "endfilter", // 0x11
- "unaligned.", // 0x12
- "volatile.", // 0x13
- "tail.", // 0x14
- "initobj", // 0x15
- "constrained.", // 0x16
- "cpblk", // 0x17
- "initblk", // 0x18
- "no.", // 0x19
- "rethrow", // 0x1A
- "unused", // 0x1B
- "sizeof", // 0x1C
- "refanytype", // 0x1D
- "readonly.", // 0x1E
- "unused53", // 0x1F
- "unused54", // 0x20
- "unused55", // 0x21
- "unused70" // 0x22
-};
-
-#endif
diff --git a/vmkit/lib/N3/VMCore/Opcodes.cpp b/vmkit/lib/N3/VMCore/Opcodes.cpp
deleted file mode 100644
index 8259535..0000000
--- a/vmkit/lib/N3/VMCore/Opcodes.cpp
+++ /dev/null
@@ -1,2567 +0,0 @@
-//===----------- Opcodes.cpp - Reads and compiles opcodes -----------------===//
-//
-// N3
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#include "N3Debug.h"
-
-#include <cstring>
-
-#include <llvm/Constants.h>
-#include <llvm/DerivedTypes.h>
-#include <llvm/LLVMContext.h>
-#include <llvm/Module.h>
-#include <llvm/Type.h>
-#include <llvm/Function.h>
-#include <llvm/Instructions.h>
-#include <llvm/PassManager.h>
-#include <llvm/Transforms/IPO.h>
-#include <llvm/Transforms/Scalar.h>
-#include <llvm/Target/TargetData.h>
-#include <llvm/Target/TargetMachine.h>
-#include <llvm/Target/TargetOptions.h>
-
-#include "mvm/JIT.h"
-
-#include "Assembly.h"
-#include "CLIJit.h"
-#include "CLIString.h"
-#include "MSCorlib.h"
-#include "N3.h"
-#include "Reader.h"
-#include "VMArray.h"
-#include "VMClass.h"
-#include "VMObject.h"
-#include "VMThread.h"
-
-#include "OpcodeNames.def"
-
-using namespace n3;
-using namespace llvm;
-
-
-static inline sint8 readS1(uint8* bytecode, uint32& i) {
- return ((sint8*)bytecode)[++i];
-}
-
-static inline uint8 readU1(uint8* bytecode, uint32& i) {
- return bytecode[++i];
-}
-
-static inline sint16 readS2(uint8* bytecode, uint32& i) {
- sint16 val = readS1(bytecode, i);
- return val | (readU1(bytecode, i) << 8);
-}
-
-static inline uint16 readU2(uint8* bytecode, uint32& i) {
- uint16 val = readU1(bytecode, i);
- return val | (readU1(bytecode, i) << 8);
-}
-
-static inline sint32 readS4(uint8* bytecode, uint32& i) {
- sint32 val = readU2(bytecode, i);
- return val | (readU2(bytecode, i) << 16);
-}
-
-
-static inline uint32 readU4(uint8* bytecode, uint32& i) {
- return readS4(bytecode, i);
-}
-
-static inline sint64 readS8(uint8* bytecode, uint32& i) {
- uint64 val = readU4(bytecode, i);
- uint64 _val2 = readU4(bytecode, i);
- uint64 val2 = _val2 << 32;
- return val | val2;
-}
-
-typedef union ufloat_t {
- uint32 i;
- float f;
-}ufloat_t;
-
-typedef union udouble_t {
- sint64 l;
- double d;
-}udouble_t;
-
-
-static inline float readFloat(uint8* bytecode, uint32& i) {
- ufloat_t tmp;
- tmp.i = readU4(bytecode, i);
- return tmp.f;
-}
-
-static inline double readDouble(uint8* bytecode, uint32& i) {
- udouble_t tmp;
- tmp.l = readS8(bytecode, i);
- return tmp.d;
-}
-
-
-extern "C" void n3PrintExecution(char* opcode, VMMethod* meth) {
- fprintf(stderr, "executing %s %s\n", mvm::PrintBuffer(meth).cString(), opcode);
-}
-
-
-static void verifyType(Value*& val1, Value*& val2, BasicBlock* currentBlock) {
- const Type* t1 = val1->getType();
- const Type* t2 = val2->getType();
- if (t1 != t2) {
- if (t1->isIntegerTy() && t2->isIntegerTy()) {
- if (t1->getPrimitiveSizeInBits() < t2->getPrimitiveSizeInBits()) {
- val1 = new SExtInst(val1, t2, "", currentBlock);
- } else {
- val2 = new SExtInst(val2, t1, "", currentBlock);
- }
- } else if (t1->isFloatTy()) {
- if (t1->getPrimitiveSizeInBits() < t2->getPrimitiveSizeInBits()) {
- val1 = new FPExtInst(val1, t2, "", currentBlock);
- } else {
- val2 = new FPExtInst(val2, t1, "", currentBlock);
- }
- } else if (isa<PointerType>(t1) && isa<PointerType>(t2)) {
- val1 = new BitCastInst(val1, VMObject::llvmType, "", currentBlock);
- val2 = new BitCastInst(val2, VMObject::llvmType, "", currentBlock);
- } else if (t1->isIntegerTy() && t2 == PointerType::getUnqual(Type::getInt8Ty(getGlobalContext()))) {
- // CLI says that this is fine for some operation
- val2 = new PtrToIntInst(val2, t1, "", currentBlock);
- } else if (t2->isIntegerTy() && t1 == PointerType::getUnqual(Type::getInt8Ty(getGlobalContext()))) {
- // CLI says that this is fine for some operation
- val1 = new PtrToIntInst(val1, t2, "", currentBlock);
- }
- }
-}
-
-void convertValue(Value*& val, const Type* t1, BasicBlock* currentBlock) {
- const Type* t2 = val->getType();
- if (t1 != t2) {
- if (t1->isIntegerTy() && t2->isIntegerTy()) {
- if (t2->getPrimitiveSizeInBits() < t1->getPrimitiveSizeInBits()) {
- val = new SExtInst(val, t1, "", currentBlock);
- } else {
- val = new TruncInst(val, t1, "", currentBlock);
- }
- } else if (t1->isFloatTy() && t2->isFloatTy()) {
- if (t2->getPrimitiveSizeInBits() < t1->getPrimitiveSizeInBits()) {
- val = new FPExtInst(val, t1, "", currentBlock);
- } else {
- val = new FPTruncInst(val, t1, "", currentBlock);
- }
- } else if (isa<PointerType>(t1) && isa<PointerType>(t2)) {
- val = new BitCastInst(val, t1, "", currentBlock);
- }
- }
-}
-
-static void store(Value* val, Value* local, bool vol,
- BasicBlock* currentBlock, mvm::BaseIntrinsics* module) {
- const Type* contained = local->getType()->getContainedType(0);
- if (contained->isSingleValueType()) {
- if (val->getType() != contained) {
- convertValue(val, contained, currentBlock);
- }
- new StoreInst(val, local, vol, currentBlock);
- } else if (isa<PointerType>(val->getType())) {
- uint64 size = mvm::MvmModule::getTypeSize(contained);
-
- std::vector<Value*> params;
- params.push_back(new BitCastInst(local, PointerType::getUnqual(Type::getInt8Ty(getGlobalContext())), "", currentBlock));
- params.push_back(new BitCastInst(val, PointerType::getUnqual(Type::getInt8Ty(getGlobalContext())), "", currentBlock));
- params.push_back(ConstantInt::get(Type::getInt32Ty(getGlobalContext()), size));
- params.push_back(module->constantZero);
- CallInst::Create(module->llvm_memcpy_i32, params.begin(), params.end(), "", currentBlock);
- } else {
- new StoreInst(val, local, vol, currentBlock);
- }
-}
-
-static Value* load(Value* val, const char* name, BasicBlock* currentBlock, mvm::BaseIntrinsics* module) {
- const Type* contained = val->getType()->getContainedType(0);
- if (contained->isSingleValueType()) {
- return new LoadInst(val, name, currentBlock);
- } else {
- uint64 size = mvm::MvmModule::getTypeSize(contained);
- Value* ret = new AllocaInst(contained, "", currentBlock);
- std::vector<Value*> params;
- params.push_back(new BitCastInst(ret, PointerType::getUnqual(Type::getInt8Ty(getGlobalContext())), "", currentBlock));
- params.push_back(new BitCastInst(val, PointerType::getUnqual(Type::getInt8Ty(getGlobalContext())), "", currentBlock));
- params.push_back(ConstantInt::get(Type::getInt32Ty(getGlobalContext()), size));
- params.push_back(module->constantZero);
- CallInst::Create(module->llvm_memcpy_i32, params.begin(), params.end(), "", currentBlock);
- return ret;
- }
-}
-
-void CLIJit::compileOpcodes(uint8* bytecodes, uint32 codeLength, VMGenericClass* genClass, VMGenericMethod* genMethod) {
- uint32 leaveIndex = 0;
- bool isVolatile = false;
- for(uint32 i = 0; i < codeLength; ++i) {
-
- if (bytecodes[i] != 0xFE) {
- PRINT_DEBUG(N3_COMPILE, 1, COLOR_NORMAL, "\t[at %5x] %-5d ", i,
- bytecodes[i]);
- PRINT_DEBUG(N3_COMPILE, 1, LIGHT_BLUE, "compiling %s::", mvm::PrintBuffer(compilingMethod).cString());
- PRINT_DEBUG(N3_COMPILE, 1, LIGHT_CYAN, OpcodeNames[bytecodes[i]]);
- PRINT_DEBUG(N3_COMPILE, 1, LIGHT_BLUE, "\n");
- }
-
- Opinfo* opinfo = &(opcodeInfos[i]);
- if (opinfo->newBlock) {
- if (currentBlock->getTerminator() == 0) {
- branch(opinfo->newBlock, currentBlock);
- }
- setCurrentBlock(opinfo->newBlock);
- }
- currentExceptionBlock = opinfo->exceptionBlock;
- if (currentBlock->getTerminator() != 0) { // To prevent a gcj bug with useless goto
- currentBlock = createBasicBlock("gcj bug");
- }
-
-#if N3_EXECUTE > 1
- if (bytecodes[i] == 0xFE) {
- std::vector<llvm::Value*> args;
- args.push_back(ConstantInt::get(Type::getInt32Ty(getGlobalContext()), (int64_t)OpcodeNamesFE[bytecodes[i + 1]]));
- args.push_back(ConstantInt::get(Type::getInt32Ty(getGlobalContext()), (int64_t)compilingMethod));
- CallInst::Create(printExecutionLLVM, args.begin(), args.end(), "", currentBlock);
- } else {
- std::vector<llvm::Value*> args;
- args.push_back(ConstantInt::get(Type::getInt32Ty(getGlobalContext()), (int64_t)OpcodeNames[bytecodes[i]]));
- args.push_back(ConstantInt::get(Type::getInt32Ty(getGlobalContext()), (int64_t)compilingMethod));
- CallInst::Create(printExecutionLLVM, args.begin(), args.end(), "", currentBlock);
- }
-#endif
-
- if (opinfo->reqSuppl) {
- push(new LoadInst(supplLocal, "", currentBlock));
- }
-
- switch (bytecodes[i]) {
-
- case ADD: {
- Value* val2 = pop();
- bool isPointer = (val2->getType() == module->ptrType);
- Value* val1 = pop();
- isPointer |= (val1->getType() == module->ptrType);
- verifyType(val1, val2, currentBlock);
- Value* res = BinaryOperator::CreateAdd(val1, val2, "", currentBlock);
- if (isPointer) {
- res = new IntToPtrInst(res, module->ptrType, "", currentBlock);
- }
- push(res);
- break;
- }
-
- case ADD_OVF: {
- VMThread::get()->getVM()->error("implement me");
- break;
- }
-
- case ADD_OVF_UN: {
- VMThread::get()->getVM()->error("implement me");
- break;
- }
-
- case AND: {
- Value* val2 = pop();
- Value* val1 = pop();
- push(BinaryOperator::CreateAnd(val1, val2, "", currentBlock));
- break;
- }
-
-#define TEST(name, read, cmpf, cmpi, offset) case name : { \
- uint32 tmp = i; \
- Value* val2 = pop(); \
- Value* val1 = pop(); \
- BasicBlock* ifTrue = opcodeInfos[tmp + offset + read(bytecodes, i)].newBlock; \
- Value* test = 0; \
- verifyType(val1, val2, currentBlock); \
- if (val1->getType()->isFloatTy()) { \
- test = new FCmpInst(*currentBlock, FCmpInst::cmpf, val1, val2, ""); \
- } else { \
- test = new ICmpInst(*currentBlock, ICmpInst::cmpi, val1, val2, ""); \
- } \
- BasicBlock* ifFalse = createBasicBlock("false BEQ"); \
- branch(test, ifTrue, ifFalse, currentBlock); \
- currentBlock = ifFalse; \
- break; \
- }
-
- TEST(BEQ, readS4, FCMP_OEQ, ICMP_EQ, 5);
- TEST(BEQ_S, readS1, FCMP_OEQ, ICMP_EQ, 2);
-
- TEST(BGE, readS4, FCMP_OGE, ICMP_SGE, 5);
- TEST(BGE_S, readS1, FCMP_OGE, ICMP_SGE, 2);
- TEST(BGE_UN, readS4, FCMP_UGE, ICMP_UGE, 5);
- TEST(BGE_UN_S, readS1, FCMP_UGE, ICMP_UGE, 2);
-
- TEST(BGT, readS4, FCMP_OGT, ICMP_SGT, 5);
- TEST(BGT_S, readS1, FCMP_OGT, ICMP_SGT, 2);
- TEST(BGT_UN, readS4, FCMP_UGT, ICMP_UGT, 5);
- TEST(BGT_UN_S, readS1, FCMP_UGT, ICMP_UGT, 2);
-
- TEST(BLE, readS4, FCMP_OLE, ICMP_SLE, 5);
- TEST(BLE_S, readS1, FCMP_OLE, ICMP_SLE, 2);
- TEST(BLE_UN, readS4, FCMP_ULE, ICMP_ULE, 5);
- TEST(BLE_UN_S, readS1, FCMP_ULE, ICMP_ULE, 2);
-
- TEST(BLT, readS4, FCMP_OLT, ICMP_SLT, 5);
- TEST(BLT_S, readS1, FCMP_OLT, ICMP_SLT, 2);
- TEST(BLT_UN, readS4, FCMP_ULT, ICMP_ULT, 5);
- TEST(BLT_UN_S, readS1, FCMP_ULT, ICMP_ULT, 2);
-
- TEST(BNE_UN, readS4, FCMP_UNE, ICMP_NE, 5);
- TEST(BNE_UN_S, readS1, FCMP_UNE, ICMP_NE, 2);
-
-#undef TEST
-
- case BR : {
- uint32 tmp = i;
- BasicBlock* br = opcodeInfos[tmp + 5 + readS4(bytecodes, i)].newBlock;
- branch(br, currentBlock);
- break;
- }
-
- case BR_S : {
- uint32 tmp = i;
- BasicBlock* br = opcodeInfos[tmp + 2 + readS1(bytecodes, i)].newBlock;
- branch(br, currentBlock);
- break;
- }
-
- case BREAK: break;
-
-#define TEST(name, read, cmpf, cmpi, offset) case name : { \
- uint32 tmp = i; \
- Value* val2 = pop(); \
- Value* val1 = Constant::getNullValue(val2->getType()); \
- BasicBlock* ifTrue = opcodeInfos[tmp + offset + read(bytecodes, i)].newBlock; \
- Value* test = 0; \
- if (val1->getType()->isFloatTy()) { \
- test = new FCmpInst(*currentBlock, FCmpInst::cmpf, val1, val2, ""); \
- } else { \
- test = new ICmpInst(*currentBlock, ICmpInst::cmpi, val1, val2, ""); \
- } \
- BasicBlock* ifFalse = createBasicBlock("false BR"); \
- branch(test, ifTrue, ifFalse, currentBlock); \
- currentBlock = ifFalse; \
- break; \
- }
-
- TEST(BRFALSE, readS4, FCMP_OEQ, ICMP_EQ, 5);
- TEST(BRFALSE_S, readS1, FCMP_OEQ, ICMP_EQ, 2);
- TEST(BRTRUE, readS4, FCMP_ONE, ICMP_NE, 5);
- TEST(BRTRUE_S, readS1, FCMP_ONE, ICMP_NE, 2);
-
-#undef TEST
-
- case CALL: {
- uint32 value = readU4(bytecodes, i);
- invoke(value, genClass, genMethod);
- break;
- }
-
- case CALLI: {
- VMThread::get()->getVM()->unknownError("implement me");
- break;
- }
-
- case CKFINITE : {
- VMThread::get()->getVM()->unknownError("implement me");
- break;
- }
-
- case CONV_I1 : {
- Value* val = pop();
- const Type* type = val->getType();
- if (type->isFloatTy()) {
- push(new FPToSIInst(val, Type::getInt8Ty(getGlobalContext()), "", currentBlock));
- } else if (type == Type::getInt16Ty(getGlobalContext()) || type == Type::getInt32Ty(getGlobalContext()) ||
- type == Type::getInt64Ty(getGlobalContext())) {
- push(new TruncInst(val, Type::getInt8Ty(getGlobalContext()), "", currentBlock));
- } else {
- VMThread::get()->getVM()->unknownError("implement me");
- }
- break;
- }
-
- case CONV_I2 : {
- Value* val = pop();
- const Type* type = val->getType();
- if (type->isFloatTy()) {
- push(new FPToSIInst(val, Type::getInt16Ty(getGlobalContext()), "", currentBlock));
- } else if (type == Type::getInt32Ty(getGlobalContext()) || type == Type::getInt64Ty(getGlobalContext())) {
- push(new TruncInst(val, Type::getInt16Ty(getGlobalContext()), "", currentBlock));
- } else if (type == Type::getInt8Ty(getGlobalContext())) {
- push(new SExtInst(val, Type::getInt16Ty(getGlobalContext()), "", currentBlock));
- } else {
- VMThread::get()->getVM()->unknownError("implement me");
- }
- break;
- }
-
- case CONV_I4 : {
- Value* val = pop();
- const Type* type = val->getType();
- if (type->isFloatTy()) {
- push(new FPToSIInst(val, Type::getInt32Ty(getGlobalContext()), "", currentBlock));
- } else if (type == Type::getInt64Ty(getGlobalContext())) {
- push(new TruncInst(val, Type::getInt32Ty(getGlobalContext()), "", currentBlock));
- } else if (type == Type::getInt8Ty(getGlobalContext()) || type == Type::getInt16Ty(getGlobalContext())) {
- push(new SExtInst(val, Type::getInt32Ty(getGlobalContext()), "", currentBlock));
- } else if (type == Type::getInt32Ty(getGlobalContext())) {
- push(val);
- } else {
- VMThread::get()->getVM()->unknownError("implement me");
- }
- break;
- }
-
- case CONV_I8 : {
- Value* val = pop();
- const Type* type = val->getType();
- if (type->isFloatTy()) {
- push(new FPToSIInst(val, Type::getInt64Ty(getGlobalContext()), "", currentBlock));
- } else if (type == Type::getInt8Ty(getGlobalContext()) || type == Type::getInt16Ty(getGlobalContext()) ||
- type == Type::getInt32Ty(getGlobalContext())) {
- push(new SExtInst(val, Type::getInt64Ty(getGlobalContext()), "", currentBlock));
- } else {
- VMThread::get()->getVM()->unknownError("implement me");
- }
- break;
- }
-
- case CONV_R4 : {
- Value* val = pop();
- const Type* type = val->getType();
- if (type == Type::getDoubleTy(getGlobalContext())) {
- push(new FPTruncInst(val, Type::getFloatTy(getGlobalContext()), "", currentBlock));
- } else if (type->isIntegerTy()) {
- push(new SIToFPInst(val, Type::getFloatTy(getGlobalContext()), "", currentBlock));
- } else {
- VMThread::get()->getVM()->unknownError("implement me");
- }
- break;
- }
-
- case CONV_R8 : {
- Value* val = pop();
- const Type* type = val->getType();
- if (type == Type::getFloatTy(getGlobalContext())) {
- push(new FPExtInst(val, Type::getDoubleTy(getGlobalContext()), "", currentBlock));
- } else if (type->isIntegerTy()) {
- push(new SIToFPInst(val, Type::getDoubleTy(getGlobalContext()), "", currentBlock));
- } else if (type == Type::getDoubleTy(getGlobalContext())) {
- push(val);
- } else {
- VMThread::get()->getVM()->unknownError("implement me");
- }
- break;
- }
-
- case CONV_U1 : {
- Value* val = pop();
- const Type* type = val->getType();
- if (type->isFloatTy()) {
- push(new FPToUIInst(val, Type::getInt8Ty(getGlobalContext()), "", currentBlock));
- } else if (type == Type::getInt16Ty(getGlobalContext()) || type == Type::getInt32Ty(getGlobalContext()) ||
- type == Type::getInt64Ty(getGlobalContext())) {
- push(new TruncInst(val, Type::getInt8Ty(getGlobalContext()), "", currentBlock));
- } else {
- VMThread::get()->getVM()->unknownError("implement me");
- }
- break;
- }
-
- case CONV_U2 : {
- Value* val = pop();
- const Type* type = val->getType();
- if (type->isFloatTy()) {
- push(new FPToUIInst(val, Type::getInt16Ty(getGlobalContext()), "", currentBlock));
- } else if (type == Type::getInt32Ty(getGlobalContext()) || type == Type::getInt64Ty(getGlobalContext())) {
- push(new TruncInst(val, Type::getInt8Ty(getGlobalContext()), "", currentBlock));
- } else if (type == Type::getInt8Ty(getGlobalContext())) {
- push(new ZExtInst(val, Type::getInt16Ty(getGlobalContext()), "", currentBlock));
- } else {
- VMThread::get()->getVM()->unknownError("implement me");
- }
- break;
- }
-
- case CONV_U4 : {
- Value* val = pop();
- const Type* type = val->getType();
- if (type->isFloatTy()) {
- push(new FPToUIInst(val, Type::getInt32Ty(getGlobalContext()), "", currentBlock));
- } else if (type == Type::getInt64Ty(getGlobalContext())) {
- push(new TruncInst(val, Type::getInt8Ty(getGlobalContext()), "", currentBlock));
- } else if (type == Type::getInt8Ty(getGlobalContext()) || type == Type::getInt16Ty(getGlobalContext())) {
- push(new ZExtInst(val, Type::getInt16Ty(getGlobalContext()), "", currentBlock));
- } else {
- VMThread::get()->getVM()->unknownError("implement me");
- }
- break;
- }
-
- case CONV_U8 : {
- Value* val = pop();
- const Type* type = val->getType();
- if (type->isFloatTy()) {
- push(new FPToUIInst(val, Type::getInt64Ty(getGlobalContext()), "", currentBlock));
- } else if (type == Type::getInt8Ty(getGlobalContext()) || type == Type::getInt16Ty(getGlobalContext()) ||
- type == Type::getInt32Ty(getGlobalContext())) {
- push(new ZExtInst(val, Type::getInt64Ty(getGlobalContext()), "", currentBlock));
- } else {
- VMThread::get()->getVM()->unknownError("implement me");
- }
- break;
- }
-
- case CONV_I : {
- Value* val = pop();
- Value* res = 0;
-
- if (val->getType()->isIntegerTy()) {
- if (val->getType() != Type::getInt64Ty(getGlobalContext())) {
- val = new ZExtInst(val, Type::getInt64Ty(getGlobalContext()), "", currentBlock);
- }
- res = new IntToPtrInst(val, PointerType::getUnqual(Type::getInt8Ty(getGlobalContext())), "", currentBlock);
- } else if (!val->getType()->isFloatTy()) {
- res = new BitCastInst(val, PointerType::getUnqual(Type::getInt8Ty(getGlobalContext())), "", currentBlock);
- } else {
- VMThread::get()->getVM()->unknownError("implement me");
- }
-
- push(res);
- break;
- }
-
- case CONV_U : {
- VMThread::get()->getVM()->error("implement me");
- break;
- }
-
- case CONV_R_UN : {
- Value* val = pop();
- const Type* type = val->getType();
- if (type == Type::getFloatTy(getGlobalContext())) {
- push(new FPExtInst(val, Type::getDoubleTy(getGlobalContext()), "", currentBlock));
- } else if (type->isIntegerTy()) {
- push(new UIToFPInst(val, Type::getDoubleTy(getGlobalContext()), "", currentBlock));
- } else if (type == Type::getDoubleTy(getGlobalContext())) {
- push(val);
- } else {
- VMThread::get()->getVM()->unknownError("implement me");
- }
- break;
- }
-
- case CONV_OVF_I1 : {
- VMThread::get()->getVM()->error("implement me");
- break;
- }
-
- case CONV_OVF_I2 : {
- VMThread::get()->getVM()->error("implement me");
- break;
- }
-
- case CONV_OVF_I4 : {
- VMThread::get()->getVM()->error("implement me");
- break;
- }
-
- case CONV_OVF_I8 : {
- VMThread::get()->getVM()->error("implement me");
- break;
- }
-
- case CONV_OVF_U1 : {
- VMThread::get()->getVM()->error("implement me");
- break;
- }
-
- case CONV_OVF_U2 : {
- VMThread::get()->getVM()->error("implement me");
- break;
- }
-
- case CONV_OVF_U4 : {
- VMThread::get()->getVM()->error("implement me");
- break;
- }
-
- case CONV_OVF_U8 : {
- VMThread::get()->getVM()->error("implement me");
- break;
- }
-
- case CONV_OVF_I : {
- VMThread::get()->getVM()->error("implement me");
- break;
- }
-
- case CONV_OVF_U : {
- VMThread::get()->getVM()->error("implement me");
- break;
- }
-
- case CONV_OVF_I1_UN : {
- VMThread::get()->getVM()->error("implement me");
- break;
- }
-
- case CONV_OVF_I2_UN : {
- VMThread::get()->getVM()->error("implement me");
- break;
- }
-
- case CONV_OVF_I4_UN : {
- Value* val = pop();
- const Type* type = val->getType();
- if (type->isFloatTy()) {
- push(new FPToUIInst(val, Type::getInt32Ty(getGlobalContext()), "", currentBlock));
- } else if (type == Type::getInt64Ty(getGlobalContext())) {
- push(new TruncInst(val, Type::getInt8Ty(getGlobalContext()), "", currentBlock));
- } else if (type == Type::getInt8Ty(getGlobalContext()) || type == Type::getInt16Ty(getGlobalContext())) {
- push(new ZExtInst(val, Type::getInt16Ty(getGlobalContext()), "", currentBlock));
- } else if (type == Type::getInt32Ty(getGlobalContext())) {
- push(val);
- } else {
- VMThread::get()->getVM()->unknownError("implement me");
- }
- break;
- }
-
- case CONV_OVF_I8_UN : {
- VMThread::get()->getVM()->error("implement me");
- break;
- }
-
- case CONV_OVF_U1_UN : {
- VMThread::get()->getVM()->error("implement me");
- break;
- }
-
- case CONV_OVF_U2_UN : {
- VMThread::get()->getVM()->error("implement me");
- break;
- }
-
- case CONV_OVF_U4_UN : {
- VMThread::get()->getVM()->error("implement me");
- break;
- }
-
- case CONV_OVF_U8_UN : {
- VMThread::get()->getVM()->error("implement me");
- break;
- }
-
-
- case DIV: {
- Value* two = pop();
- Value* one = pop();
- if (one->getType()->isFloatTy()) {
- convertValue(one, two->getType(), currentBlock);
- push(BinaryOperator::CreateFDiv(one, two, "", currentBlock));
- } else {
- push(BinaryOperator::CreateSDiv(one, two, "", currentBlock));
- }
- break;
- }
-
- case DIV_UN: {
- Value* two = pop();
- Value* one = pop();
- if (one->getType()->isFloatTy()) {
- push(BinaryOperator::CreateFDiv(one, two, "", currentBlock));
- } else {
- push(BinaryOperator::CreateUDiv(one, two, "", currentBlock));
- }
- break;
- }
-
- case DUP: {
- push(top());
- break;
- }
-
- case ENDFINALLY : {
- Value* val = new LoadInst(supplLocal, "", currentBlock);
- val = new PtrToIntInst(val, Type::getInt32Ty(getGlobalContext()), "", currentBlock);
- SwitchInst* inst = SwitchInst::Create(val, leaves[0],
- leaves.size(), currentBlock);
-
- uint32 index = 0;
- for (std::vector<BasicBlock*>::iterator i = leaves.begin(),
- e = leaves.end(); i!= e; ++i, ++index) {
- inst->addCase(ConstantInt::get(Type::getInt32Ty(getGlobalContext()), index), *i);
- }
-
- //currentBlock = bb2;
-
- break;
- }
-
- case JMP : {
- VMThread::get()->getVM()->error("implement me");
- break;
- }
-
- case LDARG_S : {
- push(new LoadInst(arguments[readU1(bytecodes, i)], "", currentBlock));
- break;
- }
-
- case LDARG_0 : {
- push(new LoadInst(arguments[0], "", currentBlock));
- break;
- }
-
- case LDARG_1 : {
- push(new LoadInst(arguments[1], "", currentBlock));
- break;
- }
-
- case LDARG_2 : {
- push(new LoadInst(arguments[2], "", currentBlock));
- break;
- }
-
- case LDARG_3 : {
- push(new LoadInst(arguments[3], "", currentBlock));
- break;
- }
-
- case LDARGA_S : {
- push(arguments[readU1(bytecodes, i)]);
- break;
- }
-
- case LDC_I4 : {
- push(ConstantInt::get(Type::getInt32Ty(getGlobalContext()), readS4(bytecodes, i)));
- break;
- }
-
- case LDC_I8 : {
- push(ConstantInt::get(Type::getInt64Ty(getGlobalContext()), readS8(bytecodes, i)));
- break;
- }
-
- case LDC_R4 : {
- push(ConstantFP::get(Type::getFloatTy(getGlobalContext()), readFloat(bytecodes, i)));
- break;
- }
-
- case LDC_R8 : {
- push(ConstantFP::get(Type::getDoubleTy(getGlobalContext()), readDouble(bytecodes, i)));
- break;
- }
-
- case LDC_I4_0 : {
- push(module->constantZero);
- break;
- }
-
- case LDC_I4_1 : {
- push(module->constantOne);
- break;
- }
-
- case LDC_I4_2 : {
- push(module->constantTwo);
- break;
- }
-
- case LDC_I4_3 : {
- push(module->constantThree);
- break;
- }
-
- case LDC_I4_4 : {
- push(module->constantFour);
- break;
- }
-
- case LDC_I4_5 : {
- push(module->constantFive);
- break;
- }
-
- case LDC_I4_6 : {
- push(module->constantSix);
- break;
- }
-
- case LDC_I4_7 : {
- push(module->constantSeven);
- break;
- }
-
- case LDC_I4_8 : {
- push(module->constantEight);
- break;
- }
-
- case LDC_I4_M1 : {
- push(module->constantMinusOne);
- break;
- }
-
- case LDC_I4_S : {
- push(ConstantInt::get(Type::getInt32Ty(getGlobalContext()), readS1(bytecodes, i)));
- break;
- }
-
- case LDIND_U1 :
- case LDIND_I1 : {
- Value* _val = pop();
- Value* val = new BitCastInst(_val, PointerType::getUnqual(Type::getInt8Ty(getGlobalContext())), "", currentBlock);
- push(new LoadInst(val, "", isVolatile, currentBlock));
- isVolatile = false;
- break;
- }
-
- case LDIND_U2 :
- case LDIND_I2 : {
- Value* _val = pop();
- Value* val = new BitCastInst(_val, PointerType::getUnqual(Type::getInt16Ty(getGlobalContext())), "", currentBlock);
- push(new LoadInst(val, "", isVolatile, currentBlock));
- isVolatile = false;
- break;
- }
-
- case LDIND_U4 :
- case LDIND_I4 : {
- Value* val = pop();
- if (val->getType()->isIntegerTy()) {
- val = new IntToPtrInst(val, PointerType::getUnqual(Type::getInt32Ty(getGlobalContext())), "", currentBlock);
- } else {
- val = new BitCastInst(val, PointerType::getUnqual(Type::getInt32Ty(getGlobalContext())), "", currentBlock);
- }
- push(new LoadInst(val, "", isVolatile, currentBlock));
- isVolatile = false;
- break;
- }
-
- case LDIND_I8 : {
- Value* _val = pop();
- Value* val = new BitCastInst(_val, PointerType::getUnqual(Type::getInt64Ty(getGlobalContext())), "", currentBlock);
- push(new LoadInst(val, "", isVolatile, currentBlock));
- isVolatile = false;
- break;
- }
-
- case LDIND_R4 : {
- Value* _val = pop();
- Value* val = new BitCastInst(_val, PointerType::getUnqual(Type::getFloatTy(getGlobalContext())), "", currentBlock);
- push(new LoadInst(val, "", isVolatile, currentBlock));
- isVolatile = false;
- break;
- }
-
- case LDIND_R8 : {
- Value* _val = pop();
- Value* val = new BitCastInst(_val, PointerType::getUnqual(Type::getDoubleTy(getGlobalContext())), "", currentBlock);
- push(new LoadInst(val, "", isVolatile, currentBlock));
- isVolatile = false;
- break;
- }
-
- case LDIND_I : {
- Value* _val = pop();
- Value* val = new BitCastInst(_val, PointerType::getUnqual(
- PointerType::getUnqual(Type::getInt8Ty(getGlobalContext()))), "", currentBlock);
- push(new LoadInst(val, "", isVolatile, currentBlock));
- isVolatile = false;
- break;
- }
-
- case LDIND_REF : {
- Value* _val = pop();
- Value* val = new BitCastInst(_val, PointerType::getUnqual(
- PointerType::getUnqual(VMObject::llvmType)), "", currentBlock);
- push(new LoadInst(val, "", isVolatile, currentBlock));
- isVolatile = false;
- break;
- }
-
- case LDLOC_S : {
- Value* val = load(locals[readU1(bytecodes, i)], "", currentBlock, module);
- push(val);
- break;
- }
-
- case LDLOC_0 : {
- Value* val = load(locals[0], "", currentBlock, module);
- push(val);
- break;
- }
-
- case LDLOC_1 : {
- Value* val = load(locals[1], "", currentBlock, module);
- push(val);
- break;
- }
-
- case LDLOC_2 : {
- Value* val = load(locals[2], "", currentBlock, module);
- push(val);
- break;
- }
-
- case LDLOC_3 : {
- Value* val = load(locals[3], "", currentBlock, module);
- push(val);
- break;
- }
-
- case LDLOCA_S : {
- push(locals[readU1(bytecodes, i)]);
- break;
- }
-
- case LDNULL : {
- push(CLIJit::constantVMObjectNull);
- break;
- }
-
- case LEAVE : {
- uint32 tmp = i;
- uint32 index = tmp + 5 + readS4(bytecodes, i);
- BasicBlock* bb = opcodeInfos[index].newBlock;
- assert(bb);
- stack.clear();
- if (finallyHandlers.size()) {
- ExceptionBlockDesc* res = 0;
- for (std::vector<ExceptionBlockDesc*>::iterator i = finallyHandlers.begin(),
- e = finallyHandlers.end(); i!= e; ++i) {
- ExceptionBlockDesc* ex = (*i);
- if (tmp >= ex->tryOffset && tmp < ex->tryOffset + ex->tryLength) {
- res = ex;
- break;
- }
- }
- if (res) {
- Value* expr = ConstantExpr::getIntToPtr(
- ConstantInt::get(Type::getInt64Ty(getGlobalContext()),
- uint64_t (leaveIndex++)),
- VMObject::llvmType);
-
- new StoreInst(expr, supplLocal, false, currentBlock);
- branch(res->handler, currentBlock);
- } else {
- branch(bb, currentBlock);
- }
- } else {
- branch(bb, currentBlock);
- }
- break;
- }
-
- case LEAVE_S : {
- uint32 tmp = i;
- BasicBlock* bb = opcodeInfos[tmp + 2 + readS1(bytecodes, i)].newBlock;
- assert(bb);
- stack.clear();
- if (finallyHandlers.size()) {
- ExceptionBlockDesc* res = 0;
- for (std::vector<ExceptionBlockDesc*>::iterator i = finallyHandlers.begin(),
- e = finallyHandlers.end(); i!= e; ++i) {
- ExceptionBlockDesc* ex = (*i);
- if (tmp >= ex->tryOffset && tmp < ex->tryOffset + ex->tryLength) {
- res = ex;
- break;
- }
- }
- if (res) {
- Value* expr = ConstantExpr::getIntToPtr(
- ConstantInt::get(Type::getInt64Ty(getGlobalContext()),
- uint64_t (leaveIndex++)),
- VMObject::llvmType);
-
- new StoreInst(expr, supplLocal, false, currentBlock);
- branch(res->handler, currentBlock);
- } else {
- branch(bb, currentBlock);
- }
- } else {
- branch(bb, currentBlock);
- }
- break;
- }
-
- case MUL : {
- Value* val2 = pop();
- Value* val1 = pop();
- convertValue(val1, val2->getType(), currentBlock);
- push(BinaryOperator::CreateMul(val1, val2, "", currentBlock));
- break;
- }
-
- case MUL_OVF : {
- VMThread::get()->getVM()->error("implement me");
- break;
- }
-
- case MUL_OVF_UN : {
- VMThread::get()->getVM()->error("implement me");
- break;
- }
-
- case NEG : {
- Value* val = pop();
- push(BinaryOperator::CreateSub(
- Constant::getNullValue(val->getType()),
- val, "", currentBlock));
- break;
- }
-
- case NOP : break;
-
- case NOT : {
- push(BinaryOperator::CreateNot(pop(), "", currentBlock));
- break;
- }
-
- case OR : {
- Value* two = pop();
- Value* one = pop();
- push(BinaryOperator::CreateOr(one, two, "", currentBlock));
- break;
- }
-
- case POP : {
- pop();
- break;
- }
-
- case REM : {
- Value* two = pop();
- Value* one = pop();
- if (one->getType()->isFloatTy()) {
- push(BinaryOperator::CreateFRem(one, two, "", currentBlock));
- } else {
- push(BinaryOperator::CreateSRem(one, two, "", currentBlock));
- }
- break;
- }
-
- case REM_UN : {
- Value* two = pop();
- Value* one = pop();
- if (one->getType()->isFloatTy()) {
- push(BinaryOperator::CreateFRem(one, two, "", currentBlock));
- } else {
- push(BinaryOperator::CreateURem(one, two, "", currentBlock));
- }
- break;
- }
-
- case RET : {
- if (compilingMethod->getSignature(genMethod)->getReturnType() != Type::getVoidTy(getGlobalContext())) {
- Value* val = pop();
- if (val->getType() == PointerType::getUnqual(endNode->getType())) {
- // In case it's a struct
- val = new LoadInst(val, "", currentBlock);
- } else {
- convertValue(val, endNode->getType(), currentBlock);
- }
- endNode->addIncoming(val, currentBlock);
- } else if (compilingMethod->structReturn) {
- endNode->addIncoming(pop(), currentBlock);
- }
- BranchInst::Create(endBlock, currentBlock);
- break;
- }
-
- case SHL : {
- Value* val2 = pop();
- Value* val1 = pop();
- verifyType(val1, val2, currentBlock);
- push(BinaryOperator::CreateShl(val1, val2, "", currentBlock));
- break;
- }
-
- case SHR : {
- Value* val2 = pop();
- Value* val1 = pop();
- verifyType(val1, val2, currentBlock);
- push(BinaryOperator::CreateAShr(val1, val2, "", currentBlock));
- break;
- }
-
- case SHR_UN : {
- Value* val2 = pop();
- Value* val1 = pop();
- verifyType(val1, val2, currentBlock);
- push(BinaryOperator::CreateLShr(val1, val2, "", currentBlock));
- break;
- }
-
- case STARG_S : {
- Value* val = pop();
- Value* arg = arguments[readU1(bytecodes, i)];
- convertValue(val, arg->getType()->getContainedType(0), currentBlock);
- new StoreInst(val, arg, false, currentBlock);
- break;
- }
-
- case STIND_I1 : {
- Value* val = pop();
- Value* _addr = pop();
- Value* addr = new BitCastInst(_addr, PointerType::getUnqual(Type::getInt8Ty(getGlobalContext())), "",
- currentBlock);
- convertValue(val, Type::getInt8Ty(getGlobalContext()), currentBlock);
- new StoreInst(val, addr, isVolatile, currentBlock);
- isVolatile = false;
- break;
- }
-
- case STIND_I2 : {
- Value* val = pop();
- Value* _addr = pop();
- Value* addr = new BitCastInst(_addr, PointerType::getUnqual(Type::getInt16Ty(getGlobalContext())),
- "", currentBlock);
- new StoreInst(val, addr, isVolatile, currentBlock);
- isVolatile = false;
- break;
- }
-
- case STIND_I4 : {
- Value* val = pop();
- Value* _addr = pop();
- Value* addr = new BitCastInst(_addr, PointerType::getUnqual(Type::getInt32Ty(getGlobalContext())),
- "", currentBlock);
- new StoreInst(val, addr, isVolatile, currentBlock);
- isVolatile = false;
- break;
- }
-
- case STIND_I8 : {
- Value* val = pop();
- Value* _addr = pop();
- Value* addr = new BitCastInst(_addr, PointerType::getUnqual(Type::getInt64Ty(getGlobalContext())),
- "", currentBlock);
- new StoreInst(val, addr, isVolatile, currentBlock);
- isVolatile = false;
- break;
- }
-
- case STIND_R4 : {
- Value* val = pop();
- Value* _addr = pop();
- Value* addr = new BitCastInst(_addr, PointerType::getUnqual(Type::getFloatTy(getGlobalContext())),
- "", currentBlock);
- new StoreInst(val, addr, isVolatile, currentBlock);
- isVolatile = false;
- break;
- }
-
- case STIND_R8 : {
- Value* val = pop();
- Value* _addr = pop();
- Value* addr = new BitCastInst(_addr, PointerType::getUnqual(Type::getDoubleTy(getGlobalContext())),
- "", currentBlock);
- new StoreInst(val, addr, isVolatile, currentBlock);
- isVolatile = false;
- break;
- }
-
- case STIND_I : {
- Value* val = pop();
- Value* _addr = pop();
- Value* addr = new BitCastInst(_addr, PointerType::getUnqual(Type::getInt32Ty(getGlobalContext())),
- "", currentBlock);
- new StoreInst(val, addr, isVolatile, currentBlock);
- isVolatile = false;
- break;
- }
-
- case STIND_REF : {
- Value* val = pop();
- Value* _addr = pop();
- Value* addr = new BitCastInst(_addr, PointerType::getUnqual(val->getType()),
- "", currentBlock);
- new StoreInst(val, addr, isVolatile, currentBlock);
- isVolatile = false;
- break;
- }
-
- case STLOC_S : {
- Value* val = pop();
- Value* local = locals[readU1(bytecodes, i)];
- store(val, local, false, currentBlock, module);
- break;
- }
-
- case STLOC_0 : {
- Value* val = pop();
- Value* local = locals[0];
- store(val, local, false, currentBlock, module);
- break;
- }
-
- case STLOC_1 : {
- Value* val = pop();
- Value* local = locals[1];
- store(val, local, false, currentBlock, module);
- break;
- }
-
- case STLOC_2 : {
- Value* val = pop();
- Value* local = locals[2];
- store(val, local, false, currentBlock, module);
- break;
- }
-
- case STLOC_3 : {
- Value* val = pop();
- Value* local = locals[3];
- store(val, local, false, currentBlock, module);
- break;
- }
-
- case SUB : {
- Value* val2 = pop();
- Value* val1 = pop();
- verifyType(val1, val2, currentBlock);
- push(BinaryOperator::CreateSub(val1, val2, "", currentBlock));
- break;
- }
-
- case SUB_OVF : {
- VMThread::get()->getVM()->error("implement me");
- break;
- }
-
- case SUB_OVF_UN : {
- VMThread::get()->getVM()->error("implement me");
- break;
- }
-
- case SWITCH : {
- uint32 value = readU4(bytecodes, i);
- Value* val = pop();
- uint32 next = i + value * sizeof(sint32) + 1;
- BasicBlock* defBB = opcodeInfos[next].newBlock;
- SwitchInst* SI = SwitchInst::Create(val, defBB, value, currentBlock);
- for (uint32 t = 0; t < value; t++) {
- sint32 offset = readS4(bytecodes, i);
- sint32 index = next + offset;
- assert(index > 0);
- BasicBlock* BB = opcodeInfos[index].newBlock;
- SI->addCase(ConstantInt::get(Type::getInt32Ty(getGlobalContext()), t), BB);
- }
- break;
- }
-
- case XOR : {
- Value* two = pop();
- Value* one = pop();
- convertValue(two, one->getType(), currentBlock);
- push(BinaryOperator::CreateXor(one, two, "", currentBlock));
- break;
- }
-
- case BOX : {
- uint32 token = readU4(bytecodes, i);
- Assembly* assembly = compilingClass->assembly;
- N3* vm = (N3*)(VMThread::get()->getVM());
- VMCommonClass* type = assembly->loadType(vm, token, true, false, false,
- true, genClass, genMethod);
- assert(type);
-
- if (!type->isPrimitive) {
- // the box instruction has no effect on non-primitive types
- break;
- }
-
- Value* var = new LoadInst(type->llvmVar(), "", currentBlock);
- Value* obj = CallInst::Create(objConsLLVM, var, "", currentBlock);
- Value* val = pop();
- obj = new BitCastInst(obj, type->virtualType, "", currentBlock);
-
-
- std::vector<Value*> ptrs;
- ptrs.push_back(module->constantZero);
- ptrs.push_back(module->constantOne);
- Value* ptr = GetElementPtrInst::Create(obj, ptrs.begin(), ptrs.end(), "",
- currentBlock);
-
- if (val->getType()->getTypeID() != Type::PointerTyID) {
- convertValue(val, type->naturalType, currentBlock);
- Value* tmp = new AllocaInst(type->naturalType, "", currentBlock);
- new StoreInst(val, tmp, false, currentBlock);
- val = tmp;
- }
-
-
- uint64 size = mvm::MvmModule::getTypeSize(type->naturalType);
-
- std::vector<Value*> params;
- params.push_back(new BitCastInst(ptr, PointerType::getUnqual(Type::getInt8Ty(getGlobalContext())), "", currentBlock));
- params.push_back(new BitCastInst(val, PointerType::getUnqual(Type::getInt8Ty(getGlobalContext())), "", currentBlock));
- params.push_back(ConstantInt::get(Type::getInt32Ty(getGlobalContext()), size));
- params.push_back(module->constantZero);
- CallInst::Create(module->llvm_memcpy_i32, params.begin(), params.end(), "", currentBlock);
-
-
- push(obj);
- break;
- }
-
- case CALLVIRT : {
- uint32 value = readU4(bytecodes, i);
- invokeInterfaceOrVirtual(value, genClass, genMethod);
- break;
- }
-
- case CASTCLASS : {
- Assembly* assembly = compilingClass->assembly;
- N3* vm = (N3*)(VMThread::get()->getVM());
- uint32 token = readU4(bytecodes, i);
- VMCommonClass* dcl = assembly->loadType(vm, token, true, false,
- false, true, genClass, genMethod);
- Value* obj = new BitCastInst(pop(), VMObject::llvmType, "", currentBlock);
-
- Value* cmp = new ICmpInst(*currentBlock, ICmpInst::ICMP_EQ, obj,
- CLIJit::constantVMObjectNull, "");
-
- BasicBlock* ifTrue = createBasicBlock("null checkcast");
- BasicBlock* ifFalse = createBasicBlock("non null checkcast");
-
- branch(cmp, ifTrue, ifFalse, currentBlock);
-
- Value* clVar = new LoadInst(dcl->llvmVar(), "", ifFalse);
- std::vector<Value*> args;
- args.push_back(obj);
- args.push_back(clVar);
- Value* call = CallInst::Create(instanceOfLLVM, args.begin(), args.end(),
- "", ifFalse);
-
- cmp = new ICmpInst(*ifFalse, ICmpInst::ICMP_EQ, call,
- module->constantZero, "");
-
- BasicBlock* ex = createBasicBlock("false checkcast");
- branch(cmp, ex, ifTrue, ifFalse);
-
- std::vector<Value*> exArgs;
- if (currentExceptionBlock != endExceptionBlock) {
- InvokeInst::Create(classCastExceptionLLVM, unifiedUnreachable, currentExceptionBlock, exArgs.begin(), exArgs.end(), "", ex);
- } else {
- CallInst::Create(classCastExceptionLLVM, exArgs.begin(), exArgs.end(), "", ex);
- new UnreachableInst(getGlobalContext(), ex);
- }
-
- currentBlock = ifTrue;
- push(new BitCastInst(obj, dcl->virtualType, "", currentBlock));
- break;
- }
-
-
- case CPOBJ : {
- VMThread::get()->getVM()->error("implement me");
- break;
- }
-
- case ISINST : {
- Assembly* assembly = compilingClass->assembly;
- N3* vm = (N3*)(VMThread::get()->getVM());
- uint32 token = readU4(bytecodes, i);
- VMCommonClass* dcl = assembly->loadType(vm, token, true, false,
- false, true, genClass, genMethod);
- Value* obj = pop();
-
- Value* cmp = new ICmpInst(*currentBlock, ICmpInst::ICMP_EQ, obj,
- Constant::getNullValue(obj->getType()), "");
- Constant* nullVirtual = Constant::getNullValue(dcl->virtualType);
-
-
- BasicBlock* isInstEndBlock = createBasicBlock("end isinst");
- PHINode* node = PHINode::Create(dcl->virtualType, "", isInstEndBlock);
-
- BasicBlock* ifFalse = createBasicBlock("non null isinst");
- BasicBlock* ifTrue = createBasicBlock("null isinst");
-
- BranchInst::Create(ifTrue, ifFalse, cmp, currentBlock);
- node->addIncoming(nullVirtual, ifTrue);
- BranchInst::Create(isInstEndBlock, ifTrue);
-
-
- Value* clVar = new LoadInst(dcl->llvmVar(), "", ifFalse);
- std::vector<Value*> args;
- args.push_back(new BitCastInst(obj, VMObject::llvmType, "", ifFalse));
- args.push_back(clVar);
- Value* call = CallInst::Create(instanceOfLLVM, args.begin(), args.end(),
- "", ifFalse);
-
- cmp = new ICmpInst(*ifFalse, ICmpInst::ICMP_EQ, call,
- module->constantZero, "");
-
- BasicBlock* falseInst = createBasicBlock("false isinst");
- BasicBlock* trueInst = createBasicBlock("true isinst");
- BranchInst::Create(falseInst, trueInst, cmp, ifFalse);
-
- node->addIncoming(new BitCastInst(obj, dcl->virtualType, "", trueInst), trueInst);
- BranchInst::Create(isInstEndBlock, trueInst);
-
- node->addIncoming(nullVirtual, falseInst);
- BranchInst::Create(isInstEndBlock, falseInst);
-
- currentBlock = isInstEndBlock;
- push(node);
- break;
- }
-
- case LDELEM : {
- VMThread::get()->getVM()->error("implement me");
- break;
- }
-
- case LDELEM_I1 : {
- VMThread::get()->getVM()->error("implement me");
- break;
- }
-
- case LDELEM_I2 : {
- Value* index = pop();
- Value* obj = pop();
- Value* ptr = verifyAndComputePtr(obj, index, ArraySInt16::llvmType);
- push(new LoadInst(ptr, "", currentBlock));
- break;
- }
-
- case LDELEM_I4 : {
- Value* index = pop();
- Value* obj = pop();
- Value* ptr = verifyAndComputePtr(obj, index, ArraySInt32::llvmType);
- push(new LoadInst(ptr, "", currentBlock));
- break;
- }
-
- case LDELEM_I8 : {
- Value* index = pop();
- Value* obj = pop();
- Value* ptr = verifyAndComputePtr(obj, index, ArrayUInt64::llvmType);
- push(new LoadInst(ptr, "", currentBlock));
- break;
- }
-
- case LDELEM_U1 : {
- Value* index = pop();
- Value* obj = pop();
- Value* ptr = verifyAndComputePtr(obj, index, ArrayUInt8::llvmType);
- push(new LoadInst(ptr, "", currentBlock));
- break;
- }
-
- case LDELEM_U2 : {
- Value* index = pop();
- Value* obj = pop();
- Value* ptr = verifyAndComputePtr(obj, index, ArrayUInt16::llvmType);
- push(new LoadInst(ptr, "", currentBlock));
- break;
- }
-
- case LDELEM_U4 : {
- Value* index = pop();
- Value* obj = pop();
- Value* ptr = verifyAndComputePtr(obj, index, ArrayUInt32::llvmType);
- push(new LoadInst(ptr, "", currentBlock));
- break;
- }
-
- case LDELEM_R4 : {
- Value* index = pop();
- Value* obj = pop();
- Value* ptr = verifyAndComputePtr(obj, index, ArrayFloat::llvmType);
- push(new LoadInst(ptr, "", currentBlock));
- break;
- }
-
- case LDELEM_R8 : {
- Value* index = pop();
- Value* obj = pop();
- Value* ptr = verifyAndComputePtr(obj, index, ArrayDouble::llvmType);
- push(new LoadInst(ptr, "", currentBlock));
- break;
- }
-
- case LDELEM_I : {
- Value* index = pop();
- Value* obj = pop();
- Value* ptr = verifyAndComputePtr(obj, index, ArraySInt32::llvmType);
- push(new LoadInst(ptr, "", currentBlock));
- break;
- }
-
- case LDELEM_REF : {
- Value* index = pop();
- Value* obj = pop();
- Value* ptr = verifyAndComputePtr(obj, index, ArrayObject::llvmType);
- push(new LoadInst(ptr, "", currentBlock));
- break;
- }
-
- case LDELEMA : {
- Assembly* assembly = compilingClass->assembly;
- N3* vm = (N3*)(VMThread::get()->getVM());
- uint32 token = readU4(bytecodes, i);
- VMCommonClass* cl = assembly->loadType(vm, token, true, false,
- false, true, genClass, genMethod);
- VMClassArray* array = assembly->constructArray(cl, 1);
- array->resolveType(false, false, genMethod);
- Value* index = pop();
- Value* obj = pop();
- Value* ptr = verifyAndComputePtr(obj, index, array->naturalType);
- push(ptr);
- break;
- }
-
- case LDFLD : {
- uint32 value = readU4(bytecodes, i);
- Value* val = getVirtualField(value, genClass, genMethod);
- push(new LoadInst(val, "", isVolatile, currentBlock));
- isVolatile = false;
- break;
- }
-
- case LDFLDA : {
- uint32 value = readU4(bytecodes, i);
- push(getVirtualField(value, genClass, genMethod));
- break;
- }
-
- case LDLEN : {
- push(arraySize(pop()));
- break;
- }
-
- case LDOBJ : {
- Assembly* assembly = compilingClass->assembly;
- N3* vm = (N3*)(VMThread::get()->getVM());
- uint32 token = readU4(bytecodes, i);
- VMCommonClass* cl = assembly->loadType(vm, token, true, false,
- false, true, genClass, genMethod);
- if (!(cl->super == MSCorlib::pValue || cl->super == MSCorlib::pEnum)) {
- push(new LoadInst(pop(), "", isVolatile, currentBlock));
- isVolatile = false;
- }
- break;
- }
-
- case LDSFLD : {
- uint32 value = readU4(bytecodes, i);
- Value* val = getStaticField(value, genClass, genMethod);
- push(new LoadInst(val, "", isVolatile, currentBlock));
- isVolatile = false;
- break;
- }
-
- case LDSFLDA : {
- uint32 value = readU4(bytecodes, i);
- push(getStaticField(value, genClass, genMethod));
- break;
- }
-
- case LDSTR : {
- uint32 value = readU4(bytecodes, i);
- uint32 index = value & 0xfffffff;
- // must modify this opcode
- declare_gcroot(const ArrayChar*, array) = compilingClass->assembly->readUserString(index);
- Value* val = ConstantExpr::getIntToPtr(ConstantInt::get(Type::getInt64Ty(getGlobalContext()), (int64_t)array),
- module->ptrType);
- Value* res = CallInst::Create(newStringLLVM, val, "", currentBlock);
- /*CLIString * str =
- (CLIString*)(((N3*)VMThread::get()->getVM())->UTF8ToStr(utf8));
- GlobalVariable* gv = str->llvmVar();
- push(new BitCastInst(new LoadInst(gv, "", currentBlock),
- MSCorlib::pString->naturalType, "", currentBlock));*/
- push(new BitCastInst(res, MSCorlib::pString->naturalType, "", currentBlock));
- break;
- }
-
- case LDTOKEN : {
- uint32 token = readU4(bytecodes, i);
- uint32 table = token >> 24;
- Assembly* assembly = compilingClass->assembly;
- N3* vm = (N3*)(VMThread::get()->getVM());
- switch (table) {
- case CONSTANT_Field : {
- uint32 typeToken = assembly->getTypedefTokenFromField(token);
- assembly->loadType(vm, typeToken, true, true, false, true, genClass, genMethod);
- VMField* field = assembly->lookupFieldFromToken(token);
- if (!field) {
- VMThread::get()->getVM()->error("implement me");
- }
- Value* arg = new LoadInst(field->llvmVar(), "", currentBlock);
- push(arg);
- break;
- }
-
- case CONSTANT_MethodDef : {
- uint32 typeToken = assembly->getTypedefTokenFromMethod(token);
- assembly->loadType(vm, typeToken, true, true, false, true, genClass, genMethod);
- VMMethod* meth = assembly->lookupMethodFromToken(token);
- if (!meth) {
- VMThread::get()->getVM()->error("implement me");
- }
- Value* arg = new LoadInst(meth->llvmVar(), "", currentBlock);
- push(arg);
- break;
- }
-
- case CONSTANT_TypeDef :
- case CONSTANT_TypeRef : {
- VMCommonClass* cl = assembly->loadType(vm, token, true, false,
- false, true, genClass, genMethod);
- Value* arg = new LoadInst(cl->llvmVar(), "", currentBlock);
- push(arg);
- break;
- }
-
- default :
- VMThread::get()->getVM()->error("implement me");
- }
- break;
- }
-
- case MKREFANY : {
- VMThread::get()->getVM()->error("implement me");
- break;
- }
-
- case NEWARR : {
- uint32 value = readU4(bytecodes, i);
- Assembly* ass = compilingClass->assembly;
- VMCommonClass* baseType = ass->loadType((N3*)(VMThread::get()->getVM()),
- value, true, false, false,
- true, genClass, genMethod);
-
- VMClassArray* type = ass->constructArray(baseType, 1);
- type->resolveType(false, false, genMethod);
- Value* var = new LoadInst(type->llvmVar(), "", currentBlock);
- std::vector<Value*> args;
- args.push_back(var);
- args.push_back(pop());
- Value* val = CallInst::Create(arrayConsLLVM, args.begin(), args.end(), "",
- currentBlock);
- push(new BitCastInst(val, type->naturalType, "", currentBlock));
- break;
- }
-
- case NEWOBJ : {
- uint32 value = readU4(bytecodes, i);
- invokeNew(value, genClass, genMethod);
- break;
- }
-
- case REFANYVAL : {
- VMThread::get()->getVM()->error("implement me");
- break;
- }
-
- case STELEM : {
- VMThread::get()->getVM()->error("implement me");
- break;
- }
-
- case STELEM_I1 : {
- Value* val = pop();
- Value* index = pop();
- Value* obj = pop();
- Value* ptr = verifyAndComputePtr(obj, index, ArraySInt8::llvmType);
- convertValue(val, Type::getInt8Ty(getGlobalContext()), currentBlock);
- new StoreInst(val, ptr, false, currentBlock);
- break;
- }
-
- case STELEM_I2 : {
- Value* val = pop();
- Value* index = pop();
- Value* obj = pop();
- Value* ptr = verifyAndComputePtr(obj, index, ArraySInt16::llvmType);
- convertValue(val, Type::getInt16Ty(getGlobalContext()), currentBlock);
- new StoreInst(val, ptr, false, currentBlock);
- break;
- }
-
- case STELEM_I4 : {
- Value* val = pop();
- Value* index = pop();
- Value* obj = pop();
- Value* ptr = verifyAndComputePtr(obj, index, ArraySInt32::llvmType);
- convertValue(val, Type::getInt32Ty(getGlobalContext()), currentBlock);
- new StoreInst(val, ptr, false, currentBlock);
- break;
- }
-
- case STELEM_I8 : {
- Value* val = pop();
- Value* index = pop();
- Value* obj = pop();
- Value* ptr = verifyAndComputePtr(obj, index, ArrayUInt64::llvmType);
- convertValue(val, Type::getInt64Ty(getGlobalContext()), currentBlock);
- new StoreInst(val, ptr, false, currentBlock);
- break;
- }
-
- case STELEM_R4 : {
- Value* val = pop();
- Value* index = pop();
- Value* obj = pop();
- Value* ptr = verifyAndComputePtr(obj, index, ArrayFloat::llvmType);
- convertValue(val, Type::getFloatTy(getGlobalContext()), currentBlock);
- new StoreInst(val, ptr, false, currentBlock);
- break;
- }
-
- case STELEM_R8 : {
- Value* val = pop();
- Value* index = pop();
- Value* obj = pop();
- Value* ptr = verifyAndComputePtr(obj, index, ArrayDouble::llvmType);
- convertValue(val, Type::getDoubleTy(getGlobalContext()), currentBlock);
- new StoreInst(val, ptr, false, currentBlock);
- break;
- }
-
- case STELEM_I : {
- VMThread::get()->getVM()->error("implement me");
- break;
- }
-
- case STELEM_REF : {
- Value* val = new BitCastInst(pop(), VMObject::llvmType, "",
- currentBlock);
- Value* index = pop();
- Value* obj = pop();
- Value* ptr = verifyAndComputePtr(obj, index, ArrayObject::llvmType);
- new StoreInst(val, ptr, false, currentBlock);
- break;
- }
-
- case STFLD : {
- uint32 index = readU4(bytecodes, i);
- setVirtualField(index, isVolatile, genClass, genMethod);
- isVolatile = false;
- break;
- }
-
- case STOBJ : {
- VMThread::get()->getVM()->error("implement me");
- isVolatile = false;
- break;
- }
-
- case STSFLD : {
- uint32 index = readU4(bytecodes, i);
- setStaticField(index, isVolatile, genClass, genMethod);
- isVolatile = false;
- break;
- }
-
- case THROW : {
- llvm::Value* arg = pop();
- arg = new BitCastInst(arg, VMObject::llvmType, "", currentBlock);
- std::vector<Value*> args;
- args.push_back(arg);
- if (currentExceptionBlock != endExceptionBlock) {
- InvokeInst::Create(throwExceptionLLVM, unifiedUnreachable, currentExceptionBlock, args.begin(), args.end(), "", currentBlock);
- } else {
- CallInst::Create(throwExceptionLLVM, args.begin(), args.end(), "", currentBlock);
- new UnreachableInst(getGlobalContext(), currentBlock);
- }
- break;
- }
-
- case UNBOX : {
- uint32 token = readU4(bytecodes, i);
- Assembly* assembly = compilingClass->assembly;
- N3* vm = (N3*)(VMThread::get()->getVM());
- VMCommonClass* type = assembly->loadType(vm, token, true, false, false,
- true, genClass, genMethod);
- assert(type);
-
- Value* val = new AllocaInst(type->naturalType, "", currentBlock);
- Value* obj = pop();
-
- if (obj->getType() != type->virtualType) {
- obj = new BitCastInst(obj, type->virtualType, "", currentBlock);
- }
-
- std::vector<Value*> ptrs;
- ptrs.push_back(module->constantZero);
- ptrs.push_back(module->constantOne);
- Value* ptr = GetElementPtrInst::Create(obj, ptrs.begin(), ptrs.end(), "",
- currentBlock);
-
- uint64 size = mvm::MvmModule::getTypeSize(type->naturalType);
-
- std::vector<Value*> params;
- params.push_back(new BitCastInst(val, PointerType::getUnqual(Type::getInt8Ty(getGlobalContext())), "", currentBlock));
- params.push_back(new BitCastInst(ptr, PointerType::getUnqual(Type::getInt8Ty(getGlobalContext())), "", currentBlock));
- params.push_back(ConstantInt::get(Type::getInt32Ty(getGlobalContext()), size));
- params.push_back(module->constantZero);
- CallInst::Create(module->llvm_memcpy_i32, params.begin(), params.end(), "", currentBlock);
-
-
- push(val);
- break;
- }
-
- case UNBOX_ANY : {
- VMThread::get()->getVM()->error("implement me");
- break;
- }
-
- case 0xFE : {
- PRINT_DEBUG(N3_COMPILE, 1, COLOR_NORMAL, "\t[at %5x] %-5d ", i,
- bytecodes[i + 1]);
- PRINT_DEBUG(N3_COMPILE, 1, LIGHT_BLUE, "compiling %s::", mvm::PrintBuffer(compilingMethod).cString());
- PRINT_DEBUG(N3_COMPILE, 1, LIGHT_CYAN, OpcodeNamesFE[bytecodes[i + 1]]);
- PRINT_DEBUG(N3_COMPILE, 1, LIGHT_BLUE, "\n");
-
- switch (bytecodes[++i]) {
-
-#define TEST(name, cmpf, cmpi) case name : { \
- Value* val2 = pop(); \
- Value* val1 = pop(); \
- Value* test = 0; \
- if (val1->getType()->isFloatTy()) { \
- test = new FCmpInst(*currentBlock, FCmpInst::cmpf, val1, val2, ""); \
- } else { \
- convertValue(val2, val1->getType(), currentBlock); \
- test = new ICmpInst(*currentBlock, ICmpInst::cmpi, val1, val2, ""); \
- } \
- push(test); \
- break; \
- }
-
- TEST(CEQ, FCMP_OEQ, ICMP_EQ);
- TEST(CGT, FCMP_OGT, ICMP_SGT);
- TEST(CGT_UN, FCMP_UGT, ICMP_UGT);
- TEST(CLT, FCMP_OLT, ICMP_SLT);
- TEST(CLT_UN, FCMP_ULT, ICMP_ULT);
-
-#undef TEST
-
- case CPBLK : {
- Value* three = pop();
- Value* two = pop();
- Value* one = pop();
- std::vector<Value*> args;
- args.push_back(one);
- args.push_back(two);
- args.push_back(three);
- CallInst::Create(module->llvm_memcpy_i32,
- args.begin(), args.end(), "", currentBlock);
- isVolatile = false;
- break;
- }
-
- case ENDFILTER: {
- VMThread::get()->getVM()->error("implement me");
- break;
- }
-
- case LDARG : {
- push(new LoadInst(arguments[readU2(bytecodes, i)], "", currentBlock));
- break;
- }
-
- case LDARGA : {
- push(arguments[readU2(bytecodes, i)]);
- break;
- }
-
- case LDFTN : {
- Assembly* assembly = compilingClass->assembly;
- N3* vm = (N3*)(VMThread::get()->getVM());
- uint32 token = readU4(bytecodes, i);
- uint32 table = token >> 24;
- if (table == CONSTANT_MethodDef) {
- uint32 typeToken = assembly->getTypedefTokenFromMethod(token);
- assembly->loadType(vm, typeToken, true, false, false, true, genClass, genMethod);
- VMMethod* meth = assembly->lookupMethodFromToken(token);
- if (!meth) VMThread::get()->getVM()->error("implement me");
- Value* arg = new LoadInst(meth->llvmVar(), "", currentBlock);
- push(arg);
- } else {
- VMThread::get()->getVM()->error("implement me");
- }
- break;
- }
-
- case INITBLK : {
- Value* three = pop();
- Value* two = pop();
- Value* one = pop();
- std::vector<Value*> args;
- args.push_back(one);
- args.push_back(two);
- args.push_back(three);
- CallInst::Create(module->llvm_memset_i32,
- args.begin(), args.end(), "", currentBlock);
- isVolatile = false;
- break;
- }
-
- case LDLOC : {
- push(new LoadInst(locals[readU2(bytecodes, i)], "", currentBlock));
- break;
- }
-
- case LOCALLOC : {
- push(new AllocaInst(Type::getInt8Ty(getGlobalContext()), pop(), "", currentBlock));
- break;
- }
-
- case STARG : {
- new StoreInst(pop(), arguments[readU2(bytecodes, i)], false, currentBlock);
- break;
- }
-
- case STLOC : {
- Value* val = pop();
- Value* local = locals[readU2(bytecodes, i)];
- store(val, local, false, currentBlock, module);
- break;
- }
-
- case LDLOCA : {
- push(locals[readU2(bytecodes, i)]);
- break;
- }
-
- case ARGLIST : {
- VMThread::get()->getVM()->error("implement me");
- break;
- }
-
- case INITOBJ : {
- uint32 token = readU4(bytecodes, i);
- Assembly* assembly = compilingClass->assembly;
- N3* vm = (N3*)(VMThread::get()->getVM());
- VMCommonClass* type = assembly->loadType(vm, token, true, false, false,
- true, genClass, genMethod);
- if (type->super == MSCorlib::pValue) {
- uint64 size = mvm::MvmModule::getTypeSize(type->naturalType);
-
- std::vector<Value*> params;
- params.push_back(new BitCastInst(pop(), module->ptrType, "",
- currentBlock));
- params.push_back(module->constantInt8Zero);
- params.push_back(ConstantInt::get(Type::getInt32Ty(getGlobalContext()), size));
- params.push_back(module->constantZero);
- CallInst::Create(module->llvm_memset_i32, params.begin(),
- params.end(), "", currentBlock);
- }
-
- break;
- }
-
- case LDVIRTFTN : {
- VMThread::get()->getVM()->error("implement me");
- break;
- }
-
- case REFANYTYPE : {
- VMThread::get()->getVM()->error("implement me");
- break;
- }
-
- case RETHROW : {
- std::vector<Value*> args;
- if (opinfo->exception) {
- args.push_back(opinfo->exception);
- } else {
- args.push_back(CLIJit::constantVMObjectNull);
- }
- if (currentExceptionBlock != endExceptionBlock) {
- InvokeInst::Create(throwExceptionLLVM, unifiedUnreachable, currentExceptionBlock, args.begin(), args.end(), "", currentBlock);
- } else {
- CallInst::Create(throwExceptionLLVM, args.begin(), args.end(), "", currentBlock);
- new UnreachableInst(getGlobalContext(), currentBlock);
- }
- break;
- }
-
- case SIZEOF : {
- VMThread::get()->getVM()->error("implement me");
- break;
- }
-
- case VOLATILE_ : {
- isVolatile = true;
- break;
- }
- default :
- VMThread::get()->getVM()->unknownError("unknown bytecode");
- }
- break;
- }
-
- default :
- VMThread::get()->getVM()->unknownError("unknown bytecode");
- }
- }
-}
-
-void CLIJit::exploreOpcodes(uint8* bytecodes, uint32 codeLength) {
- for(uint32 i = 0; i < codeLength; ++i) {
-
- if (bytecodes[i] != 0xFE) {
- PRINT_DEBUG(N3_COMPILE, 1, COLOR_NORMAL, "\t[at %5x] %-5d ", i,
- bytecodes[i]);
- PRINT_DEBUG(N3_COMPILE, 1, LIGHT_BLUE, "exploring %s::", mvm::PrintBuffer(compilingMethod).cString());
- PRINT_DEBUG(N3_COMPILE, 1, LIGHT_CYAN, OpcodeNames[bytecodes[i]]);
- PRINT_DEBUG(N3_COMPILE, 1, LIGHT_BLUE, "\n");
- }
-
- switch (bytecodes[i]) {
-
- case ADD:
- case ADD_OVF:
- case ADD_OVF_UN:
- case AND: break;
-
-#define TEST(name, read, offset) case name : { \
- uint32 tmp = i; \
- uint16 index = tmp + offset + read(bytecodes, i); \
- if (!(opcodeInfos[index].newBlock)) \
- opcodeInfos[index].newBlock = createBasicBlock("Branches"); \
- break; \
- }
-
- TEST(BEQ, readS4, 5);
- TEST(BEQ_S, readS1, 2);
-
- TEST(BGE, readS4, 5);
- TEST(BGE_S, readS1, 2);
- TEST(BGE_UN, readS4, 5);
- TEST(BGE_UN_S, readS1, 2);
-
- TEST(BGT, readS4, 5);
- TEST(BGT_S, readS1, 2);
- TEST(BGT_UN, readS4, 5);
- TEST(BGT_UN_S, readS1, 2);
-
- TEST(BLE, readS4, 5);
- TEST(BLE_S, readS1, 2);
- TEST(BLE_UN, readS4, 5);
- TEST(BLE_UN_S, readS1, 2);
-
- TEST(BLT, readS4, 5);
- TEST(BLT_S, readS1, 2);
- TEST(BLT_UN, readS4, 5);
- TEST(BLT_UN_S, readS1, 2);
-
- TEST(BNE_UN, readS4, 5);
- TEST(BNE_UN_S, readS1, 2);
-
- case BR : {
- uint32 tmp = i;
- uint16 index = tmp + 5 + readS4(bytecodes, i);
- if (!(opcodeInfos[index].newBlock))
- opcodeInfos[index].newBlock = createBasicBlock("BR");
- break;
- }
-
- case BR_S : {
- uint32 tmp = i;
- uint16 index = tmp + 2 + readS1(bytecodes, i);
- if (!(opcodeInfos[index].newBlock))
- opcodeInfos[index].newBlock = createBasicBlock("BR");
- break;
- }
-
- case BREAK: break;
-
- TEST(BRFALSE, readS4, 5);
- TEST(BRFALSE_S, readS1, 2);
- TEST(BRTRUE, readS4, 5);
- TEST(BRTRUE_S, readS1, 2);
-
-#undef TEST
-
- case CALL: {
- i+= 4;
- break;
- }
-
- case CALLI: {
- VMThread::get()->getVM()->unknownError("implement me");
- break;
- }
-
- case CKFINITE : {
- VMThread::get()->getVM()->unknownError("implement me");
- break;
- }
-
- case CONV_I1 :
- case CONV_I2 :
- case CONV_I4 :
- case CONV_I8 :
- case CONV_R4 :
- case CONV_R8 :
- case CONV_U1 :
- case CONV_U2 :
- case CONV_U4 :
- case CONV_U8 :
- case CONV_I :
- case CONV_U :
- case CONV_R_UN :
- case CONV_OVF_I1 :
- case CONV_OVF_I2 :
- case CONV_OVF_I4 :
- case CONV_OVF_I8 :
- case CONV_OVF_U1 :
- case CONV_OVF_U2 :
- case CONV_OVF_U4 :
- case CONV_OVF_U8 :
- case CONV_OVF_I :
- case CONV_OVF_U :
- case CONV_OVF_I1_UN :
- case CONV_OVF_I2_UN :
- case CONV_OVF_I4_UN :
- case CONV_OVF_I8_UN :
- case CONV_OVF_U1_UN :
- case CONV_OVF_U2_UN :
- case CONV_OVF_U4_UN :
- case CONV_OVF_U8_UN :
- case DIV:
- case DIV_UN:
- case DUP:
- case ENDFINALLY : break;
-
- case JMP : {
- VMThread::get()->getVM()->error("implement me");
- break;
- }
-
- case LDARG_S : {
- i+= 1;
- break;
- }
-
- case LDARG_0 :
- case LDARG_1 :
- case LDARG_2 :
- case LDARG_3 : break;
-
- case LDARGA_S : {
- i += 1;
- break;
- }
-
- case LDC_I4 : {
- i += 4;
- break;
- }
-
- case LDC_I8 : {
- i += 8;
- break;
- }
-
- case LDC_R4 : {
- i += 4;
- break;
- }
-
- case LDC_R8 : {
- i += 8;
- break;
- }
-
- case LDC_I4_0 :
- case LDC_I4_1 :
- case LDC_I4_2 :
- case LDC_I4_3 :
- case LDC_I4_4 :
- case LDC_I4_5 :
- case LDC_I4_6 :
- case LDC_I4_7 :
- case LDC_I4_8 :
- case LDC_I4_M1 : break;
-
- case LDC_I4_S : {
- i += 1;
- break;
- }
-
- case LDIND_U1 :
- case LDIND_I1 :
- case LDIND_U2 :
- case LDIND_I2 :
- case LDIND_U4 :
- case LDIND_I4 :
- case LDIND_I8 :
- case LDIND_R4 :
- case LDIND_R8 :
- case LDIND_I : break;
-
- case LDIND_REF : {
- break;
- }
-
- case LDLOC_S : {
- i += 1;
- break;
- }
-
- case LDLOC_0 :
- case LDLOC_1 :
- case LDLOC_2 :
- case LDLOC_3 : break;
-
- case LDLOCA_S : {
- i += 1;
- break;
- }
-
- case LDNULL : break;
-
- case LEAVE : {
- uint32 tmp = i;
- uint32 value = readS4(bytecodes, i);
- uint32 index = tmp + 5 + value;
- if (!(opcodeInfos[index].newBlock))
- opcodeInfos[index].newBlock = createBasicBlock("LEAVE");
- leaves.push_back(opcodeInfos[index].newBlock);
- break;
- }
-
- case LEAVE_S : {
- uint32 tmp = i;
- uint8 value = readS1(bytecodes, i);
- uint32 index = tmp + 2 + value;
- if (!(opcodeInfos[index].newBlock))
- opcodeInfos[index].newBlock = createBasicBlock("LEAVE_S");
- leaves.push_back(opcodeInfos[index].newBlock);
- break;
- }
-
- case MUL :
- case MUL_OVF :
- case MUL_OVF_UN :
- case NEG :
- case NOP :
- case NOT :
- case OR :
- case POP :
- case REM :
- case REM_UN :
- case RET :
- case SHL :
- case SHR :
- case SHR_UN : break;
-
- case STARG_S : {
- i += 1;
- break;
- }
-
- case STIND_I1 :
- case STIND_I2 :
- case STIND_I4 :
- case STIND_I8 :
- case STIND_R4 :
- case STIND_R8 :
- case STIND_I :
- case STIND_REF : break;
-
- case STLOC_S : {
- i += 1;
- break;
- }
-
- case STLOC_0 :
- case STLOC_1 :
- case STLOC_2 :
- case STLOC_3 :
- case SUB :
- case SUB_OVF :
- case SUB_OVF_UN : break;
-
- case SWITCH : {
- uint32 value = readU4(bytecodes, i);
- uint32 next = i + value * sizeof(sint32) + 1;
- for (uint32 t = 0; t < value; t++) {
- sint32 offset = readS4(bytecodes, i);
- sint32 index = next + offset;
- assert(index > 0);
- if (!(opcodeInfos[index].newBlock)) {
- BasicBlock* block = createBasicBlock("switch");
- opcodeInfos[index].newBlock = block;
- }
- }
- if (!(opcodeInfos[i + 1].newBlock)) {
- BasicBlock* block = createBasicBlock("switch");
- opcodeInfos[i + 1].newBlock = block;
- }
- break;
- }
-
- case XOR : break;
-
- case BOX : {
- i += 4;
- break;
- }
-
- case CALLVIRT : {
- i += 4;
- break;
- }
-
- case CASTCLASS : {
- i += 4;
- break;
- }
-
- case CPOBJ : {
- VMThread::get()->getVM()->error("implement me");
- break;
- }
-
- case ISINST : {
- i += 4;
- break;
- }
-
- case LDELEM : {
- VMThread::get()->getVM()->error("implement me");
- break;
- }
-
- case LDELEM_I1 : {
- VMThread::get()->getVM()->error("implement me");
- break;
- }
-
- case LDELEM_I2 :
- case LDELEM_I4 :
- case LDELEM_I8 :
- case LDELEM_U1 :
- case LDELEM_U2 :
- case LDELEM_U4 :
- case LDELEM_R4 :
- case LDELEM_R8 :
- case LDELEM_I :
- case LDELEM_REF :
- case LDELEMA : break;
-
- case LDFLD : {
- i += 4;
- break;
- }
-
- case LDFLDA : {
- i += 4;
- break;
- }
-
- case LDLEN : break;
-
- case LDOBJ : {
- i += 4;
- break;
- }
-
- case LDSFLD : {
- i += 4;
- break;
- }
-
- case LDSFLDA : {
- i += 4;
- break;
- }
-
- case LDSTR : {
- i += 4;
- break;
- }
-
- case LDTOKEN : {
- i += 4;
- break;
- }
-
- case MKREFANY : {
- VMThread::get()->getVM()->error("implement me");
- break;
- }
-
- case NEWARR : {
- i += 4;
- break;
- }
-
- case NEWOBJ : {
- i += 4;
- break;
- }
-
- case REFANYVAL : {
- VMThread::get()->getVM()->error("implement me");
- break;
- }
-
- case STELEM : {
- VMThread::get()->getVM()->error("implement me");
- break;
- }
-
- case STELEM_I1 :
- case STELEM_I2 :
- case STELEM_I4 :
- case STELEM_I8 :
- case STELEM_R4 :
- case STELEM_R8 :
- case STELEM_I :
- case STELEM_REF : break;
-
- case STFLD : {
- i += 4;
- break;
- }
-
- case STOBJ : {
- VMThread::get()->getVM()->error("implement me");
- break;
- }
-
- case STSFLD : {
- i += 4;
- break;
- }
-
- case THROW : {
- break;
- }
-
- case UNBOX : {
- i += 4;
- break;
- }
-
- case UNBOX_ANY : {
- VMThread::get()->getVM()->error("implement me");
- break;
- }
-
- case 0xFE : {
-
- PRINT_DEBUG(N3_COMPILE, 1, COLOR_NORMAL, "\t[at %5x] %-5d ", i,
- bytecodes[i + 1]);
- PRINT_DEBUG(N3_COMPILE, 1, LIGHT_BLUE, "exploring %s::", mvm::PrintBuffer(compilingMethod).cString());
- PRINT_DEBUG(N3_COMPILE, 1, LIGHT_CYAN, OpcodeNamesFE[bytecodes[i + 1]]);
- PRINT_DEBUG(N3_COMPILE, 1, LIGHT_BLUE, "\n");
-
- switch (bytecodes[++i]) {
-
- case CEQ:
- case CGT:
- case CGT_UN:
- case CLT:
- case CLT_UN:
- case CPBLK : break;
-
- case ENDFILTER: {
- VMThread::get()->getVM()->error("implement me");
- break;
- }
-
- case LDARG : {
- i += 2;
- break;
- }
-
- case LDARGA : {
- i += 2;
- break;
- }
-
- case LDFTN : {
- i += 4;
- break;
- }
-
- case INITBLK : break;
-
- case LDLOC : {
- i += 2;
- break;
- }
-
- case LOCALLOC : break;
-
- case STARG : {
- i += 2;
- break;
- }
-
- case STLOC : {
- i += 2;
- break;
- }
-
- case LDLOCA : {
- i += 2;
- break;
- }
-
- case ARGLIST : {
- VMThread::get()->getVM()->error("implement me");
- break;
- }
-
- case INITOBJ : {
- i += 4;
- break;
- }
-
- case LDVIRTFTN : {
- VMThread::get()->getVM()->error("implement me");
- break;
- }
-
- case REFANYTYPE : {
- VMThread::get()->getVM()->error("implement me");
- break;
- }
-
- case RETHROW : {
- break;
- }
-
- case SIZEOF : {
- VMThread::get()->getVM()->error("implement me");
- break;
- }
-
- case VOLATILE_ : {
- break;
- }
- default :
- VMThread::get()->getVM()->unknownError("unknown bytecode");
- }
- break;
- }
-
- default :
- VMThread::get()->getVM()->unknownError("unknown bytecode");
- }
- }
-}
diff --git a/vmkit/lib/N3/VMCore/Reader.cpp b/vmkit/lib/N3/VMCore/Reader.cpp
deleted file mode 100644
index 641af12..0000000
--- a/vmkit/lib/N3/VMCore/Reader.cpp
+++ /dev/null
@@ -1,151 +0,0 @@
-//===--------------- Reader.cpp - Open and read files ---------------------===//
-//
-// N3
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#include <stdio.h>
-#include <string.h>
-
-#include "types.h"
-
-#include "MSCorlib.h"
-#include "N3.h"
-#include "VMArray.h"
-#include "VMClass.h"
-#include "VMThread.h"
-#include "Reader.h"
-
-using namespace n3;
-
-double Reader::readDouble(int first, int second) {
- int values[2];
- double res[1];
-#if defined(__PPC__)
- values[0] = second;
- values[1] = first;
-#else
- values[0] = first;
- values[1] = second;
-#endif
- memcpy(res, values, 8);
- return res[0];
-}
-
-sint64 Reader::readLong(int first, int second) {
- int values[2];
- sint64 res[1];
-#if defined(__PPC__)
- values[0] = second;
- values[1] = first;
-#else
- values[0] = first;
- values[1] = second;
-#endif
- memcpy(res, values, 8);
- return res[0];
-}
-
-const int Reader::SeekSet = SEEK_SET;
-const int Reader::SeekCur = SEEK_CUR;
-const int Reader::SeekEnd = SEEK_END;
-
-ByteCode::ByteCode(mvm::BumpPtrAllocator &allocator, int size) {
- this->size = size;
- this->elements = (uint8*)allocator.Allocate(size * sizeof(uint8), "uint8[]");
-}
-
-ByteCode* Reader::openFile(mvm::BumpPtrAllocator &allocator, char* path) {
- FILE* fp = fopen(path, "r");
- ByteCode* res = 0;
- if (fp != 0) {
- fseek(fp, 0, SeekEnd);
- long nbb = ftell(fp);
- fseek(fp, 0, SeekSet);
- res = new(allocator, "ByteCode") ByteCode(allocator, nbb);
- fread(res->elements, nbb, 1, fp);
- fclose(fp);
- }
- return res;
-}
-
-uint8 Reader::readU1() {
- if(cursor >= (uint32)bytes->size)
- VMThread::get()->getVM()->error("readU1 outside the buffer");
- return bytes->elements[cursor++];
-}
-
-sint8 Reader::readS1() {
- return readU1();
-}
-
-uint16 Reader::readU2() {
- uint16 tmp = ((uint16)(readU1()));
- return tmp | (((uint16)(readU1())) << 8);
-}
-
-sint16 Reader::readS2() {
- sint16 tmp = ((sint16)(readS1()));
- return tmp | (((sint16)(readS1())) << 8);
-}
-
-uint32 Reader::readU4() {
- uint32 tmp = ((uint32)(readU2()));
- return tmp | (((uint32)(readU2())) << 16);
-}
-
-sint32 Reader::readS4() {
- sint32 tmp = ((sint32)(readS2()));
- return tmp | (((sint32)(readS2())) << 16);
-}
-
-uint64 Reader::readU8() {
- uint64 tmp = ((uint64)(readU4()));
- return tmp | (((uint64)(readU4())) << 32);
-}
-
-sint64 Reader::readS8() {
- sint64 tmp = ((sint64)(readS8()));
- return tmp | (((sint64)(readS8())) << 32);
-}
-
-Reader::Reader(ByteCode* array, uint32 start, uint32 end) {
- if (!end)
- end = array->size;
-
- bytes = array;
- cursor = start;
- min = start;
- max = start + end;
-}
-
-unsigned int Reader::tell() {
- return cursor - min;
-}
-
-// Reader* Reader::derive(uint32 nbb) {
-// return new(allocator, "Reader") Reader(allocator, bytes, cursor, nbb);
-// }
-
-void Reader::seek(uint32 pos, int from) {
- uint32 n = 0;
- uint32 start = min;
- uint32 end = max;
-
- if (from == SeekCur) n = cursor + pos;
- else if (from == SeekSet) n = start + pos;
- else if (from == SeekEnd) n = end + pos;
-
-
- if ((n < start) || (n > end))
- VMThread::get()->getVM()->unknownError("out of range %d %d", n, end);
-
- cursor = n;
-}
-
-void Reader::print(mvm::PrintBuffer* buf) const {
- buf->write("Reader<>");
-}
diff --git a/vmkit/lib/N3/VMCore/Reader.h b/vmkit/lib/N3/VMCore/Reader.h
deleted file mode 100644
index c251586..0000000
--- a/vmkit/lib/N3/VMCore/Reader.h
+++ /dev/null
@@ -1,100 +0,0 @@
-//===----------------- Reader.h - Open and read files ---------------------===//
-//
-// N3
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#ifndef N3_READER_H
-#define N3_READER_H
-
-#include "mvm/Object.h"
-
-#include "types.h"
-
-namespace n3 {
-
-class ByteCode : public mvm::PermanentObject {
-public:
- sint32 size;
- uint8 *elements;
-
- ByteCode(mvm::BumpPtrAllocator &allocator, int nbb);
-};
-
-class Reader : public mvm::PermanentObject {
-public:
- ByteCode* bytes;
- uint32 min;
- uint32 cursor;
- uint32 max;
-
- Reader(ByteCode* array, uint32 start = 0, uint32 end = 0);
-
- static double readDouble(int first, int second);
- static sint64 readLong(int first, int second);
-
- static const int SeekSet;
- static const int SeekCur;
- static const int SeekEnd;
-
- static ByteCode* openFile(mvm::BumpPtrAllocator &allocator, char* path);
- uint8 readU1();
- sint8 readS1();
- uint16 readU2();
- sint16 readS2();
- uint32 readU4();
- sint32 readS4();
- uint64 readU8();
- sint64 readS8();
- unsigned int tell();
- // Reader* derive(uint32 nbb);
- void seek(uint32 pos, int from);
-
- virtual void print(mvm::PrintBuffer* buf) const;
-};
-
-static sint8 inline READ_S1(ByteCode* bytes, uint32& offset) {
- return (sint8)(bytes->elements[offset++]);
-}
-
-static uint8 inline READ_U1(ByteCode* bytes, uint32& offset) {
- return(uint8)(bytes->elements[offset++]);
-}
-
-static sint16 inline READ_S2(ByteCode* bytes, uint32& offset) {
- sint16 val = READ_S1(bytes, offset);
- return val | (READ_U1(bytes, offset) << 8);
-}
-
-static uint16 inline READ_U2(ByteCode* bytes, uint32& offset) {
- uint16 val = READ_U1(bytes, offset);
- return val | (READ_U1(bytes, offset) << 8);
-}
-
-static sint32 inline READ_S4(ByteCode* bytes, uint32& offset) {
- sint32 val = READ_U2(bytes, offset);
- return val | (READ_U2(bytes, offset) << 16);
-}
-
-static uint32 inline READ_U3(ByteCode* bytes, uint32& offset) {
- uint32 val = READ_U2(bytes, offset);
- return val | (READ_U1(bytes, offset) << 16);
-}
-
-static uint32 inline READ_U4(ByteCode* bytes, uint32& offset) {
- return READ_S4(bytes, offset);
-}
-
-static uint32 inline READ_U8(ByteCode* bytes, uint32& offset) {
- uint64 val1 = READ_U4(bytes, offset);
- uint64 val2 = READ_U4(bytes, offset);
- return (val2 << 32) + val1;
-}
-
-
-} // end namespace jnjvm
-
-#endif
diff --git a/vmkit/lib/N3/VMCore/SignatureNames.def b/vmkit/lib/N3/VMCore/SignatureNames.def
deleted file mode 100644
index 89dfea5..0000000
--- a/vmkit/lib/N3/VMCore/SignatureNames.def
+++ /dev/null
@@ -1,85 +0,0 @@
-//===---------- SignatureNames.def - Names of signature -------------------===//
-//
-// N3
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#ifndef SIGNATURE_NAMES_DEF
-#define SIGNATURE_NAMES_DEF
-
-const char* n3::Assembly::signatureNames[0x46] = {
- "ElementTypeEnd", // 0x00
- "ElementTypeVoid", // 0x01
- "ElementTypeBoolean", // 0x02
- "ElementTypeChar", // 0x03
- "ElementTypeI1", // 0x04
- "ElementTypeU1", // 0x05
- "ElementTypeI2", // 0x06
- "ElementTypeU2", // 0x07
- "ElementTypeI4", // 0x08
- "ElementTypeU4", // 0x09
- "ElementTypeI8", // 0x0A
- "ElementTypeU8", // 0x0B
- "ElementTypeR4", // 0x0C
- "ElementTypeR8", // 0x0D
- "ElementTypeString", // 0x0E
- "ElementTypePtr", // 0x1F
- "ElementTypeByRef", // 0x10
- "ElementTypeValueType", // 0x11
- "ElementTypeClass", // 0x12
- "ElementTypeVar", // 0x13
- "ElementTypeArray", // 0x14
- "ElementTypeGenericInst", // 0x15
- "ElementTypedByRef", // 0x16
- "Undefined 0x17", // 0x17
- "ElementTypeI", // 0x18
- "ElementTypeU", // 0x19
- "Undefined 0x1a", // 0x1A
- "ElementTypeFnptr", // 0x1B
- "ElementTypeObject", // 0x1C
- "ElementTypeSzarray", // 0x1D
- "ElementTypeMvar", // 0x1E
- "ElementTypeCmodReqd", // 0x1F
- "ElementTypeCmodOpt", // 0x20
- "ElementTypeInternal", // 0x21
- "ElementTypeModifier", // 0x22
- "Undefined", // 0x23
- "Undefined", // 0x24
- "Undefined", // 0x25
- "Undefined", // 0x26
- "Undefined", // 0x27
- "Undefined", // 0x28
- "Undefined", // 0x29
- "Undefined", // 0x2A
- "Undefined", // 0x2B
- "Undefined", // 0x2C
- "Undefined", // 0x2D
- "Undefined", // 0x2E
- "Undefined", // 0x2F
- "Undefined", // 0x30
- "Undefined", // 0x31
- "Undefined", // 0x32
- "Undefined", // 0x33
- "Undefined", // 0x34
- "Undefined", // 0x35
- "Undefined", // 0x36
- "Undefined", // 0x37
- "Undefined", // 0x38
- "Undefined", // 0x39
- "Undefined", // 0x3A
- "Undefined", // 0x3B
- "Undefined", // 0x3C
- "Undefined", // 0x3D
- "Undefined", // 0x3E
- "Undefined", // 0x3F
- "ElementTypeSentinel", // 0x41
- "Undefined", // 0x42
- "Undefined", // 0x43
- "Undefined", // 0x44
- "ElementTypePinned" // 0x45
-};
-
-#endif
diff --git a/vmkit/lib/N3/VMCore/UTF8.cpp b/vmkit/lib/N3/VMCore/UTF8.cpp
deleted file mode 100644
index e69de29..0000000
--- a/vmkit/lib/N3/VMCore/UTF8.cpp
+++ /dev/null
diff --git a/vmkit/lib/N3/VMCore/UTF8.h b/vmkit/lib/N3/VMCore/UTF8.h
deleted file mode 100644
index 81dc8ab..0000000
--- a/vmkit/lib/N3/VMCore/UTF8.h
+++ /dev/null
@@ -1,11 +0,0 @@
-#ifndef _N3_UTF8_
-#define _N3_UTF8_
-
-#include "mvm/UTF8.h"
-
-namespace n3 {
- using mvm::UTF8;
- using mvm::UTF8Map;
-}
-
-#endif
diff --git a/vmkit/lib/N3/VMCore/VMArray.cpp b/vmkit/lib/N3/VMCore/VMArray.cpp
deleted file mode 100644
index e682309..0000000
--- a/vmkit/lib/N3/VMCore/VMArray.cpp
+++ /dev/null
@@ -1,40 +0,0 @@
-//===----------------- VMArray.cpp - VM arrays ------------------------===//
-//
-// N3
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#include <stdlib.h>
-
-#include "VMArray.h"
-#include "VMClass.h"
-#include "VMObject.h"
-#include "VMThread.h"
-#include "N3.h"
-
-
-using namespace n3;
-
-const sint32 VMArray::MaxArraySize = 268435455;
-
-#define DEFINE_ARRAY_PRINT(name, type, do_root, printer, pre, sep, post) \
- void Array##name::do_print(const Array##name *self, mvm::PrintBuffer *buf) { \
- llvm_gcroot(self, 0); \
- buf->write(pre); \
- for(int i=0; i<self->size; i++) { \
- if(i) \
- buf->write(sep); \
- type cur; \
- do_root(cur, 0); \
- cur = self->elements[i]; \
- buf->printer(cur); \
- } \
- buf->write(post); \
- }
-
-ON_TYPES(DEFINE_ARRAY_PRINT, _F_NTRW)
-
-#undef DEFINE_ARRAY_PRINT
diff --git a/vmkit/lib/N3/VMCore/VMArray.h b/vmkit/lib/N3/VMCore/VMArray.h
deleted file mode 100644
index 4223472..0000000
--- a/vmkit/lib/N3/VMCore/VMArray.h
+++ /dev/null
@@ -1,62 +0,0 @@
-//===-------------------- VMArray.h - VM arrays ---------------------------===//
-//
-// N3
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#ifndef N3_VM_ARRAY_H
-#define N3_VM_ARRAY_H
-
-#include "mvm/PrintBuffer.h"
-
-#include "llvm/Constants.h"
-#include "llvm/Type.h"
-
-#include "types.h"
-
-#include "VMObject.h"
-
-#include "UTF8.h"
-
-namespace n3 {
-
-class VMClassArray;
-class VMCommonClass;
-class VMObject;
-
- // never allocate a VMArray, it is just a C++ type to access N3 object
-class VMArray : public VMObject {
- void *operator new(size_t n) { return VMObject::operator new(n, 0); }
-
-public:
- sint32 size;
- void* elements[1];
-
- static const sint32 MaxArraySize;
- static const llvm::Type* llvmType;
- static llvm::Constant* sizeOffset();
- static llvm::Constant* elementsOffset();
-};
-
- // never allocate a VMArray, it is just a C++ type to access N3 object
-#define DEFINE_ARRAY_CLASS(name, type) \
- class Array##name : public VMObject { \
- void *operator new(size_t n) { return VMObject::operator new(n, 0); } \
- public: \
- static const llvm::Type* llvmType; \
- sint32 size; \
- type elements[1]; \
- static void do_print(const Array##name *self, mvm::PrintBuffer* buf); \
- };
-
-ON_TYPES(DEFINE_ARRAY_CLASS, _F_NT)
-
-#undef DEFINE_ARRAY_CLASS
-
-
-} // end namespace n3
-
-#endif
diff --git a/vmkit/lib/N3/VMCore/VMCache.cpp b/vmkit/lib/N3/VMCore/VMCache.cpp
deleted file mode 100644
index aa9820f..0000000
--- a/vmkit/lib/N3/VMCore/VMCache.cpp
+++ /dev/null
@@ -1,158 +0,0 @@
-//===------- VMCache.cpp - Inline cache for virtual calls -----------------===//
-//
-// N3
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#include <vector>
-
-#include "llvm/DerivedTypes.h"
-#include "llvm/Instructions.h"
-#include "llvm/LLVMContext.h"
-
-#include "mvm/JIT.h"
-#include "mvm/Object.h"
-#include "mvm/PrintBuffer.h"
-#include "mvm/Threads/Locks.h"
-
-#include "Assembly.h"
-#include "CLIJit.h"
-#include "MSCorlib.h"
-#include "N3.h"
-#include "VMArray.h"
-#include "VMCache.h"
-#include "VMClass.h"
-#include "VMThread.h"
-
-#include "types.h"
-
-using namespace n3;
-using namespace llvm;
-
-void CacheNode::print(mvm::PrintBuffer* buf) const {
- buf->write("CacheNode<");
- if (lastCible) {
- lastCible->print(buf);
- buf->write(" -- ");
- buf->writePtr(methPtr);
- }
- buf->write(" in ");
- enveloppe->print(buf);
- buf->write(">");
-}
-
-void Enveloppe::print(mvm::PrintBuffer* buf) const {
- buf->write("Enveloppe<>");
-}
-
-CacheNode* CacheNode::allocate(mvm::BumpPtrAllocator &allocator) {
- CacheNode* cache = new(allocator, "CacheNode") CacheNode();
- cache->lastCible = 0;
- cache->methPtr = 0;
- cache->next = 0;
- return cache;
-}
-
-Enveloppe* Enveloppe::allocate(mvm::BumpPtrAllocator &allocator, VMMethod* meth) {
- Enveloppe* enveloppe = new(allocator, "Enveloppe") Enveloppe();
- enveloppe->firstCache = CacheNode::allocate(allocator);
- enveloppe->firstCache->enveloppe = enveloppe;
- enveloppe->cacheLock = new mvm::LockNormal();
- enveloppe->originalMethod = meth;
- return enveloppe;
-}
-
-void CLIJit::invokeInterfaceOrVirtual(uint32 value, VMGenericClass* genClass, VMGenericMethod* genMethod) {
-
- VMMethod* origMeth = compilingClass->assembly->getMethodFromToken(value, genClass, genMethod);
- const llvm::FunctionType* funcType = origMeth->getSignature(genMethod);
-
- std::vector<Value*> args;
- makeArgs(funcType, args, origMeth->structReturn);
-
- BasicBlock* callBlock = createBasicBlock("call virtual invoke");
- PHINode* node = PHINode::Create(CacheNode::llvmType, "", callBlock);
-
- Value* argObj = args[0];
- if (argObj->getType() != VMObject::llvmType) {
- argObj = new BitCastInst(argObj, VMObject::llvmType, "", currentBlock);
- }
- JITVerifyNull(argObj);
-
- // ok now the cache
- Enveloppe* enveloppe = Enveloppe::allocate(origMeth->classDef->assembly->allocator, origMeth);
- compilingMethod->caches.push_back(enveloppe);
-
- Value* zero = module->constantZero;
- Value* one = module->constantOne;
- Value* two = module->constantTwo;
- Value* five = module->constantFive;
-
- Value* llvmEnv =
- ConstantExpr::getIntToPtr(ConstantInt::get(Type::getInt64Ty(getGlobalContext()), uint64_t (enveloppe)),
- Enveloppe::llvmType);
-
- std::vector<Value*> args1;
- args1.push_back(zero);
- args1.push_back(one);
- Value* cachePtr = GetElementPtrInst::Create(llvmEnv, args1.begin(), args1.end(),
- "", currentBlock);
- Value* cache = new LoadInst(cachePtr, "", currentBlock);
-
- std::vector<Value*> args2;
- args2.push_back(zero);
- args2.push_back(VMObject::classOffset());
- Value* classPtr = GetElementPtrInst::Create(argObj, args2.begin(),
- args2.end(), "",
- currentBlock);
-
- Value* cl = new LoadInst(classPtr, "", currentBlock);
- std::vector<Value*> args3;
- args3.push_back(zero);
- args3.push_back(two);
- Value* lastCiblePtr = GetElementPtrInst::Create(cache, args3.begin(), args3.end(),
- "", currentBlock);
- Value* lastCible = new LoadInst(lastCiblePtr, "", currentBlock);
-
- Value* cmp = new ICmpInst(*currentBlock, ICmpInst::ICMP_EQ, cl, lastCible, "");
-
- BasicBlock* ifFalse = createBasicBlock("cache not ok");
- BranchInst::Create(callBlock, ifFalse, cmp, currentBlock);
- node->addIncoming(cache, currentBlock);
-
- currentBlock = ifFalse;
- Value* newCache = invoke(virtualLookupLLVM, cache, argObj, "", ifFalse, false);
- node->addIncoming(newCache, currentBlock);
- BranchInst::Create(callBlock, currentBlock);
-
- currentBlock = callBlock;
- Value* methPtr = GetElementPtrInst::Create(node, args1.begin(), args1.end(),
- "", currentBlock);
-
- Value* _meth = new LoadInst(methPtr, "", currentBlock);
- Value* meth = new BitCastInst(_meth, PointerType::getUnqual(funcType), "", currentBlock);
-
-
-
- std::vector<Value*> args4;
- args4.push_back(zero);
- args4.push_back(five);
- Value* boxedptr = GetElementPtrInst::Create(node, args4.begin(), args4.end(), "", currentBlock);
- Value* boxed = new LoadInst(boxedptr, "", currentBlock);
- /* I put VMArray::llvmType here, but in should be something else... */
- Value* unboxed = new BitCastInst(args[0], VMArray::llvmType, "", currentBlock);
- Value* unboxedptr = GetElementPtrInst::Create(unboxed, args1.begin(), args1.end(), "", currentBlock);
- Value* fakeunboxedptr = new BitCastInst(unboxedptr, args[0]->getType(), "", currentBlock);
- args[0] = SelectInst::Create(boxed, fakeunboxedptr, args[0], "", currentBlock);
-
-
- Value* ret = invoke(meth, args, "", currentBlock, origMeth->structReturn);
-
-
- if (ret->getType() != Type::getVoidTy(getGlobalContext())) {
- push(ret);
- }
-}
diff --git a/vmkit/lib/N3/VMCore/VMCache.h b/vmkit/lib/N3/VMCore/VMCache.h
deleted file mode 100644
index 6ce68d9..0000000
--- a/vmkit/lib/N3/VMCore/VMCache.h
+++ /dev/null
@@ -1,58 +0,0 @@
-//===--------- VMCache.h - Inline cache for virtual calls -----------------===//
-//
-// N3
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#ifndef N3_VM_CACHE_H
-#define N3_VM_CACHE_H
-
-#include "mvm/Object.h"
-#include "mvm/PrintBuffer.h"
-#include "mvm/Threads/Locks.h"
-
-#include "llvm/DerivedTypes.h"
-
-#include "types.h"
-
-namespace n3 {
-
-class Assembly;
-class Enveloppe;
-class VMClass;
-
-class CacheNode : public mvm::PermanentObject {
-public:
- virtual void print(mvm::PrintBuffer* buf) const;
-
- void* methPtr;
- VMClass* lastCible;
- CacheNode* next;
- Enveloppe* enveloppe;
- bool box;
-
- static const llvm::Type* llvmType;
-
- static CacheNode* allocate(mvm::BumpPtrAllocator &allocator);
-};
-
-class Enveloppe : public mvm::PermanentObject {
-public:
- virtual void print(mvm::PrintBuffer* buf) const;
-
- CacheNode *firstCache;
- mvm::Lock* cacheLock;
- VMMethod* originalMethod;
-
- static const llvm::Type* llvmType;
-
- static Enveloppe* allocate(mvm::BumpPtrAllocator &allocator, VMMethod* orig);
-
-};
-
-} // end namespace n3
-
-#endif
diff --git a/vmkit/lib/N3/VMCore/VMClass.cpp b/vmkit/lib/N3/VMCore/VMClass.cpp
deleted file mode 100644
index c17f1c9..0000000
--- a/vmkit/lib/N3/VMCore/VMClass.cpp
+++ /dev/null
@@ -1,902 +0,0 @@
-//===------------ VMClass.cpp - CLI class representation ------------------===//
-//
-// N3
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#include <stdarg.h>
-#include <vector>
-
-#include "llvm/DerivedTypes.h"
-#include "llvm/LLVMContext.h"
-#include "llvm/Module.h"
-
-#include "N3Debug.h"
-#include "types.h"
-#include "mvm/JIT.h"
-#include "mvm/PrintBuffer.h"
-#include "mvm/Threads/Locks.h"
-
-
-#include "Assembly.h"
-#include "CLIAccess.h"
-#include "CLIJit.h"
-#include "MSCorlib.h"
-#include "N3.h"
-#include "VMArray.h"
-#include "VMClass.h"
-#include "VMThread.h"
-
-using namespace n3;
-
-void VMCommonClass::print(mvm::PrintBuffer* buf) const {
- buf->write("CLIType<");
- nameSpace->print(buf);
- buf->write("::");
- name->print(buf);
- buf->write(">");
-}
-
-void VMCommonClass::aquire() {
- lockVar->lock();
-}
-
-void VMCommonClass::release() {
- lockVar->unlock();
-}
-
-void VMCommonClass::waitClass() {
- condVar->wait(lockVar);
-}
-
-void VMCommonClass::broadcastClass() {
- condVar->broadcast();
-}
-
-bool VMCommonClass::ownerClass() {
- return lockVar->selfOwner();
-}
-
-
-void VMClass::print(mvm::PrintBuffer* buf) const {
- buf->write("CLIType<");
- nameSpace->print(buf);
- buf->write("::");
- name->print(buf);
- buf->write(">");
-}
-
-void VMClassArray::print(mvm::PrintBuffer* buf) const {
- buf->write("CLITypeArray<");
- nameSpace->print(buf);
- buf->write("::");
- name->print(buf);
- buf->write(">");
-}
-
-void VMClassPointer::print(mvm::PrintBuffer* buf) const {
- buf->write("CLITypePointer<");
- nameSpace->print(buf);
- buf->write("::");
- name->print(buf);
- buf->write(">");
-}
-
-void VMMethod::print(mvm::PrintBuffer* buf) const {
- buf->write("CLIMethod<");
- classDef->nameSpace->print(buf);
- buf->write(".");
- classDef->name->print(buf);
- buf->write("::");
- name->print(buf);
- buf->write("(");
- std::vector<VMCommonClass*>::iterator i = ((VMMethod*)this)->parameters.begin();
- std::vector<VMCommonClass*>::iterator e = ((VMMethod*)this)->parameters.end();
-
- ++i;
- if (i != e) {
- while (true) {
- (*i)->nameSpace->print(buf);
- buf->write(".");
- (*i)->name->print(buf);
- ++i;
- if (i == e) break;
- else buf->write(" ,");
- }
- }
- buf->write(")");
- buf->write(">");
-}
-
-void VMGenericMethod::print(mvm::PrintBuffer* buf) const {
- buf->write("CLIGenericMethod<");
- classDef->nameSpace->print(buf);
- buf->write(".");
- classDef->name->print(buf);
- buf->write("::");
- name->print(buf);
- buf->write("(");
- std::vector<VMCommonClass*>::iterator i = ((VMMethod*)this)->parameters.begin();
- std::vector<VMCommonClass*>::iterator e = ((VMMethod*)this)->parameters.end();
-
- ++i;
- if (i != e) {
- while (true) {
- (*i)->nameSpace->print(buf);
- buf->write(".");
- (*i)->name->print(buf);
- ++i;
- if (i == e) break;
- else buf->write(" ,");
- }
- }
- buf->write(")");
- buf->write(">");
-}
-
-void VMField::print(mvm::PrintBuffer* buf) const {
- buf->write("CLIField<");
- classDef->nameSpace->print(buf);
- buf->write(".");
- classDef->name->print(buf);
- buf->write("::");
- name->print(buf);
- buf->write(">");
-}
-
-void Param::print(mvm::PrintBuffer* buf) const {
- buf->write("CLIParam<");
- name->print(buf);
- buf->write(">");
-}
-
-void Property::print(mvm::PrintBuffer* buf) const {
- buf->write("Property def with name <");
- name->print(buf);
- buf->write(">");
-}
-
-
-void VMCommonClass::initialise(N3* vm, bool isArray) {
- this->lockVar = new mvm::LockRecursive();
- this->condVar = new mvm::Cond();
- this->ooo_delegatee = 0;
- this->status = hashed;
- this->vm = vm;
- this->isArray = isArray;
- this->isPointer = false;
- this->isPrimitive = false;
- this->naturalType = llvm::OpaqueType::get(llvm::getGlobalContext());
-}
-
-const UTF8* VMClassArray::constructArrayName(const UTF8* name, uint32 dims) {
- mvm::PrintBuffer _asciiz(name);
- const char* asciiz = _asciiz.cString();
- char* res = (char*)alloca(strlen(asciiz) + (dims * 2) + 1);
- sprintf(res, asciiz);
-
- for (uint32 i = 0; i < dims; ++i) {
- sprintf(res, "%s[]", res);
- }
-
- return VMThread::get()->getVM()->asciizToUTF8(res);
-}
-
-const UTF8* VMClassPointer::constructPointerName(const UTF8* name, uint32 dims) {
- mvm::PrintBuffer _asciiz(name);
- const char* asciiz = _asciiz.cString();
- char* res = (char*)alloca(strlen(asciiz) + (dims * 2) + 1);
- sprintf(res, asciiz);
-
- for (uint32 i = 0; i < dims; ++i) {
- sprintf(res, "%s*", res);
- }
-
- return VMThread::get()->getVM()->asciizToUTF8(res);
-}
-
-
-void VMCommonClass::loadParents(VMGenericClass* genClass, VMGenericMethod* genMethod) {
- if ((0xffff & superToken) == 0) {
- depth = 0;
- display.push_back(this);
- } else {
- super = assembly->loadType((N3*)vm, superToken, true, false, false, true, genClass, genMethod);
- depth = super->depth + 1;
- for (uint32 i = 0; i < super->display.size(); ++i) {
- display.push_back(super->display[i]);
- }
- display.push_back(this);
- }
-
- for (std::vector<uint32>::iterator i = interfacesToken.begin(),
- e = interfacesToken.end(); i!= e; ++i) {
- interfaces.push_back((VMClass*)assembly->loadType((N3*)vm, (*i), true,
- false, false, true, genClass, genMethod));
- }
-
-}
-
-typedef void (*clinit_t)(void);
-
-void VMCommonClass::clinitClass(VMGenericMethod* genMethod) {
- // printf("----- clinit: %s\n", mvm::PrintBuffer::objectToString(this));
- VMCommonClass* cl = this;
- if (cl->status < ready) {
- cl->aquire();
- int status = cl->status;
- if (status == ready) {
- cl->release();
- } else if (status == static_resolved) {
- cl->status = clinitParent;
- cl->release();
- if (cl->super) {
- cl->super->resolveStatic(true, genMethod);
- }
- for (uint32 i = 0; i < cl->interfaces.size(); i++) {
- cl->interfaces[i]->resolveStatic(true, genMethod);
- }
-
- cl->status = inClinit;
- resolveVT();
- std::vector<VMCommonClass*> args;
- args.push_back(MSCorlib::pVoid);
- VMMethod* meth = cl->lookupMethodDontThrow(N3::clinitName, args,
- true, false);
-
- PRINT_DEBUG(N3_LOAD, 0, COLOR_NORMAL, "%s", "; ");
- PRINT_DEBUG(N3_LOAD, 0, LIGHT_GREEN, "%s", "clinit ");
- PRINT_DEBUG(N3_LOAD, 0, COLOR_NORMAL, "%s::%s\n", mvm::PrintBuffer(this).cString(),
- mvm::PrintBuffer(cl).cString());
-
- if (meth) {
- llvm::Function* pred = meth->compiledPtr(genMethod);
- clinit_t res = (clinit_t)
- (intptr_t)mvm::MvmModule::executionEngine->getPointerToGlobal(pred);
- res();
- }
-
- cl->status = ready;
- cl->broadcastClass();
- } else if (status < static_resolved) {
- cl->release();
- VMThread::get()->getVM()->unknownError("try to clinit a not-readed class...");
- } else {
- if (!cl->ownerClass()) {
- while (status < ready) cl->waitClass();
- }
- cl->release();
- }
- }
-}
-
-void VMClass::resolveStaticFields(VMGenericMethod* genMethod) {
-
- VMClass* cl = this;
-
- std::vector<const llvm::Type*> fields;
- fields.push_back(VMObject::llvmType->getContainedType(0));
- uint64 offset = 0;
- for (std::vector<VMField*>::iterator i = cl->staticFields.begin(),
- e = cl->staticFields.end(); i!= e; ++i) {
- // preincrement because 0 is VMObject
- (*i)->offset = llvm::ConstantInt::get(llvm::Type::getInt32Ty(llvm::getGlobalContext()), ++offset);
- }
- for (std::vector<VMField*>::iterator i = cl->staticFields.begin(),
- e = cl->staticFields.end(); i!= e; ++i) {
- (*i)->signature->resolveType(false, false, genMethod);
- fields.push_back((*i)->signature->naturalType);
- }
-
- cl->staticType = llvm::PointerType::getUnqual(llvm::StructType::get(vm->LLVMModule->getContext(), fields, false));
-
- N3VirtualTable* VT = CLIJit::makeVT(cl, true);
-
- uint64 size = mvm::MvmModule::getTypeSize(cl->staticType->getContainedType(0));
- cl->staticInstance = (VMObject*)gc::operator new(size, VT);
- VMObject::initialise(cl->staticInstance, cl);
-
- for (std::vector<VMField*>::iterator i = cl->staticFields.begin(),
- e = cl->staticFields.end(); i!= e; ++i) {
-
- (*i)->initField(cl->staticInstance);
- }
-}
-
-void VMClass::unifyTypes(VMGenericClass* genClass, VMGenericMethod* genMethod) {
- llvm::PATypeHolder PA = naturalType;
- for (std::vector<VMField*>::iterator i = virtualFields.begin(),
- e = virtualFields.end(); i!= e; ++i) {
- (*i)->signature->resolveVirtual(genClass, genMethod);
- }
- naturalType = PA.get();
-}
-
-void VMClass::resolveVirtualFields(VMGenericClass* genClass, VMGenericMethod* genMethod) {
- const llvm::Type* ResultTy = 0;
- if (hasExplicitLayout(flags)) {
- explicitLayoutSize = assembly->getExplicitLayout(token);
- ResultTy = llvm::IntegerType::get(llvm::getGlobalContext(), explicitLayoutSize);
- } else if (super != 0) {
- if (super == MSCorlib::pValue) {
- uint32 size = virtualFields.size();
- if (size == 1) {
- virtualFields[0]->offset = VMThread::get()->getVM()->module->constantZero;
- ResultTy = virtualFields[0]->signature->naturalType;
- } else if (size == 0) {
- ResultTy = llvm::Type::getVoidTy(llvm::getGlobalContext());
- } else {
- std::vector<const llvm::Type*> Elts;
- uint32 offset = -1;
- for (std::vector<VMField*>::iterator i = virtualFields.begin(),
- e = virtualFields.end(); i!= e; ++i) {
- (*i)->offset = llvm::ConstantInt::get(llvm::Type::getInt32Ty(llvm::getGlobalContext()), ++offset);
- const llvm::Type* type = (*i)->signature->naturalType;
- Elts.push_back(type);
- }
- ResultTy = llvm::StructType::get(vm->LLVMModule->getContext(), Elts);
- }
- } else if (super == MSCorlib::pEnum) {
- ResultTy = llvm::Type::getInt32Ty(llvm::getGlobalContext()); // TODO find max
- } else {
- std::vector<const llvm::Type*> Elts;
- Elts.push_back(super->naturalType->getContainedType(0));
- uint32 offset = 0;
- for (std::vector<VMField*>::iterator i = virtualFields.begin(),
- e = virtualFields.end(); i!= e; ++i) {
- (*i)->offset = llvm::ConstantInt::get(llvm::Type::getInt32Ty(llvm::getGlobalContext()), ++offset);
- const llvm::Type* type = (*i)->signature->naturalType;
- Elts.push_back(type);
- }
- ResultTy = llvm::PointerType::getUnqual(llvm::StructType::get(vm->LLVMModule->getContext(), Elts));
- }
- } else {
- ResultTy = VMObject::llvmType;
- }
-
-
- if (naturalType->isAbstract()) {
- const llvm::OpaqueType *OldTy =
- llvm::dyn_cast_or_null<llvm::OpaqueType>(this->naturalType);
- if (OldTy) {
- const_cast<llvm::OpaqueType*>(OldTy)->refineAbstractTypeTo(ResultTy);
- }
- naturalType = ResultTy;
- }
-
- unifyTypes(genClass, genMethod);
-
- if (super == MSCorlib::pValue) {
- std::vector<const llvm::Type*> Elts;
- Elts.push_back(VMObject::llvmType->getContainedType(0));
- for (std::vector<VMField*>::iterator i = virtualFields.begin(),
- e = virtualFields.end(); i!= e; ++i) {
- Elts.push_back((*i)->signature->naturalType);
- }
- virtualType = llvm::PointerType::getUnqual(llvm::StructType::get(vm->LLVMModule->getContext(), Elts));
- } else {
- virtualType = naturalType;
- }
-
-
-}
-
-
-void VMClassArray::makeType() {
- std::vector<const llvm::Type*> arrayFields;
- arrayFields.push_back(VMObject::llvmType->getContainedType(0));
- arrayFields.push_back(llvm::Type::getInt32Ty(llvm::getGlobalContext()));
- arrayFields.push_back(llvm::ArrayType::get(baseClass->naturalType, 0));
- const llvm::Type* type = llvm::PointerType::getUnqual(llvm::StructType::get(vm->LLVMModule->getContext(), arrayFields, false));
- ((llvm::OpaqueType*)naturalType)->refineAbstractTypeTo(type);
- naturalType = type;
- virtualType = naturalType;
-}
-
-void VMClassPointer::makeType() {
- const llvm::Type* type = (baseClass->naturalType == llvm::Type::getVoidTy(llvm::getGlobalContext())) ? llvm::Type::getInt8Ty(llvm::getGlobalContext()) : baseClass->naturalType;
- const llvm::Type* pType = llvm::PointerType::getUnqual(type);
- ((llvm::OpaqueType*)naturalType)->refineAbstractTypeTo(pType);
- naturalType = pType;
-}
-
-void VMCommonClass::resolveVirtual(VMGenericClass* genClass, VMGenericMethod *genMethod) {
- // printf("Resolve virtual: %s\n", mvm::PrintBuffer::objectToString(this));
- VMCommonClass* cl = this;
-
- if (cl->status < virtual_resolved) {
- cl->aquire();
- int status = cl->status;
- if (status >= virtual_resolved) {
- cl->release();
- } else if (status < loaded) {
- cl->release();
- VMThread::get()->getVM()->unknownError("try to resolve a not-readed class");
- } else if (status == loaded) {
- if (cl->isArray) {
- VMClassArray* arrayCl = (VMClassArray*)cl;
- VMCommonClass* baseClass = arrayCl->baseClass;
- // printf("Resolveing base class: %s\n", mvm::PrintBuffer::objectToString(baseClass));
- baseClass->resolveType(false, false, genMethod);
- // printf("Resolveing base class: %s done\n", mvm::PrintBuffer::objectToString(baseClass));
- arrayCl->makeType();
- cl->status = virtual_resolved;
- } else if (cl->isPointer) {
- VMClassPointer* pointerCl = (VMClassPointer*)cl;
- VMCommonClass* baseClass = pointerCl->baseClass;
- baseClass->resolveType(false, false, genMethod);
- pointerCl->makeType();
- cl->status = virtual_resolved;
- } else {
- cl->release();
- cl->loadParents(genClass, genMethod);
- cl->aquire();
- cl->status = prepared;
- assembly->readClass(cl, genMethod);
- cl->status = readed;
- ((VMClass*)cl)->resolveVirtualFields(genClass, genMethod);
- cl->status = virtual_resolved;
- }
- cl->release();
- } else {
- if (!(cl->ownerClass())) {
- while (status < virtual_resolved) {
- cl->waitClass();
- }
- }
- cl->release();
- }
- }
-}
-
-void VMCommonClass::resolveVT() {
- VMCommonClass* cl = this;
- if (cl->isArray) {
- VMClassArray* arrayCl = (VMClassArray*)cl;
- arrayCl->baseClass->resolveVT();
- // printf("Making vt of %s\n", mvm::PrintBuffer(this).cString());
- arrayCl->arrayVT = CLIJit::makeArrayVT(arrayCl);
- } else if (cl->isPointer) {
- } else {
- VMClass* cl = (VMClass*)this;
- if (super)
- super->resolveVT();
-
- // We check for virtual instance because the string class has a
- // bigger size than the class declares.
- if (super != MSCorlib::pEnum && !cl->virtualInstance) {
- cl->vtSize = super ? ((VMClass*)super)->vtSize : sizeof(N3VirtualTable) / sizeof(uintptr_t);
- for (std::vector<VMMethod*>::iterator i = virtualMethods.begin(),
- e = virtualMethods.end(); i!= e; ++i) {
- (*i)->offsetInVt = cl->vtSize++;
- }
-
- // printf("Making vt of %s with %d elements\n", mvm::PrintBuffer(this).cString(), cl->vtSize);
- N3VirtualTable* VT = CLIJit::makeVT(cl, false);
-
- uint64 size = mvm::MvmModule::getTypeSize(cl->virtualType->getContainedType(0));
- cl->virtualInstance = (VMObject*)gc::operator new(size, VT);
- VMObject::initialise(cl->virtualInstance, cl);
-
- for (std::vector<VMField*>::iterator i = cl->virtualFields.begin(),
- e = cl->virtualFields.end(); i!= e; ++i) {
-
- (*i)->initField(cl->virtualInstance);
- }
- }
- }
-}
-
-void VMCommonClass::resolveType(bool stat, bool clinit, VMGenericMethod* genMethod) {
- // printf("Resolve type: %s %d %d\n", mvm::PrintBuffer::objectToString(this), stat, clinit);
- resolveVirtual(static_cast<VMGenericClass*>(this), genMethod);
- if (stat) resolveStatic(clinit, genMethod);
-}
-
-void VMCommonClass::resolveStatic(bool clinit, VMGenericMethod* genMethod) {
- // printf("Resolve static: %s %d\n", mvm::PrintBuffer::objectToString(this), clinit);
- VMCommonClass* cl = this;
- if (cl->status < static_resolved) {
- cl->aquire();
- int status = cl->status;
- if (status >= static_resolved) {
- cl->release();
- } else if (status < virtual_resolved) {
- cl->release();
- // printf("Will throw an exception: %s....\n", mvm::PrintBuffer::objectToString(this));
- // ((char *)0)[0] = 22;
- VMThread::get()->getVM()->unknownError("try to resolve static of a not virtual-resolved class");
- } else if (status == virtual_resolved) {
- if (cl->isArray) {
- VMClassArray* arrayCl = (VMClassArray*)cl;
- VMCommonClass* baseClass = arrayCl->baseClass;
- baseClass->resolveStatic(false, genMethod);
- cl->status = static_resolved;
- } else if (cl->isPointer) {
- VMClassPointer* pointerCl = (VMClassPointer*)cl;
- VMCommonClass* baseClass = pointerCl->baseClass;
- baseClass->resolveStatic(false, genMethod);
- cl->status = static_resolved;
- } else {
- ((VMClass*)cl)->resolveStaticFields(genMethod);
- cl->status = static_resolved;
- }
- cl->release();
- } else {
- if (!(cl->ownerClass())) {
- while (status < static_resolved) {
- cl->waitClass();
- }
- }
- cl->release();
- }
- }
- if (clinit) cl->clinitClass(genMethod);
-}
-
-
-VMMethod* VMCommonClass::lookupMethodDontThrow(const UTF8* name,
- std::vector<VMCommonClass*>& args,
- bool isStatic, bool recurse) {
-
- std::vector<VMMethod*>* meths = (isStatic? &staticMethods :
- &virtualMethods);
-
- VMMethod *cur, *res = 0;
- int i = 0;
- int nbm = meths->size();
-
- while (!res && i < nbm) {
- cur = meths->at(i);
- if (cur->name == name && cur->signatureEquals(args)) {
- return cur;
- }
- ++i;
- }
-
- if (recurse) {
- if (super) res = super->lookupMethodDontThrow(name, args, isStatic,
- recurse);
- if (!res && isStatic) {
- int nbi = interfaces.size();
- i = 0;
- while (res == 0 && i < nbi) {
- res = interfaces[i]->lookupMethodDontThrow(name, args, isStatic,
- recurse);
- ++i;
- }
- }
- }
-
- return res;
-}
-
-VMMethod* VMCommonClass::lookupMethod(const UTF8* name,
- std::vector<VMCommonClass*>& args,
- bool isStatic, bool recurse) {
-
- VMMethod* res = lookupMethodDontThrow(name, args, isStatic, recurse);
- if (!res) {
- VMThread::get()->getVM()->error(N3::MissingMethodException,
- "unable to find %s in %s",
- mvm::PrintBuffer(name).cString(), mvm::PrintBuffer(this).cString());
- }
- return res;
-}
-
-VMField* VMCommonClass::lookupFieldDontThrow(const UTF8* name,
- VMCommonClass* type,
- bool isStatic, bool recurse) {
-
- std::vector<VMField*>* fields = (isStatic? &staticFields : &virtualFields);
-
- VMField *cur, *res = 0;
- int i = 0;
- int nbm = fields->size();
-
- while (!res && i < nbm) {
- cur = fields->at(i);
- if (cur->name == name && cur->signature == type) {
- return cur;
- }
- ++i;
- }
-
- if (recurse) {
- if (super) res = super->lookupFieldDontThrow(name, type, isStatic,
- recurse);
- if (!res && isStatic) {
- int nbi = interfaces.size();
- i = 0;
- while (res == 0 && i < nbi) {
- res = interfaces[i]->lookupFieldDontThrow(name, type, isStatic,
- recurse);
- ++i;
- }
- }
- }
-
- return res;
-}
-
-VMField* VMCommonClass::lookupField(const UTF8* name, VMCommonClass* type,
- bool isStatic, bool recurse) {
-
- VMField* res = lookupFieldDontThrow(name, type, isStatic, recurse);
- if (!res) {
- VMThread::get()->getVM()->error(N3::MissingFieldException,
- "unable to find %s in %s",
- mvm::PrintBuffer(name).cString(), mvm::PrintBuffer(this).cString());
- }
- return res;
-}
-
-VMObject* VMClass::initialiseObject(VMObject* obj) {
- uint64 size = mvm::MvmModule::getTypeSize(virtualType->getContainedType(0));
- memcpy(obj, virtualInstance, size);
- return obj;
-}
-
-VMObject* VMClass::doNew() {
- if (status < inClinit) resolveType(true, true, NULL);
- uint64 size = mvm::MvmModule::getTypeSize(virtualType->getContainedType(0));
- declare_gcroot(VMObject*, res) = (VMObject*)gc::operator new(size, VMObject::getN3VirtualTable(virtualInstance));
- memcpy(res, virtualInstance, size);
- return res;
-}
-
-VMObject* VMClassArray::doNew(uint32 nb) {
- if (status < inClinit) resolveType(true, true, NULL);
- uint64 size = mvm::MvmModule::getTypeSize(baseClass->naturalType);
- declare_gcroot(VMArray*, res) = (VMArray*)gc::operator new(size * nb + sizeof(VMObject) + sizeof(sint32), arrayVT);
- memset(res->elements, 0, size * nb);
- VMObject::initialise(res, this);
- res->size = nb;
- return res;
-}
-
-static void disassembleStruct(std::vector<const llvm::Type*> &args,
- const llvm::Type* arg) {
- const llvm::StructType* STy = llvm::dyn_cast<llvm::StructType>(arg);
- for (llvm::StructType::element_iterator I = STy->element_begin(),
- E = STy->element_end(); I != E; ++I) {
- if ((*I)->isSingleValueType()) {
- args.push_back(*I);
- } else {
- disassembleStruct(args, *I);
- }
- }
-}
-
-const llvm::FunctionType* VMMethod::resolveSignature(
- std::vector<VMCommonClass*> & parameters, bool isVirt,
- bool& structRet, VMGenericMethod* genMethod) {
- const llvm::Type* ret;
- std::vector<const llvm::Type*> args;
- std::vector<VMCommonClass*>::iterator i = parameters.begin(),
- e = parameters.end();
- if ((*i)->naturalType->isAbstract()) {
- (*i)->resolveType(false, false, genMethod);
- }
- ret = (*i)->naturalType;
- ++i;
-
- if (isVirt) {
- VMCommonClass* cur = (*i);
- ++i;
- if (cur->naturalType->isAbstract()) {
- cur->resolveType(false, false, genMethod);
- }
- if (cur->super != MSCorlib::pValue && cur->super != MSCorlib::pEnum) {
- args.push_back(cur->naturalType);
- } else {
- args.push_back(llvm::PointerType::getUnqual(cur->naturalType));
- }
- }
-
- for ( ; i!= e; ++i) {
- VMCommonClass* cur = (*i);
- if (cur->naturalType->isAbstract()) {
- cur->resolveType(false, false, genMethod);
- }
- if (cur->naturalType->isSingleValueType()) {
- args.push_back(cur->naturalType);
- } else {
- args.push_back(llvm::PointerType::getUnqual(cur->naturalType));
- }
- }
-
- if (!(ret->isSingleValueType()) && ret != llvm::Type::getVoidTy(llvm::getGlobalContext())) {
- args.push_back(llvm::PointerType::getUnqual(ret));
- ret = llvm::Type::getVoidTy(llvm::getGlobalContext());
- structRet = true;
- } else {
- structRet = false;
- }
- return llvm::FunctionType::get(ret, args, false);
-}
-
-const llvm::FunctionType* VMMethod::getSignature(VMGenericMethod* genMethod) {
- if (!_signature) {
- _signature = resolveSignature(parameters, !isStatic(flags), structReturn, genMethod);
- }
- return _signature;
-}
-
-const llvm::FunctionType* Property::getSignature(VMGenericMethod* genMethod) {
- if (!_signature) {
- bool structReturn = false;
- _signature = VMMethod::resolveSignature(parameters, virt, structReturn, genMethod);
- }
- return _signature;
-}
-
-bool VMCommonClass::implements(VMCommonClass* cl) {
- if (this == cl) return true;
- else {
- for (uint32 i = 0; i < interfaces.size(); i++) {
- VMCommonClass* cur = interfaces[i];
- if (cur == cl) return true;
- else if (cur->implements(cl)) return true;
- }
- if (super) {
- return super->implements(cl);
- }
- }
- return false;
-}
-
-bool VMCommonClass::instantiationOfArray(VMCommonClass* cl) {
- if (this == cl) return true;
- else {
- if (isArray && cl->isArray) {
- VMCommonClass* baseThis = ((VMClassArray*)this)->baseClass;
- VMCommonClass* baseCl = ((VMClassArray*)cl)->baseClass;
-
- if (isInterface(baseThis->flags) && isInterface(baseCl->flags)) {
- return baseThis->implements(baseCl);
- } else {
- return baseThis->isAssignableFrom(baseCl);
- }
- }
- }
- return false;
-}
-
-bool VMCommonClass::subclassOf(VMCommonClass* cl) {
- if (cl->depth < display.size()) {
- return display[cl->depth] == cl;
- } else {
- return false;
- }
-}
-
-bool VMCommonClass::isAssignableFrom(VMCommonClass* cl) {
- if (this == cl) {
- return true;
- } else if (isInterface(cl->flags)) {
- return this->implements(cl);
- } else if (cl->isArray) {
- return this->instantiationOfArray(cl);
- } else if (cl->isPointer){
- VMThread::get()->getVM()->error("implement me");
- return false;
- } else {
- return this->subclassOf(cl);
- }
-}
-
-VMMethod *VMMethod::compileToNative(VMGenericMethod* genMethod) {
- if(!code) {
- if (classDef->status < ready)
- classDef->resolveType(true, true, NULL);
-
- llvm::Function *methPtr = compiledPtr(genMethod);
- void* res =
- mvm::MvmModule::executionEngine->getPointerToGlobalIfAvailable(methPtr);
- if (res == 0) {
- classDef->aquire();
- res =
- mvm::MvmModule::executionEngine->getPointerToGlobalIfAvailable(methPtr);
- if (res == 0) {
- CLIJit::compile(classDef, this);
- void* res = mvm::MvmModule::executionEngine->getPointerToGlobal(methPtr);
- code = res;
- // N3* vm = VMThread::get()->getVM();
- // vm->addMethodInFunctionMap(this, res);
- }
- classDef->release();
- classDef->resolveStatic(true, NULL);
- }
- }
- return this;
-}
-
-bool VMMethod::signatureEquals(std::vector<VMCommonClass*>& args) {
- bool stat = isStatic(flags);
- if (args.size() != parameters.size()) return false;
- else {
- std::vector<VMCommonClass*>::iterator i = parameters.begin(),
- a = args.begin(), e = args.end();
-
- if ((*i) != (*a)) return false;
- ++i; ++a;
- if (!stat) {
- ++i; ++a;
- }
- for( ; a != e; ++i, ++a) {
- if ((*i) != (*a)) return false;
- }
- }
- return true;
-}
-
-bool VMMethod::signatureEqualsGeneric(std::vector<VMCommonClass*> & args) {
- bool stat = isStatic(flags);
-
- if (args.size() != parameters.size())
- return false;
- else {
- std::vector<VMCommonClass*>::iterator i = parameters.begin(), a =
- args.begin(), e = args.end();
-
- // dummy classes for generic arguments have a NULL assembly field
- // check whether both i and a point to a dummy class
- if (((*i)->assembly == NULL && (*a)->assembly != NULL) ||
- ((*i)->assembly != NULL && (*a)->assembly == NULL))
- return false;
-
- // dummy classes for generic arguments contain the
- // argument number in the token field
- // signature is only equal if the argument number matches
- if ((*i)->assembly == NULL && (*a)->assembly == NULL) {
- if ((*i)->token != (*a)->token) {
- return false;
- }
- }
-
- if ((*i) != (*a))
- return false;
- ++i;
- ++a;
-
- if (!stat) {
- ++i;
- ++a;
- }
-
- for (; a != e; ++i, ++a) {
- // dummy classes for generic arguments have a NULL assembly field
- // check whether both i and a point to a dummy class
- if (((*i)->assembly == NULL && (*a)->assembly != NULL) ||
- ((*i)->assembly != NULL && (*a)->assembly == NULL))
- return false;
-
- // dummy classes for generic arguments contain the
- // argument number in the token field
- // signature is only equal if the argument number matches
- if ((*i)->assembly == NULL && (*a)->assembly == NULL) {
- if ((*i)->token != (*a)->token) {
- return false;
- } else {
- continue;
- }
- }
-
- if ((*i) != (*a))
- return false;
- }
- }
- return true;
-}
-
-void VMGenericClass::print(mvm::PrintBuffer* buf) const {
- buf->write("GenCLIType<");
- nameSpace->print(buf);
- buf->write("::");
- name->print(buf);
- buf->write(">");
-}
diff --git a/vmkit/lib/N3/VMCore/VMClass.h b/vmkit/lib/N3/VMCore/VMClass.h
deleted file mode 100644
index 0b1f606..0000000
--- a/vmkit/lib/N3/VMCore/VMClass.h
+++ /dev/null
@@ -1,319 +0,0 @@
-//===------------- VMClass.h - CLI class representation -------------------===//
-//
-// N3
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#ifndef N3_VM_CLASS_H
-#define N3_VM_CLASS_H
-
-#include "types.h"
-
-#include "mvm/Object.h"
-#include "mvm/Threads/Locks.h"
-#include "mvm/Threads/Cond.h"
-
-#include "llvm/Constants.h"
-#include "llvm/ExecutionEngine/GenericValue.h"
-#include "llvm/Function.h"
-#include "llvm/Type.h"
-
-#include "N3MetaType.h"
-
-#include <cstdarg>
-
-namespace mvm {
- class UTF8;
-}
-
-namespace n3 {
-using mvm::UTF8;
-
-class ArraySInt32;
-class Assembly;
-class Enveloppe;
-class Param;
-class Property;
-class VMClass;
-class VMField;
-class VMMethod;
-class VMObject;
-class VMGenericClass;
-class VMGenericMethod;
-class N3;
-
-typedef enum VMClassState {
- hashed = 0, loaded, prepared, readed, virtual_resolved, static_resolved, clinitParent, inClinit, ready
-}VMClassState;
-
-
-class VMCommonClass : public mvm::PermanentObject {
-public:
- virtual void print(mvm::PrintBuffer* buf) const;
- virtual void TRACER;
-
- std::vector<VMMethod*> virtualMethods;
- std::vector<VMMethod*> staticMethods;
- std::vector<VMField*> virtualFields;
- std::vector<VMField*> staticFields;
- std::vector<VMClass*> interfaces;
- std::vector<uint32> interfacesToken;
- VMCommonClass* super;
- N3* vm;
- const UTF8* name;
- const UTF8* nameSpace;
- mvm::Lock* lockVar;
- mvm::Cond* condVar;
- VMObject* ooo_delegatee;
- std::vector<VMCommonClass*> display;
- Assembly* assembly;
- std::vector<Property*, gc_allocator<Property*> > properties;
-
- llvm::Function* virtualTracer;
- llvm::Function* staticTracer;
-
- uint32 superToken;
- uint32 token;
- bool isArray;
- bool isPointer;
- bool isPrimitive;
- uint32 depth;
- VMClassState status;
- uint32 flags;
-
- static const uint32 maxDisplay;
-
- void aquire();
- void release();
- void waitClass();
- void broadcastClass();
- bool ownerClass();
-
- void initialise(N3* vm, bool isArray);
-
- const llvm::Type* naturalType; // true type
- const llvm::Type* virtualType; // true type or box
- const llvm::Type* staticType; // static type
-
- bool inheritName(const UTF8* Tname);
- bool isOfTypeName(const UTF8* Tname);
- bool implements(VMCommonClass* cl);
- bool instantiationOfArray(VMCommonClass* cl);
- bool subclassOf(VMCommonClass* cl);
- bool isAssignableFrom(VMCommonClass* cl);
-
- void assignType();
- void clinitClass(VMGenericMethod* genMethod);
- void resolveStatic(bool clinit, VMGenericMethod* genMethod);
- void resolveVirtual(VMGenericClass* genClass, VMGenericMethod* genMethod);
- void resolveVT();
- void resolveType(bool stat, bool clinit, VMGenericMethod* genMethod);
- void loadParents(VMGenericClass* genClass, VMGenericMethod* genMethod);
-
- VMMethod* lookupMethodDontThrow(const UTF8* name,
- std::vector<VMCommonClass*>& args,
- bool isStatic, bool recurse);
-
- VMMethod* lookupMethod(const UTF8* name, std::vector<VMCommonClass*>& args,
- bool isStatic, bool recurse);
-
- VMField* lookupFieldDontThrow(const UTF8* name, VMCommonClass* type,
- bool isStatic, bool recurse);
-
- VMField* lookupField(const UTF8* name, VMCommonClass* type, bool isStatic,
- bool recurse);
-
- llvm::GlobalVariable* llvmVar();
- llvm::GlobalVariable* _llvmVar;
-
- VMObject* getClassDelegatee();
-};
-
-
-
-class VMClass : public VMCommonClass {
-public:
- virtual void print(mvm::PrintBuffer* buf) const;
- virtual void TRACER;
-
- void resolveFields();
- void resolveStaticFields(VMGenericMethod* genMethod);
- void resolveVirtualFields(VMGenericClass* genClass, VMGenericMethod* genMethod);
- void unifyTypes(VMGenericClass* genClass, VMGenericMethod* genMethod);
-
- VMObject* staticInstance;
- VMObject* virtualInstance;
- std::vector<VMClass*> innerClasses;
- VMClass* outerClass;
- std::vector<VMMethod*> genericMethods;
- uint32 vtSize; // in number of methods
-
- VMObject* doNew();
- VMObject* initialiseObject(VMObject*);
-
- uint32 explicitLayoutSize;
-};
-
-// FIXME try to get rid of this class
-// add flag to VMClass instead
-class VMGenericClass : public VMClass {
-public:
- virtual void print(mvm::PrintBuffer* buf) const;
- virtual void TRACER;
-
- std::vector<VMCommonClass*> genericParams;
-};
-
-class VMClassArray : public VMCommonClass {
-public:
- virtual void print(mvm::PrintBuffer* buf) const;
- virtual void TRACER;
-
- uint32 dims;
- VMCommonClass* baseClass;
-
- static VMCommonClass* SuperArray;
- static std::vector<VMClass*> InterfacesArray;
- static std::vector<VMMethod*> VirtualMethodsArray;
- static std::vector<VMMethod*> StaticMethodsArray;
- static std::vector<VMField*> VirtualFieldsArray;
- static std::vector<VMField*> StaticFieldsArray;
-
- static const UTF8* constructArrayName(const UTF8* name, uint32 dims);
- void makeType();
- VMObject* doNew(uint32 nb);
- VirtualTable* arrayVT;
-};
-
-class VMClassPointer : public VMCommonClass {
-public:
- virtual void print(mvm::PrintBuffer* buf) const;
- virtual void TRACER;
-
- uint32 dims;
- VMCommonClass* baseClass;
- static const UTF8* constructPointerName(const UTF8* name, uint32 dims);
- void makeType();
-};
-
-class VMMethod : public mvm::PermanentObject {
-public:
- virtual void print(mvm::PrintBuffer* buf) const;
- virtual void TRACER;
-
- uint32 offsetInVt;
- uint32 flags;
- uint32 offsetInTextSection;
- uint32 implFlags;
- uint32 token;
-
- VMObject* ooo_delegatee;
- VMObject* getMethodDelegatee();
- std::vector<Param*, gc_allocator<Param*> > params;
- std::vector<Enveloppe*, gc_allocator<Enveloppe*> > caches;
- std::vector<VMCommonClass*> parameters;
- VMClass* classDef;
- llvm::Function* compiledPtr(VMGenericMethod* genMethod);
- llvm::Function* methPtr;
- const UTF8* name;
- const llvm::FunctionType* _signature;
- bool structReturn;
- bool virt;
- bool canBeInlined;
-
- void* code;
-
- VMMethod *compileToNative(VMGenericMethod* genMethod=0);
-
- llvm::GenericValue invokeGeneric(std::vector<llvm::GenericValue>& args);
- llvm::GenericValue invokeGeneric(va_list ap);
- llvm::GenericValue invokeGeneric(...);
-
-#define DEFINE_CALLER(name, type) \
- type invoke##name(...);
-
- ON_TYPES(DEFINE_CALLER, _F_NT)
- ON_VOID(DEFINE_CALLER, _F_NT)
-
-#undef DEFINE_CALLER
-
- const llvm::FunctionType* getSignature(VMGenericMethod* genMethod);
- static const llvm::FunctionType* resolveSignature(
- std::vector<VMCommonClass*>& params, bool isVirt, bool &structRet, VMGenericMethod* genMethod);
- bool signatureEquals(std::vector<VMCommonClass*>& args);
- bool signatureEqualsGeneric(std::vector<VMCommonClass*>& args);
- llvm::GlobalVariable* llvmVar();
- llvm::GlobalVariable* _llvmVar;
-};
-
-// FIXME try to get rid of this class
-// add flag to VMMethod instead
-class VMGenericMethod : public VMMethod {
-public:
- virtual void print(mvm::PrintBuffer* buf) const;
- virtual void TRACER;
-
- std::vector<VMCommonClass*> genericParams;
-};
-
-class VMField : public mvm::PermanentObject {
-public:
- virtual void print(mvm::PrintBuffer* buf) const;
- virtual void TRACER;
-
- uint32 flags;
- llvm::Constant* offset;
- uint32 token;
- const UTF8* name;
- VMClass* classDef;
- VMCommonClass* signature;
- uint64 ptrOffset;
-
- void initField(VMObject* obj);
-
-#define DEF_VMFIELD_ASSESSORS(name, type) \
- void set##name(VMObject *obj, type value); \
- type get##name(VMObject *obj);
-
- ON_TYPES(DEF_VMFIELD_ASSESSORS, _F_NT)
-
-#undef DEF_VMFIELD_ASSESSORS
-
- llvm::GlobalVariable* llvmVar();
- llvm::GlobalVariable* _llvmVar;
-};
-
-class Param : public mvm::PermanentObject {
-public:
- virtual void print(mvm::PrintBuffer* buf) const;
-
- uint32 flags;
- uint32 sequence;
- VMMethod* method;
- const UTF8* name;
-};
-
-class Property : public mvm::PermanentObject {
-public:
- virtual void print(mvm::PrintBuffer* buf) const;
- virtual void TRACER;
-
- std::vector<VMCommonClass*> parameters;
- VMCommonClass* type;
- const llvm::FunctionType* _signature;
- const llvm::FunctionType* getSignature(VMGenericMethod* genMethod);
- bool virt;
- const UTF8* name;
- VMObject* ooo_delegatee;
- uint32 flags;
- VMObject* getPropertyDelegatee();
-};
-
-
-
-} // end namespace n3
-
-#endif
diff --git a/vmkit/lib/N3/VMCore/VMObject.cpp b/vmkit/lib/N3/VMCore/VMObject.cpp
deleted file mode 100644
index 55774bc..0000000
--- a/vmkit/lib/N3/VMCore/VMObject.cpp
+++ /dev/null
@@ -1,259 +0,0 @@
-//===------------- VMObject.cpp - VM object definition --------------------===//
-//
-// N3
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#include <vector>
-
-#include "mvm/Threads/Locks.h"
-
-#include "VMClass.h"
-#include "VMObject.h"
-#include "VMThread.h"
-#include "N3.h"
-
-using namespace n3;
-
-N3VirtualTable LockObj::_VT((uintptr_t)LockObj::_destroy,
- (uintptr_t)0,
- (uintptr_t)mvm::Object::default_tracer,
- (uintptr_t)LockObj::_print,
- (uintptr_t)mvm::Object::default_hashCode);
-
-void *N3VirtualTable::operator new(size_t size, mvm::BumpPtrAllocator &allocator, size_t totalVtSize) {
- //printf("Allocate N3VirtualTable with %d elements\n", totalVtSize);
- return allocator.Allocate(totalVtSize * sizeof(uintptr_t), "N3VirtualTable");
-}
-
-N3VirtualTable::N3VirtualTable() {
-}
-
-N3VirtualTable::N3VirtualTable(N3VirtualTable *baseVt, uint32 baseVtSize, uint32 totalSize) {
- memcpy(this, baseVt, baseVtSize * sizeof(uintptr_t));
-}
-
-N3VirtualTable::N3VirtualTable(uintptr_t d, uintptr_t o, uintptr_t t, uintptr_t p, uintptr_t h) : VirtualTable(d, o, t) {
- print = p;
- hashCode = h;
-}
-
-uint32 N3VirtualTable::baseVtSize() {
- return sizeof(N3VirtualTable) / sizeof(uintptr_t);
-}
-
-
-LockObj* LockObj::allocate() {
- declare_gcroot(LockObj*, res) = new(&_VT) LockObj();
- res->threads = new std::vector<VMThread*>();
- res->lock = new mvm::LockRecursive();
- return res;
-}
-
-void LockObj::_print(const LockObj *self, mvm::PrintBuffer* buf) {
- llvm_gcroot(self, 0);
- buf->write("Lock<>");
-}
-
-void LockObj::_destroy(LockObj *self) {
- llvm_gcroot(self, 0);
- delete self->threads;
- delete self->lock;
-}
-
-void LockObj::notify(LockObj *self) {
- llvm_gcroot(self, 0);
- for (std::vector<VMThread*>::iterator i = self->threads->begin(),
- e = self->threads->end(); i!= e; ++i) {
- VMThread* cur = *i;
- cur->lock->lock();
- if (cur->interruptFlag != 0) {
- cur->lock->unlock();
- continue;
- } else {
- declare_gcroot(VMObject *, th) = cur->ooo_appThread;
- if (th != 0) {
- cur->varcond->signal();
- cur->lock->unlock();
- self->threads->erase(i);
- break;
- } else { // dead thread
- self->threads->erase(i);
- }
- }
- }
-}
-
-void LockObj::notifyAll(LockObj *self) {
- llvm_gcroot(self, 0);
- for (std::vector<VMThread*>::iterator i = self->threads->begin(),
- e = self->threads->end(); i!= e; ++i) {
- VMThread* cur = *i;
- cur->lock->lock();
- cur->varcond->signal();
- cur->lock->unlock();
- self->threads->erase(i);
- }
-}
-
-void LockObj::wait(LockObj *self, VMThread* th) {
- llvm_gcroot(self, 0);
- self->threads->push_back(th);
-}
-
-void LockObj::remove(LockObj *self, VMThread* th) {
- llvm_gcroot(self, 0);
- for (std::vector<VMThread*>::iterator i = self->threads->begin(),
- e = self->threads->end(); i!= e; ++i) {
- if (*i == th) {
- self->threads->erase(i);
- break;
- }
- }
-}
-
-void LockObj::aquire(LockObj *self) {
- llvm_gcroot(self, 0);
- self->lock->lock();
-}
-
-void LockObj::release(LockObj *self) {
- llvm_gcroot(self, 0);
- self->lock->unlock();
-}
-
-bool LockObj::owner(LockObj *self) {
- llvm_gcroot(self, 0);
- return self->lock->selfOwner();
-}
-
-static LockObj* myLock(VMObject* obj) {
- llvm_gcroot(obj, 0);
- verifyNull(obj);
- declare_gcroot(LockObj*, lock) = obj->lockObj;
- if (lock == 0) {
- VMObject::globalLock->lock();
- lock = obj->lockObj;
- if (lock == 0) {
- lock = LockObj::allocate();
- obj->lockObj = lock;
- }
- VMObject::globalLock->unlock();
- }
- return lock;
-}
-
-void VMObject::initialise(VMObject* self, VMCommonClass* cl) {
- llvm_gcroot(self, 0);
- self->classOf = cl;
- self->lockObj = 0;
-}
-
-void VMObject::_print(const VMObject *self, mvm::PrintBuffer* buf) {
- llvm_gcroot(self, 0);
- buf->write("VMObject<");
- self->classOf->print(buf);
- buf->write("@0x");
- buf->writePtr((void*)self->hashCode());
- buf->write(">");
-}
-
-void VMObject::aquire(VMObject* self) {
- llvm_gcroot(self, 0);
- declare_gcroot(LockObj*, lock) = myLock(self);
- LockObj::aquire(lock);
-}
-
-void VMObject::unlock(VMObject* self) {
- llvm_gcroot(self, 0);
- verifyNull(self);
- declare_gcroot(LockObj*, lock) = myLock(self);
- LockObj::release(lock);
-}
-
-void VMObject::waitIntern(VMObject* self, struct timeval* info, bool timed) {
- llvm_gcroot(self, 0);
- declare_gcroot(LockObj *, l) = myLock(self);
- bool owner = LockObj::owner(l);
-
- if (owner) {
- VMThread* thread = VMThread::get();
- mvm::Lock* mutexThread = thread->lock;
- mvm::Cond* varcondThread = thread->varcond;
-
- mutexThread->lock();
- if (thread->interruptFlag != 0) {
- mutexThread->unlock();
- thread->interruptFlag = 0;
- thread->getVM()->interruptedException(self);
- } else {
- unsigned int recur = l->lock->recursionCount();
- bool timeout = false;
- l->lock->unlockAll();
- LockObj::wait(l, thread);
- thread->state = VMThread::StateWaiting;
-
- if (timed) {
- timeout = varcondThread->timedWait(mutexThread, info);
- } else {
- varcondThread->wait(mutexThread);
- }
-
- bool interrupted = (thread->interruptFlag != 0);
- mutexThread->unlock();
- l->lock->lockAll(recur);
-
- if (interrupted || timeout) {
- LockObj::remove(l, thread);
- }
-
- thread->state = VMThread::StateRunning;
-
- if (interrupted) {
- thread->interruptFlag = 0;
- thread->getVM()->interruptedException(self);
- }
- }
- } else {
- VMThread::get()->getVM()->illegalMonitorStateException(self);
- }
-}
-
-void VMObject::wait(VMObject* self) {
- llvm_gcroot(self, 0);
- waitIntern(self, 0, false);
-}
-
-void VMObject::timedWait(VMObject* self, struct timeval& info) {
- llvm_gcroot(self, 0);
- waitIntern(self, &info, false);
-}
-
-void VMObject::notify(VMObject* self) {
- llvm_gcroot(self, 0);
- declare_gcroot(LockObj*, l) = myLock(self);
- if (LockObj::owner(l)) {
- LockObj::notify(l);
- } else {
- VMThread::get()->getVM()->illegalMonitorStateException(self);
- }
-}
-
-void VMObject::notifyAll(VMObject* self) {
- llvm_gcroot(self, 0);
- declare_gcroot(LockObj*, l) = myLock(self);
- if (LockObj::owner(l)) {
- LockObj::notifyAll(l);
- } else {
- VMThread::get()->getVM()->illegalMonitorStateException(self);
- }
-}
-
-bool VMObject::instanceOf(VMObject* self, VMCommonClass* cl) {
- llvm_gcroot(self, 0);
- if (!self) return false;
- else return self->classOf->isAssignableFrom(cl);
-}
diff --git a/vmkit/lib/N3/VMCore/VMObject.h b/vmkit/lib/N3/VMCore/VMObject.h
deleted file mode 100644
index 5970198..0000000
--- a/vmkit/lib/N3/VMCore/VMObject.h
+++ /dev/null
@@ -1,109 +0,0 @@
-//===---------------- VMObject.h - VM object definition -------------------===//
-//
-// N3
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#ifndef N3_VM_OBJECT_H
-#define N3_VM_OBJECT_H
-
-#include <vector>
-
-#include "N3MetaType.h"
-
-#include "llvm/Constants.h"
-#include "llvm/Type.h"
-#include "llvm/ExecutionEngine/GenericValue.h"
-
-#include "mvm/Object.h"
-#include "mvm/Threads/Locks.h"
-
-#include "mvm/GC/GC.h"
-
-#include "types.h"
-
-namespace n3 {
-
-class VMCommonClass;
-class VMField;
-class VMObject;
-class VMThread;
-
-struct N3VirtualTable : VirtualTable {
- uintptr_t print;
- uintptr_t hashCode;
-
- void *operator new(size_t size, mvm::BumpPtrAllocator &allocator, size_t totalVtSize);
-
- N3VirtualTable();
- N3VirtualTable(N3VirtualTable *vmobjVt, uint32 baseVtSize, uint32 totalVtSize=-1);
- N3VirtualTable(uintptr_t d, uintptr_t o, uintptr_t t, uintptr_t p, uintptr_t h);
-
- static uint32 baseVtSize();
-};
-
-class LockObj : public mvm::Object {
-public:
- static N3VirtualTable _VT;
- mvm::LockRecursive *lock;
- std::vector<VMThread*> *threads;
-
- static LockObj* allocate();
- static void _destroy(LockObj *);
- static void _print(const LockObj *, mvm::PrintBuffer *);
-
- static void notify(LockObj*);
- static void notifyAll(LockObj*);
- static void wait(LockObj*, VMThread* th);
- static void remove(LockObj*, VMThread* th);
-
- static void aquire(LockObj*);
- static void release(LockObj*);
- static bool owner(LockObj*);
-};
-
-#define VALUE_OFFSET 3
-
-class VMObject : public mvm::Object {
-public:
- VMCommonClass* classOf;
- LockObj* lockObj;
-
- static mvm::Lock* globalLock;
- static const llvm::Type* llvmType;
-
- static void _print(const VMObject *, mvm::PrintBuffer *);
- static void _trace(VMObject *);
-
- static void aquire(VMObject *self);
- static void unlock(VMObject *self);
- static void waitIntern(VMObject *self, struct timeval *info, bool timed);
- static void wait(VMObject *self);
- static void timedWait(VMObject *self, struct timeval &info);
- static void notify(VMObject *self);
- static void notifyAll(VMObject *self);
- static void initialise(VMObject *self, VMCommonClass* cl);
-
- static llvm::Constant* classOffset();
-
- static bool instanceOf(VMObject *self, VMCommonClass* cl);
-
-
- static N3VirtualTable *getN3VirtualTable(VMObject *self) { llvm_gcroot(self, 0); return *((N3VirtualTable**)self); }
-
-#ifdef SIGSEGV_THROW_NULL
- #define verifyNull(obj) {}
-#else
- #define verifyNull(obj) \
- if (obj == 0) VMThread::get()->getVM()->nullPointerException("");
-#endif
-
-};
-
-
-} // end namespace n3
-
-#endif
diff --git a/vmkit/lib/N3/VMCore/VMThread.cpp b/vmkit/lib/N3/VMCore/VMThread.cpp
deleted file mode 100644
index 8c690b0..0000000
--- a/vmkit/lib/N3/VMCore/VMThread.cpp
+++ /dev/null
@@ -1,100 +0,0 @@
-//===------------ VMThread.cpp - VM thread description --------------------===//
-//
-// N3
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#include "llvm/Target/TargetData.h"
-
-#include "mvm/JIT.h"
-#include "mvm/PrintBuffer.h"
-#include "mvm/Threads/Locks.h"
-#include "mvm/Threads/Thread.h"
-
-#include "Assembly.h"
-#include "CLIJit.h"
-#include "N3ModuleProvider.h"
-#include "VMClass.h"
-#include "VMObject.h"
-#include "VMThread.h"
-#include "N3.h"
-
-using namespace n3;
-
-const unsigned int VMThread::StateRunning = 0;
-const unsigned int VMThread::StateWaiting = 1;
-const unsigned int VMThread::StateInterrupted = 2;
-
-void VMThread::print(mvm::PrintBuffer* buf) const {
- buf->write("Thread<>");
- declare_gcroot(VMObject *, appThread) = ooo_appThread;
- appThread->print(buf);
-}
-
-extern void AddStandardCompilePasses(llvm::FunctionPassManager*);
-
-VMThread::~VMThread() {
- delete perFunctionPasses;
-}
-
-VMThread::VMThread(VMObject* appThread, N3* vm) {
- llvm_gcroot(appThread, 0);
- this->perFunctionPasses = 0;
- this->ooo_appThread = appThread;
- this->MyVM = vm;
- this->lock = new mvm::LockNormal();
- this->varcond = new mvm::Cond();
- this->interruptFlag = 0;
- this->state = StateRunning;
- this->ooo_pendingException = 0;
- this->perFunctionPasses = new llvm::FunctionPassManager(vm->getLLVMModule());
- this->perFunctionPasses->add(new llvm::TargetData(vm->getLLVMModule()));
- AddStandardCompilePasses(this->perFunctionPasses);
-}
-
-VMObject* VMThread::currentThread() {
- VMThread* result = get();
- if (result != 0) {
- declare_gcroot(VMObject *, appThread) = result->ooo_appThread;
- return appThread;
- } else
- return 0;
-}
-
-void* VMThread::getCppException() {
- return (void*)((char*)VMThread::get()->internalPendingException - 8 * sizeof(void*));
-}
-
-VMObject* VMThread::getCLIException() {
- VMThread* th = VMThread::get();
- declare_gcroot(VMObject *, pendingException) = th->ooo_pendingException;
- return pendingException;
-}
-
-extern "C" void* __cxa_allocate_exception(unsigned);
-extern "C" void __cxa_throw(void*, void*, void*);
-
-
-void VMThread::throwException(VMObject* obj) {
- llvm_gcroot(obj, 0);
- VMThread* th = VMThread::get();
- assert(th->ooo_pendingException == 0 && "pending exception already there?");
- th->ooo_pendingException = obj;
- void* exc = __cxa_allocate_exception(0);
- th->internalPendingException = exc;
- __cxa_throw(exc, 0, 0);
-}
-
-void VMThread::internalClearException() {
- ooo_pendingException = 0;
- internalPendingException = 0;
-}
-
-bool VMThread::compareException(VMClass* cl) {
- declare_gcroot(VMObject*, pe) = VMThread::get()->ooo_pendingException;
- assert(pe && "no pending exception?");
- return pe->classOf->subclassOf(cl);
-}
diff --git a/vmkit/lib/N3/VMCore/VMThread.h b/vmkit/lib/N3/VMCore/VMThread.h
deleted file mode 100644
index 7605a30..0000000
--- a/vmkit/lib/N3/VMCore/VMThread.h
+++ /dev/null
@@ -1,76 +0,0 @@
-//===--------------- VMThread.h - VM thread description -------------------===//
-//
-// N3
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#ifndef N3_VM_THREAD_H
-#define N3_VM_THREAD_H
-
-#include <setjmp.h>
-
-#include "llvm/PassManager.h"
-
-#include "mvm/Object.h"
-#include "mvm/Threads/Cond.h"
-#include "mvm/Threads/Locks.h"
-#include "MutatorThread.h"
-
-namespace n3 {
-
-class N3;
-class VMClass;
-class VMGenericClass;
-class VMObject;
-class VMGenericMethod;
-
-class VMThread : public mvm::MutatorThread {
-public:
- VMObject* ooo_appThread;
-
- N3* getVM() {
- return (N3*)MyVM;
- }
-
- mvm::Lock* lock;
- mvm::Cond* varcond;
- VMObject* ooo_pendingException;
- void* internalPendingException;
- unsigned int interruptFlag;
- unsigned int state;
-
- static const unsigned int StateRunning;
- static const unsigned int StateWaiting;
- static const unsigned int StateInterrupted;
-
- virtual void print(mvm::PrintBuffer *buf) const;
- virtual void TRACER;
- ~VMThread();
- VMThread(VMObject *thread, N3 *vm);
-
- // Temporary solution until N3 can cleanly bootstrap itself and
- // implement threads.
- static VMThread* TheThread;
- static VMThread* get() {
- return TheThread;
- }
- static VMObject* currentThread();
-
- static VMObject* getCLIException();
- static void* getCppException();
- static void throwException(VMObject*);
- static bool compareException(VMClass*);
-
- llvm::FunctionPassManager* perFunctionPasses;
- std::vector<jmp_buf*> sjlj_buffers;
-
-private:
- virtual void internalClearException();
-};
-
-} // end namespace n3
-
-#endif
diff --git a/vmkit/lib/N3/VMCore/VirtualTables.cpp b/vmkit/lib/N3/VMCore/VirtualTables.cpp
deleted file mode 100644
index 8fd6e15..0000000
--- a/vmkit/lib/N3/VMCore/VirtualTables.cpp
+++ /dev/null
@@ -1,108 +0,0 @@
-//===----- VirtualTables.cpp - Virtual methods for N3 objects -------------===//
-//
-// N3
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#include "mvm/Object.h"
-
-#include "Assembly.h"
-#include "CLIString.h"
-#include "CLIJit.h"
-#include "LockedMap.h"
-#include "N3.h"
-#include "Reader.h"
-#include "VMArray.h"
-#include "VMCache.h"
-#include "VMClass.h"
-#include "VMObject.h"
-#include "VMThread.h"
-
-using namespace n3;
-
-extern "C" void CLIObjectTracer(VMObject* obj) {
- VMObject::_trace(obj);
-}
-
-// N3 Objects
-void VMObject::_trace(VMObject *self) {
- mvm::Collector::markAndTrace(self, &self->lockObj);
-}
-
-#define TRACE_VECTOR(type, name, alloc) { \
- for (std::vector<type, alloc<type> >::iterator i = name.begin(), e = name.end(); \
- i!= e; ++i) { \
- mvm::Collector::markAndTraceRoot(&(*i)); }}
-
-#define CALL_TRACER_VECTOR(type, name, alloc) { \
- for (std::vector<type, alloc<type> >::iterator i = name.begin(), e = name.end(); \
- i!= e; ++i) { \
- (*i)->tracer(); }}
-
-// internal objects
-void VMThread::tracer() {
- mvm::Collector::markAndTraceRoot(&ooo_appThread);
- mvm::Collector::markAndTraceRoot(&ooo_pendingException);
- // I suppose that the vm is already traced by the gc
- // vm->tracer();
-}
-
-void N3::tracer() {
- // If I understand, the gc already call trace for all VMThread
-// if (bootstrapThread) {
-// bootstrapThread->tracer();
-// for (VMThread* th = (VMThread*)bootstrapThread->next();
-// th != bootstrapThread; th = (VMThread*)th->next())
-// th->tracer();
-// }
- loadedAssemblies->tracer();
-}
-
-void Assembly::tracer() {
- loadedNameClasses->tracer();
- mvm::Collector::markAndTraceRoot(&ooo_delegatee);
-}
-
-void VMCommonClass::tracer() {
- mvm::Collector::markAndTraceRoot(&ooo_delegatee);
- CALL_TRACER_VECTOR(VMMethod*, virtualMethods, std::allocator);
- CALL_TRACER_VECTOR(VMMethod*, staticMethods, std::allocator);
- CALL_TRACER_VECTOR(Property*, properties, gc_allocator);
-}
-
-void VMClass::tracer() {
- VMCommonClass::tracer();
- mvm::Collector::markAndTraceRoot(&staticInstance);
- mvm::Collector::markAndTraceRoot(&virtualInstance);
-}
-
-void VMGenericClass::tracer() {
- VMClass::tracer();
-}
-
-void VMClassArray::tracer() {
- VMCommonClass::tracer();
-}
-
-void VMClassPointer::tracer() {
- VMCommonClass::tracer();
-}
-
-void VMMethod::tracer() {
- mvm::Collector::markAndTraceRoot(&ooo_delegatee);
-}
-
-void VMGenericMethod::tracer() {
- VMMethod::tracer();
-}
-
-void Property::tracer() {
- mvm::Collector::markAndTraceRoot(&ooo_delegatee);
-}
-
-// useless (never called or used) but it simplifies the definition of LockedMap
-void VMField::tracer() {
-}
diff --git a/vmkit/mmtk/LICENSE.html b/vmkit/mmtk/LICENSE.html
deleted file mode 100644
index e8a73dc..0000000
--- a/vmkit/mmtk/LICENSE.html
+++ /dev/null
@@ -1,285 +0,0 @@
-<?xml version="1.0" encoding="ISO-8859-1" ?>
-<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
-<html xmlns="http://www.w3.org/1999/xhtml">
-
-<head>
-<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
-<title>License Information</title>
-<style type="text/css">
- body {
- size: 8.5in 11.0in;
- margin: 0.25in 0.5in 0.25in 0.5in;
- tab-interval: 0.5in;
- }
- p {
- margin-left: auto;
- margin-top: 0.5em;
- margin-bottom: 0.5em;
- }
- p.list {
- margin-left: 0.5in;
- margin-top: 0.05em;
- margin-bottom: 0.05em;
- }
- </style>
-
-</head>
-
-<body lang="EN-US">
-
-<h2>General Information</h2>
-
-<p>Jikes RVM is free, open source software, distributed and freely
-redistributable under the Eclipse Public License (EPL). The EPL has
-been certified by the Open Source Initiative as an open source
-license. The EPL meets the Debian Free Software Guidelines.</p>
-
-<p>Note: some code in the libraryInterface tree is distributed under
-other open source licenses. See the various LICENSE files in that
-tree for details.</p>
-
-<p>Note: some code in the external tree is distributed under
-other open source licenses. See the various LICENSE files in that
-tree for details.</p>
-
-<p>Note: rvm/src-generated/opt-burs/jburg contains a tool, jburg,
-which was derived from iburg and is not distributed under the EPL.
-See rvm/src-generated/opt-burs/jburg/LICENSE for details.</p>
-
-<p>The legal text of the Eclipse Public License is appended below for
-reference</p>
-
-<hline>
-
-<h2>Eclipse Public License - v 1.0</h2>
-
-<p>THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE
-PUBLIC LICENSE ("AGREEMENT"). ANY USE, REPRODUCTION OR
-DISTRIBUTION OF THE PROGRAM CONSTITUTES RECIPIENT'S ACCEPTANCE OF THIS
-AGREEMENT.</p>
-
-<p><b>1. DEFINITIONS</b></p>
-
-<p>"Contribution" means:</p>
-
-<p class="list">a) in the case of the initial Contributor, the initial
-code and documentation distributed under this Agreement, and</p>
-<p class="list">b) in the case of each subsequent Contributor:</p>
-<p class="list">i) changes to the Program, and</p>
-<p class="list">ii) additions to the Program;</p>
-<p class="list">where such changes and/or additions to the Program
-originate from and are distributed by that particular Contributor. A
-Contribution 'originates' from a Contributor if it was added to the
-Program by such Contributor itself or anyone acting on such
-Contributor's behalf. Contributions do not include additions to the
-Program which: (i) are separate modules of software distributed in
-conjunction with the Program under their own license agreement, and (ii)
-are not derivative works of the Program.</p>
-
-<p>"Contributor" means any person or entity that distributes
-the Program.</p>
-
-<p>"Licensed Patents" mean patent claims licensable by a
-Contributor which are necessarily infringed by the use or sale of its
-Contribution alone or when combined with the Program.</p>
-
-<p>"Program" means the Contributions distributed in accordance
-with this Agreement.</p>
-
-<p>"Recipient" means anyone who receives the Program under
-this Agreement, including all Contributors.</p>
-
-<p><b>2. GRANT OF RIGHTS</b></p>
-
-<p class="list">a) Subject to the terms of this Agreement, each
-Contributor hereby grants Recipient a non-exclusive, worldwide,
-royalty-free copyright license to reproduce, prepare derivative works
-of, publicly display, publicly perform, distribute and sublicense the
-Contribution of such Contributor, if any, and such derivative works, in
-source code and object code form.</p>
-
-<p class="list">b) Subject to the terms of this Agreement, each
-Contributor hereby grants Recipient a non-exclusive, worldwide,
-royalty-free patent license under Licensed Patents to make, use, sell,
-offer to sell, import and otherwise transfer the Contribution of such
-Contributor, if any, in source code and object code form. This patent
-license shall apply to the combination of the Contribution and the
-Program if, at the time the Contribution is added by the Contributor,
-such addition of the Contribution causes such combination to be covered
-by the Licensed Patents. The patent license shall not apply to any other
-combinations which include the Contribution. No hardware per se is
-licensed hereunder.</p>
-
-<p class="list">c) Recipient understands that although each Contributor
-grants the licenses to its Contributions set forth herein, no assurances
-are provided by any Contributor that the Program does not infringe the
-patent or other intellectual property rights of any other entity. Each
-Contributor disclaims any liability to Recipient for claims brought by
-any other entity based on infringement of intellectual property rights
-or otherwise. As a condition to exercising the rights and licenses
-granted hereunder, each Recipient hereby assumes sole responsibility to
-secure any other intellectual property rights needed, if any. For
-example, if a third party patent license is required to allow Recipient
-to distribute the Program, it is Recipient's responsibility to acquire
-that license before distributing the Program.</p>
-
-<p class="list">d) Each Contributor represents that to its knowledge it
-has sufficient copyright rights in its Contribution, if any, to grant
-the copyright license set forth in this Agreement.</p>
-
-<p><b>3. REQUIREMENTS</b></p>
-
-<p>A Contributor may choose to distribute the Program in object code
-form under its own license agreement, provided that:</p>
-
-<p class="list">a) it complies with the terms and conditions of this
-Agreement; and</p>
-
-<p class="list">b) its license agreement:</p>
-
-<p class="list">i) effectively disclaims on behalf of all Contributors
-all warranties and conditions, express and implied, including warranties
-or conditions of title and non-infringement, and implied warranties or
-conditions of merchantability and fitness for a particular purpose;</p>
-
-<p class="list">ii) effectively excludes on behalf of all Contributors
-all liability for damages, including direct, indirect, special,
-incidental and consequential damages, such as lost profits;</p>
-
-<p class="list">iii) states that any provisions which differ from this
-Agreement are offered by that Contributor alone and not by any other
-party; and</p>
-
-<p class="list">iv) states that source code for the Program is available
-from such Contributor, and informs licensees how to obtain it in a
-reasonable manner on or through a medium customarily used for software
-exchange.</p>
-
-<p>When the Program is made available in source code form:</p>
-
-<p class="list">a) it must be made available under this Agreement; and</p>
-
-<p class="list">b) a copy of this Agreement must be included with each
-copy of the Program.</p>
-
-<p>Contributors may not remove or alter any copyright notices contained
-within the Program.</p>
-
-<p>Each Contributor must identify itself as the originator of its
-Contribution, if any, in a manner that reasonably allows subsequent
-Recipients to identify the originator of the Contribution.</p>
-
-<p><b>4. COMMERCIAL DISTRIBUTION</b></p>
-
-<p>Commercial distributors of software may accept certain
-responsibilities with respect to end users, business partners and the
-like. While this license is intended to facilitate the commercial use of
-the Program, the Contributor who includes the Program in a commercial
-product offering should do so in a manner which does not create
-potential liability for other Contributors. Therefore, if a Contributor
-includes the Program in a commercial product offering, such Contributor
-("Commercial Contributor") hereby agrees to defend and
-indemnify every other Contributor ("Indemnified Contributor")
-against any losses, damages and costs (collectively "Losses")
-arising from claims, lawsuits and other legal actions brought by a third
-party against the Indemnified Contributor to the extent caused by the
-acts or omissions of such Commercial Contributor in connection with its
-distribution of the Program in a commercial product offering. The
-obligations in this section do not apply to any claims or Losses
-relating to any actual or alleged intellectual property infringement. In
-order to qualify, an Indemnified Contributor must: a) promptly notify
-the Commercial Contributor in writing of such claim, and b) allow the
-Commercial Contributor to control, and cooperate with the Commercial
-Contributor in, the defense and any related settlement negotiations. The
-Indemnified Contributor may participate in any such claim at its own
-expense.</p>
-
-<p>For example, a Contributor might include the Program in a commercial
-product offering, Product X. That Contributor is then a Commercial
-Contributor. If that Commercial Contributor then makes performance
-claims, or offers warranties related to Product X, those performance
-claims and warranties are such Commercial Contributor's responsibility
-alone. Under this section, the Commercial Contributor would have to
-defend claims against the other Contributors related to those
-performance claims and warranties, and if a court requires any other
-Contributor to pay any damages as a result, the Commercial Contributor
-must pay those damages.</p>
-
-<p><b>5. NO WARRANTY</b></p>
-
-<p>EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, THE PROGRAM IS
-PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS
-OF ANY KIND, EITHER EXPRESS OR IMPLIED INCLUDING, WITHOUT LIMITATION,
-ANY WARRANTIES OR CONDITIONS OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY
-OR FITNESS FOR A PARTICULAR PURPOSE. Each Recipient is solely
-responsible for determining the appropriateness of using and
-distributing the Program and assumes all risks associated with its
-exercise of rights under this Agreement , including but not limited to
-the risks and costs of program errors, compliance with applicable laws,
-damage to or loss of data, programs or equipment, and unavailability or
-interruption of operations.</p>
-
-<p><b>6. DISCLAIMER OF LIABILITY</b></p>
-
-<p>EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, NEITHER RECIPIENT
-NOR ANY CONTRIBUTORS SHALL HAVE ANY LIABILITY FOR ANY DIRECT, INDIRECT,
-INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING
-WITHOUT LIMITATION LOST PROFITS), HOWEVER CAUSED AND ON ANY THEORY OF
-LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
-NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OR
-DISTRIBUTION OF THE PROGRAM OR THE EXERCISE OF ANY RIGHTS GRANTED
-HEREUNDER, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.</p>
-
-<p><b>7. GENERAL</b></p>
-
-<p>If any provision of this Agreement is invalid or unenforceable under
-applicable law, it shall not affect the validity or enforceability of
-the remainder of the terms of this Agreement, and without further action
-by the parties hereto, such provision shall be reformed to the minimum
-extent necessary to make such provision valid and enforceable.</p>
-
-<p>If Recipient institutes patent litigation against any entity
-(including a cross-claim or counterclaim in a lawsuit) alleging that the
-Program itself (excluding combinations of the Program with other
-software or hardware) infringes such Recipient's patent(s), then such
-Recipient's rights granted under Section 2(b) shall terminate as of the
-date such litigation is filed.</p>
-
-<p>All Recipient's rights under this Agreement shall terminate if it
-fails to comply with any of the material terms or conditions of this
-Agreement and does not cure such failure in a reasonable period of time
-after becoming aware of such noncompliance. If all Recipient's rights
-under this Agreement terminate, Recipient agrees to cease use and
-distribution of the Program as soon as reasonably practicable. However,
-Recipient's obligations under this Agreement and any licenses granted by
-Recipient relating to the Program shall continue and survive.</p>
-
-<p>Everyone is permitted to copy and distribute copies of this
-Agreement, but in order to avoid inconsistency the Agreement is
-copyrighted and may only be modified in the following manner. The
-Agreement Steward reserves the right to publish new versions (including
-revisions) of this Agreement from time to time. No one other than the
-Agreement Steward has the right to modify this Agreement. The Eclipse
-Foundation is the initial Agreement Steward. The Eclipse Foundation may
-assign the responsibility to serve as the Agreement Steward to a
-suitable separate entity. Each new version of the Agreement will be
-given a distinguishing version number. The Program (including
-Contributions) may always be distributed subject to the version of the
-Agreement under which it was received. In addition, after a new version
-of the Agreement is published, Contributor may elect to distribute the
-Program (including its Contributions) under the new version. Except as
-expressly stated in Sections 2(a) and 2(b) above, Recipient receives no
-rights or licenses to the intellectual property of any Contributor under
-this Agreement, whether expressly, by implication, estoppel or
-otherwise. All rights in the Program not expressly granted under this
-Agreement are reserved.</p>
-
-<p>This Agreement is governed by the laws of the State of New York and
-the intellectual property laws of the United States of America. No party
-to this Agreement will bring a legal action under this Agreement more
-than one year after the cause of action arose. Each party waives its
-rights to a jury trial in any resulting litigation.</p>
-
-</body>
-
-</html>
\ No newline at end of file
diff --git a/vmkit/mmtk/Makefile b/vmkit/mmtk/Makefile
deleted file mode 100644
index f23cf70..0000000
--- a/vmkit/mmtk/Makefile
+++ /dev/null
@@ -1,17 +0,0 @@
-##===- mmtk/Makefile ---------------------------------------*- Makefile -*-===##
-#
-# The vmkit project
-#
-# This file is distributed under the University of Illinois Open Source
-# License. See LICENSE.TXT for details.
-#
-##===----------------------------------------------------------------------===##
-LEVEL = ..
-
-DIRS = magic mmtk-j3 mmtk-alloc java inline
-EXTRA_DIST = config/marksweep
-
-include $(LEVEL)/Makefile.config
-
-include $(LEVEL)/Makefile.common
-
diff --git a/vmkit/mmtk/config/copyms/MMTkInline.inc b/vmkit/mmtk/config/copyms/MMTkInline.inc
deleted file mode 100644
index 43347d3..0000000
--- a/vmkit/mmtk/config/copyms/MMTkInline.inc
+++ /dev/null
@@ -1,6 +0,0 @@
-// Generated by llvm2cpp - DO NOT MODIFY!
-
-
-Function* makeLLVMFunction(Module *mod) {
-return 0;
-}
diff --git a/vmkit/mmtk/config/copyms/ObjectHeader.h b/vmkit/mmtk/config/copyms/ObjectHeader.h
deleted file mode 100644
index 6b38b0b..0000000
--- a/vmkit/mmtk/config/copyms/ObjectHeader.h
+++ /dev/null
@@ -1,20 +0,0 @@
-//===----- ObjectHeader.h - Macros for describing an object header --------===//
-//
-// The VMKit project
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#ifndef MVM_OBJECT_HEADER_H
-#define MVM_OBJECT_HEADER_H
-
-#include <stdint.h>
-
-namespace mvm {
- static const uint32_t GCBits = 8;
- static const bool MovesObject = true;
-}
-
-#endif // MVM_OBJECT_HEADER_H
diff --git a/vmkit/mmtk/config/marksweep/MMTkInline.inc b/vmkit/mmtk/config/marksweep/MMTkInline.inc
deleted file mode 100644
index 5ca17ea..0000000
--- a/vmkit/mmtk/config/marksweep/MMTkInline.inc
+++ /dev/null
@@ -1,6 +0,0 @@
-// Generated by llvm2cpp - DO NOT MODIFY!
-
-
-Function* makeLLVMFunction(Module *mod) {
- return 0;
-}
diff --git a/vmkit/mmtk/config/marksweep/ObjectHeader.h b/vmkit/mmtk/config/marksweep/ObjectHeader.h
deleted file mode 100644
index b33cc39..0000000
--- a/vmkit/mmtk/config/marksweep/ObjectHeader.h
+++ /dev/null
@@ -1,20 +0,0 @@
-//===----- ObjectHeader.h - Macros for describing an object header --------===//
-//
-// The VMKit project
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#ifndef MVM_OBJECT_HEADER_H
-#define MVM_OBJECT_HEADER_H
-
-#include <stdint.h>
-
-namespace mvm {
- static const uint32_t GCBits = 8;
- static const bool MovesObject = false;
-}
-
-#endif // MVM_OBJECT_HEADER_H
diff --git a/vmkit/mmtk/inline/InlineMethods.cpp b/vmkit/mmtk/inline/InlineMethods.cpp
deleted file mode 100644
index cff06fe..0000000
--- a/vmkit/mmtk/inline/InlineMethods.cpp
+++ /dev/null
@@ -1,30 +0,0 @@
-//===-------- InlineMethods.cpp - Initialize the inline methods -----------===//
-//
-// The VMKit project
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#include <llvm/CallingConv.h>
-#include <llvm/Constants.h>
-#include <llvm/DerivedTypes.h>
-#include <llvm/Instructions.h>
-#include <llvm/LLVMContext.h>
-#include <llvm/Module.h>
-#include <llvm/Type.h>
-
-using namespace llvm;
-
-namespace mmtk {
-
-namespace mmtk_runtime {
- #include "MMTkInline.inc"
-}
-
-extern "C" void MMTk_InlineMethods(llvm::Module* module) {
- mmtk_runtime::makeLLVMFunction(module);
-}
-
-}
diff --git a/vmkit/mmtk/inline/Makefile b/vmkit/mmtk/inline/Makefile
deleted file mode 100644
index 4da4f06..0000000
--- a/vmkit/mmtk/inline/Makefile
+++ /dev/null
@@ -1,16 +0,0 @@
-##===- lib/Mvm/CommonThread/Makefile -----------------------*- Makefile -*-===##
-#
-# The vmkit project
-#
-# This file is distributed under the University of Illinois Open Source
-# License. See LICENSE.TXT for details.
-#
-##===----------------------------------------------------------------------===##
-LEVEL = ../..
-
-include $(LEVEL)/Makefile.config
-
-MODULE_NAME = InlineMMTk
-
-include $(LEVEL)/Makefile.common
-
diff --git a/vmkit/mmtk/java/Makefile b/vmkit/mmtk/java/Makefile
deleted file mode 100644
index 979a36b..0000000
--- a/vmkit/mmtk/java/Makefile
+++ /dev/null
@@ -1,17 +0,0 @@
-##===- mmtk/java/Makefile ----------------------------------*- Makefile -*-===##
-#
-# The vmkit project
-#
-# This file is distributed under the University of Illinois Open Source
-# License. See LICENSE.TXT for details.
-#
-##===----------------------------------------------------------------------===##
-LEVEL = ../..
-
-include $(LEVEL)/Makefile.config
-
-RUN_ANT = 1
-JARNAME = mmtk-vmkit
-EXTRA_DIST = vmkit.properties build.xml.in src
-
-include $(LEVEL)/Makefile.common
diff --git a/vmkit/mmtk/java/build.xml b/vmkit/mmtk/java/build.xml
deleted file mode 100644
index a5cd6c3..0000000
--- a/vmkit/mmtk/java/build.xml
+++ /dev/null
@@ -1,9 +0,0 @@
-<project name="MMTK-VMKit" default="main" basedir=".">
- <target name="main">
- <mkdir dir="classes"/>
- <javac srcdir="src" destdir="classes" source="1.5"/>
- <jar jarfile="mmtk-vmkit.jar">
- <fileset dir="classes"/>
- </jar>
- </target>
-</project>
diff --git a/vmkit/mmtk/java/src/org/j3/bindings/Bindings.java b/vmkit/mmtk/java/src/org/j3/bindings/Bindings.java
deleted file mode 100644
index ef3da8e..0000000
--- a/vmkit/mmtk/java/src/org/j3/bindings/Bindings.java
+++ /dev/null
@@ -1,117 +0,0 @@
-//===-------------------------- Bindings.java -----------------------------===//
-//
-// The VMKit project
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-package org.j3.bindings;
-
-import org.j3.config.Selected;
-import org.mmtk.plan.MutatorContext;
-import org.mmtk.plan.Plan;
-import org.mmtk.plan.TraceLocal;
-import org.mmtk.plan.TransitiveClosure;
-import org.mmtk.utility.heap.HeapGrowthManager;
-import org.vmmagic.pragma.Inline;
-import org.vmmagic.unboxed.Address;
-import org.vmmagic.unboxed.Extent;
-import org.vmmagic.unboxed.ObjectReference;
-
-public final class Bindings {
- @Inline
- private static Address gcmalloc(int size, ObjectReference virtualTable) {
- Selected.Mutator mutator = Selected.Mutator.get();
- int allocator = mutator.checkAllocator(size, 0, 0);
- Address res = mutator.alloc(size, 0, 0, allocator, 0);
- res.store(virtualTable);
- mutator.postAlloc(res.toObjectReference(), virtualTable, size, allocator);
- return res;
- }
-
- @Inline
- private static boolean isLive(TraceLocal closure, ObjectReference obj) {
- return closure.isLive(obj);
- }
-
- @Inline
- private static void reportDelayedRootEdge(TraceLocal closure, Address obj) {
- closure.reportDelayedRootEdge(obj);
- }
-
- @Inline
- private static void processRootEdge(TraceLocal closure, Address obj, boolean traced) {
- closure.processRootEdge(obj, traced);
- }
-
- @Inline
- private static ObjectReference retainForFinalize(TraceLocal closure, ObjectReference obj) {
- return closure.retainForFinalize(obj);
- }
-
- @Inline
- private static ObjectReference retainReferent(TraceLocal closure, ObjectReference obj) {
- return closure.retainReferent(obj);
- }
-
- @Inline
- private static ObjectReference getForwardedReference(TraceLocal closure, ObjectReference obj) {
- return closure.getForwardedReference(obj);
- }
-
- @Inline
- private static ObjectReference getForwardedReferent(TraceLocal closure, ObjectReference obj) {
- return closure.getForwardedReferent(obj);
- }
-
- @Inline
- private static ObjectReference getForwardedFinalizable(TraceLocal closure, ObjectReference obj) {
- return closure.getForwardedFinalizable(obj);
- }
-
- @Inline
- private static void processEdge(TransitiveClosure closure, ObjectReference source, Address slot) {
- closure.processEdge(source, slot);
- }
-
- @Inline
- private static MutatorContext allocateMutator(int id) {
- Selected.Mutator mutator = new Selected.Mutator();
- mutator.initMutator(id);
- return mutator;
- }
-
- @Inline
- private static void freeMutator(MutatorContext mutator) {
- mutator.deinitMutator();
- }
-
- @Inline
- private static void boot(Extent minSize, Extent maxSize) {
- HeapGrowthManager.boot(minSize, maxSize);
- Plan plan = Selected.Plan.get();
- plan.boot();
- plan.postBoot();
- plan.fullyBooted();
- }
-
- @Inline
- private static Address copy(ObjectReference from,
- ObjectReference virtualTable,
- int size,
- int allocator) {
- Selected.Collector plan = Selected.Collector.get();
- allocator = plan.copyCheckAllocator(from, size, 0, allocator);
- Address to = plan.allocCopy(from, size, 0, 0, allocator);
- memcpy(to.toObjectReference(), from, size);
- plan.postCopy(to.toObjectReference(), virtualTable, size, allocator);
- return to;
- }
-
- @Inline
- private static native void memcpy(
- ObjectReference to, ObjectReference from, int size);
-
-}
diff --git a/vmkit/mmtk/java/src/org/j3/config/Selected.java.in b/vmkit/mmtk/java/src/org/j3/config/Selected.java.in
deleted file mode 100644
index e64ecd0..0000000
--- a/vmkit/mmtk/java/src/org/j3/config/Selected.java.in
+++ /dev/null
@@ -1,66 +0,0 @@
-//===------------------------- Selected.java ------------------------------===//
-//
-// The VMKit project
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-package org.j3.config;
-
-import org.mmtk.utility.Log;
-
-import org.vmmagic.pragma.*;
-
-public class Selected {
- public static final String name = "@MMTK_PLAN@";
- @Uninterruptible
- public static final class Plan extends @MMTK_PLAN@
- {
- private static final Plan plan = new Plan();
-
- @Inline
- public static Plan get() { return plan; }
- }
-
- @Uninterruptible
- public static final class Constraints extends @MMTK_PLAN@Constraints
- {
- private static final Constraints constraints = new Constraints();
-
- @Inline
- public static Constraints get() { return constraints; }
- }
-
- @Uninterruptible
- public static class Collector extends @MMTK_PLAN@Collector
- {
- private static final Collector bootstrapCollector = new Collector();
-
- public static void staticCollect() {
- bootstrapCollector.collect();
- }
-
- public Collector() {}
- @Inline
- public static Collector get() {
- return bootstrapCollector;
- }
- }
-
- @Uninterruptible
- public static class Mutator extends @MMTK_PLAN@Mutator
- {
-
- // Unused mutator used by the AOT compiler to know what instances
- // will be alive during MMTk execution. This allows to inline
- // virtual calls of singleton objects.
- private static final Mutator unusedMutator = new Mutator();
-
- public Mutator() {}
-
- @Inline
- public static native Mutator get();
- }
-}
diff --git a/vmkit/mmtk/java/src/org/j3/mmtk/ActivePlan.java b/vmkit/mmtk/java/src/org/j3/mmtk/ActivePlan.java
deleted file mode 100644
index 65f526e..0000000
--- a/vmkit/mmtk/java/src/org/j3/mmtk/ActivePlan.java
+++ /dev/null
@@ -1,72 +0,0 @@
-//===---------------- ActivePlan.java - Plan for J3 -----------------------===//
-//
-// The VMKit project
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-package org.j3.mmtk;
-
-
-import org.mmtk.plan.Plan;
-import org.mmtk.plan.CollectorContext;
-import org.mmtk.plan.MutatorContext;
-import org.mmtk.plan.PlanConstraints;
-import org.mmtk.utility.Log;
-
-import org.j3.config.Selected;
-
-import org.vmmagic.pragma.*;
-
-public final class ActivePlan extends org.mmtk.vm.ActivePlan {
-
- Object currentThread = null;
-
- /** @return The active Plan instance. */
- @Inline
- public Plan global() {
- return Selected.Plan.get();
- }
-
- /** @return The active PlanConstraints instance. */
- @Inline
- public PlanConstraints constraints() {
- return Selected.Constraints.get();
- }
-
- /** @return The number of registered CollectorContext instances. */
- @Inline
- public native int collectorCount();
-
- /** @return The active CollectorContext instance. */
- @Inline
- public CollectorContext collector() {
- return Selected.Collector.get();
- }
-
- /** @return The active MutatorContext instance. */
- @Inline
- public MutatorContext mutator() {
- return Selected.Mutator.get();
- }
-
- /** @return The log for the active thread */
- public Log log() {
- return Selected.Mutator.get().getLog();
- }
-
- /** Reset the mutator iterator */
- public native void resetMutatorIterator();
-
- /**
- * Return the next <code>MutatorContext</code> in a
- * synchronized iteration of all mutators.
- *
- * @return The next <code>MutatorContext</code> in a
- * synchronized iteration of all mutators, or
- * <code>null</code> when all mutators have been done.
- */
- public native MutatorContext getNextMutator();
-}
diff --git a/vmkit/mmtk/java/src/org/j3/mmtk/Assert.java b/vmkit/mmtk/java/src/org/j3/mmtk/Assert.java
deleted file mode 100644
index 653ed40..0000000
--- a/vmkit/mmtk/java/src/org/j3/mmtk/Assert.java
+++ /dev/null
@@ -1,92 +0,0 @@
-//===--------------------------- Assert.java ------------------------------===//
-//
-// The VMKit project
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-
-package org.j3.mmtk;
-
-import org.mmtk.policy.Space;
-import org.vmmagic.pragma.*;
-import org.j3.runtime.VM;
-
-@Uninterruptible
-public final class Assert extends org.mmtk.vm.Assert {
-
- /**
- * <code>true</code> if assertions should be verified
- */
- protected final boolean getVerifyAssertionsConstant() {
- return VM.VerifyAssertions;
- }
-
- /**
- * This method should be called whenever an error is encountered.
- *
- * @param str A string describing the error condition.
- */
- public final void error(String str) {
- Space.printUsagePages();
- Space.printUsageMB();
- fail(str);
- }
-
- /**
- * Logs a message and traceback, then exits.
- *
- * @param message the string to log
- */
- public final void fail(String message) {
- VM.sysFail(message);
- }
-
- @Uninterruptible
- public final void exit(int rc) {
- VM.sysExit(rc);
- }
-
- /**
- * Checks that the given condition is true. If it is not, this
- * method does a traceback and exits. All calls to this method
- * must be guarded by <code>VM.VERIFY_ASSERTIONS</code>.
- *
- * @param cond the condition to be checked
- */
- @Inline(value=Inline.When.AllArgumentsAreConstant)
- public final void _assert(boolean cond) {
- if (!org.mmtk.vm.VM.VERIFY_ASSERTIONS)
- VM.sysFail("All assertions must be guarded by VM.VERIFY_ASSERTIONS: please check the failing assertion");
- VM._assert(cond);
- }
-
- /**
- * Checks that the given condition is true. If it is not, this
- * method prints a message, does a traceback and exits. All calls
- * to this method must be guarded by <code>VM.VERIFY_ASSERTIONS</code>.
- *
- * @param cond the condition to be checked
- * @param message the message to print
- */
- @Inline(value=Inline.When.ArgumentsAreConstant, arguments={1})
- public final void _assert(boolean cond, String message) {
- if (!org.mmtk.vm.VM.VERIFY_ASSERTIONS)
- VM.sysFail("All assertions must be guarded by VM.VERIFY_ASSERTIONS: please check the failing assertion");
- if (!cond) VM.sysWriteln(message);
- VM._assert(cond);
- }
-
- public native final void dumpStack();
-
- /**
- * Checks if the virtual machine is running. This value changes, so
- * the call-through to the VM must be a method.
- *
- * @return <code>true</code> if the virtual machine is running
- */
- public final boolean runningVM() { return VM.runningVM; }
-
-}
diff --git a/vmkit/mmtk/java/src/org/j3/mmtk/Barriers.java b/vmkit/mmtk/java/src/org/j3/mmtk/Barriers.java
deleted file mode 100644
index 5bdf6ac..0000000
--- a/vmkit/mmtk/java/src/org/j3/mmtk/Barriers.java
+++ /dev/null
@@ -1,607 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.j3.mmtk;
-
-import org.jikesrvm.SizeConstants;
-import org.jikesrvm.Magic;
-import org.mmtk.vm.VM;
-
-import org.vmmagic.unboxed.*;
-import org.vmmagic.pragma.*;
-
-@Uninterruptible
-public class Barriers extends org.mmtk.vm.Barriers implements SizeConstants {
- /**
- * Perform the actual write of a boolean write barrier.
- *
- * @param objref The object that has the boolean field
- * @param value The value that the slot will be updated to
- * @param offset The offset from the ref
- * @param location The FieldReference index to assist the store
- * @param mode The context in which the write is occurring
- */
- @Inline
- @Override
- public final void booleanWrite(ObjectReference objref, boolean value, Word offset, Word location, int mode) {
- Magic.setBooleanAtOffset(objref.toObject(), offset.toOffset(), value, location.toInt());
- }
-
- /**
- * Perform the actual read of a boolean read barrier.
- *
- * @param objref The object that has the boolean field
- * @param offset The offset from the ref
- * @param unused Unused
- * @param mode The context in which the write is occurring
- * @return the read value
- */
- @Inline
- @Override
- public final boolean booleanRead(ObjectReference objref, Word offset, Word location, int mode) {
- return Magic.getByteAtOffset(objref.toObject(), offset.toOffset()) == 0;
- }
-
- /**
- * Perform the actual write of a byte write barrier.
- *
- * @param objref The object that has the byte field
- * @param value The value that the slot will be updated to
- * @param offset The offset from the ref
- * @param location The FieldReference index to assist the store
- * @param mode The context in which the write is occurring
- */
- @Inline
- @Override
- public final void byteWrite(ObjectReference objref, byte value, Word offset, Word location, int mode) {
- Magic.setByteAtOffset(objref.toObject(), offset.toOffset(), value, location.toInt());
- }
-
- /**
- * Perform the actual read of a byte read barrier.
- *
- * @param objref The object that has the byte field
- * @param offset The offset from the ref
- * @param unused Unused
- * @param mode The context in which the write is occurring
- * @return the read value
- */
- @Inline
- @Override
- public final byte byteRead(ObjectReference objref, Word offset, Word location, int mode) {
- return Magic.getByteAtOffset(objref.toObject(), offset.toOffset());
- }
-
- /**
- * Perform the actual write of a char write barrier.
- *
- * @param objref The object that has the char field
- * @param value The value that the slot will be updated to
- * @param offset The offset from the ref
- * @param location The FieldReference index to assist the store
- * @param mode The context in which the write is occurring
- */
- @Inline
- @Override
- public final void charWrite(ObjectReference objref, char value, Word offset, Word location, int mode) {
- Magic.setCharAtOffset(objref.toObject(), offset.toOffset(), value, location.toInt());
- }
-
- /**
- * Perform the actual read of a char read barrier.
- *
- * @param objref The object that has the char field
- * @param offset The offset from the ref
- * @param unused Unused
- * @param mode The context in which the write is occurring
- * @return the read value
- */
- @Inline
- @Override
- public final char charRead(ObjectReference objref, Word offset, Word location, int mode) {
- return Magic.getCharAtOffset(objref.toObject(), offset.toOffset());
- }
-
- /**
- * Perform the actual write of a short write barrier.
- *
- * @param objref The object that has the short field
- * @param value The value that the slot will be updated to
- * @param offset The offset from the ref
- * @param location The FieldReference index to assist the store
- * @param mode The context in which the write is occurring
- */
- @Inline
- @Override
- public final void shortWrite(ObjectReference objref, short value, Word offset, Word location, int mode) {
- Magic.setShortAtOffset(objref.toObject(), offset.toOffset(), value, location.toInt());
- }
-
- /**
- * Perform the actual read of a short read barrier.
- *
- * @param objref The object that has the short field
- * @param offset The offset from the ref
- * @param unused Unused
- * @param mode The context in which the write is occurring
- * @return the read value
- */
- @Inline
- @Override
- public final short shortRead(ObjectReference objref, Word offset, Word location, int mode) {
- return Magic.getShortAtOffset(objref.toObject(), offset.toOffset());
- }
-
- /**
- * Perform the actual write of a int write barrier.
- *
- * @param objref The object that has the int field
- * @param value The value that the slot will be updated to
- * @param offset The offset from the ref
- * @param location The FieldReference index to assist the store
- * @param mode The context in which the write is occurring
- */
- @Inline
- @Override
- public final void intWrite(ObjectReference objref, int value, Word offset, Word location, int mode) {
- Magic.setIntAtOffset(objref.toObject(), offset.toOffset(), value, location.toInt());
- }
-
- /**
- * Perform the actual read of a int read barrier.
- *
- * @param objref The object that has the int field
- * @param offset The offset from the ref
- * @param unused Unused
- * @param mode The context in which the write is occurring
- * @return the read value
- */
- @Inline
- @Override
- public final int intRead(ObjectReference objref, Word offset, Word location, int mode) {
- return Magic.getIntAtOffset(objref.toObject(), offset.toOffset());
- }
-
- /**
- * Attempt an atomic compare and exchange in a write barrier sequence.
- *
- * @param objref The object that has the int field
- * @param expected The old int to be swapped out
- * @param newValue the new int
- * @param offset The offset from the ref
- * @param unused Unused
- * @param mode The context in which the write is occurring
- * @return True if the compare and swap was successful
- */
- @Override
- public boolean intTryCompareAndSwap(ObjectReference objref, int expected, int newValue, Word offset, Word unused, int mode) {
- int oldValue;
- do {
- oldValue = Magic.prepareInt(objref, offset.toOffset());
- if (oldValue != expected) return false;
- } while (!Magic.attemptInt(objref, offset.toOffset(), oldValue, newValue));
- return true;
- }
-
- /**
- * Perform the actual write of a long write barrier.
- *
- * @param objref The object that has the long field
- * @param value The value that the slot will be updated to
- * @param offset The offset from the ref
- * @param location The FieldReference index to assist the store
- * @param mode The context in which the write is occurring
- */
- @Inline
- @Override
- public final void longWrite(ObjectReference objref, long value, Word offset, Word location, int mode) {
- Magic.setLongAtOffset(objref.toObject(), offset.toOffset(), value, location.toInt());
- }
-
- /**
- * Perform the actual read of a long read barrier.
- *
- * @param objref The object that has the long field
- * @param offset The offset from the ref
- * @param unused Unused
- * @param mode The context in which the write is occurring
- * @return the read value
- */
- @Inline
- @Override
- public final long longRead(ObjectReference objref, Word offset, Word location, int mode) {
- return Magic.getLongAtOffset(objref.toObject(), offset.toOffset());
- }
-
- /**
- * Attempt an atomic compare and exchange in a write barrier sequence.
- *
- * @param objref The object that has the long field
- * @param expected The old long to be swapped out
- * @param newValue the new long
- * @param offset The offset from the ref
- * @param unused Unused
- * @param mode The context in which the write is occurring
- * @return True if the compare and swap was successful
- */
- @Override
- public boolean longTryCompareAndSwap(ObjectReference objref, long expected, long newValue, Word offset, Word unused, int mode) {
- long oldValue;
- do {
- oldValue = Magic.prepareLong(objref, offset.toOffset());
- if (oldValue != expected) return false;
- } while (!Magic.attemptLong(objref, offset.toOffset(), oldValue, newValue));
- return true;
- }
-
- /**
- * Perform the actual write of a float write barrier.
- *
- * @param objref The object that has the float field
- * @param value The value that the slot will be updated to
- * @param offset The offset from the ref
- * @param location The FieldReference index to assist the store
- * @param mode The context in which the write is occurring
- */
- @Inline
- @Override
- public final void floatWrite(ObjectReference objref, float value, Word offset, Word location, int mode) {
- Magic.setFloatAtOffset(objref.toObject(), offset.toOffset(), value, location.toInt());
- }
-
- /**
- * Perform the actual read of a float read barrier.
- *
- * @param objref The object that has the float field
- * @param offset The offset from the ref
- * @param unused Unused
- * @param mode The context in which the write is occurring
- * @return the read value
- */
- @Inline
- @Override
- public final float floatRead(ObjectReference objref, Word offset, Word location, int mode) {
- return Magic.getFloatAtOffset(objref.toObject(), offset.toOffset());
- }
-
- /**
- * Perform the actual write of a double write barrier.
- *
- * @param objref The object that has the double field
- * @param value The value that the slot will be updated to
- * @param offset The offset from the ref
- * @param location The FieldReference index to assist the store
- * @param mode The context in which the write is occurring
- */
- @Inline
- @Override
- public final void doubleWrite(ObjectReference objref, double value, Word offset, Word location, int mode) {
- Magic.setDoubleAtOffset(objref.toObject(), offset.toOffset(), value, location.toInt());
- }
-
- /**
- * Perform the actual read of a double read barrier.
- *
- * @param objref The object that has the double field
- * @param offset The offset from the ref
- * @param unused Unused
- * @param mode The context in which the write is occurring
- * @return the read value
- */
- @Inline
- @Override
- public final double doubleRead(ObjectReference objref, Word offset, Word location, int mode) {
- return Magic.getDoubleAtOffset(objref.toObject(), offset.toOffset());
- }
-
- /**
- * Perform the actual write of an object reference write barrier.
- *
- * @param objref The object that has the reference field
- * @param value The value that the slot will be updated to
- * @param offset The offset from the ref
- * @param location The index of the FieldReference
- * @param mode The context in which the write is occurring
- */
- @Inline
- @Override
- public final void objectReferenceWrite(ObjectReference objref, ObjectReference value, Word offset, Word location, int mode) {
- Magic.setObjectAtOffset(objref.toObject(), offset.toOffset(), value.toObject(), location.toInt());
- }
-
- /**
- * Perform the actual read of an object reference read barrier.
- *
- * @param objref The object that has the reference field
- * @param offset The offset from the ref
- * @param location The index of the FieldReference
- * @param mode The context in which the write is occurring
- * @return the object reference read value
- */
- @Inline
- @Override
- public final ObjectReference objectReferenceRead(ObjectReference objref, Word offset, Word location, int mode) {
- return ObjectReference.fromObject(Magic.getObjectAtOffset(objref.toObject(), offset.toOffset(), location.toInt()));
- }
-
- /**
- * Perform the actual write of the non-heap write barrier. This is
- * used when the store is not to an object, but to a non-heap location
- * such as statics or the stack.
- * @param target The value that the slot will be updated to
- * @param unusedA The offset from the ref
- * @param unusedB Unused
- * @param ref The object that has the reference field
- */
- @Inline
- @Override
- public final void objectReferenceNonHeapWrite(Address slot, ObjectReference target, Word unusedA, Word unusedB) {
- slot.store(target);
- }
-
- /**
- * Atomically write a reference field of an object or array and return
- * the old value of the reference field.
- *
- * @param objref The object that has the reference field
- * @param target The value that the slot will be updated to
- * @param offset The offset from the ref
- * @param unused Unused
- * @param mode The context in which the write is occurring
- * @return The value that was replaced by the write.
- */
- @Inline
- @Override
- public final ObjectReference objectReferenceAtomicWrite(ObjectReference objref, ObjectReference target, Word offset, Word unused, int mode) {
- Object obj = objref.toObject();
- Object newObject = target.toObject();
- Object oldObject;
- do {
- oldObject = Magic.prepareObject(obj, offset.toOffset());
- } while (!Magic.attemptObject(obj, offset.toOffset(), oldObject, newObject));
- return ObjectReference.fromObject(oldObject);
- }
-
- /**
- * Attempt an atomic compare and exchange in a write barrier sequence.
- *
- * @param objref The object that has the reference field
- * @param old The old reference to be swapped out
- * @param target The value that the slot will be updated to
- * @param offset The offset from the ref
- * @param unused Unused
- * @param mode The context in which the write is occurring
- * @return True if the compare and swap was successful
- */
- @Inline
- @Override
- public final boolean objectReferenceTryCompareAndSwap(ObjectReference objref, ObjectReference old, ObjectReference target, Word offset, Word unused, int mode) {
- Object oldValue;
- do {
- oldValue = Magic.prepareObject(objref, offset.toOffset());
- if (oldValue != old) return false;
- } while (!Magic.attemptObject(objref, offset.toOffset(), oldValue, target));
- return true;
- }
-
- /**
- * Perform the actual write of the write barrier, writing the value as a raw Word.
- *
- * @param ref The object that has the Word field
- * @param target The value that the slot will be updated to
- * @param offset The offset from the ref
- * @param location The index of the FieldReference
- * @param mode The context in which the write is occurring
- */
- @Inline
- @Override
- public final void wordWrite(ObjectReference ref, Word target,
- Word offset, Word location, int mode) {
- Magic.setWordAtOffset(ref.toObject(), offset.toOffset(), target, location.toInt());
- }
-
- /**
- * Atomically write a raw reference field of an object or array and return
- * the old value of the reference field.
- *
- * @param ref The object that has the Word field
- * @param target The value that the slot will be updated to
- * @param offset The offset from the ref
- * @param unused Unused
- * @param mode The context in which the write is occurring
- * @return The value that was replaced by the write.
- */
- @Inline
- @Override
- public final Word wordAtomicWrite(ObjectReference ref, Word target,
- Word offset, Word unused, int mode) {
- Word oldValue;
- do {
- oldValue = Magic.prepareWord(ref.toObject(), offset.toOffset());
- } while (!Magic.attemptWord(ref.toObject(), offset.toOffset(), oldValue, target));
- return oldValue;
- }
-
- /**
- * Attempt an atomic compare and exchange in a write barrier sequence.
- *
- * @param ref The object that has the Word field
- * @param old The old Word to be swapped out
- * @param target The value that the slot will be updated to
- * @param offset The offset from the ref
- * @param unused Unused
- * @param mode The context in which the write is occurring
- * @return True if the compare and swap was successful
- */
- @Inline
- @Override
- public final boolean wordTryCompareAndSwap(ObjectReference ref, Word old, Word target,
- Word offset, Word unused, int mode) {
- do {
- Word currentValue = Magic.prepareWord(ref, offset.toOffset());
- if (currentValue != old) return false;
- } while (!Magic.attemptWord(ref, offset.toOffset(), old, target));
- return true;
- }
-
- /**
- * Perform the actual read of the read barrier, returning the value as a raw Word.
- *
- * @param ref The object that has the Word field
- * @param offset The offset from the ref
- * @param location The index of the FieldReference
- * @param mode The context in which the write is occurring
- * @return the read value
- */
- @Inline
- @Override
- public final Word wordRead(ObjectReference ref,
- Word offset, Word location, int mode) {
- return Magic.getWordAtOffset(ref.toObject(), offset.toOffset(), location.toInt());
- }
-
- /**
- * Perform the actual write of the write barrier, writing the value as a raw Address.
- *
- * @param ref The object that has the Address field
- * @param target The value that the slot will be updated to
- * @param offset The offset from the ref
- * @param location The index of the FieldReference
- * @param mode The context in which the write is occurring
- */
- @Inline
- @Override
- public final void addressWrite(ObjectReference ref, Address target,
- Word offset, Word location, int mode) {
- Magic.setAddressAtOffset(ref.toObject(), offset.toOffset(), target, location.toInt());
- }
-
- /**
- * Perform the actual read of the read barrier, returning the value as a raw Address.
- *
- * @param ref The object that has the Address field
- * @param offset The offset from the ref
- * @param location The index of the FieldReference
- * @param mode The context in which the write is occurring
- * @return the read value
- */
- @Inline
- @Override
- public final Address addressRead(ObjectReference ref,
- Word offset, Word location, int mode) {
- return Magic.getAddressAtOffset(ref.toObject(), offset.toOffset(), location.toInt());
- }
-
- /**
- * Attempt an atomic compare and exchange in a write barrier sequence.
- *
- * @param objref The object that has the Address field
- * @param expected The old Address to be swapped out
- * @param newValue the new Address
- * @param offset The offset from the ref
- * @param unused Unused
- * @param mode The context in which the write is occurring
- * @return True if the compare and swap was successful
- */
- @Override
- public boolean addressTryCompareAndSwap(ObjectReference objref, Address expected, Address newValue, Word offset, Word unused, int mode) {
- Address oldValue;
- do {
- oldValue = Magic.prepareAddress(objref, offset.toOffset());
- if (oldValue != expected) return false;
- } while (!Magic.attemptAddress(objref, offset.toOffset(), oldValue, newValue));
- return true;
- }
-
- /**
- * Perform the actual write of the write barrier, writing the value as a raw Offset.
- *
- * @param ref The object that has the Offset field
- * @param target The value that the slot will be updated to
- * @param offset The offset from the ref
- * @param location The index of the FieldReference
- * @param mode The context in which the write is occurring
- */
- @Inline
- @Override
- public final void offsetWrite(ObjectReference ref, Offset target,
- Word offset, Word location, int mode) {
- Magic.setOffsetAtOffset(ref.toObject(), offset.toOffset(), target, location.toInt());
- }
-
- /**
- * Perform the actual read of the read barrier, returning the value as a raw Offset.
- *
- * @param ref The object that has the Offset field
- * @param offset The offset from the ref
- * @param location The index of the FieldReference
- * @param mode The context in which the write is occurring
- * @return the read value
- */
- @Inline
- @Override
- public final Offset offsetRead(ObjectReference ref,
- Word offset, Word location, int mode) {
- return Magic.getOffsetAtOffset(ref.toObject(), offset.toOffset(), location.toInt());
- }
-
- /**
- * Perform the actual write of the write barrier, writing the value as a raw Extent.
- *
- * @param ref The object that has the Extent field
- * @param target The value that the slot will be updated to
- * @param offset The offset from the ref
- * @param location The index of the FieldReference
- * @param mode The context in which the write is occurring
- */
- @Inline
- @Override
- public final void extentWrite(ObjectReference ref, Extent target,
- Word offset, Word location, int mode) {
- Magic.setExtentAtOffset(ref.toObject(), offset.toOffset(), target, location.toInt());
- }
-
- /**
- * Perform the actual read of the read barrier, returning the value as a raw Extent.
- *
- * @param ref The object that has the Extent field
- * @param offset The offset from the ref
- * @param location The index of the FieldReference
- * @param mode The context in which the write is occurring
- * @return the read value
- */
- @Inline
- @Override
- public final Extent extentRead(ObjectReference ref,
- Word offset, Word location, int mode) {
- return Magic.getExtentAtOffset(ref.toObject(), offset.toOffset(), location.toInt());
- }
-
- /**
- * Sets an element of an object array without invoking any write
- * barrier. This method is called by the Map class to ensure
- * potentially-allocation-triggering write barriers do not occur in
- * allocation slow path code.
- *
- * @param dst the destination array
- * @param index the index of the element to set
- * @param value the new value for the element
- */
- @UninterruptibleNoWarn
- @Override
- public final void objectArrayStoreNoGCBarrier(Object[] dst, int index, Object value) {
- Address base = ObjectReference.fromObject(dst).toAddress();
- // Add 3 for the header, the class, and the length.
- Address slot = base.plus(Offset.fromIntZeroExtend((index + 3) << LOG_BYTES_IN_ADDRESS));
- VM.activePlan.global().storeObjectReference(slot, ObjectReference.fromObject(value));
- }
-}
diff --git a/vmkit/mmtk/java/src/org/j3/mmtk/BuildTimeConfig.java b/vmkit/mmtk/java/src/org/j3/mmtk/BuildTimeConfig.java
deleted file mode 100644
index 8dc8f82..0000000
--- a/vmkit/mmtk/java/src/org/j3/mmtk/BuildTimeConfig.java
+++ /dev/null
@@ -1,127 +0,0 @@
-//===---------------------- BuildTimeConfig.java --------------------------===//
-//
-// The VMKit project
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-package org.j3.mmtk;
-
-import java.io.BufferedInputStream;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileNotFoundException;
-import java.io.IOException;
-import java.util.Properties;
-
-import org.j3.runtime.VM;
-import org.j3.config.Selected;
-
-/**
- * Read build-time configuration information for MMTk from a Java properties
- * file. Properties read through this mechanism should be read at build time
- * and saved in static final fields.
- *
- * This is a wrapper for a java.util.Properties object.
- */
-public final class BuildTimeConfig extends org.mmtk.vm.BuildTimeConfig {
-
- /**
- * The underlying properties object
- */
- private Properties props;
-
- public BuildTimeConfig(String property_file_property, String default_property_file) {
- props = getProperties(property_file_property,default_property_file);
- }
-
- public BuildTimeConfig(String property_file_property) {
- props = getProperties(property_file_property,null);
- }
-
- /**
- * @param property_file_property The name of the property that sets
- * the location of the properties file
- * @param default_property_file The default properties file.
- *
- */
- private Properties getProperties(String property_file_property, String default_property_file) {
- Properties props = new Properties();
- String propFileName;
- if (default_property_file == null) {
- propFileName = System.getProperty(property_file_property);
- if (propFileName == null) {
- System.err.println(property_file_property+" must specify a properties file");
- VM.sysExit(1);
- }
- } else {
- propFileName = System.getProperty(property_file_property, default_property_file);
- }
- File propFile = new File(propFileName);
-
- try {
- BufferedInputStream propFileStream = new BufferedInputStream(new FileInputStream(propFile));
- props.load(propFileStream);
- propFileStream.close();
- } catch (FileNotFoundException e) {
- if (!propFileName.equals(default_property_file)) {
- System.err.println(propFileName+" not found.");
- VM.sysExit(1);
- }
- } catch (IOException e) {
- e.printStackTrace();
- VM.sysExit(1);
- }
- return props;
- }
-
- @Override
- public String getPlanName() {
- return Selected.name;
- }
-
- @Override
- public boolean getBooleanProperty(String name, boolean dflt) {
- String value = props.getProperty(name,Boolean.toString(dflt));
- return Boolean.valueOf(value);
- }
-
- @Override
- public boolean getBooleanProperty(String name) {
- String value = props.getProperty(name);
- if (value == null)
- throw new RuntimeException("Undefined property "+name);
- return Boolean.valueOf(value);
- }
-
- @Override
- public int getIntProperty(String name, int dflt) {
- String value = props.getProperty(name,Integer.toString(dflt));
- return Integer.valueOf(value);
- }
-
- @Override
- public int getIntProperty(String name) {
- String value = props.getProperty(name);
- if (value == null)
- throw new RuntimeException("Undefined property "+name);
- return Integer.valueOf(value);
- }
-
- @Override
- public String getStringProperty(String name, String dflt) {
- return props.getProperty(name,dflt);
- }
-
- @Override
- public String getStringProperty(String name) {
- String value = props.getProperty(name);
- if (value == null)
- throw new RuntimeException("Undefined property "+name);
- return value;
- }
-
-
-}
diff --git a/vmkit/mmtk/java/src/org/j3/mmtk/Collection.java b/vmkit/mmtk/java/src/org/j3/mmtk/Collection.java
deleted file mode 100644
index e2ca4f4..0000000
--- a/vmkit/mmtk/java/src/org/j3/mmtk/Collection.java
+++ /dev/null
@@ -1,120 +0,0 @@
-//===------------------------- Collection.java ----------------------------===//
-//
-// The VMKit project
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-package org.j3.mmtk;
-
-import org.mmtk.plan.Plan;
-import org.mmtk.plan.CollectorContext;
-import org.mmtk.plan.MutatorContext;
-import org.mmtk.utility.options.Options;
-
-import org.vmmagic.pragma.Inline;
-import org.vmmagic.pragma.Interruptible;
-import org.vmmagic.pragma.Uninterruptible;
-import org.vmmagic.pragma.UninterruptibleNoWarn;
-import org.vmmagic.pragma.Unpreemptible;
-import org.vmmagic.unboxed.Address;
-
-@Uninterruptible
-public final class Collection extends org.mmtk.vm.Collection {
-
- /**
- * Triggers a collection.
- *
- * @param why the reason why a collection was triggered. 0 to
- * <code>TRIGGER_REASONS - 1</code>.
- */
- @Unpreemptible("Becoming another thread interrupts the current thread, avoid preemption in the process")
- public native final void triggerCollection(int why);
-
- /**
- * Joins a collection.
- */
- @Unpreemptible("Becoming another thread interrupts the current thread, avoid preemption in the process")
- public native final void joinCollection();
-
- /**
- * The maximum number collection attempts across threads.
- */
- public native int maximumCollectionAttempt();
-
- /**
- * Report that the the physical allocation has succeeded.
- */
- public native void reportAllocationSuccess();
-
- /**
- * Report that a physical allocation has failed.
- */
- public native void reportPhysicalAllocationFailed();
-
- /**
- * Does the VM consider this an emergency allocation, where the normal
- * heap size rules can be ignored.
- */
- public native boolean isEmergencyAllocation();
-
- /**
- * Trigger an asynchronous collection, checking for memory
- * exhaustion first.
- */
- @Unpreemptible("Becoming another thread interrupts the current thread, avoid preemption in the process")
- public native final void triggerAsyncCollection(int why);
-
- /**
- * Determine whether a collection cycle has fully completed (this is
- * used to ensure a GC is not in the process of completing, to
- * avoid, for example, an async GC being triggered on the switch
- * from GC to mutator thread before all GC threads have switched.
- *
- * @return True if GC is not in progress.
- */
- @Uninterruptible
- public native final boolean noThreadsInGC();
-
- /**
- * Prepare a mutator for a collection.
- *
- * @param m the mutator to prepare
- */
- public native final void prepareMutator(MutatorContext m);
-
- /**
- * Prepare a collector for a collection.
- *
- * @param c the collector to prepare
- */
- public native final void prepareCollector(CollectorContext c);
-
- /**
- * Rendezvous with all other processors, returning the rank
- * (that is, the order this processor arrived at the barrier).
- */
- public native final int rendezvous(int where);
-
- // REVIEW: what are the semantics of this method in a concurrent collector?
- /** @return The number of active collector threads */
- public native final int activeGCThreads();
-
- /**
- * @return The ordinal ID of the running collector thread w.r.t.
- * the set of active collector threads (zero based)
- */
- public native final int activeGCThreadOrdinal();
-
- /**
- * Request each mutator flush remembered sets. This method
- * will trigger the flush and then yield until all processors have
- * flushed.
- */
- @UninterruptibleNoWarn("This method is really unpreemptible, since it involves blocking")
- public native void requestMutatorFlush();
-
-}
-
diff --git a/vmkit/mmtk/java/src/org/j3/mmtk/Debug.java b/vmkit/mmtk/java/src/org/j3/mmtk/Debug.java
deleted file mode 100644
index 19291b9..0000000
--- a/vmkit/mmtk/java/src/org/j3/mmtk/Debug.java
+++ /dev/null
@@ -1,28 +0,0 @@
-//===--------------------------- Debug.java -------------------------------===//
-//
-// The VMKit project
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-package org.j3.mmtk;
-
-import org.vmmagic.pragma.Uninterruptible;
-
-/**
- * Debugger support for the MMTk harness
- */
-@Uninterruptible
-public final class Debug extends org.mmtk.vm.Debug {
-
- /**
- * Enable/disable MMTk debugger support
- */
- @Override
- public boolean isEnabled() {
- return false;
- }
-
-}
diff --git a/vmkit/mmtk/java/src/org/j3/mmtk/Factory.java b/vmkit/mmtk/java/src/org/j3/mmtk/Factory.java
deleted file mode 100644
index ed6d5e9..0000000
--- a/vmkit/mmtk/java/src/org/j3/mmtk/Factory.java
+++ /dev/null
@@ -1,501 +0,0 @@
-//===-------------------------- Factory.java ------------------------------===//
-//
-// The VMKit project
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-package org.j3.mmtk;
-
-import org.vmutil.options.OptionSet;
-import org.mmtk.utility.gcspy.Color;
-import org.mmtk.utility.gcspy.drivers.AbstractDriver;
-import org.mmtk.vm.ReferenceProcessor.Semantics;
-
-import org.j3.runtime.VM;
-
-/**
- * This is a VM-specific class which defines factory methods for
- * VM-specific types which must be instantiated within MMTk.
- *
- * @see org.mmtk.vm.Factory
- */
-public final class Factory extends org.mmtk.vm.Factory {
-
- private static final String DEFAULT_MMTK_PROPERTIES = ".mmtk.properties";
- private static final String CONFIG_FILE_PROPERTY = "mmtk.properties";
-
- /**
- * Create or retrieve the OptionSet used for MMTk options.
- *
- * @return A concrete VM-specific OptionSet instance
- */
- public OptionSet getOptionSet() {
- return org.j3.options.OptionSet.gc;
- }
-
- /**
- * Create a new ActivePlan instance using the appropriate VM-specific
- * concrete ActivePlan sub-class.
- *
- * @see ActivePlan
- * @return A concrete VM-specific ActivePlan instance.
- */
- public org.mmtk.vm.ActivePlan newActivePlan() {
- try {
- return new ActivePlan();
- } catch (Exception e) {
- VM.sysFail("Failed to allocate new ActivePlan!");
- return null; // never get here
- }
- }
-
- /**
- * Create a new Assert instance using the appropriate VM-specific
- * concrete Assert sub-class.
- *
- * @see Assert
- * @return A concrete VM-specific Assert instance.
- */
- public org.mmtk.vm.Assert newAssert() {
- try {
- return new Assert();
- } catch (Exception e) {
- VM.sysFail("Failed to allocate new Assert!");
- return null; // never get here
- }
- }
-
- /**
- * Create a new Barriers instance using the appropriate VM-specific
- * concrete Barriers sub-class.
- *
- * @see Barriers
- * @return A concrete VM-specific Barriers instance.
- */
- public org.mmtk.vm.Barriers newBarriers() {
- try {
- return new Barriers();
- } catch (Exception e) {
- VM.sysFail("Failed to allocate new Barriers!");
- return null; // never get here
- }
- }
-
- /**
- * Create a new Collection instance using the appropriate VM-specific
- * concrete Collection sub-class.
- *
- * @see Collection
- * @return A concrete VM-specific Collection instance.
- */
- public org.mmtk.vm.Collection newCollection() {
- try {
- return new Collection();
- } catch (Exception e) {
- VM.sysFail("Failed to allocate new Collection!");
- return null; // never get here
- }
- }
-
- /**
- * Create a new BuildTimeConfig instance using the appropriate VM-specific
- * concrete BuildTimeConfig sub-class.
- *
- * @see Collection
- * @return A concrete VM-specific Collection instance.
- */
- public org.mmtk.vm.BuildTimeConfig newBuildTimeConfig() {
- try {
- return new BuildTimeConfig(CONFIG_FILE_PROPERTY, DEFAULT_MMTK_PROPERTIES);
- } catch (Exception e) {
- VM.sysFail("Failed to allocate new BuildTimeConfiguration!");
- return null; // never get here
- }
- }
-
- /**
- * Create a new Lock instance using the appropriate VM-specific
- * concrete Lock sub-class.
- *
- * @see Lock
- *
- * @param name The string to be associated with this lock instance
- * @return A concrete VM-specific Lock instance.
- */
- public org.mmtk.vm.Lock newLock(String name) {
- try {
- return new Lock(name);
- } catch (Exception e) {
- VM.sysFail("Failed to allocate new Lock!");
- return null; // never get here
- }
- }
-
- /**
- * Create a new Memory instance using the appropriate VM-specific
- * concrete Memory sub-class.
- *
- * @see Memory
- * @return A concrete VM-specific Memory instance.
- */
- public org.mmtk.vm.Memory newMemory() {
- try {
- return new Memory();
- } catch (Exception e) {
- VM.sysFail("Failed to allocate new Memory!");
- return null; // never get here
- }
- }
-
- /**
- * Create a new ObjectModel instance using the appropriate VM-specific
- * concrete ObjectModel sub-class.
- *
- * @see ObjectModel
- * @return A concrete VM-specific ObjectModel instance.
- */
- public org.mmtk.vm.ObjectModel newObjectModel() {
- try {
- return new ObjectModel();
- } catch (Exception e) {
- VM.sysFail("Failed to allocate new ObjectModel!");
- return null; // never get here
- }
- }
-
- /**
- * Create a new ReferenceProcessor instance using the appropriate VM-specific
- * concrete ReferenceProcessor sub-class.
- *
- * @see ReferenceProcessor
- * @return A concrete VM-specific ReferenceProcessor instance.
- */
- public org.mmtk.vm.ReferenceProcessor newReferenceProcessor(Semantics semantics) {
- try {
- return ReferenceProcessor.get(semantics);
- } catch (Exception e) {
- VM.sysFail("Failed to allocate new ReferenceProcessor!");
- return null; // never get here
- }
- }
-
- /**
- * Create a new FinalizableProcessor instance using the appropriate VM-specific
- * concrete FinalizableProcessor sub-class.
- *
- * @see ReferenceProcessor
- * @return A concrete VM-specific FinalizableProcessor instance.
- */
- public org.mmtk.vm.FinalizableProcessor newFinalizableProcessor() {
- try {
- return FinalizableProcessor.getProcessor();
- } catch (Exception e) {
- VM.sysFail("Failed to allocate new FinalizableProcessor!");
- return null; // never get here
- }
- }
-
- /**
- * Create a new Scanning instance using the appropriate VM-specific
- * concrete Scanning sub-class.
- *
- * @see Scanning
- * @return A concrete VM-specific Scanning instance.
- */
- public org.mmtk.vm.Scanning newScanning() {
- try {
- return new Scanning();
- } catch (Exception e) {
- VM.sysFail("Failed to allocate new Scanning!");
- return null; // never get here
- }
- }
-
- /**
- * Create a new Statistics instance using the appropriate VM-specific
- * concrete Statistics sub-class.
- *
- * @see Statistics
- * @return A concrete VM-specific Statistics instance.
- */
- public org.mmtk.vm.Statistics newStatistics() {
- try {
- return new Statistics();
- } catch (Exception e) {
- VM.sysFail("Failed to allocate new Statistics!");
- return null; // never get here
- }
- }
-
- /**
- * Create a new Strings instance using the appropriate VM-specific
- * concrete Strings sub-class.
- *
- * @see Strings
- * @return A concrete VM-specific Strings instance.
- */
- public org.mmtk.vm.Strings newStrings() {
- try {
- return new Strings();
- } catch (Exception e) {
- VM.sysFail("Failed to allocate new Strings!");
- return null; // never get here
- }
- }
-
- /**
- * Create a new SynchronizedCounter instance using the appropriate
- * VM-specific concrete SynchronizedCounter sub-class.
- *
- * @see SynchronizedCounter
- *
- * @return A concrete VM-specific SynchronizedCounter instance.
- */
- public org.mmtk.vm.SynchronizedCounter newSynchronizedCounter() {
- try {
- return new SynchronizedCounter();
- } catch (Exception e) {
- VM.sysFail("Failed to allocate new SynchronizedCounter!");
- return null; // never get here
- }
- }
-
- /**
- * Create a new TraceInterface instance using the appropriate VM-specific
- * concrete TraceInterface sub-class.
- *
- * @see TraceInterface
- * @return A concrete VM-specific TraceInterface instance.
- */
- public org.mmtk.vm.TraceInterface newTraceInterface() {
- try {
- return new TraceInterface();
- } catch (Exception e) {
- VM.sysFail("Failed to allocate new TraceInterface!");
- return null; // never get here
- }
- }
-
- /**
- * Create a new MMTk_Events instance using the appropriate VM-specific
- * concrete MMTk_Events sub-class.
- *
- * @see MMTk_Events
- * @return A concrete VM-specific MMTk_Events instance.
- */
- public org.mmtk.vm.MMTk_Events newEvents() {
- try {
- return new MMTk_Events();
- } catch (Exception e) {
- VM.sysFail("Failed to allocate new MMTk_Events!");
- return null; // never get here
- }
- }
-
- public org.mmtk.vm.Debug newDebug() {
- return new Debug();
- }
-
- /**********************************************************************
- * GCspy methods
- */
-
- /**
- * Create a new Util instance using the appropriate VM-specific
- * concrete Util sub-class.
- *
- * @see org.mmtk.vm.gcspy.Util
- * @return A concrete VM-specific Util instance.
- */
- public org.mmtk.vm.gcspy.Util newGCspyUtil() {
- try {
- return null;
- } catch (Exception e) {
- VM.sysFail("Failed to allocate new Util!");
- return null; // never get here
- }
- }
-
- /**
- * Create a new ServerInterpreter instance using the appropriate VM-specific
- * concrete ServerInterpreter sub-class.
- *
- * @see org.mmtk.vm.gcspy.ServerInterpreter
- * @return A concrete VM-specific ServerInterpreter instance.
- */
- public org.mmtk.vm.gcspy.ServerInterpreter newGCspyServerInterpreter() {
- try {
- return null;
- } catch (Exception e) {
- VM.sysFail("Failed to allocate new ServerInterpreter!");
- return null; // never get here
- }
- }
-
- /**
- * Create a new ServerSpace instance using the appropriate VM-specific
- * concrete ServerSpace sub-class.
- *
- * @param serverInterpreter The server that owns this space
- * @param serverName The server's name
- * @param driverName The space driver's name
- * @param title Title for the space
- * @param blockInfo A label for each block
- * @param tileNum Max number of tiles in this space
- * @param unused A label for unused blocks
- * @param mainSpace Whether this space is the main space
- *
- * @see org.mmtk.vm.gcspy.ServerSpace
- * @return A concrete VM-specific ServerSpace instance.
- */
- public org.mmtk.vm.gcspy.ServerSpace newGCspyServerSpace(
- org.mmtk.vm.gcspy.ServerInterpreter serverInterpreter,
- String serverName,
- String driverName,
- String title,
- String blockInfo,
- int tileNum,
- String unused,
- boolean mainSpace){
- try {
- return null;
- } catch (Exception e) {
- VM.sysFail("Failed to allocate new ServerSpace!");
- return null; // never get here
- }
- }
-
- /**
- * Create a new ByteStream instance using the appropriate
- * VM-specific concrete ByteStream sub-class.
- *
- * @param driver The driver that owns this Stream
- * @param name The name of the stream (e.g. "Used space")
- * @param minValue The minimum value for any item in this stream.
- * Values less than this will be represented as "minValue-"
- * @param maxValue The maximum value for any item in this stream.
- * Values greater than this will be represented as "maxValue+"
- * @param zeroValue The zero value for this stream
- * @param defaultValue The default value for this stream
- * @param stringPre A string to prefix values (e.g. "Used: ")
- * @param stringPost A string to suffix values (e.g. " bytes.")
- * @param presentation How a stream value is to be presented.
- * @param paintStyle How the value is to be painted.
- * @param indexMaxStream The index of the maximum stream if the presentation is *_VAR.
- * @param colour The default colour for tiles of this stream
- * @see org.mmtk.vm.gcspy.IntStream
- *
- * @return A concrete VM-specific ByteStream instance.
- */
- public org.mmtk.vm.gcspy.ByteStream newGCspyByteStream(
- AbstractDriver driver,
- String name,
- byte minValue,
- byte maxValue,
- byte zeroValue,
- byte defaultValue,
- String stringPre,
- String stringPost,
- int presentation,
- int paintStyle,
- int indexMaxStream,
- Color colour,
- boolean summary) {
- try {
- return null;
- } catch (Exception e) {
- VM.sysFail("Failed to allocate new ByteStream!");
- return null; // never get here
- }
- }
- /**
- * Create a new IntStream instance using the appropriate
- * VM-specific concrete IntStream sub-class.
- *
- * @param driver The driver that owns this Stream
- * @param name The name of the stream (e.g. "Used space")
- * @param minValue The minimum value for any item in this stream.
- * Values less than this will be represented as "minValue-"
- * @param maxValue The maximum value for any item in this stream.
- * Values greater than this will be represented as "maxValue+"
- * @param zeroValue The zero value for this stream
- * @param defaultValue The default value for this stream
- * @param stringPre A string to prefix values (e.g. "Used: ")
- * @param stringPost A string to suffix values (e.g. " bytes.")
- * @param presentation How a stream value is to be presented.
- * @param paintStyle How the value is to be painted.
- * @param indexMaxStream The index of the maximum stream if the presentation is *_VAR.
- * @param colour The default colour for tiles of this stream
- * @see org.mmtk.vm.gcspy.IntStream
- *
- * @return A concrete VM-specific IntStream instance.
- */
- public org.mmtk.vm.gcspy.IntStream newGCspyIntStream(
- AbstractDriver driver,
- String name,
- int minValue,
- int maxValue,
- int zeroValue,
- int defaultValue,
- String stringPre,
- String stringPost,
- int presentation,
- int paintStyle,
- int indexMaxStream,
- Color colour,
- boolean summary) {
- try {
- return null;
- } catch (Exception e) {
- VM.sysFail("Failed to allocate new IntStream!");
- return null; // never get here
- }
- }
-
- /**
- * Create a new ShortStream instance using the appropriate
- * VM-specific concrete ShortStream sub-class.
- *
- * @param driver The driver that owns this Stream
- * @param name The name of the stream (e.g. "Used space")
- * @param minValue The minimum value for any item in this stream.
- * Values less than this will be represented as "minValue-"
- * @param maxValue The maximum value for any item in this stream.
- * Values greater than this will be represented as "maxValue+"
- * @param zeroValue The zero value for this stream
- * @param defaultValue The default value for this stream
- * @param stringPre A string to prefix values (e.g. "Used: ")
- * @param stringPost A string to suffix values (e.g. " bytes.")
- * @param presentation How a stream value is to be presented.
- * @param paintStyle How the value is to be painted.
- * @param indexMaxStream The index of the maximum stream if the presentation is *_VAR.
- * @param colour The default colour for tiles of this stream
- * @see org.mmtk.vm.gcspy.IntStream
- *
- * @return A concrete VM-specific ShortStream instance.
- */
- public org.mmtk.vm.gcspy.ShortStream newGCspyShortStream(
- AbstractDriver driver,
- String name,
- short minValue,
- short maxValue,
- short zeroValue,
- short defaultValue,
- String stringPre,
- String stringPost,
- int presentation,
- int paintStyle,
- int indexMaxStream,
- Color colour,
- boolean summary) {
- try {
- return null;
- } catch (Exception e) {
- VM.sysFail("Failed to allocate new ShortStream!");
- return null; // never get here
- }
- }
-}
diff --git a/vmkit/mmtk/java/src/org/j3/mmtk/FinalizableProcessor.java b/vmkit/mmtk/java/src/org/j3/mmtk/FinalizableProcessor.java
deleted file mode 100644
index 9d03cfe..0000000
--- a/vmkit/mmtk/java/src/org/j3/mmtk/FinalizableProcessor.java
+++ /dev/null
@@ -1,68 +0,0 @@
-//===---------------------- FinalizableProcessor.java ---------------------===//
-//
-// The VMKit project
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-package org.j3.mmtk;
-
-import org.vmmagic.pragma.*;
-import org.vmmagic.unboxed.*;
-
-import org.j3.runtime.VM;
-import org.j3.config.Selected;
-import org.mmtk.plan.TraceLocal;
-
-/**
- * This class manages the processing of finalizable objects.
- */
-
-@Uninterruptible
-public final class FinalizableProcessor extends org.mmtk.vm.FinalizableProcessor {
-
- /********************************************************************
- * Class fields
- */
-
- /** The FinalizableProcessor singleton */
- private static final FinalizableProcessor finalizableProcessor = new FinalizableProcessor();
-
- public static FinalizableProcessor getProcessor() {
- return finalizableProcessor;
- }
-
- public native void clear();
-
- /**
- * Scan through all entries in the table and forward.
- *
- * Currently ignores the nursery hint.
- *
- * TODO parallelise this code?
- *
- * @param trace The trace
- * @param nursery Is this a nursery collection ?
- */
- @Override
- public native void forward(TraceLocal trace, boolean nursery);
-
- /**
- * Scan through the list of references. Calls ReferenceProcessor's
- * processReference method for each reference and builds a new
- * list of those references still active.
- *
- * Depending on the value of <code>nursery</code>, we will either
- * scan all references, or just those created since the last scan.
- *
- * TODO parallelise this code
- *
- * @param nursery Scan only the newly created references
- */
- @Override
- @UninterruptibleNoWarn
- public native void scan(TraceLocal trace, boolean nursery);
-
-}
diff --git a/vmkit/mmtk/java/src/org/j3/mmtk/Lock.java b/vmkit/mmtk/java/src/org/j3/mmtk/Lock.java
deleted file mode 100644
index e480445..0000000
--- a/vmkit/mmtk/java/src/org/j3/mmtk/Lock.java
+++ /dev/null
@@ -1,39 +0,0 @@
-//===--------------------------- Lock.java --------------------------------===//
-//
-// The VMKit project
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-package org.j3.mmtk;
-
-import org.vmmagic.unboxed.*;
-import org.vmmagic.pragma.*;
-
-@Uninterruptible public class Lock extends org.mmtk.vm.Lock {
-
- private int state;
- private String name; // logical name of lock
-
- // Diagnosis Instance fields
- public Lock(String name) {
- this();
- this.name = name;
- }
-
- public Lock() {
- state = 0;
- }
-
- public void setName(String str) {
- name = str;
- }
-
- public native void acquire();
-
- public native void check(int w);
-
- public native void release();
-}
diff --git a/vmkit/mmtk/java/src/org/j3/mmtk/MMTk_Events.java b/vmkit/mmtk/java/src/org/j3/mmtk/MMTk_Events.java
deleted file mode 100644
index e3bebfc..0000000
--- a/vmkit/mmtk/java/src/org/j3/mmtk/MMTk_Events.java
+++ /dev/null
@@ -1,29 +0,0 @@
-//===-------------------- --- MMTk_Events.java ----------------------------===//
-//
-// The VMKit project
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-package org.j3.mmtk;
-
-import org.mmtk.policy.Space;
-import org.vmmagic.pragma.Uninterruptible;
-import org.vmmagic.unboxed.Address;
-import org.vmmagic.unboxed.Extent;
-
-/**
- * Implementation of simple MMTK event generation hooks
- * to allow MMTk to generate TuningFork events.
- */
-@Uninterruptible
-public class MMTk_Events extends org.mmtk.vm.MMTk_Events {
-
- public native void tracePageAcquired(Space space, Address startAddress, int numPages);
-
- public native void tracePageReleased(Space space, Address startAddress, int numPages);
-
- public native void heapSizeChanged(Extent heapSize);
-}
diff --git a/vmkit/mmtk/java/src/org/j3/mmtk/Memory.java b/vmkit/mmtk/java/src/org/j3/mmtk/Memory.java
deleted file mode 100644
index b3e9ad0..0000000
--- a/vmkit/mmtk/java/src/org/j3/mmtk/Memory.java
+++ /dev/null
@@ -1,147 +0,0 @@
-//===-------------------------- Memory.java -------------------------------===//
-//
-// The VMKit project
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-package org.j3.mmtk;
-
-import org.mmtk.plan.Plan;
-import org.mmtk.policy.ImmortalSpace;
-import org.mmtk.utility.Constants;
-import org.mmtk.utility.heap.VMRequest;
-
-import org.j3.runtime.VM;
-import org.jikesrvm.Magic;
-import org.jikesrvm.SizeConstants;
-
-import org.vmmagic.unboxed.*;
-import org.vmmagic.pragma.*;
-
-@Uninterruptible
-public final class Memory extends org.mmtk.vm.Memory {
-
- protected native final Address getHeapStartConstant();
- protected native final Address getHeapEndConstant();
- protected native final Address getAvailableStartConstant();
- protected native final Address getAvailableEndConstant();
- protected final byte getLogBytesInAddressConstant() { return (byte)SizeConstants.LOG_BYTES_IN_ADDRESS; }
- protected final byte getLogBytesInWordConstant() { return (byte)SizeConstants.LOG_BYTES_IN_WORD; }
- protected final byte getLogBytesInPageConstant() { return (byte)SizeConstants.LOG_BYTES_IN_PAGE; }
- protected final byte getLogMinAlignmentConstant() { return (byte)SizeConstants.LOG_BYTES_IN_INT;}
- protected final int getMaxBytesPaddingConstant() { return (byte)SizeConstants.BYTES_IN_DOUBLE; }
- protected final int getAlignmentValueConstant() { return 0xdeadbeef; }
-
- /* On Intel we align code to 16 bytes as recommended in the optimization manual */
- protected final byte getMaxAlignmentShiftConstant() {
- return (byte)((VM.BuildForIA32 ? 1 : 0) + SizeConstants.LOG_BYTES_IN_LONG - SizeConstants.LOG_BYTES_IN_INT);
- }
-
- private static ImmortalSpace bootSpace;
-
- /**
- * Return the space associated with/reserved for the VM.
- */
- @Interruptible
- public final ImmortalSpace getVMSpace() {
- if (bootSpace == null) {
- bootSpace = new ImmortalSpace("boot", Plan.DEFAULT_POLL_FREQUENCY, VMRequest.create());
- }
- return bootSpace;
- }
-
- /** Global preparation for a collection. */
- public final void globalPrepareVMSpace() { bootSpace.prepare(); }
-
- /** Per-collector preparation for a collection. */
- public final void collectorPrepareVMSpace() {}
-
- /** Per-collector post-collection work. */
- public final void collectorReleaseVMSpace() {}
-
- /** Global post-collection work. */
- public final void globalReleaseVMSpace() { bootSpace.release(); }
-
- /**
- * Sets the range of addresses associated with a heap.
- *
- * @param id the heap identifier
- * @param start the address of the start of the heap
- * @param end the address of the end of the heap
- */
- public final void setHeapRange(int id, Address start, Address end) {}
-
- /**
- * Demand zero mmaps an area of virtual memory.
- *
- * @param start the address of the start of the area to be mapped
- * @param size the size, in bytes, of the area to be mapped
- * @return 0 if successful, otherwise the system errno
- */
- public native final int dzmmap(Address start, int size);
-
- /**
- * Protects access to an area of virtual memory.
- *
- * @param start the address of the start of the area to be mapped
- * @param size the size, in bytes, of the area to be mapped
- * @return <code>true</code> if successful, otherwise
- * <code>false</code>
- */
- public native final boolean mprotect(Address start, int size);
-
- /**
- * Allows access to an area of virtual memory.
- *
- * @param start the address of the start of the area to be mapped
- * @param size the size, in bytes, of the area to be mapped
- * @return <code>true</code> if successful, otherwise
- * <code>false</code>
- */
- public native final boolean munprotect(Address start, int size);
-
- /**
- * Zero a region of memory.
- * @param start Start of address range (inclusive)
- * @param len Length in bytes of range to zero
- * Returned: nothing
- */
- public native final void zero(Address start, Extent len);
-
- /**
- * Zero a range of pages of memory.
- * @param start Start of address range (must be a page address)
- * @param len Length in bytes of range (must be multiple of page size)
- */
- public native final void zeroPages(Address start, int len);
-
- /**
- * Logs the contents of an address and the surrounding memory to the
- * error output.
- *
- * @param start the address of the memory to be dumped
- * @param beforeBytes the number of bytes before the address to be
- * included
- * @param afterBytes the number of bytes after the address to be
- * included
- */
- public native final void dumpMemory(Address start, int beforeBytes,
- int afterBytes);
-
- /*
- * Utilities from the VM class
- */
-
- @Inline
- public final void sync() {
- Magic.sync();
- }
-
- @Inline
- public final void isync() {
- Magic.isync();
- }
-}
diff --git a/vmkit/mmtk/java/src/org/j3/mmtk/ObjectModel.java b/vmkit/mmtk/java/src/org/j3/mmtk/ObjectModel.java
deleted file mode 100644
index 03cf829..0000000
--- a/vmkit/mmtk/java/src/org/j3/mmtk/ObjectModel.java
+++ /dev/null
@@ -1,237 +0,0 @@
-//===------------------------ ObjectModel.java ----------------------------===//
-//
-// The VMKit project
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-package org.j3.mmtk;
-
-import org.vmmagic.unboxed.*;
-import org.vmmagic.pragma.*;
-
-@Uninterruptible
-public final class ObjectModel extends org.mmtk.vm.ObjectModel {
-
- protected native Offset getArrayBaseOffset();
-
- /**
- * Copy an object using a plan's allocCopy to get space and install
- * the forwarding pointer. On entry, <code>from</code> must have
- * been reserved for copying by the caller. This method calls the
- * plan's <code>getStatusForCopy()</code> method to establish a new
- * status word for the copied object and <code>postCopy()</code> to
- * allow the plan to perform any post copy actions.
- *
- * @param from the address of the object to be copied
- * @return the address of the new object
- */
- @Inline
- public native ObjectReference copy(ObjectReference from, int allocator);
-
- /**
- * Copy an object to be pointer to by the to address. This is required
- * for delayed-copy collectors such as compacting collectors. During the
- * collection, MMTk reserves a region in the heap for an object as per
- * requirements found from ObjectModel and then asks ObjectModel to
- * determine what the object's reference will be post-copy.
- *
- * @param from the address of the object to be copied
- * @param to The target location.
- * @param region The start (or an address less than) the region that was reserved for this object.
- * @return Address The address past the end of the copied object
- */
- @Inline
- public native Address copyTo(ObjectReference from, ObjectReference to, Address region);
-
- /**
- * Return the reference that an object will be refered to after it is copied
- * to the specified region. Used in delayed-copy collectors such as compacting
- * collectors.
- *
- * @param from The object to be copied.
- * @param to The region to be copied to.
- * @return The resulting reference.
- */
- public native ObjectReference getReferenceWhenCopiedTo(ObjectReference from, Address to);
-
- /**
- * Gets a pointer to the address just past the end of the object.
- *
- * @param object The object.
- */
- public native Address getObjectEndAddress(ObjectReference object);
-
- /**
- * Return the size required to copy an object
- *
- * @param object The object whose size is to be queried
- * @return The size required to copy <code>obj</code>
- */
- public native int getSizeWhenCopied(ObjectReference object);
-
- /**
- * Return the alignment requirement for a copy of this object
- *
- * @param object The object whose size is to be queried
- * @return The alignment required for a copy of <code>obj</code>
- */
- public native int getAlignWhenCopied(ObjectReference object);
-
- /**
- * Return the alignment offset requirements for a copy of this object
- *
- * @param object The object whose size is to be queried
- * @return The alignment offset required for a copy of <code>obj</code>
- */
- public native int getAlignOffsetWhenCopied(ObjectReference object);
-
- /**
- * Return the size used by an object
- *
- * @param object The object whose size is to be queried
- * @return The size of <code>obj</code>
- */
- public native int getCurrentSize(ObjectReference object);
-
- /**
- * Return the next object in the heap under contiguous allocation
- */
- public native ObjectReference getNextObject(ObjectReference object);
-
- /**
- * Return an object reference from knowledge of the low order word
- */
- public native ObjectReference getObjectFromStartAddress(Address start);
-
- /**
- * Get the type descriptor for an object.
- *
- * @param ref address of the object
- * @return byte array with the type descriptor
- */
- public native byte [] getTypeDescriptor(ObjectReference ref);
-
- @Inline
- public native int getArrayLength(ObjectReference object);
-
- /**
- * Is the passed object an array?
- *
- * @param object address of the object
- */
- public native boolean isArray(ObjectReference object);
-
- /**
- * Is the passed object a primitive array?
- *
- * @param object address of the object
- */
- public native boolean isPrimitiveArray(ObjectReference object);
-
- /**
- * Attempts to set the bits available for memory manager use in an
- * object. The attempt will only be successful if the current value
- * of the bits matches <code>oldVal</code>. The comparison with the
- * current value and setting are atomic with respect to other
- * allocators.
- *
- * @param object the address of the object
- * @param oldVal the required current value of the bits
- * @param newVal the desired new value of the bits
- * @return <code>true</code> if the bits were set,
- * <code>false</code> otherwise
- */
- public native boolean attemptAvailableBits(ObjectReference object,
- Word oldVal, Word newVal);
-
- /**
- * Gets the value of bits available for memory manager use in an
- * object, in preparation for setting those bits.
- *
- * @param object the address of the object
- * @return the value of the bits
- */
- public native Word prepareAvailableBits(ObjectReference object);
-
- /**
- * Sets the byte available for memory manager use in an object.
- *
- * @param object the address of the object
- * @param val the new value of the byte
- */
- public native void writeAvailableByte(ObjectReference object, byte val);
-
- /**
- * Read the byte available for memory manager use in an object.
- *
- * @param object the address of the object
- * @return the value of the byte
- */
- public native byte readAvailableByte(ObjectReference object);
-
- /**
- * Sets the bits available for memory manager use in an object.
- *
- * @param object the address of the object
- * @param val the new value of the bits
- */
- public native void writeAvailableBitsWord(ObjectReference object, Word val);
-
- /**
- * Read the bits available for memory manager use in an object.
- *
- * @param object the address of the object
- * @return the value of the bits
- */
- public native Word readAvailableBitsWord(ObjectReference object);
-
- /**
- * Gets the offset of the memory management header from the object
- * reference address. XXX The object model / memory manager
- * interface should be improved so that the memory manager does not
- * need to know this.
- *
- * @return the offset, relative the object reference address
- */
- /* AJG: Should this be a variable rather than method? */
- public native Offset GC_HEADER_OFFSET();
-
- /**
- * Returns the lowest address of the storage associated with an object.
- *
- * @param object the reference address of the object
- * @return the lowest address of the object
- */
- @Inline
- public native Address objectStartRef(ObjectReference object);
-
- /**
- * Returns an address guaranteed to be inside the storage assocatied
- * with and object.
- *
- * @param object the reference address of the object
- * @return an address inside the object
- */
- public native Address refToAddress(ObjectReference object);
-
- /**
- * Checks if a reference of the given type in another object is
- * inherently acyclic.
- *
- * @return <code>true</code> if a reference of the type is
- * inherently acyclic
- */
- @Inline
- public native boolean isAcyclic(ObjectReference typeRef);
-
- /**
- * Dump debugging information for an object.
- *
- * @param object The object whose information is to be dumped
- */
- public native void dumpObject(ObjectReference object);
-}
-
diff --git a/vmkit/mmtk/java/src/org/j3/mmtk/ReferenceProcessor.java b/vmkit/mmtk/java/src/org/j3/mmtk/ReferenceProcessor.java
deleted file mode 100644
index c314007..0000000
--- a/vmkit/mmtk/java/src/org/j3/mmtk/ReferenceProcessor.java
+++ /dev/null
@@ -1,105 +0,0 @@
-//===--------------------- ReferenceProcessor.java ------------------------===//
-//
-// The VMKit project
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-
-package org.j3.mmtk;
-
-import org.mmtk.plan.Plan;
-import org.mmtk.plan.TraceLocal;
-import org.mmtk.utility.options.Options;
-
-import org.vmmagic.pragma.*;
-import org.vmmagic.unboxed.*;
-
-import org.j3.runtime.VM;
-
-@Uninterruptible
-public final class ReferenceProcessor extends org.mmtk.vm.ReferenceProcessor {
-
- /********************************************************************
- * Class fields
- */
-
- private static final ReferenceProcessor softReferenceProcessor =
- new ReferenceProcessor(Semantics.SOFT);
- private static final ReferenceProcessor weakReferenceProcessor =
- new ReferenceProcessor(Semantics.WEAK);
- private static final ReferenceProcessor phantomReferenceProcessor =
- new ReferenceProcessor(Semantics.PHANTOM);
-
- private final Semantics semantics;
- private int SemanticsNum;
-
- private ReferenceProcessor(Semantics semantics) {
- this.semantics = semantics;
- SemanticsNum = semantics.ordinal();
- }
-
- /**
- * Factory method.
- * Creates an instance of the appropriate reference type processor.
- * @return the reference processor
- */
- @Interruptible
- public static ReferenceProcessor get(Semantics semantics) {
- switch(semantics) {
- case WEAK: return weakReferenceProcessor;
- case SOFT: return softReferenceProcessor;
- case PHANTOM: return phantomReferenceProcessor;
- default:
- VM._assert(false,"Unrecognized semantics");
- return null;
- }
- }
-
- /**
- * Scan through all references and forward.
- *
- * Collectors like MarkCompact determine liveness and move objects
- * using separate traces.
- *
- * Currently ignores the nursery hint.
- *
- * TODO parallelise this code
- *
- * @param trace The trace
- * @param nursery Is this a nursery collection ?
- */
- @Override
- public native void forward(TraceLocal trace, boolean nursery);
-
- /**
- * Clear the contents of the table. This is called when reference types are
- * disabled to make it easier for VMs to change this setting at runtime.
- */
- @Override
- public native void clear();
-
- /**
- * Scan through the list of references. Calls ReferenceProcessor's
- * processReference method for each reference and builds a new
- * list of those references still active.
- *
- * Depending on the value of <code>nursery</code>, we will either
- * scan all references, or just those created since the last scan.
- *
- * TODO parallelise this code
- *
- * @param nursery Scan only the newly created references
- */
- @Override
- public native void scan(TraceLocal trace, boolean nursery);
-
- /***********************************************************************
- *
- * Statistics and debugging
- */
-
- public native int countWaitingReferences();
-}
diff --git a/vmkit/mmtk/java/src/org/j3/mmtk/Scanning.java b/vmkit/mmtk/java/src/org/j3/mmtk/Scanning.java
deleted file mode 100644
index a96d4f3..0000000
--- a/vmkit/mmtk/java/src/org/j3/mmtk/Scanning.java
+++ /dev/null
@@ -1,145 +0,0 @@
-//===------------------------- Scanning.java ------------------------------===//
-//
-// The VMKit project
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-package org.j3.mmtk;
-
-import org.mmtk.plan.TraceLocal;
-import org.mmtk.plan.TransitiveClosure;
-
-import org.vmmagic.unboxed.*;
-import org.vmmagic.pragma.*;
-
-@Uninterruptible
-public final class Scanning extends org.mmtk.vm.Scanning {
-
- @Inline
- public native void scanObject(TransitiveClosure trace, ObjectReference object);
-
- /**
- * Invoke a specialized scan method. Note that these methods must have been allocated
- * explicitly through Plan and PlanConstraints.
- *
- * @param id The specialized method id
- * @param trace The trace the method has been specialized for
- * @param object The object to be scanned
- */
- @Inline
- public native void specializedScanObject(int id, TransitiveClosure trace, ObjectReference object);
-
-
- /**
- * Precopying of a object's fields, processing each pointer field encountered.
- *
- * @param trace The trace being used.
- * @param object The object to be scanned.
- */
- @Inline
- public native void precopyChildren(TraceLocal trace, ObjectReference object);
-
- /**
- * Prepares for using the <code>computeAllRoots</code> method. The
- * thread counter allows multiple GC threads to co-operatively
- * iterate through the thread data structure (if load balancing
- * parallel GC threads were not important, the thread counter could
- * simply be replaced by a for loop).
- */
- public native void resetThreadCounter();
-
- /**
- * Pre-copy all potentially movable instances used in the course of
- * GC. This includes the thread objects representing the GC threads
- * themselves. It is crucial that these instances are forwarded
- * <i>prior</i> to the GC proper. Since these instances <i>are
- * not</i> enqueued for scanning, it is important that when roots
- * are computed the same instances are explicitly scanned and
- * included in the set of roots. The existence of this method
- * allows the actions of calculating roots and forwarding GC
- * instances to be decoupled.
- *
- * The thread table is scanned in parallel by each processor, by striding
- * through the table at a gap of chunkSize*numProcs. Feel free to adjust
- * chunkSize if you want to tune a parallel collector.
- *
- * Explicitly no-inlined to prevent over-inlining of collectionPhase.
- *
- * TODO Experiment with specialization to remove virtual dispatch ?
- */
- @NoInline
- public native void preCopyGCInstances(TraceLocal trace);
-
- /**
- * Computes static roots. This method establishes all such roots for
- * collection and places them in the root locations queue. This method
- * should not have side effects (such as copying or forwarding of
- * objects). There are a number of important preconditions:
- *
- * <ul>
- * <li> All objects used in the course of GC (such as the GC thread
- * objects) need to be "pre-copied" prior to calling this method.
- * <li> The <code>threadCounter</code> must be reset so that load
- * balancing parallel GC can share the work of scanning threads.
- * </ul>
- *
- * @param trace The trace to use for computing roots.
- */
- public native void computeStaticRoots(TraceLocal trace);
-
- /**
- * Computes global roots. This method establishes all such roots for
- * collection and places them in the root locations queue. This method
- * should not have side effects (such as copying or forwarding of
- * objects). There are a number of important preconditions:
- *
- * <ul>
- * <li> All objects used in the course of GC (such as the GC thread
- * objects) need to be "pre-copied" prior to calling this method.
- * <li> The <code>threadCounter</code> must be reset so that load
- * balancing parallel GC can share the work of scanning threads.
- * </ul>
- *
- * @param trace The trace to use for computing roots.
- */
- public native void computeGlobalRoots(TraceLocal trace);
-
- /**
- * Computes roots pointed to by threads, their associated registers
- * and stacks. This method places these roots in the root values,
- * root locations and interior root locations queues. This method
- * should not have side effects (such as copying or forwarding of
- * objects). There are a number of important preconditions:
- *
- * <ul>
- * <li> All objects used in the course of GC (such as the GC thread
- * objects) need to be "pre-copied" prior to calling this method.
- * <li> The <code>threadCounter</code> must be reset so that load
- * balancing parallel GC can share the work of scanning threads.
- * </ul>
- *
- * TODO rewrite to avoid the per-thread synchronization, like precopy.
- *
- * @param trace The trace to use for computing roots.
- */
- public native void computeThreadRoots(TraceLocal trace);
-
- /**
- * Compute all roots out of the VM's boot image (if any). This method is a no-op
- * in the case where the VM does not maintain an MMTk-visible Java space. However,
- * when the VM does maintain a space (such as a boot image) which is visible to MMTk,
- * that space could either be scanned by MMTk as part of its transitive closure over
- * the whole heap, or as a (considerable) performance optimization, MMTk could avoid
- * scanning the space if it is aware of all pointers out of that space. This method
- * is used to establish the root set out of the scannable space in the case where
- * such a space exists.
- *
- * @param trace The trace object to use to report root locations.
- */
- public void computeBootImageRoots(TraceLocal trace) {
- }
-}
-
diff --git a/vmkit/mmtk/java/src/org/j3/mmtk/Statistics.java b/vmkit/mmtk/java/src/org/j3/mmtk/Statistics.java
deleted file mode 100644
index 2ad564d..0000000
--- a/vmkit/mmtk/java/src/org/j3/mmtk/Statistics.java
+++ /dev/null
@@ -1,76 +0,0 @@
-//===------------------------ Statistics.java -----------------------------===//
-//
-// The VMKit project
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-package org.j3.mmtk;
-
-import org.vmmagic.pragma.*;
-
-@Uninterruptible
-public final class Statistics extends org.mmtk.vm.Statistics {
- /**
- * Returns the number of collections that have occurred.
- *
- * @return The number of collections that have occurred.
- */
- @Uninterruptible
- public native int getCollectionCount();
-
- /**
- * Read nanoTime (high resolution, monotonically increasing clock).
- * Has same semantics as java.lang.System.nanoTime().
- */
- public native long nanoTime();
-
- /**
- * Read a cycle counter (high resolution, non-monotonic clock).
- * This method should be used with care as the cycle counters (especially on IA32 SMP machines)
- * are not a reliably time source.
- */
- public native long cycles();
-
- /**
- * Convert nanoseconds to milliseconds
- */
- public double nanosToMillis(long c) {
- return ((double)c)/1e6;
- }
-
- /**
- * Convert nanoseconds to seconds
- */
- public double nanosToSecs(long c) {
- return ((double)c)/1e9;
- }
-
- /**
- * Convert milliseconds to nanoseconds
- */
- public long millisToNanos(double t) {
- return (long)(t * 1e6);
- }
-
- /**
- * Convert seconds to nanoseconds
- */
- public long secsToNanos(double t) {
- return (long)(t * 1e9);
- }
-
- /**
- * Initialize performance events
- */
- @Interruptible
- public native void perfEventInit(String events);
-
- /**
- * Read a performance event
- */
- public native void perfEventRead(int id, long[] values);
-}
-
diff --git a/vmkit/mmtk/java/src/org/j3/mmtk/Strings.java b/vmkit/mmtk/java/src/org/j3/mmtk/Strings.java
deleted file mode 100644
index 9db29e5..0000000
--- a/vmkit/mmtk/java/src/org/j3/mmtk/Strings.java
+++ /dev/null
@@ -1,49 +0,0 @@
-//===------------------------- Strings.java -------------------------------===//
-//
-// The VMKit project
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-package org.j3.mmtk;
-
-import org.vmmagic.pragma.Uninterruptible;
-
-
-@Uninterruptible
-public final class Strings extends org.mmtk.vm.Strings {
- /**
- * Log a message.
- *
- * @param c character array with message starting at index 0
- * @param len number of characters in message
- */
- public native void write(char [] c, int len);
-
- /**
- * Log a thread identifier and a message.
- *
- * @param c character array with message starting at index 0
- * @param len number of characters in message
- */
- public native void writeThreadId(char [] c, int len);
-
- /**
- * Copies characters from the string into the character array.
- * Thread switching is disabled during this method's execution.
- * <p>
- * <b>TODO:</b> There are special memory management semantics here that
- * someone should document.
- *
- * @param src the source string
- * @param dst the destination array
- * @param dstBegin the start offset in the desination array
- * @param dstEnd the index after the last character in the
- * destination to copy to
- * @return the number of characters copied.
- */
- public native int copyStringToChars(String src, char [] dst,
- int dstBegin, int dstEnd);
-}
diff --git a/vmkit/mmtk/java/src/org/j3/mmtk/SynchronizedCounter.java b/vmkit/mmtk/java/src/org/j3/mmtk/SynchronizedCounter.java
deleted file mode 100644
index 284d98f..0000000
--- a/vmkit/mmtk/java/src/org/j3/mmtk/SynchronizedCounter.java
+++ /dev/null
@@ -1,27 +0,0 @@
-//===---------- SynchronizedCounter.java - Atomic counter -----------------===//
-//
-// The VMKit project
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-package org.j3.mmtk;
-
-/**
- * A counter that supports atomic increment and reset.
- */
-public final class SynchronizedCounter extends org.mmtk.vm.SynchronizedCounter {
-
- private int count = 0;
-
- public native int reset();
-
- public native int increment();
-
- public int peek() {
- return count;
- }
-
-}
diff --git a/vmkit/mmtk/java/src/org/j3/mmtk/TraceInterface.java b/vmkit/mmtk/java/src/org/j3/mmtk/TraceInterface.java
deleted file mode 100644
index a354427..0000000
--- a/vmkit/mmtk/java/src/org/j3/mmtk/TraceInterface.java
+++ /dev/null
@@ -1,80 +0,0 @@
-//===----------------------- TraceInterface.java --------------------------===//
-//
-// The VMKit project
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-
-
-package org.j3.mmtk;
-
-import org.vmmagic.unboxed.*;
-import org.vmmagic.pragma.*;
-
-/**
- * Class that supports scanning Objects or Arrays for references
- * during tracing, handling those references, and computing death times
- */
-@Uninterruptible
-public class TraceInterface extends org.mmtk.vm.TraceInterface {
-
-
- /***********************************************************************
- *
- * Public Methods
- */
-
- /**
- * Returns if the VM is ready for a garbage collection.
- *
- * @return True if the VM is ready for GC, false otherwise.
- */
- public native boolean gcEnabled();
-
- /**
- * This adjusts the offset into an object to reflect what it would look like
- * if the fields were laid out in memory space immediately after the object
- * pointer.
- *
- * @param isScalar If this is a pointer store to a scalar object
- * @param src The address of the source object
- * @param slot The address within <code>src</code> into which
- * the update will be stored
- * @return The easy to understand offset of the slot
- */
- public native Offset adjustSlotOffset(boolean isScalar,
- ObjectReference src,
- Address slot);
-
- /**
- * This skips over the frames added by the tracing algorithm, outputs
- * information identifying the method the containts the "new" call triggering
- * the allocation, and returns the address of the first non-trace, non-alloc
- * stack frame.
- *
- *@param typeRef The type reference (tib) of the object just allocated
- * @return The frame pointer address for the method that allocated the object
- */
- @Interruptible
- public native Address skipOwnFramesAndDump(ObjectReference typeRef);
-
- /***********************************************************************
- *
- * Wrapper methods
- */
- public native void updateDeathTime(ObjectReference obj);
- public native void setDeathTime(ObjectReference ref, Word time_);
- public native void setLink(ObjectReference ref, ObjectReference link);
- public native void updateTime(Word time_);
- public native Word getOID(ObjectReference ref);
- public native Word getDeathTime(ObjectReference ref);
- public native ObjectReference getLink(ObjectReference ref);
- public native Address getBootImageLink();
- public native Word getOID();
- public native void setOID(Word oid);
- public native int getHeaderSize();
- public native int getHeaderEndOffset();
-}
diff --git a/vmkit/mmtk/java/src/org/j3/options/OptionSet.java b/vmkit/mmtk/java/src/org/j3/options/OptionSet.java
deleted file mode 100644
index 2223c43..0000000
--- a/vmkit/mmtk/java/src/org/j3/options/OptionSet.java
+++ /dev/null
@@ -1,161 +0,0 @@
-//===------------------------- OptionSet.java -----------------------------===//
-//
-// The VMKit project
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-package org.j3.options;
-
-
-import org.mmtk.utility.Constants;
-import org.vmmagic.pragma.Uninterruptible;
-import org.vmmagic.unboxed.Extent;
-import org.vmmagic.unboxed.Word;
-import org.vmutil.options.AddressOption;
-import org.vmutil.options.BooleanOption;
-import org.vmutil.options.EnumOption;
-import org.vmutil.options.FloatOption;
-import org.vmutil.options.IntOption;
-import org.vmutil.options.MicrosecondsOption;
-import org.vmutil.options.Option;
-import org.vmutil.options.PagesOption;
-import org.vmutil.options.StringOption;
-
-import org.jikesrvm.SizeConstants;
-import org.j3.runtime.VM;
-
-/**
- * Class to handle command-line arguments and options for GC.
- */
-public final class OptionSet extends org.vmutil.options.OptionSet {
-
- private String prefix;
-
- public static final OptionSet gc = new OptionSet("-X:gc");
-
- private OptionSet(String prefix) {
- this.prefix = prefix;
- }
-
- /**
- * Format and log an option value.
- *
- * @param o The option.
- * @param forXml Is this part of xml output?
- */
- protected void logValue(Option o, boolean forXml) {
- switch (o.getType()) {
- case Option.BOOLEAN_OPTION:
- VM.sysWrite(((BooleanOption) o).getValue() ? "true" : "false");
- break;
- case Option.INT_OPTION:
- VM.sysWrite(((IntOption) o).getValue());
- break;
- case Option.ADDRESS_OPTION:
- VM.sysWrite(((AddressOption) o).getValue());
- break;
- case Option.FLOAT_OPTION:
- VM.sysWrite(((FloatOption) o).getValue());
- break;
- case Option.MICROSECONDS_OPTION:
- VM.sysWrite(((MicrosecondsOption) o).getMicroseconds());
- VM.sysWrite(" usec");
- break;
- case Option.PAGES_OPTION:
- VM.sysWrite(((PagesOption) o).getBytes());
- VM.sysWrite(" bytes");
- break;
- case Option.STRING_OPTION:
- VM.sysWrite(((StringOption) o).getValue());
- break;
- case Option.ENUM_OPTION:
- VM.sysWrite(((EnumOption) o).getValueString());
- break;
- }
- }
-
- /**
- * Log a string.
- */
- protected void logString(String s) {
- VM.sysWrite(s);
- }
-
- /**
- * Print a new line.
- */
- protected void logNewLine() {
- VM.sysWriteln();
- }
-
- /**
- * Determine the VM specific key for a given option name. Option names are
- * space delimited with capitalised words (e.g. "GC Verbosity Level").
- *
- * @param name The option name.
- * @return The VM specific key.
- */
- protected String computeKey(String name) {
- int space = name.indexOf(' ');
- if (space < 0) return name.toLowerCase();
-
- String word = name.substring(0, space);
- String key = word.toLowerCase();
-
- do {
- int old = space+1;
- space = name.indexOf(' ', old);
- if (space < 0) {
- key += name.substring(old);
- return key;
- }
- key += name.substring(old, space);
- } while (true);
- }
-
- /**
- * A non-fatal error occurred during the setting of an option. This method
- * calls into the VM and shall not cause the system to stop.
- *
- * @param o The responsible option.
- * @param message The message associated with the warning.
- */
- protected void warn(Option o, String message) {
- VM.sysWriteln("WARNING: Option '" + o.getKey() + "' : " + message);
- }
-
- /**
- * A fatal error occurred during the setting of an option. This method
- * calls into the VM and is required to cause the system to stop.
- *
- * @param o The responsible option.
- * @param message The error message associated with the failure.
- */
- protected void fail(Option o, String message) {
- VM.sysFail("ERROR: Option '" + o.getKey() + "' : " + message);
- }
-
- /**
- * Convert bytes into pages, rounding up if necessary.
- *
- * @param bytes The number of bytes.
- * @return The corresponding number of pages.
- */
- @Uninterruptible
- protected int bytesToPages(Extent bytes) {
- return bytes.plus(Constants.BYTES_IN_PAGE-1).toWord().rshl(Constants.LOG_BYTES_IN_PAGE).toInt();
- }
-
- /**
- * Convert from pages into bytes.
- * @param pages the number of pages.
- * @return The corresponding number of bytes.
- */
- @Uninterruptible
- protected Extent pagesToBytes(int pages) {
- return Word.fromIntZeroExtend(pages).lsh(Constants.LOG_BYTES_IN_PAGE).toExtent();
- }
-}
diff --git a/vmkit/mmtk/java/src/org/j3/runtime/VM.java b/vmkit/mmtk/java/src/org/j3/runtime/VM.java
deleted file mode 100644
index 8edae0e..0000000
--- a/vmkit/mmtk/java/src/org/j3/runtime/VM.java
+++ /dev/null
@@ -1,41 +0,0 @@
-//===---------------------------- VM.java ---------------------------------===//
-//
-// The VMKit project
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-
-package org.j3.runtime;
-
-import org.vmmagic.unboxed.Address;
-import org.vmmagic.unboxed.Extent;
-
-public final class VM {
-
- private native static boolean verifyAssertions();
- private native static boolean buildForIA32();
- private native static boolean buildFor64Addr();
-
- public final static boolean NOT_REACHED = false;
-
- public final static boolean VerifyAssertions = verifyAssertions();
- public final static boolean runningVM = false;
- public final static boolean BuildForIA32 = buildForIA32();
- public final static boolean BuildFor64Addr = buildFor64Addr();
-
-
- public native static void sysFail(String a);
- public native static void sysExit(int a);
- public native static void _assert(boolean cond);
- public native static void _assert(boolean cond, String msg);
- public native static void sysWriteln(String a);
- public native static void sysWriteln();
- public native static void sysWrite(String a);
- public native static void sysWrite(int a);
- public native static void sysWrite(float a);
- public native static void sysWrite(Address a);
- public native static void sysWrite(Extent a);
-}
diff --git a/vmkit/mmtk/java/src/org/jikesrvm/Magic.java b/vmkit/mmtk/java/src/org/jikesrvm/Magic.java
deleted file mode 100644
index 9039eab..0000000
--- a/vmkit/mmtk/java/src/org/jikesrvm/Magic.java
+++ /dev/null
@@ -1,592 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.jikesrvm;
-
-import org.j3.runtime.VM;
-
-import org.vmmagic.Intrinsic;
-import org.vmmagic.pragma.Entrypoint;
-import org.vmmagic.pragma.Uninterruptible;
-import org.vmmagic.unboxed.Address;
-import org.vmmagic.unboxed.Extent;
-import org.vmmagic.unboxed.Offset;
-import org.vmmagic.unboxed.Word;
-import org.vmmagic.unboxed.WordArray;
-
-/**
- * Magic methods for accessing raw machine memory, registers, and
- * operating system calls.
- *
- * <p> These are "inline assembler functions" that cannot be implemented in
- * Java code. Their names are recognized by RVM's compilers
- * and cause inline machine code to be generated instead of
- * actual method calls.
- */
-@SuppressWarnings({"UnusedDeclaration"})
-@Intrinsic
-public final class Magic {
-
- //---------------------------------------//
- // Memory Access. //
- //---------------------------------------//
-
- /**
- * Get unsigned byte at arbitrary (byte) offset from object. The
- * most significant 24bits of the result will be 0.
- */
- public static byte getUnsignedByteAtOffset(Object object, Offset offset) {
- if (VM.VerifyAssertions) VM._assert(VM.NOT_REACHED); // call site should have been hijacked by magic in compiler
- return -1;
- }
-
- /**
- * Get byte at arbitrary (byte) offset from object. The most
- * significant 24bits of the result will be the same as the most
- * significant bit in the byte.
- */
- public static byte getByteAtOffset(Object object, Offset offset) {
- if (VM.VerifyAssertions) VM._assert(VM.NOT_REACHED); // call site should have been hijacked by magic in compiler
- return -1;
- }
-
- /**
- * Get char at arbitrary (byte) offset from object. The most
- * significant 16bits will be 0.
- */
- public static char getCharAtOffset(Object object, Offset offset) {
- if (VM.VerifyAssertions) VM._assert(VM.NOT_REACHED); // call site should have been hijacked by magic in compiler
- return (char) -1;
- }
-
- /**
- * Get short at arbitrary (byte) offset from object. The most
- * significant 16bits will be the same as the most significant bit
- * in the short.
- */
- public static short getShortAtOffset(Object object, Offset offset) {
- if (VM.VerifyAssertions) VM._assert(VM.NOT_REACHED); // call site should have been hijacked by magic in compiler
- return (short) -1;
- }
-
- /**
- * Get int at arbitrary (byte) offset from object.
- * Use getIntAtOffset(obj, ofs) instead of getMemoryInt(objectAsAddress(obj)+ofs)
- */
- public static int getIntAtOffset(Object object, Offset offset) {
- if (VM.VerifyAssertions) VM._assert(VM.NOT_REACHED); // call site should have been hijacked by magic in compiler
- return -1;
- }
-
- /**
- * Get long at arbitrary (byte) offset from object.
- * Use getlongAtOffset(obj, ofs) instead of two getIntAtOffset
- */
- public static long getLongAtOffset(Object object, Offset offset) {
- if (VM.VerifyAssertions) VM._assert(VM.NOT_REACHED); // call site should have been hijacked by magic in compiler
- return -1;
- }
-
- /**
- * Get float at arbitrary (byte) offset from object.
- */
- public static float getFloatAtOffset(Object object, Offset offset) {
- if (VM.VerifyAssertions) VM._assert(VM.NOT_REACHED); // call site should have been hijacked by magic in compiler
- return -1;
- }
-
- /**
- * Get double at arbitrary (byte) offset from object.
- * Use getDoubleAtOffset(obj, ofs) instead of two getIntAtOffset
- */
- public static double getDoubleAtOffset(Object object, Offset offset) {
- if (VM.VerifyAssertions) VM._assert(VM.NOT_REACHED); // call site should have been hijacked by magic in compiler
- return -1;
- }
-
- /**
- * Get Object at arbitrary (byte) offset from object.
- * Use getObjectAtOffset(obj, ofs) instead of
- * addressAsObject(getMemoryAddress(objectAsAddress(obj)+ofs))
- */
- public static Object getObjectAtOffset(Object object, Offset offset) {
- if (VM.VerifyAssertions) VM._assert(VM.NOT_REACHED); // call site should have been hijacked by magic in compiler
- return null;
- }
-
- /**
- * Get Object at arbitrary (byte) offset from object.
- * Use getObjectAtOffset(obj, ofs) instead of
- * addressAsObject(getMemoryAddress(objectAsAddress(obj)+ofs))
- */
- public static Object getObjectAtOffset(Object object, Offset offset, int locationMetadata) {
- if (VM.VerifyAssertions) VM._assert(VM.NOT_REACHED); // call site should have been hijacked by magic in compiler
- return null;
- }
-
- /**
- * Get Word at arbitrary (byte) offset from object.
- * Use getWordAtOffset(obj, ofs) instead of getMemoryWord(objectAsAddress(obj)+ofs)
- */
- public static Word getWordAtOffset(Object object, Offset offset) {
- if (VM.VerifyAssertions) VM._assert(VM.NOT_REACHED); // call site should have been hijacked by magic in compiler
- return Word.max();
- }
-
- /**
- * Get Word at arbitrary (byte) offset from object.
- */
- public static Word getWordAtOffset(Object object, Offset offset, int locationMetadata) {
- if (VM.VerifyAssertions) VM._assert(VM.NOT_REACHED); // call site should have been hijacked by magic in compiler
- return null;
- }
-
- /**
- * Get Address at arbitrary (byte) offset from object.
- * Use getAddressAtOffset(obj, ofs) instead of getMemoryWord(objectAsAddress(obj)+ofs)
- */
- public static Address getAddressAtOffset(Object object, Offset offset) {
- if (VM.VerifyAssertions) VM._assert(VM.NOT_REACHED); // call site should have been hijacked by magic in compiler
- return null;
- }
-
- /**
- * Get Address at arbitrary (byte) offset from object.
- */
- public static Address getAddressAtOffset(Object object, Offset offset, int locationMetadata) {
- if (VM.VerifyAssertions) VM._assert(VM.NOT_REACHED); // call site should have been hijacked by magic in compiler
- return null;
- }
-
- /**
- * Get Extent at arbitrary (byte) offset from object.
- * Use getExtentAtOffset(obj, ofs) instead of getMemoryWord(objectAsAddress(obj)+ofs)
- */
- public static Extent getExtentAtOffset(Object object, Offset offset) {
- if (VM.VerifyAssertions) VM._assert(VM.NOT_REACHED); // call site should have been hijacked by magic in compiler
- return null;
- }
-
- /**
- * Get Extent at arbitrary (byte) offset from object.
- */
- public static Extent getExtentAtOffset(Object object, Offset offset, int locationMetadata) {
- if (VM.VerifyAssertions) VM._assert(VM.NOT_REACHED); // call site should have been hijacked by magic in compiler
- return null;
- }
-
- /**
- * Get Offset at arbitrary (byte) offset from object.
- * Use getOffsetAtOffset(obj, ofs) instead of getMemoryWord(objectAsAddress(obj)+ofs)
- */
- public static Offset getOffsetAtOffset(Object object, Offset offset) {
- if (VM.VerifyAssertions) VM._assert(VM.NOT_REACHED); // call site should have been hijacked by magic in compiler
- return null;
- }
-
- /**
- * Get Offset at arbitrary (byte) offset from object.
- */
- public static Offset getOffsetAtOffset(Object object, Offset offset, int locationMetadata) {
- if (VM.VerifyAssertions) VM._assert(VM.NOT_REACHED); // call site should have been hijacked by magic in compiler
- return null;
- }
-
- /**
- * Set boolean at arbitrary (byte) offset from object.
- */
- public static void setBooleanAtOffset(Object object, Offset offset, boolean newvalue) {
- if (VM.VerifyAssertions)
- VM._assert(VM.NOT_REACHED); // call site should have been hijacked by magic in compiler
- }
-
- /**
- * Set boolean at arbitrary (byte) offset from object.
- */
- public static void setBooleanAtOffset(Object object, Offset offset, boolean newvalue, int locationMetadata) {
- if (VM.VerifyAssertions)
- VM._assert(VM.NOT_REACHED); // call site should have been hijacked by magic in compiler
- }
-
- /**
- * Set byte at arbitrary (byte) offset from object.
- */
- public static void setByteAtOffset(Object object, Offset offset, byte newvalue) {
- if (VM.VerifyAssertions) VM._assert(VM.NOT_REACHED); // call site should have been hijacked by magic in compiler
- }
-
- /**
- * Set byte at arbitrary (byte) offset from object.
- */
- public static void setByteAtOffset(Object object, Offset offset, byte newvalue, int locationMetadata) {
- if (VM.VerifyAssertions)
- VM._assert(VM.NOT_REACHED); // call site should have been hijacked by magic in compiler
- }
-
- /**
- * Set char at arbitrary (byte) offset from object.
- */
- public static void setCharAtOffset(Object object, Offset offset, char newvalue) {
- if (VM.VerifyAssertions) VM._assert(VM.NOT_REACHED); // call site should have been hijacked by magic in compiler
- }
-
- /**
- * Set char at arbitrary (byte) offset from object.
- */
- public static void setCharAtOffset(Object object, Offset offset, char newvalue, int locationMetadata) {
- if (VM.VerifyAssertions)
- VM._assert(VM.NOT_REACHED); // call site should have been hijacked by magic in compiler
- }
-
- /**
- * Set short at arbitrary (byte) offset from object.
- */
- public static void setShortAtOffset(Object object, Offset offset, short newvalue) {
- if (VM.VerifyAssertions) VM._assert(VM.NOT_REACHED); // call site should have been hijacked by magic in compiler
- }
-
- /**
- * Set short at arbitrary (byte) offset from object.
- */
- public static void setShortAtOffset(Object object, Offset offset, short newvalue, int locationMetadata) {
- if (VM.VerifyAssertions)
- VM._assert(VM.NOT_REACHED); // call site should have been hijacked by magic in compiler
- }
-
- /**
- * Set int at arbitrary (byte) offset from object.
- * Use setIntAtOffset(obj, ofs, new) instead of setMemoryWord(objectAsAddress(obj)+ofs, new)
- */
- public static void setIntAtOffset(Object object, Offset offset, int newvalue) {
- if (VM.VerifyAssertions) VM._assert(VM.NOT_REACHED); // call site should have been hijacked by magic in compiler
- }
-
- /**
- * Set int at arbitrary (byte) offset from object.
- */
- public static void setIntAtOffset(Object object, Offset offset, int newvalue, int locationMetadata) {
- if (VM.VerifyAssertions)
- VM._assert(VM.NOT_REACHED); // call site should have been hijacked by magic in compiler
- }
-
- /**
- * Set long at arbitrary (byte) offset from object.
- * Use setlongAtOffset(obj, ofs) instead of two setIntAtOffset
- */
- public static void setLongAtOffset(Object object, Offset offset, long newvalue) {
- if (VM.VerifyAssertions) VM._assert(VM.NOT_REACHED); // call site should have been hijacked by magic in compiler
- }
-
- /**
- * Set long at arbitrary (byte) offset from object. Use setlongAtOffset(obj,
- * ofs) instead of two setIntAtOffset
- */
- public static void setLongAtOffset(Object object, Offset offset, long newvalue, int locationMetadata) {
- if (VM.VerifyAssertions)
- VM._assert(VM.NOT_REACHED); // call site should have been hijacked by magic in compiler
- }
-
- /**
- * Set float at arbitrary (byte) offset from object.
- */
- public static void setFloatAtOffset(Object object, Offset offset, float newvalue) {
- if (VM.VerifyAssertions) VM._assert(VM.NOT_REACHED); // call site should have been hijacked by magic in compiler
- }
-
- /**
- * Set float at arbitrary (byte) offset from object.
- */
- public static void setFloatAtOffset(Object object, Offset offset, float newvalue, int locationMetadata) {
- if (VM.VerifyAssertions)
- VM._assert(VM.NOT_REACHED); // call site should have been hijacked by magic in compiler
- }
-
- /**
- * Set double at arbitrary (byte) offset from object.
- * Use setDoubleAtOffset(obj, ofs) instead of two setIntAtOffset
- */
- public static void setDoubleAtOffset(Object object, Offset offset, double newvalue) {
- if (VM.VerifyAssertions) VM._assert(VM.NOT_REACHED); // call site should have been hijacked by magic in compiler
- }
-
- /**
- * Set double at arbitrary (byte) offset from object. Use
- * setDoubleAtOffset(obj, ofs) instead of two setIntAtOffset
- */
- public static void setDoubleAtOffset(Object object, Offset offset, double newvalue, int locationMetadata) {
- if (VM.VerifyAssertions)
- VM._assert(VM.NOT_REACHED); // call site should have been hijacked by magic in compiler
- }
-
- /**
- * Set Word at arbitrary (byte) offset from object.
- * Use setWordAtOffset(obj, ofs, new) instead of setMemoryWord(objectAsAddress(obj)+ofs, new)
- */
- public static void setWordAtOffset(Object object, Offset offset, Word newvalue) {
- if (VM.VerifyAssertions) VM._assert(VM.NOT_REACHED); // call site should have been hijacked by magic in compiler
- }
-
- /**
- * Set Word at arbitrary (byte) offset from object.
- * Use setWordAtOffset(obj, ofs, new) instead of setMemoryWord(objectAsAddress(obj)+ofs, new)
- */
- public static void setWordAtOffset(Object object, Offset offset, Word newvalue, int locationMetadata) {
- if (VM.VerifyAssertions) VM._assert(VM.NOT_REACHED); // call site should have been hijacked by magic in compiler
- }
-
- /**
- * Set Address at arbitrary (byte) offset from object.
- * Use setAddressAtOffset(obj, ofs, new) instead of setMemoryWord(objectAsAddress(obj)+ofs, new)
- */
- public static void setAddressAtOffset(Object object, Offset offset, Address newvalue) {
- if (VM.VerifyAssertions) VM._assert(VM.NOT_REACHED); // call site should have been hijacked by magic in compiler
- }
-
- /**
- * Set Address at arbitrary (byte) offset from object.
- * Use setAddressAtOffset(obj, ofs, new) instead of setMemoryWord(objectAsAddress(obj)+ofs, new)
- */
- public static void setAddressAtOffset(Object object, Offset offset, Address newvalue, int locationMetadata) {
- if (VM.VerifyAssertions) VM._assert(VM.NOT_REACHED); // call site should have been hijacked by magic in compiler
- }
-
- /**
- * Set Extent at arbitrary (byte) offset from object.
- * Use setExtentAtOffset(obj, ofs, new) instead of setMemoryWord(objectAsAddress(obj)+ofs, new)
- */
- public static void setExtentAtOffset(Object object, Offset offset, Extent newvalue) {
- if (VM.VerifyAssertions) VM._assert(VM.NOT_REACHED); // call site should have been hijacked by magic in compiler
- }
-
- /**
- * Set Extent at arbitrary (byte) offset from object.
- * Use setExtenttOffset(obj, ofs, new) instead of setMemoryWord(objectAsAddress(obj)+ofs, new)
- */
- public static void setExtentAtOffset(Object object, Offset offset, Extent newvalue, int locationMetadata) {
- if (VM.VerifyAssertions) VM._assert(VM.NOT_REACHED); // call site should have been hijacked by magic in compiler
- }
-
- /**
- * Set Offset at arbitrary (byte) offset from object.
- * Use setOffsetAtOffset(obj, ofs, new) instead of setMemoryWord(objectAsAddress(obj)+ofs, new)
- */
- public static void setOffsetAtOffset(Object object, Offset offset, Offset newvalue) {
- if (VM.VerifyAssertions) VM._assert(VM.NOT_REACHED); // call site should have been hijacked by magic in compiler
- }
-
- /**
- * Set Offset at arbitrary (byte) offset from object.
- * Use setOffsetAtOffset(obj, ofs, new) instead of setMemoryWord(objectAsAddress(obj)+ofs, new)
- */
- public static void setOffsetAtOffset(Object object, Offset offset, Offset newvalue, int locationMetadata) {
- if (VM.VerifyAssertions) VM._assert(VM.NOT_REACHED); // call site should have been hijacked by magic in compiler
- }
-
- /**
- * Set Object at arbitrary (byte) offset from object.
- * Use setObjectAtOffset(obj, ofs, new) instead of setMemoryWord(objectAsAddress(obj)+ofs, objectAsAddress(new))
- */
- public static void setObjectAtOffset(Object object, Offset offset, Object newvalue) {
- if (VM.VerifyAssertions) VM._assert(VM.NOT_REACHED); // call site should have been hijacked by magic in compiler
- }
-
- /**
- * Set Object at arbitrary (byte) offset from object.
- */
- public static void setObjectAtOffset(Object object, Offset offset, Object newvalue, int locationMetadata) {
- if (VM.VerifyAssertions) VM._assert(VM.NOT_REACHED); // call site should have been hijacked by magic in compiler
- }
-
-
- //---------------------------------------//
- // Atomic Memory Access Primitives. //
- //---------------------------------------//
-
- /**
- * Get contents of (object + offset) and begin conditional critical section.
- */
- public static int prepareInt(Object object, Offset offset) {
- if (VM.VerifyAssertions) VM._assert(VM.NOT_REACHED); // call site should have been hijacked by magic in compiler
- return -1;
- }
-
- /**
- * Get contents of (object + offset) and begin conditional critical section.
- */
- public static Object prepareObject(Object object, Offset offset) {
- if (VM.VerifyAssertions) VM._assert(VM.NOT_REACHED); // call site should have been hijacked by magic in compiler
- return null;
- }
-
- /**
- * Get contents of (object + offset) and begin conditional critical section.
- */
- public static Address prepareAddress(Object object, Offset offset) {
- if (VM.VerifyAssertions) VM._assert(VM.NOT_REACHED); // call site should have been hijacked by magic in compiler
- return Address.max();
- }
-
- /**
- * Get contents of (object + offset) and begin conditional critical section.
- */
- public static Word prepareWord(Object object, Offset offset) {
- if (VM.VerifyAssertions) VM._assert(VM.NOT_REACHED); // call site should have been hijacked by magic in compiler
- return Word.max();
- }
-
- /**
- * Get contents of (object + offset) and begin conditional critical section.
- */
- @Uninterruptible
- public static long prepareLong(Object object, Offset offset) {
- if (VM.VerifyAssertions) VM._assert(VM.NOT_REACHED); // call site should have been hijacked by magic in compiler
- return -1;
- }
-
- /**
- * Sets the memory at (object + offset) to newValue if its contents are oldValue.
- * Must be paired with a preceding prepare (which returned the oldValue)
- * Returns true if successful.
- * Ends conditional critical section.
- */
- public static boolean attemptInt(Object object, Offset offset, int oldValue, int newValue) {
- if (VM.VerifyAssertions) VM._assert(VM.NOT_REACHED); // call site should have been hijacked by magic in compiler
- return false;
- }
-
- /**
- * Sets the memory at (object + offset) to newValue if its contents are oldValue.
- * Must be paired with a preceding prepare (which returned the oldValue)
- * Returns true if successful.
- * Ends conditional critical section.
- */
- public static boolean attemptObject(Object object, Offset offset, Object oldValue, Object newValue) {
- if (VM.VerifyAssertions) VM._assert(VM.NOT_REACHED); // call site should have been hijacked by magic in compiler
- return false;
- }
-
- /**
- * Sets the memory at (object + offset) to newValue if its contents are oldValue.
- * Must be paired with a preceding prepare (which returned the oldValue)
- * Returns true if successful.
- * Ends conditional critical section.
- */
- public static boolean attemptAddress(Object object, Offset offset, Address oldValue, Address newValue) {
- if (VM.VerifyAssertions) VM._assert(VM.NOT_REACHED); // call site should have been hijacked by magic in compiler
- return false;
- }
-
- /**
- * Sets the memory at (object + offset) to newValue if its contents are oldValue.
- * Must be paired with a preceding prepare (which returned the oldValue)
- * Returns true if successful.
- * Ends conditional critical section.
- */
- public static boolean attemptWord(Object object, Offset offset, Word oldValue, Word newValue) {
- if (VM.VerifyAssertions) VM._assert(VM.NOT_REACHED); // call site should have been hijacked by magic in compiler
- return false;
- }
-
- /**
- * Sets the memory at (object + offset) to newValue if its contents are oldValue.
- * Must be paired with a preceding prepare (which returned the oldValue)
- * Returns true if successful.
- * Ends conditional critical section.
- */
- public static boolean attemptLong(Object object, Offset offset, long oldValue,
- long newValue) {
- if (VM.VerifyAssertions) VM._assert(VM.NOT_REACHED); // call site should have been hijacked by magic in compiler
- return false;
- }
-
- //---------------------------------------//
- // Cache Management. //
- //---------------------------------------//
-
- /**** NOTE: all per-address operations now live in vmmagic.Address *****/
-
- /**
- * Wait for preceeding cache flush/invalidate instructions to
- * complete on all processors.
- */
- public static void sync() {
- if (VM.runningVM && VM.VerifyAssertions) {
- VM._assert(VM.NOT_REACHED); // call site should have been hijacked by magic in compiler
- }
- }
-
- /**
- * Wait for all preceeding instructions to complete and discard any
- * prefetched instructions on this processor.
- */
- public static void isync() {
- if (VM.runningVM && VM.VerifyAssertions) {
- VM._assert(VM.NOT_REACHED); // call site should have been hijacked by magic in compiler
- }
- }
-
- /****************************************************************
- *
- * Misc
- *
- */
-
- /**
- * On IA32, emit a PAUSE instruction, to optimize spin-wait loops.
- */
- public static void pause() {
- if (VM.runningVM && VM.VerifyAssertions) {
- VM._assert(VM.NOT_REACHED); // call site should have been hijacked by magic in compiler
- }
- }
-
- /**
- * A hardware SQRT instruction
- */
- public static float sqrt(float value) {
- if (VM.runningVM && VM.VerifyAssertions) {
- VM._assert(VM.NOT_REACHED); // call site should have been hijacked by magic in compiler
- }
- return -1.0f; // which should upset them even if assertions aren't enabled ...
- }
-
- /**
- * A hardware SQRT instruction
- */
- public static double sqrt(double value) {
- if (VM.runningVM && VM.VerifyAssertions) {
- VM._assert(VM.NOT_REACHED); // call site should have been hijacked by magic in compiler
- }
- return -1.0d; // which should upset them even if assertions aren't enabled ...
- }
-
- /**
- * How deeply inlined is this method (0 means no inlining).
- */
- public static int getInlineDepth() {
- if (VM.runningVM && VM.VerifyAssertions) {
- VM._assert(VM.NOT_REACHED); // call site should have been hijacked by magic in compiler
- }
- return 0;
- }
-
- /**
- * Is the specified parameter constant (due to either inlining or specialization).
- * Count starts at zero and includes the 'this' parameter for instance methods.
- */
- public static boolean isConstantParameter(int index) {
- if (VM.runningVM && VM.VerifyAssertions) {
- VM._assert(VM.NOT_REACHED); // call site should have been hijacked by magic in compiler
- }
- return false;
- }
-}
diff --git a/vmkit/mmtk/java/src/org/jikesrvm/SizeConstants.java b/vmkit/mmtk/java/src/org/jikesrvm/SizeConstants.java
deleted file mode 100644
index e41b83b..0000000
--- a/vmkit/mmtk/java/src/org/jikesrvm/SizeConstants.java
+++ /dev/null
@@ -1,76 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.jikesrvm;
-
-import org.j3.runtime.VM;
-
-/**
- * Constants defining the basic sizes of primitive quantities
- */
-public interface SizeConstants {
-
- int LOG_BYTES_IN_BYTE = 0;
- int BYTES_IN_BYTE = 1;
- int LOG_BITS_IN_BYTE = 3;
- int BITS_IN_BYTE = 1 << LOG_BITS_IN_BYTE;
-
- int LOG_BYTES_IN_BOOLEAN = 0;
- int BYTES_IN_BOOLEAN = 1 << LOG_BYTES_IN_BOOLEAN;
- int LOG_BITS_IN_BOOLEAN = LOG_BITS_IN_BYTE + LOG_BYTES_IN_BOOLEAN;
- int BITS_IN_BOOLEAN = 1 << LOG_BITS_IN_BOOLEAN;
-
- int LOG_BYTES_IN_CHAR = 1;
- int BYTES_IN_CHAR = 1 << LOG_BYTES_IN_CHAR;
- int LOG_BITS_IN_CHAR = LOG_BITS_IN_BYTE + LOG_BYTES_IN_CHAR;
- int BITS_IN_CHAR = 1 << LOG_BITS_IN_CHAR;
-
- int LOG_BYTES_IN_SHORT = 1;
- int BYTES_IN_SHORT = 1 << LOG_BYTES_IN_SHORT;
- int LOG_BITS_IN_SHORT = LOG_BITS_IN_BYTE + LOG_BYTES_IN_SHORT;
- int BITS_IN_SHORT = 1 << LOG_BITS_IN_SHORT;
-
- int LOG_BYTES_IN_INT = 2;
- int BYTES_IN_INT = 1 << LOG_BYTES_IN_INT;
- int LOG_BITS_IN_INT = LOG_BITS_IN_BYTE + LOG_BYTES_IN_INT;
- int BITS_IN_INT = 1 << LOG_BITS_IN_INT;
-
- int LOG_BYTES_IN_FLOAT = 2;
- int BYTES_IN_FLOAT = 1 << LOG_BYTES_IN_FLOAT;
- int LOG_BITS_IN_FLOAT = LOG_BITS_IN_BYTE + LOG_BYTES_IN_FLOAT;
- int BITS_IN_FLOAT = 1 << LOG_BITS_IN_FLOAT;
-
- int LOG_BYTES_IN_LONG = 3;
- int BYTES_IN_LONG = 1 << LOG_BYTES_IN_LONG;
- int LOG_BITS_IN_LONG = LOG_BITS_IN_BYTE + LOG_BYTES_IN_LONG;
- int BITS_IN_LONG = 1 << LOG_BITS_IN_LONG;
-
- int LOG_BYTES_IN_DOUBLE = 3;
- int BYTES_IN_DOUBLE = 1 << LOG_BYTES_IN_DOUBLE;
- int LOG_BITS_IN_DOUBLE = LOG_BITS_IN_BYTE + LOG_BYTES_IN_DOUBLE;
- int BITS_IN_DOUBLE = 1 << LOG_BITS_IN_DOUBLE;
-
- int LOG_BYTES_IN_ADDRESS = VM.BuildFor64Addr ? 3 : 2;
- int BYTES_IN_ADDRESS = 1 << LOG_BYTES_IN_ADDRESS;
- int LOG_BITS_IN_ADDRESS = LOG_BITS_IN_BYTE + LOG_BYTES_IN_ADDRESS;
- int BITS_IN_ADDRESS = 1 << LOG_BITS_IN_ADDRESS;
-
- int LOG_BYTES_IN_WORD = VM.BuildFor64Addr ? 3 : 2;
- int BYTES_IN_WORD = 1 << LOG_BYTES_IN_WORD;
- int LOG_BITS_IN_WORD = LOG_BITS_IN_BYTE + LOG_BYTES_IN_WORD;
- int BITS_IN_WORD = 1 << LOG_BITS_IN_WORD;
-
- int LOG_BYTES_IN_PAGE = 12;
- int BYTES_IN_PAGE = 1 << LOG_BYTES_IN_PAGE;
- int LOG_BITS_IN_PAGE = LOG_BITS_IN_BYTE + LOG_BYTES_IN_PAGE;
- int BITS_IN_PAGE = 1 << LOG_BITS_IN_PAGE;
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/plan/CollectorContext.java b/vmkit/mmtk/java/src/org/mmtk/plan/CollectorContext.java
deleted file mode 100644
index 0ea4103..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/plan/CollectorContext.java
+++ /dev/null
@@ -1,205 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.plan;
-
-import org.mmtk.policy.ImmortalLocal;
-import org.mmtk.utility.sanitychecker.SanityCheckerLocal;
-import org.mmtk.utility.alloc.Allocator;
-import org.mmtk.utility.alloc.BumpPointer;
-import org.mmtk.utility.Constants;
-
-import org.mmtk.vm.VM;
-
-import org.vmmagic.pragma.*;
-import org.vmmagic.unboxed.*;
-
-/**
- * This class (and its sub-classes) implement <i>per-collector thread</i>
- * behavior. We assume <i>N</i> collector threads and <i>M</i>
- * mutator threads, where <i>N</i> is often equal to the number of
- * available processors, P (for P-way parallelism at GC-time), and
- * <i>M</i> may simply be the number of mutator (application) threads.
- * Both <i>N</i> and <i>M</i> are determined by the VM, not MMTk. In
- * the case where a VM uses posix threads (pthreads) for each mutator
- * ("1:1" threading), <i>M</i> will typically be equal to the number of
- * mutator threads. When a uses "green threads" or a hybrid threading
- * scheme (such as Jikes RVM), <i>M</i> will typically be equal to the
- * level of <i>true</i> parallelism (ie the number of underlying
- * kernel threads).</p>
- *
- * <p>Collector operations are separated into <i>per-collector thread</i>
- * operations (the bulk of the GC), and <i>per-mutator thread</i> operations
- * (important in flushing and restoring per-mutator state such as allocator
- * state and write buffer/remset state). {@link SimplePhase}
- * ensures that per-collector thread GC phases are performed by each
- * collector thread, and that the <i>M</i> per-mutator thread operations
- * are multiplexed across the <i>N</i> active collector threads.</p>
- *
- * <p>MMTk assumes that the VM instantiates instances of {@link CollectorContext}
- * in thread local storage (TLS) for each thread participating in
- * collection. Accesses to this state are therefore assumed to be
- * low-cost at GC time.<p>
- *
- * <p>MMTk explicitly separates thread-local (this class) and global
- * operations (See {@link Plan}), so that syncrhonization is localized
- * and explicit, and thus hopefully minimized (See {@link Plan}). Global (Plan)
- * and per-thread (this class) state are also explicitly separated.
- * Operations in this class (and its children) are therefore strictly
- * local to each collector thread, and synchronized operations always
- * happen via access to explicitly global classes such as Plan and its
- * children.</p>
- *
- * <p>This class (and its children) therefore typically implement per-collector
- * thread structures such as collection work queues.</p>
- *
- * @see MutatorContext
- * @see org.mmtk.vm.ActivePlan
- * @see Plan
- */
-@Uninterruptible public abstract class CollectorContext implements Constants {
-
- /****************************************************************************
- * Instance fields
- */
- /** Unique collector identifier */
- private int id;
-
- /** Per-collector allocator into the immortal space */
- protected final BumpPointer immortal = new ImmortalLocal(Plan.immortalSpace);
-
- /** Used for aborting concurrent phases pre-empted by stop the world collection */
- protected boolean resetConcurrentWork;
-
- /** Used for sanity checking */
- protected final SanityCheckerLocal sanityLocal = new SanityCheckerLocal();
-
- /****************************************************************************
- *
- * Initialization
- */
- protected CollectorContext() {
- }
-
- /**
- * Notify that the collector context is registered and ready to execute.
- *
- * @param id The id of this collector context.
- */
- public void initCollector(int id) {
- this.id = id;
- }
-
- /****************************************************************************
- * Collection-time allocation.
- */
-
- /**
- * Allocate memory when copying an object.
- *
- * @param original The object that is being copied.
- * @param bytes The number of bytes required for the copy.
- * @param align Required alignment for the copy.
- * @param offset Offset associated with the alignment.
- * @param allocator The allocator associated with this request.
- * @return The address of the newly allocated region.
- */
- public Address allocCopy(ObjectReference original, int bytes,
- int align, int offset, int allocator) {
- VM.assertions.fail("Collector has not implemented allocCopy");
- return Address.max();
- }
-
- /**
- * Perform any post-copy actions.
- *
- * @param ref The newly allocated object.
- * @param typeRef the type reference for the instance being created.
- * @param bytes The size of the space to be allocated (in bytes).
- * @param allocator The allocator statically assigned to this allocation.
- */
- public void postCopy(ObjectReference ref, ObjectReference typeRef,
- int bytes, int allocator) {
- VM.assertions.fail("Collector has not implemented postCopy");
- }
-
- /**
- * Run-time check of the allocator to use for a given copy allocation
- *
- * At the moment this method assumes that allocators will use the simple
- * (worst) method of aligning to determine if the object is a large object
- * to ensure that no objects are larger than other allocators can handle.
- *
- * @param from The object that is being copied.
- * @param bytes The number of bytes to be allocated.
- * @param align The requested alignment.
- * @param allocator The allocator statically assigned to this allocation.
- * @return The allocator dyncamically assigned to this allocation.
- */
- @Inline
- public int copyCheckAllocator(ObjectReference from, int bytes,
- int align, int allocator) {
- boolean large = Allocator.getMaximumAlignedSize(bytes, align) > Plan.MAX_NON_LOS_COPY_BYTES;
- return large ? Plan.ALLOC_LOS : allocator;
- }
-
- /****************************************************************************
- * Collection.
- */
-
- /** Perform a garbage collection */
- public abstract void collect();
-
- /** Perform some concurrent garbage collection */
- public abstract void concurrentCollect();
-
- /**
- * Perform a (local) collection phase.
- *
- * @param phaseId The unique phase identifier
- * @param primary Should this thread be used to execute any single-threaded
- * local operations?
- */
- public abstract void collectionPhase(short phaseId, boolean primary);
-
- /**
- * Perform some concurrent collection work.
- *
- * @param phaseId The unique phase identifier
- */
- public abstract void concurrentCollectionPhase(short phaseId);
-
- /** @return The current trace instance. */
- public abstract TraceLocal getCurrentTrace();
-
- /**
- * Abort concurrent work due to pre-empt by stop the world collection.
- */
- protected void resetConcurrentWork() {
- resetConcurrentWork = true;
- }
-
- /**
- * Allow concurrent work to continue.
- */
- protected void clearResetConcurrentWork() {
- resetConcurrentWork = false;
- }
-
- /****************************************************************************
- * Miscellaneous.
- */
-
- /** @return the unique identifier for this collector context. */
- @Inline
- public int getId() { return id; }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/plan/ComplexPhase.java b/vmkit/mmtk/java/src/org/mmtk/plan/ComplexPhase.java
deleted file mode 100644
index 0529496..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/plan/ComplexPhase.java
+++ /dev/null
@@ -1,134 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.plan;
-
-import org.mmtk.utility.Constants;
-import org.mmtk.utility.statistics.Timer;
-import org.mmtk.utility.Log;
-import org.mmtk.vm.VM;
-
-import org.vmmagic.pragma.*;
-
-/**
- * Phases of a garbage collection.
- *
- * A complex phase is a sequence of phases.
- *
- */
-@Uninterruptible
-public final class ComplexPhase extends Phase
- implements Constants {
-
- /****************************************************************************
- * Instance fields
- */
-
- /**
- * The phases that comprise this phase.
- */
- private final int[] scheduledSubPhases;
-
- /**
- * Construct a complex phase from an array of phase IDs.
- *
- * @param name The name of the phase.
- * @param scheduledSubPhases The sub phases
- */
- protected ComplexPhase(String name, int[] scheduledSubPhases) {
- super(name);
- this.scheduledSubPhases = scheduledSubPhases;
- checkPhases();
- }
-
- /**
- * Construct a complex phase from an array of phase IDs, but using
- * the specified timer rather than creating one.
- *
- * @param name The name of the phase.
- * @param timer The timer for this phase to contribute to.
- * @param scheduledSubPhases The sub phases
- */
- protected ComplexPhase(String name, Timer timer, int[] scheduledSubPhases) {
- super(name, timer);
- this.scheduledSubPhases = scheduledSubPhases;
- checkPhases();
- }
-
- /**
- * Validate the scheduled sub phases.
- */
- private void checkPhases() {
- if (VM.VERIFY_ASSERTIONS) {
- VM.assertions._assert(scheduledSubPhases.length > 0);
- for(int scheduledPhase: scheduledSubPhases) {
- VM.assertions._assert(getSchedule(scheduledPhase) > 0);
- VM.assertions._assert(getPhaseId(scheduledPhase) > 0);
- }
- }
- }
-
- /**
- * The number of scheduled sub phases.
- */
- protected int count() {
- return scheduledSubPhases.length;
- }
-
- /**
- * Return an individual scheduled sub phase.
- *
- * @param index The index
- * @return The scheduled phase.
- */
- protected int get(int index) {
- return scheduledSubPhases[index];
- }
-
- /**
- * Display a description of this phase, for debugging purposes.
- */
- protected void logPhase() {
- Log.write("ComplexPhase(");
- Log.write(name);
- Log.write(", < ");
- for (int subPhase : scheduledSubPhases) {
- short ordering = getSchedule(subPhase);
- short phaseId = getPhaseId(subPhase);
- Log.write(getScheduleName(ordering));
- Log.write("(");
- Log.write(getName(phaseId));
- Log.write(") ");
- }
- Log.write(">)");
- }
-
- /**
- * Replace a scheduled phase. Used for example to replace a placeholder.
- *
- * @param oldScheduledPhase The scheduled phase to replace.
- * @param newScheduledPhase The new scheduled phase.
- */
- public void replacePhase(int oldScheduledPhase, int newScheduledPhase) {
- for (int i = 0; i < scheduledSubPhases.length; i++) {
- int scheduledPhase = scheduledSubPhases[i];
- if (scheduledPhase == oldScheduledPhase) {
- /* Replace */
- scheduledSubPhases[i] = newScheduledPhase;
- } else if (getSchedule(scheduledPhase) == SCHEDULE_COMPLEX) {
- /* Recurse */
- ComplexPhase p = (ComplexPhase)getPhase(getPhaseId(scheduledPhase));
- p.replacePhase(oldScheduledPhase, newScheduledPhase);
- }
- }
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/plan/GCspyPlan.java b/vmkit/mmtk/java/src/org/mmtk/plan/GCspyPlan.java
deleted file mode 100644
index 5b931db..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/plan/GCspyPlan.java
+++ /dev/null
@@ -1,32 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.plan;
-
-import org.mmtk.policy.ImmortalSpace;
-import org.mmtk.utility.heap.VMRequest;
-
-/**
- * This interface provides an immortal allocation space for GCspy objects.
- */
-public interface GCspyPlan {
-
- /**
- * Any GCspy objects allocated after booting are allocated
- * in a separate immortal space.
- */
- ImmortalSpace gcspySpace =
- new ImmortalSpace("gcspy", Plan.DEFAULT_POLL_FREQUENCY, VMRequest.create());
-
- /** The descriptor for the GCspy allocation space */
- int GCSPY = gcspySpace.getDescriptor();
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/plan/MutatorContext.java b/vmkit/mmtk/java/src/org/mmtk/plan/MutatorContext.java
deleted file mode 100644
index c37b5dd..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/plan/MutatorContext.java
+++ /dev/null
@@ -1,1262 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.plan;
-
-import org.mmtk.policy.MarkSweepLocal;
-import org.mmtk.policy.Space;
-import org.mmtk.policy.ImmortalLocal;
-import org.mmtk.policy.LargeObjectLocal;
-import org.mmtk.utility.alloc.Allocator;
-import org.mmtk.utility.alloc.BumpPointer;
-import org.mmtk.utility.Constants;
-import org.mmtk.utility.Log;
-
-import org.mmtk.vm.VM;
-
-import org.vmmagic.pragma.*;
-import org.vmmagic.unboxed.*;
-
-/**
- * This class (and its sub-classes) implement <i>per-mutator thread</i>
- * behavior. We assume <i>N</i> collector threads and <i>M</i>
- * mutator threads, where <i>N</i> is often equal to the number of
- * available processors, P (for P-way parallelism at GC-time), and
- * <i>M</i> may simply be the number of mutator (application) threads.
- * Both <i>N</i> and <i>M</i> are determined by the VM, not MMTk. In
- * the case where a VM uses posix threads (pthreads) for each mutator
- * ("1:1" threading), <i>M</i> will typically be equal to the number of
- * mutator threads. When a uses "green threads" or a hybrid threading
- * scheme (such as Jikes RVM), <i>M</i> will typically be equal to the
- * level of <i>true</i> parallelism (ie the number of underlying
- * kernel threads).<p>
- *
- * MMTk assumes that the VM instantiates instances of MutatorContext
- * in thread local storage (TLS) for each thread participating in
- * collection. Accesses to this state are therefore assumed to be
- * low-cost during mutator time.<p>
- *
- * This class (and its children) is therefore used for unsynchronized
- * per-mutator operations such as <i>allocation</i> and <i>write barriers</i>.
- * The semantics and necessary state for these operations are therefore
- * specified in the GC-specific subclasses of this class.
- *
- * MMTk explicitly separates thread-local (this class) and global
- * operations (@see Plan), so that syncrhonization is localized
- * and explicit, and thus hopefully minimized (@see Plan). Gloabl (Plan)
- * and per-thread (this class) state are also explicitly separated.
- * Operations in this class (and its children) are therefore strictly
- * local to each mutator thread, and synchronized operations always
- * happen via access to explicitly global classes such as Plan and its
- * children. Therefore only <i>"fast path"</i> (unsynchronized)
- * allocation and barrier semantics are defined in MutatorContext and
- * its subclasses. These call out to <i>"slow path"</i> (synchronize(d)
- * methods which have global state and are globally synchronized. For
- * example, an allocation fast path may bump a pointer without any
- * syncrhonization (the "fast path") until a limit is reached, at which
- * point the "slow path" is called, and more memory is aquired from a
- * global resource.<p>
- *
- * As the super-class of all per-mutator contexts, this class implements
- * basic per-mutator behavior common to all MMTk collectors, including
- * support for immortal and large object space allocation, as well as
- * empty stubs for write barriers (to be overridden by sub-classes as
- * needed).
- *
- * @see CollectorContext
- * @see org.mmtk.vm.ActivePlan
- * @see Plan
- */
-@Uninterruptible
-public abstract class MutatorContext implements Constants {
-
- /****************************************************************************
- * Initialization
- */
-
-
- /**
- * Notify that the mutator context is registered and ready to execute. From
- * this point it will be included in iterations over mutators.
- *
- * @param id The id of this mutator context.
- */
- public void initMutator(int id) {
- this.id = id;
- }
-
- /**
- * The mutator is about to be cleaned up, make sure all local data is returned.
- */
- public void deinitMutator() {
- flush();
- }
-
- /****************************************************************************
- * Instance fields
- */
-
- /** Unique mutator identifier */
- private int id;
-
- /** Used for printing log information in a thread safe manner */
- protected final Log log = new Log();
-
- /** Per-mutator allocator into the immortal space */
- protected final BumpPointer immortal = new ImmortalLocal(Plan.immortalSpace);
-
- /** Per-mutator allocator into the large object space */
- protected final LargeObjectLocal los = new LargeObjectLocal(Plan.loSpace);
-
- /** Per-mutator allocator into the small code space */
- protected final MarkSweepLocal smcode = Plan.USE_CODE_SPACE ? new MarkSweepLocal(Plan.smallCodeSpace) : null;
-
- /** Per-mutator allocator into the large code space */
- protected final LargeObjectLocal lgcode = Plan.USE_CODE_SPACE ? new LargeObjectLocal(Plan.largeCodeSpace) : null;
-
- /** Per-mutator allocator into the non moving space */
- protected final MarkSweepLocal nonmove = new MarkSweepLocal(Plan.nonMovingSpace);
-
-
- /****************************************************************************
- *
- * Collection.
- */
-
- /**
- * Perform a per-mutator collection phase.
- *
- * @param phaseId The unique phase identifier
- * @param primary Should this thread be used to execute any single-threaded
- * local operations?
- */
- public abstract void collectionPhase(short phaseId, boolean primary);
-
- /****************************************************************************
- *
- * Allocation.
- */
-
- /**
- * Run-time check of the allocator to use for a given allocation
- *
- * At the moment this method assumes that allocators will use the simple
- * (worst) method of aligning to determine if the object is a large object
- * to ensure that no objects are larger than other allocators can handle.
- *
- * @param bytes The number of bytes to be allocated
- * @param align The requested alignment.
- * @param allocator The allocator statically assigned to this allocation
- * @return The allocator dynamically assigned to this allocation
- */
- @Inline
- public int checkAllocator(int bytes, int align, int allocator) {
- int maxBytes = Allocator.getMaximumAlignedSize(bytes, align);
- if (allocator == Plan.ALLOC_DEFAULT) {
- return (maxBytes > Plan.MAX_NON_LOS_DEFAULT_ALLOC_BYTES) ? Plan.ALLOC_LOS : allocator;
- }
-
- if (Plan.USE_CODE_SPACE && allocator == Plan.ALLOC_CODE) {
- return (maxBytes > Plan.MAX_NON_LOS_NONMOVING_ALLOC_BYTES) ? Plan.ALLOC_LARGE_CODE : allocator;
- }
-
- if (allocator == Plan.ALLOC_NON_REFERENCE) {
- return (maxBytes > Plan.MAX_NON_LOS_DEFAULT_ALLOC_BYTES) ? Plan.ALLOC_LOS : Plan.ALLOC_DEFAULT;
- }
-
- if (allocator == Plan.ALLOC_NON_MOVING) {
- return (maxBytes > Plan.MAX_NON_LOS_NONMOVING_ALLOC_BYTES) ? Plan.ALLOC_LOS : allocator;
- }
-
- return allocator;
- }
-
- /**
- * Allocate memory for an object.
- *
- * @param bytes The number of bytes required for the object.
- * @param align Required alignment for the object.
- * @param offset Offset associated with the alignment.
- * @param allocator The allocator associated with this request.
- * @param site Allocation site
- * @return The low address of the allocated chunk.
- */
- @Inline
- public Address alloc(int bytes, int align, int offset, int allocator, int site) {
- switch (allocator) {
- case Plan.ALLOC_LOS: return los.alloc(bytes, align, offset);
- case Plan.ALLOC_IMMORTAL: return immortal.alloc(bytes, align, offset);
- case Plan.ALLOC_CODE: return smcode.alloc(bytes, align, offset);
- case Plan.ALLOC_LARGE_CODE: return lgcode.alloc(bytes, align, offset);
- case Plan.ALLOC_NON_MOVING: return nonmove.alloc(bytes, align, offset);
- default:
- VM.assertions.fail("No such allocator");
- return Address.zero();
- }
- }
-
- /**
- * Perform post-allocation actions. For many allocators none are
- * required.
- *
- * @param ref The newly allocated object
- * @param typeRef the type reference for the instance being created
- * @param bytes The size of the space to be allocated (in bytes)
- * @param allocator The allocator number to be used for this allocation
- */
- @Inline
- public void postAlloc(ObjectReference ref, ObjectReference typeRef,
- int bytes, int allocator) {
- switch (allocator) {
- case Plan.ALLOC_LOS: Plan.loSpace.initializeHeader(ref, true); return;
- case Plan.ALLOC_IMMORTAL: Plan.immortalSpace.initializeHeader(ref); return;
- case Plan.ALLOC_CODE: Plan.smallCodeSpace.initializeHeader(ref, true); return;
- case Plan.ALLOC_LARGE_CODE: Plan.largeCodeSpace.initializeHeader(ref, true); return;
- case Plan.ALLOC_NON_MOVING: Plan.nonMovingSpace.initializeHeader(ref, true); return;
- default:
- VM.assertions.fail("No such allocator");
- }
- }
-
- /****************************************************************************
- *
- * Space - Allocator mapping.
- */
-
- /**
- * Return the allocator instance associated with a space
- * <code>space</code>, for this plan instance.
- *
- * @param space The space for which the allocator instance is desired.
- * @return The allocator instance associated with this plan instance
- * which is allocating into <code>space</code>, or <code>null</code>
- * if no appropriate allocator can be established.
- */
- public Allocator getAllocatorFromSpace(Space space) {
- if (space == Plan.immortalSpace) return immortal;
- if (space == Plan.loSpace) return los;
- if (space == Plan.nonMovingSpace) return nonmove;
- if (Plan.USE_CODE_SPACE && space == Plan.smallCodeSpace) return smcode;
- if (Plan.USE_CODE_SPACE && space == Plan.largeCodeSpace) return lgcode;
-
- // Invalid request has been made
- if (space == Plan.metaDataSpace) {
- VM.assertions.fail("MutatorContext.getAllocatorFromSpace given meta space");
- } else if (space != null) {
- VM.assertions.fail("MutatorContext.getAllocatorFromSpace given invalid space");
- } else {
- VM.assertions.fail("MutatorContext.getAllocatorFromSpace given null space");
- }
-
- return null;
- }
-
- /****************************************************************************
- *
- * Write and read barriers. By default do nothing, override if
- * appropriate.
- */
-
- /**
- * Read a reference type. In a concurrent collector this may
- * involve adding the referent to the marking queue.
- *
- * @param referent The referent being read.
- * @return The new referent.
- */
- @Inline
- public ObjectReference javaLangReferenceReadBarrier(ObjectReference referent) {
- // Either: read barriers are used and this is overridden, or
- // read barriers are not used and this is never called
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(false);
- return ObjectReference.nullReference();
- }
-
- /**
- * Write a boolean. Take appropriate write barrier actions.<p>
- *
- * <b>By default do nothing, override if appropriate.</b>
- *
- * @param src The object into which the new reference will be stored
- * @param slot The address into which the new reference will be
- * stored.
- * @param value The value of the new boolean
- * @param metaDataA A value that assists the host VM in creating a store
- * @param metaDataB A value that assists the host VM in creating a store
- * @param mode The context in which the store occurred
- */
- public void booleanWrite(ObjectReference src, Address slot, boolean value, Word metaDataA, Word metaDataB, int mode) {
- // Either: write barriers are used and this is overridden, or
- // write barriers are not used and this is never called
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(false);
- }
-
- /**
- * Read a boolean. Take appropriate read barrier action, and
- * return the value that was read.<p> This is a <b>substituting<b>
- * barrier. The call to this barrier takes the place of a load.<p>
- *
- * @param src The object reference holding the field being read.
- * @param slot The address of the slot being read.
- * @param metaDataA A value that assists the host VM in creating a load
- * @param metaDataB A value that assists the host VM in creating a load
- * @param mode The context in which the load occurred
- * @return The boolean that was read.
- */
- @Inline
- public boolean booleanRead(ObjectReference src, Address slot, Word metaDataA, Word metaDataB, int mode) {
- // Either: read barriers are used and this is overridden, or
- // read barriers are not used and this is never called
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(false);
- return false;
- }
-
- /**
- * A number of booleans are about to be copied from object
- * <code>src</code> to object <code>dst</code> (as in an array
- * copy). Thus, <code>dst</code> is the mutated object. Take
- * appropriate write barrier actions.<p>
- *
- * @param src The source array
- * @param srcOffset The starting source offset
- * @param dst The destination array
- * @param dstOffset The starting destination offset
- * @param bytes The number of bytes to be copied
- * @return True if the update was performed by the barrier, false if
- * left to the caller (always false in this case).
- */
- public boolean booleanBulkCopy(ObjectReference src, Offset srcOffset, ObjectReference dst, Offset dstOffset, int bytes) {
- // Either: bulk copy is supported and this is overridden, or
- // write barriers are not used and this is never called
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(false);
- return false;
- }
-
- /**
- * Write a byte. Take appropriate write barrier actions.<p>
- *
- * <b>By default do nothing, override if appropriate.</b>
- *
- * @param src The object into which the new reference will be stored
- * @param slot The address into which the new reference will be
- * stored.
- * @param value The value of the new byte
- * @param metaDataA A value that assists the host VM in creating a store
- * @param metaDataB A value that assists the host VM in creating a store
- * @param mode The context in which the store occurred
- */
- public void byteWrite(ObjectReference src, Address slot, byte value, Word metaDataA, Word metaDataB, int mode) {
- // Either: write barriers are used and this is overridden, or
- // write barriers are not used and this is never called
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(false);
- }
-
- /**
- * Read a byte. Take appropriate read barrier action, and
- * return the value that was read.<p> This is a <b>substituting<b>
- * barrier. The call to this barrier takes the place of a load.<p>
- *
- * @param src The object reference holding the field being read.
- * @param slot The address of the slot being read.
- * @param metaDataA A value that assists the host VM in creating a load
- * @param metaDataB A value that assists the host VM in creating a load
- * @param mode The context in which the load occurred
- * @return The byte that was read.
- */
- @Inline
- public byte byteRead(ObjectReference src, Address slot, Word metaDataA, Word metaDataB, int mode) {
- // Either: read barriers are used and this is overridden, or
- // read barriers are not used and this is never called
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(false);
- return 0;
- }
-
- /**
- * A number of bytes are about to be copied from object
- * <code>src</code> to object <code>dst</code> (as in an array
- * copy). Thus, <code>dst</code> is the mutated object. Take
- * appropriate write barrier actions.<p>
- *
- * @param src The source array
- * @param srcOffset The starting source offset
- * @param dst The destination array
- * @param dstOffset The starting destination offset
- * @param bytes The number of bytes to be copied
- * @return True if the update was performed by the barrier, false if
- * left to the caller (always false in this case).
- */
- public boolean byteBulkCopy(ObjectReference src, Offset srcOffset, ObjectReference dst, Offset dstOffset, int bytes) {
- // Either: bulk copy is supported and this is overridden, or
- // write barriers are not used and this is never called
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(false);
- return false;
- }
-
- /**
- * Write a char. Take appropriate write barrier actions.<p>
- *
- * <b>By default do nothing, override if appropriate.</b>
- *
- * @param src The object into which the new reference will be stored
- * @param slot The address into which the new reference will be
- * stored.
- * @param value The value of the new char
- * @param metaDataA A value that assists the host VM in creating a store
- * @param metaDataB A value that assists the host VM in creating a store
- * @param mode The context in which the store occurred
- */
- public void charWrite(ObjectReference src, Address slot, char value, Word metaDataA, Word metaDataB, int mode) {
- // Either: write barriers are used and this is overridden, or
- // write barriers are not used and this is never called
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(false);
- }
-
- /**
- * Read a char. Take appropriate read barrier action, and
- * return the value that was read.<p> This is a <b>substituting<b>
- * barrier. The call to this barrier takes the place of a load.<p>
- *
- * @param src The object reference holding the field being read.
- * @param slot The address of the slot being read.
- * @param metaDataA A value that assists the host VM in creating a load
- * @param metaDataB A value that assists the host VM in creating a load
- * @param mode The context in which the load occurred
- * @return The char that was read.
- */
- @Inline
- public char charRead(ObjectReference src, Address slot, Word metaDataA, Word metaDataB, int mode) {
- // Either: read barriers are used and this is overridden, or
- // read barriers are not used and this is never called
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(false);
- return 0;
- }
-
- /**
- * A number of chars are about to be copied from object
- * <code>src</code> to object <code>dst</code> (as in an array
- * copy). Thus, <code>dst</code> is the mutated object. Take
- * appropriate write barrier actions.<p>
- *
- * @param src The source array
- * @param srcOffset The starting source offset
- * @param dst The destination array
- * @param dstOffset The starting destination offset
- * @param bytes The number of bytes to be copied
- * @return True if the update was performed by the barrier, false if
- * left to the caller (always false in this case).
- */
- public boolean charBulkCopy(ObjectReference src, Offset srcOffset, ObjectReference dst, Offset dstOffset, int bytes) {
- // Either: bulk copy is supported and this is overridden, or
- // write barriers are not used and this is never called
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(false);
- return false;
- }
-
- /**
- * Write a short. Take appropriate write barrier actions.<p>
- *
- * <b>By default do nothing, override if appropriate.</b>
- *
- * @param src The object into which the new reference will be stored
- * @param slot The address into which the new reference will be
- * stored.
- * @param value The value of the new short
- * @param metaDataA A value that assists the host VM in creating a store
- * @param metaDataB A value that assists the host VM in creating a store
- * @param mode The context in which the store occurred
- */
- public void shortWrite(ObjectReference src, Address slot, short value, Word metaDataA, Word metaDataB, int mode) {
- // Either: write barriers are used and this is overridden, or
- // write barriers are not used and this is never called
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(false);
- }
-
- /**
- * Read a short. Take appropriate read barrier action, and
- * return the value that was read.<p> This is a <b>substituting<b>
- * barrier. The call to this barrier takes the place of a load.<p>
- *
- * @param src The object reference holding the field being read.
- * @param slot The address of the slot being read.
- * @param metaDataA A value that assists the host VM in creating a load
- * @param metaDataB A value that assists the host VM in creating a load
- * @param mode The context in which the load occurred
- * @return The short that was read.
- */
- @Inline
- public short shortRead(ObjectReference src, Address slot, Word metaDataA, Word metaDataB, int mode) {
- // Either: read barriers are used and this is overridden, or
- // read barriers are not used and this is never called
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(false);
- return 0;
- }
-
- /**
- * A number of shorts are about to be copied from object
- * <code>src</code> to object <code>dst</code> (as in an array
- * copy). Thus, <code>dst</code> is the mutated object. Take
- * appropriate write barrier actions.<p>
- *
- * @param src The source array
- * @param srcOffset The starting source offset
- * @param dst The destination array
- * @param dstOffset The starting destination offset
- * @param bytes The number of bytes to be copied
- * @return True if the update was performed by the barrier, false if
- * left to the caller (always false in this case).
- */
- public boolean shortBulkCopy(ObjectReference src, Offset srcOffset, ObjectReference dst, Offset dstOffset, int bytes) {
- // Either: bulk copy is supported and this is overridden, or
- // write barriers are not used and this is never called
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(false);
- return false;
- }
-
-
- /**
- * Write a int. Take appropriate write barrier actions.<p>
- *
- * <b>By default do nothing, override if appropriate.</b>
- *
- * @param src The object into which the new reference will be stored
- * @param slot The address into which the new reference will be
- * stored.
- * @param value The value of the new int
- * @param metaDataA A value that assists the host VM in creating a store
- * @param metaDataB A value that assists the host VM in creating a store
- * @param mode The context in which the store occurred
- */
- public void intWrite(ObjectReference src, Address slot, int value, Word metaDataA, Word metaDataB, int mode) {
- // Either: write barriers are used and this is overridden, or
- // write barriers are not used and this is never called
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(false);
- }
-
- /**
- * Read a int. Take appropriate read barrier action, and
- * return the value that was read.<p> This is a <b>substituting<b>
- * barrier. The call to this barrier takes the place of a load.<p>
- *
- * @param src The object reference holding the field being read.
- * @param slot The address of the slot being read.
- * @param metaDataA A value that assists the host VM in creating a load
- * @param metaDataB A value that assists the host VM in creating a load
- * @param mode The context in which the load occurred
- * @return The int that was read.
- */
- @Inline
- public int intRead(ObjectReference src, Address slot, Word metaDataA, Word metaDataB, int mode) {
- // Either: read barriers are used and this is overridden, or
- // read barriers are not used and this is never called
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(false);
- return 0;
- }
-
- /**
- * A number of ints are about to be copied from object
- * <code>src</code> to object <code>dst</code> (as in an array
- * copy). Thus, <code>dst</code> is the mutated object. Take
- * appropriate write barrier actions.<p>
- *
- * @param src The source array
- * @param srcOffset The starting source offset
- * @param dst The destination array
- * @param dstOffset The starting destination offset
- * @param bytes The number of bytes to be copied
- * @return True if the update was performed by the barrier, false if
- * left to the caller (always false in this case).
- */
- public boolean intBulkCopy(ObjectReference src, Offset srcOffset, ObjectReference dst, Offset dstOffset, int bytes) {
- // Either: bulk copy is supported and this is overridden, or
- // write barriers are not used and this is never called
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(false);
- return false;
- }
-
- /**
- * Attempt to atomically exchange the value in the given slot
- * with the passed replacement value.
- *
- * <b>By default do nothing, override if appropriate.</b>
- *
- * @param src The object into which the value will be stored
- * @param slot The address into which the value will be
- * stored.
- * @param old The old int to be swapped out
- * @param value The new int
- * @param metaDataA A value that assists the host VM in creating a store
- * @param metaDataB A value that assists the host VM in creating a store
- * @param mode The context in which the store occurred
- * @return True if the swap was successful.
- */
- public boolean intTryCompareAndSwap(ObjectReference src, Address slot, int old, int value, Word metaDataA, Word metaDataB, int mode) {
- // Either: write barriers are used and this is overridden, or
- // write barriers are not used and this is never called
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(false);
- return false;
- }
-
- /**
- * Write a long. Take appropriate write barrier actions.<p>
- *
- * <b>By default do nothing, override if appropriate.</b>
- *
- * @param src The object into which the new reference will be stored
- * @param slot The address into which the new reference will be
- * stored.
- * @param value The value of the new long
- * @param metaDataA A value that assists the host VM in creating a store
- * @param metaDataB A value that assists the host VM in creating a store
- * @param mode The context in which the store occurred
- */
- public void longWrite(ObjectReference src, Address slot, long value, Word metaDataA, Word metaDataB, int mode) {
- // Either: write barriers are used and this is overridden, or
- // write barriers are not used and this is never called
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(false);
- }
-
- /**
- * Read a long. Take appropriate read barrier action, and
- * return the value that was read.<p> This is a <b>substituting<b>
- * barrier. The call to this barrier takes the place of a load.<p>
- *
- * @param src The object reference holding the field being read.
- * @param slot The address of the slot being read.
- * @param metaDataA A value that assists the host VM in creating a load
- * @param metaDataB A value that assists the host VM in creating a load
- * @param mode The context in which the load occurred
- * @return The long that was read.
- */
- @Inline
- public long longRead(ObjectReference src, Address slot, Word metaDataA, Word metaDataB, int mode) {
- // Either: read barriers are used and this is overridden, or
- // read barriers are not used and this is never called
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(false);
- return 0;
- }
-
- /**
- * A number of longs are about to be copied from object
- * <code>src</code> to object <code>dst</code> (as in an array
- * copy). Thus, <code>dst</code> is the mutated object. Take
- * appropriate write barrier actions.<p>
- *
- * @param src The source array
- * @param srcOffset The starting source offset
- * @param dst The destination array
- * @param dstOffset The starting destination offset
- * @param bytes The number of bytes to be copied
- * @return True if the update was performed by the barrier, false if
- * left to the caller (always false in this case).
- */
- public boolean longBulkCopy(ObjectReference src, Offset srcOffset, ObjectReference dst, Offset dstOffset, int bytes) {
- // Either: bulk copy is supported and this is overridden, or
- // write barriers are not used and this is never called
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(false);
- return false;
- }
-
- /**
- * Attempt to atomically exchange the value in the given slot
- * with the passed replacement value.
- *
- * <b>By default do nothing, override if appropriate.</b>
- *
- * @param src The object into which the value will be stored
- * @param slot The address into which the value will be
- * stored.
- * @param old The old long to be swapped out
- * @param value The new long
- * @param metaDataA A value that assists the host VM in creating a store
- * @param metaDataB A value that assists the host VM in creating a store
- * @param mode The context in which the store occurred
- * @return True if the swap was successful.
- */
- public boolean longTryCompareAndSwap(ObjectReference src, Address slot, long old, long value, Word metaDataA, Word metaDataB, int mode) {
- // Either: write barriers are used and this is overridden, or
- // write barriers are not used and this is never called
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(false);
- return false;
- }
-
- /**
- * Write a float. Take appropriate write barrier actions.<p>
- *
- * <b>By default do nothing, override if appropriate.</b>
- *
- * @param src The object into which the new reference will be stored
- * @param slot The address into which the new reference will be
- * stored.
- * @param value The value of the new float
- * @param metaDataA A value that assists the host VM in creating a store
- * @param metaDataB A value that assists the host VM in creating a store
- * @param mode The context in which the store occurred
- */
- public void floatWrite(ObjectReference src, Address slot, float value, Word metaDataA, Word metaDataB, int mode) {
- // Either: write barriers are used and this is overridden, or
- // write barriers are not used and this is never called
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(false);
- }
-
- /**
- * Read a float. Take appropriate read barrier action, and
- * return the value that was read.<p> This is a <b>substituting<b>
- * barrier. The call to this barrier takes the place of a load.<p>
- *
- * @param src The object reference holding the field being read.
- * @param slot The address of the slot being read.
- * @param metaDataA A value that assists the host VM in creating a load
- * @param metaDataB A value that assists the host VM in creating a load
- * @param mode The context in which the load occurred
- * @return The float that was read.
- */
- @Inline
- public float floatRead(ObjectReference src, Address slot, Word metaDataA, Word metaDataB, int mode) {
- // Either: read barriers are used and this is overridden, or
- // read barriers are not used and this is never called
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(false);
- return 0;
- }
-
- /**
- * A number of floats are about to be copied from object
- * <code>src</code> to object <code>dst</code> (as in an array
- * copy). Thus, <code>dst</code> is the mutated object. Take
- * appropriate write barrier actions.<p>
- *
- * @param src The source array
- * @param srcOffset The starting source offset
- * @param dst The destination array
- * @param dstOffset The starting destination offset
- * @param bytes The number of bytes to be copied
- * @return True if the update was performed by the barrier, false if
- * left to the caller (always false in this case).
- */
- public boolean floatBulkCopy(ObjectReference src, Offset srcOffset, ObjectReference dst, Offset dstOffset, int bytes) {
- // Either: bulk copy is supported and this is overridden, or
- // write barriers are not used and this is never called
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(false);
- return false;
- }
-
- /**
- * Write a double. Take appropriate write barrier actions.<p>
- *
- * <b>By default do nothing, override if appropriate.</b>
- *
- * @param src The object into which the new reference will be stored
- * @param slot The address into which the new reference will be
- * stored.
- * @param value The value of the new double
- * @param metaDataA A value that assists the host VM in creating a store
- * @param metaDataB A value that assists the host VM in creating a store
- * @param mode The context in which the store occurred
- */
- public void doubleWrite(ObjectReference src, Address slot, double value, Word metaDataA, Word metaDataB, int mode) {
- // Either: write barriers are used and this is overridden, or
- // write barriers are not used and this is never called
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(false);
- }
-
- /**
- * Read a double. Take appropriate read barrier action, and
- * return the value that was read.<p> This is a <b>substituting<b>
- * barrier. The call to this barrier takes the place of a load.<p>
- *
- * @param src The object reference holding the field being read.
- * @param slot The address of the slot being read.
- * @param metaDataA A value that assists the host VM in creating a load
- * @param metaDataB A value that assists the host VM in creating a load
- * @param mode The context in which the load occurred
- * @return The double that was read.
- */
- @Inline
- public double doubleRead(ObjectReference src, Address slot, Word metaDataA, Word metaDataB, int mode) {
- // Either: read barriers are used and this is overridden, or
- // read barriers are not used and this is never called
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(false);
- return 0;
- }
-
- /**
- * A number of doubles are about to be copied from object
- * <code>src</code> to object <code>dst</code> (as in an array
- * copy). Thus, <code>dst</code> is the mutated object. Take
- * appropriate write barrier actions.<p>
- *
- * @param src The source array
- * @param srcOffset The starting source offset
- * @param dst The destination array
- * @param dstOffset The starting destination offset
- * @param bytes The number of bytes to be copied
- * @return True if the update was performed by the barrier, false if
- * left to the caller (always false in this case).
- */
- public boolean doubleBulkCopy(ObjectReference src, Offset srcOffset, ObjectReference dst, Offset dstOffset, int bytes) {
- // Either: bulk copy is supported and this is overridden, or
- // write barriers are not used and this is never called
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(false);
- return false;
- }
-
- /**
- * Write a Word. Take appropriate write barrier actions.<p>
- *
- * <b>By default do nothing, override if appropriate.</b>
- *
- * @param src The object into which the new reference will be stored
- * @param slot The address into which the new reference will be
- * stored.
- * @param value The value of the new Word
- * @param metaDataA A value that assists the host VM in creating a store
- * @param metaDataB A value that assists the host VM in creating a store
- * @param mode The context in which the store occurred
- */
- public void wordWrite(ObjectReference src, Address slot, Word value, Word metaDataA, Word metaDataB, int mode) {
- // Either: write barriers are used and this is overridden, or
- // write barriers are not used and this is never called
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(false);
- }
-
- /**
- * Read a Word. Take appropriate read barrier action, and
- * return the value that was read.<p> This is a <b>substituting<b>
- * barrier. The call to this barrier takes the place of a load.<p>
- *
- * @param src The object reference holding the field being read.
- * @param slot The address of the slot being read.
- * @param metaDataA A value that assists the host VM in creating a load
- * @param metaDataB A value that assists the host VM in creating a load
- * @param mode The context in which the load occurred
- * @return The Word that was read.
- */
- @Inline
- public Word wordRead(ObjectReference src, Address slot, Word metaDataA, Word metaDataB, int mode) {
- // Either: read barriers are used and this is overridden, or
- // read barriers are not used and this is never called
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(false);
- return Word.zero();
- }
-
- /**
- * A number of Words are about to be copied from object
- * <code>src</code> to object <code>dst</code> (as in an array
- * copy). Thus, <code>dst</code> is the mutated object. Take
- * appropriate write barrier actions.<p>
- *
- * @param src The source array
- * @param srcOffset The starting source offset
- * @param dst The destination array
- * @param dstOffset The starting destination offset
- * @param bytes The number of bytes to be copied
- * @return True if the update was performed by the barrier, false if
- * left to the caller (always false in this case).
- */
- public boolean wordBulkCopy(ObjectReference src, Offset srcOffset, ObjectReference dst, Offset dstOffset, int bytes) {
- // Either: bulk copy is supported and this is overridden, or
- // write barriers are not used and this is never called
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(false);
- return false;
- }
-
- /**
- * Attempt to atomically exchange the value in the given slot
- * with the passed replacement value.
- *
- * <b>By default do nothing, override if appropriate.</b>
- *
- * @param src The object into which the new reference will be stored
- * @param slot The address into which the new reference will be
- * stored.
- * @param old The old Word to be swapped out
- * @param value The new Word
- * @param metaDataA A value that assists the host VM in creating a store
- * @param metaDataB A value that assists the host VM in creating a store
- * @param mode The context in which the store occurred
- * @return True if the swap was successful.
- */
- public boolean wordTryCompareAndSwap(ObjectReference src, Address slot, Word old, Word value, Word metaDataA, Word metaDataB, int mode) {
- // Either: write barriers are used and this is overridden, or
- // write barriers are not used and this is never called
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(false);
- return false;
- }
-
- /**
- * Write an Address. Take appropriate write barrier actions.<p>
- *
- * <b>By default do nothing, override if appropriate.</b>
- *
- * @param src The object into which the Word will be stored
- * @param slot The address into which the Word will be
- * stored.
- * @param value The value of the new Address
- * @param metaDataA A value that assists the host VM in creating a store
- * @param metaDataB A value that assists the host VM in creating a store
- * @param mode The context in which the store occurred
- */
- public void addressWrite(ObjectReference src, Address slot, Address value, Word metaDataA, Word metaDataB, int mode) {
- // Either: write barriers are used and this is overridden, or
- // write barriers are not used and this is never called
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(false);
- }
-
- /**
- * Read an Address. Take appropriate read barrier action, and
- * return the value that was read.<p> This is a <b>substituting<b>
- * barrier. The call to this barrier takes the place of a load.<p>
- *
- * @param src The object reference holding the field being read.
- * @param slot The address of the slot being read.
- * @param metaDataA A value that assists the host VM in creating a load
- * @param metaDataB A value that assists the host VM in creating a load
- * @param mode The context in which the load occurred
- * @return The Address that was read.
- */
- @Inline
- public Address addressRead(ObjectReference src, Address slot, Word metaDataA, Word metaDataB, int mode) {
- // Either: read barriers are used and this is overridden, or
- // read barriers are not used and this is never called
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(false);
- return Address.zero();
- }
-
- /**
- * A number of Addresse's are about to be copied from object
- * <code>src</code> to object <code>dst</code> (as in an array
- * copy). Thus, <code>dst</code> is the mutated object. Take
- * appropriate write barrier actions.<p>
- *
- * @param src The source array
- * @param srcOffset The starting source offset
- * @param dst The destination array
- * @param dstOffset The starting destination offset
- * @param bytes The number of bytes to be copied
- * @return True if the update was performed by the barrier, false if
- * left to the caller (always false in this case).
- */
- public boolean addressBulkCopy(ObjectReference src, Offset srcOffset, ObjectReference dst, Offset dstOffset, int bytes) {
- // Either: bulk copy is supported and this is overridden, or
- // write barriers are not used and this is never called
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(false);
- return false;
- }
-
- /**
- * Attempt to atomically exchange the value in the given slot
- * with the passed replacement value.
- *
- * <b>By default do nothing, override if appropriate.</b>
- *
- * @param src The object into which the Address will be stored
- * @param slot The address into which the Address will be
- * stored.
- * @param old The old Address to be swapped out
- * @param value The new Address
- * @param metaDataA A value that assists the host VM in creating a store
- * @param metaDataB A value that assists the host VM in creating a store
- * @param mode The context in which the store occurred
- * @return True if the swap was successful.
- */
- public boolean addressTryCompareAndSwap(ObjectReference src, Address slot, Address old, Address value, Word metaDataA, Word metaDataB, int mode) {
- // Either: write barriers are used and this is overridden, or
- // write barriers are not used and this is never called
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(false);
- return false;
- }
-
- /**
- * Write an Extent. Take appropriate write barrier actions.<p>
- *
- * <b>By default do nothing, override if appropriate.</b>
- *
- * @param src The object into which the new reference will be stored
- * @param slot The address into which the new reference will be
- * stored.
- * @param value The value of the new Extent
- * @param metaDataA A value that assists the host VM in creating a store
- * @param metaDataB A value that assists the host VM in creating a store
- * @param mode The context in which the store occurred
- */
- public void extentWrite(ObjectReference src, Address slot, Extent value, Word metaDataA, Word metaDataB, int mode) {
- // Either: write barriers are used and this is overridden, or
- // write barriers are not used and this is never called
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(false);
- }
-
- /**
- * Read an Extent. Take appropriate read barrier action, and
- * return the value that was read.<p> This is a <b>substituting<b>
- * barrier. The call to this barrier takes the place of a load.<p>
- *
- * @param src The object reference holding the field being read.
- * @param slot The address of the slot being read.
- * @param metaDataA A value that assists the host VM in creating a load
- * @param metaDataB A value that assists the host VM in creating a load
- * @param mode The context in which the load occurred
- * @return The Extent that was read.
- */
- @Inline
- public Extent extentRead(ObjectReference src, Address slot, Word metaDataA, Word metaDataB, int mode) {
- // Either: read barriers are used and this is overridden, or
- // read barriers are not used and this is never called
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(false);
- return Extent.zero();
- }
-
- /**
- * A number of Extents are about to be copied from object
- * <code>src</code> to object <code>dst</code> (as in an array
- * copy). Thus, <code>dst</code> is the mutated object. Take
- * appropriate write barrier actions.<p>
- *
- * @param src The source array
- * @param srcOffset The starting source offset
- * @param dst The destination array
- * @param dstOffset The starting destination offset
- * @param bytes The number of bytes to be copied
- * @return True if the update was performed by the barrier, false if
- * left to the caller (always false in this case).
- */
- public boolean extentBulkCopy(ObjectReference src, Offset srcOffset, ObjectReference dst, Offset dstOffset, int bytes) {
- // Either: bulk copy is supported and this is overridden, or
- // write barriers are not used and this is never called
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(false);
- return false;
- }
-
- /**
- * Write an Offset. Take appropriate write barrier actions.<p>
- *
- * <b>By default do nothing, override if appropriate.</b>
- *
- * @param src The object into which the new reference will be stored
- * @param slot The address into which the new reference will be
- * stored.
- * @param value The value of the new Offset
- * @param metaDataA A value that assists the host VM in creating a store
- * @param metaDataB A value that assists the host VM in creating a store
- * @param mode The context in which the store occurred
- */
- public void offsetWrite(ObjectReference src, Address slot, Offset value, Word metaDataA, Word metaDataB, int mode) {
- // Either: write barriers are used and this is overridden, or
- // write barriers are not used and this is never called
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(false);
- }
-
- /**
- * Read an Offset. Take appropriate read barrier action, and
- * return the value that was read.<p> This is a <b>substituting<b>
- * barrier. The call to this barrier takes the place of a load.<p>
- *
- * @param src The object reference holding the field being read.
- * @param slot The address of the slot being read.
- * @param metaDataA A value that assists the host VM in creating a load
- * @param metaDataB A value that assists the host VM in creating a load
- * @param mode The context in which the load occurred
- * @return The Offset that was read.
- */
- @Inline
- public Offset offsetRead(ObjectReference src, Address slot, Word metaDataA, Word metaDataB, int mode) {
- // Either: read barriers are used and this is overridden, or
- // read barriers are not used and this is never called
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(false);
- return Offset.zero();
- }
-
- /**
- * A number of Offsets are about to be copied from object
- * <code>src</code> to object <code>dst</code> (as in an array
- * copy). Thus, <code>dst</code> is the mutated object. Take
- * appropriate write barrier actions.<p>
- *
- * @param src The source array
- * @param srcOffset The starting source offset
- * @param dst The destination array
- * @param dstOffset The starting destination offset
- * @param bytes The number of bytes to be copied
- * @return True if the update was performed by the barrier, false if
- * left to the caller (always false in this case).
- */
- public boolean offsetBulkCopy(ObjectReference src, Offset srcOffset, ObjectReference dst, Offset dstOffset, int bytes) {
- // Either: bulk copy is supported and this is overridden, or
- // write barriers are not used and this is never called
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(false);
- return false;
- }
-
- /**
- * Write an object reference. Take appropriate write barrier actions.<p>
- *
- * <b>By default do nothing, override if appropriate.</b>
- *
- * @param src The object into which the new reference will be stored
- * @param slot The address into which the new reference will be
- * stored.
- * @param value The value of the new reference
- * @param metaDataA A value that assists the host VM in creating a store
- * @param metaDataB A value that assists the host VM in creating a store
- * @param mode The context in which the store occurred
- */
- public void objectReferenceWrite(ObjectReference src, Address slot, ObjectReference value, Word metaDataA, Word metaDataB, int mode) {
- // Either: write barriers are used and this is overridden, or
- // write barriers are not used and this is never called
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(false);
- }
-
- /**
- * Read an object reference. Take appropriate read barrier action, and
- * return the value that was read.<p> This is a <b>substituting<b>
- * barrier. The call to this barrier takes the place of a load.<p>
- *
- * @param src The object reference holding the field being read.
- * @param slot The address of the slot being read.
- * @param metaDataA A value that assists the host VM in creating a load
- * @param metaDataB A value that assists the host VM in creating a load
- * @param mode The context in which the load occurred
- * @return The reference that was read.
- */
- @Inline
- public ObjectReference objectReferenceRead(ObjectReference src, Address slot, Word metaDataA, Word metaDataB, int mode) {
- // Either: read barriers are used and this is overridden, or
- // read barriers are not used and this is never called
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(false);
- return ObjectReference.nullReference();
- }
-
- /**
- * A number of references are about to be copied from object
- * <code>src</code> to object <code>dst</code> (as in an array
- * copy). Thus, <code>dst</code> is the mutated object. Take
- * appropriate write barrier actions.<p>
- *
- * @param src The source array
- * @param srcOffset The starting source offset
- * @param dst The destination array
- * @param dstOffset The starting destination offset
- * @param bytes The number of bytes to be copied
- * @return True if the update was performed by the barrier, false if
- * left to the caller (always false in this case).
- */
- public boolean objectReferenceBulkCopy(ObjectReference src, Offset srcOffset, ObjectReference dst, Offset dstOffset, int bytes) {
- // Either: bulk copy is supported and this is overridden, or
- // write barriers are not used and this is never called
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(false);
- return false;
- }
-
-
- /**
- * A new reference is about to be created in a location that is not
- * a regular heap object. Take appropriate write barrier actions.<p>
- *
- * <b>By default do nothing, override if appropriate.</b>
- *
- * @param slot The address into which the new reference will be
- * stored.
- * @param tgt The target of the new reference
- * @param metaDataA A value that assists the host VM in creating a store
- * @param metaDataB A value that assists the host VM in creating a store
- */
- public void objectReferenceNonHeapWrite(Address slot, ObjectReference tgt, Word metaDataA, Word metaDataB) {
- // Either: write barriers are used and this is overridden, or
- // write barriers are not used and this is never called
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(false);
- }
-
- /**
- * Read an object reference. Take appropriate read barrier action, and
- * return the value that was read.<p> This is a <b>substituting<b>
- * barrier. The call to this barrier takes the place of a load.<p>
- *
- * @param slot The address of the slot being read.
- * @param metaDataA A value that assists the host VM in creating a load
- * @param metaDataB A value that assists the host VM in creating a load
- * @return The reference that was read.
- */
- @Inline
- public ObjectReference objectReferenceNonHeapRead(Address slot, Word metaDataA, Word metaDataB) {
- // Either: read barriers are used and this is overridden, or
- // read barriers are not used and this is never called
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(false);
- return ObjectReference.nullReference();
- }
-
- /**
- * Attempt to atomically exchange the value in the given slot
- * with the passed replacement value. If a new reference is
- * created, we must then take appropriate write barrier actions.<p>
- *
- * <b>By default do nothing, override if appropriate.</b>
- *
- * @param src The object into which the new reference will be stored
- * @param slot The address into which the new reference will be
- * stored.
- * @param old The old reference to be swapped out
- * @param tgt The target of the new reference
- * @param metaDataA A value that assists the host VM in creating a store
- * @param metaDataB A value that assists the host VM in creating a store
- * @param mode The context in which the store occurred
- * @return True if the swap was successful.
- */
- public boolean objectReferenceTryCompareAndSwap(ObjectReference src, Address slot, ObjectReference old, ObjectReference tgt, Word metaDataA, Word metaDataB, int mode) {
- // Either: write barriers are used and this is overridden, or
- // write barriers are not used and this is never called
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(false);
- return false;
- }
-
- /**
- * Flush mutator context, in response to a requestMutatorFlush.
- * Also called by the default implementation of deinitMutator.
- */
- public void flush() {
- flushRememberedSets();
- smcode.flush();
- nonmove.flush();
- }
-
- /**
- * Flush per-mutator remembered sets into the global remset pool.
- */
- public void flushRememberedSets() {
- // Either: write barriers are used and this is overridden, or
- // write barriers are not used and this is a no-op
- }
-
- /**
- * Assert that the remsets have been flushed. This is critical to
- * correctness. We need to maintain the invariant that remset entries
- * do not accrue during GC. If the host JVM generates barrier entires
- * it is its own responsibility to ensure that they are flushed before
- * returning to MMTk.
- */
- public void assertRemsetsFlushed() {
- // Either: write barriers are used and this is overridden, or
- // write barriers are not used and this is a no-op
- }
-
- /***********************************************************************
- *
- * Miscellaneous
- */
-
- /** @return the <code>Log</code> instance for this PlanLocal */
- public final Log getLog() {
- return log;
- }
-
- /** @return the unique identifier for this mutator context. */
- @Inline
- public int getId() { return id; }
-
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/plan/Phase.java b/vmkit/mmtk/java/src/org/mmtk/plan/Phase.java
deleted file mode 100644
index 701b442..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/plan/Phase.java
+++ /dev/null
@@ -1,658 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.plan;
-
-import org.mmtk.utility.Constants;
-import org.mmtk.utility.Log;
-import org.mmtk.utility.options.Options;
-import org.mmtk.utility.statistics.Timer;
-import org.mmtk.vm.Collection;
-import org.mmtk.vm.VM;
-
-import org.vmmagic.pragma.*;
-
-/**
- * A garbage collection proceeds as a sequence of phases. Each
- * phase is either simple (singular) or complex (an array).
- *
- * The context an individual phase executes in may be global, mutator,
- * or collector.
- *
- * Phases are executed within a stack and all synchronization between
- * parallel GC threads is managed from within this class.
- *
- * @see CollectorContext#collectionPhase
- * @see MutatorContext#collectionPhase
- * @see Plan#collectionPhase
- */
-@Uninterruptible
-public abstract class Phase implements Constants {
- /***********************************************************************
- *
- * Phase allocation and storage.
- */
-
- /** The maximum number of phases */
- private static final int MAX_PHASES = 64;
- /** The array of phase instances. Zero is unused. */
- private static final Phase[] phases = new Phase[MAX_PHASES];
- /** The id to be allocated for the next phase */
- private static short nextPhaseId = 1;
-
- /** Run the phase globally. */
- protected static final short SCHEDULE_GLOBAL = 1;
- /** Run the phase on collectors. */
- protected static final short SCHEDULE_COLLECTOR = 2;
- /** Run the phase on mutators. */
- protected static final short SCHEDULE_MUTATOR = 3;
- /** Don't run this phase. */
- protected static final short SCHEDULE_PLACEHOLDER = 100;
- /** This is a complex phase. */
- protected static final short SCHEDULE_COMPLEX = 101;
-
- /**
- * Retrieve a phase by the unique phase identifier.
- *
- * @param id The phase identifier.
- * @return The Phase instance.
- */
- public static Phase getPhase(short id) {
- if (VM.VERIFY_ASSERTIONS) {
- VM.assertions._assert(id < nextPhaseId, "Phase ID unknown");
- VM.assertions._assert(phases[id] != null, "Uninitialised phase");
- }
- return phases[id];
- }
-
- /** Get the phase id component of an encoded phase */
- protected static short getPhaseId(int scheduledPhase) {
- short phaseId = (short)(scheduledPhase & 0x0000FFFF);
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(phaseId > 0);
- return phaseId;
- }
-
- /**
- * @param phaseId The unique phase identifier.
- * @return The name of the phase.
- */
- public static String getName(short phaseId) {
- return phases[phaseId].name;
- }
-
- /** Get the ordering component of an encoded phase */
- protected static short getSchedule(int scheduledPhase) {
- short ordering = (short)((scheduledPhase >> 16) & 0x0000FFFF);
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(ordering > 0);
- return ordering;
- }
-
- /** Get the ordering component of an encoded phase */
- protected static String getScheduleName(short ordering) {
- switch (ordering) {
- case SCHEDULE_GLOBAL: return "Global";
- case SCHEDULE_COLLECTOR: return "Collector";
- case SCHEDULE_MUTATOR: return "Mutator";
- case SCHEDULE_PLACEHOLDER: return "Placeholder";
- case SCHEDULE_COMPLEX: return "Complex";
- default: return "UNKNOWN!";
- }
- }
-
- /**
- * Construct a phase.
- *
- * @param name Display name of the phase
- */
- @Interruptible
- public static short createSimple(String name) {
- return new SimplePhase(name).getId();
- }
-
- /**
- * Construct a phase, re-using a specified timer.
- *
- * @param name Display name of the phase
- */
- @Interruptible
- public static short createSimple(String name, Timer timer) {
- return new SimplePhase(name, timer).getId();
- }
-
- /**
- * Construct a complex phase.
- *
- * @param name Display name of the phase
- * @param scheduledPhases The phases in this complex phase.
- */
- @Interruptible
- public static short createComplex(String name,int... scheduledPhases) {
- return new ComplexPhase(name, scheduledPhases).getId();
- }
-
- /**
- * Construct a complex phase, re-using a specified timer.
- *
- * @param name Display name of the phase
- * @param timer Timer for this phase to contribute to
- * @param scheduledPhases The phases in this complex phase.
- */
- @Interruptible
- public static short createComplex(String name, Timer timer, int... scheduledPhases) {
- return new ComplexPhase(name, timer, scheduledPhases).getId();
- }
-
- /**
- * Take the passed phase and return an encoded phase to
- * run that phase as a complex phase.
- *
- * @param phaseId The phase to run as complex
- * @return The encoded phase value.
- */
- public static int scheduleComplex(short phaseId) {
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(Phase.getPhase(phaseId) instanceof ComplexPhase);
- return (SCHEDULE_COMPLEX << 16) + phaseId;
- }
-
- /**
- * Take the passed phase and return an encoded phase to
- * run that phase in a global context;
- *
- * @param phaseId The phase to run globally
- * @return The encoded phase value.
- */
- public static int scheduleGlobal(short phaseId) {
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(Phase.getPhase(phaseId) instanceof SimplePhase);
- return (SCHEDULE_GLOBAL << 16) + phaseId;
- }
-
- /**
- * Take the passed phase and return an encoded phase to
- * run that phase in a collector context;
- *
- * @param phaseId The phase to run on collectors
- * @return The encoded phase value.
- */
- public static int scheduleCollector(short phaseId) {
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(Phase.getPhase(phaseId) instanceof SimplePhase);
- return (SCHEDULE_COLLECTOR << 16) + phaseId;
- }
-
- /**
- * Take the passed phase and return an encoded phase to
- * run that phase in a mutator context;
- *
- * @param phaseId The phase to run on mutators
- * @return The encoded phase value.
- */
- public static int scheduleMutator(short phaseId) {
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(Phase.getPhase(phaseId) instanceof SimplePhase);
- return (SCHEDULE_MUTATOR << 16) + phaseId;
- }
-
- /**
- * Take the passed phase and return an encoded phase to
- * run that phase in a mutator context;
- *
- * @param phaseId The phase to run on mutators
- * @return The encoded phase value.
- */
- public static int schedulePlaceholder(short phaseId) {
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(Phase.getPhase(phaseId) instanceof SimplePhase);
- return (SCHEDULE_PLACEHOLDER << 16) + phaseId;
- }
-
- /***********************************************************************
- *
- * Phase instance fields/methods.
- */
-
- /**
- * The unique phase identifier.
- */
- protected final short id;
-
- /**
- * The name of the phase.
- */
- protected final String name;
-
- /**
- * The Timer that is started and stopped around the execution of this
- * phase.
- */
- protected final Timer timer;
-
- /**
- * Create a new Phase. This involves creating a corresponding Timer
- * instance, allocating a unique identifier, and registering the
- * Phase.
- *
- * @param name The name for the phase.
- */
- protected Phase(String name) {
- this(name, new Timer(name, false, true));
- }
-
- /**
- * Create a new phase. This involves setting the corresponding Timer
- * instance, allocating a unique identifier, and registering the Phase.
- *
- * @param name The name of the phase.
- * @param timer The timer, or null if this is an untimed phase.
- */
- protected Phase(String name, Timer timer) {
- this.name = name;
- this.timer = timer;
- this.id = nextPhaseId++;
- phases[this.id] = this;
- }
-
- /**
- * @return The unique identifier for this phase.
- */
- public final short getId() {
- return this.id;
- }
-
- /**
- * Display a phase for debugging purposes.
- */
- protected abstract void logPhase();
-
- /***********************************************************************
- *
- * Phase stack
- */
-
- /** The maximum stack depth for the phase stack. */
- private static final int MAX_PHASE_STACK_DEPTH = MAX_PHASES;
-
- /** Stores the current sub phase for a complex phase. Each entry corresponds to a phase stack entry */
- private static int[] complexPhaseCursor = new int[MAX_PHASE_STACK_DEPTH];
-
- /** The phase stack. Stores the current nesting of phases */
- private static int[] phaseStack = new int[MAX_PHASE_STACK_DEPTH];
-
- /** The current stack pointer */
- private static int phaseStackPointer = -1;
-
- /**
- * The current even (0 mod 2) scheduled phase.
- * As we only sync at the end of a phase we need this to ensure that
- * the primary thread setting the phase does not race with the other
- * threads reading it.
- */
- private static int evenScheduledPhase;
-
- /**
- * The current odd (1 mod 2) scheduled phase.
- * As we only sync at the end of a phase we need this to ensure that
- * the primary thread setting the phase does not race with the other
- * threads reading it.
- */
- private static int oddScheduledPhase;
-
- /**
- * Do we need to add a sync point to reset the mutator count. This
- * is necessary for consecutive mutator phases and unneccessary
- * otherwise. Again we separate in even and odd to ensure that there
- * is no race between the primary thread setting and the helper
- * threads reading.
- */
- private static boolean evenMutatorResetRendezvous;
-
- /**
- * Do we need to add a sync point to reset the mutator count. This
- * is necessary for consecutive mutator phases and unneccessary
- * otherwise. Again we separate in even and odd to ensure that there
- * is no race between the primary thread setting and the helper
- * threads reading.
- */
- private static boolean oddMutatorResetRendezvous;
-
- /**
- * The complex phase whose timer should be started after the next
- * rendezvous. We can not start the timer at the point we determine
- * the next complex phase as we determine the next phase at the
- * end of the previous phase before the sync point.
- */
- private static short startComplexTimer;
-
- /**
- * The complex phase whose timer should be stopped after the next
- * rendezvous. We can not start the timer at the point we determine
- * the next complex phase as we determine the next phase at the
- * end of the previous phase before the sync point.
- */
- private static short stopComplexTimer;
-
- /**
- * Place a phase on the phase stack and begin processing.
- *
- * @param scheduledPhase The phase to execute
- * @return True if the phase stack is exhausted.
- */
- public static boolean beginNewPhaseStack(int scheduledPhase) {
- int order = VM.collection.rendezvous(1001);
-
- if (order == 1) {
- pushScheduledPhase(scheduledPhase);
- }
- return processPhaseStack(false);
- }
-
- /**
- * Process the phase stack. This method is called by multiple threads.
- */
- private static boolean processPhaseStack(boolean resume) {
- int order = VM.collection.rendezvous(1001);
- final boolean primary = order == 1;
-
- boolean log = Options.verbose.getValue() >= 6;
- boolean logDetails = Options.verbose.getValue() >= 7;
-
- if (primary && resume) {
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(!Phase.isPhaseStackEmpty());
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(!Plan.gcInProgress());
- Plan.setGCStatus(Plan.GC_PROPER);
- }
-
- /* In order to reduce the need for synchronization, we keep an odd or even
- * counter for the number of phases processed. As each phase has a single
- * rendezvous it is only possible to be out by one so the odd or even counter
- * protects us. */
- boolean isEvenPhase = true;
-
- if (primary) {
- /* First phase will be even, so we say we are odd here so that the next phase set is even*/
- setNextPhase(false, getNextPhase(), false);
- }
-
- /* Make sure everyone sees the first phase */
- VM.collection.rendezvous(1002);
-
- /* Global and Collector instances used in phases */
- Plan plan = VM.activePlan.global();
- CollectorContext collector = VM.activePlan.collector();
-
- /* The main phase execution loop */
- int scheduledPhase;
- while((scheduledPhase = getCurrentPhase(isEvenPhase)) > 0) {
- short schedule = getSchedule(scheduledPhase);
- short phaseId = getPhaseId(scheduledPhase);
- Phase p = getPhase(phaseId);
-
- /* Start the timer(s) */
- if (primary) {
- if (resume) {
- resumeComplexTimers();
- }
- if (p.timer != null) p.timer.start();
- if (startComplexTimer > 0) {
- Phase.getPhase(startComplexTimer).timer.start();
- startComplexTimer = 0;
- }
- }
-
- if (log) {
- Log.write("Execute ");
- p.logPhase();
- }
-
- /* Execute a single simple scheduled phase */
- switch (schedule) {
- /* Global phase */
- case SCHEDULE_GLOBAL: {
- if (logDetails) Log.writeln(" as Global...");
- if (primary) {
- if (VM.DEBUG) VM.debugging.globalPhase(phaseId,true);
- plan.collectionPhase(phaseId);
- if (VM.DEBUG) VM.debugging.globalPhase(phaseId,false);
- }
- break;
- }
-
- /* Collector phase */
- case SCHEDULE_COLLECTOR: {
- if (logDetails) Log.writeln(" as Collector...");
- if (VM.DEBUG) VM.debugging.collectorPhase(phaseId,order,true);
- collector.collectionPhase(phaseId, primary);
- if (VM.DEBUG) VM.debugging.collectorPhase(phaseId,order,false);
- break;
- }
-
- /* Mutator phase */
- case SCHEDULE_MUTATOR: {
- if (logDetails) Log.writeln(" as Mutator...");
- /* Iterate through all mutator contexts */
- MutatorContext mutator;
- while ((mutator = VM.activePlan.getNextMutator()) != null) {
- if (VM.DEBUG) VM.debugging.mutatorPhase(phaseId,mutator.getId(),true);
- mutator.collectionPhase(phaseId, primary);
- if (VM.DEBUG) VM.debugging.mutatorPhase(phaseId,mutator.getId(),false);
- }
- break;
- }
-
- default: {
- /* getNextPhase has done the wrong thing */
- VM.assertions.fail("Invalid schedule in Phase.processPhaseStack");
- break;
- }
- }
-
- if (primary) {
- /* Set the next phase by processing the stack */
- int next = getNextPhase();
- boolean needsResetRendezvous = (next > 0) && (schedule == SCHEDULE_MUTATOR && getSchedule(next) == SCHEDULE_MUTATOR);
- setNextPhase(isEvenPhase, next, needsResetRendezvous);
- }
-
- /* Sync point after execution of a phase */
- VM.collection.rendezvous(1004);
-
- /* Mutator phase reset */
- if (primary && schedule == SCHEDULE_MUTATOR) {
- VM.activePlan.resetMutatorIterator();
- }
-
- /* At this point, in the case of consecutive phases with mutator
- * scheduling, we have to double-synchronize to ensure all
- * collector threads see the reset mutator counter. */
- if (needsMutatorResetRendezvous(isEvenPhase)) {
- VM.collection.rendezvous(1005);
- }
-
- /* Stop the timer(s) */
- if (primary) {
- if (p.timer != null) p.timer.stop();
- if (stopComplexTimer > 0) {
- Phase.getPhase(stopComplexTimer).timer.stop();
- stopComplexTimer = 0;
- }
- }
-
- /* Flip the even / odd phase sense */
- isEvenPhase = !isEvenPhase;
- resume = false;
- }
-
- /* Phase stack exhausted so we return true */
- return true;
- }
-
- /**
- * Get the next phase.
- */
- private static int getCurrentPhase(boolean isEvenPhase) {
- return isEvenPhase ? evenScheduledPhase : oddScheduledPhase;
- }
-
- /**
- * Do we need a mutator reset rendezvous in this phase?
- */
- private static boolean needsMutatorResetRendezvous(boolean isEvenPhase) {
- return isEvenPhase ? evenMutatorResetRendezvous : oddMutatorResetRendezvous;
- }
- /**
- * Set the next phase. If we are in an even phase the next phase is odd.
- */
- private static void setNextPhase(boolean isEvenPhase, int scheduledPhase, boolean needsResetRendezvous) {
- if (isEvenPhase) {
- oddScheduledPhase = scheduledPhase;
- evenMutatorResetRendezvous = needsResetRendezvous;
- } else {
- evenScheduledPhase = scheduledPhase;
- oddMutatorResetRendezvous = needsResetRendezvous;
- }
- }
-
- /**
- * Pull the next scheduled phase off the stack. This may involve
- * processing several complex phases and skipping placeholders, etc.
- *
- * @return The next phase to run, or -1 if no phases are left.
- */
- private static int getNextPhase() {
- boolean allowConcurrentPhase = Plan.collectionTrigger == Collection.INTERNAL_PHASE_GC_TRIGGER;
-
- while (phaseStackPointer >= 0) {
- int scheduledPhase = peekScheduledPhase();
- short schedule = getSchedule(scheduledPhase);
- short phaseId = getPhaseId(scheduledPhase);
-
- switch(schedule) {
- case SCHEDULE_PLACEHOLDER: {
- /* Placeholders are ignored and we continue looking */
- popScheduledPhase();
- continue;
- }
-
- case SCHEDULE_GLOBAL:
- case SCHEDULE_COLLECTOR:
- case SCHEDULE_MUTATOR: {
- /* Simple phases are just popped off the stack and executed */
- popScheduledPhase();
- return scheduledPhase;
- }
-
- case SCHEDULE_COMPLEX: {
- /* A complex phase may either be a newly pushed complex phase,
- * or a complex phase we are in the process of executing in
- * which case we move to the next subphase. */
- ComplexPhase p = (ComplexPhase)getPhase(phaseId);
- int cursor = incrementComplexPhaseCursor();
- if (cursor == 0 && p.timer != null) {
- /* Tell the primary thread to start the timer after the next sync. */
- startComplexTimer = phaseId;
- }
- if (cursor < p.count()) {
- /* There are more entries, we push the next one and continue */
- pushScheduledPhase(p.get(cursor));
- continue;
- }
-
- /* We have finished this complex phase */
- popScheduledPhase();
- if (p.timer != null) {
- /* Tell the primary thread to stop the timer after the next sync. */
- stopComplexTimer = phaseId;
- }
- continue;
- }
-
- default: {
- VM.assertions.fail("Invalid phase type encountered");
- }
- }
- }
- return -1;
- }
-
- /**
- * Pause all of the timers for the complex phases sitting in the stack.
- */
- private static void pauseComplexTimers() {
- for(int i=phaseStackPointer; i >=0; i--) {
- Phase p = getPhase(getPhaseId(phaseStack[i]));
- if (p.timer != null) p.timer.stop();
- }
- }
-
- /**
- * Resume all of the timers for the complex phases sitting in the stack.
- */
- private static void resumeComplexTimers() {
- for(int i=phaseStackPointer; i >=0; i--) {
- Phase p = getPhase(getPhaseId(phaseStack[i]));
- if (p.timer != null) p.timer.start();
- }
- }
-
- /**
- * Return true if phase stack is empty, false otherwise.
- *
- * @return true if phase stack is empty, false otherwise.
- */
- @Inline
- public static boolean isPhaseStackEmpty() {
- return phaseStackPointer < 0;
- }
-
- /**
- * Clears the scheduled phase stack.
- */
- @Inline
- public static void resetPhaseStack() {
- phaseStackPointer = -1;
- }
-
- /**
- * Push a scheduled phase onto the top of the work stack.
- *
- * @param scheduledPhase The scheduled phase.
- */
- @Inline
- public static void pushScheduledPhase(int scheduledPhase) {
- phaseStack[++phaseStackPointer] = scheduledPhase;
- complexPhaseCursor[phaseStackPointer] = 0;
- }
-
- /**
- * Increment the cursor associated with the current phase
- * stack entry. This is used to remember the current sub phase
- * when executing a complex phase.
- *
- * @return The old value of the cursor.
- */
- @Inline
- private static int incrementComplexPhaseCursor() {
- return complexPhaseCursor[phaseStackPointer]++;
- }
-
- /**
- * Pop off the scheduled phase at the top of the work stack.
- */
- @Inline
- private static int popScheduledPhase() {
- return phaseStack[phaseStackPointer--];
- }
-
- /**
- * Peek the scheduled phase at the top of the work stack.
- */
- @Inline
- private static int peekScheduledPhase() {
- return phaseStack[phaseStackPointer];
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/plan/Plan.java b/vmkit/mmtk/java/src/org/mmtk/plan/Plan.java
deleted file mode 100644
index 75d644c..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/plan/Plan.java
+++ /dev/null
@@ -1,984 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.plan;
-
-import org.mmtk.policy.MarkSweepSpace;
-import org.mmtk.policy.Space;
-import org.mmtk.policy.ImmortalSpace;
-import org.mmtk.policy.RawPageSpace;
-import org.mmtk.policy.LargeObjectSpace;
-import org.mmtk.utility.alloc.LinearScan;
-import org.mmtk.utility.Constants;
-import org.mmtk.utility.Conversions;
-import org.mmtk.utility.heap.HeapGrowthManager;
-import org.mmtk.utility.heap.Map;
-import org.mmtk.utility.heap.VMRequest;
-import org.mmtk.utility.Log;
-import org.mmtk.utility.options.*;
-import org.mmtk.utility.sanitychecker.SanityChecker;
-import org.mmtk.utility.statistics.Timer;
-import org.mmtk.utility.statistics.Stats;
-
-import org.mmtk.vm.VM;
-import org.mmtk.vm.Collection;
-
-
-import org.vmmagic.pragma.*;
-import org.vmmagic.unboxed.*;
-
-/**
- * This abstract class implements the global core functionality for all
- * memory management schemes. All global MMTk plans should inherit from
- * this class.<p>
- *
- * All plans make a clear distinction between <i>global</i> and
- * <i>thread-local</i> activities, and divides global and local state
- * into separate class hierarchies. Global activities must be
- * synchronized, whereas no synchronization is required for
- * thread-local activities. There is a single instance of Plan (or the
- * appropriate sub-class), and a 1:1 mapping of PlanLocal to "kernel
- * threads" (aka CPUs). Thus instance
- * methods of PlanLocal allow fast, unsynchronized access to functions such as
- * allocation and collection.
- *
- * The global instance defines and manages static resources
- * (such as memory and virtual memory resources). This mapping of threads to
- * instances is crucial to understanding the correctness and
- * performance properties of MMTk plans.
- */
-@Uninterruptible
-public abstract class Plan implements Constants {
- /****************************************************************************
- * Constants
- */
-
- /* GC State */
- public static final int NOT_IN_GC = 0; // this must be zero for C code
- public static final int GC_PREPARE = 1; // before setup and obtaining root
- public static final int GC_PROPER = 2;
-
- /* Polling */
- public static final int DEFAULT_POLL_FREQUENCY = (128 << 10) >> LOG_BYTES_IN_PAGE;
- public static final int META_DATA_POLL_FREQUENCY = DEFAULT_POLL_FREQUENCY;
-
- /* Space Size Constants. */
- public static final boolean USE_CODE_SPACE = true;
- public static final float PLOS_FRAC = 0.07f;
- public static final int HEAP_FULL_MINIMUM = (1 << 17) >> LOG_BYTES_IN_PAGE; // 128K
- public static final int HEAP_FULL_PERCENTAGE = 2;
-
- /* Allocator Constants */
- public static final int ALLOC_DEFAULT = 0;
- public static final int ALLOC_NON_REFERENCE = 1;
- public static final int ALLOC_NON_MOVING = 2;
- public static final int ALLOC_IMMORTAL = 3;
- public static final int ALLOC_LOS = 4;
- public static final int ALLOC_PRIMITIVE_LOS = 5;
- public static final int ALLOC_GCSPY = 6;
- public static final int ALLOC_CODE = 7;
- public static final int ALLOC_LARGE_CODE = 8;
- public static final int ALLOC_HOT_CODE = USE_CODE_SPACE ? ALLOC_CODE : ALLOC_DEFAULT;
- public static final int ALLOC_COLD_CODE = USE_CODE_SPACE ? ALLOC_CODE : ALLOC_DEFAULT;
- public static final int ALLOC_STACK = ALLOC_LOS;
- public static final int ALLOCATORS = 9;
- public static final int DEFAULT_SITE = -1;
-
- /* Miscellaneous Constants */
-// public static final int LOS_SIZE_THRESHOLD = SegregatedFreeListSpace.MAX_CELL_SIZE;
- public static final int NON_PARTICIPANT = 0;
- public static final boolean GATHER_WRITE_BARRIER_STATS = false;
- public static final int DEFAULT_MIN_NURSERY = (256 * 1024) >> LOG_BYTES_IN_PAGE;
- public static final int DEFAULT_MAX_NURSERY = (32 << 20) >> LOG_BYTES_IN_PAGE;
- public static final boolean SCAN_BOOT_IMAGE = true; // scan it for roots rather than trace it
- public static final int MAX_COLLECTION_ATTEMPTS = 10;
- // public static final boolean REQUIRES_LOS = VM.activePlan.constraints().requiresLOS();
- public static final int MAX_NON_LOS_DEFAULT_ALLOC_BYTES = VM.activePlan.constraints().maxNonLOSDefaultAllocBytes();
- public static final int MAX_NON_LOS_NONMOVING_ALLOC_BYTES = VM.activePlan.constraints().maxNonLOSNonMovingAllocBytes();
- public static final int MAX_NON_LOS_COPY_BYTES = VM.activePlan.constraints().maxNonLOSCopyBytes();
-
-
-/* Do we support a log bit in the object header? Some write barriers may use it */
- public static final boolean NEEDS_LOG_BIT_IN_HEADER = VM.activePlan.constraints().needsLogBitInHeader();
-
- /****************************************************************************
- * Class variables
- */
-
- /** The space that holds any VM specific objects (e.g. a boot image) */
- public static final Space vmSpace = VM.memory.getVMSpace();
-
- /** Any immortal objects allocated after booting are allocated here. */
- public static final ImmortalSpace immortalSpace = new ImmortalSpace("immortal", DEFAULT_POLL_FREQUENCY, VMRequest.create());
-
- /** All meta data that is used by MMTk is allocated (and accounted for) in the meta data space. */
- public static final RawPageSpace metaDataSpace = new RawPageSpace("meta", DEFAULT_POLL_FREQUENCY, VMRequest.create());
-
- /** Large objects are allocated into a special large object space. */
- public static final LargeObjectSpace loSpace = new LargeObjectSpace("los", DEFAULT_POLL_FREQUENCY, VMRequest.create());
-
- /** Space used by the sanity checker (used at runtime only if sanity checking enabled */
- public static final RawPageSpace sanitySpace = new RawPageSpace("sanity", Integer.MAX_VALUE, VMRequest.create());
-
- /** Space used to allocate objects that cannot be moved. we do not need a large space as the LOS is non-moving. */
- public static final MarkSweepSpace nonMovingSpace = new MarkSweepSpace("non-moving", DEFAULT_POLL_FREQUENCY, VMRequest.create());
-
- public static final MarkSweepSpace smallCodeSpace = USE_CODE_SPACE ? new MarkSweepSpace("sm-code", DEFAULT_POLL_FREQUENCY, VMRequest.create()) : null;
- public static final LargeObjectSpace largeCodeSpace = USE_CODE_SPACE ? new LargeObjectSpace("lg-code", DEFAULT_POLL_FREQUENCY, VMRequest.create()) : null;
-
- /* Space descriptors */
- public static final int IMMORTAL = immortalSpace.getDescriptor();
- public static final int VM_SPACE = vmSpace.getDescriptor();
- public static final int META = metaDataSpace.getDescriptor();
- public static final int LOS = loSpace.getDescriptor();
- public static final int SANITY = sanitySpace.getDescriptor();
- public static final int NON_MOVING = nonMovingSpace.getDescriptor();
- public static final int SMALL_CODE = USE_CODE_SPACE ? smallCodeSpace.getDescriptor() : 0;
- public static final int LARGE_CODE = USE_CODE_SPACE ? largeCodeSpace.getDescriptor() : 0;
-
- /** Timer that counts total time */
- public static final Timer totalTime = new Timer("time");
-
- /** Support for time-limited GCs */
- protected static long timeCap;
-
- /** Support for allocation-site identification */
- protected static int allocationSiteCount = 0;
-
- /** Global sanity checking state **/
- public static final SanityChecker sanityChecker = new SanityChecker();
-
- /****************************************************************************
- * Constructor.
- */
- public Plan() {
- /* Create base option instances */
- Options.verbose = new Verbose();
- Options.verboseTiming = new VerboseTiming();
- Options.stressFactor = new StressFactor();
- Options.noFinalizer = new NoFinalizer();
- Options.noReferenceTypes = new NoReferenceTypes();
- Options.fullHeapSystemGC = new FullHeapSystemGC();
- Options.harnessAll = new HarnessAll();
- Options.ignoreSystemGC = new IgnoreSystemGC();
- Options.metaDataLimit = new MetaDataLimit();
- Options.nurserySize = new NurserySize();
- Options.variableSizeHeap = new VariableSizeHeap();
- Options.eagerMmapSpaces = new EagerMmapSpaces();
- Options.sanityCheck = new SanityCheck();
- Options.debugAddress = new DebugAddress();
- Options.perfEvents = new PerfEvents();
- Map.finalizeStaticSpaceMap();
- registerSpecializedMethods();
- }
-
- /****************************************************************************
- * Boot.
- */
-
- /**
- * The boot method is called early in the boot process before any
- * allocation.
- */
- @Interruptible
- public void boot() {
- }
-
- /**
- * The postBoot method is called by the runtime immediately after
- * command-line arguments are available. Note that allocation must
- * be supported prior to this point because the runtime
- * infrastructure may require allocation in order to parse the
- * command line arguments. For this reason all plans should operate
- * gracefully on the default minimum heap size until the point that
- * boot is called.
- */
- @Interruptible
- public void postBoot() {
- VM.statistics.perfEventInit(Options.perfEvents.getValue());
- if (Options.verbose.getValue() > 2) Space.printVMMap();
- if (Options.verbose.getValue() > 3) VM.config.printConfig();
- if (Options.verbose.getValue() > 0) Stats.startAll();
- if (Options.eagerMmapSpaces.getValue()) Space.eagerlyMmapMMTkSpaces();
- }
-
- /**
- * The fullyBooted method is called by the runtime just before normal
- * execution commences.
- */
- @Interruptible
- public void fullyBooted() {
- initialized = true;
- if (Options.harnessAll.getValue()) harnessBegin();
- }
-
- /**
- * The VM is about to exit. Perform any clean up operations.
- *
- * @param value The exit value
- */
- @Interruptible
- public void notifyExit(int value) {
- if (Options.harnessAll.getValue()) harnessEnd();
- if (Options.verbose.getValue() == 1) {
- Log.write("[End ");
- totalTime.printTotalSecs();
- Log.writeln(" s]");
- } else if (Options.verbose.getValue() == 2) {
- Log.write("[End ");
- totalTime.printTotalMillis();
- Log.writeln(" ms]");
- }
- if (Options.verboseTiming.getValue()) printDetailedTiming(true);
- }
-
- /**
- * Any Plan can override this to provide additional plan specific
- * timing information.
- *
- * @param totals Print totals
- */
- protected void printDetailedTiming(boolean totals) {}
-
- /**
- * Perform any required write barrier action when installing an object reference
- * a boot time.
- *
- * @param reference the reference value that is to be stored
- * @return The raw value to be
- */
- public Word bootTimeWriteBarrier(Word reference) {
- return reference;
- }
-
- /****************************************************************************
- * Allocation
- */
- public static int getAllocationSite(boolean compileTime) {
- if (compileTime) // a new allocation site is being compiled
- return allocationSiteCount++;
- else // an anonymous site
- return DEFAULT_SITE;
- }
-
- /****************************************************************************
- * Collection.
- */
-
- /**
- * Perform a (global) collection phase.
- */
- public abstract void collectionPhase(short phase);
-
- /**
- * Replace a phase.
- *
- * @param oldScheduledPhase The scheduled phase to insert after
- * @param scheduledPhase The scheduled phase to insert
- */
- @Interruptible
- public void replacePhase(int oldScheduledPhase, int scheduledPhase) {
- VM.assertions.fail("replacePhase not implemented for this plan");
- }
-
-
- /**
- * Insert a phase.
- *
- * @param markerScheduledPhase The scheduled phase to insert after
- * @param scheduledPhase The scheduled phase to insert
- */
- @Interruptible
- public void insertPhaseAfter(int markerScheduledPhase, int scheduledPhase) {
- short tempPhase = Phase.createComplex("auto-gen", null, markerScheduledPhase, scheduledPhase);
- replacePhase(markerScheduledPhase, Phase.scheduleComplex(tempPhase));
- }
-
- /**
- * @return Whether last GC was an exhaustive attempt to collect the heap. For many collectors this is the same as asking whether the last GC was a full heap collection.
- */
- public boolean lastCollectionWasExhaustive() {
- return lastCollectionFullHeap();
- }
-
- /**
- * @return Whether last GC is a full GC.
- */
- public boolean lastCollectionFullHeap() {
- return true;
- }
-
- /**
- * @return Is last GC a full collection?
- */
- public static boolean isEmergencyCollection() {
- return emergencyCollection;
- }
-
- /**
- * @return True if we have run out of heap space.
- */
- public final boolean lastCollectionFailed() {
- return !(collectionTrigger == Collection.EXTERNAL_GC_TRIGGER ||
- collectionTrigger == Collection.INTERNAL_PHASE_GC_TRIGGER) &&
- (getPagesAvail() < getHeapFullThreshold() || getPagesAvail() < requiredAtStart);
- }
-
- /**
- * Force the next collection to be full heap.
- */
- public void forceFullHeapCollection() {}
-
- /**
- * @return Is current GC only collecting objects allocated since last GC.
- */
- public boolean isCurrentGCNursery() {
- return false;
- }
-
- private long lastStressPages = 0;
-
- /**
- * Return the expected reference count. For non-reference counting
- * collectors this becomes a true/false relationship.
- *
- * @param object The object to check.
- * @param sanityRootRC The number of root references to the object.
- * @return The expected (root excluded) reference count.
- */
- public int sanityExpectedRC(ObjectReference object, int sanityRootRC) {
- Space space = Space.getSpaceForObject(object);
- return space.isReachable(object) ? SanityChecker.ALIVE : SanityChecker.DEAD;
- }
-
- /**
- * Perform a linear scan of all spaces to check for possible leaks.
- * This is only called after a full-heap GC.
- *
- * @param scanner The scanner callback to use.
- */
- public void sanityLinearScan(LinearScan scanner) {
- }
-
- /**
- * @return True is a stress test GC is required
- */
- @Inline
- public final boolean stressTestGCRequired() {
- long pages = Space.cumulativeCommittedPages();
- if (initialized &&
- ((pages ^ lastStressPages) > Options.stressFactor.getPages())) {
- lastStressPages = pages;
- return true;
- } else
- return false;
- }
-
- /****************************************************************************
- * GC State
- */
-
- protected static int requiredAtStart;
- protected static int collectionTrigger;
- protected static boolean emergencyCollection;
- protected static boolean awaitingAsyncCollection;
- protected static boolean stacksPrepared;
-
- private static boolean initialized = false;
- private static boolean collectionTriggered;
- @Entrypoint
- private static int gcStatus = NOT_IN_GC; // shared variable
-
- /** @return Is the memory management system initialized? */
- public static boolean isInitialized() {
- return initialized;
- }
-
- /**
- * Has collection has triggered?
- */
- public static boolean isCollectionTriggered() {
- return collectionTriggered;
- }
-
- /**
- * Set that a collection has been triggered.
- */
- public static void setCollectionTriggered() {
- collectionTriggered = true;
- }
-
- /**
- * A collection has fully completed. Clear the triggered flag.
- */
- public static void collectionComplete() {
- collectionTriggered = false;
- }
-
- /**
- * Return true if stacks have been prepared in this collection cycle.
- *
- * @return True if stacks have been prepared in this collection cycle.
- */
- public static boolean stacksPrepared() {
- return stacksPrepared;
- }
- /**
- * Return true if a collection is in progress.
- *
- * @return True if a collection is in progress.
- */
- public static boolean gcInProgress() {
- return gcStatus != NOT_IN_GC;
- }
-
- /**
- * Return true if a collection is in progress and past the preparatory stage.
- *
- * @return True if a collection is in progress and past the preparatory stage.
- */
- public static boolean gcInProgressProper() {
- return gcStatus == GC_PROPER;
- }
-
- /**
- * Sets the GC status.
- *
- * @param s The new GC status.
- */
- public static void setGCStatus(int s) {
- if (gcStatus == NOT_IN_GC) {
- /* From NOT_IN_GC to any phase */
- stacksPrepared = false;
- if (Stats.gatheringStats()) {
- Stats.startGC();
- VM.activePlan.global().printPreStats();
- }
- }
- VM.memory.isync();
- gcStatus = s;
- VM.memory.sync();
- if (gcStatus == NOT_IN_GC) {
- /* From any phase to NOT_IN_GC */
- if (Stats.gatheringStats()) {
- Stats.endGC();
- VM.activePlan.global().printPostStats();
- }
- }
- }
-
- /**
- * Print out statistics at the start of a GC
- */
- public void printPreStats() {
- if ((Options.verbose.getValue() == 1) ||
- (Options.verbose.getValue() == 2)) {
- Log.write("[GC "); Log.write(Stats.gcCount());
- if (Options.verbose.getValue() == 1) {
- Log.write(" Start ");
- Plan.totalTime.printTotalSecs();
- Log.write(" s");
- } else {
- Log.write(" Start ");
- Plan.totalTime.printTotalMillis();
- Log.write(" ms");
- }
- Log.write(" ");
- Log.write(Conversions.pagesToKBytes(getPagesUsed()));
- Log.write("KB ");
- Log.flush();
- }
- if (Options.verbose.getValue() > 2) {
- Log.write("Collection "); Log.write(Stats.gcCount());
- Log.write(": ");
- printUsedPages();
- Log.write(" Before Collection: ");
- Space.printUsageMB();
- if (Options.verbose.getValue() >= 4) {
- Log.write(" ");
- Space.printUsagePages();
- }
- if (Options.verbose.getValue() >= 5) {
- Space.printVMMap();
- }
- }
- }
-
- /**
- * Print out statistics at the end of a GC
- */
- public final void printPostStats() {
- if ((Options.verbose.getValue() == 1) ||
- (Options.verbose.getValue() == 2)) {
- Log.write("-> ");
- Log.writeDec(Conversions.pagesToBytes(getPagesUsed()).toWord().rshl(10));
- Log.write("KB ");
- if (Options.verbose.getValue() == 1) {
- totalTime.printLast();
- Log.writeln(" ms]");
- } else {
- Log.write("End ");
- totalTime.printTotal();
- Log.writeln(" ms]");
- }
- }
- if (Options.verbose.getValue() > 2) {
- Log.write(" After Collection: ");
- Space.printUsageMB();
- if (Options.verbose.getValue() >= 4) {
- Log.write(" ");
- Space.printUsagePages();
- }
- if (Options.verbose.getValue() >= 5) {
- Space.printVMMap();
- }
- Log.write(" ");
- printUsedPages();
- Log.write(" Collection time: ");
- totalTime.printLast();
- Log.writeln(" ms");
- }
- }
-
- public final void printUsedPages() {
- Log.write("reserved = ");
- Log.write(Conversions.pagesToMBytes(getPagesReserved()));
- Log.write(" MB (");
- Log.write(getPagesReserved());
- Log.write(" pgs)");
- Log.write(" total = ");
- Log.write(Conversions.pagesToMBytes(getTotalPages()));
- Log.write(" MB (");
- Log.write(getTotalPages());
- Log.write(" pgs)");
- Log.writeln();
- }
-
- /**
- * Set the collection trigger.
- */
- public static void setCollectionTrigger(int trigger) {
- collectionTrigger = trigger;
- }
-
- /****************************************************************************
- * Harness
- */
- protected static boolean insideHarness = false;
-
- /**
- * Generic hook to allow benchmarks to be harnessed. A plan may use
- * this to perform certain actions prior to the commencement of a
- * benchmark, such as a full heap collection, turning on
- * instrumentation, etc. By default we do a full heap GC,
- * and then start stats collection.
- */
- @Interruptible
- public static void harnessBegin() {
- // Save old values.
- boolean oldFullHeap = Options.fullHeapSystemGC.getValue();
- boolean oldIgnore = Options.ignoreSystemGC.getValue();
-
- // Set desired values.
- Options.fullHeapSystemGC.setValue(true);
- Options.ignoreSystemGC.setValue(false);
-
- // Trigger a full heap GC.
- System.gc();
-
- // Restore old values.
- Options.ignoreSystemGC.setValue(oldIgnore);
- Options.fullHeapSystemGC.setValue(oldFullHeap);
-
- // Start statistics
- insideHarness = true;
- Stats.startAll();
- }
-
- /**
- * Generic hook to allow benchmarks to be harnessed. A plan may use
- * this to perform certain actions after the completion of a
- * benchmark, such as a full heap collection, turning off
- * instrumentation, etc. By default we stop all statistics objects
- * and print their values.
- */
- @Interruptible
- public static void harnessEnd() {
- Stats.stopAll();
- insideHarness = false;
- }
-
- /****************************************************************************
- * VM Accounting
- */
-
- /* Global accounting and static access */
-
- /**
- * Return the amount of <i>free memory</i>, in bytes (where free is
- * defined as not in use). Note that this may overstate the amount
- * of <i>available memory</i>, which must account for unused memory
- * that is held in reserve for copying, and therefore unavailable
- * for allocation.
- *
- * @return The amount of <i>free memory</i>, in bytes (where free is
- * defined as not in use).
- */
- public static Extent freeMemory() {
- return totalMemory().minus(usedMemory());
- }
-
- /**
- * Return the amount of <i>available memory</i>, in bytes. Note
- * that this accounts for unused memory that is held in reserve
- * for copying, and therefore unavailable for allocation.
- *
- * @return The amount of <i>available memory</i>, in bytes.
- */
- public static Extent availableMemory() {
- return totalMemory().minus(reservedMemory());
- }
-
- /**
- * Return the amount of <i>memory in use</i>, in bytes. Note that
- * this excludes unused memory that is held in reserve for copying,
- * and therefore unavailable for allocation.
- *
- * @return The amount of <i>memory in use</i>, in bytes.
- */
- public static Extent usedMemory() {
- return Conversions.pagesToBytes(VM.activePlan.global().getPagesUsed());
- }
-
-
- /**
- * Return the amount of <i>memory in use</i>, in bytes. Note that
- * this includes unused memory that is held in reserve for copying,
- * and therefore unavailable for allocation.
- *
- * @return The amount of <i>memory in use</i>, in bytes.
- */
- public static Extent reservedMemory() {
- return Conversions.pagesToBytes(VM.activePlan.global().getPagesReserved());
- }
-
- /**
- * Return the total amount of memory managed to the memory
- * management system, in bytes.
- *
- * @return The total amount of memory managed to the memory
- * management system, in bytes.
- */
- public static Extent totalMemory() {
- return HeapGrowthManager.getCurrentHeapSize();
- }
-
- /* Instance methods */
-
- /**
- * Return the total amount of memory managed to the memory
- * management system, in pages.
- *
- * @return The total amount of memory managed to the memory
- * management system, in pages.
- */
- public final int getTotalPages() {
- return totalMemory().toWord().rshl(LOG_BYTES_IN_PAGE).toInt();
- }
-
- /**
- * Return the number of pages available for allocation.
- *
- * @return The number of pages available for allocation.
- */
- public int getPagesAvail() {
- return getTotalPages() - getPagesReserved();
- }
-
- /**
- * Return the number of pages reserved for use given the pending
- * allocation. Sub-classes must override the getCopyReserve method,
- * as the arithmetic here is fixed.
- *
- * @return The number of pages reserved given the pending
- * allocation, including space reserved for copying.
- */
- public final int getPagesReserved() {
- return getPagesUsed() + getCollectionReserve();
- }
-
- /**
- * Return the number of pages reserved for collection.
- * In most cases this is a copy reserve, all subclasses that
- * manage a copying space must add the copying contribution.
- *
- * @return The number of pages reserved given the pending
- * allocation, including space reserved for collection.
- */
- public int getCollectionReserve() {
- return 0;
- }
-
- /**
- * Return the number of pages reserved for use given the pending
- * allocation.
- *
- * @return The number of pages reserved given the pending
- * allocation, excluding space reserved for copying.
- */
- public int getPagesUsed() {
- return loSpace.reservedPages() +
- immortalSpace.reservedPages() + metaDataSpace.reservedPages() +
- nonMovingSpace.reservedPages();
- }
-
- /**
- * Calculate the number of pages a collection is required to free to satisfy
- * outstanding allocation requests.
- *
- * @return the number of pages a collection is required to free to satisfy
- * outstanding allocation requests.
- */
- public int getPagesRequired() {
- return loSpace.requiredPages() +
- metaDataSpace.requiredPages() + immortalSpace.requiredPages() +
- nonMovingSpace.requiredPages();
- }
-
- /**
- * The minimum number of pages a GC must have available after a collection
- * for us to consider the collection successful.
- */
- public int getHeapFullThreshold() {
- int threshold = (getTotalPages() * HEAP_FULL_PERCENTAGE) / 100;
- if (threshold < HEAP_FULL_MINIMUM) threshold = HEAP_FULL_MINIMUM;
- return threshold;
- }
-
- /**
- * Return the number of metadata pages reserved for use given the pending
- * allocation.
- *
- * @return The number of pages reserved given the pending
- * allocation, excluding space reserved for copying.
- */
- public int getMetaDataPagesUsed() {
- return metaDataSpace.reservedPages();
- }
-
- /**
- * Return the cycle time at which this GC should complete.
- *
- * @return The time cap for this GC (i.e. the time by which it
- * should complete).
- */
- public static long getTimeCap() {
- return timeCap;
- }
-
- /****************************************************************************
- * Internal read/write barriers.
- */
-
- /**
- * Store an object reference
- *
- * @param slot The location of the reference
- * @param value The value to store
- */
- @Inline
- public void storeObjectReference(Address slot, ObjectReference value) {
- slot.store(value);
- }
-
- /**
- * Load an object reference
- *
- * @param slot The location of the reference
- * @return the object reference loaded from slot
- */
- @Inline
- public ObjectReference loadObjectReference(Address slot) {
- return slot.loadObjectReference();
- }
-
- /****************************************************************************
- * Collection.
- */
-
- /**
- * This method is called periodically by the allocation subsystem
- * (by default, each time a page is consumed), and provides the
- * collector with an opportunity to collect.
- *
- * @param spaceFull Space request failed, must recover pages within 'space'.
- * @param space The space that triggered the poll.
- * @return true if a collection is required.
- */
- @LogicallyUninterruptible
- public final boolean poll(boolean spaceFull, Space space) {
- if (isCollectionTriggered()) {
- if (space == metaDataSpace) {
- /* This is not, in general, in a GC safe point. */
- return false;
- }
- /* Someone else initiated a collection, we should join it */
- logPoll(space, "Joining collection");
- VM.collection.joinCollection();
- return true;
- }
-
- if (collectionRequired(spaceFull)) {
- if (space == metaDataSpace) {
- /* In general we must not trigger a GC on metadata allocation since
- * this is not, in general, in a GC safe point. Instead we initiate
- * an asynchronous GC, which will occur at the next safe point.
- */
- logPoll(space, "Asynchronous collection requested");
- setAwaitingAsyncCollection();
- return false;
- }
- logPoll(space, "Triggering collection");
- VM.collection.triggerCollection(Collection.RESOURCE_GC_TRIGGER);
- return true;
- }
-
- if (concurrentCollectionRequired()) {
- logPoll(space, "Triggering collection");
- VM.collection.triggerCollection(Collection.INTERNAL_PHASE_GC_TRIGGER);
- return true;
- }
-
- return false;
- }
-
- /**
- * Check whether an asynchronous collection is pending.<p>
- *
- * This is decoupled from the poll() mechanism because the
- * triggering of asynchronous collections can trigger write
- * barriers, which can trigger an asynchronous collection. Thus, if
- * the triggering were tightly coupled with the request to alloc()
- * within the write buffer code, then inifinite regress could
- * result. There is no race condition in the following code since
- * there is no harm in triggering the collection more than once,
- * thus it is unsynchronized.
- */
- @Inline
- public static void checkForAsyncCollection() {
- if (awaitingAsyncCollection && VM.collection.noThreadsInGC()) {
- awaitingAsyncCollection = false;
- VM.collection.triggerAsyncCollection(Collection.RESOURCE_GC_TRIGGER);
- }
- }
-
- /** Request an async GC */
- protected static void setAwaitingAsyncCollection() {
- awaitingAsyncCollection = true;
- }
-
- /**
- * Log a message from within 'poll'
- * @param space
- * @param message
- */
- private void logPoll(Space space, String message) {
- if (Options.verbose.getValue() >= 3) {
- Log.write(" [POLL] ");
- Log.write(space.getName());
- Log.write(": ");
- Log.writeln(message);
- }
- }
-
- /**
- * This method controls the triggering of a GC. It is called periodically
- * during allocation. Returns true to trigger a collection.
- *
- * @param spaceFull Space request failed, must recover pages within 'space'.
- * @return True if a collection is requested by the plan.
- */
- protected boolean collectionRequired(boolean spaceFull) {
- boolean stressForceGC = stressTestGCRequired();
- boolean heapFull = getPagesReserved() > getTotalPages();
-
- return spaceFull || stressForceGC || heapFull;
- }
-
- /**
- * This method controls the triggering of an atomic phase of a concurrent
- * collection. It is called periodically during allocation.
- *
- * @return True if a collection is requested by the plan.
- */
- protected boolean concurrentCollectionRequired() {
- return false;
- }
-
- /**
- * Start GCspy server.
- *
- * @param port The port to listen on,
- * @param wait Should we wait for a client to connect?
- */
- @Interruptible
- public void startGCspyServer(int port, boolean wait) {
- VM.assertions.fail("startGCspyServer called on non GCspy plan");
- }
-
- /**
- * Can this object ever move. Used by the VM to make decisions about
- * whether it needs to copy IO buffers etc.
- *
- * @param object The object in question
- * @return True if it is not possible that the object will ever move.
- */
- public boolean willNeverMove(ObjectReference object) {
- if (!VM.activePlan.constraints().movesObjects())
- return true;
- if (Space.isInSpace(LOS, object))
- return true;
- if (Space.isInSpace(IMMORTAL, object))
- return true;
- if (Space.isInSpace(VM_SPACE, object))
- return true;
- if (Space.isInSpace(NON_MOVING, object))
- return true;
- if (USE_CODE_SPACE && Space.isInSpace(SMALL_CODE, object))
- return true;
- if (USE_CODE_SPACE && Space.isInSpace(LARGE_CODE, object))
- return true;
- /*
- * Default to false- this preserves correctness over efficiency.
- * Individual plans should override for non-moving spaces they define.
- */
- return false;
- }
-
- /****************************************************************************
- * Specialized Methods
- */
-
- /**
- * Register specialized methods.
- */
- @Interruptible
- protected void registerSpecializedMethods() {
- }
-
- /**
- * Get the specialized scan with the given id.
- */
- public final Class<?> getSpecializedScanClass(int id) {
- return TransitiveClosure.getSpecializedScanClass(id);
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/plan/PlanConstraints.java b/vmkit/mmtk/java/src/org/mmtk/plan/PlanConstraints.java
deleted file mode 100644
index 4d5f202..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/plan/PlanConstraints.java
+++ /dev/null
@@ -1,196 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.plan;
-
-import org.mmtk.policy.SegregatedFreeListSpace;
-import org.vmmagic.pragma.*;
-
-/**
- * This class and its subclasses communicate to the host VM/Runtime
- * any features of the selected plan that it needs to know. This is
- * separate from the main Plan/PlanLocal class in order to bypass any
- * issues with ordering of static initialization.
- */
-@Uninterruptible public abstract class PlanConstraints {
- /** @return True if this Plan requires read barriers on java.lang.reference types. */
- public boolean needsJavaLangReferenceReadBarrier() { return false; }
-
- /** @return True if this Plan requires write barriers on booleans. */
- public boolean needsBooleanWriteBarrier() { return false; }
-
- /** @return True if this Plan requires read barriers on booleans. */
- public boolean needsBooleanReadBarrier() { return false; }
-
- /** @return True if this Plan can perform bulk boolean arraycopy barriers. */
- public boolean booleanBulkCopySupported() { return false; }
-
- /** @return True if this Plan requires write barriers on bytes. */
- public boolean needsByteWriteBarrier() { return false; }
-
- /** @return True if this Plan requires read barriers on bytes. */
- public boolean needsByteReadBarrier() { return false; }
-
- /** @return True if this Plan can perform bulk byte arraycopy barriers. */
- public boolean byteBulkCopySupported() { return false; }
-
- /** @return True if this Plan requires write barriers on chars. */
- public boolean needsCharWriteBarrier() { return false; }
-
- /** @return True if this Plan requires read barriers on chars. */
- public boolean needsCharReadBarrier() { return false; }
-
- /** @return True if this Plan can perform bulk char arraycopy barriers. */
- public boolean charBulkCopySupported() { return false; }
-
- /** @return True if this Plan requires write barriers on shorts. */
- public boolean needsShortWriteBarrier() { return false; }
-
- /** @return True if this Plan requires read barriers on shorts. */
- public boolean needsShortReadBarrier() { return false; }
-
- /** @return True if this Plan can perform bulk short arraycopy barriers. */
- public boolean shortBulkCopySupported() { return false; }
-
- /** @return True if this Plan requires write barriers on ints. */
- public boolean needsIntWriteBarrier() { return false; }
-
- /** @return True if this Plan requires read barriers on ints. */
- public boolean needsIntReadBarrier() { return false; }
-
- /** @return True if this Plan can perform bulk int arraycopy barriers. */
- public boolean intBulkCopySupported() { return false; }
-
- /** @return True if this Plan requires write barriers on longs. */
- public boolean needsLongWriteBarrier() { return false; }
-
- /** @return True if this Plan requires read barriers on longs. */
- public boolean needsLongReadBarrier() { return false; }
-
- /** @return True if this Plan can perform bulk long arraycopy barriers. */
- public boolean longBulkCopySupported() { return false; }
-
- /** @return True if this Plan requires write barriers on floats. */
- public boolean needsFloatWriteBarrier() { return false; }
-
- /** @return True if this Plan requires read barriers on floats. */
- public boolean needsFloatReadBarrier() { return false; }
-
- /** @return True if this Plan can perform bulk float arraycopy barriers. */
- public boolean floatBulkCopySupported() { return false; }
-
- /** @return True if this Plan requires write barriers on doubles. */
- public boolean needsDoubleWriteBarrier() { return false; }
-
- /** @return True if this Plan requires read barriers on doubles. */
- public boolean needsDoubleReadBarrier() { return false; }
-
- /** @return True if this Plan can perform bulk double arraycopy barriers. */
- public boolean doubleBulkCopySupported() { return false; }
-
- /** @return True if this Plan requires write barriers on Words. */
- public boolean needsWordWriteBarrier() { return false; }
-
- /** @return True if this Plan requires read barriers on Words. */
- public boolean needsWordReadBarrier() { return false; }
-
- /** @return True if this Plan can perform bulk Word arraycopy barriers. */
- public boolean wordBulkCopySupported() { return false; }
-
- /** @return True if this Plan requires write barriers on Address's. */
- public boolean needsAddressWriteBarrier() { return false; }
-
- /** @return True if this Plan requires read barriers on Address's. */
- public boolean needsAddressReadBarrier() { return false; }
-
- /** @return True if this Plan can perform bulk Address arraycopy barriers. */
- public boolean addressBulkCopySupported() { return false; }
-
- /** @return True if this Plan requires write barriers on Extents. */
- public boolean needsExtentWriteBarrier() { return false; }
-
- /** @return True if this Plan requires read barriers on Extents. */
- public boolean needsExtentReadBarrier() { return false; }
-
- /** @return True if this Plan can perform bulk Extent arraycopy barriers. */
- public boolean extentBulkCopySupported() { return false; }
-
- /** @return True if this Plan requires write barriers on Offsets. */
- public boolean needsOffsetWriteBarrier() { return false; }
-
- /** @return True if this Plan requires read barriers on Offsets. */
- public boolean needsOffsetReadBarrier() { return false; }
-
- /** @return True if this Plan can perform bulk Offset arraycopy barriers. */
- public boolean offsetBulkCopySupported() { return false; }
-
- /** @return True if this Plan requires write barriers on object references. */
- public boolean needsObjectReferenceWriteBarrier() { return false; }
-
- /** @return True if this Plan requires read barriers on object references. */
- public boolean needsObjectReferenceReadBarrier() { return false; }
-
- /** @return True if this Plan requires non-heap write barriers on object references. */
- public boolean needsObjectReferenceNonHeapWriteBarrier() { return false;}
-
- /** @return True if this Plan requires non-heap read barriers on object references. */
- public boolean needsObjectReferenceNonHeapReadBarrier() { return false; }
-
- /** @return True if this Plan can perform bulk object arraycopy barriers. */
- public boolean objectReferenceBulkCopySupported() { return false; }
-
- /** @return True if this Plan requires linear scanning. */
- public boolean needsLinearScan() { return org.mmtk.utility.Constants.SUPPORT_CARD_SCANNING;}
-
- /** @return True if this Plan does not support parallel collection. */
- public boolean noParallelGC() { return false;}
-
- /** @return True if this Plan moves objects. */
- public boolean movesObjects() { return false;}
-
- /** @return Size (in bytes) beyond which new regular objects must be allocated to the LOS */
- public int maxNonLOSDefaultAllocBytes() { return org.mmtk.utility.Constants.MAX_INT;}
-
- /** @return Size (in bytes) beyond which new non-moving objects must be allocated to the LOS */
- public int maxNonLOSNonMovingAllocBytes() { return SegregatedFreeListSpace.MAX_FREELIST_OBJECT_BYTES;}
-
- /** @return Size (in bytes) beyond which copied objects must be copied to the LOS */
- public int maxNonLOSCopyBytes() { return org.mmtk.utility.Constants.MAX_INT;}
-
- /** @return True if this object forwards objects <i>after</i>
- * determining global object liveness (e.g. many compacting collectors). */
- public boolean needsForwardAfterLiveness() { return false;}
-
- /** @return Is this plan generational in nature. */
- public boolean generational() { return false;}
-
- /** @return The number of header bits that are required. */
- public abstract int gcHeaderBits();
-
- /** @return The number of header words that are required. */
- public abstract int gcHeaderWords();
-
- /** @return True if this plan contains GCspy. */
- public boolean withGCspy() { return false; }
-
- /** @return True if this plan contains GCTrace. */
- public boolean generateGCTrace() { return false; }
-
- /** @return The specialized scan methods required */
- public int numSpecializedScans() { return 0; }
-
- /** @return True if this plan requires concurrent worker threads */
- public boolean needsConcurrentWorkers() { return false; }
-
- /** @return True if this Plan requires a header bit for object logging */
- public boolean needsLogBitInHeader() { return false; }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/plan/Simple.java b/vmkit/mmtk/java/src/org/mmtk/plan/Simple.java
deleted file mode 100644
index e62421e..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/plan/Simple.java
+++ /dev/null
@@ -1,286 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.plan;
-
-import org.mmtk.policy.Space;
-import org.mmtk.utility.Constants;
-import org.mmtk.utility.Log;
-import org.mmtk.utility.options.*;
-import org.mmtk.utility.statistics.Timer;
-import org.mmtk.vm.VM;
-
-import org.vmmagic.pragma.*;
-
-/**
- * This abstract class implements the core functionality for
- * simple collectors.<p>
- *
- * This class defines the collection phases, and provides base
- * level implementations of them. Subclasses should provide
- * implementations for the spaces that they introduce, and
- * delegate up the class hierarchy.<p>
- *
- * For details of the split between global and thread-local operations
- * @see org.mmtk.plan.Plan
- */
-@Uninterruptible
-public abstract class Simple extends Plan implements Constants {
- /****************************************************************************
- * Constants
- */
-
- /* Shared Timers */
- private static final Timer refTypeTime = new Timer("refType", false, true);
- private static final Timer scanTime = new Timer("scan", false, true);
- private static final Timer finalizeTime = new Timer("finalize", false, true);
-
- /* Phases */
- public static final short SET_COLLECTION_KIND = Phase.createSimple("set-collection-kind", null);
- public static final short INITIATE = Phase.createSimple("initiate", null);
- public static final short PREPARE = Phase.createSimple("prepare");
- public static final short PRECOPY = Phase.createSimple("precopy");
- public static final short PREPARE_STACKS = Phase.createSimple("prepare-stacks", null);
- public static final short STACK_ROOTS = Phase.createSimple("stacks");
- public static final short ROOTS = Phase.createSimple("root");
- public static final short CLOSURE = Phase.createSimple("closure", scanTime);
- public static final short SOFT_REFS = Phase.createSimple("soft-ref", refTypeTime);
- public static final short WEAK_REFS = Phase.createSimple("weak-ref", refTypeTime);
- public static final short FINALIZABLE = Phase.createSimple("finalize", finalizeTime);
- public static final short WEAK_TRACK_REFS = Phase.createSimple("weak-track-ref", refTypeTime);
- public static final short PHANTOM_REFS = Phase.createSimple("phantom-ref", refTypeTime);
- public static final short FORWARD = Phase.createSimple("forward");
- public static final short FORWARD_REFS = Phase.createSimple("forward-ref", refTypeTime);
- public static final short FORWARD_FINALIZABLE = Phase.createSimple("forward-finalize", finalizeTime);
- public static final short RELEASE = Phase.createSimple("release");
- public static final short COMPLETE = Phase.createSimple("complete", null);
-
- /* Sanity placeholder */
- public static final short PRE_SANITY_PLACEHOLDER = Phase.createSimple("pre-sanity-placeholder", null);
- public static final short POST_SANITY_PLACEHOLDER = Phase.createSimple("post-sanity-placeholder", null);
-
- /* Sanity phases */
- public static final short SANITY_SET_PREGC = Phase.createSimple("sanity-setpre", null);
- public static final short SANITY_SET_POSTGC = Phase.createSimple("sanity-setpost", null);
- public static final short SANITY_PREPARE = Phase.createSimple("sanity-prepare", null);
- public static final short SANITY_ROOTS = Phase.createSimple("sanity-roots", null);
- public static final short SANITY_COPY_ROOTS = Phase.createSimple("sanity-copy-roots", null);
- public static final short SANITY_BUILD_TABLE = Phase.createSimple("sanity-build-table", null);
- public static final short SANITY_CHECK_TABLE = Phase.createSimple("sanity-check-table", null);
- public static final short SANITY_RELEASE = Phase.createSimple("sanity-release", null);
-
- // CHECKSTYLE:OFF
-
- /** Ensure stacks are ready to be scanned */
- protected static final short prepareStacks = Phase.createComplex("prepare-stacks", null,
- Phase.scheduleCollector (PREPARE_STACKS),
- Phase.scheduleMutator (PREPARE_STACKS),
- Phase.scheduleGlobal (PREPARE_STACKS));
-
- /** Trace and set up a sanity table */
- protected static final short sanityBuildPhase = Phase.createComplex("sanity-build", null,
- Phase.scheduleGlobal (SANITY_PREPARE),
- Phase.scheduleCollector (SANITY_PREPARE),
- Phase.scheduleComplex (prepareStacks),
- Phase.scheduleCollector (SANITY_ROOTS),
- Phase.scheduleGlobal (SANITY_ROOTS),
- Phase.scheduleCollector (SANITY_COPY_ROOTS),
- Phase.scheduleGlobal (SANITY_BUILD_TABLE));
-
- /** Validate a sanity table */
- protected static final short sanityCheckPhase = Phase.createComplex("sanity-check", null,
- Phase.scheduleGlobal (SANITY_CHECK_TABLE),
- Phase.scheduleCollector (SANITY_RELEASE),
- Phase.scheduleGlobal (SANITY_RELEASE));
-
- /** Start the collection, including preparation for any collected spaces. */
- protected static final short initPhase = Phase.createComplex("init",
- Phase.scheduleGlobal (SET_COLLECTION_KIND),
- Phase.scheduleGlobal (INITIATE),
- Phase.schedulePlaceholder(PRE_SANITY_PLACEHOLDER));
-
- /**
- * Perform the initial determination of liveness from the roots.
- */
- protected static final short rootClosurePhase = Phase.createComplex("initial-closure", null,
- Phase.scheduleMutator (PREPARE),
- Phase.scheduleGlobal (PREPARE),
- Phase.scheduleCollector (PREPARE),
- Phase.scheduleComplex (prepareStacks),
- Phase.scheduleCollector (PRECOPY),
- Phase.scheduleCollector (STACK_ROOTS),
- Phase.scheduleCollector (ROOTS),
- Phase.scheduleGlobal (ROOTS),
- Phase.scheduleGlobal (CLOSURE),
- Phase.scheduleCollector (CLOSURE));
-
- /**
- * Complete closure including reference types and finalizable objects.
- */
- protected static final short refTypeClosurePhase = Phase.createComplex("refType-closure", null,
- Phase.scheduleCollector (SOFT_REFS),
- Phase.scheduleGlobal (CLOSURE),
- Phase.scheduleCollector (CLOSURE),
- Phase.scheduleCollector (WEAK_REFS),
- Phase.scheduleCollector (FINALIZABLE),
- Phase.scheduleGlobal (CLOSURE),
- Phase.scheduleCollector (CLOSURE),
- Phase.schedulePlaceholder(WEAK_TRACK_REFS),
- Phase.scheduleCollector (PHANTOM_REFS));
-
- /**
- * Ensure that all references in the system are correct.
- */
- protected static final short forwardPhase = Phase.createComplex("forward-all", null,
- /* Finish up */
- Phase.schedulePlaceholder(FORWARD),
- Phase.scheduleCollector (FORWARD_REFS),
- Phase.scheduleCollector (FORWARD_FINALIZABLE));
-
- /**
- * Complete closure including reference types and finalizable objects.
- */
- protected static final short completeClosurePhase = Phase.createComplex("release", null,
- Phase.scheduleMutator (RELEASE),
- Phase.scheduleCollector (RELEASE),
- Phase.scheduleGlobal (RELEASE));
-
-
- /**
- * The collection scheme - this is a small tree of complex phases.
- */
- protected static final short finishPhase = Phase.createComplex("finish",
- Phase.schedulePlaceholder(POST_SANITY_PLACEHOLDER),
- Phase.scheduleCollector (COMPLETE),
- Phase.scheduleGlobal (COMPLETE));
-
- /**
- * This is the phase that is executed to perform a collection.
- */
- public short collection = Phase.createComplex("collection", null,
- Phase.scheduleComplex(initPhase),
- Phase.scheduleComplex(rootClosurePhase),
- Phase.scheduleComplex(refTypeClosurePhase),
- Phase.scheduleComplex(forwardPhase),
- Phase.scheduleComplex(completeClosurePhase),
- Phase.scheduleComplex(finishPhase));
-
- // CHECKSTYLE:ON
-
- /**
- * The current collection attempt.
- */
- protected int collectionAttempt;
-
- /****************************************************************************
- * Collection
- */
-
- /**
- * Perform a (global) collection phase.
- *
- * @param phaseId The unique of the phase to perform.
- */
- @Inline
- public void collectionPhase(short phaseId) {
- if (phaseId == SET_COLLECTION_KIND) {
- requiredAtStart = getPagesRequired();
- collectionAttempt = VM.collection.maximumCollectionAttempt();
- emergencyCollection = lastCollectionWasExhaustive() && collectionAttempt > 1;
- if (collectionAttempt > MAX_COLLECTION_ATTEMPTS) {
- VM.assertions.fail("Too many collection attempts. Suspect plan is not setting FullHeap flag");
- }
- if (emergencyCollection) {
- if (Options.verbose.getValue() >= 1) Log.write("[Emergency]");
- forceFullHeapCollection();
- }
- return;
- }
-
- if (phaseId == INITIATE) {
- setGCStatus(GC_PREPARE);
- return;
- }
-
- if (phaseId == PREPARE_STACKS) {
- stacksPrepared = true;
- return;
- }
-
- if (phaseId == PREPARE) {
- loSpace.prepare(true);
- nonMovingSpace.prepare(true);
- if (USE_CODE_SPACE) {
- smallCodeSpace.prepare(true);
- largeCodeSpace.prepare(true);
- }
- immortalSpace.prepare();
- VM.memory.globalPrepareVMSpace();
- return;
- }
-
- if (phaseId == ROOTS) {
- VM.scanning.resetThreadCounter();
- setGCStatus(GC_PROPER);
- return;
- }
-
- if (phaseId == RELEASE) {
- loSpace.release(true);
- nonMovingSpace.release();
- if (USE_CODE_SPACE) {
- smallCodeSpace.release();
- largeCodeSpace.release(true);
- }
- immortalSpace.release();
- VM.memory.globalReleaseVMSpace();
- return;
- }
-
- if (phaseId == COMPLETE) {
- setGCStatus(NOT_IN_GC);
- Space.clearAllAllocationFailed();
- awaitingAsyncCollection = false;
- return;
- }
-
- if (Options.sanityCheck.getValue() && sanityChecker.collectionPhase(phaseId)) {
- return;
- }
-
- Log.write("Global phase "); Log.write(Phase.getName(phaseId));
- Log.writeln(" not handled.");
- VM.assertions.fail("Global phase not handled!");
- }
-
- /**
- * Replace a scheduled phase. Used for example to replace a placeholder.
- *
- * @param oldScheduledPhase The scheduled phase to replace.
- * @param newScheduledPhase The new scheduled phase.
- */
- public void replacePhase(int oldScheduledPhase, int newScheduledPhase) {
- ComplexPhase cp = (ComplexPhase)Phase.getPhase(collection);
- cp.replacePhase(oldScheduledPhase, newScheduledPhase);
- }
-
- /**
- * Replace a placeholder phase.
- *
- * @param placeHolderPhase The placeholder phase
- * @param newScheduledPhase The new scheduled phase.
- */
- public void replacePlaceholderPhase(short placeHolderPhase, int newScheduledPhase) {
- ComplexPhase cp = (ComplexPhase)Phase.getPhase(collection);
- cp.replacePhase(Phase.schedulePlaceholder(placeHolderPhase), newScheduledPhase);
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/plan/SimpleCollector.java b/vmkit/mmtk/java/src/org/mmtk/plan/SimpleCollector.java
deleted file mode 100644
index 2348df2..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/plan/SimpleCollector.java
+++ /dev/null
@@ -1,174 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.plan;
-
-import org.mmtk.utility.Log;
-import org.mmtk.utility.options.Options;
-
-import org.mmtk.vm.VM;
-
-import org.vmmagic.pragma.*;
-
-/**
- * This class (and its sub-classes) implement <i>per-collector thread</i>
- * behavior and state.
- *
- * MMTk assumes that the VM instantiates instances of CollectorContext
- * in thread local storage (TLS) for each thread participating in
- * collection. Accesses to this state are therefore assumed to be
- * low-cost during mutator time.<p>
- *
- * @see CollectorContext
- */
-@Uninterruptible
-public abstract class SimpleCollector extends CollectorContext {
-
- /****************************************************************************
- * Instance fields
- */
-
- /****************************************************************************
- *
- * Collection
- */
-
- /**
- * Perform a per-collector collection phase.
- *
- * @param phaseId The unique phase identifier
- * @param primary Should this thread be used to execute any single-threaded
- * local operations?
- */
- @Inline
- public void collectionPhase(short phaseId, boolean primary) {
- if (phaseId == Simple.PREPARE_STACKS) {
- if (!Plan.stacksPrepared()) {
- VM.collection.prepareCollector(this);
- }
- return;
- }
-
- if (phaseId == Simple.PREPARE) {
- // Nothing to do
- return;
- }
-
- if (phaseId == Simple.PRECOPY) {
- if (VM.activePlan.constraints().movesObjects()) {
- VM.scanning.preCopyGCInstances(getCurrentTrace());
- }
- return;
- }
-
- if (phaseId == Simple.STACK_ROOTS) {
- VM.scanning.computeThreadRoots(getCurrentTrace());
- return;
- }
-
- if (phaseId == Simple.ROOTS) {
- VM.scanning.computeGlobalRoots(getCurrentTrace());
- VM.scanning.computeStaticRoots(getCurrentTrace());
- if (Plan.SCAN_BOOT_IMAGE) {
- VM.scanning.computeBootImageRoots(getCurrentTrace());
- }
- return;
- }
-
- if (phaseId == Simple.SOFT_REFS) {
- if (primary) {
- if (Options.noReferenceTypes.getValue())
- VM.softReferences.clear();
- else
- VM.softReferences.scan(getCurrentTrace(),global().isCurrentGCNursery());
- }
- return;
- }
-
- if (phaseId == Simple.WEAK_REFS) {
- if (primary) {
- if (Options.noReferenceTypes.getValue())
- VM.weakReferences.clear();
- else
- VM.weakReferences.scan(getCurrentTrace(),global().isCurrentGCNursery());
- }
- return;
- }
-
- if (phaseId == Simple.FINALIZABLE) {
- if (primary) {
- if (Options.noFinalizer.getValue())
- VM.finalizableProcessor.clear();
- else
- VM.finalizableProcessor.scan(getCurrentTrace(),global().isCurrentGCNursery());
- }
- return;
- }
-
- if (phaseId == Simple.PHANTOM_REFS) {
- if (primary) {
- if (Options.noReferenceTypes.getValue())
- VM.phantomReferences.clear();
- else
- VM.phantomReferences.scan(getCurrentTrace(),global().isCurrentGCNursery());
- }
- return;
- }
-
- if (phaseId == Simple.FORWARD_REFS) {
- if (primary && !Options.noReferenceTypes.getValue() &&
- VM.activePlan.constraints().needsForwardAfterLiveness()) {
- VM.softReferences.forward(getCurrentTrace(),global().isCurrentGCNursery());
- VM.weakReferences.forward(getCurrentTrace(),global().isCurrentGCNursery());
- VM.phantomReferences.forward(getCurrentTrace(),global().isCurrentGCNursery());
- }
- return;
- }
-
- if (phaseId == Simple.FORWARD_FINALIZABLE) {
- if (primary && !Options.noFinalizer.getValue() &&
- VM.activePlan.constraints().needsForwardAfterLiveness()) {
- VM.finalizableProcessor.forward(getCurrentTrace(),global().isCurrentGCNursery());
- }
- return;
- }
-
- if (phaseId == Simple.COMPLETE) {
- // Nothing to do
- return;
- }
-
- if (phaseId == Simple.RELEASE) {
- // Nothing to do
- return;
- }
-
- if (Options.sanityCheck.getValue() && sanityLocal.collectionPhase(phaseId, primary)) {
- return;
- }
-
- Log.write("Per-collector phase "); Log.write(Phase.getName(phaseId));
- Log.writeln(" not handled.");
- VM.assertions.fail("Per-collector phase not handled!");
- }
-
- /****************************************************************************
- *
- * Miscellaneous.
- */
-
- /** @return The active global plan as a <code>Simple</code> instance. */
- @Inline
- private static Simple global() {
- return (Simple) VM.activePlan.global();
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/plan/SimpleConstraints.java b/vmkit/mmtk/java/src/org/mmtk/plan/SimpleConstraints.java
deleted file mode 100644
index a09619f..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/plan/SimpleConstraints.java
+++ /dev/null
@@ -1,22 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.plan;
-
-import org.vmmagic.pragma.*;
-
-/**
- * Constraints specific to simple collectors.
- */
-@Uninterruptible
-public abstract class SimpleConstraints extends PlanConstraints {
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/plan/SimpleMutator.java b/vmkit/mmtk/java/src/org/mmtk/plan/SimpleMutator.java
deleted file mode 100644
index 88156fc..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/plan/SimpleMutator.java
+++ /dev/null
@@ -1,79 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.plan;
-
-import org.mmtk.utility.Log;
-import org.mmtk.vm.VM;
-
-import org.vmmagic.pragma.*;
-
-/**
- * This class (and its sub-classes) implement <i>per-mutator thread</i>
- * behavior and state.
- *
- * MMTk assumes that the VM instantiates instances of MutatorContext
- * in thread local storage (TLS) for each application thread. Accesses
- * to this state are therefore assumed to be low-cost during mutator
- * time.<p>
- *
- * @see MutatorContext
- */
-@Uninterruptible
-public abstract class SimpleMutator extends MutatorContext {
-
- /****************************************************************************
- *
- * Collection.
- */
-
- /**
- * Perform a per-mutator collection phase. This is executed by
- * one collector thread on behalf of a mutator thread.
- *
- * @param phaseId The unique phase identifier
- * @param primary Should this thread be used to execute any single-threaded
- * local operations?
- */
- @Inline
- public void collectionPhase(short phaseId, boolean primary) {
- if (phaseId == Simple.PREPARE_STACKS) {
- if (!Plan.stacksPrepared()) {
- VM.collection.prepareMutator(this);
- }
- flushRememberedSets();
- return;
- }
-
- if (phaseId == Simple.PREPARE) {
- los.prepare(true);
- lgcode.prepare(true);
- smcode.prepare();
- nonmove.prepare();
- VM.memory.collectorPrepareVMSpace();
- return;
- }
-
- if (phaseId == Simple.RELEASE) {
- los.release(true);
- lgcode.release(true);
- smcode.release();
- nonmove.release();
- VM.memory.collectorReleaseVMSpace();
- return;
- }
-
- Log.write("Per-mutator phase \""); Phase.getPhase(phaseId).logPhase();
- Log.writeln("\" not handled.");
- VM.assertions.fail("Per-mutator phase not handled!");
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/plan/SimplePhase.java b/vmkit/mmtk/java/src/org/mmtk/plan/SimplePhase.java
deleted file mode 100644
index aba8994..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/plan/SimplePhase.java
+++ /dev/null
@@ -1,60 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.plan;
-
-import org.mmtk.utility.Constants;
-import org.mmtk.utility.statistics.Timer;
-import org.mmtk.utility.Log;
-
-import org.vmmagic.pragma.*;
-
-/**
- * Phases of a garbage collection.
- *
- */
-@Uninterruptible
-public final class SimplePhase extends Phase
- implements Constants {
- /****************************************************************************
- * Instance fields
- */
-
- /**
- * Construct a phase given just a name and a global/local ordering
- * scheme.
- *
- * @param name The name of the phase
- */
- protected SimplePhase(String name) {
- super(name);
- }
-
- /**
- * Construct a phase, re-using a specified timer.
- *
- * @param name Display name of the phase
- * @param timer Timer for this phase to contribute to
- */
- protected SimplePhase(String name, Timer timer) {
- super(name, timer);
- }
-
- /**
- * Display a phase for debugging purposes.
- */
- protected void logPhase() {
- Log.write("SimplePhase(");
- Log.write(name);
- Log.write(")");
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/plan/StopTheWorld.java b/vmkit/mmtk/java/src/org/mmtk/plan/StopTheWorld.java
deleted file mode 100644
index 989744e..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/plan/StopTheWorld.java
+++ /dev/null
@@ -1,69 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.plan;
-
-import org.mmtk.utility.Log;
-import org.mmtk.utility.options.Options;
-import org.vmmagic.pragma.*;
-
-/**
- * This abstract class implements the core functionality for
- * stop-the-world collectors. Stop-the-world collectors should
- * inherit from this class.<p>
- *
- * This class defines the collection phases, and provides base
- * level implementations of them. Subclasses should provide
- * implementations for the spaces that they introduce, and
- * delegate up the class hierarchy.<p>
- *
- * For details of the split between global and thread-local operations
- * @see org.mmtk.plan.Plan
- */
-@Uninterruptible
-public abstract class StopTheWorld extends Simple {
-
- // CHECKSTYLE:OFF
-
- /** Build and validate a sanity table */
- protected static final short preSanityPhase = Phase.createComplex("pre-sanity", null,
- Phase.scheduleGlobal (SANITY_SET_PREGC),
- Phase.scheduleComplex (sanityBuildPhase),
- Phase.scheduleComplex (sanityCheckPhase));
-
- /** Build and validate a sanity table */
- protected static final short postSanityPhase = Phase.createComplex("post-sanity", null,
- Phase.scheduleGlobal (SANITY_SET_POSTGC),
- Phase.scheduleComplex (sanityBuildPhase),
- Phase.scheduleComplex (sanityCheckPhase));
-
- // CHECKSTYLE:ON
-
- /****************************************************************************
- * Collection
- */
-
- /**
- * The boot method is called early in the boot process before any
- * allocation.
- */
- @Interruptible
- public void postBoot() {
- super.postBoot();
-
- if (Options.sanityCheck.getValue()) {
- Log.writeln("Collection sanity checking enabled.");
- replacePhase(Phase.schedulePlaceholder(PRE_SANITY_PLACEHOLDER), Phase.scheduleComplex(preSanityPhase));
- replacePhase(Phase.schedulePlaceholder(POST_SANITY_PLACEHOLDER), Phase.scheduleComplex(postSanityPhase));
- }
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/plan/StopTheWorldCollector.java b/vmkit/mmtk/java/src/org/mmtk/plan/StopTheWorldCollector.java
deleted file mode 100644
index 7fedc0a..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/plan/StopTheWorldCollector.java
+++ /dev/null
@@ -1,66 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.plan;
-
-import org.mmtk.vm.VM;
-import org.vmmagic.pragma.*;
-
-/**
- * This class (and its sub-classes) implement <i>per-collector thread</i>
- * behavior and state.
- *
- * MMTk assumes that the VM instantiates instances of CollectorContext
- * in thread local storage (TLS) for each thread participating in
- * collection. Accesses to this state are therefore assumed to be
- * low-cost during mutator time.<p>
- *
- * @see CollectorContext
- */
-@Uninterruptible
-public abstract class StopTheWorldCollector extends SimpleCollector {
-
- /****************************************************************************
- *
- * Collection.
- */
-
- /** Perform garbage collection */
- public void collect() {
- Phase.beginNewPhaseStack(Phase.scheduleComplex(global().collection));
- }
-
- /** Perform some concurrent garbage collection */
- public final void concurrentCollect() {
- VM.assertions.fail("concurrentCollect called on StopTheWorld collector");
- }
-
- /**
- * Perform some concurrent collection work.
- *
- * @param phaseId The unique phase identifier
- */
- public void concurrentCollectionPhase(short phaseId) {
- VM.assertions.fail("concurrentCollectionPhase triggered on StopTheWorld collector");
- }
-
- /****************************************************************************
- *
- * Miscellaneous.
- */
-
- /** @return The active global plan as a <code>StopTheWorld</code> instance. */
- @Inline
- private static StopTheWorld global() {
- return (StopTheWorld) VM.activePlan.global();
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/plan/StopTheWorldConstraints.java b/vmkit/mmtk/java/src/org/mmtk/plan/StopTheWorldConstraints.java
deleted file mode 100644
index b21aef3..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/plan/StopTheWorldConstraints.java
+++ /dev/null
@@ -1,22 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.plan;
-
-import org.vmmagic.pragma.*;
-
-/**
- * Constraints specific to Stop-the-world collectors.
- */
-@Uninterruptible
-public abstract class StopTheWorldConstraints extends SimpleConstraints {
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/plan/StopTheWorldMutator.java b/vmkit/mmtk/java/src/org/mmtk/plan/StopTheWorldMutator.java
deleted file mode 100644
index b60da12..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/plan/StopTheWorldMutator.java
+++ /dev/null
@@ -1,30 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.plan;
-
-import org.vmmagic.pragma.*;
-
-/**
- * This class (and its sub-classes) implement <i>per-mutator thread</i>
- * behavior and state.
- *
- * MMTk assumes that the VM instantiates instances of MutatorContext
- * in thread local storage (TLS) for each application thread. Accesses
- * to this state are therefore assumed to be low-cost during mutator
- * time.<p>
- *
- * @see MutatorContext
- */
-@Uninterruptible
-public abstract class StopTheWorldMutator extends SimpleMutator {
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/plan/Trace.java b/vmkit/mmtk/java/src/org/mmtk/plan/Trace.java
deleted file mode 100644
index c73691f..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/plan/Trace.java
+++ /dev/null
@@ -1,72 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.plan;
-
-import org.mmtk.utility.Constants;
-import org.mmtk.utility.deque.SharedDeque;
-import org.mmtk.policy.RawPageSpace;
-
-import org.vmmagic.pragma.*;
-
-/**
- * This abstract class implements the core functionality for a transitive
- * closure over the heap. This class holds the global state, TraceLocal
- * and its super-classes handle per-thread state.
- */
-@Uninterruptible
-public class Trace implements Constants {
-
- // Global pools for load-balancing deques
- final SharedDeque valuePool;
- final SharedDeque rootLocationPool;
-
- /**
- * Constructor
- */
- public Trace(RawPageSpace metaDataSpace) {
- valuePool = new SharedDeque("valuePool",metaDataSpace, 1);
- rootLocationPool = new SharedDeque("rootLocations", metaDataSpace, 1);
- }
-
- /**
- * Prepare for a new collection pass.
- */
- public void prepareNonBlocking() {
- valuePool.prepareNonBlocking();
- rootLocationPool.prepareNonBlocking();
- }
-
- /**
- * Prepare for a new collection pass.
- * All active GC threads take part.
- */
- public void prepare() {
- valuePool.prepare();
- rootLocationPool.prepareNonBlocking();
- }
-
- /**
- * Release resources after completing a collection pass.
- */
- public void release() {
- valuePool.reset();
- rootLocationPool.reset();
- }
-
- /**
- * Is there any work outstanding in this trace. That is are there any pages in the pools.
- */
- public boolean hasWork() {
- return (valuePool.enqueuedPages() + rootLocationPool.enqueuedPages()) > 0;
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/plan/TraceLocal.java b/vmkit/mmtk/java/src/org/mmtk/plan/TraceLocal.java
deleted file mode 100644
index a21c419..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/plan/TraceLocal.java
+++ /dev/null
@@ -1,571 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.plan;
-
-import org.mmtk.policy.Space;
-import org.mmtk.utility.Constants;
-import org.mmtk.utility.Log;
-import org.mmtk.utility.deque.*;
-import org.mmtk.utility.options.Options;
-
-import org.mmtk.vm.VM;
-
-import org.vmmagic.pragma.*;
-import org.vmmagic.unboxed.*;
-
-/**
- * This abstract class and its global counterpart implement the core
- * functionality for a transitive closure over the heap graph. This class
- * specifically implements the unsynchronized thread-local component
- * (ie the 'fast path') of the trace mechanism.<p>
- *
- * @see org.mmtk.plan.Plan
- * @see org.mmtk.plan.Trace
- */
-@Uninterruptible
-public abstract class TraceLocal extends TransitiveClosure implements Constants {
- /****************************************************************************
- *
- * Instance variables
- */
- /* gray object */
- protected final ObjectReferenceDeque values;
- /* delayed root slots */
- protected final AddressDeque rootLocations;
-
- /****************************************************************************
- *
- * Initialization
- */
-
- /**
- * Constructor
- *
- * @param trace The global trace class to use.
- */
- public TraceLocal(Trace trace) {
- this(-1, trace);
- }
-
- /**
- * Constructor
- *
- * @param specializedScan The specialized scan id.
- * @param trace The global trace class to use.
- */
- public TraceLocal(int specializedScan, Trace trace) {
- super(specializedScan);
- values = new ObjectReferenceDeque("value", trace.valuePool);
- rootLocations = new AddressDeque("roots", trace.rootLocationPool);
- }
-
- /****************************************************************************
- *
- * Internally visible Object processing and tracing
- */
-
- /**
- * Trace a reference during GC. This involves determining which
- * collection policy applies and calling the appropriate
- * <code>trace</code> method.
- *
- * @param source The source of the reference.
- * @param slot The location containing the object reference to be
- * traced. The object reference is <i>NOT</i> an interior pointer.
- */
- @Inline
- public final void processEdge(ObjectReference source, Address slot) {
- ObjectReference object = VM.activePlan.global().loadObjectReference(slot);
- ObjectReference newObject = traceObject(object, false);
- VM.activePlan.global().storeObjectReference(slot, newObject);
- }
-
- /**
- * Report a root edge to be processed during GC. As the given reference
- * may theoretically point to an object required during root scanning,
- * the caller has requested processing be delayed.
- *
- * NOTE: delayed roots are assumed to be raw.
- *
- * @param slot The location containing the object reference to be
- * traced. The object reference is <i>NOT</i> an interior pointer.
- */
- @Inline
- public final void reportDelayedRootEdge(Address slot) {
- rootLocations.push(slot);
- }
-
- /**
- * Trace a reference during GC. This involves determining which
- * collection policy applies and calling the appropriate
- * <code>trace</code> method.
- *
- * @param slot The location containing the object reference to be
- * traced. The object reference is <i>NOT</i> an interior pointer.
- * @param untraced True if <code>objLoc</code> is an untraced root.
- */
- @Inline
- public final void processRootEdge(Address slot, boolean untraced) {
- ObjectReference object;
- if (untraced) object = slot.loadObjectReference();
- else object = VM.activePlan.global().loadObjectReference(slot);
- ObjectReference newObject = traceObject(object, true);
- if (untraced) slot.store(newObject);
- else VM.activePlan.global().storeObjectReference(slot, newObject);
- }
-
- /**
- * Trace a reference during GC. This involves determining which
- * collection policy applies and calling the appropriate
- * <code>trace</code> method.
- *
- * @param target The object the interior edge points within.
- * @param slot The location of the interior edge.
- * @param root True if this is a root edge.
- */
- public final void processInteriorEdge(ObjectReference target, Address slot, boolean root) {
- Address interiorRef = slot.loadAddress();
- Offset offset = interiorRef.diff(target.toAddress());
- ObjectReference newTarget = traceObject(target, root);
- if (VM.VERIFY_ASSERTIONS) {
- if (offset.sLT(Offset.zero()) || offset.sGT(Offset.fromIntSignExtend(1<<24))) {
- // There is probably no object this large
- Log.writeln("ERROR: Suspiciously large delta to interior pointer");
- Log.write(" object base = "); Log.writeln(target);
- Log.write(" interior reference = "); Log.writeln(interiorRef);
- Log.write(" delta = "); Log.writeln(offset);
- VM.assertions._assert(false);
- }
- }
- slot.store(newTarget.toAddress().plus(offset));
- }
-
- /**
- * Collectors that move objects <b>must</b> override this method.
- * It performs the deferred scanning of objects which are forwarded
- * during bootstrap of each copying collection. Because of the
- * complexities of the collection bootstrap (such objects are
- * generally themselves gc-critical), the forwarding and scanning of
- * the objects must be dislocated. It is an error for a non-moving
- * collector to call this method.
- *
- * @param object The forwarded object to be scanned
- */
- @Inline
- protected void scanObject(ObjectReference object) {
- if (specializedScan >= 0) {
- VM.scanning.specializedScanObject(specializedScan, this, object);
- } else {
- VM.scanning.scanObject(this, object);
- }
- }
-
-
- /****************************************************************************
- *
- * Externally visible Object processing and tracing
- */
-
- /**
- * Add a gray object
- *
- * @param object The object to be enqueued
- */
- @Inline
- public final void processNode(ObjectReference object) {
- values.push(object);
- }
-
- /**
- * Flush the local buffers of all deques.
- */
- public final void flush() {
- values.flushLocal();
- rootLocations.flushLocal();
- }
-
- /**
- * Is the specified object live?
- *
- * @param object The object.
- * @return True if the object is live.
- */
- @Inline
- public boolean isLive(ObjectReference object) {
- Space space = Space.getSpaceForObject(object);
- if (space == Plan.loSpace)
- return Plan.loSpace.isLive(object);
- else if (space == Plan.nonMovingSpace)
- return Plan.nonMovingSpace.isLive(object);
- else if (Plan.USE_CODE_SPACE && space == Plan.smallCodeSpace)
- return Plan.smallCodeSpace.isLive(object);
- else if (Plan.USE_CODE_SPACE && space == Plan.largeCodeSpace)
- return Plan.largeCodeSpace.isLive(object);
- else if (space == null) {
- if (VM.VERIFY_ASSERTIONS) {
- Log.write("space failure: "); Log.writeln(object);
- }
- }
- return true;
- }
-
- /**
- * Is the specified object reachable? Used for GC Trace
- *
- * @param object The object.
- * @return True if the object is live.
- */
- @Inline
- public boolean isReachable(ObjectReference object) {
- return Space.getSpaceForObject(object).isReachable(object);
- }
-
- /**
- * Is the specified referent of a reference type object live?
- *
- * @param object The object.
- * @return True if the reference object is live.
- */
- @Inline
- public boolean isReferentLive(ObjectReference object) {
- return isLive(object);
- }
-
- /**
- * This method is the core method during the trace of the object graph.
- * The role of this method is to:
- *
- * 1. Ensure the traced object is not collected.
- * 2. If this is the first visit to the object enqueue it to be scanned.
- * 3. Return the forwarded reference to the object.
- *
- * @param object The object to be traced.
- * @return The new reference to the same object instance.
- */
- @Inline
- public ObjectReference traceObject(ObjectReference object) {
- if (Space.isInSpace(Plan.VM_SPACE, object))
- return (Plan.SCAN_BOOT_IMAGE) ? object : Plan.vmSpace.traceObject(this, object);
- if (Space.isInSpace(Plan.IMMORTAL, object))
- return Plan.immortalSpace.traceObject(this, object);
- if (Space.isInSpace(Plan.LOS, object))
- return Plan.loSpace.traceObject(this, object);
- if (Space.isInSpace(Plan.NON_MOVING, object))
- return Plan.nonMovingSpace.traceObject(this, object);
- if (Plan.USE_CODE_SPACE && Space.isInSpace(Plan.SMALL_CODE, object))
- return Plan.smallCodeSpace.traceObject(this, object);
- if (Plan.USE_CODE_SPACE && Space.isInSpace(Plan.LARGE_CODE, object))
- return Plan.largeCodeSpace.traceObject(this, object);
- if (VM.VERIFY_ASSERTIONS) {
- Log.write("Failing object => "); Log.writeln(object);
- Space.printVMMap();
- VM.assertions._assert(false, "No special case for space in traceObject");
- }
- return ObjectReference.nullReference();
- }
-
-
- /**
- * Ensure that this object will not move for the rest of the GC.
- *
- * @param object The object that must not move
- * @return The new object, guaranteed stable for the rest of the GC.
- */
- @Inline
- public ObjectReference precopyObject(ObjectReference object) {
- return traceObject(object);
- }
-
- /**
- * This method traces an object with knowledge of the fact that object
- * is a root or not. In simple collectors the fact it is a root is not
- * important so this is the default implementation given here.
- *
- * @param object The object to be traced.
- * @return The new reference to the same object instance.
- */
- @Inline
- public ObjectReference traceObject(ObjectReference object, boolean root) {
- return traceObject(object);
- }
-
- /**
- * Ensure that the referenced object will not move from this point through
- * to the end of the collection. This can involve forwarding the object
- * if necessary.
- *
- * <i>Non-copying collectors do nothing, copying collectors must
- * override this method in each of their trace classes.</i>
- *
- * @param object The object that must not move during the collection.
- * @return True If the object will not move during collection
- */
- public boolean willNotMoveInCurrentCollection(ObjectReference object) {
- if (!VM.activePlan.constraints().movesObjects())
- return true;
- if (Space.isInSpace(Plan.LOS, object))
- return true;
- if (Space.isInSpace(Plan.IMMORTAL, object))
- return true;
- if (Space.isInSpace(Plan.VM_SPACE, object))
- return true;
- if (Space.isInSpace(Plan.NON_MOVING, object))
- return true;
- if (Plan.USE_CODE_SPACE && Space.isInSpace(Plan.SMALL_CODE, object))
- return true;
- if (Plan.USE_CODE_SPACE && Space.isInSpace(Plan.LARGE_CODE, object))
- return true;
- if (VM.VERIFY_ASSERTIONS)
- VM.assertions._assert(false, "willNotMove not defined properly in subclass");
- return false;
- }
-
- /**
- * If a Finalizable object has moved, return the new location.
- *
- * @param object The object which may have been forwarded.
- * @return The new location of <code>object</code>.
- */
- public ObjectReference getForwardedFinalizable(ObjectReference object) {
- return getForwardedReference(object);
- }
-
- /**
- * If the reference object (from a Reference Type) has object has moved,
- * return the new location.
- *
- * @param object The object which may have been forwarded.
- * @return The new location of <code>object</code>.
- */
- @Inline
- public ObjectReference getForwardedReferent(ObjectReference object) {
- return getForwardedReference(object);
- }
-
- /**
- * If the Reference Type object has moved, return the new location.
- *
- * @param object The object which may have been forwarded.
- * @return The new location of <code>object</code>.
- */
- @Inline
- public ObjectReference getForwardedReferenceType(ObjectReference object) {
- return getForwardedReference(object);
- }
-
- /**
- * If the referenced object has moved, return the new location.
- *
- * Some copying collectors will need to override this method.
- *
- * @param object The object which may have been forwarded.
- * @return The new location of <code>object</code>.
- */
- @Inline
- public ObjectReference getForwardedReference(ObjectReference object) {
- return traceObject(object);
- }
-
- /**
- * Make alive a referent object that is known not to be live
- * (isLive is false). This is used by the ReferenceProcessor.
- *
- * <i>For many collectors these semantics relfect those of
- * <code>traceObject</code>, which is implemented here. Other
- * collectors must override this method.</i>
- *
- * @param object The object which is to be made alive.
- * @return The possibly forwarded address of the object.
- */
- @Inline
- public ObjectReference retainReferent(ObjectReference object) {
- return traceObject(object);
- }
-
- /**
- * An object is unreachable and is about to be added to the
- * finalizable queue. The collector must ensure the object is not
- * collected (despite being otherwise unreachable), and should
- * return its forwarded address if keeping the object alive involves
- * forwarding. This is only ever called once for an object.<p>
- *
- * <i>For many collectors these semantics relfect those of
- * <code>traceObject</code>, which is implemented here. Other
- * collectors must override this method.</i>
- *
- * @param object The object which may have been forwarded.
- * @return The forwarded value for <code>object</code>. <i>In this
- * case return <code>object</code>, copying collectors must override
- * this method.
- */
- public ObjectReference retainForFinalize(ObjectReference object) {
- return traceObject(object);
- }
-
- /**
- * Return true if an object is ready to move to the finalizable
- * queue, i.e. it has no regular references to it. This method may
- * (and in some cases is) be overridden by subclasses. If this method
- * returns true then it can be assumed that retainForFinalize will be
- * called during the current collection.
- *
- * <i>For many collectors these semantics relfect those of
- * <code>isLive</code>, which is implemented here. Other
- * collectors must override this method.</i>
- *
- * @param object The object being queried.
- * @return <code>true</code> if the object has no regular references
- * to it.
- */
- public boolean readyToFinalize(ObjectReference object) {
- return !isLive(object);
- }
-
- /****************************************************************************
- *
- * Collection
- *
- * Important notes:
- * . Global actions are executed by only one thread
- * . Thread-local actions are executed by all threads
- * . The following order is guaranteed by BasePlan, with each
- * separated by a synchronization barrier.
- * 1. globalPrepare()
- * 2. threadLocalPrepare()
- * 3. threadLocalRelease()
- * 4. globalRelease()
- */
- public void prepare() {
- // Nothing to do
- }
-
- public void release() {
- values.reset();
- rootLocations.reset();
- }
-
- /**
- * Process any roots for which processing was delayed.
- */
- @Inline
- public void processRoots() {
- logMessage(5, "processing delayed root objects");
- while (!rootLocations.isEmpty()) {
- processRootEdge(rootLocations.pop(), true);
- }
- }
-
- /**
- * Finishing processing all GC work. This method iterates until all work queues
- * are empty.
- */
- @Inline
- public void completeTrace() {
- logMessage(4, "Processing GC in parallel");
- if (!rootLocations.isEmpty()) {
- processRoots();
- }
- logMessage(5, "processing gray objects");
- assertMutatorRemsetsFlushed();
- do {
- while (!values.isEmpty()) {
- ObjectReference v = values.pop();
- scanObject(v);
- }
- processRememberedSets();
- } while (!values.isEmpty());
- assertMutatorRemsetsFlushed();
- }
-
- /**
- * Process GC work until either complete or workLimit
- * units of work are completed.
- *
- * @param workLimit The maximum units of work to perform.
- * @return True if all work was completed within workLimit.
- */
- @Inline
- public boolean incrementalTrace(int workLimit) {
- logMessage(4, "Continuing GC in parallel (incremental)");
- logMessage(5, "processing gray objects");
- int units = 0;
- do {
- while (!values.isEmpty() && units < workLimit) {
- ObjectReference v = values.pop();
- scanObject(v);
- units++;
- }
- } while (!values.isEmpty() && units < workLimit);
- return values.isEmpty();
- }
-
- /**
- * Flush any remembered sets pertaining to the current collection.
- * Non-generational collectors do nothing.
- */
-
- protected void processRememberedSets() {}
-
- /**
- * Assert that the remsets have been flushed. This is critical to
- * correctness. We need to maintain the invariant that remset entries
- * do not accrue during GC. If the host JVM generates barrier entires
- * it is its own responsibility to ensure that they are flushed before
- * returning to MMTk.
- */
- private void assertMutatorRemsetsFlushed() {
- /* FIXME: PNT
- if (VM.VERIFY_ASSERTIONS) {
- for (int m = 0; m < VM.activePlan.mutatorCount(); m++) {
- VM.activePlan.mutator(m).assertRemsetsFlushed();
- }
- }
- */
- }
-
- /**
- * This method logs a message with preprended thread id, if the
- * verbosity level is greater or equal to the passed level.
- *
- * @param minVerbose The required verbosity level
- * @param message The message to display
- */
- @Inline
- protected final void logMessage(int minVerbose, String message) {
- if (Options.verbose.getValue() >= minVerbose) {
- Log.prependThreadId();
- Log.write(" ");
- Log.writeln(message);
- }
- }
-
- /**
- * Given a slot (ie the address of an ObjectReference), ensure that the
- * referent will not move for the rest of the GC. This is achieved by
- * calling the precopyObject method.
- *
- * @param slot The slot to check
- * @param untraced Is this is an untraced reference?
- */
- @Inline
- public final void processPrecopyEdge(Address slot, boolean untraced) {
- ObjectReference child;
- if (untraced) child = slot.loadObjectReference();
- else child = VM.activePlan.global().loadObjectReference(slot);
- if (!child.isNull()) {
- child = precopyObject(child);
- if (untraced) slot.store(child);
- else VM.activePlan.global().storeObjectReference(slot, child);
- }
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/plan/TraceWriteBuffer.java b/vmkit/mmtk/java/src/org/mmtk/plan/TraceWriteBuffer.java
deleted file mode 100644
index b595eba..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/plan/TraceWriteBuffer.java
+++ /dev/null
@@ -1,72 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.plan;
-
-import org.mmtk.utility.deque.WriteBuffer;
-import org.vmmagic.pragma.*;
-import org.vmmagic.unboxed.*;
-
-/**
- * This class is used to push values in one direction during a trace. It
- * was designed for use in mutators that use write barriers to push
- * work to collector threads during concurrent tracing.
- *
- * @see org.mmtk.plan.TraceLocal
- */
-@Uninterruptible
-public final class TraceWriteBuffer extends TransitiveClosure {
- /****************************************************************************
- *
- * Instance variables
- */
- private final WriteBuffer buffer;
-
- /****************************************************************************
- *
- * Initialization
- */
-
- /**
- * Constructor
- *
- * @param trace The global trace class to use.
- */
- public TraceWriteBuffer(Trace trace) {
- buffer = new WriteBuffer(trace.valuePool);
- }
-
- /**
- * Flush the buffer to the trace.
- */
- public void flush() {
- buffer.flushLocal();
- }
-
-
- /**
- * @return True if the buffer is flushed.
- */
- public boolean isFlushed() {
- return buffer.isFlushed();
- }
-
- /**
- * Enqueue an object during a trace.
- *
- * @param object The object to enqueue
- */
- @Inline
- public void processNode(ObjectReference object) {
- buffer.insert(object.toAddress());
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/plan/TransitiveClosure.java b/vmkit/mmtk/java/src/org/mmtk/plan/TransitiveClosure.java
deleted file mode 100644
index 197f046..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/plan/TransitiveClosure.java
+++ /dev/null
@@ -1,94 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.plan;
-
-import org.mmtk.vm.VM;
-import org.vmmagic.pragma.*;
-import org.vmmagic.unboxed.*;
-
-/**
- * This abstract class is the fundamental mechanism for performing a
- * transitive closure over an object graph.<p>
- *
- * Some mechanisms only operate on nodes or edges, but due to limitations
- * of inheritance we have combined these two here.
- *
- * @see org.mmtk.plan.TraceLocal
- */
-@Uninterruptible
-public abstract class TransitiveClosure {
-
- /** Database of specialized scan classes. */
- private static final Class<?>[] specializedScans = new Class[VM.activePlan.constraints().numSpecializedScans()];
-
- /**
- * A transitive closure has been created that is designed to work with a specialized scan method. We must
- * register it here so the specializer can return the class when queried.
- *
- * @param id The method id to register.
- * @param specializedScanClass The class to register.
- */
- @Interruptible
- public static synchronized void registerSpecializedScan(int id, Class<?> specializedScanClass) {
- specializedScans[id] = specializedScanClass;
- }
-
- /**
- * Get the specialized scan with the given id.
- */
- public static Class<?> getSpecializedScanClass(int id) {
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(specializedScans[id] != null);
- return specializedScans[id];
- }
-
- /** The specialized scan identifier */
- protected final int specializedScan;
-
- /**
- * Constructor
- */
- protected TransitiveClosure() {
- this(-1);
- }
-
- /**
- * Constructor
- *
- * @param specializedScan The specialized scan for this trace.
- */
- protected TransitiveClosure(int specializedScan) {
- this.specializedScan = specializedScan;
- if (specializedScan >= 0) {
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(getClass() == getSpecializedScanClass(specializedScan));
- }
- }
-
- /**
- * Trace an edge during GC.
- *
- * @param source The source of the reference.
- * @param slot The location containing the object reference.
- */
- public void processEdge(ObjectReference source, Address slot) {
- VM.assertions.fail("processEdge not implemented.");
- }
-
- /**
- * Trace a node during GC.
- *
- * @param object The object to be processed.
- */
- public void processNode(ObjectReference object) {
- VM.assertions.fail("processNode not implemented.");
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/plan/copyms/CopyMS.java b/vmkit/mmtk/java/src/org/mmtk/plan/copyms/CopyMS.java
deleted file mode 100644
index 243d55f..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/plan/copyms/CopyMS.java
+++ /dev/null
@@ -1,204 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.plan.copyms;
-
-import org.mmtk.plan.*;
-import org.mmtk.policy.CopySpace;
-import org.mmtk.policy.MarkSweepSpace;
-import org.mmtk.policy.Space;
-import org.mmtk.utility.heap.VMRequest;
-import org.mmtk.utility.options.Options;
-import org.mmtk.utility.sanitychecker.SanityChecker;
-
-import org.vmmagic.pragma.*;
-import org.vmmagic.unboxed.ObjectReference;
-
-/**
- * This class implements the global state of a full-heap collector
- * with a copying nursery and mark-sweep mature space. Unlike a full
- * generational collector, there is no write barrier, no remembered set, and
- * every collection is full-heap.
- *
- * All plans make a clear distinction between <i>global</i> and
- * <i>thread-local</i> activities, and divides global and local state
- * into separate class hierarchies. Global activities must be
- * synchronized, whereas no synchronization is required for
- * thread-local activities. There is a single instance of Plan (or the
- * appropriate sub-class), and a 1:1 mapping of PlanLocal to "kernel
- * threads" (aka CPUs). Thus instance
- * methods of PlanLocal allow fast, unsychronized access to functions such as
- * allocation and collection.
- *
- * The global instance defines and manages static resources
- * (such as memory and virtual memory resources). This mapping of threads to
- * instances is crucial to understanding the correctness and
- * performance properties of MMTk plans.
- */
-@Uninterruptible
-public class CopyMS extends StopTheWorld {
-
- /****************************************************************************
- * Constants
- */
-
- /****************************************************************************
- * Class variables
- */
- public static final CopySpace nurserySpace = new CopySpace("nursery", DEFAULT_POLL_FREQUENCY, false, VMRequest.create(0.15f, true));
- public static final MarkSweepSpace msSpace = new MarkSweepSpace("ms", DEFAULT_POLL_FREQUENCY, VMRequest.create());
-
- public static final int NURSERY = nurserySpace.getDescriptor();
- public static final int MARK_SWEEP = msSpace.getDescriptor();
-
- public static final int ALLOC_NURSERY = ALLOC_DEFAULT;
- public static final int ALLOC_MS = StopTheWorld.ALLOCATORS + 1;
-
- public static final int SCAN_COPYMS = 0;
-
- /****************************************************************************
- * Instance variables
- */
-
- public final Trace trace;
-
- /**
- * Constructor.
- */
- public CopyMS() {
- trace = new Trace(metaDataSpace);
- }
-
-
- /*****************************************************************************
- * Collection
- */
-
- /**
- * Perform a (global) collection phase.
- *
- * @param phaseId Collection phase to execute.
- */
- @Inline
- public final void collectionPhase(short phaseId) {
- if (phaseId == PREPARE) {
- super.collectionPhase(phaseId);
- trace.prepare();
- msSpace.prepare(true);
- nurserySpace.prepare(true);
- return;
- }
- if (phaseId == CLOSURE) {
- trace.prepare();
- return;
- }
- if (phaseId == RELEASE) {
- trace.release();
- msSpace.release();
- nurserySpace.release();
- super.collectionPhase(phaseId);
- return;
- }
-
- super.collectionPhase(phaseId);
- }
-
- /**
- * This method controls the triggering of a GC. It is called periodically
- * during allocation. Returns true to trigger a collection.
- *
- * @param spaceFull Space request failed, must recover pages within 'space'.
- * @return True if a collection is requested by the plan.
- */
- public final boolean collectionRequired(boolean spaceFull) {
- boolean nurseryFull = nurserySpace.reservedPages() > Options.nurserySize.getMaxNursery();
-
- return super.collectionRequired(spaceFull) || nurseryFull;
- }
-
- /*****************************************************************************
- *
- * Accounting
- */
-
- /**
- * Return the number of pages reserved for use given the pending
- * allocation.
- *
- * @return The number of pages reserved given the pending
- * allocation, excluding space reserved for copying.
- */
- public int getPagesUsed() {
- return super.getPagesUsed() +
- msSpace.reservedPages() +
- nurserySpace.reservedPages();
- }
-
- /**
- * Return the number of pages reserved for collection.
- * For mark sweep this is a fixed fraction of total pages.
- *
- * @return The number of pages reserved given the pending
- * allocation, including space reserved for collection.
- */
- public int getCollectionReserve() {
- return nurserySpace.reservedPages() + super.getCollectionReserve();
- }
-
- /**
- * @return The number of pages available for allocation, <i>assuming
- * all future allocation is to the nursery</i>.
- */
- public final int getPagesAvail() {
- return (getTotalPages() - getPagesReserved()) >> 1;
- }
-
- /**
- * Calculate the number of pages a collection is required to free to satisfy
- * outstanding allocation requests.
- *
- * @return the number of pages a collection is required to free to satisfy
- * outstanding allocation requests.
- */
- public int getPagesRequired() {
- return super.getPagesRequired() + msSpace.requiredPages() +
- (nurserySpace.requiredPages() << 1);
- }
-
- /**
- * Return the expected reference count. For non-reference counting
- * collectors this becomes a true/false relationship.
- *
- * @param object The object to check.
- * @param sanityRootRC The number of root references to the object.
- * @return The expected (root excluded) reference count.
- */
- public int sanityExpectedRC(ObjectReference object, int sanityRootRC) {
- Space space = Space.getSpaceForObject(object);
-
- // Nursery
- if (space == CopyMS.nurserySpace) {
- return SanityChecker.DEAD;
- }
-
- return space.isReachable(object) ? SanityChecker.ALIVE : SanityChecker.DEAD;
- }
-
- /**
- * Register specialized methods.
- */
- @Interruptible
- protected void registerSpecializedMethods() {
- TransitiveClosure.registerSpecializedScan(SCAN_COPYMS, CopyMSTraceLocal.class);
- super.registerSpecializedMethods();
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/plan/copyms/CopyMSCollector.java b/vmkit/mmtk/java/src/org/mmtk/plan/copyms/CopyMSCollector.java
deleted file mode 100644
index 420d0e9..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/plan/copyms/CopyMSCollector.java
+++ /dev/null
@@ -1,159 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.plan.copyms;
-
-import org.mmtk.plan.*;
-import org.mmtk.policy.LargeObjectLocal;
-import org.mmtk.policy.MarkSweepLocal;
-import org.mmtk.utility.alloc.Allocator;
-import org.mmtk.vm.VM;
-
-import org.vmmagic.pragma.*;
-import org.vmmagic.unboxed.*;
-
-/**
- * This class implements <i>per-collector thread</i> behavior
- * and state for the <i>CopyMS</i> plan.<p>
- *
- * Specifically, this class defines <i>CopyMS</i>
- * collection behavior (through <code>trace</code> and
- * the <code>collectionPhase</code> method), and
- * collection-time allocation into the mature space.
- *
- * @see CopyMS
- * @see CopyMSMutator
- * @see StopTheWorldCollector
- * @see CollectorContext
- */
-@Uninterruptible
-public class CopyMSCollector extends StopTheWorldCollector {
-
- /****************************************************************************
- * Instance fields
- */
-
- private MarkSweepLocal mature;
- private CopyMSTraceLocal trace;
-
- protected final LargeObjectLocal los;
-
- /****************************************************************************
- *
- * Initialization
- */
-
- /**
- * Create a new (local) instance.
- */
- public CopyMSCollector() {
- los = new LargeObjectLocal(Plan.loSpace);
- mature = new MarkSweepLocal(CopyMS.msSpace);
- trace = new CopyMSTraceLocal(global().trace);
- }
-
- /****************************************************************************
- *
- * Collection-time allocation
- */
-
- /**
- * Allocate space for copying an object (this method <i>does not</i>
- * copy the object, it only allocates space)
- *
- * @param original A reference to the original object
- * @param bytes The size of the space to be allocated (in bytes)
- * @param align The requested alignment.
- * @param offset The alignment offset.
- * @return The address of the first byte of the allocated region
- */
- @Inline
- public final Address allocCopy(ObjectReference original, int bytes,
- int align, int offset, int allocator) {
- if (allocator == Plan.ALLOC_LOS) {
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(Allocator.getMaximumAlignedSize(bytes, align) > Plan.MAX_NON_LOS_COPY_BYTES);
- return los.alloc(bytes, align, offset);
- } else {
- if (VM.VERIFY_ASSERTIONS) {
- VM.assertions._assert(bytes <= Plan.MAX_NON_LOS_COPY_BYTES);
- VM.assertions._assert(allocator == CopyMS.ALLOC_MS);
- }
- return mature.alloc(bytes, align, offset);
- }
- }
-
- /**
- * Perform any post-copy actions.
- *
- * @param object The newly allocated object
- * @param typeRef the type reference for the instance being created
- * @param bytes The size of the space to be allocated (in bytes)
- */
- @Inline
- public final void postCopy(ObjectReference object, ObjectReference typeRef,
- int bytes, int allocator) {
- if (allocator == Plan.ALLOC_LOS)
- Plan.loSpace.initializeHeader(object, false);
- else
- CopyMS.msSpace.postCopy(object, true);
- }
-
- /****************************************************************************
- *
- * Collection
- */
-
- /**
- * Perform a per-collector collection phase.
- *
- * @param phaseId The collection phase to perform
- * @param primary Use this thread for single-threaded local activities.
- */
- @Inline
- public final void collectionPhase(short phaseId, boolean primary) {
- if (phaseId == CopyMS.PREPARE) {
- super.collectionPhase(phaseId, primary);
- mature.prepare();
- trace.prepare();
- return;
- }
-
- if (phaseId == CopyMS.CLOSURE) {
- trace.completeTrace();
- return;
- }
-
- if (phaseId == CopyMS.RELEASE) {
- mature.release();
- trace.release();
- super.collectionPhase(phaseId, primary);
- return;
- }
-
- super.collectionPhase(phaseId, primary);
- }
-
- /****************************************************************************
- *
- * Miscellaneous
- */
-
- /** @return the active global plan as an <code>MS</code> instance. */
- @Inline
- private static CopyMS global() {
- return (CopyMS) VM.activePlan.global();
- }
-
- /** @return The current trace instance. */
- public final TraceLocal getCurrentTrace() { return trace; }
-
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/plan/copyms/CopyMSConstraints.java b/vmkit/mmtk/java/src/org/mmtk/plan/copyms/CopyMSConstraints.java
deleted file mode 100644
index 786db37..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/plan/copyms/CopyMSConstraints.java
+++ /dev/null
@@ -1,41 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.plan.copyms;
-
-import org.mmtk.plan.StopTheWorldConstraints;
-
-import org.mmtk.policy.CopySpace;
-import org.mmtk.policy.SegregatedFreeListSpace;
-
-import org.vmmagic.pragma.*;
-
-/**
- * This class and its subclasses communicate to the host VM/Runtime
- * any features of the selected plan that it needs to know. This is
- * separate from the main Plan/PlanLocal class in order to bypass any
- * issues with ordering of static initialization.
- */
-@Uninterruptible
-public class CopyMSConstraints extends StopTheWorldConstraints {
-
- @Override
- public int gcHeaderBits() { return CopySpace.LOCAL_GC_BITS_REQUIRED; }
- @Override
- public int gcHeaderWords() { return CopySpace.GC_HEADER_WORDS_REQUIRED; }
- @Override
- public int numSpecializedScans() { return 1; }
- @Override
- public boolean movesObjects() { return true; }
- @Override
- public int maxNonLOSCopyBytes() { return SegregatedFreeListSpace.MAX_FREELIST_OBJECT_BYTES;}
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/plan/copyms/CopyMSMutator.java b/vmkit/mmtk/java/src/org/mmtk/plan/copyms/CopyMSMutator.java
deleted file mode 100644
index efb5a2e..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/plan/copyms/CopyMSMutator.java
+++ /dev/null
@@ -1,163 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.plan.copyms;
-
-import org.mmtk.plan.StopTheWorldMutator;
-import org.mmtk.policy.CopyLocal;
-import org.mmtk.policy.MarkSweepLocal;
-import org.mmtk.policy.Space;
-
-import org.mmtk.utility.alloc.Allocator;
-
-import org.vmmagic.pragma.*;
-import org.vmmagic.unboxed.*;
-
-/**
- * This class implements <i>per-mutator thread</i> behavior
- * and state for the <i>CopyMS</i> plan.<p>
- *
- * Specifically, this class defines <i>CopyMS</i> mutator-time
- * allocation into the nursery and mature space (through pre-tenuring).
- * Per-mutator thread collection semantics are also defined (flushing
- * and restoring per-mutator allocator state).
- *
- * @see CopyMS
- * @see CopyMSCollector
- * @see org.mmtk.plan.StopTheWorldMutator
- * @see org.mmtk.plan.MutatorContext
- */
-@Uninterruptible
-public class CopyMSMutator extends StopTheWorldMutator {
-
- /****************************************************************************
- * Instance fields
- */
-
- private final MarkSweepLocal mature;
- private final CopyLocal nursery;
-
- /****************************************************************************
- *
- * Initialization
- */
-
- /**
- * Constructor
- */
- public CopyMSMutator() {
- mature = new MarkSweepLocal(CopyMS.msSpace);
- nursery = new CopyLocal(CopyMS.nurserySpace);
- }
-
- /****************************************************************************
- *
- * Mutator-time allocation
- */
-
- /**
- * Allocate memory for an object. This class handles the default allocator
- * from the mark sweep space, and delegates everything else to the
- * superclass.
- *
- * @param bytes The number of bytes required for the object.
- * @param align Required alignment for the object.
- * @param offset Offset associated with the alignment.
- * @param allocator The allocator associated with this request.
- * @return The low address of the allocated memory.
- */
- @Inline
- public Address alloc(int bytes, int align, int offset, int allocator, int site) {
- if (allocator == CopyMS.ALLOC_DEFAULT)
- return nursery.alloc(bytes, align, offset);
- if (allocator == CopyMS.ALLOC_MS)
- return mature.alloc(bytes, align, offset);
-
- return super.alloc(bytes, align, offset, allocator, site);
- }
-
- /**
- * Perform post-allocation actions. Initialize the object header for
- * objects in the mark-sweep space, and delegate to the superclass for
- * other objects.
- *
- * @param ref The newly allocated object
- * @param typeRef the type reference for the instance being created
- * @param bytes The size of the space to be allocated (in bytes)
- * @param allocator The allocator number to be used for this allocation
- */
- @SuppressWarnings({"UnnecessaryReturnStatement"})
- @Inline
- public void postAlloc(ObjectReference ref, ObjectReference typeRef,
- int bytes, int allocator) {
- if (allocator == CopyMS.ALLOC_DEFAULT)
- return;
- else if (allocator == CopyMS.ALLOC_MS)
- CopyMS.msSpace.initializeHeader(ref, true);
- else
- super.postAlloc(ref, typeRef, bytes, allocator);
- }
-
- /**
- * Return the allocator instance associated with a space
- * <code>space</code>, for this plan instance.
- *
- * @param space The space for which the allocator instance is desired.
- * @return The allocator instance associated with this plan instance
- * which is allocating into <code>space</code>, or <code>null</code>
- * if no appropriate allocator can be established.
- */
- public Allocator getAllocatorFromSpace(Space space) {
- if (space == CopyMS.nurserySpace) return nursery;
- if (space == CopyMS.msSpace) return mature;
- return super.getAllocatorFromSpace(space);
- }
-
- /****************************************************************************
- *
- * Collection
- */
-
- /**
- * Perform a per-mutator collection phase.
- *
- * @param phaseId The collection phase to perform
- * @param primary Use this thread for single-threaded local activities.
- */
- @Inline
- public final void collectionPhase(short phaseId, boolean primary) {
- if (phaseId == CopyMS.PREPARE) {
- super.collectionPhase(phaseId, primary);
- mature.prepare();
- return;
- }
-
- if (phaseId == CopyMS.RELEASE) {
- nursery.reset();
- mature.release();
- super.collectionPhase(phaseId, primary);
- return;
- }
-
- super.collectionPhase(phaseId, primary);
- }
-
- /**
- * Flush mutator context, in response to a requestMutatorFlush.
- * Also called by the default implementation of deinitMutator.
- */
- @Override
- public void flush() {
- super.flush();
- mature.flush();
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/plan/copyms/CopyMSTraceLocal.java b/vmkit/mmtk/java/src/org/mmtk/plan/copyms/CopyMSTraceLocal.java
deleted file mode 100644
index fc71b47..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/plan/copyms/CopyMSTraceLocal.java
+++ /dev/null
@@ -1,111 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.plan.copyms;
-
-import org.mmtk.plan.TraceLocal;
-import org.mmtk.plan.Trace;
-import org.mmtk.policy.Space;
-
-import org.vmmagic.pragma.*;
-import org.vmmagic.unboxed.*;
-
-/**
- * This class implements the thread-local functionality for a
- * transitive closure over a coping/mark-sweep hybrid collector.
- */
-@Uninterruptible
-public final class CopyMSTraceLocal extends TraceLocal {
-
- /**
- * Constructor
- */
- public CopyMSTraceLocal(Trace trace) {
- super(CopyMS.SCAN_COPYMS, trace);
- }
-
- /****************************************************************************
- *
- * Externally visible Object processing and tracing
- */
-
- /**
- * Is the specified object reachable?
- *
- * @param object The object.
- * @return True if the object is live.
- */
- @Override
- public boolean isLive(ObjectReference object) {
- if (object.isNull()) return false;
- if (Space.isInSpace(CopyMS.NURSERY, object)) {
- return CopyMS.nurserySpace.isLive(object);
- }
- if (Space.isInSpace(CopyMS.MARK_SWEEP, object)) {
- return CopyMS.msSpace.isLive(object);
- }
- return super.isLive(object);
- }
-
- /**
- * This method is the core method during the trace of the object graph.
- * The role of this method is to:
- *
- * 1. Ensure the traced object is not collected.
- * 2. If this is the first visit to the object enqueue it to be scanned.
- * 3. Return the forwarded reference to the object.
- *
- * In this instance, we refer objects in the mark-sweep space to the
- * msSpace for tracing, and defer to the superclass for all others.
- *
- * @param object The object to be traced.
- * @return The new reference to the same object instance.
- */
- @Inline
- @Override
- public ObjectReference traceObject(ObjectReference object) {
- if (object.isNull()) return object;
- if (Space.isInSpace(CopyMS.NURSERY, object))
- return CopyMS.nurserySpace.traceObject(this, object, CopyMS.ALLOC_MS);
- if (Space.isInSpace(CopyMS.MARK_SWEEP, object))
- return CopyMS.msSpace.traceObject(this, object);
- return super.traceObject(object);
- }
-
-
- /**
- * Ensure that this object will not move for the rest of the GC.
- *
- * @param object The object that must not move
- * @return The new object, guaranteed stable for the rest of the GC.
- */
- @Inline
- @Override
- public ObjectReference precopyObject(ObjectReference object) {
- if (object.isNull()) return object;
- else if (Space.isInSpace(CopyMS.NURSERY, object))
- return CopyMS.nurserySpace.traceObject(this, object, CopyMS.ALLOC_MS);
- else
- return object;
- }
-
- /**
- * Will this object move from this point on, during the current collection ?
- *
- * @param object The object to query.
- * @return True if the object will not move during this collection.
- */
- @Override
- public boolean willNotMoveInCurrentCollection(ObjectReference object) {
- return !Space.isInSpace(CopyMS.NURSERY, object);
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/plan/generational/Gen.java b/vmkit/mmtk/java/src/org/mmtk/plan/generational/Gen.java
deleted file mode 100644
index 0c37d1e..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/plan/generational/Gen.java
+++ /dev/null
@@ -1,472 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.plan.generational;
-
-import org.mmtk.plan.*;
-import org.mmtk.policy.CopySpace;
-import org.mmtk.policy.Space;
-
-import org.mmtk.utility.deque.*;
-import org.mmtk.utility.heap.Map;
-import org.mmtk.utility.heap.VMRequest;
-import org.mmtk.utility.Log;
-import org.mmtk.utility.options.Options;
-import org.mmtk.utility.sanitychecker.SanityChecker;
-import org.mmtk.utility.statistics.*;
-
-import org.mmtk.vm.Collection;
-import org.mmtk.vm.VM;
-
-import org.vmmagic.pragma.*;
-import org.vmmagic.unboxed.*;
-
-/**
- * This abstract class implements the core functionality of generic
- * two-generationa copying collectors. Nursery collections occur when
- * either the heap is full or the nursery is full. The nursery size
- * is determined by an optional command line argument. If undefined,
- * the nursery size is "infinite", so nursery collections only occur
- * when the heap is full (this is known as a flexible-sized nursery
- * collector). Thus both fixed and flexible nursery sizes are
- * supported. Full heap collections occur when the nursery size has
- * dropped to a statically defined threshold,
- * <code>NURSERY_THRESHOLD</code><p>
- *
- * See also Plan.java for general comments on local vs global plan
- * classes.
- */
-@Uninterruptible
-public abstract class Gen extends StopTheWorld {
-
- /*****************************************************************************
- *
- * Constants
- */
- protected static final float SURVIVAL_ESTIMATE = 0.8f; // est yield
- protected static final float MATURE_FRACTION = 0.5f; // est yield
- private static final float WORST_CASE_COPY_EXPANSION = 1.5f; // worst case for addition of one word overhead due to address based hashing
- public static final boolean IGNORE_REMSETS = false;
- public static final boolean USE_NON_HEAP_OBJECT_REFERENCE_WRITE_BARRIER = false;
- public static final boolean USE_OBJECT_BARRIER_FOR_AASTORE = false; // choose between slot and object barriers
- public static final boolean USE_OBJECT_BARRIER_FOR_PUTFIELD = false; // choose between slot and object barriers
- public static final boolean USE_OBJECT_BARRIER = USE_OBJECT_BARRIER_FOR_AASTORE || USE_OBJECT_BARRIER_FOR_PUTFIELD;
-
- /** Fraction of available virtual memory to give to the nursery (if contiguous) */
- protected static final float NURSERY_VM_FRACTION = 0.15f;
-
- /** Switch between a contiguous and discontiguous nursery (experimental) */
- static final boolean USE_DISCONTIGUOUS_NURSERY = false;
-
- // Allocators
- public static final int ALLOC_NURSERY = ALLOC_DEFAULT;
- public static final int ALLOC_MATURE = StopTheWorld.ALLOCATORS + 1;
- public static final int ALLOC_MATURE_MINORGC = StopTheWorld.ALLOCATORS + 2;
- public static final int ALLOC_MATURE_MAJORGC = StopTheWorld.ALLOCATORS + 3;
-
- public static final int SCAN_NURSERY = 0;
- public static final int SCAN_MATURE = 1;
-
- /*****************************************************************************
- *
- * Class fields
- */
-
- /* Statistics */
- protected static final BooleanCounter fullHeap = new BooleanCounter("majorGC", true, true);
- private static final Timer fullHeapTime = new Timer("majorGCTime", false, true);
- protected static final EventCounter wbFast;
- protected static final EventCounter wbSlow;
- public static final SizeCounter nurseryMark;
- public static final SizeCounter nurseryCons;
-
- /** The nursery space is where all new objects are allocated by default */
- private static final VMRequest vmRequest = USE_DISCONTIGUOUS_NURSERY ? VMRequest.create() : VMRequest.create(NURSERY_VM_FRACTION, true);
- public static final CopySpace nurserySpace = new CopySpace("nursery", DEFAULT_POLL_FREQUENCY, false, vmRequest);
-
- public static final int NURSERY = nurserySpace.getDescriptor();
- private static final Address NURSERY_START = nurserySpace.getStart();
-
- /*****************************************************************************
- *
- * Instance fields
- */
- /* status fields */
- public boolean gcFullHeap = false;
- public boolean nextGCFullHeap = false;
-
- /* The trace object */
- public final Trace nurseryTrace = new Trace(metaDataSpace);
-
- /**
- * Remset pools
- */
- public final SharedDeque modbufPool = new SharedDeque("modBufs",metaDataSpace, 1);
- public final SharedDeque remsetPool = new SharedDeque("remSets",metaDataSpace, 1);
- public final SharedDeque arrayRemsetPool = new SharedDeque("arrayRemSets",metaDataSpace, 2);
-
- /*
- * Class initializer
- */
- static {
- if (GATHER_WRITE_BARRIER_STATS) {
- wbFast = new EventCounter("wbFast");
- wbSlow = new EventCounter("wbSlow");
- } else {
- wbFast = null;
- wbSlow = null;
- }
- if (Stats.GATHER_MARK_CONS_STATS) {
- nurseryMark = new SizeCounter("nurseryMark", true, true);
- nurseryCons = new SizeCounter("nurseryCons", true, true);
- } else {
- nurseryMark = null;
- nurseryCons = null;
- }
- }
-
- /*****************************************************************************
- *
- * Collection
- */
-
- /**
- * Force the next collection to be full heap.
- */
- public void forceFullHeapCollection() {
- nextGCFullHeap = true;
- }
-
- /**
- * Perform a (global) collection phase.
- *
- * @param phaseId Collection phase to execute.
- */
- @NoInline
- public void collectionPhase(short phaseId) {
- if (phaseId == SET_COLLECTION_KIND) {
- super.collectionPhase(phaseId);
- gcFullHeap = requiresFullHeapCollection();
- return;
- }
-
- if (phaseId == PREPARE) {
- nurserySpace.prepare(true);
- if (traceFullHeap()){
- if (gcFullHeap) {
- if (Stats.gatheringStats()) fullHeap.set();
- fullHeapTime.start();
- }
- super.collectionPhase(phaseId);
-
- // we can throw away the remsets (but not modbuf) for a full heap GC
- remsetPool.clearDeque(1);
- arrayRemsetPool.clearDeque(2);
- }
- return;
- }
-
- if (phaseId == CLOSURE) {
- if (!traceFullHeap()) {
- nurseryTrace.prepare();
- }
- return;
- }
- if (phaseId == RELEASE) {
- nurserySpace.release();
- modbufPool.clearDeque(1);
- remsetPool.clearDeque(1);
- arrayRemsetPool.clearDeque(2);
- if (!traceFullHeap()) {
- nurseryTrace.release();
- } else {
- super.collectionPhase(phaseId);
- if (gcFullHeap) fullHeapTime.stop();
- }
- nextGCFullHeap = (getPagesAvail() < Options.nurserySize.getMinNursery());
- return;
- }
-
- super.collectionPhase(phaseId);
- }
-
- /**
- * This method controls the triggering of a GC. It is called periodically
- * during allocation. Returns true to trigger a collection.
- *
- * @param spaceFull Space request failed, must recover pages within 'space'.
- * @return True if a collection is requested by the plan.
- */
- public final boolean collectionRequired(boolean spaceFull) {
- int nurseryPages = nurserySpace.reservedPages();
-
- if (nurseryPages > Options.nurserySize.getMaxNursery()) {
- return true;
- }
-
- if (virtualMemoryExhausted())
- return true;
-
- return super.collectionRequired(spaceFull);
- }
-
- /**
- * Determine if this GC should be a full heap collection.
- *
- * @return True is this GC should be a full heap collection.
- */
- protected boolean requiresFullHeapCollection() {
- if (collectionTrigger == Collection.EXTERNAL_GC_TRIGGER && Options.fullHeapSystemGC.getValue()) {
- return true;
- }
-
- if (nextGCFullHeap || collectionAttempt > 1) {
- // Forces full heap collection
- return true;
- }
-
- if (loSpace.allocationFailed() ||
- nonMovingSpace.allocationFailed() ||
- (USE_CODE_SPACE && (largeCodeSpace.allocationFailed() || smallCodeSpace.allocationFailed()))) {
- // We need space from the nursery
- return true;
- }
-
- if (virtualMemoryExhausted())
- return true;
-
- int smallNurseryPages = nurserySpace.committedPages();
- int smallNurseryYield = (int)((smallNurseryPages << 1) * SURVIVAL_ESTIMATE);
-
- if (smallNurseryYield < getPagesRequired()) {
- // Our total yield is insufficent.
- return true;
- }
-
- if (nurserySpace.allocationFailed()) {
- if (smallNurseryYield < (nurserySpace.requiredPages() << 1)) {
- // We have run out of VM pages in the nursery
- return true;
- }
- }
-
-
- return false;
- }
-
- /**
- * Independent of how many pages remain in the page budget (a function of
- * heap size), we must ensure we never exhaust virtual memory. Therefore
- * we must never let the nursery grow to the extent that it can't be
- * copied into the mature space.
- *
- * @return True if the nursery has grown to the extent that it may not be
- * able to be copied into the mature space.
- */
- private boolean virtualMemoryExhausted() {
- return ((int) (nurserySpace.reservedPages()*WORST_CASE_COPY_EXPANSION) >= getMaturePhysicalPagesAvail());
- }
-
- /*****************************************************************************
- *
- * Correctness
- */
-
- /*****************************************************************************
- *
- * Accounting
- */
-
- /**
- * Return the number of pages in use given the pending
- * allocation. Simply add the nursery's contribution to that of
- * the superclass.
- *
- * @return The number of pages reserved given the pending
- * allocation, excluding space reserved for copying.
- */
- @Override
- public int getPagesUsed() {
- return (nurserySpace.reservedPages() + super.getPagesUsed());
- }
-
- /**
- * Return the number of pages available for allocation, <i>assuming
- * all future allocation is to the nursery</i>.
- *
- * @return The number of pages available for allocation, <i>assuming
- * all future allocation is to the nursery</i>.
- */
- @Override
- public int getPagesAvail() {
- return super.getPagesAvail() >> 1;
- }
-
- /**
- * Return the number of pages reserved for copying.
- *
- * @return The number of pages reserved given the pending
- * allocation, including space reserved for copying.
- */
- @Override
- public int getCollectionReserve() {
- return nurserySpace.reservedPages() + super.getCollectionReserve();
- }
-
- /**
- * Return the number of pages available for allocation into the mature
- * space.
- *
- * @return The number of pages available for allocation into the mature
- * space.
- */
- public abstract int getMaturePhysicalPagesAvail();
-
- /**
- * Calculate the number of pages a collection is required to free to satisfy
- * outstanding allocation requests.
- *
- * @return the number of pages a collection is required to free to satisfy
- * outstanding allocation requests.
- */
- @Override
- public int getPagesRequired() {
- /* We don't currently pretenure, so mature space must be zero */
- return super.getPagesRequired() + (nurserySpace.requiredPages() << 1);
- }
-
- /*****************************************************************************
- *
- * Miscellaneous
- */
-
- /**
- * Return true if the address resides within the nursery
- *
- * @param addr The object to be tested
- * @return true if the address resides within the nursery
- */
- @Inline
- static boolean inNursery(Address addr) {
- if (USE_DISCONTIGUOUS_NURSERY)
- return Map.getDescriptorForAddress(addr) == NURSERY;
- else
- return addr.GE(NURSERY_START);
- }
-
- /**
- * Return true if the object resides within the nursery
- *
- * @param obj The object to be tested
- * @return true if the object resides within the nursery
- */
- @Inline
- static boolean inNursery(ObjectReference obj) {
- return inNursery(obj.toAddress());
- }
-
- /**
- * @return Does the mature space do copying ?
- */
- protected boolean copyMature() {
- return false;
- }
-
- /**
- * Print pre-collection statistics. In this class we prefix the output
- * indicating whether the collection was full heap or not.
- */
- public void printPreStats() {
- if ((Options.verbose.getValue() >= 1) && (gcFullHeap))
- Log.write("[Full heap]");
- super.printPreStats();
- }
-
- /**
- * @return The mature space, set by each subclass of <code>Gen</code>.
- */
- protected abstract Space activeMatureSpace();
-
- /**
- * @return True if we should trace the whole heap during collection. True if
- * we're ignorning remsets or if we're doing a full heap GC.
- */
- public final boolean traceFullHeap() {
- return IGNORE_REMSETS || gcFullHeap;
- }
-
- /**
- * @return Is current GC only collecting objects allocated since last GC.
- */
- public final boolean isCurrentGCNursery() {
- return !gcFullHeap;
- }
-
- /**
- * @return Is last GC a full collection?
- */
- public final boolean lastCollectionFullHeap() {
- return gcFullHeap;
- }
-
- /**
- * @see org.mmtk.plan.Plan#willNeverMove
- *
- * @param object Object in question
- * @return True if the object will never move
- */
- @Override
- public boolean willNeverMove(ObjectReference object) {
- if (Space.isInSpace(NURSERY, object))
- return false;
- return super.willNeverMove(object);
- }
-
- /**
- * Return the expected reference count. For non-reference counting
- * collectors this becomes a true/false relationship.
- *
- * @param object The object to check.
- * @param sanityRootRC The number of root references to the object.
- * @return The expected (root excluded) reference count.
- */
- public int sanityExpectedRC(ObjectReference object, int sanityRootRC) {
- Space space = Space.getSpaceForObject(object);
-
- // Nursery
- if (space == Gen.nurserySpace) {
- return SanityChecker.DEAD;
- }
-
- // Immortal spaces
- if (space == Gen.immortalSpace || space == Gen.vmSpace) {
- return space.isReachable(object) ? SanityChecker.ALIVE : SanityChecker.DEAD;
- }
-
- // Mature space (nursery collection)
- if (VM.activePlan.global().isCurrentGCNursery()) {
- return SanityChecker.UNSURE;
- }
-
- // Mature space (full heap collection)
- return space.isReachable(object) ? SanityChecker.ALIVE : SanityChecker.DEAD;
- }
-
- /**
- * Register specialized methods.
- */
- @Interruptible
- protected void registerSpecializedMethods() {
- TransitiveClosure.registerSpecializedScan(SCAN_NURSERY, GenNurseryTraceLocal.class);
- super.registerSpecializedMethods();
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/plan/generational/GenCollector.java b/vmkit/mmtk/java/src/org/mmtk/plan/generational/GenCollector.java
deleted file mode 100644
index 72a418c..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/plan/generational/GenCollector.java
+++ /dev/null
@@ -1,147 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.plan.generational;
-
-import org.mmtk.plan.*;
-import org.mmtk.policy.LargeObjectLocal;
-import org.mmtk.utility.deque.*;
-
-import org.mmtk.vm.VM;
-
-import org.vmmagic.pragma.*;
-
-/**
- * This abstract class implements <i>per-collector thread</i>
- * behavior and state for <i>generational copying collectors</i>.<p>
- *
- * Specifically, this class defines nursery collection behavior (through
- * <code>nurseryTrace</code> and the <code>collectionPhase</code> method).
- * Per-collector thread remset consumers are instantiated here (used by
- * sub-classes).
- *
- * @see Gen
- * @see GenMutator
- * @see StopTheWorldCollector
- * @see CollectorContext
- */
-@Uninterruptible public abstract class GenCollector extends StopTheWorldCollector {
-
- /*****************************************************************************
- * Instance fields
- */
-
- protected final GenNurseryTraceLocal nurseryTrace;
-
- protected final LargeObjectLocal los;
-
- // remembered set consumers
- protected final ObjectReferenceDeque modbuf;
- protected final AddressDeque remset;
- protected final AddressPairDeque arrayRemset;
-
- /****************************************************************************
- *
- * Initialization
- */
-
- /**
- * Constructor
- *
- * Note that the collector is a consumer of remsets, while the
- * mutator is a producer. The <code>GenMutator</code> class is
- * responsible for construction of the WriteBuffer (producer).
- * @see GenMutator
- */
- public GenCollector() {
- los = new LargeObjectLocal(Plan.loSpace);
- arrayRemset = new AddressPairDeque(global().arrayRemsetPool);
- remset = new AddressDeque("remset", global().remsetPool);
- modbuf = new ObjectReferenceDeque("modbuf", global().modbufPool);
- nurseryTrace = new GenNurseryTraceLocal(global().nurseryTrace, this);
- }
-
- /****************************************************************************
- *
- * Collection
- */
-
- /**
- * Perform a per-collector collection phase.
- *
- * @param phaseId The collection phase to perform
- * @param primary Use this thread for single-threaded local activities.
- */
- @NoInline
- public void collectionPhase(short phaseId, boolean primary) {
-
- if (phaseId == Gen.PREPARE) {
- los.prepare(true);
- global().arrayRemsetPool.prepareNonBlocking();
- global().remsetPool.prepareNonBlocking();
- global().modbufPool.prepareNonBlocking();
- nurseryTrace.prepare();
- return;
- }
-
- if (phaseId == StopTheWorld.ROOTS) {
- VM.scanning.computeGlobalRoots(getCurrentTrace());
- if (!Gen.USE_NON_HEAP_OBJECT_REFERENCE_WRITE_BARRIER || global().traceFullHeap()) {
- VM.scanning.computeStaticRoots(getCurrentTrace());
- }
- if (Plan.SCAN_BOOT_IMAGE && global().traceFullHeap()) {
- VM.scanning.computeBootImageRoots(getCurrentTrace());
- }
- return;
- }
-
- if (phaseId == Gen.CLOSURE) {
- if (!global().gcFullHeap) {
- nurseryTrace.completeTrace();
- }
- return;
- }
-
- if (phaseId == Gen.RELEASE) {
- los.release(true);
- if (!global().traceFullHeap()) {
- nurseryTrace.release();
- global().arrayRemsetPool.reset();
- global().remsetPool.reset();
- global().modbufPool.reset();
- }
- return;
- }
-
- super.collectionPhase(phaseId, primary);
- }
-
- /****************************************************************************
- *
- * Miscellaneous
- */
-
- /** @return The active global plan as a <code>Gen</code> instance. */
- @Inline
- private static Gen global() {
- return (Gen) VM.activePlan.global();
- }
-
- public final TraceLocal getCurrentTrace() {
- if (global().traceFullHeap()) return getFullHeapTrace();
- return nurseryTrace;
- }
-
- /** @return The trace to use when collecting the mature space */
- public abstract TraceLocal getFullHeapTrace();
-
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/plan/generational/GenConstraints.java b/vmkit/mmtk/java/src/org/mmtk/plan/generational/GenConstraints.java
deleted file mode 100644
index 5c3a9f0..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/plan/generational/GenConstraints.java
+++ /dev/null
@@ -1,82 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.plan.generational;
-
-import org.mmtk.plan.StopTheWorldConstraints;
-
-import org.mmtk.policy.CopySpace;
-import org.mmtk.policy.Space;
-
-import org.vmmagic.pragma.*;
-
-/**
- * This class and its subclasses communicate to the host VM/Runtime
- * any features of the selected plan that it needs to know. This is
- * separate from the main Plan/PlanLocal class in order to bypass any
- * issues with ordering of static initialization.
- */
-@Uninterruptible
-public class GenConstraints extends StopTheWorldConstraints {
-
- /** @return True if this plan is generational. */
- @Override
- public boolean generational() { return true; }
-
- /** @return True if this plan moves objects. */
- @Override
- public boolean movesObjects() { return true; }
-
- /** @return The number of header bits that are required. */
- @Override
- public int gcHeaderBits() { return CopySpace.LOCAL_GC_BITS_REQUIRED; }
-
- /** @return The number of header words that are required. */
- @Override
- public int gcHeaderWords() { return CopySpace.GC_HEADER_WORDS_REQUIRED; }
-
- /** @return True if this plan requires a write barrier */
- @Override
- public boolean needsObjectReferenceWriteBarrier() { return true; }
-
- /** @return True if this plan requires a static barrier */
- @Override
- public boolean needsObjectReferenceNonHeapWriteBarrier() { return Gen.USE_NON_HEAP_OBJECT_REFERENCE_WRITE_BARRIER; }
-
- /** @return True if this Plan can perform bulk object arraycopy barriers. */
- @Override
- public boolean objectReferenceBulkCopySupported() { return true; }
-
- /** @return The specialized scan methods required */
- @Override
- public int numSpecializedScans() { return 2; }
-
- /** @return True if this Plan requires a header bit for object logging */
- @Override
- public boolean needsLogBitInHeader() { return Gen.USE_OBJECT_BARRIER; }
-
- /**
- * @return The maximum size of an object that may be allocated directly into the nursery
- */
- @Override
- public int maxNonLOSDefaultAllocBytes() {
- /*
- * If the nursery is discontiguous, the maximum object is essentially unbounded. In
- * a contiguous nursery, we can't attempt to nursery-allocate objects larger than the
- * available nursery virtual memory.
- */
- return Gen.USE_DISCONTIGUOUS_NURSERY ?
- org.mmtk.utility.Constants.MAX_INT :
- Space.getFracAvailable(Gen.NURSERY_VM_FRACTION).toInt();
- }
-
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/plan/generational/GenMatureTraceLocal.java b/vmkit/mmtk/java/src/org/mmtk/plan/generational/GenMatureTraceLocal.java
deleted file mode 100644
index 94cb0bf..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/plan/generational/GenMatureTraceLocal.java
+++ /dev/null
@@ -1,140 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.plan.generational;
-
-import org.mmtk.plan.TraceLocal;
-import org.mmtk.plan.Trace;
-import org.mmtk.utility.HeaderByte;
-import org.mmtk.utility.deque.*;
-
-import org.mmtk.vm.VM;
-
-import org.vmmagic.unboxed.*;
-import org.vmmagic.pragma.*;
-
-/**
- * This abstract class implments the core functionality for a transitive
- * closure over the heap graph.
- */
-@Uninterruptible
-public abstract class GenMatureTraceLocal extends TraceLocal {
-
- /****************************************************************************
- *
- * Instance fields.
- */
- private final ObjectReferenceDeque modbuf;
- private final AddressDeque remset;
- private final AddressPairDeque arrayRemset;
-
- /****************************************************************************
- *
- * Initialization
- */
-
- /**
- * Constructor
- */
- public GenMatureTraceLocal(int specializedScan, Trace trace, GenCollector plan) {
- super(specializedScan, trace);
- this.modbuf = plan.modbuf;
- this.remset = plan.remset;
- this.arrayRemset = plan.arrayRemset;
- }
-
- /**
- * Constructor
- */
- public GenMatureTraceLocal(Trace trace, GenCollector plan) {
- super(Gen.SCAN_MATURE, trace);
- this.modbuf = plan.modbuf;
- this.remset = plan.remset;
- this.arrayRemset = plan.arrayRemset;
- }
-
- /****************************************************************************
- *
- * Object processing and tracing
- */
-
- /**
- * Is the specified object live?
- *
- * @param object The object.
- * @return True if the object is live.
- */
- @Inline
- public boolean isLive(ObjectReference object) {
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(!object.isNull());
- if (Gen.inNursery(object)) {
- return Gen.nurserySpace.isLive(object);
- }
- return super.isLive(object);
- }
-
- /**
- * Return true if this object is guaranteed not to move during this
- * collection (i.e. this object is defintely not an unforwarded
- * object).
- *
- * @param object
- * @return True if this object is guaranteed not to move during this
- * collection.
- */
- public boolean willNotMoveInCurrentCollection(ObjectReference object) {
- if (Gen.inNursery(object))
- return false;
- else
- return super.willNotMoveInCurrentCollection(object);
- }
-
- /**
- * This method is the core method during the trace of the object graph.
- * The role of this method is to:
- *
- * 1. Ensure the traced object is not collected.
- * 2. If this is the first visit to the object enqueue it to be scanned.
- * 3. Return the forwarded reference to the object.
- *
- * @param object The object to be traced.
- * @return The new reference to the same object instance.
- */
- @Inline
- public ObjectReference traceObject(ObjectReference object) {
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(!object.isNull());
- if (Gen.inNursery(object))
- return Gen.nurserySpace.traceObject(this, object, Gen.ALLOC_MATURE_MAJORGC);
- return super.traceObject(object);
- }
-
- /**
- * Process any remembered set entries.
- */
- protected void processRememberedSets() {
- logMessage(5, "clearing modbuf");
- ObjectReference obj;
- while (!(obj = modbuf.pop()).isNull()) {
- HeaderByte.markAsUnlogged(obj);
- }
- logMessage(5, "clearing remset");
- while (!remset.isEmpty()) {
- remset.pop();
- }
- logMessage(5, "clearing array remset");
- while (!arrayRemset.isEmpty()) {
- arrayRemset.pop1();
- arrayRemset.pop2();
- }
- }
-
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/plan/generational/GenMutator.java b/vmkit/mmtk/java/src/org/mmtk/plan/generational/GenMutator.java
deleted file mode 100644
index b8a1d23..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/plan/generational/GenMutator.java
+++ /dev/null
@@ -1,350 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.plan.generational;
-
-import org.mmtk.plan.*;
-import org.mmtk.policy.CopyLocal;
-import org.mmtk.policy.Space;
-import org.mmtk.utility.HeaderByte;
-import org.mmtk.utility.deque.*;
-import org.mmtk.utility.alloc.Allocator;
-import org.mmtk.utility.statistics.Stats;
-import org.mmtk.vm.VM;
-import static org.mmtk.plan.generational.Gen.USE_OBJECT_BARRIER_FOR_AASTORE;
-import static org.mmtk.plan.generational.Gen.USE_OBJECT_BARRIER_FOR_PUTFIELD;
-
-import org.vmmagic.pragma.*;
-import org.vmmagic.unboxed.*;
-
-/**
- * This abstract class implements <i>per-mutator thread</i> behavior
- * and state for <i>generational copying collectors</i>.<p>
- *
- * Specifically, this class defines mutator-time allocation into the nursery;
- * write barrier semantics, and per-mutator thread collection semantics
- * (flushing and restoring per-mutator allocator and remset state).
- *
- * @see Gen
- * @see GenCollector
- * @see StopTheWorldMutator
- * @see MutatorContext
- */
-@Uninterruptible public class GenMutator extends StopTheWorldMutator {
-
- /*****************************************************************************
- *
- * Instance fields
- */
- protected final CopyLocal nursery = new CopyLocal(Gen.nurserySpace);
-
- private final ObjectReferenceDeque modbuf; /* remember modified scalars */
- protected final WriteBuffer remset; /* remember modified array fields */
- protected final AddressPairDeque arrayRemset; /* remember modified array ranges */
-
- /****************************************************************************
- *
- * Initialization
- */
-
- /**
- * Constructor
- *
- * Note that each mutator is a producer of remsets, while each
- * collector is a consumer. The <code>GenCollector</code> class
- * is responsible for construction of the consumer.
- * @see GenCollector
- */
- public GenMutator() {
- modbuf = new ObjectReferenceDeque("modbuf", global().modbufPool);
- remset = new WriteBuffer(global().remsetPool);
- arrayRemset = new AddressPairDeque(global().arrayRemsetPool);
- }
-
- /****************************************************************************
- *
- * Mutator-time allocation
- */
-
- /**
- * Allocate memory for an object.
- *
- * @param bytes The number of bytes required for the object.
- * @param align Required alignment for the object.
- * @param offset Offset associated with the alignment.
- * @param allocator The allocator associated with this request.
- * @param site Allocation site
- * @return The low address of the allocated memory.
- */
- @Inline
- public Address alloc(int bytes, int align, int offset, int allocator, int site) {
- if (allocator == Gen.ALLOC_NURSERY) {
- if (Stats.GATHER_MARK_CONS_STATS) Gen.nurseryCons.inc(bytes);
- return nursery.alloc(bytes, align, offset);
- }
- return super.alloc(bytes, align, offset, allocator, site);
- }
-
- /**
- * Perform post-allocation actions. For many allocators none are
- * required.
- *
- * @param ref The newly allocated object
- * @param typeRef the type reference for the instance being created
- * @param bytes The size of the space to be allocated (in bytes)
- * @param allocator The allocator number to be used for this allocation
- */
- @Inline
- public void postAlloc(ObjectReference ref, ObjectReference typeRef,
- int bytes, int allocator) {
- if (allocator != Gen.ALLOC_NURSERY) {
- super.postAlloc(ref, typeRef, bytes, allocator);
- }
- }
-
- /**
- * Return the allocator instance associated with a space
- * <code>space</code>, for this plan instance.
- *
- * @param space The space for which the allocator instance is desired.
- * @return The allocator instance associated with this plan instance
- * which is allocating into <code>space</code>, or <code>null</code>
- * if no appropriate allocator can be established.
- */
- public Allocator getAllocatorFromSpace(Space space) {
- if (space == Gen.nurserySpace) return nursery;
- return super.getAllocatorFromSpace(space);
- }
-
- /****************************************************************************
- *
- * Barriers
- */
-
- /**
- * Perform the write barrier fast path, which may involve remembering
- * a reference if necessary.
- *
- * @param src The object into which the new reference will be stored
- * @param slot The address into which the new reference will be
- * stored.
- * @param tgt The target of the new reference
- * @param mode The mode of the store (eg putfield, putstatic etc)
- */
- @Inline
- private void fastPath(ObjectReference src, Address slot, ObjectReference tgt, int mode) {
- if (Gen.GATHER_WRITE_BARRIER_STATS) Gen.wbFast.inc();
- if ((mode == ARRAY_ELEMENT && USE_OBJECT_BARRIER_FOR_AASTORE) ||
- (mode == INSTANCE_FIELD && USE_OBJECT_BARRIER_FOR_PUTFIELD)) {
- if (HeaderByte.isUnlogged(src)) {
- if (Gen.GATHER_WRITE_BARRIER_STATS) Gen.wbSlow.inc();
- HeaderByte.markAsLogged(src);
- modbuf.insert(src);
- }
- } else {
- if (!Gen.inNursery(slot) && Gen.inNursery(tgt)) {
- if (Gen.GATHER_WRITE_BARRIER_STATS) Gen.wbSlow.inc();
- remset.insert(slot);
- }
- }
- }
-
- /**
- * A new reference is about to be created. Take appropriate write
- * barrier actions.<p>
- *
- * In this case, we remember the address of the source of the
- * pointer if the new reference points into the nursery from
- * non-nursery space.
- *
- * @param src The object into which the new reference will be stored
- * @param slot The address into which the new reference will be
- * stored.
- * @param tgt The target of the new reference
- * @param metaDataA A value that assists the host VM in creating a store
- * @param metaDataB A value that assists the host VM in creating a store
- * @param mode The mode of the store (eg putfield, putstatic etc)
- */
- @Inline
- public final void objectReferenceWrite(ObjectReference src, Address slot,
- ObjectReference tgt, Word metaDataA,
- Word metaDataB, int mode) {
- fastPath(src, slot, tgt, mode);
- VM.barriers.objectReferenceWrite(src, tgt, metaDataA, metaDataB, mode);
- }
-
-
- /**
- * Perform the root write barrier fast path, which may involve remembering
- * a reference if necessary.
- *
- * @param slot The address into which the new reference will be
- * stored.
- * @param tgt The target of the new reference
- * @param mode The mode of the store (eg putfield, putstatic etc)
- */
- @Inline
- private void fastPath(Address slot, ObjectReference tgt) {
- if (Gen.GATHER_WRITE_BARRIER_STATS) Gen.wbFast.inc();
- if (Gen.inNursery(tgt)) {
- if (Gen.GATHER_WRITE_BARRIER_STATS) Gen.wbSlow.inc();
- remset.insert(slot);
- }
- }
-
- /**
- * A new reference is about to be created in a location that is not
- * a regular heap object. Take appropriate write barrier actions.<p>
- *
- * In this case, we remember the address of the source of the
- * pointer if the new reference points into the nursery from
- * non-nursery space.
- *
- * @param slot The address into which the new reference will be
- * stored.
- * @param tgt The target of the new reference
- * @param metaDataA A value that assists the host VM in creating a store
- * @param metaDataB A value that assists the host VM in creating a store
- */
- @Inline
- public final void objectReferenceNonHeapWrite(Address slot, ObjectReference tgt,
- Word metaDataA, Word metaDataB) {
- fastPath(slot, tgt);
- VM.barriers.objectReferenceNonHeapWrite(slot, tgt, metaDataA, metaDataB);
- }
-
- /**
- * Attempt to atomically exchange the value in the given slot
- * with the passed replacement value. If a new reference is
- * created, we must then take appropriate write barrier actions.<p>
- *
- * In this case, we remember the address of the source of the
- * pointer if the new reference points into the nursery from
- * non-nursery space.
- *
- * @param src The object into which the new reference will be stored
- * @param slot The address into which the new reference will be
- * stored.
- * @param old The old reference to be swapped out
- * @param tgt The target of the new reference
- * @param metaDataA A value that assists the host VM in creating a store
- * @param metaDataB A value that assists the host VM in creating a store
- * @param mode The context in which the store occured
- * @return True if the swap was successful.
- */
- @Inline
- public boolean objectReferenceTryCompareAndSwap(ObjectReference src, Address slot, ObjectReference old, ObjectReference tgt,
- Word metaDataA, Word metaDataB, int mode) {
- boolean result = VM.barriers.objectReferenceTryCompareAndSwap(src, old, tgt, metaDataA, metaDataB, mode);
- if (result)
- fastPath(src, slot, tgt, mode);
- return result;
- }
-
- /**
- * A number of references are about to be copied from object
- * <code>src</code> to object <code>dst</code> (as in an array
- * copy). Thus, <code>dst</code> is the mutated object. Take
- * appropriate write barrier actions.<p>
- *
- * In this case, we remember the mutated source address range and
- * will scan that address range at GC time.
- *
- * @param src The source of the values to be copied
- * @param srcIdx The starting source index
- * @param dst The mutated object, i.e. the destination of the copy.
- * @param srcIdx The starting source index
- * @param len The number of array elements to be copied
- * @return True if the update was performed by the barrier, false if
- * left to the caller (always false in this case).
- */
- @Inline
- @Override
- public final boolean objectReferenceBulkCopy(ObjectReference src, Offset srcOffset, ObjectReference dst, Offset dstOffset, int bytes) {
- if (!Gen.inNursery(dst)) {
- Address start = dst.toAddress().plus(dstOffset);
- arrayRemset.insert(start, start.plus(bytes));
- }
- return false;
- }
-
- /**
- * Flush per-mutator remembered sets into the global remset pool.
- */
- public final void flushRememberedSets() {
- modbuf.flushLocal();
- remset.flushLocal();
- arrayRemset.flushLocal();
- assertRemsetsFlushed();
- }
-
- /**
- * Assert that the remsets have been flushed. This is critical to
- * correctness. We need to maintain the invariant that remset entries
- * do not accrue during GC. If the host JVM generates barrier entires
- * it is its own responsibility to ensure that they are flushed before
- * returning to MMTk.
- */
- public final void assertRemsetsFlushed() {
- if (VM.VERIFY_ASSERTIONS) {
- VM.assertions._assert(modbuf.isFlushed());
- VM.assertions._assert(remset.isFlushed());
- VM.assertions._assert(arrayRemset.isFlushed());
- }
- }
-
- /****************************************************************************
- *
- * Collection
- */
-
- /**
- * Perform a per-mutator collection phase.
- */
- @NoInline
- public void collectionPhase(short phaseId, boolean primary) {
-
- if (phaseId == Gen.PREPARE) {
- nursery.reset();
- if (global().traceFullHeap()) {
- super.collectionPhase(phaseId, primary);
- modbuf.flushLocal();
- remset.resetLocal();
- arrayRemset.resetLocal();
- } else {
- flushRememberedSets();
- }
- return;
- }
-
- if (phaseId == Gen.RELEASE) {
- if (global().traceFullHeap()) {
- super.collectionPhase(phaseId, primary);
- }
- assertRemsetsFlushed();
- return;
- }
-
- super.collectionPhase(phaseId, primary);
- }
-
- /****************************************************************************
- *
- * Miscellaneous
- */
-
- /** @return The active global plan as a <code>Gen</code> instance. */
- @Inline
- private static Gen global() {
- return (Gen) VM.activePlan.global();
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/plan/generational/GenNurseryTraceLocal.java b/vmkit/mmtk/java/src/org/mmtk/plan/generational/GenNurseryTraceLocal.java
deleted file mode 100644
index d364525..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/plan/generational/GenNurseryTraceLocal.java
+++ /dev/null
@@ -1,131 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.plan.generational;
-
-import org.mmtk.plan.TraceLocal;
-import org.mmtk.plan.Trace;
-import org.mmtk.utility.HeaderByte;
-import org.mmtk.utility.deque.*;
-import org.mmtk.vm.VM;
-
-import org.vmmagic.pragma.*;
-import org.vmmagic.unboxed.*;
-
-/**
- * This class implments the core functionality for a transitive
- * closure over the heap graph.
- */
-@Uninterruptible
-public final class GenNurseryTraceLocal extends TraceLocal {
-
- /****************************************************************************
- *
- * Instance fields.
- */
- private final ObjectReferenceDeque modbuf;
- private final AddressDeque remset;
- private final AddressPairDeque arrayRemset;
-
-
- /**
- * Constructor
- */
- public GenNurseryTraceLocal(Trace trace, GenCollector plan) {
- super(Gen.SCAN_NURSERY, trace);
- this.modbuf = plan.modbuf;
- this.remset = plan.remset;
- this.arrayRemset = plan.arrayRemset;
- }
-
- /****************************************************************************
- *
- * Externally visible Object processing and tracing
- */
-
- /**
- * Is the specified object live?
- *
- * @param object The object.
- * @return True if the object is live.
- */
- public boolean isLive(ObjectReference object) {
- if (object.isNull()) return false;
- if (Gen.inNursery(object)) {
- return Gen.nurserySpace.isLive(object);
- }
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(super.isLive(object));
- return true;
- }
-
- /**
- * This method is the core method during the trace of the object graph.
- * The role of this method is to:
- *
- * 1. Ensure the traced object is not collected.
- * 2. If this is the first visit to the object enqueue it to be scanned.
- * 3. Return the forwarded reference to the object.
- *
- * @param object The object to be traced.
- * @return The new reference to the same object instance.
- */
- @Inline
- public ObjectReference traceObject(ObjectReference object) {
- if (Gen.inNursery(object)) {
- return Gen.nurserySpace.traceObject(this, object, Gen.ALLOC_MATURE_MINORGC);
- }
- return object;
- }
-
- /**
- * Process any remembered set entries.
- */
- @Inline
- protected void processRememberedSets() {
- logMessage(5, "processing modbuf");
- ObjectReference obj;
- while (!(obj = modbuf.pop()).isNull()) {
- if (VM.DEBUG) VM.debugging.modbufEntry(obj);
- HeaderByte.markAsUnlogged(obj);
- scanObject(obj);
- }
- logMessage(5, "processing remset");
- while (!remset.isEmpty()) {
- Address loc = remset.pop();
- if (VM.DEBUG) VM.debugging.remsetEntry(loc);
- processRootEdge(loc, false);
- }
- logMessage(5, "processing array remset");
- arrayRemset.flushLocal();
- while (!arrayRemset.isEmpty()) {
- Address start = arrayRemset.pop1();
- Address guard = arrayRemset.pop2();
- if (VM.DEBUG) VM.debugging.arrayRemsetEntry(start,guard);
- while (start.LT(guard)) {
- processRootEdge(start, false);
- start = start.plus(BYTES_IN_ADDRESS);
- }
- }
- }
-
- /**
- * Will the object move from now on during the collection.
- *
- * @param object The object to query.
- * @return True if the object is guaranteed not to move.
- */
- public boolean willNotMoveInCurrentCollection(ObjectReference object) {
- if (object.isNull()) return false;
- return !Gen.inNursery(object);
- }
-
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/plan/generational/copying/GenCopy.java b/vmkit/mmtk/java/src/org/mmtk/plan/generational/copying/GenCopy.java
deleted file mode 100644
index d963383..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/plan/generational/copying/GenCopy.java
+++ /dev/null
@@ -1,232 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.plan.generational.copying;
-
-import org.mmtk.policy.CopySpace;
-import org.mmtk.policy.Space;
-import org.mmtk.plan.generational.*;
-import org.mmtk.plan.Trace;
-import org.mmtk.plan.TransitiveClosure;
-import org.mmtk.utility.heap.VMRequest;
-import org.mmtk.vm.VM;
-
-import org.vmmagic.pragma.*;
-
-/**
- * This class implements the functionality of a standard
- * two-generation copying collector. Nursery collections occur when
- * either the heap is full or the nursery is full. The nursery size
- * is determined by an optional command line argument. If undefined,
- * the nursery size is "infinite", so nursery collections only occur
- * when the heap is full (this is known as a flexible-sized nursery
- * collector). Thus both fixed and flexible nursery sizes are
- * supported. Full heap collections occur when the nursery size has
- * dropped to a statically defined threshold,
- * <code>NURSERY_THRESHOLD</code><p>
- *
- * See the Jones & Lins GC book, chapter 7 for a detailed discussion
- * of generational collection and section 7.3 for an overview of the
- * flexible nursery behavior ("The Standard ML of New Jersey
- * collector"), or go to Appel's paper "Simple generational garbage
- * collection and fast allocation." SP&E 19(2):171--183, 1989.<p>
- *
- * All plans make a clear distinction between <i>global</i> and
- * <i>thread-local</i> activities. Global activities must be
- * synchronized, whereas no synchronization is required for
- * thread-local activities. Instances of Plan map 1:1 to "kernel
- * threads" (aka CPUs). Thus instance
- * methods allow fast, unsychronized access to Plan utilities such as
- * allocation and collection. Each instance rests on static resources
- * (such as memory and virtual memory resources) which are "global"
- * and therefore "static" members of Plan. This mapping of threads to
- * instances is crucial to understanding the correctness and
- * performance proprties of this plan.
- */
-@Uninterruptible public class GenCopy extends Gen {
-
- /****************************************************************************
- *
- * Class variables
- */
-
- // GC state
- static boolean hi = false; // True if copying to "higher" semispace
-
- /**
- * The low half of the copying mature space. We allocate into this space
- * when <code>hi</code> is <code>false</code>.
- */
- static CopySpace matureSpace0 = new CopySpace("ss0", DEFAULT_POLL_FREQUENCY, false, VMRequest.create());
- static final int MS0 = matureSpace0.getDescriptor();
-
- /**
- * The high half of the copying mature space. We allocate into this space
- * when <code>hi</code> is <code>true</code>.
- */
- static CopySpace matureSpace1 = new CopySpace("ss1", DEFAULT_POLL_FREQUENCY, true, VMRequest.create());
- static final int MS1 = matureSpace1.getDescriptor();
-
-
- /****************************************************************************
- *
- * Instance fields
- */
- final Trace matureTrace;
-
- /**
- * Constructor
- */
- public GenCopy() {
- super();
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(!IGNORE_REMSETS); // Not supported for GenCopy
- matureTrace = new Trace(metaDataSpace);
- }
-
- /**
- * @return Does the mature space do copying ?
- */
- protected boolean copyMature() {
- return true;
- }
-
- /**
- * @return The semispace we are currently allocating into
- */
- static CopySpace toSpace() {
- return hi ? matureSpace1 : matureSpace0;
- }
-
- /**
- * @return Space descriptor for to-space.
- */
- static int toSpaceDesc() { return hi ? MS1 : MS0; }
-
- /**
- * @return The semispace we are currently copying from
- * (or copied from at last major GC)
- */
- static CopySpace fromSpace() {
- return hi ? matureSpace0 : matureSpace1;
- }
-
- /**
- * @return Space descriptor for from-space
- */
- static int fromSpaceDesc() { return hi ? MS0 : MS1; }
-
- /****************************************************************************
- *
- * Collection
- */
-
- /**
- * Perform a phase of the currently active collection.
- *
- * @param phaseId Collection phase to process
- */
- @Inline
- public void collectionPhase(short phaseId) {
- if (traceFullHeap()) {
- if (phaseId == PREPARE) {
- super.collectionPhase(phaseId);
- hi = !hi; // flip the semi-spaces
- matureSpace0.prepare(hi);
- matureSpace1.prepare(!hi);
- matureTrace.prepare();
- return;
- }
- if (phaseId == CLOSURE) {
- matureTrace.prepare();
- return;
- }
- if (phaseId == RELEASE) {
- matureTrace.release();
- fromSpace().release();
- super.collectionPhase(phaseId);
- return;
- }
- }
- super.collectionPhase(phaseId);
- }
-
- /*****************************************************************************
- *
- * Accounting
- */
-
- /**
- * Return the number of pages reserved for use given the pending
- * allocation.
- *
- * @return The number of pages reserved given the pending
- * allocation, excluding space reserved for copying.
- */
- @Inline
- public int getPagesUsed() {
- return toSpace().reservedPages() + super.getPagesUsed();
- }
-
- /**
- * Return the number of pages reserved for copying.
- *
- * @return the number of pages reserved for copying.
- */
- public final int getCollectionReserve() {
- // we must account for the number of pages required for copying,
- // which equals the number of semi-space pages reserved
- return toSpace().reservedPages() + super.getCollectionReserve();
- }
-
- /**
- * Calculate the number of pages a collection is required to free to satisfy
- * outstanding allocation requests.
- *
- * @return the number of pages a collection is required to free to satisfy
- * outstanding allocation requests.
- */
- public int getPagesRequired() {
- return super.getPagesRequired() + (toSpace().requiredPages() << 1);
- }
-
- /**
- * Return the number of pages available for allocation into the mature
- * space.
- *
- * @return The number of pages available for allocation into the mature
- * space.
- */
- public int getMaturePhysicalPagesAvail() {
- return toSpace().availablePhysicalPages() >> 1;
- }
-
- /**************************************************************************
- * Miscellaneous methods
- */
-
- /**
- * @return The mature space we are currently allocating into
- */
- @Inline
- public Space activeMatureSpace() {
- return toSpace();
- }
-
- /**
- * Register specialized methods.
- */
- @Interruptible
- protected void registerSpecializedMethods() {
- TransitiveClosure.registerSpecializedScan(SCAN_MATURE, GenCopyMatureTraceLocal.class);
- super.registerSpecializedMethods();
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/plan/generational/copying/GenCopyCollector.java b/vmkit/mmtk/java/src/org/mmtk/plan/generational/copying/GenCopyCollector.java
deleted file mode 100644
index b945e564..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/plan/generational/copying/GenCopyCollector.java
+++ /dev/null
@@ -1,172 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.plan.generational.copying;
-
-import org.mmtk.plan.generational.Gen;
-import org.mmtk.plan.generational.GenCollector;
-import org.mmtk.plan.Plan;
-import org.mmtk.plan.TraceLocal;
-import org.mmtk.policy.CopyLocal;
-import org.mmtk.utility.ForwardingWord;
-import org.mmtk.utility.HeaderByte;
-import org.mmtk.utility.alloc.Allocator;
-import org.mmtk.vm.VM;
-
-import org.vmmagic.unboxed.*;
-import org.vmmagic.pragma.*;
-
-/**
- * This class implements <i>per-collector thread</i> behavior and state for
- * the <code>GenCopy</code> two-generational copying collector.<p>
- *
- * Specifically, this class defines semantics specific to the collection of
- * the mature generation (<code>GenCollector</code> defines nursery semantics).
- * In particular the mature space allocator is defined (for collection-time
- * allocation into the mature space), and the mature space per-collector thread
- * collection time semantics are defined.<p>
- *
- * @see GenCopy for a description of the <code>GenCopy</code> algorithm.
- *
- * @see GenCopy
- * @see GenCopyMutator
- * @see GenCollector
- * @see org.mmtk.plan.StopTheWorldCollector
- * @see org.mmtk.plan.CollectorContext
- */
-@Uninterruptible
-public class GenCopyCollector extends GenCollector {
-
- /******************************************************************
- * Instance fields
- */
-
- /** The allocator for the mature space */
- private final CopyLocal mature;
-
- /** The trace object for full-heap collections */
- private final GenCopyMatureTraceLocal matureTrace;
-
- /****************************************************************************
- *
- * Initialization
- */
-
- /**
- * Constructor
- */
- public GenCopyCollector() {
- mature = new CopyLocal(GenCopy.toSpace());
- matureTrace = new GenCopyMatureTraceLocal(global().matureTrace, this);
- }
-
- /****************************************************************************
- *
- * Collection-time allocation
- */
-
- /**
- * Allocate space for copying an object (this method <i>does not</i>
- * copy the object, it only allocates space)
- *
- * @param original A reference to the original object
- * @param bytes The size of the space to be allocated (in bytes)
- * @param align The requested alignment.
- * @param offset The alignment offset.
- * @return The address of the first byte of the allocated region
- */
- @Inline
- public Address allocCopy(ObjectReference original, int bytes,
- int align, int offset, int allocator) {
- if (allocator == Plan.ALLOC_LOS) {
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(Allocator.getMaximumAlignedSize(bytes, align) > Plan.MAX_NON_LOS_COPY_BYTES);
- return los.alloc(bytes, align, offset);
- } else {
- if (VM.VERIFY_ASSERTIONS) {
- VM.assertions._assert(bytes <= Plan.MAX_NON_LOS_COPY_BYTES);
- VM.assertions._assert(allocator == GenCopy.ALLOC_MATURE_MINORGC ||
- allocator == GenCopy.ALLOC_MATURE_MAJORGC);
- }
- return mature.alloc(bytes, align, offset);
- }
- }
-
- /**
- * Perform any post-copy actions. In this case we clear any bits used
- * for this object's GC metadata.
- *
- * @param object The newly allocated object
- * @param typeRef the type reference for the instance being created
- * @param bytes The size of the space to be allocated (in bytes)
- * @param allocator The allocator to allocate from
- */
- @Inline
- public final void postCopy(ObjectReference object, ObjectReference typeRef,
- int bytes, int allocator) {
- ForwardingWord.clearForwardingBits(object);
- if (allocator == Plan.ALLOC_LOS)
- Plan.loSpace.initializeHeader(object, false);
- else if (GenCopy.IGNORE_REMSETS)
- GenCopy.immortalSpace.traceObject(getCurrentTrace(), object); // FIXME this does not look right
- if (Gen.USE_OBJECT_BARRIER)
- HeaderByte.markAsUnlogged(object);
- }
-
-
- /*****************************************************************************
- *
- * Collection
- */
-
- /**
- * Execute a per-collector collection phase.
- *
- * @param phaseId The phase to execute.
- * @param primary True if this thread should peform local single-threaded
- * actions.
- */
- public void collectionPhase(short phaseId, boolean primary) {
- if (global().traceFullHeap()) {
- if (phaseId == GenCopy.PREPARE) {
- super.collectionPhase(phaseId, primary);
- if (global().gcFullHeap) mature.rebind(GenCopy.toSpace());
- }
- if (phaseId == GenCopy.CLOSURE) {
- matureTrace.completeTrace();
- return;
- }
- if (phaseId == GenCopy.RELEASE) {
- matureTrace.release();
- super.collectionPhase(phaseId, primary);
- return;
- }
- }
- super.collectionPhase(phaseId, primary);
- }
-
- /*****************************************************************************
- *
- * Miscellaneous
- */
-
- /** @return The active global plan as a <code>GenCopy</code> instance. */
- private static GenCopy global() {
- return (GenCopy) VM.activePlan.global();
- }
-
- /** Show the status of the mature allocator. */
- protected final void showMature() {
- mature.show();
- }
-
- public final TraceLocal getFullHeapTrace() { return matureTrace; }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/plan/generational/copying/GenCopyConstraints.java b/vmkit/mmtk/java/src/org/mmtk/plan/generational/copying/GenCopyConstraints.java
deleted file mode 100644
index 9396b58..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/plan/generational/copying/GenCopyConstraints.java
+++ /dev/null
@@ -1,22 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.plan.generational.copying;
-
-import org.mmtk.plan.generational.GenConstraints;
-import org.vmmagic.pragma.*;
-
-/**
- * GenCopy constants.
- */
-@Uninterruptible public class GenCopyConstraints extends GenConstraints {
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/plan/generational/copying/GenCopyMatureTraceLocal.java b/vmkit/mmtk/java/src/org/mmtk/plan/generational/copying/GenCopyMatureTraceLocal.java
deleted file mode 100644
index 6e4809c..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/plan/generational/copying/GenCopyMatureTraceLocal.java
+++ /dev/null
@@ -1,105 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.plan.generational.copying;
-
-import org.mmtk.plan.generational.Gen;
-import org.mmtk.plan.generational.GenCollector;
-import org.mmtk.plan.generational.GenMatureTraceLocal;
-import org.mmtk.plan.Trace;
-import org.mmtk.policy.Space;
-
-import org.mmtk.vm.VM;
-
-import org.vmmagic.pragma.*;
-import org.vmmagic.unboxed.*;
-
-/**
- * This class implments the core functionality for a transitive
- * closure over the heap graph, specifically in a Generational copying
- * collector.
- */
-@Uninterruptible
-public final class GenCopyMatureTraceLocal extends GenMatureTraceLocal {
-
- /**
- * Constructor
- */
- public GenCopyMatureTraceLocal(Trace global, GenCollector plan) {
- super(global, plan);
- }
-
- private static GenCopy global() {
- return (GenCopy) VM.activePlan.global();
- }
-
- /**
- * Trace a reference into the mature space during GC. This involves
- * determining whether the instance is in from space, and if so,
- * calling the <code>traceObject</code> method of the Copy
- * collector.
- *
- * @param object The object reference to be traced. This is <i>NOT</i> an
- * interior pointer.
- * @return The possibly moved reference.
- */
- public ObjectReference traceObject(ObjectReference object) {
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(global().traceFullHeap());
- if (object.isNull()) return object;
-
- if (Space.isInSpace(GenCopy.MS0, object))
- return GenCopy.matureSpace0.traceObject(this, object, Gen.ALLOC_MATURE_MAJORGC);
- if (Space.isInSpace(GenCopy.MS1, object))
- return GenCopy.matureSpace1.traceObject(this, object, Gen.ALLOC_MATURE_MAJORGC);
- return super.traceObject(object);
- }
-
- /**
- * Return true if <code>obj</code> is a live object.
- *
- * @param object The object in question
- * @return True if <code>obj</code> is a live object.
- */
- public boolean isLive(ObjectReference object) {
- if (object.isNull()) return false;
- if (Space.isInSpace(GenCopy.MS0, object))
- return GenCopy.hi ? GenCopy.matureSpace0.isLive(object) : true;
- if (Space.isInSpace(GenCopy.MS1, object))
- return GenCopy.hi ? true : GenCopy.matureSpace1.isLive(object);
- return super.isLive(object);
- }
-
- /****************************************************************************
- *
- * Object processing and tracing
- */
-
-
- /**
- * Return true if this object is guaranteed not to move during this
- * collection (i.e. this object is defintely not an unforwarded
- * object).
- *
- * @param object
- * @return True if this object is guaranteed not to move during this
- * collection.
- */
- public boolean willNotMoveInCurrentCollection(ObjectReference object) {
- if (Space.isInSpace(GenCopy.toSpaceDesc(), object)) {
- return true;
- }
- if (Space.isInSpace(GenCopy.fromSpaceDesc(), object)) {
- return false;
- }
- return super.willNotMoveInCurrentCollection(object);
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/plan/generational/copying/GenCopyMutator.java b/vmkit/mmtk/java/src/org/mmtk/plan/generational/copying/GenCopyMutator.java
deleted file mode 100644
index 21d2be0..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/plan/generational/copying/GenCopyMutator.java
+++ /dev/null
@@ -1,165 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.plan.generational.copying;
-
-import org.mmtk.plan.generational.GenMutator;
-import org.mmtk.policy.CopyLocal;
-import org.mmtk.policy.Space;
-import org.mmtk.utility.alloc.Allocator;
-import org.mmtk.vm.VM;
-
-import org.vmmagic.unboxed.*;
-import org.vmmagic.pragma.*;
-
-/**
- * This class implements <i>per-mutator thread</i> behavior and state for
- * the <code>GenCopy</code> two-generational copying collector.<p>
- *
- * Specifically, this class defines mutator-time semantics specific to the
- * mature generation (<code>GenMutator</code> defines nursery semantics).
- * In particular the mature space allocator is defined (for mutator-time
- * allocation into the mature space via pre-tenuring), and the mature space
- * per-mutator thread collection time semantics are defined (rebinding
- * the mature space allocator).<p>
- *
- * @see GenCopy for a description of the <code>GenCopy</code> algorithm.
- *
- * @see GenCopy
- * @see GenCopyCollector
- * @see GenMutator
- * @see org.mmtk.plan.StopTheWorldMutator
- * @see org.mmtk.plan.MutatorContext
- */
-@Uninterruptible
-public class GenCopyMutator extends GenMutator {
- /******************************************************************
- * Instance fields
- */
-
- /**
- * The allocator for the copying mature space (the mutator may
- * "pretenure" objects into this space otherwise used only by
- * the collector)
- */
- private CopyLocal mature;
-
- /****************************************************************************
- *
- * Initialization
- */
-
- /**
- * Constructor
- */
- public GenCopyMutator() {
- mature = new CopyLocal();
- }
-
- /**
- * Called before the MutatorContext is used, but after the context has been
- * fully registered and is visible to collection.
- */
- public void initMutator(int id) {
- super.initMutator(id);
- mature.rebind(GenCopy.toSpace());
- }
-
- /****************************************************************************
- *
- * Mutator-time allocation
- */
-
- /**
- * Allocate space (for an object) in the specified space
- *
- * @param bytes The size of the space to be allocated (in bytes)
- * @param align The requested alignment.
- * @param offset The alignment offset.
- * @param allocator The allocator to allocate from
- * @param site Allocation site
- * @return The address of the first byte of the allocated region
- */
- @Inline
- public final Address alloc(int bytes, int align, int offset, int allocator, int site) {
- if (allocator == GenCopy.ALLOC_MATURE) {
- return mature.alloc(bytes, align, offset);
- }
- return super.alloc(bytes, align, offset, allocator, site);
- }
-
- /**
- * Perform post-allocation initialization of an object
- *
- * @param object The newly allocated object
- * @param typeRef the type reference for the instance being created
- * @param allocator The allocator to allocate from
- * @param bytes The size of the space allocated (in bytes)
- */
- @Inline
- public final void postAlloc(ObjectReference object, ObjectReference typeRef,
- int bytes, int allocator) {
- // nothing to be done
- if (allocator == GenCopy.ALLOC_MATURE) return;
- super.postAlloc(object, typeRef, bytes, allocator);
- }
-
- /**
- * Return the allocator instance associated with a space
- * <code>space</code>, for this plan instance.
- *
- * @param space The space for which the allocator instance is desired.
- * @return The allocator instance associated with this plan instance
- * which is allocating into <code>space</code>, or <code>null</code>
- * if no appropriate allocator can be established.
- */
- public final Allocator getAllocatorFromSpace(Space space) {
- if (space == GenCopy.matureSpace0 || space == GenCopy.matureSpace1) return mature;
- return super.getAllocatorFromSpace(space);
- }
-
-
- /*****************************************************************************
- *
- * Collection
- */
-
- /**
- * Execute a per-mutator collection phase.
- *
- * @param phaseId The phase to execute.
- * @param primary True if this thread should peform local single-threaded
- * actions.
- */
- public void collectionPhase(short phaseId, boolean primary) {
- if (global().traceFullHeap()) {
- if (phaseId == GenCopy.RELEASE) {
- super.collectionPhase(phaseId, primary);
- if (global().gcFullHeap) mature.rebind(GenCopy.toSpace());
- return;
- }
- }
-
- super.collectionPhase(phaseId, primary);
- }
-
- /*****************************************************************************
- *
- * Miscellaneous
- */
-
- /** @return The active global plan as a <code>GenCopy</code> instance. */
- private static GenCopy global() {
- return (GenCopy) VM.activePlan.global();
- }
-
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/plan/generational/immix/GenImmix.java b/vmkit/mmtk/java/src/org/mmtk/plan/generational/immix/GenImmix.java
deleted file mode 100644
index 236fa98..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/plan/generational/immix/GenImmix.java
+++ /dev/null
@@ -1,196 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.plan.generational.immix;
-
-import org.mmtk.plan.generational.Gen;
-import org.mmtk.plan.Trace;
-import org.mmtk.plan.TransitiveClosure;
-import org.mmtk.policy.immix.ImmixSpace;
-import org.mmtk.policy.immix.ObjectHeader;
-import org.mmtk.policy.Space;
-import org.mmtk.utility.heap.VMRequest;
-
-import org.vmmagic.pragma.*;
-import org.vmmagic.unboxed.*;
-
-/**
- * This class implements the functionality of a two-generation copying
- * collector where <b>the higher generation is an immix space</b>.
- *
- * Nursery collections occur when either the heap is full or the nursery
- * is full. The nursery size is determined by an optional command line
- * argument. If undefined, the nursery size is "infinite", so nursery
- * collections only occur when the heap is full (this is known as a
- * flexible-sized nursery collector). Thus both fixed and flexible
- * nursery sizes are supported. Full heap collections occur when the
- * nursery size has dropped to a statically defined threshold,
- * <code>NURSERY_THRESHOLD</code><p>
- *
- * See the PLDI'08 paper by Blackburn and McKinley for a description
- * of the algorithm: http://doi.acm.org/10.1145/1375581.1375586
- *
- * See the Jones & Lins GC book, chapter 7 for a detailed discussion
- * of generational collection and section 7.3 for an overview of the
- * flexible nursery behavior ("The Standard ML of New Jersey
- * collector"), or go to Appel's paper "Simple generational garbage
- * collection and fast allocation." SP&E 19(2):171--183, 1989.<p>
- *
- *
- * For general comments about the global/local distinction among classes refer
- * to Plan.java and PlanLocal.java.
- */
-@Uninterruptible
-public class GenImmix extends Gen {
-
- /*****************************************************************************
- *
- * Class fields
- */
-
- /** The mature space, which for GenImmix uses a mark sweep collection policy. */
- public static final ImmixSpace immixSpace = new ImmixSpace("immix", DEFAULT_POLL_FREQUENCY, VMRequest.create());
-
- public static final int IMMIX = immixSpace.getDescriptor();
-
- public static final int SCAN_IMMIX = 1;
- public static final int SCAN_DEFRAG = 2;
-
- /****************************************************************************
- *
- * Instance fields
- */
- /* The trace class for a full-heap collection */
- public final Trace matureTrace = new Trace(metaDataSpace);
- private boolean lastGCWasDefrag = false;
-
- /*****************************************************************************
- *
- * Collection
- */
-
- /**
- * Perform a (global) collection phase.
- */
- @Inline
- @Override
- public final void collectionPhase(short phaseId) {
- if (phaseId == SET_COLLECTION_KIND) {
- super.collectionPhase(phaseId);
- if (gcFullHeap)
- immixSpace.decideWhetherToDefrag(emergencyCollection, true, collectionAttempt, collectionTrigger);
- return;
- }
-
- if (traceFullHeap()) {
- if (phaseId == PREPARE) {
- super.collectionPhase(phaseId);
- matureTrace.prepare();
- immixSpace.prepare(true);
- return;
- }
-
- if (phaseId == CLOSURE) {
- matureTrace.prepare();
- return;
- }
-
- if (phaseId == RELEASE) {
- matureTrace.release();
- lastGCWasDefrag = immixSpace.release(true);
- super.collectionPhase(phaseId);
- return;
- }
- } else
- lastGCWasDefrag = false;
-
- super.collectionPhase(phaseId);
- }
-
- /**
- * @return Whether last GC was an exhaustive attempt to collect the heap. For many collectors this is the same as asking whether the last GC was a full heap collection.
- */
- @Override
- public boolean lastCollectionWasExhaustive() {
- return lastGCWasDefrag;
- }
-
- /*****************************************************************************
- *
- * Accounting
- */
-
- /**
- * Return the number of pages reserved for use given the pending
- * allocation.
- *
- * @return The number of pages reserved given the pending
- * allocation, excluding space reserved for copying.
- */
- @Inline
- @Override
- public int getPagesUsed() {
- return immixSpace.reservedPages() + super.getPagesUsed();
- }
-
- /**
- * Return the number of pages available for allocation into the mature
- * space.
- *
- * @return The number of pages available for allocation into the mature
- * space.
- */
- public int getMaturePhysicalPagesAvail() {
- return immixSpace.availablePhysicalPages();
- }
-
- /*****************************************************************************
- *
- * Miscellaneous
- */
-
- /**
- * Accessor method to allow the generic generational code in Gen.java
- * to access the mature space.
- *
- * @return The active mature space
- */
- @Inline
- protected final Space activeMatureSpace() {
- return immixSpace;
- }
-
- /**
- * @see org.mmtk.plan.Plan#willNeverMove
- *
- * @param object Object in question
- * @return true if the object will never move
- */
- @Override
- public boolean willNeverMove(ObjectReference object) {
- if (Space.isInSpace(IMMIX, object)) {
- ObjectHeader.pinObject(object);
- return true;
- } else
- return super.willNeverMove(object);
- }
-
- /**
- * Register specialized methods.
- */
- @Interruptible
- protected void registerSpecializedMethods() {
- TransitiveClosure.registerSpecializedScan(SCAN_IMMIX, GenImmixMatureTraceLocal.class);
- TransitiveClosure.registerSpecializedScan(SCAN_DEFRAG, GenImmixMatureDefragTraceLocal.class);
- super.registerSpecializedMethods();
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/plan/generational/immix/GenImmixCollector.java b/vmkit/mmtk/java/src/org/mmtk/plan/generational/immix/GenImmixCollector.java
deleted file mode 100644
index 599a106..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/plan/generational/immix/GenImmixCollector.java
+++ /dev/null
@@ -1,187 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.plan.generational.immix;
-
-import org.mmtk.plan.Plan;
-import org.mmtk.plan.TraceLocal;
-import org.mmtk.plan.generational.*;
-import org.mmtk.policy.Space;
-import org.mmtk.utility.HeaderByte;
-import org.mmtk.utility.alloc.Allocator;
-import org.mmtk.utility.alloc.ImmixAllocator;
-import org.mmtk.utility.statistics.Stats;
-
-import org.mmtk.vm.VM;
-
-import org.vmmagic.pragma.*;
-import org.vmmagic.unboxed.*;
-
-/**
- * This class implements <i>per-collector thread</i> behavior and state for
- * the <code>GenImmix</code> two-generational copying collector.<p>
- *
- * Specifically, this class defines semantics specific to the collection of
- * the copy generation (<code>GenCollector</code> defines nursery semantics).
- * In particular the copy space allocator is defined (for collection-time
- * allocation into the copy space), and the copy space per-collector thread
- * collection time semantics are defined.<p>
- *
- * @see GenImmix for a description of the <code>GenImmix</code> algorithm.
- *
- * @see GenImmix
- * @see GenImmixMutator
- * @see GenCollector
- * @see org.mmtk.plan.StopTheWorldCollector
- * @see org.mmtk.plan.CollectorContext
- */
-@Uninterruptible
-public class GenImmixCollector extends GenCollector {
-
- /*****************************************************************************
- *
- * Instance fields
- */
- private final GenImmixMatureTraceLocal matureTrace = new GenImmixMatureTraceLocal(global().matureTrace, this);
- private final GenImmixMatureDefragTraceLocal defragTrace = new GenImmixMatureDefragTraceLocal(global().matureTrace, this);
-
- private final org.mmtk.policy.immix.CollectorLocal immix = new org.mmtk.policy.immix.CollectorLocal(GenImmix.immixSpace);
-
- private final ImmixAllocator copy = new ImmixAllocator(GenImmix.immixSpace, true, false);
- private final ImmixAllocator defragCopy = new ImmixAllocator(GenImmix.immixSpace, true, true);
-
- /****************************************************************************
- *
- * Collection-time allocation
- */
-
- /**
- * Allocate space for copying an object (this method <i>does not</i>
- * copy the object, it only allocates space)
- *
- * @param original A reference to the original object
- * @param bytes The size of the space to be allocated (in bytes)
- * @param align The requested alignment.
- * @param offset The alignment offset.
- * @param allocator The allocator to use.
- * @return The address of the first byte of the allocated region
- */
- @Inline
- public final Address allocCopy(ObjectReference original, int bytes,
- int align, int offset, int allocator) {
-
- if (Stats.GATHER_MARK_CONS_STATS) {
- if (Space.isInSpace(GenImmix.NURSERY, original)) GenImmix.nurseryMark.inc(bytes);
- }
- if (allocator == Plan.ALLOC_LOS) {
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(Allocator.getMaximumAlignedSize(bytes, align) > Plan.MAX_NON_LOS_COPY_BYTES);
- return los.alloc(bytes, align, offset);
- } else {
- if (VM.VERIFY_ASSERTIONS) {
- VM.assertions._assert(bytes <= Plan.MAX_NON_LOS_COPY_BYTES);
- if (GenImmix.immixSpace.inImmixCollection())
- VM.assertions._assert(allocator == GenImmix.ALLOC_MATURE_MAJORGC);
- else
- VM.assertions._assert(allocator == GenImmix.ALLOC_MATURE_MINORGC);
- }
- if (GenImmix.immixSpace.inImmixDefragCollection()) {
- return defragCopy.alloc(bytes, align, offset);
- } else
- return copy.alloc(bytes, align, offset);
- }
- }
-
- /**
- * Perform any post-copy actions.
- *
- * @param object The newly allocated object
- * @param typeRef the type reference for the instance being created
- * @param bytes The size of the space to be allocated (in bytes)
- */
- @Inline
- public final void postCopy(ObjectReference object, ObjectReference typeRef,
- int bytes, int allocator) {
- if (allocator == Plan.ALLOC_LOS)
- Plan.loSpace.initializeHeader(object, false);
- else {
- if (VM.VERIFY_ASSERTIONS) {
- VM.assertions._assert((!GenImmix.immixSpace.inImmixCollection() && allocator == GenImmix.ALLOC_MATURE_MINORGC) ||
- (GenImmix.immixSpace.inImmixCollection() && allocator == GenImmix.ALLOC_MATURE_MAJORGC));
- }
- GenImmix.immixSpace.postCopy(object, bytes, allocator == GenImmix.ALLOC_MATURE_MAJORGC);
- }
- if (Gen.USE_OBJECT_BARRIER)
- HeaderByte.markAsUnlogged(object);
- }
-
- /*****************************************************************************
- *
- * Collection
- */
-
- /**
- * Perform a (local) collection phase.
- *
- * @param phaseId Collection phase to perform
- * @param primary Is this thread to do the one-off thread-local tasks
- */
- @NoInline
- public void collectionPhase(short phaseId, boolean primary) {
- TraceLocal trace = GenImmix.immixSpace.inImmixDefragCollection() ? defragTrace : matureTrace;
-
- if (global().traceFullHeap()) {
- if (phaseId == GenImmix.PREPARE) {
- super.collectionPhase(phaseId, primary);
- trace.prepare();
- copy.reset();
- if (global().gcFullHeap) {
- immix.prepare(true);
- defragCopy.reset();
- }
- return;
- }
-
- if (phaseId == GenImmix.CLOSURE) {
- trace.completeTrace();
- return;
- }
-
- if (phaseId == GenImmix.RELEASE) {
- trace.release();
- if (global().gcFullHeap) {
- immix.release(true);
- copy.reset();
- }
- super.collectionPhase(phaseId, primary);
- return;
- }
- }
-
- super.collectionPhase(phaseId, primary);
- }
-
- @Inline
- public final TraceLocal getFullHeapTrace() {
- return GenImmix.immixSpace.inImmixDefragCollection() ? defragTrace : matureTrace;
- }
-
- /****************************************************************************
- *
- * Miscellaneous
- */
-
- /** @return The active global plan as a <code>GenImmix</code> instance. */
- @Inline
- private static GenImmix global() {
- return (GenImmix) VM.activePlan.global();
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/plan/generational/immix/GenImmixConstraints.java b/vmkit/mmtk/java/src/org/mmtk/plan/generational/immix/GenImmixConstraints.java
deleted file mode 100644
index bb79960..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/plan/generational/immix/GenImmixConstraints.java
+++ /dev/null
@@ -1,34 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.plan.generational.immix;
-
-import org.mmtk.plan.generational.GenConstraints;
-import static org.mmtk.policy.immix.ImmixConstants.MAX_IMMIX_OBJECT_BYTES;
-
-import org.vmmagic.pragma.*;
-
-/**
- * This class and its subclasses communicate to the host VM/Runtime
- * any features of the selected plan that it needs to know. This is
- * separate from the main Plan/PlanLocal class in order to bypass any
- * issues with ordering of static initialization.
- *
- */
-@Uninterruptible
-public class GenImmixConstraints extends GenConstraints {
- /** @return The specialized scan methods required */
- @Override
- public int numSpecializedScans() { return 3; }
- @Override
- public int maxNonLOSCopyBytes() { return MAX_IMMIX_OBJECT_BYTES;}
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/plan/generational/immix/GenImmixMatureDefragTraceLocal.java b/vmkit/mmtk/java/src/org/mmtk/plan/generational/immix/GenImmixMatureDefragTraceLocal.java
deleted file mode 100644
index 370bb50..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/plan/generational/immix/GenImmixMatureDefragTraceLocal.java
+++ /dev/null
@@ -1,125 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.plan.generational.immix;
-
-import static org.mmtk.policy.immix.ImmixConstants.MARK_LINE_AT_SCAN_TIME;
-
-import org.mmtk.plan.generational.GenCollector;
-import org.mmtk.plan.generational.GenMatureTraceLocal;
-import org.mmtk.plan.Trace;
-import org.mmtk.policy.Space;
-import org.mmtk.utility.Log;
-import org.mmtk.utility.options.Options;
-import org.mmtk.vm.VM;
-
-import org.vmmagic.unboxed.*;
-import org.vmmagic.pragma.*;
-
-/**
- * This class implments the core functionality for a transitive
- * closure over the heap graph, specifically in a defragmenting pass over
- * a generational immix collector.
- */
-@Uninterruptible
-public final class GenImmixMatureDefragTraceLocal extends GenMatureTraceLocal{
-
- /**
- * Constructor
- */
- public GenImmixMatureDefragTraceLocal(Trace global, GenCollector plan) {
- super(GenImmix.SCAN_DEFRAG, global, plan);
- }
-
- /**
- * Is the specified object live?
- *
- * @param object The object.
- * @return True if the object is live.
- */
- public boolean isLive(ObjectReference object) {
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(GenImmix.immixSpace.inImmixDefragCollection());
- if (object.isNull()) return false;
- if (Space.isInSpace(GenImmix.IMMIX, object)) {
- return GenImmix.immixSpace.isLive(object);
- }
- return super.isLive(object);
- }
-
- /**
- * This method is the core method during the trace of the object graph.
- * The role of this method is to:
- *
- * 1. Ensure the traced object is not collected.
- * 2. If this is the first visit to the object enqueue it to be scanned.
- * 3. Return the forwarded reference to the object.
- *
- * @param object The object to be traced.
- * @return The new reference to the same object instance.
- */
- @Inline
- public ObjectReference traceObject(ObjectReference object) {
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(GenImmix.immixSpace.inImmixDefragCollection());
- if (object.isNull()) return object;
- if (Space.isInSpace(GenImmix.IMMIX, object))
- return GenImmix.immixSpace.traceObject(this, object, GenImmix.ALLOC_MATURE_MAJORGC);
- return super.traceObject(object);
- }
-
- @Inline
- @Override
- public ObjectReference precopyObject(ObjectReference object) {
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(GenImmix.immixSpace.inImmixDefragCollection());
- ObjectReference rtn = traceObject(object);
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(willNotMoveInCurrentCollection(rtn));
- return rtn;
- }
-
- /**
- * Return true if this object is guaranteed not to move during this
- * collection (i.e. this object is defintely not an unforwarded
- * object).
- *
- * @param object
- * @return True if this object is guaranteed not to move during this
- * collection.
- */
- @Override
- public boolean willNotMoveInCurrentCollection(ObjectReference object) {
- if (Space.isInSpace(GenImmix.IMMIX, object)) {
- return GenImmix.immixSpace.willNotMoveThisGC(object);
- }
- return super.willNotMoveInCurrentCollection(object);
- }
-
- /**
- * Collectors that move objects <b>must</b> override this method.
- * It performs the deferred scanning of objects which are forwarded
- * during bootstrap of each copying collection. Because of the
- * complexities of the collection bootstrap (such objects are
- * generally themselves gc-critical), the forwarding and scanning of
- * the objects must be dislocated. It is an error for a non-moving
- * collector to call this method.
- *
- * @param object The forwarded object to be scanned
- */
- @Inline
- @Override
- protected void scanObject(ObjectReference object) {
- if (VM.VERIFY_ASSERTIONS && Options.verbose.getValue() >= 9) {
- Log.write("SO["); Log.write(object); Log.writeln("]");
- }
- super.scanObject(object);
- if (MARK_LINE_AT_SCAN_TIME && Space.isInSpace(GenImmix.IMMIX, object))
- GenImmix.immixSpace.markLines(object);
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/plan/generational/immix/GenImmixMatureTraceLocal.java b/vmkit/mmtk/java/src/org/mmtk/plan/generational/immix/GenImmixMatureTraceLocal.java
deleted file mode 100644
index 507bf3f..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/plan/generational/immix/GenImmixMatureTraceLocal.java
+++ /dev/null
@@ -1,110 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.plan.generational.immix;
-
-import static org.mmtk.policy.immix.ImmixConstants.MARK_LINE_AT_SCAN_TIME;
-
-import org.mmtk.plan.generational.GenCollector;
-import org.mmtk.plan.generational.GenMatureTraceLocal;
-import org.mmtk.plan.Trace;
-import org.mmtk.policy.Space;
-
-import org.vmmagic.unboxed.*;
-import org.vmmagic.pragma.*;
-
-/**
- * This class implements the core functionality for a transitive
- * closure over the heap graph, specifically in a generational immix
- * collector.
- */
-@Uninterruptible
-public final class GenImmixMatureTraceLocal extends GenMatureTraceLocal{
-
- /**
- * Constructor
- */
- public GenImmixMatureTraceLocal(Trace global, GenCollector plan) {
- super(GenImmix.SCAN_IMMIX, global, plan);
- }
-
- /**
- * This method is the core method during the trace of the object graph.
- * The role of this method is to:
- *
- * 1. Ensure the traced object is not collected.
- * 2. If this is the first visit to the object enqueue it to be scanned.
- * 3. Return the forwarded reference to the object.
- *
- * @param object The object to be traced.
- * @return The new reference to the same object instance.
- */
- @Inline
- public ObjectReference traceObject(ObjectReference object) {
- if (object.isNull()) return object;
-
- if (Space.isInSpace(GenImmix.IMMIX, object)) {
- return GenImmix.immixSpace.fastTraceObject(this, object);
- }
- return super.traceObject(object);
- }
-
- /**
- * Is the specified object live?
- *
- * @param object The object.
- * @return True if the object is live.
- */
- public boolean isLive(ObjectReference object) {
- if (object.isNull()) return false;
- if (Space.isInSpace(GenImmix.IMMIX, object)) {
- return GenImmix.immixSpace.isLive(object);
- }
- return super.isLive(object);
- }
-
- /**
- * Return true if this object is guaranteed not to move during this
- * collection (i.e. this object is defintely not an unforwarded
- * object).
- *
- * @param object
- * @return True if this object is guaranteed not to move during this
- * collection.
- */
- @Override
- public boolean willNotMoveInCurrentCollection(ObjectReference object) {
- if (Space.isInSpace(GenImmix.IMMIX, object)) {
- return true;
- }
- return super.willNotMoveInCurrentCollection(object);
- }
-
- /**
- * Collectors that move objects <b>must</b> override this method.
- * It performs the deferred scanning of objects which are forwarded
- * during bootstrap of each copying collection. Because of the
- * complexities of the collection bootstrap (such objects are
- * generally themselves gc-critical), the forwarding and scanning of
- * the objects must be dislocated. It is an error for a non-moving
- * collector to call this method.
- *
- * @param object The forwarded object to be scanned
- */
- @Inline
- @Override
- protected void scanObject(ObjectReference object) {
- super.scanObject(object);
- if (MARK_LINE_AT_SCAN_TIME && Space.isInSpace(GenImmix.IMMIX, object))
- GenImmix.immixSpace.markLines(object);
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/plan/generational/immix/GenImmixMutator.java b/vmkit/mmtk/java/src/org/mmtk/plan/generational/immix/GenImmixMutator.java
deleted file mode 100644
index 5eb8928..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/plan/generational/immix/GenImmixMutator.java
+++ /dev/null
@@ -1,169 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.plan.generational.immix;
-
-import org.mmtk.plan.generational.*;
-import org.mmtk.policy.Space;
-import org.mmtk.policy.immix.MutatorLocal;
-import org.mmtk.utility.alloc.Allocator;
-
-import org.mmtk.vm.VM;
-
-import org.vmmagic.pragma.*;
-import org.vmmagic.unboxed.*;
-
-/**
- * This class implements <i>per-mutator thread</i> behavior and state for
- * the <code>GenImmix</code> two-generational copying collector.<p>
- *
- * Specifically, this class defines mutator-time semantics specific to the
- * mature generation (<code>GenMutator</code> defines nursery semantics).
- * In particular the mature space allocator is defined (for mutator-time
- * allocation into the mature space via pre-tenuring), and the mature space
- * per-mutator thread collection time semantics are defined (rebinding
- * the mature space allocator).<p>
- *
- * See {@link GenImmix} for a description of the <code>GenImmix</code> algorithm.
- *
- * @see GenImmix
- * @see GenImmixCollector
- * @see org.mmtk.plan.generational.GenMutator
- * @see org.mmtk.plan.StopTheWorldMutator
- * @see org.mmtk.plan.MutatorContext
- * @see org.mmtk.plan.Phase
- */
-@Uninterruptible
-public class GenImmixMutator extends GenMutator {
-
- /******************************************************************
- * Instance fields
- */
-
- /**
- * The allocator for the mark-sweep mature space (the mutator may
- * "pretenure" objects into this space which is otherwise used
- * only by the collector)
- */
- private final MutatorLocal mature;
-
-
- /****************************************************************************
- *
- * Initialization
- */
-
- /**
- * Constructor
- */
- public GenImmixMutator() {
- mature = new MutatorLocal(GenImmix.immixSpace, false);
- }
-
- /****************************************************************************
- *
- * Mutator-time allocation
- */
-
- /**
- * Allocate memory for an object.
- *
- * @param bytes The number of bytes required for the object.
- * @param align Required alignment for the object.
- * @param offset Offset associated with the alignment.
- * @param allocator The allocator associated with this request.
- * @param site Allocation site
- * @return The low address of the allocated memory.
- */
- @Inline
- public final Address alloc(int bytes, int align, int offset, int allocator, int site) {
- if (allocator == GenImmix.ALLOC_MATURE) {
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(false); // no pretenuring yet
- return mature.alloc(bytes, align, offset);
- }
- return super.alloc(bytes, align, offset, allocator, site);
- }
-
- /**
- * Perform post-allocation actions. For many allocators none are
- * required.
- *
- * @param ref The newly allocated object
- * @param typeRef the type reference for the instance being created
- * @param bytes The size of the space to be allocated (in bytes)
- * @param allocator The allocator number to be used for this allocation
- */
- @Inline
- public final void postAlloc(ObjectReference ref, ObjectReference typeRef,
- int bytes, int allocator) {
- if (allocator == GenImmix.ALLOC_MATURE) {
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(false); // no pretenuring yet
- } else {
- super.postAlloc(ref, typeRef, bytes, allocator);
- }
- }
-
- /**
- * Return the allocator instance associated with a space
- * <code>space</code>, for this plan instance.
- *
- * @param space The space for which the allocator instance is desired.
- * @return The allocator instance associated with this plan instance
- * which is allocating into <code>space</code>, or <code>null</code>
- * if no appropriate allocator can be established.
- */
- public Allocator getAllocatorFromSpace(Space space) {
- if (space == GenImmix.immixSpace) return mature;
- return super.getAllocatorFromSpace(space);
- }
-
- /*****************************************************************************
- *
- * Collection
- */
-
- /**
- * Perform a per-mutator collection phase.
- *
- * @param phaseId Collection phase to perform
- * @param primary Is this thread to do the one-off thread-local tasks
- */
- @NoInline
- public void collectionPhase(short phaseId, boolean primary) {
- if (global().traceFullHeap()) {
- if (phaseId == GenImmix.PREPARE) {
- super.collectionPhase(phaseId, primary);
- if (global().gcFullHeap) mature.prepare();
- return;
- }
-
- if (phaseId == GenImmix.RELEASE) {
- if (global().gcFullHeap) mature.release();
- super.collectionPhase(phaseId, primary);
- return;
- }
- }
-
- super.collectionPhase(phaseId, primary);
- }
-
- /****************************************************************************
- *
- * Miscellaneous
- */
-
- /** @return The active global plan as a <code>GenImmix</code> instance. */
- @Inline
- private static GenImmix global() {
- return (GenImmix) VM.activePlan.global();
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/plan/generational/marksweep/GenMS.java b/vmkit/mmtk/java/src/org/mmtk/plan/generational/marksweep/GenMS.java
deleted file mode 100644
index bd53e25..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/plan/generational/marksweep/GenMS.java
+++ /dev/null
@@ -1,179 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.plan.generational.marksweep;
-
-import org.mmtk.plan.generational.Gen;
-import org.mmtk.plan.Trace;
-import org.mmtk.plan.TransitiveClosure;
-import org.mmtk.policy.MarkSweepSpace;
-import org.mmtk.policy.Space;
-import org.mmtk.utility.heap.VMRequest;
-
-import org.vmmagic.pragma.*;
-import org.vmmagic.unboxed.*;
-
-/**
- * This class implements the functionality of a two-generation copying
- * collector where <b>the higher generation is a mark-sweep space</b>
- * (free list allocation, mark-sweep collection). Nursery collections
- * occur when either the heap is full or the nursery is full. The
- * nursery size is determined by an optional command line argument.
- * If undefined, the nursery size is "infinite", so nursery
- * collections only occur when the heap is full (this is known as a
- * flexible-sized nursery collector). Thus both fixed and flexible
- * nursery sizes are supported. Full heap collections occur when the
- * nursery size has dropped to a statically defined threshold,
- * <code>NURSERY_THRESHOLD</code><p>
- *
- * See the Jones & Lins GC book, chapter 7 for a detailed discussion
- * of generational collection and section 7.3 for an overview of the
- * flexible nursery behavior ("The Standard ML of New Jersey
- * collector"), or go to Appel's paper "Simple generational garbage
- * collection and fast allocation." SP&E 19(2):171--183, 1989.<p>
- *
- *
- * For general comments about the global/local distinction among classes refer
- * to Plan.java and PlanLocal.java.
- */
-@Uninterruptible
-public class GenMS extends Gen {
-
- /*****************************************************************************
- *
- * Class fields
- */
-
- /** The mature space, which for GenMS uses a mark sweep collection policy. */
- public static final MarkSweepSpace msSpace = new MarkSweepSpace("ms", DEFAULT_POLL_FREQUENCY, VMRequest.create());
-
- public static final int MS = msSpace.getDescriptor();
-
- /****************************************************************************
- *
- * Instance fields
- */
-
- /* The trace class for a full-heap collection */
- public final Trace matureTrace = new Trace(metaDataSpace);
-
- /*****************************************************************************
- *
- * Collection
- */
-
- /**
- * Perform a (global) collection phase.
- */
- @Inline
- @Override
- public final void collectionPhase(short phaseId) {
- if (traceFullHeap()) {
- if (phaseId == PREPARE) {
- super.collectionPhase(phaseId);
- matureTrace.prepare();
- msSpace.prepare(true);
- return;
- }
-
- if (phaseId == CLOSURE) {
- matureTrace.prepare();
- return;
- }
- if (phaseId == RELEASE) {
- matureTrace.release();
- msSpace.release();
- super.collectionPhase(phaseId);
- return;
- }
- }
- super.collectionPhase(phaseId);
- }
-
- /*****************************************************************************
- *
- * Accounting
- */
-
- /**
- * Return the number of pages reserved for use given the pending
- * allocation.
- *
- * @return The number of pages reserved given the pending
- * allocation, excluding space reserved for copying.
- */
- @Inline
- @Override
- public int getPagesUsed() {
- return msSpace.reservedPages() + super.getPagesUsed();
- }
-
- /**
- * Calculate the number of pages a collection is required to free to satisfy
- * outstanding allocation requests.
- *
- * @return the number of pages a collection is required to free to satisfy
- * outstanding allocation requests.
- */
- public int getPagesRequired() {
- return super.getPagesRequired() + msSpace.requiredPages();
- }
-
- /**
- * Return the number of pages available for allocation into the mature
- * space.
- *
- * @return The number of pages available for allocation into the mature
- * space.
- */
- public int getMaturePhysicalPagesAvail() {
- return (int) (msSpace.availablePhysicalPages()/MarkSweepSpace.WORST_CASE_FRAGMENTATION);
- }
-
- /*****************************************************************************
- *
- * Miscellaneous
- */
-
- /**
- * Accessor method to allow the generic generational code in Gen.java
- * to access the mature space.
- *
- * @return The active mature space
- */
- @Inline
- protected final Space activeMatureSpace() {
- return msSpace;
- }
-
- /**
- * @see org.mmtk.plan.Plan#willNeverMove
- *
- * @param object Object in question
- * @return True if the object will never move
- */
- @Override
- public boolean willNeverMove(ObjectReference object) {
- if (Space.isInSpace(MS, object))
- return true;
- return super.willNeverMove(object);
- }
-
- /**
- * Register specialized methods.
- */
- @Interruptible
- protected void registerSpecializedMethods() {
- TransitiveClosure.registerSpecializedScan(SCAN_MATURE, GenMSMatureTraceLocal.class);
- super.registerSpecializedMethods();
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/plan/generational/marksweep/GenMSCollector.java b/vmkit/mmtk/java/src/org/mmtk/plan/generational/marksweep/GenMSCollector.java
deleted file mode 100644
index de01c91..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/plan/generational/marksweep/GenMSCollector.java
+++ /dev/null
@@ -1,176 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.plan.generational.marksweep;
-
-import org.mmtk.plan.Plan;
-import org.mmtk.plan.TraceLocal;
-import org.mmtk.plan.generational.*;
-import org.mmtk.policy.MarkSweepLocal;
-import org.mmtk.policy.Space;
-import org.mmtk.utility.HeaderByte;
-import org.mmtk.utility.alloc.Allocator;
-import org.mmtk.utility.statistics.Stats;
-
-import org.mmtk.vm.VM;
-
-import org.vmmagic.pragma.*;
-import org.vmmagic.unboxed.*;
-
-/**
- * This class implements <i>per-collector thread</i> behavior and state for
- * the <code>GenMS</code> two-generational copying collector.<p>
- *
- * Specifically, this class defines semantics specific to the collection of
- * the mature generation (<code>GenCollector</code> defines nursery semantics).
- * In particular the mature space allocator is defined (for collection-time
- * allocation into the mature space), and the mature space per-collector thread
- * collection time semantics are defined.<p>
- *
- * @see GenMS for a description of the <code>GenMS</code> algorithm.
- *
- * @see GenMS
- * @see GenMSMutator
- * @see GenCollector
- * @see org.mmtk.plan.StopTheWorldCollector
- * @see org.mmtk.plan.CollectorContext
- */
-@Uninterruptible
-public class GenMSCollector extends GenCollector {
-
- /*****************************************************************************
- *
- * Instance fields
- */
-
- /** The allocator for the mature space */
- private final MarkSweepLocal mature;
- private final GenMSMatureTraceLocal matureTrace;
-
- /**
- * Constructor
- */
- public GenMSCollector() {
- mature = new MarkSweepLocal(GenMS.msSpace);
- matureTrace = new GenMSMatureTraceLocal(global().matureTrace, this);
- }
-
- /****************************************************************************
- * Collection-time allocation
- */
-
- /**
- * Allocate space for copying an object (this method <i>does not</i>
- * copy the object, it only allocates space)
- *
- * @param original A reference to the original object
- * @param bytes The size of the space to be allocated (in bytes)
- * @param align The requested alignment.
- * @param offset The alignment offset.
- * @param allocator The allocator to use.
- * @return The address of the first byte of the allocated region
- */
- @Inline
- @Override
- public final Address allocCopy(ObjectReference original, int bytes,
- int align, int offset, int allocator) {
- if (Stats.GATHER_MARK_CONS_STATS) {
- if (Space.isInSpace(GenMS.NURSERY, original)) GenMS.nurseryMark.inc(bytes);
- }
-
- if (allocator == Plan.ALLOC_LOS) {
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(Allocator.getMaximumAlignedSize(bytes, align) > Plan.MAX_NON_LOS_COPY_BYTES);
- return los.alloc(bytes, align, offset);
- } else {
- if (VM.VERIFY_ASSERTIONS) {
- VM.assertions._assert(bytes <= Plan.MAX_NON_LOS_COPY_BYTES);
- VM.assertions._assert(allocator == GenMS.ALLOC_MATURE_MINORGC ||
- allocator == GenMS.ALLOC_MATURE_MAJORGC);
- }
- return mature.alloc(bytes, align, offset);
- }
- }
-
- /**
- * Perform any post-copy actions.
- *
- * @param object The newly allocated object
- * @param typeRef the type reference for the instance being created
- * @param bytes The size of the space to be allocated (in bytes)
- */
- @Inline
- @Override
- public final void postCopy(ObjectReference object, ObjectReference typeRef,
- int bytes, int allocator) {
- if (allocator == Plan.ALLOC_LOS)
- Plan.loSpace.initializeHeader(object, false);
- else
- GenMS.msSpace.postCopy(object, allocator == GenMS.ALLOC_MATURE_MAJORGC);
- if (Gen.USE_OBJECT_BARRIER)
- HeaderByte.markAsUnlogged(object);
- }
-
- /*****************************************************************************
- *
- * Collection
- */
-
- /**
- * Perform a (local) collection phase.
- *
- * @param phaseId Collection phase to perform
- * @param primary Is this thread to do the one-off thread-local tasks
- */
- @NoInline
- public void collectionPhase(short phaseId, boolean primary) {
- if (global().traceFullHeap()) {
- if (phaseId == GenMS.PREPARE) {
- super.collectionPhase(phaseId, primary);
- matureTrace.prepare();
- if (global().gcFullHeap) mature.prepare();
- return;
- }
-
- if (phaseId == GenMS.CLOSURE) {
- matureTrace.completeTrace();
- return;
- }
-
- if (phaseId == GenMS.RELEASE) {
- matureTrace.release();
- if (global().gcFullHeap) {
- mature.release();
- }
- super.collectionPhase(phaseId, primary);
- return;
- }
- }
-
- super.collectionPhase(phaseId, primary);
- }
-
- @Inline
- public final TraceLocal getFullHeapTrace() {
- return matureTrace;
- }
-
- /****************************************************************************
- *
- * Miscellaneous
- */
-
- /** @return The active global plan as a <code>GenMS</code> instance. */
- @Inline
- private static GenMS global() {
- return (GenMS) VM.activePlan.global();
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/plan/generational/marksweep/GenMSConstraints.java b/vmkit/mmtk/java/src/org/mmtk/plan/generational/marksweep/GenMSConstraints.java
deleted file mode 100644
index fd9a8cf..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/plan/generational/marksweep/GenMSConstraints.java
+++ /dev/null
@@ -1,30 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.plan.generational.marksweep;
-
-import org.mmtk.plan.generational.GenConstraints;
-import static org.mmtk.policy.SegregatedFreeListSpace.MAX_FREELIST_OBJECT_BYTES;
-
-import org.vmmagic.pragma.*;
-
-/**
- * This class and its subclasses communicate to the host VM/Runtime
- * any features of the selected plan that it needs to know. This is
- * separate from the main Plan/PlanLocal class in order to bypass any
- * issues with ordering of static initialization.
- */
-@Uninterruptible
-public class GenMSConstraints extends GenConstraints {
- @Override
- public int maxNonLOSCopyBytes() { return MAX_FREELIST_OBJECT_BYTES;}
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/plan/generational/marksweep/GenMSMatureTraceLocal.java b/vmkit/mmtk/java/src/org/mmtk/plan/generational/marksweep/GenMSMatureTraceLocal.java
deleted file mode 100644
index 3a42afb..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/plan/generational/marksweep/GenMSMatureTraceLocal.java
+++ /dev/null
@@ -1,88 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.plan.generational.marksweep;
-
-import org.mmtk.plan.generational.GenCollector;
-import org.mmtk.plan.generational.GenMatureTraceLocal;
-import org.mmtk.plan.Trace;
-import org.mmtk.policy.Space;
-
-import org.vmmagic.unboxed.*;
-import org.vmmagic.pragma.*;
-
-/**
- * This class implments the core functionality for a transitive
- * closure over the heap graph, specifically in a Generational Mark-Sweep
- * collector.
- */
-@Uninterruptible
-public final class GenMSMatureTraceLocal extends GenMatureTraceLocal{
-
- /**
- * Constructor
- */
- public GenMSMatureTraceLocal(Trace global, GenCollector plan) {
- super(global, plan);
- }
-
- /**
- * This method is the core method during the trace of the object graph.
- * The role of this method is to:
- *
- * 1. Ensure the traced object is not collected.
- * 2. If this is the first visit to the object enqueue it to be scanned.
- * 3. Return the forwarded reference to the object.
- *
- * @param object The object to be traced.
- * @return The new reference to the same object instance.
- */
- @Inline
- public ObjectReference traceObject(ObjectReference object) {
- if (object.isNull()) return object;
-
- if (Space.isInSpace(GenMS.MS, object)) {
- return GenMS.msSpace.traceObject(this, object);
- }
- return super.traceObject(object);
- }
-
- /**
- * Is the specified object live?
- *
- * @param object The object.
- * @return True if the object is live.
- */
- public boolean isLive(ObjectReference object) {
- if (object.isNull()) return false;
- if (Space.isInSpace(GenMS.MS, object)) {
- return GenMS.msSpace.isLive(object);
- }
- return super.isLive(object);
- }
-
- /**
- * Return true if this object is guaranteed not to move during this
- * collection (i.e. this object is defintely not an unforwarded
- * object).
- *
- * @param object
- * @return True if this object is guaranteed not to move during this
- * collection.
- */
- public boolean willNotMoveInCurrentCollection(ObjectReference object) {
- if (Space.isInSpace(GenMS.MS, object)) {
- return true;
- }
- return super.willNotMoveInCurrentCollection(object);
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/plan/generational/marksweep/GenMSMutator.java b/vmkit/mmtk/java/src/org/mmtk/plan/generational/marksweep/GenMSMutator.java
deleted file mode 100644
index 59003fc..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/plan/generational/marksweep/GenMSMutator.java
+++ /dev/null
@@ -1,176 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.plan.generational.marksweep;
-
-import org.mmtk.plan.generational.*;
-import org.mmtk.policy.MarkSweepLocal;
-import org.mmtk.policy.Space;
-import org.mmtk.utility.alloc.Allocator;
-
-import org.mmtk.vm.VM;
-
-import org.vmmagic.pragma.*;
-import org.vmmagic.unboxed.*;
-
-/**
- * This class implements <i>per-mutator thread</i> behavior and state for
- * the <code>GenMS</code> two-generational copying collector.<p>
- *
- * Specifically, this class defines mutator-time semantics specific to the
- * mature generation (<code>GenMutator</code> defines nursery semantics).
- * In particular the mature space allocator is defined (for mutator-time
- * allocation into the mature space via pre-tenuring), and the mature space
- * per-mutator thread collection time semantics are defined (rebinding
- * the mature space allocator).<p>
- *
- * See {@link GenMS} for a description of the <code>GenMS</code> algorithm.
- *
- * @see GenMS
- * @see GenMSCollector
- * @see GenMutator
- * @see org.mmtk.plan.StopTheWorldMutator
- * @see org.mmtk.plan.MutatorContext
- */
-@Uninterruptible
-public class GenMSMutator extends GenMutator {
- /******************************************************************
- * Instance fields
- */
-
- /**
- * The allocator for the mark-sweep mature space (the mutator may
- * "pretenure" objects into this space which is otherwise used
- * only by the collector)
- */
- private final MarkSweepLocal mature;
-
-
- /****************************************************************************
- *
- * Initialization
- */
-
- /**
- * Constructor
- */
- public GenMSMutator() {
- mature = new MarkSweepLocal(GenMS.msSpace);
- }
-
- /****************************************************************************
- *
- * Mutator-time allocation
- */
-
- /**
- * Allocate memory for an object.
- *
- * @param bytes The number of bytes required for the object.
- * @param align Required alignment for the object.
- * @param offset Offset associated with the alignment.
- * @param allocator The allocator associated with this request.
- * @param site Allocation site
- * @return The low address of the allocated memory.
- */
- @Inline
- public final Address alloc(int bytes, int align, int offset, int allocator, int site) {
- if (allocator == GenMS.ALLOC_MATURE) {
- return mature.alloc(bytes, align, offset);
- }
- return super.alloc(bytes, align, offset, allocator, site);
- }
-
- /**
- * Perform post-allocation actions. For many allocators none are
- * required.
- *
- * @param ref The newly allocated object
- * @param typeRef the type reference for the instance being created
- * @param bytes The size of the space to be allocated (in bytes)
- * @param allocator The allocator number to be used for this allocation
- */
- @Inline
- public final void postAlloc(ObjectReference ref, ObjectReference typeRef,
- int bytes, int allocator) {
- if (allocator == GenMS.ALLOC_MATURE) {
- GenMS.msSpace.initializeHeader(ref, true);
- } else {
- super.postAlloc(ref, typeRef, bytes, allocator);
- }
- }
-
- /**
- * Return the allocator instance associated with a space
- * <code>space</code>, for this plan instance.
- *
- * @param space The space for which the allocator instance is desired.
- * @return The allocator instance associated with this plan instance
- * which is allocating into <code>space</code>, or <code>null</code>
- * if no appropriate allocator can be established.
- */
- public Allocator getAllocatorFromSpace(Space space) {
- if (space == GenMS.msSpace) return mature;
- return super.getAllocatorFromSpace(space);
- }
-
- /*****************************************************************************
- *
- * Collection
- */
-
- /**
- * Perform a per-mutator collection phase.
- *
- * @param phaseId Collection phase to perform
- * @param primary Is this thread to do the one-off thread-local tasks
- */
- @NoInline
- public void collectionPhase(short phaseId, boolean primary) {
- if (global().traceFullHeap()) {
- if (phaseId == GenMS.PREPARE) {
- super.collectionPhase(phaseId, primary);
- if (global().gcFullHeap) mature.prepare();
- return;
- }
-
- if (phaseId == GenMS.RELEASE) {
- if (global().gcFullHeap) mature.release();
- super.collectionPhase(phaseId, primary);
- return;
- }
- }
-
- super.collectionPhase(phaseId, primary);
- }
-
- /**
- * Flush mutator context, in response to a requestMutatorFlush.
- * Also called by the default implementation of deinitMutator.
- */
- @Override
- public void flush() {
- super.flush();
- mature.flush();
- }
-
- /****************************************************************************
- *
- * Miscellaneous
- */
-
- /** @return The active global plan as a <code>GenMS</code> instance. */
- @Inline
- private static GenMS global() {
- return (GenMS) VM.activePlan.global();
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/plan/immix/Immix.java b/vmkit/mmtk/java/src/org/mmtk/plan/immix/Immix.java
deleted file mode 100644
index 693225e..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/plan/immix/Immix.java
+++ /dev/null
@@ -1,179 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.plan.immix;
-
-import org.mmtk.plan.*;
-import org.mmtk.policy.Space;
-import org.mmtk.policy.immix.ImmixSpace;
-import org.mmtk.policy.immix.ObjectHeader;
-import org.mmtk.utility.heap.VMRequest;
-
-import org.vmmagic.pragma.*;
-import org.vmmagic.unboxed.*;
-
-/**
- * This class implements the global state of an immix collector.
- *
- * See the PLDI'08 paper by Blackburn and McKinley for a description
- * of the algorithm: http://doi.acm.org/10.1145/1375581.1375586
- *
- * All plans make a clear distinction between <i>global</i> and
- * <i>thread-local</i> activities, and divides global and local state
- * into separate class hierarchies. Global activities must be
- * synchronized, whereas no synchronization is required for
- * thread-local activities. There is a single instance of Plan (or the
- * appropriate sub-class), and a 1:1 mapping of PlanLocal to "kernel
- * threads" (aka CPUs or in Jikes RVM, Processors). Thus instance
- * methods of PlanLocal allow fast, unsychronized access to functions such as
- * allocation and collection.
- *
- * The global instance defines and manages static resources
- * (such as memory and virtual memory resources). This mapping of threads to
- * instances is crucial to understanding the correctness and
- * performance properties of MMTk plans.
- */
-@Uninterruptible
-public class Immix extends StopTheWorld {
-
- /****************************************************************************
- * Constants
- */
-
- /****************************************************************************
- * Class variables
- */
- public static final ImmixSpace immixSpace = new ImmixSpace("immix", DEFAULT_POLL_FREQUENCY, VMRequest.create());
- public static final int IMMIX = immixSpace.getDescriptor();
-
- public static final int SCAN_IMMIX = 0;
- public static final int SCAN_DEFRAG = 1;
-
- /****************************************************************************
- * Instance variables
- */
-
- public final Trace immixTrace = new Trace(metaDataSpace);
- /** will the next collection collect the whole heap? */
- public boolean nextGCWholeHeap = true;
- /** will this collection collect the whole heap */
- public boolean collectWholeHeap = nextGCWholeHeap;
- protected boolean lastGCWasDefrag = false;
-
- /**
- * Constructor.
- *
- */
- public Immix() {
- }
-
- /*****************************************************************************
- *
- * Collection
- */
-
- /**
- * Perform a (global) collection phase.
- *
- * @param phaseId Collection phase to execute.
- */
- @Inline
- public void collectionPhase(short phaseId) {
- if (phaseId == SET_COLLECTION_KIND) {
- super.collectionPhase(phaseId);
- immixSpace.decideWhetherToDefrag(emergencyCollection, collectWholeHeap, collectionAttempt, collectionTrigger);
- return;
- }
-
- if (phaseId == PREPARE) {
- super.collectionPhase(phaseId);
- immixTrace.prepare();
- immixSpace.prepare(true);
- return;
- }
-
- if (phaseId == CLOSURE) {
- immixTrace.prepare();
- return;
- }
-
- if (phaseId == RELEASE) {
- immixTrace.release();
- lastGCWasDefrag = immixSpace.release(true);
- super.collectionPhase(phaseId);
- return;
- }
-
- super.collectionPhase(phaseId);
- }
-
- /**
- * @return Whether last GC was an exhaustive attempt to collect the heap. For many collectors this is the same as asking whether the last GC was a full heap collection.
- */
- @Override
- public boolean lastCollectionWasExhaustive() {
- return lastGCWasDefrag;
- }
-
- /*****************************************************************************
- *
- * Accounting
- */
-
- /**
- * Return the number of pages reserved for use given the pending
- * allocation. The superclass accounts for its spaces, we just
- * augment this with the mark-sweep space's contribution.
- *
- * @return The number of pages reserved given the pending
- * allocation, excluding space reserved for copying.
- */
- public int getPagesUsed() {
- return immixSpace.reservedPages() + super.getPagesUsed();
- }
-
- /**
- * Calculate the number of pages a collection is required to free to satisfy
- * outstanding allocation requests.
- *
- * @return the number of pages a collection is required to free to satisfy
- * outstanding allocation requests.
- */
- public int getPagesRequired() {
- return super.getPagesRequired() + immixSpace.requiredPages();
- }
-
- /**
- * @see org.mmtk.plan.Plan#willNeverMove
- *
- * @param object Object in question
- * @return True if the object will never move
- */
- @Override
- public boolean willNeverMove(ObjectReference object) {
- if (Space.isInSpace(IMMIX, object)) {
- ObjectHeader.pinObject(object);
- return true;
- } else
- return super.willNeverMove(object);
- }
-
- /**
- * Register specialized methods.
- */
- @Interruptible
- protected void registerSpecializedMethods() {
- TransitiveClosure.registerSpecializedScan(SCAN_IMMIX, ImmixTraceLocal.class);
- TransitiveClosure.registerSpecializedScan(SCAN_DEFRAG, ImmixDefragTraceLocal.class);
- super.registerSpecializedMethods();
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/plan/immix/ImmixCollector.java b/vmkit/mmtk/java/src/org/mmtk/plan/immix/ImmixCollector.java
deleted file mode 100644
index 316afc9..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/plan/immix/ImmixCollector.java
+++ /dev/null
@@ -1,175 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.plan.immix;
-
-import org.mmtk.plan.*;
-import org.mmtk.policy.ImmortalLocal;
-import org.mmtk.policy.immix.CollectorLocal;
-import org.mmtk.utility.alloc.BumpPointer;
-import org.mmtk.utility.alloc.ImmixAllocator;
-import org.mmtk.vm.VM;
-
-import org.vmmagic.pragma.*;
-import org.vmmagic.unboxed.Address;
-import org.vmmagic.unboxed.ObjectReference;
-
-/**
- * This class implements <i>per-collector thread</i> behavior
- * and state for the <i>Immix</i> plan, which implements a full-heap
- * immix collector.<p>
- *
- * Specifically, this class defines <i>Immix</i> collection behavior
- * (through <code>fastTrace</code> and the <code>collectionPhase</code>
- * method).<p>
- *
- * @see Immix for an overview of the immix algorithm.<p>
- *
- * FIXME The SegregatedFreeList class (and its decendents such as
- * MarkSweepLocal) does not properly separate mutator and collector
- * behaviors, so the immix field below should really not exist in
- * this class as there is no collection-time allocation in this
- * collector.
- *
- * @see Immix
- * @see org.mmtk.policy.immix.MutatorLocal
- * @see StopTheWorldCollector
- * @see CollectorContext
- * @see Phase
- */
-@Uninterruptible
-public class ImmixCollector extends StopTheWorldCollector {
-
- /****************************************************************************
- * Instance fields
- */
- protected ImmixTraceLocal fastTrace;
- protected ImmixDefragTraceLocal defragTrace;
- protected CollectorLocal immix;
- protected final ImmixAllocator copy;
- protected final BumpPointer immortal;
- protected TraceLocal currentTrace;
-
- /****************************************************************************
- * Initialization
- */
-
- /**
- * Constructor
- */
- public ImmixCollector() {
- fastTrace = new ImmixTraceLocal(global().immixTrace, null);
- defragTrace = new ImmixDefragTraceLocal(global().immixTrace, null);
- immix = new CollectorLocal(Immix.immixSpace);
- copy = new ImmixAllocator(Immix.immixSpace, true, true);
- immortal = new ImmortalLocal(Plan.immortalSpace);
- }
-
- /****************************************************************************
- *
- * Collection-time allocation
- */
-
- /**
- * Allocate space for copying an object (this method <i>does not</i>
- * copy the object, it only allocates space)
- *
- * @param original A reference to the original object
- * @param bytes The size of the space to be allocated (in bytes)
- * @param align The requested alignment.
- * @param offset The alignment offset.
- * @return The address of the first byte of the allocated region
- */
- @Inline
- public Address allocCopy(ObjectReference original, int bytes,
- int align, int offset, int allocator) {
- if (VM.VERIFY_ASSERTIONS) {
- VM.assertions._assert(bytes <= Plan.MAX_NON_LOS_COPY_BYTES);
- VM.assertions._assert(allocator == Immix.ALLOC_DEFAULT);
- }
- return copy.alloc(bytes, align, offset);
- }
-
- /**
- * Perform any post-copy actions.
- *
- * @param object The newly allocated object
- * @param typeRef the type reference for the instance being created
- * @param bytes The size of the space to be allocated (in bytes)
- */
- @Inline
- public void postCopy(ObjectReference object, ObjectReference typeRef,
- int bytes, int allocator) {
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(allocator == Immix.ALLOC_DEFAULT);
- Immix.immixSpace.postCopy(object, bytes, true);
-
- if (VM.VERIFY_ASSERTIONS) {
- VM.assertions._assert(getCurrentTrace().isLive(object));
- VM.assertions._assert(getCurrentTrace().willNotMoveInCurrentCollection(object));
- }
- }
-
- /****************************************************************************
- *
- * Collection
- */
-
- /**
- * Perform a per-collector collection phase.
- *
- * @param phaseId The collection phase to perform
- * @param primary Perform any single-threaded activities using this thread.
- */
- @Inline
- public void collectionPhase(short phaseId, boolean primary) {
-
- if (phaseId == Immix.PREPARE) {
- super.collectionPhase(phaseId, primary);
- currentTrace = Immix.immixSpace.inImmixDefragCollection() ? defragTrace : fastTrace;
- immix.prepare(true);
- currentTrace.prepare();
- copy.reset();
- return;
- }
-
- if (phaseId == Immix.CLOSURE) {
- currentTrace.completeTrace();
- return;
- }
-
- if (phaseId == Immix.RELEASE) {
- currentTrace.release();
- immix.release(true);
- super.collectionPhase(phaseId, primary);
- return;
- }
-
- super.collectionPhase(phaseId, primary);
- }
-
- /****************************************************************************
- *
- * Miscellaneous
- */
-
- /** @return The active global plan as an <code>Immix</code> instance. */
- @Inline
- private static Immix global() {
- return (Immix) VM.activePlan.global();
- }
-
- /** @return The current fastTrace instance. */
- @Inline
- public final TraceLocal getCurrentTrace() {
- return currentTrace;
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/plan/immix/ImmixConstraints.java b/vmkit/mmtk/java/src/org/mmtk/plan/immix/ImmixConstraints.java
deleted file mode 100644
index e998d89..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/plan/immix/ImmixConstraints.java
+++ /dev/null
@@ -1,53 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.plan.immix;
-
-import org.mmtk.plan.StopTheWorldConstraints;
-import org.mmtk.policy.immix.ObjectHeader;
-import static org.mmtk.policy.immix.ImmixConstants.MAX_IMMIX_OBJECT_BYTES;
-
-import org.vmmagic.pragma.*;
-
-/**
- * This class and its subclasses communicate to the host VM/Runtime
- * any features of the selected plan that it needs to know. This is
- * separate from the main Plan/PlanLocal class in order to bypass any
- * issues with ordering of static initialization.
- */
-@Uninterruptible
-public class ImmixConstraints extends StopTheWorldConstraints {
-
- /** @return The number of header bits that are required. */
- @Override
- public int gcHeaderBits() { return ObjectHeader.LOCAL_GC_BITS_REQUIRED; }
-
- /** @return The number of header words that are required. */
- @Override
- public int gcHeaderWords() { return ObjectHeader.GC_HEADER_WORDS_REQUIRED; }
-
- /** @return True if this plan moves objects. */
- @Override
- public boolean movesObjects() { return true;}
-
- /** @return The specialized scan methods required */
- @Override
- public int numSpecializedScans() { return 2; }
-
- /** @return Size (in bytes) beyond which new regular objects must be allocated to the LOS */
- @Override
- public int maxNonLOSDefaultAllocBytes() { return MAX_IMMIX_OBJECT_BYTES; }
-
- /** @return Size (in bytes) beyond which copied objects must be copied to the LOS */
- @Override
- public int maxNonLOSCopyBytes() { return MAX_IMMIX_OBJECT_BYTES; }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/plan/immix/ImmixDefragTraceLocal.java b/vmkit/mmtk/java/src/org/mmtk/plan/immix/ImmixDefragTraceLocal.java
deleted file mode 100644
index 1444d20..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/plan/immix/ImmixDefragTraceLocal.java
+++ /dev/null
@@ -1,153 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.plan.immix;
-
-import static org.mmtk.policy.immix.ImmixConstants.MARK_LINE_AT_SCAN_TIME;
-
-import org.mmtk.plan.Plan;
-import org.mmtk.plan.TraceLocal;
-import org.mmtk.plan.Trace;
-import org.mmtk.policy.Space;
-import org.mmtk.utility.HeaderByte;
-import org.mmtk.utility.deque.ObjectReferenceDeque;
-import org.mmtk.vm.VM;
-
-import org.vmmagic.pragma.*;
-import org.vmmagic.unboxed.*;
-
-/**
- * This class implements the thread-local functionality for a defragmenting
- * transitive closure over an immix space.
- */
-@Uninterruptible
-public final class ImmixDefragTraceLocal extends TraceLocal {
-
- /****************************************************************************
- *
- * Instance fields
- */
- private final ObjectReferenceDeque modBuffer;
-
- /**
- * Constructor
- * @param modBuffer TODO
- */
- public ImmixDefragTraceLocal(Trace trace, ObjectReferenceDeque modBuffer) {
- super(Immix.SCAN_DEFRAG, trace);
- this.modBuffer = modBuffer;
- }
-
- /****************************************************************************
- *
- * Externally visible Object processing and tracing
- */
-
- /**
- * Is the specified object live?
- *
- * @param object The object.
- * @return True if the object is live.
- */
- public boolean isLive(ObjectReference object) {
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(Immix.immixSpace.inImmixDefragCollection());
- if (object.isNull()) return false;
- if (Space.isInSpace(Immix.IMMIX, object)) {
- return Immix.immixSpace.isLive(object);
- }
- return super.isLive(object);
- }
-
- /**
- * This method is the core method during the trace of the object graph.
- * The role of this method is to:
- *
- * 1. Ensure the traced object is not collected.
- * 2. If this is the first visit to the object enqueue it to be scanned.
- * 3. Return the forwarded reference to the object.
- *
- * In this instance, we refer objects in the mark-sweep space to the
- * immixSpace for tracing, and defer to the superclass for all others.
- *
- * @param object The object to be traced.
- * @return The new reference to the same object instance.
- */
- @Inline
- public ObjectReference traceObject(ObjectReference object) {
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(Immix.immixSpace.inImmixDefragCollection());
- if (object.isNull()) return object;
- if (Space.isInSpace(Immix.IMMIX, object))
- return Immix.immixSpace.traceObject(this, object, Plan.ALLOC_DEFAULT);
- return super.traceObject(object);
- }
-
- @Inline
- @Override
- public ObjectReference precopyObject(ObjectReference object) {
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(Immix.immixSpace.inImmixDefragCollection());
- ObjectReference rtn = traceObject(object);
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(willNotMoveInCurrentCollection(rtn));
- return rtn;
- }
-
- /**
- * Return true if this object is guaranteed not to move during this
- * collection (i.e. this object is defintely not an unforwarded
- * object).
- *
- * @param object
- * @return True if this object is guaranteed not to move during this
- * collection.
- */
- @Override
- public boolean willNotMoveInCurrentCollection(ObjectReference object) {
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(Immix.immixSpace.inImmixDefragCollection());
- if (Space.isInSpace(Immix.IMMIX, object))
- return Immix.immixSpace.willNotMoveThisGC(object);
- return true;
- }
-
- /**
- * Collectors that move objects <b>must</b> override this method.
- * It performs the deferred scanning of objects which are forwarded
- * during bootstrap of each copying collection. Because of the
- * complexities of the collection bootstrap (such objects are
- * generally themselves gc-critical), the forwarding and scanning of
- * the objects must be dislocated. It is an error for a non-moving
- * collector to call this method.
- *
- * @param object The forwarded object to be scanned
- */
- @Inline
- @Override
- protected void scanObject(ObjectReference object) {
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(Immix.immixSpace.inImmixDefragCollection());
- super.scanObject(object);
- if (MARK_LINE_AT_SCAN_TIME && Space.isInSpace(Immix.IMMIX, object))
- Immix.immixSpace.markLines(object);
- }
-
- /**
- * Process any remembered set entries. This means enumerating the
- * mod buffer and for each entry, marking the object as unlogged
- * (we don't enqueue for scanning since we're doing a full heap GC).
- */
- protected void processRememberedSets() {
- if (modBuffer != null) {
- logMessage(5, "clearing modBuffer");
- while (!modBuffer.isEmpty()) {
- ObjectReference src = modBuffer.pop();
- HeaderByte.markAsUnlogged(src);
- }
- }
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/plan/immix/ImmixMutator.java b/vmkit/mmtk/java/src/org/mmtk/plan/immix/ImmixMutator.java
deleted file mode 100644
index c3b979c..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/plan/immix/ImmixMutator.java
+++ /dev/null
@@ -1,142 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.plan.immix;
-
-import org.mmtk.plan.*;
-import org.mmtk.policy.Space;
-import org.mmtk.policy.immix.MutatorLocal;
-
-import org.mmtk.utility.alloc.Allocator;
-
-import org.vmmagic.pragma.*;
-import org.vmmagic.unboxed.*;
-
-/**
- * This class implements <i>per-mutator thread</i> behavior
- * and state for the <i>Immix</i> plan, which implements a full-heap
- * immix collector.<p>
- *
- * Specifically, this class defines <i>Immix</i> mutator-time allocation
- * and per-mutator thread collection semantics (flushing and restoring
- * per-mutator allocator state).<p>
- *
- * @see Immix
- * @see org.mmtk.policy.immix.CollectorLocal
- * @see StopTheWorldMutator
- * @see MutatorContext
- */
-@Uninterruptible
-public class ImmixMutator extends StopTheWorldMutator {
-
- /****************************************************************************
- * Instance fields
- */
- protected final MutatorLocal immix;
-
- /****************************************************************************
- *
- * Initialization
- */
-
- /**
- * Constructor
- */
- public ImmixMutator() {
- immix = new org.mmtk.policy.immix.MutatorLocal(Immix.immixSpace, false);
- }
-
- /****************************************************************************
- *
- * MutatorLocal-time allocation
- */
-
- /**
- * Allocate memory for an object. This class handles the default allocator
- * from the mark sweep space, and delegates everything else to the
- * superclass.
- *
- * @param bytes The number of bytes required for the object.
- * @param align Required alignment for the object.
- * @param offset Offset associated with the alignment.
- * @param allocator The allocator associated with this request.
- * @return The low address of the allocated memory.
- */
- @Inline
- public Address alloc(int bytes, int align, int offset, int allocator, int site) {
- if (allocator == Immix.ALLOC_DEFAULT)
- return immix.alloc(bytes, align, offset);
- return super.alloc(bytes, align, offset, allocator, site);
- }
-
- /**
- * Perform post-allocation actions. Initialize the object header for
- * objects in the mark-sweep space, and delegate to the superclass for
- * other objects.
- *
- * @param ref The newly allocated object
- * @param typeRef the type reference for the instance being created
- * @param bytes The size of the space to be allocated (in bytes)
- * @param allocator The allocator number to be used for this allocation
- */
- @Inline
- public void postAlloc(ObjectReference ref, ObjectReference typeRef,
- int bytes, int allocator) {
- if (allocator == Immix.ALLOC_DEFAULT)
- Immix.immixSpace.postAlloc(ref, bytes);
- else
- super.postAlloc(ref, typeRef, bytes, allocator);
- }
-
- /**
- * Return the allocator instance associated with a space
- * <code>space</code>, for this plan instance.
- *
- * @param space The space for which the allocator instance is desired.
- * @return The allocator instance associated with this plan instance
- * which is allocating into <code>space</code>, or <code>null</code>
- * if no appropriate allocator can be established.
- */
- public Allocator getAllocatorFromSpace(Space space) {
- if (space == Immix.immixSpace) return immix; // FIXME is it not a problem that we have a 2:1 mapping?
- return super.getAllocatorFromSpace(space);
- }
-
- /****************************************************************************
- *
- * Collection
- */
-
- /**
- * Perform a per-mutator collection phase.
- *
- * @param phaseId The collection phase to perform
- * @param primary Perform any single-threaded activities using this thread.
- */
- @Inline
- public void collectionPhase(short phaseId, boolean primary) {
-
- if (phaseId == Immix.PREPARE) {
- super.collectionPhase(phaseId, primary);
- immix.prepare();
- return;
- }
-
- if (phaseId == Immix.RELEASE) {
- immix.release();
- super.collectionPhase(phaseId, primary);
- return;
- }
-
- super.collectionPhase(phaseId, primary);
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/plan/immix/ImmixTraceLocal.java b/vmkit/mmtk/java/src/org/mmtk/plan/immix/ImmixTraceLocal.java
deleted file mode 100644
index 0792c33..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/plan/immix/ImmixTraceLocal.java
+++ /dev/null
@@ -1,140 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.plan.immix;
-
-import static org.mmtk.policy.immix.ImmixConstants.MARK_LINE_AT_SCAN_TIME;
-
-import org.mmtk.plan.TraceLocal;
-import org.mmtk.plan.Trace;
-import org.mmtk.policy.Space;
-import org.mmtk.utility.HeaderByte;
-import org.mmtk.utility.deque.ObjectReferenceDeque;
-import org.mmtk.vm.VM;
-
-import org.vmmagic.pragma.*;
-import org.vmmagic.unboxed.*;
-
-/**
- * This class implements the thread-local functionality for a transitive
- * closure over an immix space.
- */
-@Uninterruptible
-public final class ImmixTraceLocal extends TraceLocal {
-
- /****************************************************************************
- *
- * Instance fields
- */
- private final ObjectReferenceDeque modBuffer;
-
- /**
- * Constructor
- *
- * @param trace The trace associated with this trace local.
- * @param modBuffer The modified objects buffer associated with this trace local. Possibly null.
- */
- public ImmixTraceLocal(Trace trace, ObjectReferenceDeque modBuffer) {
- super(Immix.SCAN_IMMIX, trace);
- this.modBuffer = modBuffer;
- }
-
- /****************************************************************************
- *
- * Externally visible Object processing and tracing
- */
-
- /**
- * Is the specified object live?
- *
- * @param object The object.
- * @return True if the object is live.
- */
- public boolean isLive(ObjectReference object) {
- if (object.isNull()) return false;
- if (Space.isInSpace(Immix.IMMIX, object)) {
- return Immix.immixSpace.fastIsLive(object);
- }
- return super.isLive(object);
- }
-
- /**
- * This method is the core method during the trace of the object graph.
- * The role of this method is to:
- *
- * 1. Ensure the traced object is not collected.
- * 2. If this is the first visit to the object enqueue it to be scanned.
- * 3. Return the forwarded reference to the object.
- *
- * In this instance, we refer objects in the mark-sweep space to the
- * immixSpace for tracing, and defer to the superclass for all others.
- *
- * @param object The object to be traced.
- * @return The new reference to the same object instance.
- */
- @Inline
- public ObjectReference traceObject(ObjectReference object) {
- if (object.isNull()) return object;
- if (Space.isInSpace(Immix.IMMIX, object))
- return Immix.immixSpace.fastTraceObject(this, object);
- return super.traceObject(object);
- }
-
- /**
- * Ensure that the referenced object will not move from this point through
- * to the end of the collection. This can involve forwarding the object
- * if necessary.
- *
- * @param object The object that must not move during the collection.
- * @return True If the object will not move during collection
- */
- @Inline
- @Override
- public boolean willNotMoveInCurrentCollection(ObjectReference object) {
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(!Immix.immixSpace.inImmixDefragCollection());
- return true;
- }
-
- /**
- * Collectors that move objects <b>must</b> override this method.
- * It performs the deferred scanning of objects which are forwarded
- * during bootstrap of each copying collection. Because of the
- * complexities of the collection bootstrap (such objects are
- * generally themselves gc-critical), the forwarding and scanning of
- * the objects must be dislocated. It is an error for a non-moving
- * collector to call this method.
- *
- * @param object The forwarded object to be scanned
- */
- @Inline
- @Override
- protected void scanObject(ObjectReference object) {
- super.scanObject(object);
- if (MARK_LINE_AT_SCAN_TIME && Space.isInSpace(Immix.IMMIX, object))
- Immix.immixSpace.markLines(object);
- }
-
- /**
- * Process any remembered set entries. This means enumerating the
- * mod buffer and for each entry, marking the object as unlogged
- * (we don't enqueue for scanning since we're doing a full heap GC).
- */
- protected void processRememberedSets() {
- if (modBuffer != null) {
- logMessage(5, "clearing modBuffer");
- while (!modBuffer.isEmpty()) {
- ObjectReference src = modBuffer.pop();
- HeaderByte.markAsUnlogged(src);
- }
- }
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/plan/markcompact/MC.java b/vmkit/mmtk/java/src/org/mmtk/plan/markcompact/MC.java
deleted file mode 100644
index 9815e5a..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/plan/markcompact/MC.java
+++ /dev/null
@@ -1,244 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.plan.markcompact;
-
-import org.mmtk.plan.*;
-import org.mmtk.policy.MarkCompactSpace;
-import org.mmtk.policy.Space;
-import org.mmtk.utility.heap.VMRequest;
-import org.mmtk.utility.sanitychecker.SanityChecker;
-
-import org.vmmagic.pragma.*;
-import org.vmmagic.unboxed.ObjectReference;
-
-/**
- * This class implements the global state of a simple sliding mark-compact
- * collector.
- *
- * FIXME Need algorithmic overview and references.
- *
- * All plans make a clear distinction between <i>global</i> and
- * <i>thread-local</i> activities, and divides global and local state
- * into separate class hierarchies. Global activities must be
- * synchronized, whereas no synchronization is required for
- * thread-local activities. There is a single instance of Plan (or the
- * appropriate sub-class), and a 1:1 mapping of PlanLocal to "kernel
- * threads" (aka CPUs). Thus instance
- * methods of PlanLocal allow fast, unsychronized access to functions such as
- * allocation and collection.
- *
- * The global instance defines and manages static resources
- * (such as memory and virtual memory resources). This mapping of threads to
- * instances is crucial to understanding the correctness and
- * performance properties of MMTk plans.
- */
-@Uninterruptible public class MC extends StopTheWorld {
-
- /****************************************************************************
- * Class variables
- */
-
- /** The mark compact space itself */
- public static final MarkCompactSpace mcSpace = new MarkCompactSpace("mc", DEFAULT_POLL_FREQUENCY, VMRequest.create(0.6f));
-
- /** The space descriptor */
- public static final int MARK_COMPACT = mcSpace.getDescriptor();
-
- /** Specialized method identifier for the MARK phase */
- public static final int SCAN_MARK = 0;
-
- /** Specialized method identifier for the FORWARD phase */
- public static final int SCAN_FORWARD = 1;
-
- /* Phases */
- public static final short PREPARE_FORWARD = Phase.createSimple("fw-prepare");
- public static final short FORWARD_CLOSURE = Phase.createSimple("fw-closure");
- public static final short RELEASE_FORWARD = Phase.createSimple("fw-release");
-
- /** Calculate forwarding pointers via a linear scan over the heap */
- public static final short CALCULATE_FP = Phase.createSimple("calc-fp");
-
- /** Perform compaction via a linear scan over the heap */
- public static final short COMPACT = Phase.createSimple("compact");
-
- // CHECKSTYLE:OFF
-
- /**
- * This is the phase that is executed to perform a mark-compact collection.
- *
- * FIXME: Far too much duplication and inside knowledge of StopTheWorld
- */
- public short mcCollection = Phase.createComplex("collection", null,
- Phase.scheduleComplex (initPhase),
- Phase.scheduleComplex (rootClosurePhase),
- Phase.scheduleComplex (refTypeClosurePhase),
- Phase.scheduleComplex (completeClosurePhase),
- Phase.scheduleCollector(CALCULATE_FP),
- Phase.scheduleGlobal (PREPARE_FORWARD),
- Phase.scheduleCollector(PREPARE_FORWARD),
- Phase.scheduleMutator (PREPARE),
- Phase.scheduleCollector(STACK_ROOTS),
- Phase.scheduleCollector(ROOTS),
- Phase.scheduleGlobal (ROOTS),
- Phase.scheduleComplex (forwardPhase),
- Phase.scheduleCollector(FORWARD_CLOSURE),
- Phase.scheduleMutator (RELEASE),
- Phase.scheduleCollector(RELEASE_FORWARD),
- Phase.scheduleGlobal (RELEASE_FORWARD),
- Phase.scheduleCollector(COMPACT),
- Phase.scheduleComplex (finishPhase));
-
- // CHECKSTYLE:ON
-
- /****************************************************************************
- * Instance variables
- */
-
- /** This trace sets the mark bit in live objects */
- public final Trace markTrace;
-
- /** This trace updates pointers with the forwarded references */
- public final Trace forwardTrace;
-
- /**
- * Constructor.
- */
- public MC() {
- markTrace = new Trace(metaDataSpace);
- forwardTrace = new Trace(metaDataSpace);
- collection = mcCollection;
- }
-
- /*****************************************************************************
- *
- * Collection
- */
-
-
- /**
- * Perform a (global) collection phase.
- *
- * @param phaseId Collection phase to execute.
- */
- @Override
- @Inline
- public final void collectionPhase(short phaseId) {
- if (phaseId == PREPARE) {
- super.collectionPhase(phaseId);
- markTrace.prepare();
- mcSpace.prepare();
- return;
- }
- if (phaseId == CLOSURE) {
- markTrace.prepare();
- return;
- }
- if (phaseId == RELEASE) {
- markTrace.release();
- mcSpace.release();
- super.collectionPhase(phaseId);
- return;
- }
-
- if (phaseId == PREPARE_FORWARD) {
- super.collectionPhase(PREPARE);
- forwardTrace.prepare();
- mcSpace.prepare();
- return;
- }
- if (phaseId == RELEASE_FORWARD) {
- forwardTrace.release();
- mcSpace.release();
- super.collectionPhase(RELEASE);
- return;
- }
-
- super.collectionPhase(phaseId);
- }
-
- /*****************************************************************************
- *
- * Accounting
- */
-
- /**
- * Return the number of pages reserved for use given the pending
- * allocation. The superclass accounts for its spaces, we just
- * augment this with the mark-sweep space's contribution.
- *
- * @return The number of pages reserved given the pending
- * allocation, excluding space reserved for copying.
- */
- @Override
- public int getPagesUsed() {
- return (mcSpace.reservedPages() + super.getPagesUsed());
- }
-
- /**
- * Calculate the number of pages a collection is required to free to satisfy
- * outstanding allocation requests.
- *
- * @return the number of pages a collection is required to free to satisfy
- * outstanding allocation requests.
- */
- @Override
- public int getPagesRequired() {
- return super.getPagesRequired() + mcSpace.requiredPages();
- }
-
- /**
- * @see org.mmtk.plan.Plan#willNeverMove
- *
- * @param object Object in question
- * @return True if the object will never move
- */
- @Override
- public boolean willNeverMove(ObjectReference object) {
- if (Space.isInSpace(MARK_COMPACT, object))
- return false;
- return super.willNeverMove(object);
- }
-
- /**
- * Return the expected reference count. For non-reference counting
- * collectors this becomes a true/false relationship.
- * @param object The object to check.
- * @param sanityRootRC The number of root references to the object.
- *
- * @return The expected (root excluded) reference count.
- */
- @Override
- public int sanityExpectedRC(ObjectReference object, int sanityRootRC) {
- Space space = Space.getSpaceForObject(object);
-
- // Nursery
- if (space == MC.mcSpace) {
- // We are never sure about objects in MC.
- // This is not very satisfying but allows us to use the sanity checker to
- // detect dangling pointers.
- return SanityChecker.UNSURE;
- }
- return super.sanityExpectedRC(object, sanityRootRC);
- }
-
- /**
- * Register specialized methods.
- */
- @Override
- @Interruptible
- protected void registerSpecializedMethods() {
- TransitiveClosure.registerSpecializedScan(SCAN_MARK, MCMarkTraceLocal.class);
- TransitiveClosure.registerSpecializedScan(SCAN_FORWARD, MCForwardTraceLocal.class);
- super.registerSpecializedMethods();
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/plan/markcompact/MCCollector.java b/vmkit/mmtk/java/src/org/mmtk/plan/markcompact/MCCollector.java
deleted file mode 100644
index 41a6d2c..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/plan/markcompact/MCCollector.java
+++ /dev/null
@@ -1,186 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.plan.markcompact;
-
-import org.mmtk.plan.*;
-import org.mmtk.policy.MarkCompactCollector;
-
-import org.mmtk.vm.VM;
-
-import org.vmmagic.pragma.*;
-import org.vmmagic.unboxed.*;
-
-/**
- * This class implements <i>per-collector thread</i> behavior
- * and state for the <i>MC</i> plan, which implements a full-heap
- * mark-compact collector.<p>
- *
- * Specifically, this class defines <i>MC</i> collection behavior
- * (through <code>trace</code> and the <code>collectionPhase</code>
- * method), and collection-time allocation.<p>
- *
- * @see MC for an overview of the mark-compact algorithm.<p>
- * @see MCMutator
- * @see StopTheWorldCollector
- * @see CollectorContext
- */
-@Uninterruptible public class MCCollector extends StopTheWorldCollector {
-
- private static final boolean TRACE_MARK = false;
- private static final boolean TRACE_FORWARD = true;
-
- /****************************************************************************
- * Instance fields
- */
-
- private final MCMarkTraceLocal markTrace;
- private final MCForwardTraceLocal forwardTrace;
- private final MarkCompactCollector mc;
- private boolean currentTrace;
-
- /****************************************************************************
- *
- * Initialization
- */
-
- /**
- * Constructor
- */
- public MCCollector() {
- markTrace = new MCMarkTraceLocal(global().markTrace);
- forwardTrace = new MCForwardTraceLocal(global().forwardTrace);
- mc = new MarkCompactCollector(MC.mcSpace);
- }
-
-
- /****************************************************************************
- *
- * Collection-time allocation
- */
-
- /**
- * Allocate space for copying an object (this method <i>does not</i>
- * copy the object, it only allocates space)
- *
- * @param original A reference to the original object
- * @param bytes The size of the space to be allocated (in bytes)
- * @param align The requested alignment.
- * @param offset The alignment offset.
- * @return The address of the first byte of the allocated region
- */
- @Override
- @Inline
- public Address allocCopy(ObjectReference original, int bytes,
- int align, int offset, int allocator) {
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(allocator == MC.ALLOC_IMMORTAL);
-
- return immortal.alloc(bytes, align, offset);
- }
-
- /**
- * Perform any post-copy actions.
- *
- * @param object The newly allocated object
- * @param typeRef the type reference for the instance being created
- * @param bytes The size of the space to be allocated (in bytes)
- */
- @Override
- @Inline
- public void postCopy(ObjectReference object, ObjectReference typeRef,
- int bytes, int allocator) {
- MC.immortalSpace.initializeHeader(object);
- }
-
- /****************************************************************************
- *
- * Collection
- */
-
- /**
- * Perform a per-collector collection phase.
- *
- * @param phaseId The collection phase to perform
- * @param primary Perform any single-threaded activities using this thread.
- */
- @Override
- @Inline
- public final void collectionPhase(short phaseId, boolean primary) {
- if (phaseId == MC.PREPARE) {
- currentTrace = TRACE_MARK;
- super.collectionPhase(phaseId, primary);
- markTrace.prepare();
- return;
- }
-
- if (phaseId == MC.CLOSURE) {
- markTrace.completeTrace();
- return;
- }
-
- if (phaseId == MC.CALCULATE_FP) {
- mc.calculateForwardingPointers();
- return;
- }
-
- if (phaseId == MC.COMPACT) {
- mc.compact();
- return;
- }
-
- if (phaseId == MC.RELEASE) {
- markTrace.release();
- super.collectionPhase(phaseId, primary);
- return;
- }
-
- if (phaseId == MC.PREPARE_FORWARD) {
- currentTrace = TRACE_FORWARD;
- super.collectionPhase(MC.PREPARE, primary);
- forwardTrace.prepare();
- return;
- }
-
- if (phaseId == MC.FORWARD_CLOSURE) {
- forwardTrace.completeTrace();
- return;
- }
-
- if (phaseId == MC.RELEASE_FORWARD) {
- forwardTrace.release();
- super.collectionPhase(MC.RELEASE, primary);
- return;
- }
-
- super.collectionPhase(phaseId, primary);
- }
-
- /****************************************************************************
- *
- * Miscellaneous
- */
-
- /** @return The current trace instance. */
- @Override
- public final TraceLocal getCurrentTrace() {
- if (currentTrace == TRACE_MARK) {
- return markTrace;
- }
- return forwardTrace;
- }
-
- /** @return The active global plan as an <code>MC</code> instance. */
- @Inline
- private static MC global() {
- return (MC) VM.activePlan.global();
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/plan/markcompact/MCConstraints.java b/vmkit/mmtk/java/src/org/mmtk/plan/markcompact/MCConstraints.java
deleted file mode 100644
index 4e9750e..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/plan/markcompact/MCConstraints.java
+++ /dev/null
@@ -1,44 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.plan.markcompact;
-
-import org.mmtk.plan.StopTheWorldConstraints;
-
-import org.mmtk.policy.MarkCompactSpace;
-import org.mmtk.policy.MarkCompactLocal;
-
-import org.vmmagic.pragma.*;
-
-/**
- * This class and its subclasses communicate to the host VM/Runtime
- * any features of the selected plan that it needs to know. This is
- * separate from the main Plan/PlanLocal class in order to bypass any
- * issues with ordering of static initialization.
- */
-@Uninterruptible
-public class MCConstraints extends StopTheWorldConstraints {
- @Override
- public boolean movesObjects() { return true; }
- @Override
- public boolean needsForwardAfterLiveness() { return true; }
- @Override
- public boolean needsLinearScan() { return true; }
- @Override
- public int maxNonLOSDefaultAllocBytes() { return MarkCompactLocal.MINIMUM_DATA_SIZE; }
- @Override
- public int gcHeaderBits() { return MarkCompactSpace.LOCAL_GC_BITS_REQUIRED; }
- @Override
- public int gcHeaderWords() { return MarkCompactSpace.GC_HEADER_WORDS_REQUIRED; }
- @Override
- public int numSpecializedScans() { return 2; }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/plan/markcompact/MCForwardTraceLocal.java b/vmkit/mmtk/java/src/org/mmtk/plan/markcompact/MCForwardTraceLocal.java
deleted file mode 100644
index ee25b1b..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/plan/markcompact/MCForwardTraceLocal.java
+++ /dev/null
@@ -1,102 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.plan.markcompact;
-
-import org.mmtk.plan.TraceLocal;
-import org.mmtk.plan.Trace;
-import org.mmtk.policy.Space;
-import org.mmtk.vm.VM;
-
-import org.vmmagic.pragma.*;
-import org.vmmagic.unboxed.*;
-
-/**
- * This class implments the thread-local functionality for a transitive
- * closure over a mark-compact space during the forwarding phase.
- */
-@Uninterruptible
-public final class MCForwardTraceLocal extends TraceLocal {
- /**
- * Constructor
- */
- public MCForwardTraceLocal(Trace trace) {
- super(MC.SCAN_FORWARD, trace);
- }
-
- /****************************************************************************
- *
- * Externally visible Object processing and tracing
- */
-
- /**
- * Is the specified object live?
- *
- * @param object The object.
- * @return True if the object is live.
- */
- public boolean isLive(ObjectReference object) {
- if (object.isNull()) return false;
- if (Space.isInSpace(MC.MARK_COMPACT, object)) {
- return MC.mcSpace.isLive(object);
- }
- return super.isLive(object);
- }
-
- /**
- * This method is the core method during the trace of the object graph.
- * The role of this method is to:
- *
- * 1. Ensure the traced object is not collected.
- * 2. If this is the first visit to the object enqueue it to be scanned.
- * 3. Return the forwarded reference to the object.
- *
- * In this instance, we refer objects in the mark-sweep space to the
- * msSpace for tracing, and defer to the superclass for all others.
- *
- * @param object The object to be traced.
- * @return The new reference to the same object instance.
- */
- @Inline
- public ObjectReference traceObject(ObjectReference object) {
- if (object.isNull()) return object;
- if (Space.isInSpace(MC.MARK_COMPACT, object))
- return MC.mcSpace.traceForwardObject(this, object);
- return super.traceObject(object);
- }
-
- /**
- * Will this object move from this point on, during the current trace ?
- *
- * @param object The object to query.
- * @return True if the object will not move.
- */
- public boolean willNotMoveInCurrentCollection(ObjectReference object) {
- return !Space.isInSpace(MC.MARK_COMPACT, object);
- }
-
- /**
- * Ensure that this object will not move for the rest of the GC.
- *
- * @param object The object that must not move
- * @return The new object, guaranteed stable for the rest of the GC.
- */
- @Inline
- public ObjectReference precopyObject(ObjectReference object) {
- if (VM.VERIFY_ASSERTIONS) {
- // All precopying must occur during the initial trace.
- VM.assertions._assert(!Space.isInSpace(MC.MARK_COMPACT, object));
- }
- return super.precopyObject(object);
- }
-
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/plan/markcompact/MCMarkTraceLocal.java b/vmkit/mmtk/java/src/org/mmtk/plan/markcompact/MCMarkTraceLocal.java
deleted file mode 100644
index a044954..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/plan/markcompact/MCMarkTraceLocal.java
+++ /dev/null
@@ -1,113 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.plan.markcompact;
-
-import org.mmtk.plan.TraceLocal;
-import org.mmtk.plan.Trace;
-import org.mmtk.policy.MarkCompactSpace;
-import org.mmtk.policy.Space;
-import org.mmtk.vm.VM;
-
-import org.vmmagic.pragma.*;
-import org.vmmagic.unboxed.*;
-
-/**
- * This class implments the thread-local functionality for a transitive
- * closure over a mark-compact space during the initial marking phase.
- */
-@Uninterruptible
-public final class MCMarkTraceLocal extends TraceLocal {
- /**
- * Constructor
- */
- public MCMarkTraceLocal(Trace trace) {
- super(MC.SCAN_MARK, trace);
- }
-
- /****************************************************************************
- *
- * Externally visible Object processing and tracing
- */
-
- /**
- * Is the specified object live?
- *
- * @param object The object.
- * @return True if the object is live.
- */
- public boolean isLive(ObjectReference object) {
- if (object.isNull()) return false;
- if (Space.isInSpace(MC.MARK_COMPACT, object)) {
- return MC.mcSpace.isLive(object);
- }
- return super.isLive(object);
- }
-
- /**
- * This method is the core method during the trace of the object graph.
- * The role of this method is to:
- *
- * 1. Ensure the traced object is not collected.
- * 2. If this is the first visit to the object enqueue it to be scanned.
- * 3. Return the forwarded reference to the object.
- *
- * In this instance, we refer objects in the mark-sweep space to the
- * msSpace for tracing, and defer to the superclass for all others.
- *
- * @param object The object to be traced.
- * @return The new reference to the same object instance.
- */
- @Inline
- public ObjectReference traceObject(ObjectReference object) {
- if (object.isNull()) return object;
- if (Space.isInSpace(MC.MARK_COMPACT, object))
- return MC.mcSpace.traceMarkObject(this, object);
- return super.traceObject(object);
- }
-
- /**
- * Ensure that this object will not move for the rest of the GC.
- *
- * @param object The object that must not move
- * @return The new object, guaranteed stable for the rest of the GC.
- */
- @Inline
- public ObjectReference precopyObject(ObjectReference object) {
- if (Space.isInSpace(MC.MARK_COMPACT, object)) {
- if (MarkCompactSpace.testAndMark(object)) {
- // TODO: If precopy returns many different objects, this will cause a leak.
- // Currently, Jikes RVM does not require many objects to be precopied.
- ObjectReference newObject = VM.objectModel.copy(object, MC.ALLOC_IMMORTAL);
- MarkCompactSpace.setForwardingPointer(object, newObject);
- processNode(newObject);
- return newObject;
- }
- // Somebody else got to it first
- while (MarkCompactSpace.getForwardingPointer(object).isNull());
- return MarkCompactSpace.getForwardingPointer(object);
- }
- return super.precopyObject(object);
- }
-
- /**
- * Will this object move from this point on, during the current trace ?
- *
- * @param object The object to query.
- * @return True if the object will not move.
- */
- public boolean willNotMoveInCurrentCollection(ObjectReference object) {
- // All objects in the MC space may move
- return !Space.isInSpace(MC.MARK_COMPACT, object);
- }
-
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/plan/markcompact/MCMutator.java b/vmkit/mmtk/java/src/org/mmtk/plan/markcompact/MCMutator.java
deleted file mode 100644
index 78c25e2..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/plan/markcompact/MCMutator.java
+++ /dev/null
@@ -1,162 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.plan.markcompact;
-
-import org.mmtk.plan.StopTheWorldMutator;
-import org.mmtk.policy.MarkCompactLocal;
-import org.mmtk.policy.Space;
-
-import org.mmtk.utility.alloc.Allocator;
-
-import org.vmmagic.pragma.*;
-import org.vmmagic.unboxed.*;
-
-/**
- * This class implements <i>per-mutator thread</i> behavior
- * and state for the <i>MC</i> plan, which implements a full-heap
- * mark-compact collector.<p>
- *
- * Specifically, this class defines <i>MC</i> mutator-time allocation
- * and per-mutator thread collection semantics (flushing and restoring
- * per-mutator allocator state).
- *
- * See {@link MC} for an overview of the mark-compact algorithm.<p>
- *
- * @see MC
- * @see MCCollector
- * @see org.mmtk.plan.StopTheWorldMutator
- * @see org.mmtk.plan.MutatorContext
- */
-@Uninterruptible public class MCMutator extends StopTheWorldMutator {
-
- /****************************************************************************
- * Instance fields
- */
- private final MarkCompactLocal mc;
-
- /****************************************************************************
- *
- * Initialization
- */
-
- /**
- * Constructor
- */
- public MCMutator() {
- mc = new MarkCompactLocal(MC.mcSpace);
- }
-
- /****************************************************************************
- *
- * Mutator-time allocation
- */
-
- /**
- * Allocate memory for an object. This class handles the default allocator
- * from the mark sweep space, and delegates everything else to the
- * superclass.
- *
- * @param bytes The number of bytes required for the object.
- * @param align Required alignment for the object.
- * @param offset Offset associated with the alignment.
- * @param allocator The allocator associated with this request.
- * @param site Allocation site
- * @return The low address of the allocated memory.
- */
- @Override
- @Inline
- public Address alloc(int bytes, int align, int offset, int allocator, int site) {
- if (allocator == MC.ALLOC_DEFAULT) {
- return mc.alloc(bytes, align, offset);
- }
- return super.alloc(bytes, align, offset, allocator, site);
- }
-
- /**
- * Perform post-allocation actions. Initialize the object header for
- * objects in the mark-sweep space, and delegate to the superclass for
- * other objects.
- *
- * @param ref The newly allocated object
- * @param typeRef the type reference for the instance being created
- * @param bytes The size of the space to be allocated (in bytes)
- * @param allocator The allocator number to be used for this allocation
- */
- @Override
- @Inline
- public void postAlloc(ObjectReference ref, ObjectReference typeRef,
- int bytes, int allocator) {
- if (allocator == MC.ALLOC_DEFAULT)
- MC.mcSpace.initializeHeader(ref);
- else
- super.postAlloc(ref, typeRef, bytes, allocator);
- }
-
- /**
- * Return the allocator instance associated with a space
- * <code>space</code>, for this plan instance.
- *
- * @param space The space for which the allocator instance is desired.
- * @return The allocator instance associated with this plan instance
- * which is allocating into <code>space</code>, or <code>null</code>
- * if no appropriate allocator can be established.
- */
- @Override
- public Allocator getAllocatorFromSpace(Space space) {
- if (space == MC.mcSpace) return mc;
- return super.getAllocatorFromSpace(space);
- }
-
-
- /****************************************************************************
- *
- * Collection
- */
-
- /**
- * Perform a per-mutator collection phase.
- *
- * @param phaseId The collection phase to perform
- * @param primary Perform any single-threaded activities using this thread.
- */
- @Override
- @Inline
- public final void collectionPhase(short phaseId, boolean primary) {
- if (phaseId == MC.PREPARE) {
- mc.prepare();
- super.collectionPhase(phaseId, primary);
- return;
- }
-
- if (phaseId == MC.RELEASE) {
- super.collectionPhase(phaseId, primary);
- return;
- }
- super.collectionPhase(phaseId, primary);
- }
-
- /**
- * Flush the pages this mutator has allocated back to the global
- * dirty page list, where the collectors can find them.
- *
- * @see org.mmtk.plan.MutatorContext#flush()
- */
- @Override
- public void flush() {
- super.flush();
- mc.flush();
- }
-
-
-
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/plan/marksweep/MS.java b/vmkit/mmtk/java/src/org/mmtk/plan/marksweep/MS.java
deleted file mode 100644
index 442d223..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/plan/marksweep/MS.java
+++ /dev/null
@@ -1,149 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.plan.marksweep;
-
-import org.mmtk.plan.*;
-import org.mmtk.policy.MarkSweepSpace;
-import org.mmtk.policy.Space;
-import org.mmtk.utility.heap.VMRequest;
-
-import org.vmmagic.pragma.*;
-import org.vmmagic.unboxed.*;
-
-/**
- * This class implements the global state of a simple mark-sweep collector.
- *
- * All plans make a clear distinction between <i>global</i> and
- * <i>thread-local</i> activities, and divides global and local state
- * into separate class hierarchies. Global activities must be
- * synchronized, whereas no synchronization is required for
- * thread-local activities. There is a single instance of Plan (or the
- * appropriate sub-class), and a 1:1 mapping of PlanLocal to "kernel
- * threads" (aka CPUs). Thus instance
- * methods of PlanLocal allow fast, unsychronized access to functions such as
- * allocation and collection.
- *
- * The global instance defines and manages static resources
- * (such as memory and virtual memory resources). This mapping of threads to
- * instances is crucial to understanding the correctness and
- * performance properties of MMTk plans.
- */
-@Uninterruptible
-public class MS extends StopTheWorld {
-
- /****************************************************************************
- * Class variables
- */
- public static final MarkSweepSpace msSpace = new MarkSweepSpace("ms", DEFAULT_POLL_FREQUENCY, VMRequest.create());
- public static final int MARK_SWEEP = msSpace.getDescriptor();
-
- public static final int SCAN_MARK = 0;
-
-
- /****************************************************************************
- * Instance variables
- */
- public final Trace msTrace = new Trace(metaDataSpace);
-
-
- /*****************************************************************************
- * Collection
- */
-
- /**
- * Perform a (global) collection phase.
- *
- * @param phaseId Collection phase to execute.
- */
- @Inline
- @Override
- public void collectionPhase(short phaseId) {
-
- if (phaseId == PREPARE) {
- super.collectionPhase(phaseId);
- msTrace.prepare();
- msSpace.prepare(true);
- return;
- }
-
- if (phaseId == CLOSURE) {
- msTrace.prepare();
- return;
- }
- if (phaseId == RELEASE) {
- msTrace.release();
- msSpace.release();
- super.collectionPhase(phaseId);
- return;
- }
-
- super.collectionPhase(phaseId);
- }
-
- /*****************************************************************************
- * Accounting
- */
-
- /**
- * Return the number of pages reserved for use given the pending
- * allocation. The superclass accounts for its spaces, we just
- * augment this with the mark-sweep space's contribution.
- *
- * @return The number of pages reserved given the pending
- * allocation, excluding space reserved for copying.
- */
- @Override
- public int getPagesUsed() {
- return (msSpace.reservedPages() + super.getPagesUsed());
- }
-
- /**
- * Calculate the number of pages a collection is required to free to satisfy
- * outstanding allocation requests.
- *
- * @return the number of pages a collection is required to free to satisfy
- * outstanding allocation requests.
- */
- @Override
- public int getPagesRequired() {
- return super.getPagesRequired() + msSpace.requiredPages();
- }
-
-
- /*****************************************************************************
- * Miscellaneous
- */
-
- /**
- * @see org.mmtk.plan.Plan#willNeverMove
- *
- * @param object Object in question
- * @return True if the object will never move
- */
- @Override
- public boolean willNeverMove(ObjectReference object) {
- if (Space.isInSpace(MARK_SWEEP, object))
- return true;
- return super.willNeverMove(object);
- }
-
- /**
- * Register specialized methods.
- */
- @Interruptible
- @Override
- protected void registerSpecializedMethods() {
- TransitiveClosure.registerSpecializedScan(SCAN_MARK, MSTraceLocal.class);
- super.registerSpecializedMethods();
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/plan/marksweep/MSCollector.java b/vmkit/mmtk/java/src/org/mmtk/plan/marksweep/MSCollector.java
deleted file mode 100644
index 823ed24..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/plan/marksweep/MSCollector.java
+++ /dev/null
@@ -1,95 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.plan.marksweep;
-
-import org.mmtk.plan.*;
-import org.mmtk.vm.VM;
-
-import org.vmmagic.pragma.*;
-
-/**
- * This class implements <i>per-collector thread</i> behavior
- * and state for the <i>MS</i> plan, which implements a full-heap
- * mark-sweep collector.<p>
- *
- * Specifically, this class defines <i>MS</i> collection behavior
- * (through <code>trace</code> and the <code>collectionPhase</code>
- * method).<p>
- *
- * @see MS for an overview of the mark-sweep algorithm.<p>
- *
- * @see MS
- * @see MSMutator
- * @see StopTheWorldCollector
- * @see CollectorContext
- */
-@Uninterruptible
-public class MSCollector extends StopTheWorldCollector {
-
- /****************************************************************************
- * Instance fields
- */
- protected MSTraceLocal fullTrace = new MSTraceLocal(global().msTrace, null);;
- protected TraceLocal currentTrace = fullTrace;
-
-
- /****************************************************************************
- * Collection
- */
-
- /**
- * Perform a per-collector collection phase.
- *
- * @param phaseId The collection phase to perform
- * @param primary Perform any single-threaded activities using this thread.
- */
- @Inline
- @Override
- public void collectionPhase(short phaseId, boolean primary) {
- if (phaseId == MS.PREPARE) {
- super.collectionPhase(phaseId, primary);
- fullTrace.prepare();
- return;
- }
-
- if (phaseId == MS.CLOSURE) {
- fullTrace.completeTrace();
- return;
- }
-
- if (phaseId == MS.RELEASE) {
- fullTrace.release();
- super.collectionPhase(phaseId, primary);
- return;
- }
-
- super.collectionPhase(phaseId, primary);
- }
-
-
- /****************************************************************************
- * Miscellaneous
- */
-
- /** @return The active global plan as an <code>MS</code> instance. */
- @Inline
- private static MS global() {
- return (MS) VM.activePlan.global();
- }
-
- /** @return The current trace instance. */
- @Override
- public final TraceLocal getCurrentTrace() {
- return currentTrace;
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/plan/marksweep/MSConstraints.java b/vmkit/mmtk/java/src/org/mmtk/plan/marksweep/MSConstraints.java
deleted file mode 100644
index acf8288..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/plan/marksweep/MSConstraints.java
+++ /dev/null
@@ -1,38 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.plan.marksweep;
-
-import org.mmtk.plan.StopTheWorldConstraints;
-
-import org.mmtk.policy.MarkSweepSpace;
-import org.mmtk.policy.SegregatedFreeListSpace;
-
-import org.vmmagic.pragma.*;
-
-/**
- * This class and its subclasses communicate to the host VM/Runtime
- * any features of the selected plan that it needs to know. This is
- * separate from the main Plan/PlanLocal class in order to bypass any
- * issues with ordering of static initialization.
- */
-@Uninterruptible
-public class MSConstraints extends StopTheWorldConstraints {
- @Override
- public int gcHeaderBits() { return MarkSweepSpace.LOCAL_GC_BITS_REQUIRED; }
- @Override
- public int gcHeaderWords() { return MarkSweepSpace.GC_HEADER_WORDS_REQUIRED; }
- @Override
- public int maxNonLOSDefaultAllocBytes() { return SegregatedFreeListSpace.MAX_FREELIST_OBJECT_BYTES; }
- @Override
- public int numSpecializedScans() { return 1; }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/plan/marksweep/MSMutator.java b/vmkit/mmtk/java/src/org/mmtk/plan/marksweep/MSMutator.java
deleted file mode 100644
index 04faa51..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/plan/marksweep/MSMutator.java
+++ /dev/null
@@ -1,143 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.plan.marksweep;
-
-import org.mmtk.plan.*;
-import org.mmtk.policy.MarkSweepLocal;
-import org.mmtk.policy.Space;
-import org.mmtk.utility.alloc.Allocator;
-
-import org.vmmagic.pragma.*;
-import org.vmmagic.unboxed.*;
-
-/**
- * This class implements <i>per-mutator thread</i> behavior
- * and state for the <i>MS</i> plan, which implements a full-heap
- * mark-sweep collector.<p>
- *
- * Specifically, this class defines <i>MS</i> mutator-time allocation
- * and per-mutator thread collection semantics (flushing and restoring
- * per-mutator allocator state).<p>
- *
- * @see MS
- * @see MSCollector
- * @see StopTheWorldMutator
- * @see MutatorContext
- */
-@Uninterruptible
-public class MSMutator extends StopTheWorldMutator {
-
- /****************************************************************************
- * Instance fields
- */
- protected MarkSweepLocal ms = new MarkSweepLocal(MS.msSpace);
-
-
- /****************************************************************************
- * Mutator-time allocation
- */
-
- /**
- * Allocate memory for an object. This class handles the default allocator
- * from the mark sweep space, and delegates everything else to the
- * superclass.
- *
- * @param bytes The number of bytes required for the object.
- * @param align Required alignment for the object.
- * @param offset Offset associated with the alignment.
- * @param allocator The allocator associated with this request.
- * @return The low address of the allocated memory.
- */
- @Inline
- @Override
- public Address alloc(int bytes, int align, int offset, int allocator, int site) {
- if (allocator == MS.ALLOC_DEFAULT) {
- return ms.alloc(bytes, align, offset);
- }
- return super.alloc(bytes, align, offset, allocator, site);
- }
-
- /**
- * Perform post-allocation actions. Initialize the object header for
- * objects in the mark-sweep space, and delegate to the superclass for
- * other objects.
- *
- * @param ref The newly allocated object
- * @param typeRef the type reference for the instance being created
- * @param bytes The size of the space to be allocated (in bytes)
- * @param allocator The allocator number to be used for this allocation
- */
- @Inline
- @Override
- public void postAlloc(ObjectReference ref, ObjectReference typeRef,
- int bytes, int allocator) {
- if (allocator == MS.ALLOC_DEFAULT)
- MS.msSpace.postAlloc(ref);
- else
- super.postAlloc(ref, typeRef, bytes, allocator);
- }
-
- /**
- * Return the allocator instance associated with a space
- * <code>space</code>, for this plan instance.
- *
- * @param space The space for which the allocator instance is desired.
- * @return The allocator instance associated with this plan instance
- * which is allocating into <code>space</code>, or <code>null</code>
- * if no appropriate allocator can be established.
- */
- @Override
- public Allocator getAllocatorFromSpace(Space space) {
- if (space == MS.msSpace) return ms;
- return super.getAllocatorFromSpace(space);
- }
-
-
- /****************************************************************************
- * Collection
- */
-
- /**
- * Perform a per-mutator collection phase.
- *
- * @param phaseId The collection phase to perform
- * @param primary Perform any single-threaded activities using this thread.
- */
- @Inline
- @Override
- public void collectionPhase(short phaseId, boolean primary) {
- if (phaseId == MS.PREPARE) {
- super.collectionPhase(phaseId, primary);
- ms.prepare();
- return;
- }
-
- if (phaseId == MS.RELEASE) {
- ms.release();
- super.collectionPhase(phaseId, primary);
- return;
- }
-
- super.collectionPhase(phaseId, primary);
- }
-
- /**
- * Flush mutator context, in response to a requestMutatorFlush.
- * Also called by the default implementation of deinitMutator.
- */
- @Override
- public void flush() {
- super.flush();
- ms.flush();
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/plan/marksweep/MSTraceLocal.java b/vmkit/mmtk/java/src/org/mmtk/plan/marksweep/MSTraceLocal.java
deleted file mode 100644
index 3f62b0b..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/plan/marksweep/MSTraceLocal.java
+++ /dev/null
@@ -1,100 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.plan.marksweep;
-
-import org.mmtk.plan.TraceLocal;
-import org.mmtk.plan.Trace;
-import org.mmtk.policy.Space;
-import org.mmtk.utility.HeaderByte;
-import org.mmtk.utility.deque.ObjectReferenceDeque;
-
-import org.vmmagic.pragma.*;
-import org.vmmagic.unboxed.*;
-
-/**
- * This class implements the thread-local functionality for a transitive
- * closure over a mark-sweep space.
- */
-@Uninterruptible
-public final class MSTraceLocal extends TraceLocal {
- /****************************************************************************
- * Instance fields
- */
- private final ObjectReferenceDeque modBuffer;
-
- /**
- * Constructor
- */
- public MSTraceLocal(Trace trace, ObjectReferenceDeque modBuffer) {
- super(MS.SCAN_MARK, trace);
- this.modBuffer = modBuffer;
- }
-
-
- /****************************************************************************
- * Externally visible Object processing and tracing
- */
-
- /**
- * Is the specified object live?
- *
- * @param object The object.
- * @return <code>true</code> if the object is live.
- */
- @Override
- public boolean isLive(ObjectReference object) {
- if (object.isNull()) return false;
- if (Space.isInSpace(MS.MARK_SWEEP, object)) {
- return MS.msSpace.isLive(object);
- }
- return super.isLive(object);
- }
-
- /**
- * This method is the core method during the trace of the object graph.
- * The role of this method is to:
- *
- * 1. Ensure the traced object is not collected.
- * 2. If this is the first visit to the object enqueue it to be scanned.
- * 3. Return the forwarded reference to the object.
- *
- * In this instance, we refer objects in the mark-sweep space to the
- * msSpace for tracing, and defer to the superclass for all others.
- *
- * @param object The object to be traced.
- * @return The new reference to the same object instance.
- */
- @Inline
- @Override
- public ObjectReference traceObject(ObjectReference object) {
- if (object.isNull()) return object;
- if (Space.isInSpace(MS.MARK_SWEEP, object))
- return MS.msSpace.traceObject(this, object);
- return super.traceObject(object);
- }
-
- /**
- * Process any remembered set entries. This means enumerating the
- * mod buffer and for each entry, marking the object as unlogged
- * (we don't enqueue for scanning since we're doing a full heap GC).
- */
- protected void processRememberedSets() {
- if (modBuffer != null) {
- logMessage(5, "clearing modBuffer");
- while (!modBuffer.isEmpty()) {
- ObjectReference src = modBuffer.pop();
- HeaderByte.markAsUnlogged(src);
- }
- }
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/plan/nogc/NoGC.java b/vmkit/mmtk/java/src/org/mmtk/plan/nogc/NoGC.java
deleted file mode 100644
index 193b74f..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/plan/nogc/NoGC.java
+++ /dev/null
@@ -1,97 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.plan.nogc;
-
-import org.mmtk.plan.*;
-import org.mmtk.policy.ImmortalSpace;
-import org.mmtk.utility.heap.VMRequest;
-import org.mmtk.vm.VM;
-
-import org.vmmagic.pragma.*;
-
-
-/**
- * This class implements the global state of a a simple allocator
- * without a collector.
- */
-@Uninterruptible
-public class NoGC extends Plan {
-
- /*****************************************************************************
- * Class variables
- */
- public static final ImmortalSpace noGCSpace = new ImmortalSpace("default", DEFAULT_POLL_FREQUENCY, VMRequest.create());
- public static final int NOGC = noGCSpace.getDescriptor();
-
-
- /*****************************************************************************
- * Instance variables
- */
- public final Trace trace = new Trace(metaDataSpace);
-
-
- /*****************************************************************************
- * Collection
- */
-
- /**
- * Perform a (global) collection phase.
- *
- * @param phaseId Collection phase
- */
- @Inline
- @Override
- public final void collectionPhase(short phaseId) {
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(false);
- /*
- if (phaseId == PREPARE) {
- }
- if (phaseId == CLOSURE) {
- }
- if (phaseId == RELEASE) {
- }
- super.collectionPhase(phaseId);
- */
- }
-
- /*****************************************************************************
- * Accounting
- */
-
- /**
- * Return the number of pages reserved for use given the pending
- * allocation. The superclass accounts for its spaces, we just
- * augment this with the default space's contribution.
- *
- * @return The number of pages reserved given the pending
- * allocation, excluding space reserved for copying.
- */
- @Override
- public int getPagesUsed() {
- return (noGCSpace.reservedPages() + super.getPagesUsed());
- }
-
-
- /*****************************************************************************
- * Miscellaneous
- */
-
- /**
- * Register specialized methods.
- */
- @Interruptible
- @Override
- protected void registerSpecializedMethods() {
- super.registerSpecializedMethods();
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/plan/nogc/NoGCCollector.java b/vmkit/mmtk/java/src/org/mmtk/plan/nogc/NoGCCollector.java
deleted file mode 100644
index ff3f674..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/plan/nogc/NoGCCollector.java
+++ /dev/null
@@ -1,111 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.plan.nogc;
-
-import org.mmtk.plan.*;
-import org.mmtk.vm.VM;
-
-import org.vmmagic.pragma.*;
-
-/**
- * This class implements <i>per-collector thread</i> behavior and state
- * for the <i>NoGC</i> plan, which simply allocates (without ever collecting
- * until the available space is exhausted.<p>
- *
- * Specifically, this class <i>would</i> define <i>NoGC</i> collection time semantics,
- * however, since this plan never collects, this class consists only of stubs which
- * may be useful as a template for implementing a basic collector.
- *
- * @see NoGC
- * @see NoGCMutator
- * @see CollectorContext
- */
-@Uninterruptible
-public class NoGCCollector extends CollectorContext {
-
- /************************************************************************
- * Instance fields
- */
- private final NoGCTraceLocal trace = new NoGCTraceLocal(global().trace);
- protected final TraceLocal currentTrace = trace;
-
-
- /****************************************************************************
- * Collection
- */
-
- /**
- * Perform a garbage collection
- */
- @Override
- public final void collect() {
- VM.assertions.fail("GC Triggered in NoGC Plan. Is -X:gc:ignoreSystemGC=true ?");
- }
-
- /** Perform some concurrent garbage collection */
- @Override
- public final void concurrentCollect() {
- VM.assertions.fail("Concurrent GC Triggered in NoGC Plan.");
- }
-
- /**
- * Perform a per-collector collection phase.
- *
- * @param phaseId The collection phase to perform
- * @param primary perform any single-threaded local activities.
- */
- @Inline
- @Override
- public final void collectionPhase(short phaseId, boolean primary) {
- VM.assertions.fail("GC Triggered in NoGC Plan.");
- /*
- if (phaseId == NoGC.PREPARE) {
- }
-
- if (phaseId == NoGC.CLOSURE) {
- }
-
- if (phaseId == NoGC.RELEASE) {
- }
-
- super.collectionPhase(phaseId, primary);
- */
- }
-
- /**
- * Perform some concurrent collection work.
- *
- * @param phaseId The unique phase identifier
- */
- @Override
- public void concurrentCollectionPhase(short phaseId) {
- VM.assertions.fail("GC Triggered in NoGC Plan.");
- }
-
-
- /****************************************************************************
- * Miscellaneous
- */
-
- /** @return The active global plan as a <code>NoGC</code> instance. */
- @Inline
- private static NoGC global() {
- return (NoGC) VM.activePlan.global();
- }
-
- /** @return The current trace instance. */
- @Override
- public final TraceLocal getCurrentTrace() {
- return currentTrace;
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/plan/nogc/NoGCConstraints.java b/vmkit/mmtk/java/src/org/mmtk/plan/nogc/NoGCConstraints.java
deleted file mode 100644
index 9302916..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/plan/nogc/NoGCConstraints.java
+++ /dev/null
@@ -1,31 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.plan.nogc;
-
-import org.mmtk.plan.PlanConstraints;
-
-import org.vmmagic.pragma.*;
-
-/**
- * This class and its subclasses communicate to the host VM/Runtime
- * any features of the selected plan that it needs to know. This is
- * separate from the main Plan/PlanLocal class in order to bypass any
- * issues with ordering of static initialization.
- */
-@Uninterruptible
-public class NoGCConstraints extends PlanConstraints {
- @Override
- public int gcHeaderBits() { return 0; }
- @Override
- public int gcHeaderWords() { return 0; }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/plan/nogc/NoGCMutator.java b/vmkit/mmtk/java/src/org/mmtk/plan/nogc/NoGCMutator.java
deleted file mode 100644
index c1658ce..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/plan/nogc/NoGCMutator.java
+++ /dev/null
@@ -1,128 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.plan.nogc;
-
-import org.mmtk.plan.MutatorContext;
-import org.mmtk.policy.ImmortalLocal;
-import org.mmtk.policy.Space;
-import org.mmtk.utility.alloc.Allocator;
-import org.mmtk.vm.VM;
-
-import org.vmmagic.pragma.*;
-import org.vmmagic.unboxed.*;
-
-/**
- * This class implements <i>per-mutator thread</i> behavior and state
- * for the <i>NoGC</i> plan, which simply allocates (without ever collecting
- * until the available space is exhausted.<p>
- *
- * Specifically, this class defines <i>NoGC</i> mutator-time allocation
- * through a bump pointer (<code>def</code>) and includes stubs for
- * per-mutator thread collection semantics (since there is no collection
- * in this plan, these remain just stubs).
- *
- * @see NoGC
- * @see NoGCCollector
- * @see org.mmtk.plan.StopTheWorldMutator
- * @see org.mmtk.plan.MutatorContext
- */
-@Uninterruptible
-public class NoGCMutator extends MutatorContext {
-
- /************************************************************************
- * Instance fields
- */
- private final ImmortalLocal nogc = new ImmortalLocal(NoGC.noGCSpace);
-
-
- /****************************************************************************
- * Mutator-time allocation
- */
-
- /**
- * Allocate memory for an object.
- *
- * @param bytes The number of bytes required for the object.
- * @param align Required alignment for the object.
- * @param offset Offset associated with the alignment.
- * @param allocator The allocator associated with this request.
- * @param site Allocation site
- * @return The address of the newly allocated memory.
- */
- @Inline
- @Override
- public Address alloc(int bytes, int align, int offset, int allocator, int site) {
- if (allocator == NoGC.ALLOC_DEFAULT) {
- return nogc.alloc(bytes, align, offset);
- }
- return super.alloc(bytes, align, offset, allocator, site);
- }
-
- /**
- * Perform post-allocation actions. For many allocators none are
- * required.
- *
- * @param ref The newly allocated object
- * @param typeRef the type reference for the instance being created
- * @param bytes The size of the space to be allocated (in bytes)
- * @param allocator The allocator number to be used for this allocation
- */
- @Inline
- @Override
- public void postAlloc(ObjectReference ref, ObjectReference typeRef,
- int bytes, int allocator) {
- if (allocator != NoGC.ALLOC_DEFAULT) {
- super.postAlloc(ref, typeRef, bytes, allocator);
- }
- }
-
- /**
- * Return the allocator instance associated with a space
- * <code>space</code>, for this plan instance.
- *
- * @param space The space for which the allocator instance is desired.
- * @return The allocator instance associated with this plan instance
- * which is allocating into <code>space</code>, or <code>null</code>
- * if no appropriate allocator can be established.
- */
- @Override
- public Allocator getAllocatorFromSpace(Space space) {
- if (space == NoGC.noGCSpace) return nogc;
- return super.getAllocatorFromSpace(space);
- }
-
-
- /****************************************************************************
- * Collection
- */
-
- /**
- * Perform a per-mutator collection phase.
- *
- * @param phaseId The collection phase to perform
- * @param primary perform any single-threaded local activities.
- */
- @Inline
- @Override
- public final void collectionPhase(short phaseId, boolean primary) {
- VM.assertions.fail("GC Triggered in NoGC Plan.");
- /*
- if (phaseId == NoGC.PREPARE) {
- }
-
- if (phaseId == NoGC.RELEASE) {
- }
- super.collectionPhase(phaseId, primary);
- */
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/plan/nogc/NoGCTraceLocal.java b/vmkit/mmtk/java/src/org/mmtk/plan/nogc/NoGCTraceLocal.java
deleted file mode 100644
index 2c5b1d4..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/plan/nogc/NoGCTraceLocal.java
+++ /dev/null
@@ -1,75 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.plan.nogc;
-
-import org.mmtk.plan.TraceLocal;
-import org.mmtk.plan.Trace;
-import org.mmtk.policy.Space;
-
-import org.vmmagic.pragma.*;
-import org.vmmagic.unboxed.*;
-
-/**
- * This class implements the thread-local core functionality for a transitive
- * closure over the heap graph.
- */
-@Uninterruptible
-public final class NoGCTraceLocal extends TraceLocal {
-
- /**
- * Constructor
- */
- public NoGCTraceLocal(Trace trace) {
- super(trace);
- }
-
-
- /****************************************************************************
- * Externally visible Object processing and tracing
- */
-
- /**
- * Is the specified object live?
- *
- * @param object The object.
- * @return <code>true</code> if the object is live.
- */
- @Override
- public boolean isLive(ObjectReference object) {
- if (object.isNull()) return false;
- if (Space.isInSpace(NoGC.NOGC, object)) {
- return NoGC.noGCSpace.isLive(object);
- }
- return super.isLive(object);
- }
-
- /**
- * This method is the core method during the trace of the object graph.
- * The role of this method is to:
- *
- * 1. Ensure the traced object is not collected.
- * 2. If this is the first visit to the object enqueue it to be scanned.
- * 3. Return the forwarded reference to the object.
- *
- * @param object The object to be traced.
- * @return The new reference to the same object instance.
- */
- @Inline
- @Override
- public ObjectReference traceObject(ObjectReference object) {
- if (object.isNull()) return object;
- if (Space.isInSpace(NoGC.NOGC, object))
- return NoGC.noGCSpace.traceObject(this, object);
- return super.traceObject(object);
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/plan/poisoned/Poisoned.java b/vmkit/mmtk/java/src/org/mmtk/plan/poisoned/Poisoned.java
deleted file mode 100644
index 7b61cd6..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/plan/poisoned/Poisoned.java
+++ /dev/null
@@ -1,80 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.plan.poisoned;
-
-import org.mmtk.plan.marksweep.MS;
-
-import org.vmmagic.pragma.*;
-import org.vmmagic.unboxed.Address;
-import org.vmmagic.unboxed.ObjectReference;
-import org.vmmagic.unboxed.Word;
-
-/**
- * This class implements a poisoned collector, that is essentially a test
- * case for read and write barriers in the VM.
- */
-@Uninterruptible
-public class Poisoned extends MS {
- /**
- * Perform any required write barrier action when installing an object reference
- * a boot time.
- *
- * @param reference the reference value that is to be stored
- * @return The raw value to be
- */
- public Word bootTimeWriteBarrier(Word reference) {
- return reference.or(Word.one());
- }
-
- /**
- * Poison a reference value.
- */
- @Inline
- public static Word poison(ObjectReference reference) {
- return reference.toAddress().toWord().or(Word.one());
- }
-
- /**
- * DePoison a reference value.
- */
- @Inline
- public static ObjectReference depoison(Word value) {
- return value.and(Word.one().not()).toAddress().toObjectReference();
- }
-
- /****************************************************************************
- * Internal read/write barriers.
- */
-
- /**
- * Store an object reference
- *
- * @param slot The location of the reference
- * @param value The value to store
- */
- @Inline
- public void storeObjectReference(Address slot, ObjectReference value) {
- slot.store(poison(value));
- }
-
- /**
- * Load an object reference
- *
- * @param slot The location of the reference
- * @return the object reference loaded from slot
- */
- @Inline
- public ObjectReference loadObjectReference(Address slot) {
- return depoison(slot.loadWord());
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/plan/poisoned/PoisonedCollector.java b/vmkit/mmtk/java/src/org/mmtk/plan/poisoned/PoisonedCollector.java
deleted file mode 100644
index c1576d7..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/plan/poisoned/PoisonedCollector.java
+++ /dev/null
@@ -1,25 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.plan.poisoned;
-
-import org.mmtk.plan.marksweep.MSCollector;
-
-import org.vmmagic.pragma.Uninterruptible;
-
-/**
- * This class implements a poisoned collector, that is essentially a test
- * case for read and write barriers in the VM.
- */
-@Uninterruptible
-public class PoisonedCollector extends MSCollector {
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/plan/poisoned/PoisonedConstraints.java b/vmkit/mmtk/java/src/org/mmtk/plan/poisoned/PoisonedConstraints.java
deleted file mode 100644
index dad02e9..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/plan/poisoned/PoisonedConstraints.java
+++ /dev/null
@@ -1,34 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.plan.poisoned;
-
-import org.mmtk.plan.marksweep.MSConstraints;
-import org.vmmagic.pragma.*;
-
-/**
- * This class and its subclasses communicate to the host VM/Runtime
- * any features of the selected plan that it needs to know. This is
- * separate from the main Plan/PlanLocal class in order to bypass any
- * issues with ordering of static initialization.
- */
-@Uninterruptible
-public class PoisonedConstraints extends MSConstraints {
- @Override
- public boolean needsObjectReferenceWriteBarrier() { return true; }
- @Override
- public boolean needsObjectReferenceReadBarrier() { return true; }
- @Override
- public boolean needsObjectReferenceNonHeapWriteBarrier() { return false; }
- @Override
- public boolean needsObjectReferenceNonHeapReadBarrier() { return false; }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/plan/poisoned/PoisonedMutator.java b/vmkit/mmtk/java/src/org/mmtk/plan/poisoned/PoisonedMutator.java
deleted file mode 100644
index 68ff8d5..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/plan/poisoned/PoisonedMutator.java
+++ /dev/null
@@ -1,96 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.plan.poisoned;
-
-import org.mmtk.plan.marksweep.MSMutator;
-import org.mmtk.vm.VM;
-
-import org.vmmagic.pragma.*;
-import org.vmmagic.unboxed.Address;
-import org.vmmagic.unboxed.ObjectReference;
-import org.vmmagic.unboxed.Word;
-
-/**
- * This class implements a poisoned collector, that is essentially a test
- * case for read and write barriers in the VM.
- */
-@Uninterruptible
-public class PoisonedMutator extends MSMutator {
-
- /****************************************************************************
- *
- * Write and read barriers. By default do nothing, override if
- * appropriate.
- */
-
- /**
- * A new reference is about to be created. Take appropriate write
- * barrier actions.<p>
- *
- * <b>By default do nothing, override if appropriate.</b>
- *
- * @param src The object into which the new reference will be stored
- * @param slot The address into which the new reference will be
- * stored.
- * @param tgt The target of the new reference
- * @param metaDataA A value that assists the host VM in creating a store
- * @param metaDataB A value that assists the host VM in creating a store
- * @param mode The context in which the store occurred
- */
- @Inline
- @Override
- public void objectReferenceWrite(ObjectReference src, Address slot, ObjectReference tgt, Word metaDataA, Word metaDataB, int mode) {
- VM.barriers.wordWrite(src, Poisoned.poison(tgt), metaDataA, metaDataB, mode);
- }
-
- /**
- * Attempt to atomically exchange the value in the given slot
- * with the passed replacement value. If a new reference is
- * created, we must then take appropriate write barrier actions.<p>
- *
- * <b>By default do nothing, override if appropriate.</b>
- *
- * @param src The object into which the new reference will be stored
- * @param slot The address into which the new reference will be
- * stored.
- * @param old The old reference to be swapped out
- * @param tgt The target of the new reference
- * @param metaDataA A value that assists the host VM in creating a store
- * @param metaDataB A value that assists the host VM in creating a store
- * @param mode The context in which the store occurred
- * @return True if the swap was successful.
- */
- @Override
- public boolean objectReferenceTryCompareAndSwap(ObjectReference src, Address slot, ObjectReference old, ObjectReference tgt,
- Word metaDataA, Word metaDataB, int mode) {
- return VM.barriers.wordTryCompareAndSwap(src, Poisoned.poison(old), Poisoned.poison(tgt), metaDataA, metaDataB, mode);
- }
-
- /**
- * Read a reference. Take appropriate read barrier action, and
- * return the value that was read.<p> This is a <b>substituting<b>
- * barrier. The call to this barrier takes the place of a load.<p>
- *
- * @param src The object reference holding the field being read.
- * @param slot The address of the slot being read.
- * @param metaDataA A value that assists the host VM in creating a load
- * @param metaDataB A value that assists the host VM in creating a load
- * @param mode The context in which the load occurred
- * @return The reference that was read.
- */
- @Inline
- @Override
- public ObjectReference objectReferenceRead(ObjectReference src, Address slot, Word metaDataA, Word metaDataB, int mode) {
- return Poisoned.depoison(VM.barriers.wordRead(src, metaDataA, metaDataB, mode));
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/plan/refcount/RCBase.java b/vmkit/mmtk/java/src/org/mmtk/plan/refcount/RCBase.java
deleted file mode 100644
index 68373e4..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/plan/refcount/RCBase.java
+++ /dev/null
@@ -1,299 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.plan.refcount;
-
-import org.mmtk.plan.Phase;
-import org.mmtk.plan.StopTheWorld;
-import org.mmtk.plan.Trace;
-import org.mmtk.plan.refcount.backuptrace.BTFreeLargeObjectSweeper;
-import org.mmtk.plan.refcount.backuptrace.BTScanLargeObjectSweeper;
-import org.mmtk.plan.refcount.backuptrace.BTSweeper;
-import org.mmtk.policy.ExplicitFreeListSpace;
-import org.mmtk.policy.ExplicitLargeObjectSpace;
-import org.mmtk.policy.Space;
-import org.mmtk.utility.Log;
-import org.mmtk.utility.alloc.LinearScan;
-import org.mmtk.utility.deque.SharedDeque;
-import org.mmtk.utility.heap.VMRequest;
-import org.mmtk.utility.options.Options;
-import org.mmtk.utility.sanitychecker.SanityChecker;
-import org.mmtk.vm.VM;
-
-import org.vmmagic.pragma.*;
-import org.vmmagic.unboxed.ObjectReference;
-
-/**
- * This class implements the global state of a a simple reference counting collector.
- */
-@Uninterruptible
-public class RCBase extends StopTheWorld {
- public static final short PROCESS_OLDROOTBUFFER = Phase.createSimple("old-root");
- public static final short PROCESS_NEWROOTBUFFER = Phase.createSimple("new-root");
- public static final short PROCESS_MODBUFFER = Phase.createSimple("mods");
- public static final short PROCESS_DECBUFFER = Phase.createSimple("decs");
-
- /** Is cycle collection enabled? */
- public static final boolean CC_ENABLED = true;
- /** Force full cycle collection at each GC? */
- public static final boolean CC_FORCE_FULL = false;
- /** Use backup tracing for cycle collection (currently the only option) */
- public static final boolean CC_BACKUP_TRACE = true;
-
- public static boolean performCycleCollection;
- public static final short BT_CLOSURE = Phase.createSimple("closure-bt");
-
- // CHECKSTYLE:OFF
-
- /**
- * Reference counting specific collection steps.
- */
- protected static final short refCountCollectionPhase = Phase.createComplex("release", null,
- Phase.scheduleGlobal (PROCESS_OLDROOTBUFFER),
- Phase.scheduleCollector (PROCESS_OLDROOTBUFFER),
- Phase.scheduleGlobal (PROCESS_NEWROOTBUFFER),
- Phase.scheduleCollector (PROCESS_NEWROOTBUFFER),
- Phase.scheduleMutator (PROCESS_DECBUFFER),
- Phase.scheduleGlobal (PROCESS_DECBUFFER),
- Phase.scheduleCollector (PROCESS_DECBUFFER),
- Phase.scheduleGlobal (BT_CLOSURE),
- Phase.scheduleCollector (BT_CLOSURE));
-
- /**
- * Perform the initial determination of liveness from the roots.
- */
- protected static final short rootClosurePhase = Phase.createComplex("initial-closure", null,
- Phase.scheduleMutator (PREPARE),
- Phase.scheduleGlobal (PREPARE),
- Phase.scheduleCollector (PREPARE),
- Phase.scheduleComplex (prepareStacks),
- Phase.scheduleCollector (PRECOPY),
- Phase.scheduleCollector (STACK_ROOTS),
- Phase.scheduleCollector (ROOTS),
- Phase.scheduleGlobal (ROOTS),
- Phase.scheduleMutator (PROCESS_MODBUFFER),
- Phase.scheduleGlobal (PROCESS_MODBUFFER),
- Phase.scheduleCollector (PROCESS_MODBUFFER),
- Phase.scheduleGlobal (CLOSURE),
- Phase.scheduleCollector (CLOSURE));
-
- /**
- * This is the phase that is executed to perform a collection.
- */
- public short collection = Phase.createComplex("collection", null,
- Phase.scheduleComplex(initPhase),
- Phase.scheduleComplex(rootClosurePhase),
- Phase.scheduleComplex(refCountCollectionPhase),
- Phase.scheduleComplex(completeClosurePhase),
- Phase.scheduleComplex(finishPhase));
-
- // CHECKSTYLE:ON
-
- /*****************************************************************************
- *
- * Class fields
- */
- public static final ExplicitFreeListSpace rcSpace = new ExplicitFreeListSpace("rc", DEFAULT_POLL_FREQUENCY, VMRequest.create());
- public static final ExplicitLargeObjectSpace rcloSpace = new ExplicitLargeObjectSpace("rclos", DEFAULT_POLL_FREQUENCY, VMRequest.create());
-
- public static final int REF_COUNT = rcSpace.getDescriptor();
- public static final int REF_COUNT_LOS = rcloSpace.getDescriptor();
-
- public final SharedDeque modPool = new SharedDeque("mod", metaDataSpace, 1);
- public final SharedDeque decPool = new SharedDeque("dec", metaDataSpace, 1);
- public final SharedDeque newRootPool = new SharedDeque("newRoot", metaDataSpace, 1);
- public final SharedDeque oldRootPool = new SharedDeque("oldRoot", metaDataSpace, 1);
-
- /*****************************************************************************
- *
- * Instance fields
- */
- public final Trace rootTrace;
- public final Trace backupTrace;
- private final BTSweeper rcSweeper;
- private final BTScanLargeObjectSweeper loScanSweeper;
- private final BTFreeLargeObjectSweeper loFreeSweeper;
-
- /**
- * Constructor
- */
- public RCBase() {
- Options.noReferenceTypes.setDefaultValue(true);
- Options.noFinalizer.setDefaultValue(true);
-
- rootTrace = new Trace(metaDataSpace);
- backupTrace = new Trace(metaDataSpace);
- rcSweeper = new BTSweeper();
- loScanSweeper = new BTScanLargeObjectSweeper();
- loFreeSweeper = new BTFreeLargeObjectSweeper();
- }
-
- /**
- * The boot method is called early in the boot process before any
- * allocation.
- */
- @Interruptible
- public void postBoot() {
- super.postBoot();
-
- if (!Options.noReferenceTypes.getValue()) {
- VM.assertions.fail("Reference Types are not supported by RC");
- }
- if (!Options.noFinalizer.getValue()) {
- VM.assertions.fail("Finalizers are not supported by RC");
- }
- }
-
- /*****************************************************************************
- *
- * Collection
- */
-
- public static final boolean isRCObject(ObjectReference object) {
- return !object.isNull() && !Space.isInSpace(VM_SPACE, object);
- }
-
- /**
- * @return Whether last GC is a full GC.
- */
- public boolean lastCollectionFullHeap() {
- return performCycleCollection;
- }
-
- /**
- * Perform a (global) collection phase.
- *
- * @param phaseId Collection phase
- */
- public void collectionPhase(short phaseId) {
- if (phaseId == SET_COLLECTION_KIND) {
- super.collectionPhase(phaseId);
- if (CC_ENABLED) {
- performCycleCollection = (collectionAttempt > 1) || emergencyCollection || CC_FORCE_FULL;
- if (performCycleCollection && Options.verbose.getValue() > 0) Log.write(" [CC] ");
- }
- return;
- }
-
- if (phaseId == PREPARE) {
- VM.finalizableProcessor.clear();
- VM.weakReferences.clear();
- VM.softReferences.clear();
- VM.phantomReferences.clear();
- rootTrace.prepare();
- rcSpace.prepare();
- if (CC_BACKUP_TRACE && performCycleCollection) {
- backupTrace.prepare();
- }
- return;
- }
-
- if (phaseId == CLOSURE) {
- rootTrace.prepare();
- return;
- }
-
- if (phaseId == BT_CLOSURE) {
- if (CC_BACKUP_TRACE && performCycleCollection) {
- backupTrace.prepare();
- }
- return;
- }
-
- if (phaseId == PROCESS_OLDROOTBUFFER) {
- oldRootPool.prepare();
- return;
- }
-
- if (phaseId == PROCESS_NEWROOTBUFFER) {
- newRootPool.prepare();
- return;
- }
-
-
- if (phaseId == PROCESS_MODBUFFER) {
- modPool.prepare();
- return;
- }
-
- if (phaseId == PROCESS_DECBUFFER) {
- decPool.prepare();
- return;
- }
-
- if (phaseId == RELEASE) {
- rootTrace.release();
- if (CC_BACKUP_TRACE && performCycleCollection) {
- backupTrace.release();
- rcSpace.sweepCells(rcSweeper);
- rcloSpace.sweep(loScanSweeper);
- rcloSpace.sweep(loFreeSweeper);
- } else {
- rcSpace.release();
- }
- return;
- }
-
- super.collectionPhase(phaseId);
- }
-
- /*****************************************************************************
- *
- * Accounting
- */
-
- /**
- * Return the number of pages used given the pending
- * allocation.
- *
- * @return The number of pages reserved given the pending
- * allocation, excluding space reserved for copying.
- */
- public int getPagesUsed() {
- return (rcSpace.reservedPages() + rcloSpace.reservedPages() + super.getPagesUsed());
- }
-
- /**
- * Perform a linear scan across all objects in the heap to check for leaks.
- */
- public void sanityLinearScan(LinearScan scan) {
- //rcSpace.linearScan(scan);
- }
-
- /**
- * Return the expected reference count. For non-reference counting
- * collectors this becomes a true/false relationship.
- *
- * @param object The object to check.
- * @param sanityRootRC The number of root references to the object.
- * @return The expected (root excluded) reference count.
- */
- public int sanityExpectedRC(ObjectReference object, int sanityRootRC) {
- if (RCBase.isRCObject(object)) {
- int fullRC = RCHeader.getRC(object);
- if (fullRC == 0) {
- return SanityChecker.DEAD;
- }
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(fullRC >= sanityRootRC);
- return fullRC - sanityRootRC;
- }
- return SanityChecker.ALIVE;
- }
-
- /**
- * Register specialized methods.
- */
- @Interruptible
- protected void registerSpecializedMethods() {
- super.registerSpecializedMethods();
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/plan/refcount/RCBaseCollector.java b/vmkit/mmtk/java/src/org/mmtk/plan/refcount/RCBaseCollector.java
deleted file mode 100644
index ab99da1..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/plan/refcount/RCBaseCollector.java
+++ /dev/null
@@ -1,182 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.plan.refcount;
-
-import org.mmtk.plan.Phase;
-import org.mmtk.plan.StopTheWorldCollector;
-import org.mmtk.plan.TraceLocal;
-import org.mmtk.plan.TransitiveClosure;
-import org.mmtk.plan.refcount.backuptrace.BTTraceLocal;
-import org.mmtk.policy.Space;
-import org.mmtk.utility.deque.ObjectReferenceDeque;
-import org.mmtk.vm.VM;
-import org.vmmagic.pragma.Inline;
-import org.vmmagic.pragma.Uninterruptible;
-import org.vmmagic.unboxed.ObjectReference;
-
-/**
- * This class implements the collector context for a simple reference counting
- * collector.
- */
-@Uninterruptible
-public abstract class RCBaseCollector extends StopTheWorldCollector {
-
- /************************************************************************
- * Initialization
- */
- protected final ObjectReferenceDeque newRootBuffer;
- private final BTTraceLocal backupTrace;
- private final ObjectReferenceDeque modBuffer;
- private final ObjectReferenceDeque oldRootBuffer;
- private final RCDecBuffer decBuffer;
- private final RCZero zero;
-
- /**
- * Constructor.
- */
- public RCBaseCollector() {
- newRootBuffer = new ObjectReferenceDeque("new-root", global().newRootPool);
- oldRootBuffer = new ObjectReferenceDeque("old-root", global().oldRootPool);
- modBuffer = new ObjectReferenceDeque("mod buf", global().modPool);
- decBuffer = new RCDecBuffer(global().decPool);
- backupTrace = new BTTraceLocal(global().backupTrace);
- zero = new RCZero();
- }
-
- /**
- * Get the modified processor to use.
- */
- protected abstract TransitiveClosure getModifiedProcessor();
-
- /**
- * Get the root trace to use.
- */
- protected abstract TraceLocal getRootTrace();
-
- /****************************************************************************
- *
- * Collection
- */
-
- /** Perform garbage collection */
- public void collect() {
- Phase.beginNewPhaseStack(Phase.scheduleComplex(global().collection));
- }
-
- /**
- * Perform a per-collector collection phase.
- *
- * @param phaseId The collection phase to perform
- * @param primary perform any single-threaded local activities.
- */
- public void collectionPhase(short phaseId, boolean primary) {
- if (phaseId == RCBase.PREPARE) {
- getRootTrace().prepare();
- if (RCBase.CC_BACKUP_TRACE && RCBase.performCycleCollection) backupTrace.prepare();
- return;
- }
-
- if (phaseId == RCBase.CLOSURE) {
- getRootTrace().completeTrace();
- newRootBuffer.flushLocal();
- return;
- }
-
- if (phaseId == RCBase.BT_CLOSURE) {
- if (RCBase.CC_BACKUP_TRACE && RCBase.performCycleCollection) {
- backupTrace.completeTrace();
- }
- return;
- }
-
- if (phaseId == RCBase.PROCESS_OLDROOTBUFFER) {
- ObjectReference current;
- while(!(current = oldRootBuffer.pop()).isNull()) {
- decBuffer.push(current);
- }
- return;
- }
-
- if (phaseId == RCBase.PROCESS_NEWROOTBUFFER) {
- ObjectReference current;
- while(!(current = newRootBuffer.pop()).isNull()) {
- RCHeader.incRC(current);
- oldRootBuffer.push(current);
- if (RCBase.CC_BACKUP_TRACE && RCBase.performCycleCollection) {
- if (RCHeader.testAndMark(current)) {
- backupTrace.processNode(current);
- }
- }
- }
- oldRootBuffer.flushLocal();
- return;
- }
-
- if (phaseId == RCBase.PROCESS_MODBUFFER) {
- ObjectReference current;
- while(!(current = modBuffer.pop()).isNull()) {
- RCHeader.makeUnlogged(current);
- VM.scanning.scanObject(getModifiedProcessor(), current);
- }
- return;
- }
-
- if (phaseId == RCBase.PROCESS_DECBUFFER) {
- ObjectReference current;
- while(!(current = decBuffer.pop()).isNull()) {
- if (RCHeader.decRC(current) == RCHeader.DEC_KILL) {
- decBuffer.processChildren(current);
- if (Space.isInSpace(RCBase.REF_COUNT, current)) {
- RCBase.rcSpace.free(current);
- } else if (Space.isInSpace(RCBase.REF_COUNT_LOS, current)) {
- RCBase.rcloSpace.free(current);
- } else if (Space.isInSpace(RCBase.IMMORTAL, current)) {
- VM.scanning.scanObject(zero, current);
- }
- }
- }
- return;
- }
-
- if (phaseId == RCBase.RELEASE) {
- if (RCBase.CC_BACKUP_TRACE && RCBase.performCycleCollection) {
- backupTrace.release();
- }
- getRootTrace().release();
- if (VM.VERIFY_ASSERTIONS) {
- VM.assertions._assert(newRootBuffer.isEmpty());
- VM.assertions._assert(modBuffer.isEmpty());
- VM.assertions._assert(decBuffer.isEmpty());
- }
- return;
- }
-
- super.collectionPhase(phaseId, primary);
- }
-
- /****************************************************************************
- *
- * Miscellaneous
- */
-
- /** @return The active global plan as an <code>RC</code> instance. */
- @Inline
- protected static RCBase global() {
- return (RCBase) VM.activePlan.global();
- }
-
- /** @return The current trace instance. */
- public final TraceLocal getCurrentTrace() {
- return getRootTrace();
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/plan/refcount/RCBaseConstraints.java b/vmkit/mmtk/java/src/org/mmtk/plan/refcount/RCBaseConstraints.java
deleted file mode 100644
index 04eab82..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/plan/refcount/RCBaseConstraints.java
+++ /dev/null
@@ -1,36 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.plan.refcount;
-
-import static org.mmtk.policy.SegregatedFreeListSpace.MAX_FREELIST_OBJECT_BYTES;
-import org.mmtk.plan.StopTheWorldConstraints;
-
-import org.vmmagic.pragma.*;
-
-/**
- * This class and its subclasses communicate to the host VM/Runtime
- * any features of the selected plan that it needs to know. This is
- * separate from the main Plan/PlanLocal class in order to bypass any
- * issues with ordering of static initialization.
- */
-@Uninterruptible
-public class RCBaseConstraints extends StopTheWorldConstraints {
- @Override
- public int gcHeaderBits() { return RCHeader.GLOBAL_GC_BITS_REQUIRED; }
- @Override
- public int gcHeaderWords() { return RCHeader.GC_HEADER_WORDS_REQUIRED; }
- @Override
- public boolean needsObjectReferenceWriteBarrier() { return true; }
- @Override
- public int maxNonLOSDefaultAllocBytes() { return MAX_FREELIST_OBJECT_BYTES; }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/plan/refcount/RCBaseMutator.java b/vmkit/mmtk/java/src/org/mmtk/plan/refcount/RCBaseMutator.java
deleted file mode 100644
index a900ed8..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/plan/refcount/RCBaseMutator.java
+++ /dev/null
@@ -1,334 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.plan.refcount;
-
-import org.mmtk.plan.StopTheWorldMutator;
-import org.mmtk.plan.refcount.backuptrace.BTSweepImmortalScanner;
-import org.mmtk.policy.ExplicitFreeListLocal;
-import org.mmtk.policy.ExplicitFreeListSpace;
-import org.mmtk.policy.LargeObjectLocal;
-import org.mmtk.policy.Space;
-import org.mmtk.utility.alloc.Allocator;
-import org.mmtk.utility.deque.ObjectReferenceDeque;
-import org.mmtk.vm.VM;
-
-import org.vmmagic.pragma.*;
-import org.vmmagic.unboxed.*;
-
-/**
- * This class implements the mutator context for a simple reference counting collector.
- */
-@Uninterruptible
-public class RCBaseMutator extends StopTheWorldMutator {
-
- /************************************************************************
- * Instance fields
- */
- private final ExplicitFreeListLocal rc;
- private final LargeObjectLocal rclos;
- private final ObjectReferenceDeque modBuffer;
- private final RCDecBuffer decBuffer;
- private final BTSweepImmortalScanner btSweepImmortal;
-
- /************************************************************************
- *
- * Initialization
- */
-
- /**
- * Constructor. One instance is created per physical processor.
- */
- public RCBaseMutator() {
- rc = new ExplicitFreeListLocal(RCBase.rcSpace);
- rclos = new LargeObjectLocal(RCBase.rcloSpace);
- modBuffer = new ObjectReferenceDeque("mod", global().modPool);
- decBuffer = new RCDecBuffer(global().decPool);
- btSweepImmortal = new BTSweepImmortalScanner();
- }
-
- /****************************************************************************
- *
- * Mutator-time allocation
- */
-
- /**
- * Allocate memory for an object.
- *
- * @param bytes The number of bytes required for the object.
- * @param align Required alignment for the object.
- * @param offset Offset associated with the alignment.
- * @param allocator The allocator associated with this request.
- * @param site Allocation site
- * @return The address of the newly allocated memory.
- */
- @Inline
- public Address alloc(int bytes, int align, int offset, int allocator, int site) {
- switch (allocator) {
- case RCBase.ALLOC_DEFAULT:
- case RCBase.ALLOC_NON_MOVING:
- case RCBase.ALLOC_CODE:
- return rc.alloc(bytes, align, offset);
- case RCBase.ALLOC_LOS:
- case RCBase.ALLOC_PRIMITIVE_LOS:
- case RCBase.ALLOC_LARGE_CODE:
- return rclos.alloc(bytes, align, offset);
- case RCBase.ALLOC_IMMORTAL:
- return super.alloc(bytes, align, offset, allocator, site);
- default:
- VM.assertions.fail("Allocator not understood by RC");
- return Address.zero();
- }
- }
-
- /**
- * Perform post-allocation actions. For many allocators none are
- * required.
- *
- * @param ref The newly allocated object
- * @param typeRef the type reference for the instance being created
- * @param bytes The size of the space to be allocated (in bytes)
- * @param allocator The allocator number to be used for this allocation
- */
- @Inline
- public void postAlloc(ObjectReference ref, ObjectReference typeRef, int bytes, int allocator) {
- switch (allocator) {
- case RCBase.ALLOC_DEFAULT:
- case RCBase.ALLOC_NON_MOVING:
- modBuffer.push(ref);
- case RCBase.ALLOC_CODE:
- decBuffer.push(ref);
- RCHeader.initializeHeader(ref, true);
- ExplicitFreeListSpace.unsyncSetLiveBit(ref);
- break;
- case RCBase.ALLOC_LOS:
- modBuffer.push(ref);
- case RCBase.ALLOC_PRIMITIVE_LOS:
- case RCBase.ALLOC_LARGE_CODE:
- decBuffer.push(ref);
- RCHeader.initializeHeader(ref, true);
- RCBase.rcloSpace.initializeHeader(ref, true);
- return;
- case RCBase.ALLOC_IMMORTAL:
- modBuffer.push(ref);
- decBuffer.push(ref);
- RCHeader.initializeHeader(ref, true);
- return;
- default:
- VM.assertions.fail("Allocator not understood by RC");
- return;
- }
- }
-
- /**
- * Return the allocator instance associated with a space
- * <code>space</code>, for this plan instance.
- *
- * @param space The space for which the allocator instance is desired.
- * @return The allocator instance associated with this plan instance
- * which is allocating into <code>space</code>, or <code>null</code>
- * if no appropriate allocator can be established.
- */
- public Allocator getAllocatorFromSpace(Space space) {
- if (space == RCBase.rcSpace) return rc;
- if (space == RCBase.rcloSpace) return rclos;
-
- return super.getAllocatorFromSpace(space);
- }
-
- /****************************************************************************
- *
- * Collection
- */
-
- /**
- * Perform a per-mutator collection phase.
- *
- * @param phaseId The collection phase to perform
- * @param primary perform any single-threaded local activities.
- */
- public void collectionPhase(short phaseId, boolean primary) {
- if (phaseId == RCBase.PREPARE) {
- rc.prepare();
- return;
- }
-
- if (phaseId == RCBase.PROCESS_MODBUFFER) {
- modBuffer.flushLocal();
- return;
- }
-
- if (phaseId == RCBase.PROCESS_DECBUFFER) {
- decBuffer.flushLocal();
- return;
- }
-
- if (phaseId == RCBase.RELEASE) {
- if (RCBase.CC_BACKUP_TRACE && RCBase.performCycleCollection) {
- immortal.linearScan(btSweepImmortal);
- }
- rc.release();
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(modBuffer.isEmpty());
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(decBuffer.isEmpty());
- return;
- }
-
- super.collectionPhase(phaseId, primary);
- }
-
- /**
- * Flush per-mutator remembered sets into the global remset pool.
- */
- public final void flushRememberedSets() {
- decBuffer.flushLocal();
- modBuffer.flushLocal();
- assertRemsetsFlushed();
- }
-
- /**
- * Assert that the remsets have been flushed. This is critical to
- * correctness. We need to maintain the invariant that remset entries
- * do not accrue during GC. If the host JVM generates barrier entires
- * it is its own responsibility to ensure that they are flushed before
- * returning to MMTk.
- */
- public final void assertRemsetsFlushed() {
- if (VM.VERIFY_ASSERTIONS) {
- VM.assertions._assert(decBuffer.isFlushed());
- VM.assertions._assert(modBuffer.isFlushed());
- }
- }
-
- /**
- * Flush mutator context, in response to a requestMutatorFlush.
- * Also called by the default implementation of deinitMutator.
- */
- @Override
- public void flush() {
- super.flush();
- rc.flush();
- }
-
- /****************************************************************************
- *
- * Write barriers.
- */
-
- /**
- * A new reference is about to be created. Take appropriate write
- * barrier actions.<p>
- *
- * <b>By default do nothing, override if appropriate.</b>
- *
- * @param src The object into which the new reference will be stored
- * @param slot The address into which the new reference will be
- * stored.
- * @param tgt The target of the new reference
- * @param metaDataA A value that assists the host VM in creating a store
- * @param metaDataB A value that assists the host VM in creating a store
- * @param mode The context in which the store occurred
- */
- @Inline
- public void objectReferenceWrite(ObjectReference src, Address slot,
- ObjectReference tgt, Word metaDataA,
- Word metaDataB, int mode) {
- if (RCHeader.logRequired(src)) {
- coalescingWriteBarrierSlow(src);
- }
- VM.barriers.objectReferenceWrite(src,tgt,metaDataA, metaDataB, mode);
- }
-
- /**
- * Attempt to atomically exchange the value in the given slot
- * with the passed replacement value. If a new reference is
- * created, we must then take appropriate write barrier actions.<p>
- *
- * <b>By default do nothing, override if appropriate.</b>
- *
- * @param src The object into which the new reference will be stored
- * @param slot The address into which the new reference will be
- * stored.
- * @param old The old reference to be swapped out
- * @param tgt The target of the new reference
- * @param metaDataA A value that assists the host VM in creating a store
- * @param metaDataB A value that assists the host VM in creating a store
- * @param mode The context in which the store occured
- * @return True if the swap was successful.
- */
- @Inline
- public boolean objectReferenceTryCompareAndSwap(ObjectReference src, Address slot,
- ObjectReference old, ObjectReference tgt, Word metaDataA,
- Word metaDataB, int mode) {
- if (RCHeader.logRequired(src)) {
- coalescingWriteBarrierSlow(src);
- }
- return VM.barriers.objectReferenceTryCompareAndSwap(src,old,tgt,metaDataA,metaDataB,mode);
- }
-
- /**
- * A number of references are about to be copied from object
- * <code>src</code> to object <code>dst</code> (as in an array
- * copy). Thus, <code>dst</code> is the mutated object. Take
- * appropriate write barrier actions.<p>
- *
- * @param src The source of the values to be copied
- * @param srcOffset The offset of the first source address, in
- * bytes, relative to <code>src</code> (in principle, this could be
- * negative).
- * @param dst The mutated object, i.e. the destination of the copy.
- * @param dstOffset The offset of the first destination address, in
- * bytes relative to <code>tgt</code> (in principle, this could be
- * negative).
- * @param bytes The size of the region being copied, in bytes.
- * @return True if the update was performed by the barrier, false if
- * left to the caller (always false in this case).
- */
- @Inline
- public boolean objectReferenceBulkCopy(ObjectReference src, Offset srcOffset,
- ObjectReference dst, Offset dstOffset, int bytes) {
- if (RCHeader.logRequired(dst)) {
- coalescingWriteBarrierSlow(dst);
- }
- return false;
- }
-
- /**
- * Slow path of the coalescing write barrier.
- *
- * <p> Attempt to log the source object. If successful in racing for
- * the log bit, push an entry into the modified buffer and add a
- * decrement buffer entry for each referent object (in the RC space)
- * before setting the header bit to indicate that it has finished
- * logging (allowing others in the race to continue).
- *
- * @param srcObj The object being mutated
- */
- @NoInline
- private void coalescingWriteBarrierSlow(ObjectReference srcObj) {
- if (RCHeader.attemptToLog(srcObj)) {
- modBuffer.push(srcObj);
- decBuffer.processChildren(srcObj);
- RCHeader.makeLogged(srcObj);
- }
- }
-
- /****************************************************************************
- *
- * Miscellaneous
- */
-
- /** @return The active global plan as an <code>RC</code> instance. */
- @Inline
- private static RCBase global() {
- return (RCBase) VM.activePlan.global();
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/plan/refcount/RCDecBuffer.java b/vmkit/mmtk/java/src/org/mmtk/plan/refcount/RCDecBuffer.java
deleted file mode 100644
index 636bb2f..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/plan/refcount/RCDecBuffer.java
+++ /dev/null
@@ -1,53 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.plan.refcount;
-
-import org.mmtk.utility.Constants;
-import org.mmtk.utility.deque.*;
-
-import org.vmmagic.pragma.*;
-import org.vmmagic.unboxed.*;
-
-/**
- * This class implements a dec-buffer for a reference counting collector
- *
- * @see org.mmtk.plan.TransitiveClosure
- */
-@Uninterruptible
-public final class RCDecBuffer extends ObjectReferenceBuffer implements Constants {
- /****************************************************************************
- *
- * Initialization
- */
-
- /**
- * Constructor
- *
- * @param queue The shared deque that is used.
- */
- public RCDecBuffer(SharedDeque queue) {
- super("dec", queue);
- }
-
- /**
- * This is the method that ensures
- *
- * @param object The object to process.
- */
- @Inline
- protected void process(ObjectReference object) {
- if (RCBase.isRCObject(object)) {
- push(object);
- }
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/plan/refcount/RCHeader.java b/vmkit/mmtk/java/src/org/mmtk/plan/refcount/RCHeader.java
deleted file mode 100644
index a987b5a..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/plan/refcount/RCHeader.java
+++ /dev/null
@@ -1,276 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.plan.refcount;
-
-import org.mmtk.utility.Constants;
-import org.mmtk.vm.VM;
-import org.vmmagic.pragma.Inline;
-import org.vmmagic.pragma.Uninterruptible;
-import org.vmmagic.unboxed.ObjectReference;
-import org.vmmagic.unboxed.Offset;
-import org.vmmagic.unboxed.Word;
-
-@Uninterruptible
-public class RCHeader implements Constants {
- /* Requirements */
- public static final int LOCAL_GC_BITS_REQUIRED = 0;
- public static final int GLOBAL_GC_BITS_REQUIRED = 2;
- public static final int GC_HEADER_WORDS_REQUIRED = 1;
-
- /****************************************************************************
- * Object Logging (applies to *all* objects)
- */
-
- /* Mask bits to signify the start/finish of logging an object */
- public static final int LOG_BIT = 0;
- public static final Word LOGGED = Word.zero(); //...00000
- public static final Word UNLOGGED = Word.one(); //...00001
- public static final Word BEING_LOGGED = Word.one().lsh(2).minus(Word.one()); //...00011
- public static final Word LOGGING_MASK = LOGGED.or(UNLOGGED).or(BEING_LOGGED); //...00011
-
- /**
- * Return true if <code>object</code> is yet to be logged (for
- * coalescing RC).
- *
- * @param object The object in question
- * @return <code>true</code> if <code>object</code> needs to be logged.
- */
- @Inline
- @Uninterruptible
- public static boolean logRequired(ObjectReference object) {
- Word value = VM.objectModel.readAvailableBitsWord(object);
- return value.and(LOGGING_MASK).EQ(UNLOGGED);
- }
-
- /**
- * Attempt to log <code>object</code> for coalescing RC. This is
- * used to handle a race to log the object, and returns
- * <code>true</code> if we are to log the object and
- * <code>false</code> if we lost the race to log the object.
- *
- * <p>If this method returns <code>true</code>, it leaves the object
- * in the <code>BEING_LOGGED</code> state. It is the responsibility
- * of the caller to change the object to <code>LOGGED</code> once
- * the logging is complete.
- *
- * @see #makeLogged(ObjectReference)
- * @param object The object in question
- * @return <code>true</code> if the race to log
- * <code>object</code>was won.
- */
- @Inline
- @Uninterruptible
- public static boolean attemptToLog(ObjectReference object) {
- Word oldValue;
- do {
- oldValue = VM.objectModel.prepareAvailableBits(object);
- if (oldValue.and(LOGGING_MASK).EQ(LOGGED)) {
- return false;
- }
- } while ((oldValue.and(LOGGING_MASK).EQ(BEING_LOGGED)) ||
- !VM.objectModel.attemptAvailableBits(object, oldValue, oldValue.or(BEING_LOGGED)));
- if (VM.VERIFY_ASSERTIONS) {
- Word value = VM.objectModel.readAvailableBitsWord(object);
- VM.assertions._assert(value.and(LOGGING_MASK).EQ(BEING_LOGGED));
- }
- return true;
- }
-
-
- /**
- * Signify completion of logging <code>object</code>.
- *
- * <code>object</code> is left in the <code>LOGGED</code> state.
- *
- * @see #attemptToLog(ObjectReference)
- * @param object The object whose state is to be changed.
- */
- @Inline
- @Uninterruptible
- public static void makeLogged(ObjectReference object) {
- Word value = VM.objectModel.readAvailableBitsWord(object);
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(value.and(LOGGING_MASK).NE(LOGGED));
- VM.objectModel.writeAvailableBitsWord(object, value.and(LOGGING_MASK.not()));
- }
-
- /**
- * Change <code>object</code>'s state to <code>UNLOGGED</code>.
- *
- * @param object The object whose state is to be changed.
- */
- @Inline
- @Uninterruptible
- public static void makeUnlogged(ObjectReference object) {
- Word value = VM.objectModel.readAvailableBitsWord(object);
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(value.and(LOGGING_MASK).EQ(LOGGED));
- VM.objectModel.writeAvailableBitsWord(object, value.or(UNLOGGED));
- }
-
- /************************************************************************
- * RC header word
- */
-
- /* Header offset */
- public static final Offset RC_HEADER_OFFSET = VM.objectModel.GC_HEADER_OFFSET();
-
- /* Reserved to allow alignment hole filling to work */
- public static final int RESERVED_ALIGN_BIT = 0;
-
- /* The mark bit used for backup tracing. */
- public static final int MARK_BIT = 1;
- public static final Word MARK_BIT_MASK = Word.one().lsh(MARK_BIT);
-
- /* Current not using any bits for cycle detection, etc */
- public static final int BITS_USED = 2;
-
- /* Reference counting increments */
- public static final int INCREMENT_SHIFT = BITS_USED;
- public static final Word INCREMENT = Word.one().lsh(INCREMENT_SHIFT);
- public static final int AVAILABLE_BITS = BITS_IN_ADDRESS - BITS_USED;
- public static final Word INCREMENT_LIMIT = Word.one().lsh(BITS_IN_ADDRESS-1).not();
- public static final Word LIVE_THRESHOLD = INCREMENT;
-
- /* Return values from decRC */
- public static final int DEC_KILL = 0;
- public static final int DEC_ALIVE = 1;
-
- /**
- * Has this object been marked by the most recent backup trace.
- */
- @Inline
- public static boolean isMarked(ObjectReference object) {
- return isHeaderMarked(object.toAddress().loadWord(RC_HEADER_OFFSET));
- }
-
- /**
- * Has this object been marked by the most recent backup trace.
- */
- @Inline
- public static void clearMarked(ObjectReference object) {
- Word oldValue, newValue;
- do {
- oldValue = object.toAddress().prepareWord(RC_HEADER_OFFSET);
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(isHeaderMarked(oldValue));
- newValue = oldValue.and(MARK_BIT_MASK.not());
- } while (!object.toAddress().attempt(oldValue, newValue, RC_HEADER_OFFSET));
- /*
- Word header = object.toAddress().loadWord(RC_HEADER_OFFSET);
- object.toAddress().store(header.and(MARK_BIT_MASK.not()), RC_HEADER_OFFSET);*/
- }
-
- /**
- * Has this object been marked by the most recent backup trace.
- */
- @Inline
- private static boolean isHeaderMarked(Word header) {
- return header.and(MARK_BIT_MASK).EQ(MARK_BIT_MASK);
- }
-
- /**
- * Attempt to atomically mark this object. Return true if the mark was performed.
- */
- @Inline
- public static boolean testAndMark(ObjectReference object) {
- Word oldValue, newValue;
- do {
- oldValue = object.toAddress().prepareWord(RC_HEADER_OFFSET);
- if (isHeaderMarked(oldValue)) {
- return false;
- }
- newValue = oldValue.or(MARK_BIT_MASK);
- } while (!object.toAddress().attempt(oldValue, newValue, RC_HEADER_OFFSET));
- return true;
- }
-
- /**
- * Perform any required initialization of the GC portion of the header.
- *
- * @param object the object
- * @param initialInc start with a reference count of 1 (0 if false)
- */
- @Inline
- public static void initializeHeader(ObjectReference object, boolean initialInc) {
- Word initialValue = (initialInc) ? INCREMENT : Word.zero();
- object.toAddress().store(initialValue, RC_HEADER_OFFSET);
- }
-
- /**
- * Return true if given object is live
- *
- * @param object The object whose liveness is to be tested
- * @return True if the object is alive
- */
- @Inline
- @Uninterruptible
- public static boolean isLiveRC(ObjectReference object) {
- return object.toAddress().loadWord(RC_HEADER_OFFSET).GE(LIVE_THRESHOLD);
- }
-
- /**
- * Return the reference count for the object.
- *
- * @param object The object whose liveness is to be tested
- * @return True if the object is alive
- */
- @Inline
- @Uninterruptible
- public static int getRC(ObjectReference object) {
- return object.toAddress().loadWord(RC_HEADER_OFFSET).rshl(INCREMENT_SHIFT).toInt();
- }
-
- /**
- * Increment the reference count of an object.
- *
- * @param object The object whose reference count is to be incremented.
- */
- @Inline
- public static void incRC(ObjectReference object) {
- Word oldValue, newValue;
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(RCBase.isRCObject(object));
- do {
- oldValue = object.toAddress().prepareWord(RC_HEADER_OFFSET);
- newValue = oldValue.plus(INCREMENT);
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(newValue.LE(INCREMENT_LIMIT));
- } while (!object.toAddress().attempt(oldValue, newValue, RC_HEADER_OFFSET));
- }
-
- /**
- * Decrement the reference count of an object. Return either
- * <code>DEC_KILL</code> if the count went to zero,
- * <code>DEC_ALIVE</code> if the count did not go to zero.
- *
- * @param object The object whose RC is to be decremented.
- * @return <code>DEC_KILL</code> if the count went to zero,
- * <code>DEC_ALIVE</code> if the count did not go to zero.
- */
- @Inline
- @Uninterruptible
- public static int decRC(ObjectReference object) {
- Word oldValue, newValue;
- int rtn;
- if (VM.VERIFY_ASSERTIONS) {
- VM.assertions._assert(RCBase.isRCObject(object));
- VM.assertions._assert(isLiveRC(object));
- }
- do {
- oldValue = object.toAddress().prepareWord(RC_HEADER_OFFSET);
- newValue = oldValue.minus(INCREMENT);
- if (newValue.LT(LIVE_THRESHOLD)) {
- rtn = DEC_KILL;
- } else {
- rtn = DEC_ALIVE;
- }
- } while (!object.toAddress().attempt(oldValue, newValue, RC_HEADER_OFFSET));
- return rtn;
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/plan/refcount/RCZero.java b/vmkit/mmtk/java/src/org/mmtk/plan/refcount/RCZero.java
deleted file mode 100644
index f2a545c..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/plan/refcount/RCZero.java
+++ /dev/null
@@ -1,40 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.plan.refcount;
-
-import org.mmtk.plan.TransitiveClosure;
-
-import org.vmmagic.pragma.*;
-import org.vmmagic.unboxed.*;
-
-/**
- * This class is the fundamental mechanism for performing a
- * transitive closure over an object graph.<p>
- *
- * @see org.mmtk.plan.TraceLocal
- */
-@Uninterruptible
-public final class RCZero extends TransitiveClosure {
-
- /**
- * Trace an edge during GC.
- *
- * @param source The source of the reference.
- * @param slot The location containing the object reference.
- */
- @Inline
- public void processEdge(ObjectReference source, Address slot) {
- slot.store(ObjectReference.nullReference());
- }
-}
-
diff --git a/vmkit/mmtk/java/src/org/mmtk/plan/refcount/backuptrace/BTDecMarked.java b/vmkit/mmtk/java/src/org/mmtk/plan/refcount/backuptrace/BTDecMarked.java
deleted file mode 100644
index 5a21868..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/plan/refcount/backuptrace/BTDecMarked.java
+++ /dev/null
@@ -1,51 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.plan.refcount.backuptrace;
-
-import org.mmtk.plan.TransitiveClosure;
-import org.mmtk.plan.refcount.RCBase;
-import org.mmtk.plan.refcount.RCHeader;
-import org.mmtk.policy.Space;
-import org.mmtk.vm.VM;
-
-import org.vmmagic.pragma.*;
-import org.vmmagic.unboxed.*;
-
-/**
- * This class is the fundamental mechanism for performing a
- * transitive closure over an object graph.<p>
- *
- * @see org.mmtk.plan.TraceLocal
- */
-@Uninterruptible
-public final class BTDecMarked extends TransitiveClosure {
-
- /**
- * Trace an edge during GC.
- *
- * @param source The source of the reference.
- * @param slot The location containing the object reference.
- */
- @Inline
- public void processEdge(ObjectReference source, Address slot) {
- ObjectReference object = slot.loadObjectReference();
- if (!object.isNull()) {
- if ((Space.isInSpace(RCBase.REF_COUNT, object) && RCBase.rcSpace.isLive(object)) ||
- Space.isInSpace(RCBase.REF_COUNT_LOS, object) ||
- Space.isInSpace(RCBase.IMMORTAL, object)) {
- int result = RCHeader.decRC(object);
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(result != RCHeader.DEC_KILL || !RCHeader.isMarked(object));
- }
- }
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/plan/refcount/backuptrace/BTDecMarkedAndZero.java b/vmkit/mmtk/java/src/org/mmtk/plan/refcount/backuptrace/BTDecMarkedAndZero.java
deleted file mode 100644
index d819d62..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/plan/refcount/backuptrace/BTDecMarkedAndZero.java
+++ /dev/null
@@ -1,52 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.plan.refcount.backuptrace;
-
-import org.mmtk.plan.TransitiveClosure;
-import org.mmtk.plan.refcount.RCBase;
-import org.mmtk.plan.refcount.RCHeader;
-import org.mmtk.policy.Space;
-import org.mmtk.vm.VM;
-
-import org.vmmagic.pragma.*;
-import org.vmmagic.unboxed.*;
-
-/**
- * This class is the fundamental mechanism for performing a
- * transitive closure over an object graph.<p>
- *
- * @see org.mmtk.plan.TraceLocal
- */
-@Uninterruptible
-public final class BTDecMarkedAndZero extends TransitiveClosure {
-
- /**
- * Trace an edge during GC.
- *
- * @param source The source of the reference.
- * @param slot The location containing the object reference.
- */
- @Inline
- public void processEdge(ObjectReference source, Address slot) {
- ObjectReference object = slot.loadObjectReference();
- slot.store(ObjectReference.nullReference());
- if (!object.isNull()) {
- if ((Space.isInSpace(RCBase.REF_COUNT, object) && RCBase.rcSpace.isLive(object)) ||
- Space.isInSpace(RCBase.REF_COUNT_LOS, object) ||
- Space.isInSpace(RCBase.IMMORTAL, object)) {
- int result = RCHeader.decRC(object);
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(result != RCHeader.DEC_KILL || !RCHeader.isMarked(object));
- }
- }
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/plan/refcount/backuptrace/BTFreeLargeObjectSweeper.java b/vmkit/mmtk/java/src/org/mmtk/plan/refcount/backuptrace/BTFreeLargeObjectSweeper.java
deleted file mode 100644
index e42c3c5..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/plan/refcount/backuptrace/BTFreeLargeObjectSweeper.java
+++ /dev/null
@@ -1,36 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.plan.refcount.backuptrace;
-
-import org.mmtk.plan.refcount.RCHeader;
-import org.mmtk.policy.ExplicitLargeObjectSpace;
-
-import org.vmmagic.pragma.*;
-import org.vmmagic.unboxed.*;
-
-/**
- * This class implements the freeing of large objects during a backup trace.
- */
-@Uninterruptible
-public final class BTFreeLargeObjectSweeper extends ExplicitLargeObjectSpace.Sweeper {
-
- public boolean sweepLargeObject(ObjectReference object) {
- if (!RCHeader.isMarked(object)) {
- // Free the object
- return true;
- }
- // Clear the mark-bit and retain the object.
- RCHeader.clearMarked(object);
- return false;
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/plan/refcount/backuptrace/BTScanLargeObjectSweeper.java b/vmkit/mmtk/java/src/org/mmtk/plan/refcount/backuptrace/BTScanLargeObjectSweeper.java
deleted file mode 100644
index e0bc57d..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/plan/refcount/backuptrace/BTScanLargeObjectSweeper.java
+++ /dev/null
@@ -1,37 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.plan.refcount.backuptrace;
-
-import org.mmtk.plan.refcount.RCHeader;
-import org.mmtk.policy.ExplicitLargeObjectSpace;
-import org.mmtk.vm.VM;
-
-import org.vmmagic.pragma.*;
-import org.vmmagic.unboxed.*;
-
-/**
- * This class implements the scanning of dead large objects during a backup trace.
- */
-@Uninterruptible
-public final class BTScanLargeObjectSweeper extends ExplicitLargeObjectSpace.Sweeper {
-
- private final BTDecMarked sdm = new BTDecMarked();
-
- public boolean sweepLargeObject(ObjectReference object) {
- if (!RCHeader.isMarked(object)) {
- VM.scanning.scanObject(sdm, object);
- }
- // Do not free any objects at this time
- return false;
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/plan/refcount/backuptrace/BTSweepImmortalScanner.java b/vmkit/mmtk/java/src/org/mmtk/plan/refcount/backuptrace/BTSweepImmortalScanner.java
deleted file mode 100644
index 93438f7..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/plan/refcount/backuptrace/BTSweepImmortalScanner.java
+++ /dev/null
@@ -1,43 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.plan.refcount.backuptrace;
-
-import org.mmtk.plan.refcount.RCHeader;
-import org.mmtk.utility.alloc.LinearScan;
-import org.mmtk.vm.VM;
-
-import org.vmmagic.pragma.*;
-import org.vmmagic.unboxed.*;
-
-/**
- * This class is used in backup tracing to sweep and zero any dead 'immortal' objects.
- */
-@Uninterruptible
-public final class BTSweepImmortalScanner extends LinearScan {
-
- private final BTDecMarkedAndZero sdmAZ = new BTDecMarkedAndZero();
-
- /**
- * Scan an object during sweep.
- *
- * @param object The source of the reference.
- */
- @Inline
- public void scan(ObjectReference object) {
- if (!RCHeader.isMarked(object)) {
- VM.scanning.scanObject(sdmAZ, object);
- } else {
- RCHeader.clearMarked(object);
- }
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/plan/refcount/backuptrace/BTSweeper.java b/vmkit/mmtk/java/src/org/mmtk/plan/refcount/backuptrace/BTSweeper.java
deleted file mode 100644
index 48e2970..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/plan/refcount/backuptrace/BTSweeper.java
+++ /dev/null
@@ -1,40 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.plan.refcount.backuptrace;
-
-import org.mmtk.plan.refcount.RCHeader;
-import org.mmtk.policy.ExplicitFreeListSpace;
-import org.mmtk.vm.VM;
-
-import org.vmmagic.pragma.*;
-import org.vmmagic.unboxed.*;
-
-/**
- * This class implements the thread-local core functionality for a transitive
- * closure over the heap graph.
- */
-@Uninterruptible
-public final class BTSweeper extends ExplicitFreeListSpace.Sweeper {
-
- private final BTDecMarked sdm = new BTDecMarked();
-
- public boolean sweepCell(ObjectReference object) {
- if (!RCHeader.isMarked(object)) {
- VM.scanning.scanObject(sdm, object);
- return true;
- } else {
- RCHeader.clearMarked(object);
- }
- return false;
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/plan/refcount/backuptrace/BTTraceLocal.java b/vmkit/mmtk/java/src/org/mmtk/plan/refcount/backuptrace/BTTraceLocal.java
deleted file mode 100644
index b44dd22..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/plan/refcount/backuptrace/BTTraceLocal.java
+++ /dev/null
@@ -1,66 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.plan.refcount.backuptrace;
-
-import org.mmtk.plan.TraceLocal;
-import org.mmtk.plan.Trace;
-import org.mmtk.plan.refcount.RCBase;
-import org.mmtk.plan.refcount.RCHeader;
-
-import org.vmmagic.pragma.*;
-import org.vmmagic.unboxed.*;
-
-/**
- * This class implements the thread-local core functionality for a transitive
- * closure over the heap graph.
- */
-@Uninterruptible
-public final class BTTraceLocal extends TraceLocal {
- /**
- * Constructor
- */
- public BTTraceLocal(Trace trace) {
- super(trace);
- }
-
- /****************************************************************************
- *
- * Externally visible Object processing and tracing
- */
-
- /**
- * Is the specified object reachable?
- *
- * @param object The object.
- * @return <code>true</code> if the object is reachable.
- */
- public boolean isLive(ObjectReference object) {
- return !RCBase.isRCObject(object) || RCHeader.isMarked(object);
- }
-
- /**
- * When we trace a non-root object we do nothing.
- *
- * @param object The object to be traced.
- * @return The new reference to the same object instance.
- */
- @Inline
- public ObjectReference traceObject(ObjectReference object) {
- if (RCBase.isRCObject(object)) {
- if (RCHeader.testAndMark(object)) {
- processNode(object);
- }
- }
- return object;
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/plan/refcount/fullheap/RC.java b/vmkit/mmtk/java/src/org/mmtk/plan/refcount/fullheap/RC.java
deleted file mode 100644
index f2cf82e..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/plan/refcount/fullheap/RC.java
+++ /dev/null
@@ -1,23 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.plan.refcount.fullheap;
-
-import org.mmtk.plan.refcount.RCBase;
-import org.vmmagic.pragma.*;
-
-/**
- * This class implements the global state of a a simple reference counting collector.
- */
-@Uninterruptible
-public class RC extends RCBase {
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/plan/refcount/fullheap/RCCollector.java b/vmkit/mmtk/java/src/org/mmtk/plan/refcount/fullheap/RCCollector.java
deleted file mode 100644
index b65ebbc..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/plan/refcount/fullheap/RCCollector.java
+++ /dev/null
@@ -1,53 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.plan.refcount.fullheap;
-
-import org.mmtk.plan.TraceLocal;
-import org.mmtk.plan.TransitiveClosure;
-import org.mmtk.plan.refcount.RCBaseCollector;
-import org.vmmagic.pragma.*;
-
-/**
- * This class implements the collector context for a simple reference counting
- * collector.
- */
-@Uninterruptible
-public class RCCollector extends RCBaseCollector {
- /************************************************************************
- * Initialization
- */
- private final RCFindRootSetTraceLocal rootTrace;
- private final RCModifiedProcessor modProcessor;
-
- /**
- * Constructor.
- */
- public RCCollector() {
- rootTrace = new RCFindRootSetTraceLocal(global().rootTrace, newRootBuffer);
- modProcessor = new RCModifiedProcessor();
- }
-
- /**
- * Get the modified processor to use.
- */
- protected final TransitiveClosure getModifiedProcessor() {
- return modProcessor;
- }
-
- /**
- * Get the root trace to use.
- */
- protected final TraceLocal getRootTrace() {
- return rootTrace;
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/plan/refcount/fullheap/RCConstraints.java b/vmkit/mmtk/java/src/org/mmtk/plan/refcount/fullheap/RCConstraints.java
deleted file mode 100644
index a4994fe..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/plan/refcount/fullheap/RCConstraints.java
+++ /dev/null
@@ -1,26 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.plan.refcount.fullheap;
-
-import org.mmtk.plan.refcount.RCBaseConstraints;
-import org.vmmagic.pragma.*;
-
-/**
- * This class and its subclasses communicate to the host VM/Runtime
- * any features of the selected plan that it needs to know. This is
- * separate from the main Plan/PlanLocal class in order to bypass any
- * issues with ordering of static initialization.
- */
-@Uninterruptible
-public class RCConstraints extends RCBaseConstraints {
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/plan/refcount/fullheap/RCFindRootSetTraceLocal.java b/vmkit/mmtk/java/src/org/mmtk/plan/refcount/fullheap/RCFindRootSetTraceLocal.java
deleted file mode 100644
index dfeef65..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/plan/refcount/fullheap/RCFindRootSetTraceLocal.java
+++ /dev/null
@@ -1,80 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.plan.refcount.fullheap;
-
-import org.mmtk.plan.TraceLocal;
-import org.mmtk.plan.Trace;
-import org.mmtk.plan.refcount.RCBase;
-import org.mmtk.plan.refcount.RCHeader;
-import org.mmtk.utility.deque.ObjectReferenceDeque;
-
-import org.vmmagic.pragma.*;
-import org.vmmagic.unboxed.*;
-
-/**
- * This class implements the thread-local core functionality for a transitive
- * closure over the heap graph.
- */
-@Uninterruptible
-public final class RCFindRootSetTraceLocal extends TraceLocal {
-
- private final ObjectReferenceDeque rootBuffer;
-
- /**
- * Constructor
- */
- public RCFindRootSetTraceLocal(Trace trace, ObjectReferenceDeque rootBuffer) {
- super(trace);
- this.rootBuffer = rootBuffer;
- }
-
- /****************************************************************************
- *
- * Externally visible Object processing and tracing
- */
-
- /**
- * Is the specified object reachable?
- *
- * @param object The object.
- * @return <code>true</code> if the object is reachable.
- */
- public boolean isLive(ObjectReference object) {
- return RCBase.isRCObject(object) && RCHeader.isLiveRC(object) || super.isLive(object);
- }
-
- /**
- * When we trace a non-root object we do nothing.
- *
- * @param object The object to be traced.
- * @return The new reference to the same object instance.
- */
- @Inline
- public ObjectReference traceObject(ObjectReference object) {
- return object;
- }
-
- /**
- * When we trace a root object we remember it.
- *
- * @param object The object to be traced.
- * @return The new reference to the same object instance.
- */
- @Inline
- public ObjectReference traceObject(ObjectReference object, boolean root) {
- if (root && RCBase.isRCObject(object)) {
- rootBuffer.push(object);
- }
- return object;
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/plan/refcount/fullheap/RCModifiedProcessor.java b/vmkit/mmtk/java/src/org/mmtk/plan/refcount/fullheap/RCModifiedProcessor.java
deleted file mode 100644
index bc9b729..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/plan/refcount/fullheap/RCModifiedProcessor.java
+++ /dev/null
@@ -1,44 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.plan.refcount.fullheap;
-
-import org.mmtk.plan.TransitiveClosure;
-import org.mmtk.plan.refcount.RCBase;
-import org.mmtk.plan.refcount.RCHeader;
-
-import org.vmmagic.pragma.*;
-import org.vmmagic.unboxed.*;
-
-/**
- * This class is the fundamental mechanism for performing a
- * transitive closure over an object graph.<p>
- *
- * @see org.mmtk.plan.TraceLocal
- */
-@Uninterruptible
-public final class RCModifiedProcessor extends TransitiveClosure {
-
- /**
- * Trace an edge during GC.
- *
- * @param source The source of the reference.
- * @param slot The location containing the object reference.
- */
- @Inline
- public void processEdge(ObjectReference source, Address slot) {
- ObjectReference object = slot.loadObjectReference();
- if (RCBase.isRCObject(object)) {
- RCHeader.incRC(object);
- }
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/plan/refcount/fullheap/RCMutator.java b/vmkit/mmtk/java/src/org/mmtk/plan/refcount/fullheap/RCMutator.java
deleted file mode 100644
index eafecc0..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/plan/refcount/fullheap/RCMutator.java
+++ /dev/null
@@ -1,23 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.plan.refcount.fullheap;
-
-import org.mmtk.plan.refcount.RCBaseMutator;
-import org.vmmagic.pragma.*;
-
-/**
- * This class implements the mutator context for a simple reference counting collector.
- */
-@Uninterruptible
-public class RCMutator extends RCBaseMutator {
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/plan/refcount/generational/GenRC.java b/vmkit/mmtk/java/src/org/mmtk/plan/refcount/generational/GenRC.java
deleted file mode 100644
index 4792568..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/plan/refcount/generational/GenRC.java
+++ /dev/null
@@ -1,128 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.plan.refcount.generational;
-
-import org.mmtk.plan.refcount.RCBase;
-import org.mmtk.policy.CopySpace;
-import org.mmtk.policy.Space;
-import org.mmtk.utility.heap.VMRequest;
-import org.mmtk.utility.options.Options;
-import org.vmmagic.pragma.*;
-import org.vmmagic.unboxed.ObjectReference;
-
-/**
- * This class implements the global state of a a simple reference counting collector.
- */
-@Uninterruptible
-public class GenRC extends RCBase {
-
- public static final int ALLOC_NURSERY = ALLOC_DEFAULT;
- public static final int ALLOC_RC = RCBase.ALLOCATORS + 1;
-
- /** The nursery space is where all new objects are allocated by default */
- public static final CopySpace nurserySpace = new CopySpace("nursery", DEFAULT_POLL_FREQUENCY, false, VMRequest.create(0.15f, true));
-
- public static final int NURSERY = nurserySpace.getDescriptor();
-
- /*****************************************************************************
- *
- * Collection
- */
-
- /**
- * Perform a (global) collection phase.
- *
- * @param phaseId Collection phase
- */
- public final void collectionPhase(short phaseId) {
- if (phaseId == PREPARE) {
- nurserySpace.prepare(true);
- super.collectionPhase(phaseId);
- return;
- }
-
- if (phaseId == RELEASE) {
- super.collectionPhase(phaseId);
- nurserySpace.release();
- return;
- }
-
- super.collectionPhase(phaseId);
- }
-
- /**
- * This method controls the triggering of a GC. It is called periodically
- * during allocation. Returns true to trigger a collection.
- *
- * @param spaceFull Space request failed, must recover pages within 'space'.
- * @return True if a collection is requested by the plan.
- */
- public final boolean collectionRequired(boolean spaceFull) {
- boolean nurseryFull = nurserySpace.reservedPages() > Options.nurserySize.getMaxNursery();
- return super.collectionRequired(spaceFull) || nurseryFull;
- }
-
- /*****************************************************************************
- *
- * Accounting
- */
-
- /**
- * Return the number of pages available for allocation, <i>assuming
- * all future allocation is to the nursery</i>.
- *
- * @return The number of pages available for allocation, <i>assuming
- * all future allocation is to the nursery</i>.
- */
- public int getPagesAvail() {
- return super.getPagesAvail() >> 1;
- }
-
- /**
- * Return the number of pages reserved for copying.
- *
- * @return The number of pages reserved given the pending
- * allocation, including space reserved for copying.
- */
- public final int getCollectionReserve() {
- return nurserySpace.reservedPages() + super.getCollectionReserve();
- }
-
- /**
- * Calculate the number of pages a collection is required to free to satisfy
- * outstanding allocation requests.
- *
- * @return the number of pages a collection is required to free to satisfy
- * outstanding allocation requests.
- */
- public int getPagesRequired() {
- return super.getPagesRequired() + (nurserySpace.requiredPages() << 1);
- }
-
- /**
- * @see org.mmtk.plan.Plan#willNeverMove
- *
- * @param object Object in question
- * @return True if the object will never move
- */
- @Override
- public boolean willNeverMove(ObjectReference object) {
- if (Space.isInSpace(NURSERY, object)) {
- return false;
- }
- if (Space.isInSpace(REF_COUNT_LOS, object)) {
- return true;
- }
- return super.willNeverMove(object);
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/plan/refcount/generational/GenRCCollector.java b/vmkit/mmtk/java/src/org/mmtk/plan/refcount/generational/GenRCCollector.java
deleted file mode 100644
index 146467b..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/plan/refcount/generational/GenRCCollector.java
+++ /dev/null
@@ -1,124 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.plan.refcount.generational;
-
-import org.mmtk.plan.TraceLocal;
-import org.mmtk.plan.TransitiveClosure;
-import org.mmtk.plan.refcount.RCBase;
-import org.mmtk.plan.refcount.RCBaseCollector;
-import org.mmtk.plan.refcount.RCHeader;
-import org.mmtk.policy.ExplicitFreeListLocal;
-import org.mmtk.policy.ExplicitFreeListSpace;
-import org.mmtk.utility.ForwardingWord;
-import org.mmtk.vm.VM;
-import org.vmmagic.pragma.*;
-import org.vmmagic.unboxed.Address;
-import org.vmmagic.unboxed.ObjectReference;
-
-/**
- * This class implements the collector context for a simple reference counting
- * collector.
- */
-@Uninterruptible
-public class GenRCCollector extends RCBaseCollector {
- private final GenRCFindRootSetTraceLocal rootTrace;
- private final GenRCModifiedProcessor modProcessor;
- private final ExplicitFreeListLocal rc;
-
- public GenRCCollector() {
- rc = new ExplicitFreeListLocal(GenRC.rcSpace);
- rootTrace = new GenRCFindRootSetTraceLocal(global().rootTrace, newRootBuffer);
- modProcessor = new GenRCModifiedProcessor(rootTrace);
- }
-
- /****************************************************************************
- *
- * Collection
- */
-
- /**
- * Perform a per-collector collection phase.
- *
- * @param phaseId The collection phase to perform
- * @param primary perform any single-threaded local activities.
- */
- public final void collectionPhase(short phaseId, boolean primary) {
- if (phaseId == RCBase.PREPARE) {
- super.collectionPhase(phaseId, primary);
- rc.prepare();
- return;
- }
-
- if (phaseId == RCBase.RELEASE) {
- rc.release();
- super.collectionPhase(phaseId, primary);
- return;
- }
-
- super.collectionPhase(phaseId, primary);
- }
-
- /****************************************************************************
- *
- * Collection-time allocation
- */
-
- /**
- * Allocate space for copying an object (this method <i>does not</i>
- * copy the object, it only allocates space)
- *
- * @param original A reference to the original object
- * @param bytes The size of the space to be allocated (in bytes)
- * @param align The requested alignment
- * @param offset The alignment offset
- * @return The address of the first byte of the allocated region
- */
- @Inline
- public final Address allocCopy(ObjectReference original, int bytes,
- int align, int offset, int allocator) {
- if (VM.VERIFY_ASSERTIONS) {
- VM.assertions._assert(allocator == GenRC.ALLOC_RC);
- }
- return rc.alloc(bytes, align, offset);
- }
-
- /**
- * Perform any post-copy actions. In this case nothing is required.
- *
- * @param object The newly allocated object
- * @param typeRef the type reference for the instance being created
- * @param bytes The size of the space to be allocated (in bytes)
- */
- @Inline
- public final void postCopy(ObjectReference object, ObjectReference typeRef,
- int bytes, int allocator) {
- ForwardingWord.clearForwardingBits(object);
- RCHeader.initializeHeader(object, false);
- RCHeader.makeUnlogged(object);
- ExplicitFreeListSpace.unsyncSetLiveBit(object);
- }
-
- /**
- * Get the modified processor to use.
- */
- protected final TransitiveClosure getModifiedProcessor() {
- return modProcessor;
- }
-
- /**
- * Get the root trace to use.
- */
- protected final TraceLocal getRootTrace() {
- return rootTrace;
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/plan/refcount/generational/GenRCConstraints.java b/vmkit/mmtk/java/src/org/mmtk/plan/refcount/generational/GenRCConstraints.java
deleted file mode 100644
index ee3af34..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/plan/refcount/generational/GenRCConstraints.java
+++ /dev/null
@@ -1,32 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.plan.refcount.generational;
-
-import static org.mmtk.policy.SegregatedFreeListSpace.MAX_FREELIST_OBJECT_BYTES;
-
-import org.mmtk.plan.refcount.RCBaseConstraints;
-import org.vmmagic.pragma.*;
-
-/**
- * This class and its subclasses communicate to the host VM/Runtime
- * any features of the selected plan that it needs to know. This is
- * separate from the main Plan/PlanLocal class in order to bypass any
- * issues with ordering of static initialization.
- */
-@Uninterruptible
-public class GenRCConstraints extends RCBaseConstraints {
- @Override
- public boolean movesObjects() { return true; }
- @Override
- public int maxNonLOSCopyBytes() { return MAX_FREELIST_OBJECT_BYTES;}
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/plan/refcount/generational/GenRCFindRootSetTraceLocal.java b/vmkit/mmtk/java/src/org/mmtk/plan/refcount/generational/GenRCFindRootSetTraceLocal.java
deleted file mode 100644
index 07bef16..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/plan/refcount/generational/GenRCFindRootSetTraceLocal.java
+++ /dev/null
@@ -1,123 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.plan.refcount.generational;
-
-import org.mmtk.plan.TraceLocal;
-import org.mmtk.plan.Trace;
-import org.mmtk.plan.refcount.RCHeader;
-import org.mmtk.policy.Space;
-import org.mmtk.utility.deque.ObjectReferenceDeque;
-import org.mmtk.vm.VM;
-
-import org.vmmagic.pragma.*;
-import org.vmmagic.unboxed.*;
-
-/**
- * This class implements the thread-local core functionality for a transitive
- * closure over the heap graph.
- */
-@Uninterruptible
-public final class GenRCFindRootSetTraceLocal extends TraceLocal {
-
- private final ObjectReferenceDeque rootBuffer;
-
- /**
- * Constructor
- */
- public GenRCFindRootSetTraceLocal(Trace trace, ObjectReferenceDeque rootBuffer) {
- super(trace);
- this.rootBuffer = rootBuffer;
- }
-
- /****************************************************************************
- *
- * Externally visible Object processing and tracing
- */
-
- /**
- * Is the specified object reachable?
- *
- * @param object The object.
- * @return <code>true</code> if the object is reachable.
- */
- public boolean isLive(ObjectReference object) {
- return GenRC.isRCObject(object) && RCHeader.isLiveRC(object) ||
- (!Space.isInSpace(GenRC.NURSERY, object) && super.isLive(object));
- }
-
- /**
- * When we trace a non-root object we do nothing.
- *
- * @param object The object to be traced.
- * @return The new reference to the same object instance.
- */
- @Inline
- public ObjectReference traceObject(ObjectReference object) {
- return traceObject(object, false);
- }
-
- /**
- * When we trace a root object we remember it.
- *
- * @param object The object to be traced.
- * @return The new reference to the same object instance.
- */
- @Inline
- public ObjectReference traceObject(ObjectReference object, boolean root) {
- if (object.isNull()) return object;
-
- if (Space.isInSpace(GenRC.NURSERY, object)) {
- object = GenRC.nurserySpace.traceObject(this, object, GenRC.ALLOC_RC);
- } else if (!GenRC.isRCObject(object)) {
- return object;
- }
-
- if (root) {
- rootBuffer.push(object);
- } else {
- RCHeader.incRC(object);
- }
-
- return object;
- }
-
- /**
- * Ensure that the referenced object will not move from this point through
- * to the end of the collection. This can involve forwarding the object
- * if necessary.
- *
- * <i>Non-copying collectors do nothing, copying collectors must
- * override this method in each of their trace classes.</i>
- *
- * @param object The object that must not move during the collection.
- * @return True If the object will not move during collection
- */
- public boolean willNotMoveInCurrentCollection(ObjectReference object) {
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(!object.isNull());
- return !(Space.isInSpace(GenRC.NURSERY, object));
- }
-
- /**
- * Ensure that this object will not move for the rest of the GC.
- *
- * @param object The object that must not move
- * @return The new object, guaranteed stable for the rest of the GC.
- */
- public ObjectReference precopyObject(ObjectReference object) {
- if (Space.isInSpace(GenRC.NURSERY, object)) {
- return GenRC.nurserySpace.traceObject(this, object, GenRC.ALLOC_RC);
- }
- return object;
- }
-
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/plan/refcount/generational/GenRCModifiedProcessor.java b/vmkit/mmtk/java/src/org/mmtk/plan/refcount/generational/GenRCModifiedProcessor.java
deleted file mode 100644
index 6063123..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/plan/refcount/generational/GenRCModifiedProcessor.java
+++ /dev/null
@@ -1,56 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.plan.refcount.generational;
-
-import org.mmtk.plan.TransitiveClosure;
-import org.mmtk.plan.refcount.RCHeader;
-import org.mmtk.policy.Space;
-
-import org.vmmagic.pragma.*;
-import org.vmmagic.unboxed.*;
-
-/**
- * This class is the fundamental mechanism for performing a
- * transitive closure over an object graph.<p>
- *
- * @see org.mmtk.plan.TraceLocal
- */
-@Uninterruptible
-public final class GenRCModifiedProcessor extends TransitiveClosure {
-
- private final GenRCFindRootSetTraceLocal trace;
-
- public GenRCModifiedProcessor(GenRCFindRootSetTraceLocal trace) {
- this.trace = trace;
- }
-
- /**
- * Trace an edge during GC.
- *
- * @param source The source of the reference.
- * @param slot The location containing the object reference.
- */
- @Inline
- public void processEdge(ObjectReference source, Address slot) {
- ObjectReference object = slot.loadObjectReference();
- if (!object.isNull()) {
- if (Space.isInSpace(GenRC.NURSERY, object)) {
- object = GenRC.nurserySpace.traceObject(trace, object, GenRC.ALLOC_RC);
- RCHeader.incRC(object);
- slot.store(object);
- } else if (GenRC.isRCObject(object)) {
- RCHeader.incRC(object);
- }
- }
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/plan/refcount/generational/GenRCMutator.java b/vmkit/mmtk/java/src/org/mmtk/plan/refcount/generational/GenRCMutator.java
deleted file mode 100644
index 358a3d9..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/plan/refcount/generational/GenRCMutator.java
+++ /dev/null
@@ -1,113 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.plan.refcount.generational;
-
-import org.mmtk.plan.refcount.RCBase;
-import org.mmtk.plan.refcount.RCBaseMutator;
-import org.mmtk.policy.CopyLocal;
-import org.mmtk.policy.Space;
-import org.mmtk.utility.alloc.Allocator;
-import org.vmmagic.pragma.*;
-import org.vmmagic.unboxed.Address;
-import org.vmmagic.unboxed.ObjectReference;
-
-/**
- * This class implements the mutator context for a simple reference counting collector.
- */
-@Uninterruptible
-public class GenRCMutator extends RCBaseMutator {
- /************************************************************************
- * Instance fields
- */
- private final CopyLocal nursery;
-
- public GenRCMutator() {
- nursery = new CopyLocal(GenRC.nurserySpace);
- }
-
- /****************************************************************************
- *
- * Mutator-time allocation
- */
-
- /**
- * Allocate memory for an object.
- *
- * @param bytes The number of bytes required for the object.
- * @param align Required alignment for the object.
- * @param offset Offset associated with the alignment.
- * @param allocator The allocator associated with this request.
- * @param site Allocation site
- * @return The address of the newly allocated memory.
- */
- @Inline
- public Address alloc(int bytes, int align, int offset, int allocator, int site) {
- if (allocator == GenRC.ALLOC_NURSERY) {
- return nursery.alloc(bytes, align, offset);
- }
- return super.alloc(bytes, align, offset, allocator, site);
- }
-
- /**
- * Perform post-allocation actions. For many allocators none are
- * required.
- *
- * @param ref The newly allocated object
- * @param typeRef the type reference for the instance being created
- * @param bytes The size of the space to be allocated (in bytes)
- * @param allocator The allocator number to be used for this allocation
- */
- @Inline
- public void postAlloc(ObjectReference ref, ObjectReference typeRef, int bytes, int allocator) {
- if (allocator == GenRC.ALLOC_NURSERY) {
- return;
- }
- super.postAlloc(ref, typeRef, bytes, allocator);
- }
-
- /**
- * Return the allocator instance associated with a space
- * <code>space</code>, for this plan instance.
- *
- * @param space The space for which the allocator instance is desired.
- * @return The allocator instance associated with this plan instance
- * which is allocating into <code>space</code>, or <code>null</code>
- * if no appropriate allocator can be established.
- */
- public Allocator getAllocatorFromSpace(Space space) {
- if (space == GenRC.nurserySpace) return nursery;
-
- return super.getAllocatorFromSpace(space);
- }
-
- /****************************************************************************
- *
- * Collection
- */
-
- /**
- * Perform a per-mutator collection phase.
- *
- * @param phaseId The collection phase to perform
- * @param primary perform any single-threaded local activities.
- */
- public final void collectionPhase(short phaseId, boolean primary) {
- if (phaseId == RCBase.PREPARE) {
- nursery.rebind(GenRC.nurserySpace);
- super.collectionPhase(phaseId, primary);
- return;
- }
-
- super.collectionPhase(phaseId, primary);
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/plan/semispace/SS.java b/vmkit/mmtk/java/src/org/mmtk/plan/semispace/SS.java
deleted file mode 100644
index bcbc38a..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/plan/semispace/SS.java
+++ /dev/null
@@ -1,206 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.plan.semispace;
-
-import org.mmtk.policy.CopySpace;
-import org.mmtk.policy.Space;
-import org.mmtk.plan.*;
-import org.mmtk.utility.heap.VMRequest;
-
-import org.vmmagic.pragma.*;
-import org.vmmagic.unboxed.*;
-
-/**
- * This class implements a simple semi-space collector. See the Jones
- * & Lins GC book, section 2.2 for an overview of the basic
- * algorithm. This implementation also includes a large object space
- * (LOS), and an uncollected "immortal" space.<p>
- *
- * All plans make a clear distinction between <i>global</i> and
- * <i>thread-local</i> activities. Global activities must be
- * synchronized, whereas no synchronization is required for
- * thread-local activities. Instances of Plan map 1:1 to "kernel
- * threads" (aka CPUs). Thus instance
- * methods allow fast, unsychronized access to Plan utilities such as
- * allocation and collection. Each instance rests on static resources
- * (such as memory and virtual memory resources) which are "global"
- * and therefore "static" members of Plan. This mapping of threads to
- * instances is crucial to understanding the correctness and
- * performance proprties of this plan.
- */
-@Uninterruptible
-public class SS extends StopTheWorld {
-
- /****************************************************************************
- *
- * Class variables
- */
-
- /** True if allocating into the "higher" semispace */
- public static boolean hi = false; // True if allocing to "higher" semispace
-
- /** One of the two semi spaces that alternate roles at each collection */
- public static final CopySpace copySpace0 = new CopySpace("ss0", DEFAULT_POLL_FREQUENCY, false, VMRequest.create());
- public static final int SS0 = copySpace0.getDescriptor();
-
- /** One of the two semi spaces that alternate roles at each collection */
- public static final CopySpace copySpace1 = new CopySpace("ss1", DEFAULT_POLL_FREQUENCY, true, VMRequest.create());
- public static final int SS1 = copySpace1.getDescriptor();
-
- public final Trace ssTrace;
-
- /****************************************************************************
- *
- * Initialization
- */
-
- /**
- * Class variables
- */
- public static final int ALLOC_SS = Plan.ALLOC_DEFAULT;
-
- public static final int SCAN_SS = 0;
-
- /**
- * Constructor
- */
- public SS() {
- ssTrace = new Trace(metaDataSpace);
- }
-
- /**
- * @return The to space for the current collection.
- */
- @Inline
- public static CopySpace toSpace() {
- return hi ? copySpace1 : copySpace0;
- }
-
- /**
- * @return The from space for the current collection.
- */
- @Inline
- public static CopySpace fromSpace() {
- return hi ? copySpace0 : copySpace1;
- }
-
-
- /****************************************************************************
- *
- * Collection
- */
-
- /**
- * Perform a (global) collection phase.
- *
- * @param phaseId Collection phase
- */
- @Inline
- public void collectionPhase(short phaseId) {
- if (phaseId == SS.PREPARE) {
- hi = !hi; // flip the semi-spaces
- // prepare each of the collected regions
- copySpace0.prepare(hi);
- copySpace1.prepare(!hi);
- ssTrace.prepare();
- super.collectionPhase(phaseId);
- return;
- }
- if (phaseId == CLOSURE) {
- ssTrace.prepare();
- return;
- }
- if (phaseId == SS.RELEASE) {
- // release the collected region
- fromSpace().release();
-
- super.collectionPhase(phaseId);
- return;
- }
-
- super.collectionPhase(phaseId);
- }
-
- /****************************************************************************
- *
- * Accounting
- */
-
- /**
- * Return the number of pages reserved for copying.
- *
- * @return The number of pages reserved given the pending
- * allocation, including space reserved for copying.
- */
- public final int getCollectionReserve() {
- // we must account for the number of pages required for copying,
- // which equals the number of semi-space pages reserved
- return toSpace().reservedPages() + super.getCollectionReserve();
- }
-
- /**
- * Return the number of pages reserved for use given the pending
- * allocation. This is <i>exclusive of</i> space reserved for
- * copying.
- *
- * @return The number of pages reserved given the pending
- * allocation, excluding space reserved for copying.
- */
- public int getPagesUsed() {
- return super.getPagesUsed() + toSpace().reservedPages();
- }
-
- /**
- * Return the number of pages available for allocation, <i>assuming
- * all future allocation is to the semi-space</i>.
- *
- * @return The number of pages available for allocation, <i>assuming
- * all future allocation is to the semi-space</i>.
- */
- public final int getPagesAvail() {
- return(super.getPagesAvail()) >> 1;
- }
-
- /**
- * Calculate the number of pages a collection is required to free to satisfy
- * outstanding allocation requests.
- *
- * @return the number of pages a collection is required to free to satisfy
- * outstanding allocation requests.
- */
- public int getPagesRequired() {
- return super.getPagesRequired() + (toSpace().requiredPages() << 1);
- }
-
- /**
- * @see org.mmtk.plan.Plan#willNeverMove
- *
- * @param object Object in question
- * @return True if the object will never move
- */
- @Override
- public boolean willNeverMove(ObjectReference object) {
- if (Space.isInSpace(SS0, object) || Space.isInSpace(SS1, object))
- return false;
- return super.willNeverMove(object);
- }
-
- /**
- * Register specialized methods.
- */
- @Interruptible
- protected void registerSpecializedMethods() {
- TransitiveClosure.registerSpecializedScan(SCAN_SS, SSTraceLocal.class);
- super.registerSpecializedMethods();
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/plan/semispace/SSCollector.java b/vmkit/mmtk/java/src/org/mmtk/plan/semispace/SSCollector.java
deleted file mode 100644
index a921b8a..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/plan/semispace/SSCollector.java
+++ /dev/null
@@ -1,188 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.plan.semispace;
-
-import org.mmtk.plan.*;
-import org.mmtk.policy.CopyLocal;
-import org.mmtk.policy.LargeObjectLocal;
-import org.mmtk.policy.Space;
-import org.mmtk.utility.ForwardingWord;
-import org.mmtk.vm.VM;
-
-import org.vmmagic.unboxed.*;
-import org.vmmagic.pragma.*;
-
-/**
- * This class implements <i>per-collector thread</i> behavior
- * and state for the <i>SS</i> plan, which implements a full-heap
- * semi-space collector.<p>
- *
- * Specifically, this class defines <i>SS</i> collection behavior
- * (through <code>trace</code> and the <code>collectionPhase</code>
- * method), and collection-time allocation (copying of objects).<p>
- *
- * See {@link SS} for an overview of the semi-space algorithm.<p>
- *
- * @see SS
- * @see SSMutator
- * @see StopTheWorldCollector
- * @see CollectorContext
- */
-@Uninterruptible
-public class SSCollector extends StopTheWorldCollector {
-
- /****************************************************************************
- * Instance fields
- */
-
- protected final SSTraceLocal trace;
- protected final CopyLocal ss;
- protected final LargeObjectLocal los;
-
- /****************************************************************************
- *
- * Initialization
- */
-
- /**
- * Constructor
- */
- public SSCollector() {
- this(new SSTraceLocal(global().ssTrace));
- }
-
- /**
- * Constructor
- * @param tr The trace to use
- */
- protected SSCollector(SSTraceLocal tr) {
- ss = new CopyLocal();
- los = new LargeObjectLocal(Plan.loSpace);
- trace = tr;
- }
-
- /****************************************************************************
- *
- * Collection-time allocation
- */
-
- /**
- * Allocate space for copying an object (this method <i>does not</i>
- * copy the object, it only allocates space)
- *
- * @param original A reference to the original object
- * @param bytes The size of the space to be allocated (in bytes)
- * @param align The requested alignment.
- * @param offset The alignment offset.
- * @return The address of the first byte of the allocated region
- */
- @Inline
- public Address allocCopy(ObjectReference original, int bytes,
- int align, int offset, int allocator) {
- if (allocator == Plan.ALLOC_LOS) {
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(bytes > Plan.MAX_NON_LOS_COPY_BYTES);
- return los.alloc(bytes, align, offset);
- } else {
- if (VM.VERIFY_ASSERTIONS) {
- VM.assertions._assert(bytes <= Plan.MAX_NON_LOS_COPY_BYTES);
- VM.assertions._assert(allocator == SS.ALLOC_SS);
- }
- return ss.alloc(bytes, align, offset);
- }
- }
-
- /**
- * Perform any post-copy actions.
- *
- * @param object The newly allocated object
- * @param typeRef the type reference for the instance being created
- * @param bytes The size of the space to be allocated (in bytes)
- */
- @Inline
- public void postCopy(ObjectReference object, ObjectReference typeRef,
- int bytes, int allocator) {
- ForwardingWord.clearForwardingBits(object);
- if (allocator == Plan.ALLOC_LOS)
- Plan.loSpace.initializeHeader(object, false);
- }
-
- /****************************************************************************
- *
- * Collection
- */
-
- /**
- * Perform a per-collector collection phase.
- *
- * @param phaseId The collection phase to perform
- * @param primary Perform any single-threaded activities using this thread.
- */
- @Inline
- public void collectionPhase(short phaseId, boolean primary) {
- if (phaseId == SS.PREPARE) {
- // rebind the copy bump pointer to the appropriate semispace.
- ss.rebind(SS.toSpace());
- los.prepare(true);
- super.collectionPhase(phaseId, primary);
- return;
- }
-
- if (phaseId == SS.CLOSURE) {
- trace.completeTrace();
- return;
- }
-
- if (phaseId == SS.RELEASE) {
- trace.release();
- los.release(true);
- super.collectionPhase(phaseId, primary);
- return;
- }
-
- super.collectionPhase(phaseId, primary);
- }
-
-
- /****************************************************************************
- *
- * Object processing and tracing
- */
-
- /**
- * Return true if the given reference is to an object that is within
- * one of the semi-spaces.
- *
- * @param object The object in question
- * @return True if the given reference is to an object that is within
- * one of the semi-spaces.
- */
- public static boolean isSemiSpaceObject(ObjectReference object) {
- return Space.isInSpace(SS.SS0, object) || Space.isInSpace(SS.SS1, object);
- }
-
- /****************************************************************************
- *
- * Miscellaneous
- */
-
- /** @return The active global plan as an <code>SS</code> instance. */
- @Inline
- private static SS global() {
- return (SS) VM.activePlan.global();
- }
-
- /** @return the current trace object. */
- public TraceLocal getCurrentTrace() {
- return trace;
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/plan/semispace/SSConstraints.java b/vmkit/mmtk/java/src/org/mmtk/plan/semispace/SSConstraints.java
deleted file mode 100644
index 9c15561..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/plan/semispace/SSConstraints.java
+++ /dev/null
@@ -1,32 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.plan.semispace;
-
-import org.mmtk.plan.*;
-import org.mmtk.policy.CopySpace;
-import org.vmmagic.pragma.*;
-
-/**
- * SemiSpace common constants.
- */
-@Uninterruptible
-public class SSConstraints extends StopTheWorldConstraints {
- @Override
- public boolean movesObjects() { return true; }
- @Override
- public int gcHeaderBits() { return CopySpace.LOCAL_GC_BITS_REQUIRED; }
- @Override
- public int gcHeaderWords() { return CopySpace.GC_HEADER_WORDS_REQUIRED; }
- @Override
- public int numSpecializedScans() { return 1; }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/plan/semispace/SSMutator.java b/vmkit/mmtk/java/src/org/mmtk/plan/semispace/SSMutator.java
deleted file mode 100644
index d14900f..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/plan/semispace/SSMutator.java
+++ /dev/null
@@ -1,163 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.plan.semispace;
-
-import org.mmtk.plan.*;
-import org.mmtk.policy.CopyLocal;
-import org.mmtk.policy.Space;
-import org.mmtk.utility.alloc.Allocator;
-
-import org.vmmagic.unboxed.*;
-import org.vmmagic.pragma.*;
-
-/**
- * This class implements <i>per-mutator thread</i> behavior
- * and state for the <i>SS</i> plan, which implements a full-heap
- * semi-space collector.<p>
- *
- * Specifically, this class defines <i>SS</i> mutator-time allocation
- * and per-mutator thread collection semantics (flushing and restoring
- * per-mutator allocator state).<p>
- *
- * See {@link SS} for an overview of the semi-space algorithm.<p>
- *
- * @see SS
- * @see SSCollector
- * @see StopTheWorldMutator
- * @see MutatorContext
- */
-@Uninterruptible
-public class SSMutator extends StopTheWorldMutator {
- /****************************************************************************
- * Instance fields
- */
- protected final CopyLocal ss;
-
- /****************************************************************************
- *
- * Initialization
- */
-
- /**
- * Constructor
- */
- public SSMutator() {
- ss = new CopyLocal();
- }
-
- /**
- * Called before the MutatorContext is used, but after the context has been
- * fully registered and is visible to collection.
- */
- public void initMutator(int id) {
- super.initMutator(id);
- ss.rebind(SS.toSpace());
- }
-
- /****************************************************************************
- *
- * Mutator-time allocation
- */
-
- /**
- * Allocate space (for an object)
- *
- * @param bytes The size of the space to be allocated (in bytes)
- * @param align The requested alignment.
- * @param offset The alignment offset.
- * @param allocator The allocator number to be used for this allocation
- * @param site Allocation site
- * @return The address of the first byte of the allocated region
- */
- @Inline
- public Address alloc(int bytes, int align, int offset, int allocator, int site) {
- if (allocator == SS.ALLOC_SS)
- return ss.alloc(bytes, align, offset);
- else
- return super.alloc(bytes, align, offset, allocator, site);
- }
-
- /**
- * Perform post-allocation actions. For many allocators none are
- * required.
- *
- * @param object The newly allocated object
- * @param typeRef The type reference for the instance being created
- * @param bytes The size of the space to be allocated (in bytes)
- * @param allocator The allocator number to be used for this allocation
- */
- @Inline
- public void postAlloc(ObjectReference object, ObjectReference typeRef,
- int bytes, int allocator) {
- if (allocator == SS.ALLOC_SS) return;
- super.postAlloc(object, typeRef, bytes, allocator);
- }
-
- /**
- * Return the allocator instance associated with a space
- * <code>space</code>, for this plan instance.
- *
- * @param space The space for which the allocator instance is desired.
- * @return The allocator instance associated with this plan instance
- * which is allocating into <code>space</code>, or <code>null</code>
- * if no appropriate allocator can be established.
- */
- public Allocator getAllocatorFromSpace(Space space) {
- if (space == SS.copySpace0 || space == SS.copySpace1) return ss;
- return super.getAllocatorFromSpace(space);
- }
-
- /****************************************************************************
- *
- * Collection
- */
-
- /**
- * Perform a per-mutator collection phase.
- *
- * @param phaseId The collection phase to perform
- * @param primary Perform any single-threaded activities using this thread.
- */
- @Inline
- public void collectionPhase(short phaseId, boolean primary) {
- if (phaseId == SS.PREPARE) {
- super.collectionPhase(phaseId, primary);
- return;
- }
-
- if (phaseId == SS.RELEASE) {
- super.collectionPhase(phaseId, primary);
- // rebind the allocation bump pointer to the appropriate semispace.
- ss.rebind(SS.toSpace());
- return;
- }
-
- super.collectionPhase(phaseId, primary);
- }
-
-
- /****************************************************************************
- *
- * Miscellaneous
- */
-
- /**
- * Show the status of each of the allocators.
- */
- public final void show() {
- ss.show();
- los.show();
- immortal.show();
- }
-
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/plan/semispace/SSTraceLocal.java b/vmkit/mmtk/java/src/org/mmtk/plan/semispace/SSTraceLocal.java
deleted file mode 100644
index eecfbd9..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/plan/semispace/SSTraceLocal.java
+++ /dev/null
@@ -1,110 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.plan.semispace;
-
-import org.mmtk.plan.TraceLocal;
-import org.mmtk.plan.Trace;
-import org.mmtk.policy.Space;
-
-import org.vmmagic.pragma.*;
-import org.vmmagic.unboxed.*;
-
-/**
- * This class implments the core functionality for a transitive
- * closure over the heap graph.
- */
-@Uninterruptible
-public class SSTraceLocal extends TraceLocal {
- /**
- * Constructor
- */
- public SSTraceLocal(Trace trace, boolean specialized) {
- super(specialized ? SS.SCAN_SS : -1, trace);
- }
-
- /**
- * Constructor
- */
- public SSTraceLocal(Trace trace) {
- this(trace, true);
- }
-
- /****************************************************************************
- *
- * Externally visible Object processing and tracing
- */
-
- /**
- * Return true if <code>obj</code> is a live object.
- *
- * @param object The object in question
- * @return True if <code>obj</code> is a live object.
- */
- public boolean isLive(ObjectReference object) {
- if (object.isNull()) return false;
- if (Space.isInSpace(SS.SS0, object))
- return SS.hi ? SS.copySpace0.isLive(object) : true;
- if (Space.isInSpace(SS.SS1, object))
- return SS.hi ? true : SS.copySpace1.isLive(object);
- return super.isLive(object);
- }
-
-
- /**
- * This method is the core method during the trace of the object graph.
- * The role of this method is to:
- *
- * 1. Ensure the traced object is not collected.
- * 2. If this is the first visit to the object enqueue it to be scanned.
- * 3. Return the forwarded reference to the object.
- *
- * @param object The object to be traced.
- * @return The new reference to the same object instance.
- */
- @Inline
- public ObjectReference traceObject(ObjectReference object) {
- if (object.isNull()) return object;
- if (Space.isInSpace(SS.SS0, object))
- return SS.copySpace0.traceObject(this, object, SS.ALLOC_SS);
- if (Space.isInSpace(SS.SS1, object))
- return SS.copySpace1.traceObject(this, object, SS.ALLOC_SS);
- return super.traceObject(object);
- }
-
- /**
- * Ensure that this object will not move for the rest of the GC.
- *
- * @param object The object that must not move
- * @return The new object, guaranteed stable for the rest of the GC.
- */
- @Inline
- public ObjectReference precopyObject(ObjectReference object) {
- if (object.isNull()) return object;
- if (Space.isInSpace(SS.SS0, object))
- return SS.copySpace0.traceObject(this, object, SS.ALLOC_SS);
- if (Space.isInSpace(SS.SS1, object))
- return SS.copySpace1.traceObject(this, object, SS.ALLOC_SS);
- return object;
- }
-
- /**
- * Will this object move from this point on, during the current trace ?
- *
- * @param object The object to query.
- * @return True if the object will not move.
- */
- public boolean willNotMoveInCurrentCollection(ObjectReference object) {
- return (SS.hi && !Space.isInSpace(SS.SS0, object)) ||
- (!SS.hi && !Space.isInSpace(SS.SS1, object));
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/plan/semispace/gcspy/SSGCspy.java b/vmkit/mmtk/java/src/org/mmtk/plan/semispace/gcspy/SSGCspy.java
deleted file mode 100644
index 78c89c1..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/plan/semispace/gcspy/SSGCspy.java
+++ /dev/null
@@ -1,353 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.plan.semispace.gcspy;
-
-import org.mmtk.plan.GCspyPlan;
-import org.mmtk.plan.Phase;
-import org.mmtk.plan.TransitiveClosure;
-import org.mmtk.plan.semispace.SS;
-import org.mmtk.policy.CopySpace;
-import org.mmtk.policy.LargeObjectSpace;
-import org.mmtk.utility.gcspy.drivers.AbstractDriver;
-import org.mmtk.utility.gcspy.drivers.LinearSpaceDriver;
-import org.mmtk.utility.gcspy.drivers.ImmortalSpaceDriver;
-import org.mmtk.utility.gcspy.drivers.TreadmillDriver;
-import org.mmtk.utility.gcspy.GCspy;
-import org.mmtk.utility.Log;
-import org.mmtk.utility.options.Options;
-
-import org.vmmagic.pragma.*;
-
-/**
- * This class extends a simple semi-space collector to instrument it for
- * GCspy. <p>
- *
- * See the Jones & Lins GC book, section 2.2 for an overview of the basic
- * algorithm. This implementation also includes a large object space
- * (LOS), and an uncollected "immortal" space.<p>
- *
- * All plans make a clear distinction between <i>global</i> and
- * <i>thread-local</i> activities. Global activities must be
- * synchronized, whereas no synchronization is required for
- * thread-local activities. Instances of Plan map 1:1 to "kernel
- * threads" (aka CPUs). Thus instance
- * methods allow fast, unsychronized access to Plan utilities such as
- * allocation and collection. Each instance rests on static resources
- * (such as memory and virtual memory resources) which are "global"
- * and therefore "static" members of Plan. This mapping of threads to
- * instances is crucial to understanding the correctness and
- * performance proprties of this plan.
- *
- * FIXME This seems to have changed
- * The order of phases and GCspy actions is important here. It is:
- * PREPARE phase
- * SSGCspyMutator.gcspyGatherData(SSGCspy.BEFORE_COLLECTION); // safepoint
- * SSMutator.PREPARE // FIXME DOES NOT ss.rebind(SS.toSpace());
- *
- * PREPARE phase
- * SS.PREPARE // flip semispaces
- * gcspySpace.prepare();
- * SSGCspyCollector.gcspyGatherData(SSGCspy.BEFORE_COLLECTION);
- * SSCollector.PREPARE // ss.rebind(SS.toSpace());
- *
- *
- * FORWARD_FINALIZABLE phase
- * SSCollector.FORWARD_FINALIZABLE
- * SSGCspyCollector.gcspyGatherData(SSGCspy.SEMISPACE_COPIED);
- *
- * RELEASE phase
- * SSGCspyMutator.gcspyGatherData(SSGCspy.SEMISPACE_COPIED); // safepoint
- * SSMutator.RELEASE // FIXME ss.rebind(SS.toSpace());
- * SSGCspyMutator.gcspyGatherData(SSGCspy.AFTER_COLLECTION);
- *
- * RELEASE phase
- * SSCollector.RELEASE
- * SSGCspyCollector.gcspyGatherData(SSGCspy.AFTER_COLLECTION);
- * SS.RELEASE
- * gcspySpace.release();
- * SSGCspy.gcspyGatherData(); // safepoint
- *
- * Note that SSMutator has changed the point at which it rebinds toSpace
- * from PREPARE (2.4.6) to after RELEASE (3.x.x).
- *
- --Phase Collector.initiate
- --Phase Mutator.initiate-mutator
- --Phase Mutator.prepare-mutator
- SSGCspyMutator.gcspyGatherData, event=0
- --Phase Plan.prepare
- --Phase Collector.prepare
- SSGCspyCollector.gcspyGatherData, event=0
- --Phase Collector.precopy
- --Phase Collector.bootimage-root
- --Phase Collector.root
- --Phase Plan.root
- --Phase Collector.start-closure
- --Phase Collector.soft-ref
- --Phase Collector.complete-closure
- --Phase Collector.weak-ref
- --Phase Collector.finalize
- --Phase Collector.complete-closure
- --Phase Collector.phantom-ref
- --Phase Collector.forward-ref
- --Phase Collector.forward-finalize
- SSGCspyCollector.gcspyGatherData, event=1
- --Phase Mutator.release-mutator
- SSGCspyMutator.gcspyGatherData, event=1
- SSGCspyMutator.gcspyGatherData, event=2
- --Phase Collector.release
- SSGCspyCollector.gcspyGatherData, event=2
- --Phase Plan.release
- SSGCspy.gcspyGatherData, event=2
- --Phase Collector.complete
- --Phase Plan.complete
- */
-@Uninterruptible public class SSGCspy extends SS implements GCspyPlan {
-
- /****************************************************************************
- *
- * Class variables
- */
-
- // The events, BEFORE_COLLECTION, SEMISPACE_COPIED or AFTER_COLLECTION
-
- /**
- * Before a collection has started,
- * i.e. before SS.collectionPhase(SS.PREPARE,..).
- */
- static final int BEFORE_COLLECTION = 0;
-
- /**
- * After the semispace has been copied and the large object space has been traced
- * At this time the Large Object Space has not been swept.
- */
- static final int SEMISPACE_COPIED = BEFORE_COLLECTION + 1;
-
- /**
- * The collection is complete,
- * i.e. immediately after SS.collectionPhase(SS.RELEASE,..).
- * The Large Object Space has been swept.
- */
- static final int AFTER_COLLECTION = SEMISPACE_COPIED + 1;
-
- static int gcspyEvent_ = BEFORE_COLLECTION;
-
- // The specific drivers for this collector
- static LinearSpaceDriver ss0Driver;
- static LinearSpaceDriver ss1Driver;
- static ImmortalSpaceDriver immortalDriver;
- static TreadmillDriver losNurseryDriver;
- static TreadmillDriver losDriver;
- static TreadmillDriver plosNurseryDriver;
- static TreadmillDriver plosDriver;
-
- private static final boolean DEBUG = false;
-
-
- static {
- GCspy.createOptions();
- }
-
- /**
- * Start the server and wait if necessary.
- * This method has the following responsibilities.
- * <ol>
- * <li> Create and initialise the GCspy server by calling.
- * <pre>server = ServerInterpreter.init(name, portNumber, verbose);</pre>
- * <li> Add each event to the ServerInterpreter
- * <pre>server.addEvent(eventID, eventName);</pre>
- * <li> Set some general information about the server (e.g. name of the collector, build, etc).
- * <pre>server.setGeneralInfo(info); </pre>
- * <li> Create new drivers for each component to be visualised.
- * <pre>myDriver = new MyDriver(server, args...);</pre>
- * Drivers extend AbstractDriver and register their spce with the
- * ServerInterpreter. In addition to the server, drivers will take as
- * arguments the name of the space, the MMTk space, the tilesize, and
- * whether this space is to be the main space in the visualiser.
- * </ol>
- *
- * WARNING: allocates memory.
- * @param wait Whether to wait
- * @param port The port to talk to the GCspy client (e.g. visualiser)
- */
- @Interruptible
- public final void startGCspyServer(int port, boolean wait) {
- GCspy.server.init("SemiSpaceServerInterpreter", port, true/*verbose*/);
- if (DEBUG) Log.writeln("SSGCspy: ServerInterpreter initialised");
-
- GCspy.server.addEvent(BEFORE_COLLECTION, "Before collection");
- GCspy.server.addEvent(SEMISPACE_COPIED, "Semispace copied; LOS traced");
- GCspy.server.addEvent(AFTER_COLLECTION, "After collection; LOS swept");
- GCspy.server.setGeneralInfo(
- "SSGCspy\n\nRichard Jones, October 2006\\http://www.cs.kent.ac.uk/~rej/");
- if (DEBUG) Log.writeln("SSGCspy: events added to ServerInterpreter");
-
- // Initialise each driver
- ss0Driver = newLinearSpaceDriver("Semispace 0 Space", copySpace0, true);
- ss1Driver = newLinearSpaceDriver("Semispace 1 Space", copySpace1, false);
- immortalDriver = new ImmortalSpaceDriver(
- GCspy.server, "Immortal Space", immortalSpace,
- Options.gcspyTileSize.getValue(), false);
- losNurseryDriver = newTreadmillDriver("LOS Nursery", loSpace);
- losDriver = newTreadmillDriver("LOS", loSpace);
-
- if (DEBUG) Log.write("SemiServerInterpreter initialised\n");
-
- // Register drivers to allow immortal space to notify direct references
- immortalDriver.registerDriversForReferenceNotification(
- new AbstractDriver[] {ss0Driver, ss1Driver, immortalDriver,
- losNurseryDriver, losDriver,
- plosNurseryDriver, plosDriver});
- if (DEBUG) Log.writeln("SSGCspy: registered drivers");
-
- gcspyEvent_ = BEFORE_COLLECTION;
-
- // Start the server
- GCspy.server.startServer(wait);
- }
-
- /**
- * Create a new LinearSpaceDriver
- * TODO is this the best name or should we call it LargeObjectSpaceDriver?
- * @param name Name of the space
- * @param space The space
- * @return A new GCspy driver for this space
- */
- @Interruptible
- private LinearSpaceDriver newLinearSpaceDriver(String name, CopySpace space, boolean mainSpace) {
- // TODO What if tileSize is too small (i.e. too many tiles for GCspy buffer)
- // TODO stop the GCspy spaces in the visualiser from fluctuating in size
- // so much as we resize them.
- return new LinearSpaceDriver(GCspy.server, name, space,
- Options.gcspyTileSize.getValue(), mainSpace);
- }
-
- /**
- * Create a new TreadmillDriver
- * TODO is this the best name or should we call it LargeObjectSpaceDriver?
- * @param name Name of the space
- * @param space The space
- * @return A new GCspy driver for this space
- */
- @Interruptible
- private TreadmillDriver newTreadmillDriver(String name, LargeObjectSpace space) {
- return new TreadmillDriver(GCspy.server, name, space,
- Options.gcspyTileSize.getValue(), MAX_NON_LOS_COPY_BYTES, false);
- }
-
- /****************************************************************************
- *
- * Collection
- */
-
- /**
- * Perform a (global) collection phase.
- *
- * @param phaseId Collection phase
- */
- @Inline
- public void collectionPhase(short phaseId) {
- if (DEBUG) { Log.write("--Phase Plan."); Log.writeln(Phase.getName(phaseId)); }
-
- if (phaseId == SSGCspy.PREPARE) {
- super.collectionPhase(phaseId);
- gcspySpace.prepare();
- return;
- }
-
- if (phaseId == SSGCspy.RELEASE) {
- super.collectionPhase(phaseId);
- gcspySpace.release();
- //if (primary)
- gcspyGatherData(SSGCspy.AFTER_COLLECTION);
- return;
- }
-
- super.collectionPhase(phaseId);
- }
-
- /**
- * Gather data for GCspy for the semispaces, the immortal space and the large
- * object space.
- * <p>
- * This method sweeps the semispace under consideration to gather data.
- * Alternatively and more efficiently, 'used space' can obviously be
- * discovered in constant time simply by comparing the start and the end
- * addresses of the semispace. However, per-object information can only be
- * gathered by sweeping through the space and we do this here for tutorial
- * purposes.
- *
- * @param event
- * The event, either BEFORE_COLLECTION, SEMISPACE_COPIED or
- * AFTER_COLLECTION
- */
- private void gcspyGatherData(int event) {
- if(DEBUG) {
- Log.writeln("SSGCspy.gcspyGatherData, event=", event);
- Log.writeln("SSGCspy.gcspyGatherData, port=", GCspy.getGCspyPort());
- }
-
- // If port = 0 there can be no GCspy client connected
- if (GCspy.getGCspyPort() == 0)
- return;
-
- // This is a safepoint for the server, i.e. it is a point at which
- // the server can pause.
- // The Mutator is called after the Collector so the Mutator must set the safepoint
- if(DEBUG) Log.writeln("SSGCspy safepoint");
- GCspy.server.serverSafepoint(event);
- }
-
- /****************************************************************************
- *
- * Accounting
- */
-
- /**
- * Return the number of pages reserved for use given the pending
- * allocation. This is <i>exclusive of</i> space reserved for
- * copying.
- *
- * @return The number of pages reserved given the pending
- * allocation, excluding space reserved for copying.
- */
- public final int getPagesUsed() {
- return super.getPagesUsed() + gcspySpace.reservedPages();
- }
-
-
- /**
- * Report information on the semispaces
- */
- static void reportSpaces() {
- Log.write("\n Low semispace: ");
- Log.write(SSGCspy.copySpace0.getStart());
- Log.write(" - ");
- Log.write(SSGCspy.copySpace0.getStart()
- .plus(SSGCspy.copySpace0.getExtent()));
- Log.write("\n High semispace: ");
- Log.write(SSGCspy.copySpace1.getStart());
- Log.write(" - ");
- Log.write(SSGCspy.copySpace1.getStart()
- .plus(SSGCspy.copySpace1.getExtent()));
- Log.flush();
- }
-
- /**
- * Register specialized methods.
- */
- @Interruptible
- protected void registerSpecializedMethods() {
- super.registerSpecializedMethods();
- TransitiveClosure.registerSpecializedScan(SCAN_SS, SSGCspyTraceLocal.class);
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/plan/semispace/gcspy/SSGCspyCollector.java b/vmkit/mmtk/java/src/org/mmtk/plan/semispace/gcspy/SSGCspyCollector.java
deleted file mode 100644
index 636b15b..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/plan/semispace/gcspy/SSGCspyCollector.java
+++ /dev/null
@@ -1,265 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.plan.semispace.gcspy;
-
-import org.mmtk.plan.Phase;
-import org.mmtk.plan.semispace.SS;
-import org.mmtk.plan.semispace.SSCollector;
-import org.mmtk.policy.CopySpace;
-import org.mmtk.utility.Log;
-import org.mmtk.utility.gcspy.GCspy;
-import org.mmtk.utility.gcspy.drivers.LinearSpaceDriver;
-import org.mmtk.vm.VM;
-
-import org.vmmagic.unboxed.*;
-import org.vmmagic.pragma.*;
-
-/**
- * This class implements <i>per-collector thread</i> behavior and state for the
- * <i>SSGCspy</i> plan.<p>
- *
- * See {@link SSGCspy} for an overview of the GC-spy mechanisms.<p>
- *
- * @see SSCollector
- * @see SSGCspy
- * @see SSGCspyMutator
- * @see org.mmtk.plan.StopTheWorldCollector
- * @see org.mmtk.plan.CollectorContext
- * @see org.mmtk.plan.SimplePhase
- */
-@Uninterruptible public class SSGCspyCollector extends SSCollector {
-
- /****************************************************************************
- *
- * Initialization
- */
-
- /*****************************************************************************
- * Instance fields
- */
-
- private static final boolean DEBUG = false;
-
- /**
- * Constructor
- */
- public SSGCspyCollector() {
- super(new SSGCspyTraceLocal(global().ssTrace));
- }
-
-
- /****************************************************************************
- *
- * Data gathering
- */
-
- /**
- * Perform a (local) collection phase.
- * Before a collection, we need to discover
- * <ul>
- * <li>the tospace objects copied by the collector in the last GC cycle
- * <li>the semispace objects allocated since by the mutator.
- * <li>all immortal objects allocated by the mutator
- * <li>all large objects allocated by the mutator
- * </ul>
- * After the semispace has been copied, we need to discover
- * <ul>
- * <li>the tospace objects copied by the collector
- * <li>all immortal objects allocated by the mutator
- * <li>all large objects allocated by the mutator
- * </ul>
- */
- @Inline
- public final void collectionPhase(short phaseId, boolean primary) {
- if (DEBUG) { Log.write("--Phase Collector."); Log.writeln(Phase.getName(phaseId)); }
-
- //TODO do we need to worry any longer about primary??
- if (phaseId == SS.PREPARE) {
- //if (primary)
- gcspyGatherData(SSGCspy.BEFORE_COLLECTION);
- super.collectionPhase(phaseId, primary);
- return;
- }
-
- if (phaseId == SS.FORWARD_FINALIZABLE) {
- super.collectionPhase(phaseId, primary);
- //if (primary)
- gcspyGatherData(SSGCspy.SEMISPACE_COPIED);
- return;
- }
-
- if (phaseId == SS.RELEASE) {
- //if (primary)
- //gcspyGatherData(SSGCspy.SEMISPACE_COPIED);
- super.collectionPhase(phaseId, primary);
- //if (primary)
- gcspyGatherData(SSGCspy.AFTER_COLLECTION);
- return;
- }
-
- super.collectionPhase(phaseId, primary);
- }
-
- /**
- * Gather data for GCspy for the semispaces only.
- * <p>
- * This method sweeps the semispace under consideration to gather data.
- * Alternatively and more efficiently, 'used space' can obviously be
- * discovered in constant time simply by comparing the start and the end
- * addresses of the semispace. However, per-object information can only be
- * gathered by sweeping through the space and we do this here for tutorial
- * purposes.
- *
- * @param event
- * The event, either BEFORE_COLLECTION, SEMISPACE_COPIED or
- * AFTER_COLLECTION
- */
- private void gcspyGatherData(int event) {
- if(DEBUG) {
- Log.writeln("SSGCspyCollector.gcspyGatherData, event=", event);
- Log.writeln("SSGCspyCollector.gcspyGatherData, port=", GCspy.getGCspyPort());
- }
-
- // If port = 0 there can be no GCspy client connected
- if (GCspy.getGCspyPort() == 0)
- return;
-
- // If the server is connected to a client that is interested in this
- // event, then we gather data. But first we start a timer to
- // compensate for the time spent gathering data here.
- if (GCspy.server.isConnected(event)) {
-
- if (DEBUG) {
- if (SSGCspy.hi)
- Log.write("\nCollector Examining Lowspace (event ", event);
- else
- Log.write("\nCollector Examining Highspace (event ", event);
- Log.write(")");
- SSGCspy.reportSpaces(); Log.writeln();
- }
-
- if (event == SSGCspy.BEFORE_COLLECTION) {
- if (DEBUG) debugSpaces(SSGCspy.fromSpace());
-
- // Just send the old values again
- if (DEBUG) {
- Log.write("SSGCspyCollector.gcspyGatherData transmit driver, ");
- Log.writeln(SSGCspy.fromSpace().getName());
- }
-
- fromSpaceDriver().transmit(event);
- // Mutator.gcspyGatherData follows so leave safepoint to there.
- } else if (event == SSGCspy.SEMISPACE_COPIED) {
- if (DEBUG) debugSpaces(SSGCspy.toSpace());
-
- // We need to reset, scan and send values for tospace
- // We'll leave resetting fromspace to AFTER_COLLECTION
- if (DEBUG) {
- Log.write("SSGCspyCollector.gcspyGatherData reset, gather and transmit driver ");
- Log.writeln(SSGCspy.toSpace().getName());
- }
-
- GCspy.server.startCompensationTimer();
- toSpaceDriver().resetData();
- ss.gcspyGatherData(toSpaceDriver(), SSGCspy.toSpace());
- GCspy.server.stopCompensationTimer();
- toSpaceDriver().transmit(event);
-
- // We'll leave the safepoint to RELEASE
- } else if (event == SSGCspy.AFTER_COLLECTION) {
- if (DEBUG) {
- Log.write("SSGCspyCollector.gcspyGatherData transmit toSpaceDriver, ");
- Log.writeln(SSGCspy.toSpace().getName());
- Log.write("SSGCspyCollector.gcspyGatherData reset fromSpaceDriver, ");
- Log.writeln(SSGCspy.fromSpace().getName());
- }
-
- toSpaceDriver().transmit(event);
-
- // Here we reset fromspace data
- fromSpaceDriver().resetData();
- Address start = SSGCspy.fromSpace().getStart();
- fromSpaceDriver().setRange(start, start);
- fromSpaceDriver().transmit(event);
- }
-
- }
- // else Log.write("not transmitting...");
- }
-
- /**
- * Print some debugging info
- * @param scannedSpace
- */
- private void debugSpaces(CopySpace scannedSpace) {
- Log.write("SSGCspyCollector.gcspyGatherData: gather data for active semispace ");
- Log.write(scannedSpace.getStart()); Log.write("-",ss.getCursor()); Log.flush();
- Log.write(". The space is: "); Log.writeln(ss.getSpace().getName());
- Log.write("scannedSpace is "); Log.writeln(scannedSpace.getName());
- Log.write("The range is "); Log.write(ss.getSpace().getStart());
- Log.write(" to "); Log.writeln(ss.getCursor());
- SSGCspy.reportSpaces();
- }
-
- /**
- * Reset all root streams.<p>
- */
- void resetRootStreams() {
- SSGCspy.ss0Driver.resetRootsStream();
- SSGCspy.ss1Driver.resetRootsStream();
- SSGCspy.immortalDriver.resetRootsStream();
- SSGCspy.losNurseryDriver.resetRootsStream();
- SSGCspy.losDriver.resetRootsStream();
- SSGCspy.plosNurseryDriver.resetRootsStream();
- SSGCspy.plosDriver.resetRootsStream();
- ss.getCursor();
- }
-
- /**
- * Pass a root to all drivers.<p>
- * @param addr The Address of the object to be checked
- */
- protected void checkAllDriversForRootAddress(Address addr) {
- if(addr.isZero())
- return;
-
- SSGCspy.ss0Driver.handleRoot(addr);
- SSGCspy.ss1Driver.handleRoot(addr);
- SSGCspy.immortalDriver.handleRoot(addr);
- SSGCspy.losNurseryDriver.handleRoot(addr);
- SSGCspy.losDriver.handleRoot(addr);
- SSGCspy.plosNurseryDriver.handleRoot(addr);
- SSGCspy.plosDriver.handleRoot(addr);
- }
-
- /****************************************************************************
- *
- * Miscellaneous
- */
-
- /** @return The active global plan as an <code>SSGCspy</code> instance. */
- @Inline
- private static SSGCspy global() {
- return (SSGCspy) VM.activePlan.global();
- }
-
- /** @return the driver for toSpace */
- private LinearSpaceDriver toSpaceDriver() {
- return SSGCspy.hi ? SSGCspy.ss1Driver : SSGCspy.ss0Driver;
- }
-
- /** @return the driver for fromSpace */
- private LinearSpaceDriver fromSpaceDriver() {
- return SSGCspy.hi ? SSGCspy.ss0Driver : SSGCspy.ss1Driver;
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/plan/semispace/gcspy/SSGCspyConstraints.java b/vmkit/mmtk/java/src/org/mmtk/plan/semispace/gcspy/SSGCspyConstraints.java
deleted file mode 100644
index b06a390..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/plan/semispace/gcspy/SSGCspyConstraints.java
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.plan.semispace.gcspy;
-
-import org.mmtk.plan.semispace.SSConstraints;
-import org.vmmagic.pragma.*;
-
-/**
- * Semi space GCspy constants.
- */
-@Uninterruptible
-public class SSGCspyConstraints extends SSConstraints {
- @Override
- public boolean needsLinearScan() { return true; }
- @Override
- public boolean withGCspy() { return true; }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/plan/semispace/gcspy/SSGCspyMutator.java b/vmkit/mmtk/java/src/org/mmtk/plan/semispace/gcspy/SSGCspyMutator.java
deleted file mode 100644
index 0de4091..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/plan/semispace/gcspy/SSGCspyMutator.java
+++ /dev/null
@@ -1,348 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.plan.semispace.gcspy;
-
-import org.mmtk.plan.Phase;
-import org.mmtk.plan.semispace.SSMutator;
-import org.mmtk.policy.CopySpace;
-import org.mmtk.policy.Space;
-import org.mmtk.policy.ImmortalLocal;
-import org.mmtk.utility.Log;
-import org.mmtk.utility.alloc.BumpPointer;
-import org.mmtk.utility.alloc.Allocator;
-import org.mmtk.utility.gcspy.GCspy;
-import org.mmtk.utility.gcspy.drivers.LinearSpaceDriver;
-
-import org.vmmagic.pragma.*;
-import org.vmmagic.unboxed.*;
-
-/**
- * This class implements <i>per-mutator thread</i> behavior and state for the
- * <i>SSGCspy</i> plan.
- *
- * See {@link SSGCspy} for an overview of the GC-spy mechanisms.
- * <p>
- *
- * @see SSMutator
- * @see SSGCspy
- * @see SSGCspyCollector
- * @see org.mmtk.plan.StopTheWorldMutator
- * @see org.mmtk.plan.MutatorContext
- */
-@Uninterruptible public class SSGCspyMutator extends SSMutator {
-
- /*****************************************************************************
- * Instance fields
- */
-
- private static final boolean DEBUG = false;
-
- private static final boolean LOS_TOSPACE = true; // gather from tospace
- private static final boolean LOS_FROMSPACE = false; // gather from fromspace
-
- /** Per-mutator allocator into GCspy's space */
- private BumpPointer gcspy = new ImmortalLocal(SSGCspy.gcspySpace);
-
-
-
- /*****************************************************************************
- *
- * Mutator-time allocation
- */
-
- /**
- * Allocate space (for an object)
- *
- * @param bytes The size of the space to be allocated (in bytes)
- * @param align The requested alignment.
- * @param offset The alignment offset.
- * @param allocator The allocator number to be used for this allocation
- * @param site Allocation site
- * @return The address of the first byte of the allocated region
- */
- @Inline
- public Address alloc(int bytes, int align, int offset, int allocator, int site) {
- if (allocator == SSGCspy.ALLOC_GCSPY)
- return gcspy.alloc(bytes, align, offset);
- else
- return super.alloc(bytes, align, offset, allocator, site);
- }
-
- /**
- * Perform post-allocation actions. For many allocators none are required.
- *
- * @param object The newly allocated object
- * @param typeRef The type reference for the instance being created
- * @param bytes The size of the space to be allocated (in bytes)
- * @param allocator The allocator number to be used for this allocation
- */
- @Inline
- public void postAlloc(ObjectReference object, ObjectReference typeRef,
- int bytes, int allocator) {
- if (allocator == SSGCspy.ALLOC_GCSPY)
- SSGCspy.gcspySpace.initializeHeader(object);
- else
- super.postAlloc(object, typeRef, bytes, allocator);
- }
-
- /**
- * Return the allocator instance associated with a space
- * <code>space</code>, for this plan instance.
- *
- * @param space The space for which the allocator instance is desired.
- * @return The allocator instance associated with this plan instance
- * which is allocating into <code>space</code>, or <code>null</code>
- * if no appropriate allocator can be established.
- */
- public Allocator getAllocatorFromSpace(Space space) {
- if (space == SSGCspy.gcspySpace) return gcspy;
- return super.getAllocatorFromSpace(space);
- }
-
- /*****************************************************************************
- *
- * Collection
- */
-
- /**
- * Perform a per-mutator collection phase.
- * Before a collection, we need to discover
- * <ul>
- * <li>the tospace objects copied by the collector in the last GC cycle
- * <li>the ojects allocated since by the mutator.
- * <li>all immortal objects allocated by the mutator
- * <li>all large objects allocated by the mutator
- * </ul>
- * After the semispace has been copied, we need to discover
- * <ul>
- * <li>the tospace objects copied by the collector
- * <li>all immortal objects allocated by the mutator
- * <li>all large objects allocated by the mutator
- * </ul>
- */
- @Inline
- public final void collectionPhase(short phaseId, boolean primary) {
- if (DEBUG) { Log.write("--Phase Mutator."); Log.writeln(Phase.getName(phaseId)); }
-
- // TODO do we need to worry any longer about primary??
- if (phaseId == SSGCspy.PREPARE) {
- //if (primary)
- gcspyGatherData(SSGCspy.BEFORE_COLLECTION);
- super.collectionPhase(phaseId, primary);
- return;
- }
-
- if (phaseId == SSGCspy.RELEASE) {
- //if (primary)
- gcspyGatherData(SSGCspy.SEMISPACE_COPIED);
- super.collectionPhase(phaseId, primary);
- //if (primary)
- gcspyGatherData(SSGCspy.AFTER_COLLECTION);
- return;
- }
-
- super.collectionPhase(phaseId, primary);
- }
-
- /**
- * Gather data for GCspy for the semispaces, the immortal space and the large
- * object space.
- * <p>
- * This method sweeps the semispace under consideration to gather data.
- * Alternatively and more efficiently, 'used space' can obviously be
- * discovered in constant time simply by comparing the start and the end
- * addresses of the semispace. However, per-object information can only be
- * gathered by sweeping through the space and we do this here for tutorial
- * purposes.
- *
- * @param event
- * The event, either BEFORE_COLLECTION, SEMISPACE_COPIED or
- * AFTER_COLLECTION
- */
- private void gcspyGatherData(int event) {
- if(DEBUG) {
- Log.writeln("SSGCspyMutator.gcspyGatherData, event=", event);
- Log.writeln("SSGCspyMutator.gcspyGatherData, port=", GCspy.getGCspyPort());
- }
-
- // If port = 0 there can be no GCspy client connected
- if (GCspy.getGCspyPort() == 0)
- return;
-
- // If the server is connected to a client that is interested in this
- // event, then we gather data. But first we start a timer to
- // compensate for the time spent gathering data here.
- if (GCspy.server.isConnected(event)) {
-
- if (DEBUG) {
- if (SSGCspy.hi)
- Log.write("\nMutator Examining Lowspace (event ", event);
- else
- Log.write("\nMutator Examining Highspace (event ", event);
- Log.write(")");
- SSGCspy.reportSpaces(); Log.writeln();
- }
-
- if (event == SSGCspy.BEFORE_COLLECTION) {
- // Before the flip
- // Mutator has not rebound toSpace yet
- GCspy.server.startCompensationTimer();
-
- // -- Handle the semispaces
- // Here I need to scan newly allocated objects
- if (DEBUG) {
- //debugSpaces(SSGCspy.fromSpace());
- debugSpaces(SSGCspy.toSpace());
- Log.write("SSGCspyMutator.gcspyGatherData reset, gather and transmit driver ");
- //Log.writeln(SSGCspy.fromSpace().getName());
- Log.writeln(SSGCspy.toSpace().getName());
- }
- //ss.gcspyGatherData(fromSpaceDriver(), SSGCspy.fromSpace());
- ss.gcspyGatherData(toSpaceDriver(), SSGCspy.toSpace());
-
- // -- Handle the immortal space --
- gatherImmortal(event);
-
- // -- Handle the LOSes
-
- // reset, collect and scan los data for the nursery and tospace
- SSGCspy.losNurseryDriver.resetData();
- los.gcspyGatherData(event, SSGCspy.losNurseryDriver);
- SSGCspy.losDriver.resetData();
- los.gcspyGatherData(event, SSGCspy.losDriver, LOS_TOSPACE);
-
- // transmit the data
- GCspy.server.stopCompensationTimer();
- //fromSpaceDriver().transmit(event);
- toSpaceDriver().transmit(event);
- SSGCspy.immortalDriver.transmit(event);
- SSGCspy.losNurseryDriver.transmit(event);
- SSGCspy.losDriver.transmit(event);
- SSGCspy.plosNurseryDriver.transmit(event);
- SSGCspy.plosDriver.transmit(event);
-
- // As this follows Collector.gcspyGatherData, I'll safepoint here
- // This is a safepoint for the server, i.e. it is a point at which
- // the server can pause.
- GCspy.server.serverSafepoint(event);
- } else if (event == SSGCspy.SEMISPACE_COPIED) {
- // We have flipped
- // toSpace still has not been rebound
-
- // -- Handle the semispaces
- if (DEBUG) {
- //debugSpaces(SSGCspy.toSpace());
- debugSpaces(SSGCspy.fromSpace());
- Log.writeln("SSGCspyMutator.gcspyGatherData: do nothing");
- }
-
- // -- Handle the immortal space --
- GCspy.server.startCompensationTimer();
- gatherImmortal(event);
-
- // reset, scan and send the los for the nursery and tospace
- // and fromspace as well if full heap collection
- SSGCspy.losNurseryDriver.resetData();
- los.gcspyGatherData(event, SSGCspy.losNurseryDriver);
- SSGCspy.losDriver.resetData();
- los.gcspyGatherData(event, SSGCspy.losDriver, LOS_FROMSPACE);
- los.gcspyGatherData(event, SSGCspy.losDriver, LOS_TOSPACE);
-
- // transmit
- GCspy.server.stopCompensationTimer();
- SSGCspy.immortalDriver.transmit(event);
- SSGCspy.losNurseryDriver.transmit(event);
- SSGCspy.losDriver.transmit(event);
- SSGCspy.plosNurseryDriver.transmit(event);
- SSGCspy.plosDriver.transmit(event);
-
- // As this follows Collector.gcspyGatherData, I'll safepoint here
- // This is a safepoint for the server, i.e. it is a point at which
- // the server can pause.
- GCspy.server.serverSafepoint(event);
- } else if (event == SSGCspy.AFTER_COLLECTION) {
- // We have flipped
- // And toSpace has been rebound
-
- GCspy.server.startCompensationTimer();
-
- // -- Handle the semispaces
- if (DEBUG) debugSpaces(SSGCspy.toSpace());
-
- // -- Handle the immortal space --
- gatherImmortal(event);
-
- // -- Handle the LOSes
-
- // reset, scan and send the los
- SSGCspy.losNurseryDriver.resetData();
- SSGCspy.losDriver.resetData();
- // no need to scan empty nursery
- los.gcspyGatherData(event, SSGCspy.losDriver, LOS_TOSPACE);
-
- //transmit
- GCspy.server.stopCompensationTimer();
- SSGCspy.immortalDriver.transmit(event);
- SSGCspy.losNurseryDriver.transmit(event);
- SSGCspy.losDriver.transmit(event);
- SSGCspy.plosNurseryDriver.transmit(event);
- SSGCspy.plosDriver.transmit(event);
-
- // Reset fromspace
- if (DEBUG) {
- Log.write("SSGCspyMutator.gcspyGatherData: reset and zero range for driver ");
- Log.write(SSGCspy.toSpace().getName());
- }
- }
-
- }
- // else Log.write("not transmitting...");
- }
-
- /**
- * Gather data for the immortal space
- * @param event
- * The event, either BEFORE_COLLECTION, SEMISPACE_COPIED or
- * AFTER_COLLECTION
- */
- private void gatherImmortal(int event) {
- // We want to do this at every GCspy event
- if (DEBUG) {
- Log.write("SSGCspyMutator.gcspyGatherData: gather data for immortal space ");
- Log.write(SSGCspy.immortalSpace.getStart()); Log.writeln("-",immortal.getCursor());
- }
- SSGCspy.immortalDriver.resetData();
- immortal.gcspyGatherData(SSGCspy.immortalDriver);
- if (DEBUG) Log.writeln("Finished immortal space.");
- }
-
- /**
- * Debugging info for the semispaces
- * @param scannedSpace the space to output debug for.
- */
- private void debugSpaces(CopySpace scannedSpace) {
- Log.write("SSGCspyMutator.gcspyGatherData: gather data for active semispace ");
- Log.write(scannedSpace.getStart()); Log.write("-",ss.getCursor()); Log.flush();
- Log.write(". The space is: "); Log.writeln(ss.getSpace().getName());
- Log.write("scannedSpace is "); Log.writeln(scannedSpace.getName());
- Log.write("The range is "); Log.write(ss.getSpace().getStart());
- Log.write(" to "); Log.writeln(ss.getCursor());
- SSGCspy.reportSpaces();
- }
-
- /** @return the driver for toSpace */
- private LinearSpaceDriver toSpaceDriver() {
- return SSGCspy.hi ? SSGCspy.ss1Driver : SSGCspy.ss0Driver;
- }
-
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/plan/semispace/gcspy/SSGCspyTraceLocal.java b/vmkit/mmtk/java/src/org/mmtk/plan/semispace/gcspy/SSGCspyTraceLocal.java
deleted file mode 100644
index 6b78cdb..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/plan/semispace/gcspy/SSGCspyTraceLocal.java
+++ /dev/null
@@ -1,70 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.plan.semispace.gcspy;
-
-import org.mmtk.plan.Trace;
-import org.mmtk.plan.semispace.SSTraceLocal;
-import org.mmtk.policy.Space;
-
-import org.vmmagic.pragma.*;
-import org.vmmagic.unboxed.*;
-
-/**
- * This class implments the core functionality for a transitive
- * closure over the heap graph.
- */
-@Uninterruptible
-public final class SSGCspyTraceLocal extends SSTraceLocal {
- /**
- * Constructor
- */
- public SSGCspyTraceLocal(Trace trace) {
- super(trace);
- }
-
- /****************************************************************************
- *
- * Externally visible Object processing and tracing
- */
-
- /**
- * This method is the core method during the trace of the object graph.
- * The role of this method is to:
- *
- * 1. Ensure the traced object is not collected.
- * 2. If this is the first visit to the object enqueue it to be scanned.
- * 3. Return the forwarded reference to the object.
- *
- * @param object The object to be traced.
- * @return The new reference to the same object instance.
- */
- @Inline
- public ObjectReference traceObject(ObjectReference object) {
- if (object.isNull()) return object;
- if (Space.isInSpace(SSGCspy.GCSPY, object))
- return SSGCspy.gcspySpace.traceObject(this, object);
- return super.traceObject(object);
- }
-
- /**
- * Will this object move from this point on, during the current trace ?
- *
- * @param object The object to query.
- * @return True if the object will not move.
- */
- public boolean willNotMoveInCurrentCollection(ObjectReference object) {
- if (Space.isInSpace(SSGCspy.GCSPY, object))
- return true;
- return super.willNotMoveInCurrentCollection(object);
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/plan/semispace/gctrace/GCTrace.java b/vmkit/mmtk/java/src/org/mmtk/plan/semispace/gctrace/GCTrace.java
deleted file mode 100644
index 8be97fb..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/plan/semispace/gctrace/GCTrace.java
+++ /dev/null
@@ -1,208 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.plan.semispace.gctrace;
-
-import org.mmtk.plan.semispace.*;
-import org.mmtk.policy.RawPageSpace;
-import org.mmtk.utility.deque.SortTODSharedDeque;
-import org.mmtk.utility.heap.VMRequest;
-import org.mmtk.utility.TraceGenerator;
-import org.mmtk.utility.options.Options;
-
-import org.mmtk.vm.VM;
-
-import org.vmmagic.pragma.*;
-
-/**
- * This plan has been modified slightly to perform the processing necessary
- * for GC trace generation. To maximize performance, it attempts to remain
- * as faithful as possible to semiSpace/Plan.java.
- *
- * The generated trace format is as follows:
- * B 345678 12
- * (Object 345678 was created in the boot image with a size of 12 bytes)
- * U 59843 234 47298
- * (Update object 59843 at the slot at offset 234 to refer to 47298)
- * S 1233 12345
- * (Update static slot 1233 to refer to 12345)
- * T 4567 78924
- * (The TIB of 4567 is set to refer to 78924)
- * D 342789
- * (Object 342789 became unreachable)
- * A 6860 24 346648 3
- * (Object 6860 was allocated, requiring 24 bytes, with fp 346648 on
- * thread 3; this allocation has perfect knowledge)
- * a 6884 24 346640 5
- * (Object 6864 was allocated, requiring 24 bytes, with fp 346640 on
- * thread 5; this allocation DOES NOT have perfect knowledge)
- * I 6860 24 346648 3
- * (Object 6860 was allocated into immortal space, requiring 24 bytes,
- * with fp 346648 on thread 3; this allocation has perfect knowledge)
- * i 6884 24 346640 5
- * (Object 6864 was allocated into immortal space, requiring 24 bytes,
- * with fp 346640 on thread 5; this allocation DOES NOT have perfect
- * knowledge)
- * 48954->[345]LObject;:blah()V:23 Ljava/lang/Foo;
- * (Citation for: a) where the was allocated, fp of 48954,
- * at the method with ID 345 -- or void Object.blah() -- and bytecode
- * with offset 23; b) the object allocated is of type java.lang.Foo)
- * D 342789 361460
- * (Object 342789 became unreachable after 361460 was allocated)
- *
- * This class implements a simple semi-space collector. See the Jones
- * & Lins GC book, section 2.2 for an overview of the basic
- * algorithm. This implementation also includes a large object space
- * (LOS), and an uncollected "immortal" space.<p>
- *
- * All plans make a clear distinction between <i>global</i> and
- * <i>thread-local</i> activities. Global activities must be
- * synchronized, whereas no synchronization is required for
- * thread-local activities. Instances of Plan map 1:1 to "kernel
- * threads" (aka CPUs). Thus instance
- * methods allow fast, unsychronized access to Plan utilities such as
- * allocation and collection. Each instance rests on static resources
- * (such as memory and virtual memory resources) which are "global"
- * and therefore "static" members of Plan. This mapping of threads to
- * instances is crucial to understanding the correctness and
- * performance proprties of this plan.
- */
-@Uninterruptible public class GCTrace extends SS {
-
- /****************************************************************************
- *
- * Class variables
- */
-
- /* Spaces */
- public static final RawPageSpace traceSpace = new RawPageSpace("trace", DEFAULT_POLL_FREQUENCY, VMRequest.create());
- public static final int TRACE = traceSpace.getDescriptor();
-
- /* GC state */
- public static boolean lastGCWasTracing = false; // True when previous GC was for tracing
- public static boolean traceInducedGC = false; // True if trace triggered GC
- public static boolean deathScan = false;
- public static boolean finalDead = false;
-
- /****************************************************************************
- *
- * Initialization
- */
-
- /**
- * Constructor
- */
- public GCTrace() {
- SortTODSharedDeque workList = new SortTODSharedDeque("workList",traceSpace, 1);
- SortTODSharedDeque traceBuf = new SortTODSharedDeque("traceBuf",traceSpace, 1);
- workList.prepareNonBlocking();
- traceBuf.prepareNonBlocking();
- TraceGenerator.init(workList, traceBuf);
- }
-
- /**
- * The postBoot method is called by the runtime immediately after
- * command-line arguments are available.
- */
- @Interruptible
- public void postBoot() {
- Options.noFinalizer.setValue(true);
- }
-
- /**
- * The planExit method is called at RVM termination to allow the
- * trace process to finish.
- */
- @Interruptible
- public final void notifyExit(int value) {
- super.notifyExit(value);
- finalDead = true;
- traceInducedGC = false;
- deathScan = true;
- TraceGenerator.notifyExit(value);
- }
-
- /**
- * This method controls the triggering of a GC. It is called periodically
- * during allocation. Returns true to trigger a collection.
- *
- * @param spaceFull Space request failed, must recover pages within 'space'.
- * @return True if a collection is requested by the plan.
- */
- public final boolean collectionRequired(boolean spaceFull) {
- if (super.collectionRequired(spaceFull)) {
- traceInducedGC = false;
- return true;
- }
- return false;
- }
-
- /****************************************************************************
- *
- * Collection
- */
-
- public void collectionPhase(short phaseId) {
- if (phaseId == PREPARE) {
- lastGCWasTracing = traceInducedGC;
- }
- if (phaseId == RELEASE) {
- if (traceInducedGC) {
- /* Clean up following a trace-induced scan */
- deathScan = false;
- } else {
- /* Finish the collection by calculating the unreachable times */
- deathScan = true;
- TraceGenerator.postCollection();
- deathScan = false;
- /* Perform the semispace collections. */
- super.collectionPhase(phaseId);
- }
- } else if (!traceInducedGC ||
- (phaseId == INITIATE) ||
- (phaseId == PREPARE_STACKS) ||
- (phaseId == ROOTS) ||
- (phaseId == STACK_ROOTS) ||
- (phaseId == COMPLETE)) {
- /* Performing normal GC; sponge off of parent's work. */
- super.collectionPhase(phaseId);
- }
- }
-
-
- /****************************************************************************
- *
- * Space management
- */
-
- /**
- * @return Since trace induced collections are not called to free up memory,
- * their failure to return memory isn't cause for concern.
- */
- public boolean isLastGCFull() {
- return !lastGCWasTracing;
- }
-
- /**
- * @return the active PlanLocal as a GCTraceLocal
- */
- public static GCTraceCollector local() {
- return ((GCTraceCollector) VM.activePlan.collector());
- }
-
- /**
- * @return the active Plan as a GCTrace
- */
- public static GCTrace global() {
- return ((GCTrace) VM.activePlan.global());
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/plan/semispace/gctrace/GCTraceCollector.java b/vmkit/mmtk/java/src/org/mmtk/plan/semispace/gctrace/GCTraceCollector.java
deleted file mode 100644
index c1989f4..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/plan/semispace/gctrace/GCTraceCollector.java
+++ /dev/null
@@ -1,108 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.plan.semispace.gctrace;
-
-import org.mmtk.plan.*;
-import org.mmtk.plan.semispace.*;
-import org.mmtk.vm.VM;
-
-import org.vmmagic.pragma.*;
-
-
-/**
- * This class implements <i>per-collector thread</i> behavior and state for the
- * <i>GCTrace</i> plan, which implements a GC tracing algorithm.<p>
- *
- * Specifically, this class defines <i>SS</i> collection behavior
- * (through <code>inducedTrace</code> and the <code>collectionPhase</code>
- * method), and collection-time allocation (copying of objects).<p>
- *
- * See {@link GCTrace} for an overview of the GC trace algorithm.<p>
- *
- * @see SSCollector
- * @see GCTrace
- * @see GCTraceMutator
- * @see org.mmtk.plan.StopTheWorldCollector
- * @see org.mmtk.plan.CollectorContext
- */
-@Uninterruptible public class GCTraceCollector extends SSCollector {
- /****************************************************************************
- * Instance fields
- */
- protected final GCTraceTraceLocal inducedTrace;
-
- /****************************************************************************
- *
- * Initialization
- */
-
- /**
- * Constructor
- */
- public GCTraceCollector() {
- inducedTrace = new GCTraceTraceLocal(global().ssTrace);
- }
-
- /****************************************************************************
- *
- * Collection
- */
-
- /**
- * Perform a per-collector collection phase.
- *
- * @param phaseId The collection phase to perform
- * @param primary perform any single-threaded local activities.
- */
- public void collectionPhase(short phaseId, boolean primary) {
- if (phaseId == GCTrace.CLOSURE) {
- inducedTrace.completeTrace();
- return;
- }
-
- if (phaseId == GCTrace.RELEASE) {
- inducedTrace.release();
- if (!GCTrace.traceInducedGC) {
- super.collectionPhase(phaseId, primary);
- }
- return;
- }
-
- /* fall through case */
- if (!GCTrace.traceInducedGC ||
- ((phaseId != StopTheWorld.SOFT_REFS) &&
- (phaseId != StopTheWorld.WEAK_REFS) &&
- (phaseId != StopTheWorld.PHANTOM_REFS) &&
- (phaseId != StopTheWorld.FINALIZABLE) &&
- (phaseId != SS.PREPARE))) {
- // Delegate up.
- super.collectionPhase(phaseId, primary);
- }
- }
-
- /****************************************************************************
- *
- * Miscellaneous
- */
-
- /** @return The active global plan as a <code>GCTrace</code> instance. */
- @Inline
- private static GCTrace global() {
- return (GCTrace) VM.activePlan.global();
- }
-
- /** @return The current trace instance */
- public TraceLocal getCurrentTrace() {
- return inducedTrace;
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/plan/semispace/gctrace/GCTraceConstraints.java b/vmkit/mmtk/java/src/org/mmtk/plan/semispace/gctrace/GCTraceConstraints.java
deleted file mode 100644
index c54f709..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/plan/semispace/gctrace/GCTraceConstraints.java
+++ /dev/null
@@ -1,28 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.plan.semispace.gctrace;
-
-import org.mmtk.plan.semispace.SSConstraints;
-
-import org.vmmagic.pragma.*;
-
-/**
- * GCTrace constants.
- */
-@Uninterruptible
-public class GCTraceConstraints extends SSConstraints {
- @Override
- public boolean needsObjectReferenceWriteBarrier() { return true; }
- @Override
- public boolean generateGCTrace() { return true; }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/plan/semispace/gctrace/GCTraceMutator.java b/vmkit/mmtk/java/src/org/mmtk/plan/semispace/gctrace/GCTraceMutator.java
deleted file mode 100644
index 1583eb0..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/plan/semispace/gctrace/GCTraceMutator.java
+++ /dev/null
@@ -1,180 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.plan.semispace.gctrace;
-
-import org.mmtk.plan.semispace.SSMutator;
-import org.mmtk.plan.*;
-import org.mmtk.utility.TraceGenerator;
-import org.mmtk.vm.VM;
-
-import org.vmmagic.unboxed.*;
-import org.vmmagic.pragma.*;
-
-/**
- * This class implements <i>per-mutator thread</i> behavior and state for the
- * <i>GCTrace</i> plan, which implements a GC tracing algorithm.<p>
- *
- * Specifically, this class defines <i>SS</i> mutator-time allocation, write
- * barriers, and per-mutator collection semantics.<p>
- *
- * See {@link GCTrace} for an overview of the GC trace algorithm.<p>
- *
- * @see SSMutator
- * @see GCTrace
- * @see GCTraceCollector
- * @see org.mmtk.plan.StopTheWorldMutator
- * @see org.mmtk.plan.MutatorContext
- */
-@Uninterruptible public class GCTraceMutator extends SSMutator {
-
- /****************************************************************************
- *
- * Mutator-time allocation
- */
-
- /**
- * Perform post-allocation actions. For many allocators none are
- * required.
- *
- * @param object The newly allocated object
- * @param typeRef the type reference for the instance being created
- * @param bytes The size of the space to be allocated (in bytes)
- * @param allocator The allocator number to be used for this allocation
- */
- @Inline
- public final void postAlloc(ObjectReference object, ObjectReference typeRef,
- int bytes, int allocator) {
- /* Make the trace generator aware of the new object. */
- TraceGenerator.addTraceObject(object, allocator);
-
- super.postAlloc(object, typeRef, bytes, allocator);
-
- /* Now have the trace process aware of the new allocation. */
- GCTrace.traceInducedGC = TraceGenerator.MERLIN_ANALYSIS;
- TraceGenerator.traceAlloc(allocator == GCTrace.ALLOC_IMMORTAL, object, typeRef, bytes);
- GCTrace.traceInducedGC = false;
- }
-
-
- /****************************************************************************
- *
- * Write barrier.
- */
-
- /**
- * A new reference is about to be created. Take appropriate write
- * barrier actions.<p>
- *
- * In this case, we remember the address of the source of the
- * pointer if the new reference points into the nursery from
- * non-nursery space.
- *
- * @param src The object into which the new reference will be stored
- * @param slot The address into which the new reference will be
- * stored.
- * @param tgt The target of the new reference
- * @param metaDataA A value that assists the host VM in creating a store
- * @param metaDataB A value that assists the host VM in creating a store
- * being modified
- * @param mode The mode of the store (eg putfield, putstatic etc)
- */
- @Inline
- public final void objectReferenceWrite(ObjectReference src, Address slot,
- ObjectReference tgt, Word metaDataA,
- Word metaDataB, int mode) {
- TraceGenerator.processPointerUpdate(mode == INSTANCE_FIELD,
- src, slot, tgt);
- VM.barriers.objectReferenceWrite(src, tgt, metaDataA, metaDataB, mode);
- }
-
- /**
- * Attempt to atomically exchange the value in the given slot
- * with the passed replacement value. If a new reference is
- * created, we must then take appropriate write barrier actions.<p>
- *
- * <b>By default do nothing, override if appropriate.</b>
- *
- * @param src The object into which the new reference will be stored
- * @param slot The address into which the new reference will be
- * stored.
- * @param old The old reference to be swapped out
- * @param tgt The target of the new reference
- * @param metaDataA A value that assists the host VM in creating a store
- * @param metaDataB A value that assists the host VM in creating a store
- * @param mode The context in which the store occured
- * @return True if the swap was successful.
- */
- @Inline
- public boolean objectReferenceTryCompareAndSwap(ObjectReference src, Address slot,
- ObjectReference old, ObjectReference tgt, Word metaDataA,
- Word metaDataB, int mode) {
- boolean result = VM.barriers.objectReferenceTryCompareAndSwap(src, old, tgt, metaDataA, metaDataB, mode);
- if (result) {
- TraceGenerator.processPointerUpdate(mode == INSTANCE_FIELD, src, slot, tgt);
- }
- return result;
- }
-
- /**
- * A number of references are about to be copied from object
- * <code>src</code> to object <code>dst</code> (as in an array
- * copy). Thus, <code>dst</code> is the mutated object. Take
- * appropriate write barrier actions.<p>
- *
- * @param src The source of the values to be copied
- * @param srcOffset The offset of the first source address, in
- * bytes, relative to <code>src</code> (in principle, this could be
- * negative).
- * @param dst The mutated object, i.e. the destination of the copy.
- * @param dstOffset The offset of the first destination address, in
- * bytes relative to <code>tgt</code> (in principle, this could be
- * negative).
- * @param bytes The size of the region being copied, in bytes.
- * @return True if the update was performed by the barrier, false if
- * left to the caller (always false in this case).
- */
- public boolean objectReferenceBulkCopy(ObjectReference src, Offset srcOffset,
- ObjectReference dst, Offset dstOffset, int bytes) {
- /* These names seem backwards, but are defined to be compatable with the
- * previous writeBarrier method. */
- Address slot = dst.toAddress().plus(dstOffset);
- Address tgtLoc = src.toAddress().plus(srcOffset);
- for (int i = 0; i < bytes; i += BYTES_IN_ADDRESS) {
- ObjectReference tgt = tgtLoc.loadObjectReference();
- TraceGenerator.processPointerUpdate(false, dst, slot, tgt);
- slot = slot.plus(BYTES_IN_ADDRESS);
- tgtLoc = tgtLoc.plus(BYTES_IN_ADDRESS);
- }
- return false;
- }
-
- /****************************************************************************
- *
- * Collection
- */
-
- /**
- * Perform a per-mutator collection phase.
- *
- * @param phaseId The collection phase to perform
- * @param primary perform any single-threaded local activities.
- */
- public void collectionPhase(short phaseId, boolean primary) {
- if (!GCTrace.traceInducedGC ||
- (phaseId != StopTheWorld.PREPARE) &&
- (phaseId != StopTheWorld.RELEASE)) {
- // Delegate up.
- super.collectionPhase(phaseId, primary);
- }
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/plan/semispace/gctrace/GCTraceTraceLocal.java b/vmkit/mmtk/java/src/org/mmtk/plan/semispace/gctrace/GCTraceTraceLocal.java
deleted file mode 100644
index d6e06a1..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/plan/semispace/gctrace/GCTraceTraceLocal.java
+++ /dev/null
@@ -1,199 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.plan.semispace.gctrace;
-
-import org.mmtk.plan.Trace;
-import org.mmtk.plan.semispace.*;
-import org.mmtk.policy.Space;
-import org.mmtk.utility.TraceGenerator;
-
-import org.vmmagic.unboxed.*;
-import org.vmmagic.pragma.*;
-
-/**
- * This plan has been modified slightly to perform the processing necessary
- * for GC trace generation. To maximize performance, it attempts to remain
- * as faithful as possible to semiSpace/Plan.java.
- *
- * The generated trace format is as follows:
- * B 345678 12
- * (Object 345678 was created in the boot image with a size of 12 bytes)
- * U 59843 234 47298
- * (Update object 59843 at the slot at offset 234 to refer to 47298)
- * S 1233 12345
- * (Update static slot 1233 to refer to 12345)
- * T 4567 78924
- * (The TIB of 4567 is set to refer to 78924)
- * D 342789
- * (Object 342789 became unreachable)
- * A 6860 24 346648 3
- * (Object 6860 was allocated, requiring 24 bytes, with fp 346648 on
- * thread 3; this allocation has perfect knowledge)
- * a 6884 24 346640 5
- * (Object 6864 was allocated, requiring 24 bytes, with fp 346640 on
- * thread 5; this allocation DOES NOT have perfect knowledge)
- * I 6860 24 346648 3
- * (Object 6860 was allocated into immortal space, requiring 24 bytes,
- * with fp 346648 on thread 3; this allocation has perfect knowledge)
- * i 6884 24 346640 5
- * (Object 6864 was allocated into immortal space, requiring 24 bytes,
- * with fp 346640 on thread 5; this allocation DOES NOT have perfect
- * knowledge)
- * 48954->[345]LObject;:blah()V:23 Ljava/lang/Foo;
- * (Citation for: a) where the was allocated, fp of 48954,
- * at the method with ID 345 -- or void Object.blah() -- and bytecode
- * with offset 23; b) the object allocated is of type java.lang.Foo)
- * D 342789 361460
- * (Object 342789 became unreachable after 361460 was allocated)
- *
- * This class implements a simple semi-space collector. See the Jones
- * & Lins GC book, section 2.2 for an overview of the basic
- * algorithm. This implementation also includes a large object space
- * (LOS), and an uncollected "immortal" space.<p>
- *
- * All plans make a clear distinction between <i>global</i> and
- * <i>thread-local</i> activities. Global activities must be
- * synchronized, whereas no synchronization is required for
- * thread-local activities. Instances of Plan map 1:1 to "kernel
- * threads" (aka CPUs). Thus instance
- * methods allow fast, unsychronized access to Plan utilities such as
- * allocation and collection. Each instance rests on static resources
- * (such as memory and virtual memory resources) which are "global"
- * and therefore "static" members of Plan. This mapping of threads to
- * instances is crucial to understanding the correctness and
- * performance proprties of this plan.
- */
-@Uninterruptible
-public final class GCTraceTraceLocal extends SSTraceLocal {
-
- /**
- * Constructor
- *
- * @param trace The global trace to use.
- */
- public GCTraceTraceLocal(Trace trace) {
- super(trace, false);
- }
-
- /****************************************************************************
- *
- * Object processing and tracing
- */
-
- /**
- * Trace a reference during GC. This involves determining which
- * collection policy applies (such as those needed for trace generation)
- * and taking the appropriate actions.
- *
- * @param object The object reference to be traced. In certain
- * cases, this should <i>NOT</i> be an interior pointer.
- * @return The possibly moved reference.
- */
- @Inline
- public ObjectReference traceObject(ObjectReference object) {
- if (object.isNull()) return object;
- if (GCTrace.traceInducedGC) {
- /* We are performing a root scan following an allocation. */
- TraceGenerator.rootEnumerate(object);
- return object;
- } else if (GCTrace.deathScan) {
- /* We are performing the last scan before program termination. */
- TraceGenerator.propagateDeathTime(object);
- return object;
- } else {
- /* *gasp* We are actually performing garbage collection */
- return super.traceObject(object);
- }
- }
-
- /**
- * Ensure that the referenced object will not move during a collection
- * by 'precopying' it at the beginning.
- *
- * @param object The object to ensure will not move.
- */
- @Inline
- public ObjectReference precopyObject(ObjectReference object) {
- if (object.isNull()) return object;
- if (GCTrace.traceInducedGC) {
- /* We are performing a root scan following an allocation. */
- TraceGenerator.rootEnumerate(object);
- return object;
- } else if (GCTrace.deathScan) {
- /* We are performing the last scan before program termination. */
- TraceGenerator.propagateDeathTime(object);
- return object;
- } else {
- return super.precopyObject(object);
- }
- }
-
-
- /**
- * If the referenced object has moved, return the new location.
- *
- * Some copying collectors will need to override this method.
- *
- * @param object The object which may have been forwarded.
- * @return The new location of <code>object</code>.
- */
- @Inline
- public ObjectReference getForwardedReference(ObjectReference object) {
- if (object.isNull()) return object;
- if (SS.hi && Space.isInSpace(SS.SS0, object)) {
- return SS.copySpace0.traceObject(this, object, GCTrace.ALLOC_SS);
- } else if (!SS.hi && Space.isInSpace(SS.SS1, object)) {
- return SS.copySpace1.traceObject(this, object, GCTrace.ALLOC_SS);
- }
- return object;
- }
-
- /**
- * Return true if <code>obj</code> is a live object.
- *
- * @param object The object in question
- * @return True if <code>obj</code> is a live object.
- */
- public boolean isLive(ObjectReference object) {
- if (object.isNull()) return false;
- else if (GCTrace.traceInducedGC) return true;
- else return super.isLive(object);
- }
-
- /**
- * Return true if <code>obj</code> is a reachable object.
- *
- * @param object The object in question
- * @return True if <code>obj</code> is a reachable object;
- * unreachable objects may still be live, however
- */
- public boolean isReachable(ObjectReference object) {
- if (GCTrace.finalDead) return false;
- else if (object.isNull()) return false;
- else {
- Space space = Space.getSpaceForObject(object);
- return space.isReachable(object);
- }
- }
-
- /**
- * Is this object guaranteed not to move during the collection.
- *
- * @param object The object to check.
- * @return True if the object is guaranteed not to move.
- */
- public boolean willNotMoveInCurrentCollection(ObjectReference object) {
- if (GCTrace.traceInducedGC) return true;
- else return super.willNotMoveInCurrentCollection(object);
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/plan/semispace/usePrimitiveWriteBarriers/UsePrimitiveWriteBarriers.java b/vmkit/mmtk/java/src/org/mmtk/plan/semispace/usePrimitiveWriteBarriers/UsePrimitiveWriteBarriers.java
deleted file mode 100644
index 92dd225..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/plan/semispace/usePrimitiveWriteBarriers/UsePrimitiveWriteBarriers.java
+++ /dev/null
@@ -1,26 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.plan.semispace.usePrimitiveWriteBarriers;
-
-import org.mmtk.plan.semispace.SS;
-
-import org.vmmagic.pragma.*;
-
-/**
- * This class exercises primitive write barriers The write barriers contain no
- * payloads but merely perform a write to the heap
- */
-@Uninterruptible
-public class UsePrimitiveWriteBarriers extends SS {
-
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/plan/semispace/usePrimitiveWriteBarriers/UsePrimitiveWriteBarriersCollector.java b/vmkit/mmtk/java/src/org/mmtk/plan/semispace/usePrimitiveWriteBarriers/UsePrimitiveWriteBarriersCollector.java
deleted file mode 100644
index 773e9a5..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/plan/semispace/usePrimitiveWriteBarriers/UsePrimitiveWriteBarriersCollector.java
+++ /dev/null
@@ -1,25 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.plan.semispace.usePrimitiveWriteBarriers;
-
-import org.mmtk.plan.semispace.SSCollector;
-import org.vmmagic.pragma.*;
-
-/**
- * This class extends the {@link SSCollector} class as part of the
- * {@link UsePrimitiveWriteBarriers} collector. All implementation details
- * concerning GC are handled by {@link SSCollector}
- */
-@Uninterruptible
-public class UsePrimitiveWriteBarriersCollector extends SSCollector {
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/plan/semispace/usePrimitiveWriteBarriers/UsePrimitiveWriteBarriersConstraints.java b/vmkit/mmtk/java/src/org/mmtk/plan/semispace/usePrimitiveWriteBarriers/UsePrimitiveWriteBarriersConstraints.java
deleted file mode 100644
index 5c47c09..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/plan/semispace/usePrimitiveWriteBarriers/UsePrimitiveWriteBarriersConstraints.java
+++ /dev/null
@@ -1,84 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.plan.semispace.usePrimitiveWriteBarriers;
-
-import org.mmtk.plan.semispace.SSConstraints;
-import org.vmmagic.pragma.*;
-
-/**
- * UsePrimitiveWriteBarriers common constants.
- */
-@Uninterruptible
-public class UsePrimitiveWriteBarriersConstraints extends SSConstraints {
-
- /** @return True if this Plan requires write barriers on booleans. */
- public boolean needsBooleanWriteBarrier() { return true; }
-
- /** @return True if this Plan can perform bulk boolean arraycopy barriers. */
- public boolean booleanBulkCopySupported() { return true; }
-
- /** @return True if this Plan requires write barriers on bytes. */
- public boolean needsByteWriteBarrier() { return true; }
-
- /** @return True if this Plan can perform bulk byte arraycopy barriers. */
- public boolean byteBulkCopySupported() { return true; }
-
- /** @return True if this Plan requires write barriers on chars. */
- public boolean needsCharWriteBarrier() { return true; }
-
- /** @return True if this Plan can perform bulk char arraycopy barriers. */
- public boolean charBulkCopySupported() { return true; }
-
- /** @return True if this Plan requires write barriers on shorts. */
- public boolean needsShortWriteBarrier() { return true; }
-
- /** @return True if this Plan can perform bulk short arraycopy barriers. */
- public boolean shortBulkCopySupported() { return true; }
-
- /** @return True if this Plan requires write barriers on ints. */
- public boolean needsIntWriteBarrier() { return true; }
-
- /** @return True if this Plan can perform bulk int arraycopy barriers. */
- public boolean intBulkCopySupported() { return true; }
-
- /** @return True if this Plan requires write barriers on longs. */
- public boolean needsLongWriteBarrier() { return true; }
-
- /** @return True if this Plan can perform bulk long arraycopy barriers. */
- public boolean longBulkCopySupported() { return true; }
-
- /** @return True if this Plan requires write barriers on floats. */
- public boolean needsFloatWriteBarrier() { return true; }
-
- /** @return True if this Plan can perform bulk float arraycopy barriers. */
- public boolean floatBulkCopySupported() { return true; }
-
- /** @return True if this Plan requires write barriers on doubles. */
- public boolean needsDoubleWriteBarrier() { return true; }
-
- /** @return True if this Plan can perform bulk double arraycopy barriers. */
- public boolean doubleBulkCopySupported() { return true; }
-
- /** @return True if this Plan requires write barriers on Words. */
- public boolean needsWordWriteBarrier() { return true; }
-
- /** @return True if this Plan requires write barriers on Address's. */
- public boolean needsAddressWriteBarrier() { return true; }
-
- /** @return True if this Plan requires write barriers on Extents. */
- public boolean needsExtentWriteBarrier() { return true; }
-
- /** @return True if this Plan requires write barriers on Offsets. */
- public boolean needsOffsetWriteBarrier() { return true; }
-
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/plan/semispace/usePrimitiveWriteBarriers/UsePrimitiveWriteBarriersMutator.java b/vmkit/mmtk/java/src/org/mmtk/plan/semispace/usePrimitiveWriteBarriers/UsePrimitiveWriteBarriersMutator.java
deleted file mode 100644
index cb84780..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/plan/semispace/usePrimitiveWriteBarriers/UsePrimitiveWriteBarriersMutator.java
+++ /dev/null
@@ -1,424 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.plan.semispace.usePrimitiveWriteBarriers;
-
-import org.mmtk.plan.semispace.SSMutator;
-import org.mmtk.vm.VM;
-
-import org.vmmagic.unboxed.*;
-import org.vmmagic.pragma.*;
-
-/**
- * This class extends the {@link SSMutator} class as part of the
- * {@link UsePrimitiveWriteBarriers} collector. It overrides various methods in
- * {@link Mutator} to implement primitive write barriers.
- */
-@Uninterruptible
-public class UsePrimitiveWriteBarriersMutator extends SSMutator {
-
- /**
- * Write an Address. Take appropriate write barrier actions.<p>
- *
- * @param src The object into which the Word will be stored
- * @param slot The address into which the Word will be
- * stored.
- * @param value The value of the new Address
- * @param metaDataA A value that assists the host VM in creating a store
- * @param metaDataB A value that assists the host VM in creating a store
- * @param mode The context in which the store occurred
- */
- public void addressWrite(ObjectReference src, Address slot, Address value, Word metaDataA, Word metaDataB, int mode) {
- VM.barriers.addressWrite(src, value, metaDataA, metaDataB, mode);
- }
-
- /**
- * Attempt to atomically exchange the value in the given slot
- * with the passed replacement value.
- *
- * @param src The object into which the Address will be stored
- * @param slot The address into which the Address will be
- * stored.
- * @param old The old Address to be swapped out
- * @param value The new Address
- * @param metaDataA A value that assists the host VM in creating a store
- * @param metaDataB A value that assists the host VM in creating a store
- * @param mode The context in which the store occurred
- * @return True if the swap was successful.
- */
- public boolean addressTryCompareAndSwap(ObjectReference src, Address slot, Address old, Address value, Word metaDataA, Word metaDataB, int mode) {
- return VM.barriers.addressTryCompareAndSwap(src, old, value, metaDataA, metaDataB, mode);
- }
-
- /**
- * Write a boolean. Take appropriate write barrier actions.<p>
- *
- * @param src The object into which the new reference will be stored
- * @param slot The address into which the new reference will be
- * stored.
- * @param value The value of the new boolean
- * @param metaDataA A value that assists the host VM in creating a store
- * @param metaDataB A value that assists the host VM in creating a store
- * @param mode The context in which the store occurred
- */
- public void booleanWrite(ObjectReference src, Address slot, boolean value, Word metaDataA, Word metaDataB, int mode) {
- VM.barriers.booleanWrite(src, value, metaDataA, metaDataB, mode);
- }
-
- /**
- * A number of booleans are about to be copied from object
- * <code>src</code> to object <code>dst</code> (as in an array
- * copy). Thus, <code>dst</code> is the mutated object. Take
- * appropriate write barrier actions.<p>
- *
- * @param src The source array
- * @param srcOffset The starting source offset
- * @param dst The destination array
- * @param dstOffset The starting destination offset
- * @param bytes The number of bytes to be copied
- * @return True if the update was performed by the barrier, false if
- * left to the caller
- */
- public boolean booleanBulkCopy(ObjectReference src, Offset srcOffset, ObjectReference dst, Offset dstOffset, int bytes) {
- return false;
- }
-
- /**
- * Write a byte. Take appropriate write barrier actions.<p>
- *
- * @param src The object into which the new reference will be stored
- * @param slot The address into which the new reference will be
- * stored.
- * @param value The value of the new byte
- * @param metaDataA A value that assists the host VM in creating a store
- * @param metaDataB A value that assists the host VM in creating a store
- * @param mode The context in which the store occurred
- */
- public void byteWrite(ObjectReference src, Address slot, byte value, Word metaDataA, Word metaDataB, int mode) {
- VM.barriers.byteWrite(src, value, metaDataA, metaDataB, mode);
- }
-
- /**
- * A number of bytes are about to be copied from object
- * <code>src</code> to object <code>dst</code> (as in an array
- * copy). Thus, <code>dst</code> is the mutated object. Take
- * appropriate write barrier actions.<p>
- *
- * @param src The source array
- * @param srcOffset The starting source offset
- * @param dst The destination array
- * @param dstOffset The starting destination offset
- * @param bytes The number of bytes to be copied
- * @return True if the update was performed by the barrier, false if
- * left to the caller
- */
- public boolean byteBulkCopy(ObjectReference src, Offset srcOffset, ObjectReference dst, Offset dstOffset, int bytes) {
- return false;
- }
-
- /**
- * Write a char. Take appropriate write barrier actions.<p>
- *
- * @param src The object into which the new reference will be stored
- * @param slot The address into which the new reference will be
- * stored.
- * @param value The value of the new char
- * @param metaDataA A value that assists the host VM in creating a store
- * @param metaDataB A value that assists the host VM in creating a store
- * @param mode The context in which the store occurred
- */
- public void charWrite(ObjectReference src, Address slot, char value, Word metaDataA, Word metaDataB, int mode) {
- VM.barriers.charWrite(src, value, metaDataA, metaDataB, mode);
- }
-
- /**
- * A number of chars are about to be copied from object
- * <code>src</code> to object <code>dst</code> (as in an array
- * copy). Thus, <code>dst</code> is the mutated object. Take
- * appropriate write barrier actions.<p>
- *
- * @param src The source array
- * @param srcOffset The starting source offset
- * @param dst The destination array
- * @param dstOffset The starting destination offset
- * @param bytes The number of bytes to be copied
- * @return True if the update was performed by the barrier, false if
- * left to the caller
- */
- public boolean charBulkCopy(ObjectReference src, Offset srcOffset, ObjectReference dst, Offset dstOffset, int bytes) {
- return false;
- }
-
- /**
- * Write a double. Take appropriate write barrier actions.<p>
- *
- * @param src The object into which the new reference will be stored
- * @param slot The address into which the new reference will be
- * stored.
- * @param value The value of the new double
- * @param metaDataA A value that assists the host VM in creating a store
- * @param metaDataB A value that assists the host VM in creating a store
- * @param mode The context in which the store occurred
- */
- public void doubleWrite(ObjectReference src, Address slot, double value, Word metaDataA, Word metaDataB, int mode) {
- VM.barriers.doubleWrite(src, value, metaDataA, metaDataB, mode);
- }
-
- /**
- * A number of doubles are about to be copied from object
- * <code>src</code> to object <code>dst</code> (as in an array
- * copy). Thus, <code>dst</code> is the mutated object. Take
- * appropriate write barrier actions.<p>
- *
- * @param src The source array
- * @param srcOffset The starting source offset
- * @param dst The destination array
- * @param dstOffset The starting destination offset
- * @param bytes The number of bytes to be copied
- * @return True if the update was performed by the barrier, false if
- * left to the caller
- */
- public boolean doubleBulkCopy(ObjectReference src, Offset srcOffset, ObjectReference dst, Offset dstOffset, int bytes) {
- return false;
- }
-
- /**
- * Write an Extent. Take appropriate write barrier actions.<p>
- *
- * @param src The object into which the new reference will be stored
- * @param slot The address into which the new reference will be
- * stored.
- * @param value The value of the new Extent
- * @param metaDataA A value that assists the host VM in creating a store
- * @param metaDataB A value that assists the host VM in creating a store
- * @param mode The context in which the store occurred
- */
- public void extentWrite(ObjectReference src, Address slot, Extent value, Word metaDataA, Word metaDataB, int mode) {
- VM.barriers.extentWrite(src, value, metaDataA, metaDataB, mode);
- }
-
- /**
- * Write a float. Take appropriate write barrier actions.<p>
- *
- * @param src The object into which the new reference will be stored
- * @param slot The address into which the new reference will be
- * stored.
- * @param value The value of the new float
- * @param metaDataA A value that assists the host VM in creating a store
- * @param metaDataB A value that assists the host VM in creating a store
- * @param mode The context in which the store occurred
- */
- public void floatWrite(ObjectReference src, Address slot, float value, Word metaDataA, Word metaDataB, int mode) {
- VM.barriers.floatWrite(src, value, metaDataA, metaDataB, mode);
- }
-
- /**
- * A number of floats are about to be copied from object
- * <code>src</code> to object <code>dst</code> (as in an array
- * copy). Thus, <code>dst</code> is the mutated object. Take
- * appropriate write barrier actions.<p>
- *
- * @param src The source array
- * @param srcOffset The starting source offset
- * @param dst The destination array
- * @param dstOffset The starting destination offset
- * @param bytes The number of bytes to be copied
- * @return True if the update was performed by the barrier, false if
- * left to the caller
- */
- public boolean floatBulkCopy(ObjectReference src, Offset srcOffset, ObjectReference dst, Offset dstOffset, int bytes) {
- return false;
- }
-
- /**
- * Write a int. Take appropriate write barrier actions.<p>
- *
- * @param src The object into which the new reference will be stored
- * @param slot The address into which the new reference will be
- * stored.
- * @param value The value of the new int
- * @param metaDataA A value that assists the host VM in creating a store
- * @param metaDataB A value that assists the host VM in creating a store
- * @param mode The context in which the store occurred
- */
- public void intWrite(ObjectReference src, Address slot, int value, Word metaDataA, Word metaDataB, int mode) {
- VM.barriers.intWrite(src, value, metaDataA, metaDataB, mode);
- }
-
- /**
- * A number of ints are about to be copied from object
- * <code>src</code> to object <code>dst</code> (as in an array
- * copy). Thus, <code>dst</code> is the mutated object. Take
- * appropriate write barrier actions.<p>
- *
- * @param src The source array
- * @param srcOffset The starting source offset
- * @param dst The destination array
- * @param dstOffset The starting destination offset
- * @param bytes The number of bytes to be copied
- * @return True if the update was performed by the barrier, false if
- * left to the caller
- */
- public boolean intBulkCopy(ObjectReference src, Offset srcOffset, ObjectReference dst, Offset dstOffset, int bytes) {
- return false;
- }
-
- /**
- * Attempt to atomically exchange the value in the given slot
- * with the passed replacement value.
- *
- * @param src The object into which the value will be stored
- * @param slot The address into which the value will be
- * stored.
- * @param old The old int to be swapped out
- * @param value The new int
- * @param metaDataA A value that assists the host VM in creating a store
- * @param metaDataB A value that assists the host VM in creating a store
- * @param mode The context in which the store occurred
- * @return True if the swap was successful.
- */
- public boolean intTryCompareAndSwap(ObjectReference src, Address slot, int old, int value, Word metaDataA, Word metaDataB, int mode) {
- return VM.barriers.intTryCompareAndSwap(src, old, value, metaDataA, metaDataB, mode);
- }
-
- /**
- * Write a long. Take appropriate write barrier actions.<p>
- *
- * @param src The object into which the new reference will be stored
- * @param slot The address into which the new reference will be
- * stored.
- * @param value The value of the new long
- * @param metaDataA A value that assists the host VM in creating a store
- * @param metaDataB A value that assists the host VM in creating a store
- * @param mode The context in which the store occurred
- */
- public void longWrite(ObjectReference src, Address slot, long value, Word metaDataA, Word metaDataB, int mode) {
- VM.barriers.longWrite(src, value, metaDataA, metaDataB, mode);
- }
-
- /**
- * A number of longs are about to be copied from object
- * <code>src</code> to object <code>dst</code> (as in an array
- * copy). Thus, <code>dst</code> is the mutated object. Take
- * appropriate write barrier actions.<p>
- *
- * @param src The source array
- * @param srcOffset The starting source offset
- * @param dst The destination array
- * @param dstOffset The starting destination offset
- * @param bytes The number of bytes to be copied
- * @return True if the update was performed by the barrier, false if
- * left to the caller
- */
- public boolean longBulkCopy(ObjectReference src, Offset srcOffset, ObjectReference dst, Offset dstOffset, int bytes) {
- return false;
- }
-
- /**
- * Attempt to atomically exchange the value in the given slot
- * with the passed replacement value.
- *
- * @param src The object into which the value will be stored
- * @param slot The address into which the value will be
- * stored.
- * @param old The old long to be swapped out
- * @param value The new long
- * @param metaDataA A value that assists the host VM in creating a store
- * @param metaDataB A value that assists the host VM in creating a store
- * @param mode The context in which the store occurred
- * @return True if the swap was successful.
- */
- public boolean longTryCompareAndSwap(ObjectReference src, Address slot, long old, long value, Word metaDataA, Word metaDataB, int mode) {
- return VM.barriers.longTryCompareAndSwap(src, old, value, metaDataA, metaDataB, mode);
- }
-
- /**
- * Write an Offset. Take appropriate write barrier actions.<p>
- *
- * @param src The object into which the new reference will be stored
- * @param slot The address into which the new reference will be
- * stored.
- * @param value The value of the new Offset
- * @param metaDataA A value that assists the host VM in creating a store
- * @param metaDataB A value that assists the host VM in creating a store
- * @param mode The context in which the store occurred
- */
- public void offsetWrite(ObjectReference src, Address slot, Offset value, Word metaDataA, Word metaDataB, int mode) {
- VM.barriers.offsetWrite(src, value, metaDataA, metaDataB, mode);
- }
-
- /**
- * Write a short. Take appropriate write barrier actions.<p>
- *
- * @param src The object into which the new reference will be stored
- * @param slot The address into which the new reference will be
- * stored.
- * @param value The value of the new short
- * @param metaDataA A value that assists the host VM in creating a store
- * @param metaDataB A value that assists the host VM in creating a store
- * @param mode The context in which the store occurred
- */
- public void shortWrite(ObjectReference src, Address slot, short value, Word metaDataA, Word metaDataB, int mode) {
- VM.barriers.shortWrite(src, value, metaDataA, metaDataB, mode);
- }
-
- /**
- * A number of shorts are about to be copied from object
- * <code>src</code> to object <code>dst</code> (as in an array
- * copy). Thus, <code>dst</code> is the mutated object. Take
- * appropriate write barrier actions.<p>
- *
- * @param src The source array
- * @param srcOffset The starting source offset
- * @param dst The destination array
- * @param dstOffset The starting destination offset
- * @param bytes The number of bytes to be copied
- * @return True if the update was performed by the barrier, false if
- * left to the caller
- */
- public boolean shortBulkCopy(ObjectReference src, Offset srcOffset, ObjectReference dst, Offset dstOffset, int bytes) {
- return false;
- }
-
- /**
- * Write a Word. Take appropriate write barrier actions.<p>
- *
- * @param src The object into which the new reference will be stored
- * @param slot The address into which the new reference will be
- * stored.
- * @param value The value of the new Word
- * @param metaDataA A value that assists the host VM in creating a store
- * @param metaDataB A value that assists the host VM in creating a store
- * @param mode The context in which the store occurred
- */
- public void wordWrite(ObjectReference src, Address slot, Word value, Word metaDataA, Word metaDataB, int mode) {
- VM.barriers.wordWrite(src, value, metaDataA, metaDataB, mode);
- }
-
- /**
- * Attempt to atomically exchange the value in the given slot
- * with the passed replacement value.
- *
- * @param src The object into which the new reference will be stored
- * @param slot The address into which the new reference will be
- * stored.
- * @param old The old Word to be swapped out
- * @param value The new Word
- * @param metaDataA A value that assists the host VM in creating a store
- * @param metaDataB A value that assists the host VM in creating a store
- * @param mode The context in which the store occurred
- * @return True if the swap was successful.
- */
- public boolean wordTryCompareAndSwap(ObjectReference src, Address slot, Word old, Word value, Word metaDataA, Word metaDataB, int mode) {
- return VM.barriers.wordTryCompareAndSwap(src, old, value, metaDataA, metaDataB, mode);
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/plan/stickyimmix/StickyImmix.java b/vmkit/mmtk/java/src/org/mmtk/plan/stickyimmix/StickyImmix.java
deleted file mode 100644
index a9beb26..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/plan/stickyimmix/StickyImmix.java
+++ /dev/null
@@ -1,237 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.plan.stickyimmix;
-
-import org.mmtk.plan.TransitiveClosure;
-import org.mmtk.plan.immix.Immix;
-import org.mmtk.utility.Log;
-import org.mmtk.utility.deque.SharedDeque;
-import org.mmtk.utility.options.Options;
-import org.mmtk.utility.statistics.BooleanCounter;
-import org.mmtk.utility.statistics.Stats;
-import org.mmtk.vm.Collection;
-
-import org.vmmagic.pragma.*;
-
-/**
- * This class implements the global state of a simple sticky mark bits collector,
- * based on an immix collector. The sticky mark bits algorithm is
- * due to Demmers et al. (http://doi.acm.org/10.1145/96709.96735), and allows
- * generational collection to be performed in a non-moving heap by overloading
- * the role of mark bits to also indicate whether an object is new (nursery) or
- * not. Thus nursery objects are identified by a bit in their header, not by
- * where they lie within the address space. While Demmers et al. did their work
- * in a conservative collector, here we have an exact collector, so we can use
- * a regular write barrier, and don't need to use page protection etc.
- *
- * See the PLDI'08 paper by Blackburn and McKinley for a description
- * of the algorithm: http://doi.acm.org/10.1145/1375581.1375586
- *
- * All plans make a clear distinction between <i>global</i> and
- * <i>thread-local</i> activities, and divides global and local state
- * into separate class hierarchies. Global activities must be
- * synchronized, whereas no synchronization is required for
- * thread-local activities. There is a single instance of Plan (or the
- * appropriate sub-class), and a 1:1 mapping of PlanLocal to "kernel
- * threads" (aka CPUs or in Jikes RVM, Processors). Thus instance
- * methods of PlanLocal allow fast, unsychronized access to functions such as
- * allocation and collection.
- *
- * The global instance defines and manages static resources
- * (such as memory and virtual memory resources). This mapping of threads to
- * instances is crucial to understanding the correctness and
- * performance properties of MMTk plans.
- */
-@Uninterruptible
-public class StickyImmix extends Immix {
-
- /****************************************************************************
- * Constants
- */
- /** If true, then new PLOS objects are collected at each nursery GC */
- static final boolean NURSERY_COLLECT_PLOS = true;
- /** If true then we only do full heap GCs---so we're like MarkSweep (+ write barrier) */
- static final boolean MAJOR_GC_ONLY = false;
- /** estimated collection yield */
- protected static final float SURVIVAL_ESTIMATE = (float) 0.8;
-
- public static int SCAN_NURSERY = 2;
-
- /****************************************************************************
- * Class variables
- */
- private static int lastCommittedImmixPages = 0;
-
- /* statistics */
- public static BooleanCounter fullHeap = new BooleanCounter("majorGC", true, true);
-
- /****************************************************************************
- * Instance variables
- */
- /* Remset pool */
- public final SharedDeque modPool = new SharedDeque("msgen mod objects", metaDataSpace, 1);
-
- /**
- * Constructor.
- *
- */
- public StickyImmix() {
- collectWholeHeap = nextGCWholeHeap = false;
- }
-
- /*****************************************************************************
- *
- * Collection
- */
-
- /**
- * A user-triggered GC has been initiated.
- */
- public void userTriggeredGC() {
- nextGCWholeHeap |= Options.fullHeapSystemGC.getValue();
- }
-
- /**
- * Force the next collection to be full heap.
- */
- @Override
- public void forceFullHeapCollection() {
- nextGCWholeHeap = true;
- }
-
- /**
- * Perform a (global) collection phase.
- *
- * @param phaseId Collection phase to execute.
- */
- @Inline
- @Override
- public final void collectionPhase(short phaseId) {
-
- if (phaseId == SET_COLLECTION_KIND) {
- collectWholeHeap = requiresFullHeapCollection();
- if (Stats.gatheringStats() && collectWholeHeap) fullHeap.set();
- super.collectionPhase(phaseId);
- return;
- }
-
- if (!collectWholeHeap && phaseId == PREPARE) {
- immixTrace.prepare();
- immixSpace.prepare(false);
- return;
- }
-
- if (phaseId == RELEASE) {
- if (collectWholeHeap) {
- super.collectionPhase(RELEASE);
- } else {
- immixTrace.release();
- lastGCWasDefrag = immixSpace.release(false);
- }
- modPool.reset();
- lastCommittedImmixPages = immixSpace.committedPages();
- nextGCWholeHeap = (getPagesAvail() < Options.nurserySize.getMinNursery());
- return;
- }
-
- super.collectionPhase(phaseId);
- }
-
- /*****************************************************************************
- *
- * Accounting
- */
-
- /**
- * This method controls the triggering of a GC. It is called periodically
- * during allocation. Returns true to trigger a collection.
- *
- * @param spaceFull Space request failed, must recover pages within 'space'.
- * @return True if a collection is requested by the plan.
- */
- public final boolean collectionRequired(boolean spaceFull) {
- boolean nurseryFull = immixSpace.getPagesAllocated() > Options.nurserySize.getMaxNursery();
- return super.collectionRequired(spaceFull) || nurseryFull;
- }
-
- /**
- * Determine whether this GC should be a full heap collection.
- *
- * @return True if this GC should be a full heap collection.
- */
- protected boolean requiresFullHeapCollection() {
- if (collectionTrigger == Collection.EXTERNAL_GC_TRIGGER && Options.fullHeapSystemGC.getValue()) {
- return true;
- }
- if (nextGCWholeHeap || collectionAttempt > 1) {
- // Forces full heap collection
- return true;
- }
- if (loSpace.allocationFailed()) {
- // We need space from the nursery
- return true;
- }
-
- // Estimate the yield from small nursery pages
- int smallNurseryPages = immixSpace.committedPages() - lastCommittedImmixPages;
- int smallNurseryYield = (int)(smallNurseryPages * SURVIVAL_ESTIMATE);
-
- if (smallNurseryYield < getPagesRequired()) {
- // Our total yield is insufficient.
- return true;
- }
-
- if (immixSpace.allocationFailed()) {
- if (smallNurseryYield < immixSpace.requiredPages()) {
- // We have run out of VM pages in the nursery
- return true;
- }
- }
-
- return false;
- }
-
- /**
- * Print pre-collection statistics. In this class we prefix the output
- * indicating whether the collection was full heap or not.
- */
- @Override
- public void printPreStats() {
- if ((Options.verbose.getValue() >= 1) && (collectWholeHeap))
- Log.write("[Full heap]");
- super.printPreStats();
- }
-
- /**
- * @return Is current GC only collecting objects allocated since last GC.
- */
- public final boolean isCurrentGCNursery() {
- return !collectWholeHeap;
- }
-
- /**
- * @return Is last GC a full collection?
- */
- public final boolean isLastGCFull() {
- return collectWholeHeap;
- }
-
- /**
- * Register specialized methods.
- */
- @Interruptible
- protected void registerSpecializedMethods() {
- TransitiveClosure.registerSpecializedScan(SCAN_NURSERY, StickyImmixNurseryTraceLocal.class);
- super.registerSpecializedMethods();
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/plan/stickyimmix/StickyImmixCollector.java b/vmkit/mmtk/java/src/org/mmtk/plan/stickyimmix/StickyImmixCollector.java
deleted file mode 100644
index 6167a1c..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/plan/stickyimmix/StickyImmixCollector.java
+++ /dev/null
@@ -1,127 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.plan.stickyimmix;
-
-import org.mmtk.plan.*;
-import org.mmtk.plan.immix.Immix;
-import org.mmtk.plan.immix.ImmixCollector;
-import org.mmtk.plan.immix.ImmixDefragTraceLocal;
-import org.mmtk.plan.immix.ImmixTraceLocal;
-import org.mmtk.policy.immix.CollectorLocal;
-import org.mmtk.utility.alloc.ImmixAllocator;
-import org.mmtk.utility.deque.ObjectReferenceDeque;
-import org.mmtk.vm.VM;
-
-import org.vmmagic.pragma.*;
-
-/**
- * This class implements <i>per-collector thread</i> behavior
- * and state for the <i>StickMS</i> plan, which implements a generational
- * sticky mark bits immix collector.<p>
- *
- * Specifically, this class defines <i>StickyMS</i> collection behavior
- * (through <code>trace</code> and the <code>collectionPhase</code>
- * method).<p>
- *
- * @see StickyImmix for an overview of the algorithm.<p>
- * @see StickyImmixMutator
- * @see StopTheWorldCollector
- * @see CollectorContext
- * @see Phase
- */
-@Uninterruptible
-public class StickyImmixCollector extends ImmixCollector {
-
- /****************************************************************************
- * Instance fields
- */
- private StickyImmixNurseryTraceLocal nurseryTrace;
- private final ImmixAllocator nurseryCopy;
-
- /****************************************************************************
- * Initialization
- */
-
- /**
- * Constructor
- */
- public StickyImmixCollector() {
- ObjectReferenceDeque modBuffer = new ObjectReferenceDeque("mod buffer", global().modPool);
- fastTrace = new ImmixTraceLocal(global().immixTrace, modBuffer);
- defragTrace = new ImmixDefragTraceLocal(global().immixTrace, modBuffer);
- nurseryTrace = new StickyImmixNurseryTraceLocal(global().immixTrace, modBuffer);
- immix = new CollectorLocal(StickyImmix.immixSpace);
- nurseryCopy = new ImmixAllocator(Immix.immixSpace, true, true);
- }
-
- /****************************************************************************
- *
- * Collection
- */
-
- /**
- * Perform a per-collector collection phase.
- *
- * @param phaseId The collection phase to perform
- * @param primary Perform any single-threaded activities using this thread.
- */
- @Inline
- public final void collectionPhase(short phaseId, boolean primary) {
- boolean collectWholeHeap = global().collectWholeHeap;
-
- if (phaseId == StickyImmix.PREPARE) {
- global().modPool.prepareNonBlocking(); /* always do this */
- }
-
- if (!collectWholeHeap) {
- if (phaseId == StickyImmix.PREPARE) {
- currentTrace = (TraceLocal) nurseryTrace;
- immix.prepare(false);
- nurseryTrace.prepare();
- nurseryCopy.reset();
- copy.reset();
- return;
- }
-
- if (phaseId == StickyImmix.ROOTS) {
- VM.scanning.computeStaticRoots(currentTrace);
- VM.scanning.computeGlobalRoots(currentTrace);
- return;
- }
-
- if (phaseId == StickyImmix.CLOSURE) {
- nurseryTrace.completeTrace();
- return;
- }
-
- if (phaseId == StickyImmix.RELEASE) {
- nurseryTrace.release();
- immix.release(false);
- global().modPool.reset();
- return;
- }
- }
-
- super.collectionPhase(phaseId, primary);
- }
-
- /****************************************************************************
- *
- * Miscellaneous
- */
-
- /** @return The active global plan as an <code>StickyImmix</code> instance. */
- private static StickyImmix global() {
- return (StickyImmix) VM.activePlan.global();
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/plan/stickyimmix/StickyImmixConstraints.java b/vmkit/mmtk/java/src/org/mmtk/plan/stickyimmix/StickyImmixConstraints.java
deleted file mode 100644
index c18ad9e..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/plan/stickyimmix/StickyImmixConstraints.java
+++ /dev/null
@@ -1,48 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.plan.stickyimmix;
-
-import static org.mmtk.policy.immix.ImmixConstants.MAX_IMMIX_OBJECT_BYTES;
-
-import org.mmtk.plan.immix.ImmixConstraints;
-
-import org.vmmagic.pragma.*;
-
-/**
- * This class and its subclasses communicate to the host VM/Runtime
- * any features of the selected plan that it needs to know. This is
- * separate from the main Plan/PlanLocal class in order to bypass any
- * issues with ordering of static initialization.
- */
-@Uninterruptible
-public class StickyImmixConstraints extends ImmixConstraints {
- /** @return The number of specialized scans. We need nursery & full heap. */
- @Override
- public int numSpecializedScans() { return 3; }
-
- /** @return True if this plan requires a write barrier */
- @Override
- public boolean needsObjectReferenceWriteBarrier() { return true; }
-
- /** @return True if this Plan requires a header bit for object logging */
- @Override
- public boolean needsLogBitInHeader() { return true; }
-
- /** @return Size (in bytes) beyond which new regular objects must be allocated to the LOS */
- @Override
- public int maxNonLOSDefaultAllocBytes() { return MAX_IMMIX_OBJECT_BYTES; }
-
- /** @return Size (in bytes) beyond which copied objects must be copied to the LOS */
- @Override
- public int maxNonLOSCopyBytes() { return MAX_IMMIX_OBJECT_BYTES; }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/plan/stickyimmix/StickyImmixMutator.java b/vmkit/mmtk/java/src/org/mmtk/plan/stickyimmix/StickyImmixMutator.java
deleted file mode 100644
index 08fa3f0..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/plan/stickyimmix/StickyImmixMutator.java
+++ /dev/null
@@ -1,202 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.plan.stickyimmix;
-
-import org.mmtk.plan.*;
-import org.mmtk.plan.immix.ImmixMutator;
-
-import org.mmtk.utility.HeaderByte;
-import org.mmtk.utility.deque.ObjectReferenceDeque;
-import org.mmtk.vm.VM;
-
-import org.vmmagic.pragma.*;
-import org.vmmagic.unboxed.*;
-
-/**
- * This class implements <i>per-mutator thread</i> behavior
- * and state for the <i>StickyImmix</i> plan, which implements a
- * generational mark-sweep collector.<p>
- *
- * Specifically, this class defines <i>MS</i> mutator-time allocation
- * and per-mutator thread collection semantics (flushing and restoring
- * per-mutator allocator state).<p>
- * *
- * @see StickyImmix
- * @see StickyImmixCollector
- * @see MutatorContext
- * @see Phase
- */
-@Uninterruptible
-public class StickyImmixMutator extends ImmixMutator {
-
- /****************************************************************************
- * Instance fields
- */
-
- private ObjectReferenceDeque modBuffer;
-
- /****************************************************************************
- *
- * Initialization
- */
-
- /**
- * Constructor
- */
- public StickyImmixMutator() {
- super();
- modBuffer = new ObjectReferenceDeque("mod buf", global().modPool);
- }
-
- /****************************************************************************
- *
- * Barriers
- */
-
- /**
- * A new reference is about to be created. Take appropriate write
- * barrier actions.<p>
- *
- * In this case, we remember the address of the source of the
- * pointer if the new reference points into the nursery from
- * non-nursery space.
- *
- * @param src The object into which the new reference will be stored
- * @param slot The address into which the new reference will be
- * stored.
- * @param tgt The target of the new reference
- * @param metaDataA A value that assists the host VM in creating a store
- * @param metaDataB A value that assists the host VM in creating a store
- * @param mode The mode of the store (eg putfield, putstatic etc)
- */
- @Inline
- public final void objectReferenceWrite(ObjectReference src, Address slot,
- ObjectReference tgt, Word metaDataA, Word metaDataB, int mode) {
- if (HeaderByte.isUnlogged(src))
- logSource(src);
- VM.barriers.objectReferenceWrite(src, tgt, metaDataA, metaDataB, mode);
- }
-
- /**
- * A number of references are about to be copied from object
- * <code>src</code> to object <code>dst</code> (as in an array
- * copy). Thus, <code>dst</code> is the mutated object. Take
- * appropriate write barrier actions.<p>
- *
- * In this case, we remember the mutated source address range and
- * will scan that address range at GC time.
- *
- * @param src The source of the values to copied
- * @param srcOffset The offset of the first source address, in
- * bytes, relative to <code>src</code> (in principle, this could be
- * negative).
- * @param dst The mutated object, i.e. the destination of the copy.
- * @param dstOffset The offset of the first destination address, in
- * bytes relative to <code>tgt</code> (in principle, this could be
- * negative).
- * @param bytes The size of the region being copied, in bytes.
- * @return True if the update was performed by the barrier, false if
- * left to the caller (always false in this case).
- */
- @Inline
- public final boolean objectReferenceBulkCopy(ObjectReference src, Offset srcOffset,
- ObjectReference dst, Offset dstOffset, int bytes) {
- if (HeaderByte.isUnlogged(src))
- logSource(src);
- return false;
- }
-
- /**
- * Add an object to the modified objects buffer and mark the
- * object has having been logged. Since duplicate entries do
- * not raise any correctness issues, we do <i>not</i> worry
- * about synchronization and allow threads to race to log the
- * object, potentially including it twice (unlike reference
- * counting where duplicates would lead to incorrect reference
- * counts).
- *
- * @param src The object to be logged
- */
- private void logSource(ObjectReference src) {
- HeaderByte.markAsLogged(src);
- modBuffer.push(src);
- }
-
- /**
- * Flush per-mutator remembered sets into the global remset pool.
- */
- public final void flushRememberedSets() {
- modBuffer.flushLocal();
- assertRemsetFlushed();
- }
-
- /**
- * Assert that the remsets have been flushed. This is critical to
- * correctness. We need to maintain the invariant that remset entries
- * do not accrue during GC. If the host JVM generates barrier entires
- * it is its own responsibility to ensure that they are flushed before
- * returning to MMTk.
- */
- public final void assertRemsetFlushed() {
- if (VM.VERIFY_ASSERTIONS) {
- VM.assertions._assert(modBuffer.isFlushed());
- }
- }
-
-
- /****************************************************************************
- *
- * Collection
- */
-
- /**
- * Perform a per-mutator collection phase.
- *
- * @param phaseId The collection phase to perform
- * @param primary Perform any single-threaded activities using this thread.
- */
- @Inline
- public final void collectionPhase(short phaseId, boolean primary) {
- if (phaseId == StickyImmix.PREPARE) {
- flushRememberedSets();
- }
- if (phaseId == StickyImmix.RELEASE) {
- assertRemsetFlushed();
- }
-
- if (!global().collectWholeHeap) {
- if (phaseId == StickyImmix.PREPARE) {
- immix.prepare();
- return;
- }
-
- if (phaseId == StickyImmix.RELEASE) {
- immix.release();
- return;
- }
- }
-
- super.collectionPhase(phaseId, primary);
- }
-
- /****************************************************************************
- *
- * Miscellaneous
- */
-
- /** @return The active global plan as an <code>MSGen</code> instance. */
- @Inline
- private static StickyImmix global() {
- return (StickyImmix) VM.activePlan.global();
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/plan/stickyimmix/StickyImmixNurseryTraceLocal.java b/vmkit/mmtk/java/src/org/mmtk/plan/stickyimmix/StickyImmixNurseryTraceLocal.java
deleted file mode 100644
index 73ca7ac..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/plan/stickyimmix/StickyImmixNurseryTraceLocal.java
+++ /dev/null
@@ -1,143 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.plan.stickyimmix;
-
-import static org.mmtk.policy.immix.ImmixConstants.MARK_LINE_AT_SCAN_TIME;
-import static org.mmtk.policy.immix.ImmixConstants.TMP_PREFER_COPY_ON_NURSERY_GC;
-
-import org.mmtk.plan.TraceLocal;
-import org.mmtk.plan.Trace;
-import org.mmtk.policy.Space;
-import org.mmtk.utility.HeaderByte;
-import org.mmtk.utility.deque.ObjectReferenceDeque;
-import org.mmtk.vm.VM;
-
-import org.vmmagic.pragma.*;
-import org.vmmagic.unboxed.*;
-
-/**
- * This class implements the thread-local functionality for a transitive
- * closure over a sticky-immix space.
- */
-@Uninterruptible
-public final class StickyImmixNurseryTraceLocal extends TraceLocal {
-
- /****************************************************************************
- *
- * Instance fields.
- */
- private final ObjectReferenceDeque modBuffer;
-
- /**
- * Constructor
- */
- public StickyImmixNurseryTraceLocal(Trace trace, ObjectReferenceDeque modBuffer) {
- super(StickyImmix.SCAN_NURSERY, trace);
- this.modBuffer = modBuffer;
- }
-
- /****************************************************************************
- *
- * Externally visible Object processing and tracing
- */
-
- /**
- * Is the specified object live?
- *
- * @param object The object.
- * @return True if the object is live.
- */
- public boolean isLive(ObjectReference object) {
- if (object.isNull()) return false;
- if (Space.isInSpace(StickyImmix.IMMIX, object))
- return TMP_PREFER_COPY_ON_NURSERY_GC ? StickyImmix.immixSpace.copyNurseryIsLive(object) : StickyImmix.immixSpace.fastIsLive(object);
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(super.isLive(object));
- return true;
- }
-
- /**
- * This method is the core method during the trace of the object graph.
- * The role of this method is to:
- *
- * 1. Ensure the traced object is not collected.
- * 2. If this is the first visit to the object enqueue it to be scanned.
- * 3. Return the forwarded reference to the object.
- *
- * In this instance, we refer objects in the mark-sweep space to the
- * msSpace for tracing, and defer to the superclass for all others.
- *
- * @param object The object to be traced.
- * @return The new reference to the same object instance.
- */
- @Inline
- public ObjectReference traceObject(ObjectReference object) {
- if (object.isNull()) return object;
- if (Space.isInSpace(StickyImmix.IMMIX, object))
- return StickyImmix.immixSpace.nurseryTraceObject(this, object, StickyImmix.ALLOC_DEFAULT);
- else
- return object;
- }
-
- /**
- * Return true if this object is guaranteed not to move during this
- * collection (i.e. this object is definitely not an unforwarded
- * object).
- *
- * @param object
- * @return True if this object is guaranteed not to move during this
- * collection.
- */
- @Override
- public boolean willNotMoveInCurrentCollection(ObjectReference object) {
- if (Space.isInSpace(StickyImmix.IMMIX, object)) {
- if (!TMP_PREFER_COPY_ON_NURSERY_GC)
- return true;
- else
- return StickyImmix.immixSpace.willNotMoveThisNurseryGC(object);
- }
- return super.willNotMoveInCurrentCollection(object);
- }
-
- /**
- * Collectors that move objects <b>must</b> override this method.
- * It performs the deferred scanning of objects which are forwarded
- * during bootstrap of each copying collection. Because of the
- * complexities of the collection bootstrap (such objects are
- * generally themselves gc-critical), the forwarding and scanning of
- * the objects must be dislocated. It is an error for a non-moving
- * collector to call this method.
- *
- * @param object The forwarded object to be scanned
- */
- @Inline
- @Override
- protected void scanObject(ObjectReference object) {
- super.scanObject(object);
- if (MARK_LINE_AT_SCAN_TIME && Space.isInSpace(StickyImmix.IMMIX, object))
- StickyImmix.immixSpace.markLines(object);
- }
-
- /**
- * Process any remembered set entries. This means enumerating the
- * mod buffer and for each entry, marking the object as unlogged
- * and enqueing it for scanning.
- */
- protected void processRememberedSets() {
- logMessage(2, "processing modBuffer");
- while (!modBuffer.isEmpty()) {
- ObjectReference src = modBuffer.pop();
- HeaderByte.markAsUnlogged(src);
- processNode(src);
- }
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/plan/stickyms/StickyMS.java b/vmkit/mmtk/java/src/org/mmtk/plan/stickyms/StickyMS.java
deleted file mode 100644
index a5629fe..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/plan/stickyms/StickyMS.java
+++ /dev/null
@@ -1,206 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.plan.stickyms;
-
-import org.mmtk.plan.TransitiveClosure;
-import org.mmtk.plan.marksweep.MS;
-import org.mmtk.policy.Space;
-import org.mmtk.utility.Log;
-import org.mmtk.utility.deque.SharedDeque;
-import org.mmtk.utility.options.Options;
-import org.mmtk.utility.sanitychecker.SanityChecker;
-import org.mmtk.vm.VM;
-
-import org.vmmagic.pragma.*;
-import org.vmmagic.unboxed.ObjectReference;
-
-/**
- * This class implements the global state of a simple sticky mark bits collector,
- * based a simple on mark-sweep collector. The sticky mark bits algorithm is
- * due to Demmers et al. (http://doi.acm.org/10.1145/96709.96735), and allows
- * generational collection to be performed in a non-moving heap by overloading
- * the role of mark bits to also indicate whether an object is new (nursery) or
- * not. Thus nursery objects are identified by a bit in their header, not by
- * where they lie within the address space. While Demmers et al. did their work
- * in a conservative collector, here we have an exact collector, so we can use
- * a regular write barrier, and don't need to use page protection etc.
- *
- * All plans make a clear distinction between <i>global</i> and
- * <i>thread-local</i> activities, and divides global and local state
- * into separate class hierarchies. Global activities must be
- * synchronized, whereas no synchronization is required for
- * thread-local activities. There is a single instance of Plan (or the
- * appropriate sub-class), and a 1:1 mapping of PlanLocal to "kernel
- * threads" (aka CPUs or in Jikes RVM, Processors). Thus instance
- * methods of PlanLocal allow fast, unsychronized access to functions such as
- * allocation and collection.
- *
- * The global instance defines and manages static resources
- * (such as memory and virtual memory resources). This mapping of threads to
- * instances is crucial to understanding the correctness and
- * performance properties of MMTk plans.
- */
-@Uninterruptible
-public class StickyMS extends MS {
-
- /****************************************************************************
- * Constants
- */
- /** If true, then new PLOS objects are collected at each nursery GC */
- static final boolean NURSERY_COLLECT_PLOS = true;
- /** If true then we only do full heap GCs---so we're like MarkSweep (+ write barrier) */
- static final boolean MAJOR_GC_ONLY = false;
-
- /****************************************************************************
- * Class variables
- */
-
- public static int SCAN_NURSERY = 1;
-
- /****************************************************************************
- * Instance variables
- */
- /* status fields */
- /** will the next collection collect the whole heap? */
- public boolean nextGCWholeHeap = false;
- /** will this collection collect the whole heap */
- public boolean collectWholeHeap = nextGCWholeHeap;
-
- /* Remset pool */
- public final SharedDeque modPool = new SharedDeque("msgen mod objects", metaDataSpace, 1);
-
- /****************************************************************************
- * Static initialization
- */
- {
- msSpace.makeAgeSegregatedSpace(); /* this space is to be collected generationally */
- }
-
- /*****************************************************************************
- *
- * Collection
- */
-
- /**
- * A user-triggered GC has been initiated.
- */
- public void userTriggeredGC() {
- nextGCWholeHeap |= Options.fullHeapSystemGC.getValue();
- }
-
- /**
- * Force the next collection to be full heap.
- */
- @Override
- public void forceFullHeapCollection() {
- nextGCWholeHeap = true;
- }
-
- /**
- * Perform a (global) collection phase.
- *
- * @param phaseId Collection phase to execute.
- */
- @Inline
- @Override
- public final void collectionPhase(short phaseId) {
-
- if (phaseId == INITIATE) {
- collectWholeHeap = MAJOR_GC_ONLY || emergencyCollection || nextGCWholeHeap;
- nextGCWholeHeap = false;
- super.collectionPhase(phaseId);
- return;
- }
-
- if (!collectWholeHeap) {
- if (phaseId == PREPARE) {
- msTrace.prepare();
- msSpace.prepare(false);
- return;
- }
-
- if (phaseId == RELEASE) {
- msTrace.release();
- msSpace.release();
- modPool.reset();
- nextGCWholeHeap = (getPagesAvail() < Options.nurserySize.getMinNursery());
- return;
- }
- }
-
- super.collectionPhase(phaseId);
- }
-
- /*****************************************************************************
- *
- * Accounting
- */
-
- /**
- * Print pre-collection statistics. In this class we prefix the output
- * indicating whether the collection was full heap or not.
- */
- @Override
- public void printPreStats() {
- if ((Options.verbose.getValue() >= 1) && (collectWholeHeap))
- Log.write("[Full heap]");
- super.printPreStats();
- }
-
- /**
- * @return Is current GC only collecting objects allocated since last GC.
- */
- public final boolean isCurrentGCNursery() {
- return !collectWholeHeap;
- }
-
- /**
- * @return Is last GC a full collection?
- */
- public final boolean isLastGCFull() {
- return collectWholeHeap;
- }
-
- /**
- * Return the expected reference count. For non-reference counting
- * collectors this becomes a true/false relationship.
- * @param object The object to check.
- * @param sanityRootRC The number of root references to the object.
- *
- * @return The expected (root excluded) reference count.
- */
- public int sanityExpectedRC(ObjectReference object, int sanityRootRC) {
- Space space = Space.getSpaceForObject(object);
-
- // Immortal spaces
- if (space == StickyMS.immortalSpace || space == StickyMS.vmSpace) {
- return space.isReachable(object) ? SanityChecker.ALIVE : SanityChecker.DEAD;
- }
-
- // Mature space (nursery collection)
- if (VM.activePlan.global().isCurrentGCNursery() && space != StickyMS.msSpace) {
- return SanityChecker.UNSURE;
- }
-
- return super.sanityExpectedRC(object, sanityRootRC);
- }
-
- /**
- * Register specialized methods.
- */
- @Interruptible
- protected void registerSpecializedMethods() {
- TransitiveClosure.registerSpecializedScan(SCAN_NURSERY, StickyMSNurseryTraceLocal.class);
- super.registerSpecializedMethods();
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/plan/stickyms/StickyMSCollector.java b/vmkit/mmtk/java/src/org/mmtk/plan/stickyms/StickyMSCollector.java
deleted file mode 100644
index 37b7945..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/plan/stickyms/StickyMSCollector.java
+++ /dev/null
@@ -1,116 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.plan.stickyms;
-
-import org.mmtk.plan.*;
-import org.mmtk.plan.marksweep.MSCollector;
-import org.mmtk.plan.marksweep.MSTraceLocal;
-import org.mmtk.utility.deque.ObjectReferenceDeque;
-import org.mmtk.vm.VM;
-
-import org.vmmagic.pragma.*;
-
-/**
- * This class implements <i>per-collector thread</i> behavior
- * and state for the <i>StickMS</i> plan, which implements a generational
- * sticky mark bits mark-sweep collector.<p>
- *
- * Specifically, this class defines <i>StickyMS</i> collection behavior
- * (through <code>trace</code> and the <code>collectionPhase</code>
- * method).<p>
- *
- * @see StickyMS for an overview of the algorithm.<p>
- * @see StickyMSMutator
- * @see StopTheWorldCollector
- * @see CollectorContext
- * @see Phase
- */
-@Uninterruptible
-public class StickyMSCollector extends MSCollector {
-
- /****************************************************************************
- * Instance fields
- */
- private StickyMSNurseryTraceLocal nurseryTrace;
-
- /****************************************************************************
- * Initialization
- */
-
- /**
- * Constructor
- */
- public StickyMSCollector() {
- ObjectReferenceDeque modBuffer = new ObjectReferenceDeque("mod buffer", global().modPool);
- fullTrace = new MSTraceLocal(global().msTrace, modBuffer);
- nurseryTrace = new StickyMSNurseryTraceLocal(global().msTrace, modBuffer);
- }
-
- /****************************************************************************
- *
- * Collection
- */
-
- /**
- * Perform a per-collector collection phase.
- *
- * @param phaseId The collection phase to perform
- * @param primary Perform any single-threaded activities using this thread.
- */
- @Inline
- public final void collectionPhase(short phaseId, boolean primary) {
- boolean collectWholeHeap = global().collectWholeHeap;
-
- if (phaseId == StickyMS.PREPARE) {
- currentTrace = collectWholeHeap ? (TraceLocal) fullTrace : (TraceLocal) nurseryTrace;
- global().modPool.prepareNonBlocking(); /* always do this */
- }
-
- if (!collectWholeHeap) {
- if (phaseId == StickyMS.PREPARE) {
- nurseryTrace.prepare();
- return;
- }
-
- if (phaseId == StickyMS.ROOTS) {
- VM.scanning.computeStaticRoots(currentTrace);
- VM.scanning.computeGlobalRoots(currentTrace);
- return;
- }
-
- if (phaseId == StickyMS.CLOSURE) {
- nurseryTrace.completeTrace();
- return;
- }
-
- if (phaseId == StickyMS.RELEASE) {
- nurseryTrace.release();
- global().modPool.reset();
- return;
- }
- }
-
- super.collectionPhase(phaseId, primary);
- }
-
- /****************************************************************************
- *
- * Miscellaneous
- */
-
- /** @return The active global plan as an <code>MS</code> instance. */
- @Inline
- private static StickyMS global() {
- return (StickyMS) VM.activePlan.global();
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/plan/stickyms/StickyMSConstraints.java b/vmkit/mmtk/java/src/org/mmtk/plan/stickyms/StickyMSConstraints.java
deleted file mode 100644
index 199b884..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/plan/stickyms/StickyMSConstraints.java
+++ /dev/null
@@ -1,43 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.plan.stickyms;
-
-import org.mmtk.plan.marksweep.MSConstraints;
-
-import org.mmtk.policy.SegregatedFreeListSpace;
-
-import org.vmmagic.pragma.*;
-
-/**
- * This class and its subclasses communicate to the host VM/Runtime
- * any features of the selected plan that it needs to know. This is
- * separate from the main Plan/PlanLocal class in order to bypass any
- * issues with ordering of static initialization.
- */
-@Uninterruptible
-public class StickyMSConstraints extends MSConstraints {
- /** @return The number of specialized scans. We need nursery & full heap. */
- @Override
- public int numSpecializedScans() { return 2; }
-
- /** @return True if this plan requires a write barrier */
- @Override
- public boolean needsObjectReferenceWriteBarrier() { return true; }
-
- /** @return True if this Plan requires a header bit for object logging */
- @Override
- public boolean needsLogBitInHeader() { return true; }
-
- @Override
- public int maxNonLOSDefaultAllocBytes() { return SegregatedFreeListSpace.MAX_FREELIST_OBJECT_BYTES; }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/plan/stickyms/StickyMSMutator.java b/vmkit/mmtk/java/src/org/mmtk/plan/stickyms/StickyMSMutator.java
deleted file mode 100644
index 3a16f7b..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/plan/stickyms/StickyMSMutator.java
+++ /dev/null
@@ -1,214 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.plan.stickyms;
-
-import org.mmtk.plan.*;
-import org.mmtk.plan.marksweep.MSMutator;
-import org.mmtk.policy.MarkSweepLocal;
-
-import org.mmtk.utility.HeaderByte;
-import org.mmtk.utility.deque.ObjectReferenceDeque;
-import org.mmtk.vm.VM;
-
-import org.vmmagic.pragma.*;
-import org.vmmagic.unboxed.*;
-
-/**
- * This class implements <i>per-mutator thread</i> behavior
- * and state for the <i>StickyMS</i> plan, which implements a
- * generational mark-sweep collector.<p>
- *
- * Specifically, this class defines <i>MS</i> mutator-time allocation
- * and per-mutator thread collection semantics (flushing and restoring
- * per-mutator allocator state).<p>
- * *
- * @see StickyMS
- * @see StickyMSCollector
- * @see MutatorContext
- * @see Phase
- */
-@Uninterruptible
-public class StickyMSMutator extends MSMutator {
-
- /****************************************************************************
- * Instance fields
- */
-
- private ObjectReferenceDeque modBuffer;
-
- /****************************************************************************
- *
- * Initialization
- */
-
- /**
- * Constructor
- */
- public StickyMSMutator() {
- ms = new MarkSweepLocal(StickyMS.msSpace);
- modBuffer = new ObjectReferenceDeque("mod buf", global().modPool);
- }
-
- /****************************************************************************
- *
- * Barriers
- */
-
- /**
- * A new reference is about to be created. Take appropriate write
- * barrier actions.<p>
- *
- * In this case, we remember the address of the source of the
- * pointer if the new reference points into the nursery from
- * non-nursery space.
- *
- * @param src The object into which the new reference will be stored
- * @param slot The address into which the new reference will be
- * stored.
- * @param tgt The target of the new reference
- * @param metaDataA A value that assists the host VM in creating a store
- * @param metaDataB A value that assists the host VM in creating a store
- * @param mode The mode of the store (eg putfield, putstatic etc)
- */
- @Inline
- public final void objectReferenceWrite(ObjectReference src, Address slot,
- ObjectReference tgt, Word metaDataA, Word metaDataB, int mode) {
- if (HeaderByte.isUnlogged(src))
- logSource(src);
- VM.barriers.objectReferenceWrite(src, tgt, metaDataA, metaDataB, mode);
- }
-
- /**
- * A number of references are about to be copied from object
- * <code>src</code> to object <code>dst</code> (as in an array
- * copy). Thus, <code>dst</code> is the mutated object. Take
- * appropriate write barrier actions.<p>
- *
- * In this case, we remember the mutated source address range and
- * will scan that address range at GC time.
- *
- * @param src The source of the values to copied
- * @param srcOffset The offset of the first source address, in
- * bytes, relative to <code>src</code> (in principle, this could be
- * negative).
- * @param dst The mutated object, i.e. the destination of the copy.
- * @param dstOffset The offset of the first destination address, in
- * bytes relative to <code>tgt</code> (in principle, this could be
- * negative).
- * @param bytes The size of the region being copied, in bytes.
- * @return True if the update was performed by the barrier, false if
- * left to the caller (always false in this case).
- */
- @Inline
- public final boolean objectReferenceBulkCopy(ObjectReference src, Offset srcOffset,
- ObjectReference dst, Offset dstOffset, int bytes) {
- if (HeaderByte.isUnlogged(src))
- logSource(src);
- return false;
- }
-
- /**
- * Add an object to the modified objects buffer and mark the
- * object has having been logged. Since duplicate entries do
- * not raise any correctness issues, we do <i>not</i> worry
- * about synchronization and allow threads to race to log the
- * object, potentially including it twice (unlike reference
- * counting where duplicates would lead to incorrect reference
- * counts).
- *
- * @param src The object to be logged
- */
- private void logSource(ObjectReference src) {
- HeaderByte.markAsLogged(src);
- modBuffer.push(src);
- }
-
- /**
- * Flush per-mutator remembered sets into the global remset pool.
- */
- public final void flushRememberedSets() {
- modBuffer.flushLocal();
- assertRemsetFlushed();
- }
-
- /**
- * Assert that the remsets have been flushed. This is critical to
- * correctness. We need to maintain the invariant that remset entries
- * do not accrue during GC. If the host JVM generates barrier entires
- * it is its own responsibility to ensure that they are flushed before
- * returning to MMTk.
- */
- public final void assertRemsetFlushed() {
- if (VM.VERIFY_ASSERTIONS) {
- VM.assertions._assert(modBuffer.isFlushed());
- }
- }
-
-
- /****************************************************************************
- *
- * Collection
- */
-
- /**
- * Perform a per-mutator collection phase.
- *
- * @param phaseId The collection phase to perform
- * @param primary Perform any single-threaded activities using this thread.
- */
- @Inline
- public final void collectionPhase(short phaseId, boolean primary) {
- if (phaseId == StickyMS.PREPARE) {
- flushRememberedSets();
- }
- if (phaseId == StickyMS.RELEASE) {
- assertRemsetFlushed();
- }
-
- if (!global().collectWholeHeap) {
- if (phaseId == StickyMS.PREPARE) {
- ms.prepare();
- return;
- }
-
- if (phaseId == StickyMS.RELEASE) {
- ms.release();
- return;
- }
- }
-
- super.collectionPhase(phaseId, primary);
- }
-
-
- /**
- * Flush mutator context, in response to a requestMutatorFlush.
- * Also called by the default implementation of deinitMutator.
- */
- @Override
- public void flush() {
- super.flush();
- ms.flush();
- }
-
- /****************************************************************************
- *
- * Miscellaneous
- */
-
- /** @return The active global plan as an <code>MSGen</code> instance. */
- @Inline
- private static StickyMS global() {
- return (StickyMS) VM.activePlan.global();
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/plan/stickyms/StickyMSNurseryTraceLocal.java b/vmkit/mmtk/java/src/org/mmtk/plan/stickyms/StickyMSNurseryTraceLocal.java
deleted file mode 100644
index 26e9e6b..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/plan/stickyms/StickyMSNurseryTraceLocal.java
+++ /dev/null
@@ -1,101 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.plan.stickyms;
-
-import org.mmtk.plan.TraceLocal;
-import org.mmtk.plan.Trace;
-import org.mmtk.policy.Space;
-import org.mmtk.utility.HeaderByte;
-import org.mmtk.utility.deque.ObjectReferenceDeque;
-import org.mmtk.vm.VM;
-
-import org.vmmagic.pragma.*;
-import org.vmmagic.unboxed.*;
-
-/**
- * This class implements the thread-local functionality for a transitive
- * closure over a mark-sweep space.
- */
-@Uninterruptible
-public final class StickyMSNurseryTraceLocal extends TraceLocal {
-
- /****************************************************************************
- *
- * Instance fields.
- */
- private final ObjectReferenceDeque modBuffer;
-
- /**
- * Constructor
- */
- public StickyMSNurseryTraceLocal(Trace trace, ObjectReferenceDeque modBuffer) {
- super(StickyMS.SCAN_NURSERY, trace);
- this.modBuffer = modBuffer;
- }
-
- /****************************************************************************
- *
- * Externally visible Object processing and tracing
- */
-
- /**
- * Is the specified object live?
- *
- * @param object The object.
- * @return True if the object is live.
- */
- public boolean isLive(ObjectReference object) {
- if (object.isNull()) return false;
- if (Space.isInSpace(StickyMS.MARK_SWEEP, object))
- return StickyMS.msSpace.isLive(object);
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(super.isLive(object));
- return true;
- }
-
- /**
- * This method is the core method during the trace of the object graph.
- * The role of this method is to:
- *
- * 1. Ensure the traced object is not collected.
- * 2. If this is the first visit to the object enqueue it to be scanned.
- * 3. Return the forwarded reference to the object.
- *
- * In this instance, we refer objects in the mark-sweep space to the
- * msSpace for tracing, and defer to the superclass for all others.
- *
- * @param object The object to be traced.
- * @return The new reference to the same object instance.
- */
- @Inline
- public ObjectReference traceObject(ObjectReference object) {
- if (object.isNull()) return object;
- if (Space.isInSpace(StickyMS.MARK_SWEEP, object))
- return StickyMS.msSpace.traceObject(this, object);
- else
- return object;
- }
-
- /**
- * Process any remembered set entries. This means enumerating the
- * mod buffer and for each entry, marking the object as unlogged
- * and enqueing it for scanning.
- */
- protected void processRememberedSets() {
- logMessage(2, "processing modBuffer");
- while (!modBuffer.isEmpty()) {
- ObjectReference src = modBuffer.pop();
- HeaderByte.markAsUnlogged(src);
- processNode(src);
- }
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/policy/BaseLargeObjectSpace.java b/vmkit/mmtk/java/src/org/mmtk/policy/BaseLargeObjectSpace.java
deleted file mode 100644
index fd54288..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/policy/BaseLargeObjectSpace.java
+++ /dev/null
@@ -1,126 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.policy;
-
-import org.mmtk.utility.heap.FreeListPageResource;
-import org.mmtk.utility.heap.VMRequest;
-import org.mmtk.utility.Constants;
-
-import org.vmmagic.pragma.*;
-import org.vmmagic.unboxed.*;
-
-/**
- * Each instance of this class corresponds to one treadmill *space*.
- *
- * Each of the instance methods of this class may be called by any
- * thread (i.e. synchronization must be explicit in any instance or
- * class method).
- *
- * This stands in contrast to TreadmillLocal, which is instantiated
- * and called on a per-thread basis, where each instance of
- * TreadmillLocal corresponds to one thread operating over one space.
- */
-@Uninterruptible
-public abstract class BaseLargeObjectSpace extends Space implements Constants {
-
- /****************************************************************************
- *
- * Class variables
- */
- protected static final Word PAGE_MASK = Word.fromIntSignExtend(~(BYTES_IN_PAGE - 1));
-
- /****************************************************************************
- *
- * Initialization
- */
-
- /**
- * The caller specifies the region of virtual memory to be used for
- * this space. If this region conflicts with an existing space,
- * then the constructor will fail.
- *
- * @param name The name of this space (used when printing error messages etc)
- * @param pageBudget The number of pages this space may consume
- * before consulting the plan
- * @param vmRequest An object describing the virtual memory requested.
- */
- public BaseLargeObjectSpace(String name, int pageBudget, VMRequest vmRequest) {
- super(name, false, false, vmRequest);
- if (vmRequest.isDiscontiguous()) {
- pr = new FreeListPageResource(pageBudget, this, 0);
- } else {
- pr = new FreeListPageResource(pageBudget, this, start, extent);
- }
- }
-
- /**
- * Calculate the header size required for the large object.
- *
- * Must be multiple of MIN_ALIGNMENT.
- */
- public final int getHeaderSize() {
- return superPageHeaderSize() + cellHeaderSize();
- }
-
- /****************************************************************************
- *
- * Freeing
- */
-
- /**
- * Free a cell. If the cell is large (own superpage) then release
- * the superpage, if not add to the super page's free list and if
- * all cells on the superpage are free, then release the
- * superpage.
- *
- * @param cell The address of the first byte of the cell to be freed
- */
- @Inline
- public final void free(Address cell) {
- release(getSuperPage(cell));
- }
-
- /****************************************************************************
- *
- * Superpages
- */
-
- protected abstract int superPageHeaderSize();
- protected abstract int cellHeaderSize();
-
- /**
- * Return the superpage for a given cell. If the cell is a small
- * cell then this is found by masking the cell address to find the
- * containing page. Otherwise the first word of the cell contains
- * the address of the page.
- *
- * @param cell The address of the first word of the cell (exclusive
- * of any sub-class specific metadata).
- * @return The address of the first word of the superpage containing
- * <code>cell</code>.
- */
- @Inline
- public static Address getSuperPage(Address cell) {
- return cell.toWord().and(PAGE_MASK).toAddress();
- }
-
- /**
- * Return the size of the super page
- *
- * @param first the Address of the first word in the superpage
- * @return the size in bytes
- */
- public Extent getSize(Address first) {
- return ((FreeListPageResource) pr).getSize(first);
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/policy/CopyLocal.java b/vmkit/mmtk/java/src/org/mmtk/policy/CopyLocal.java
deleted file mode 100644
index c4bc69e..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/policy/CopyLocal.java
+++ /dev/null
@@ -1,44 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.policy;
-
-import org.mmtk.utility.alloc.BumpPointer;
-
-import org.vmmagic.pragma.*;
-
-/**
- * This class implements unsynchronized (local) elements of a
- * copying collector. Allocation is via the bump pointer
- * (@see BumpPointer).
- *
- * @see BumpPointer
- * @see CopySpace
- */
-@Uninterruptible public final class CopyLocal extends BumpPointer {
-
- /**
- * Constructor
- *
- * @param space The space to bump point into.
- */
- public CopyLocal(CopySpace space) {
- super(space, true);
- }
-
- /**
- * Constructor
- */
- public CopyLocal() {
- super(null, true);
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/policy/CopySpace.java b/vmkit/mmtk/java/src/org/mmtk/policy/CopySpace.java
deleted file mode 100644
index 4254456..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/policy/CopySpace.java
+++ /dev/null
@@ -1,235 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.policy;
-
-import org.mmtk.plan.TransitiveClosure;
-import org.mmtk.utility.heap.*;
-import org.mmtk.utility.options.Options;
-import org.mmtk.utility.Constants;
-import org.mmtk.utility.ForwardingWord;
-import org.mmtk.utility.Log;
-
-import org.mmtk.vm.VM;
-
-import org.vmmagic.unboxed.*;
-import org.vmmagic.pragma.*;
-
-/**
- * This class implements tracing functionality for a simple copying
- * space. Since no state needs to be held globally or locally, all
- * methods are static.
- */
-@Uninterruptible public final class CopySpace extends Space
- implements Constants {
-
- /****************************************************************************
- *
- * Class variables
- */
- public static final int LOCAL_GC_BITS_REQUIRED = 2;
- public static final int GLOBAL_GC_BITS_REQUIRED = 0;
- public static final int GC_HEADER_WORDS_REQUIRED = 0;
-
- private static final int META_DATA_PAGES_PER_REGION = CARD_META_PAGES_PER_REGION;
-
-
- /****************************************************************************
- *
- * Instance variables
- */
- private boolean fromSpace = true;
-
- public boolean isFromSpace() {
- return fromSpace;
- }
-
- /** fromSpace CopySpace can always move, toSpace will not move during current GC */
- @Override
- public boolean isMovable() {
- return fromSpace;
- }
-
- /****************************************************************************
- *
- * Initialization
- */
-
- /**
- * The caller specifies the region of virtual memory to be used for
- * this space. If this region conflicts with an existing space,
- * then the constructor will fail.
- *
- * @param name The name of this space (used when printing error messages etc)
- * @param pageBudget The number of pages this space may consume
- * before consulting the plan
- * @param fromSpace The does this instance start life as from-space
- * (or to-space)?
- * @param vmRequest An object describing the virtual memory requested.
- */
- public CopySpace(String name, int pageBudget, boolean fromSpace, VMRequest vmRequest) {
- super(name, true, false, vmRequest);
- this.fromSpace = fromSpace;
- if (vmRequest.isDiscontiguous()) {
- pr = new MonotonePageResource(pageBudget, this, META_DATA_PAGES_PER_REGION);
- } else {
- pr = new MonotonePageResource(pageBudget, this, start, extent, META_DATA_PAGES_PER_REGION);
- }
- }
-
- /****************************************************************************
- *
- * Prepare and release
- */
-
- /**
- * Prepare this space instance for a collection. Set the
- * "fromSpace" field according to whether this space is the
- * source or target of the collection.
- *
- * @param fromSpace Set the fromSpace field to this value
- */
- public void prepare(boolean fromSpace) { this.fromSpace = fromSpace; }
-
- /**
- * Release this copy space after a collection. This means releasing
- * all pages associated with this (now empty) space.
- */
- public void release() {
- ((MonotonePageResource) pr).reset();
- headDiscontiguousRegion = Address.zero();
- fromSpace = false;
- }
-
- /**
- * Release an allocated page or pages. In this case we do nothing
- * because we only release pages enmasse.
- *
- * @param start The address of the start of the page or pages
- */
- @Inline
- public void release(Address start) {
- if (VM.VERIFY_ASSERTIONS)
- VM.assertions._assert(false); // this policy only releases pages enmasse
- }
-
- /****************************************************************************
- *
- * Tracing and forwarding
- */
-
- /**
- * Trace an object under a copying collection policy.
- *
- * We use a tri-state algorithm to deal with races to forward
- * the object. The tracer must wait if the object is concurrently
- * being forwarded by another thread.
- *
- * If the object is already forwarded, the copy is returned.
- * Otherwise, the object is forwarded and the copy is returned.
- *
- * @param trace The trace being conducted.
- * @param object The object to be forwarded.
- * @return The forwarded object.
- */
- @Inline
- public ObjectReference traceObject(TransitiveClosure trace, ObjectReference object) {
- VM.assertions.fail("CopySpace.traceLocal called without allocator");
- return ObjectReference.nullReference();
- }
-
- /**
- * Trace an object under a copying collection policy.
- *
- * We use a tri-state algorithm to deal with races to forward
- * the object. The tracer must wait if the object is concurrently
- * being forwarded by another thread.
- *
- * If the object is already forwarded, the copy is returned.
- * Otherwise, the object is forwarded and the copy is returned.
- *
- * @param trace The trace being conducted.
- * @param object The object to be forwarded.
- * @param allocator The allocator to use when copying.
- * @return The forwarded object.
- */
- @Inline
- public ObjectReference traceObject(TransitiveClosure trace, ObjectReference object, int allocator) {
- /* If the object in question is already in to-space, then do nothing */
- if (!fromSpace) return object;
-
- /* Try to forward the object */
- Word forwardingWord = ForwardingWord.attemptToForward(object);
-
- if (ForwardingWord.stateIsForwardedOrBeingForwarded(forwardingWord)) {
- /* Somebody else got to it first. */
-
- /* We must wait (spin) if the object is not yet fully forwarded */
- while (ForwardingWord.stateIsBeingForwarded(forwardingWord))
- forwardingWord = VM.objectModel.readAvailableBitsWord(object);
-
- /* Now extract the object reference from the forwarding word and return it */
- return ForwardingWord.extractForwardingPointer(forwardingWord);
- } else {
- /* We are the designated copier, so forward it and enqueue it */
- ObjectReference newObject = VM.objectModel.copy(object, allocator);
- ForwardingWord.setForwardingPointer(object, newObject);
- trace.processNode(newObject); // Scan it later
-
- if (VM.VERIFY_ASSERTIONS && Options.verbose.getValue() >= 9) {
- Log.write("C["); Log.write(object); Log.write("/");
- Log.write(getName()); Log.write("] -> ");
- Log.write(newObject); Log.write("/");
- Log.write(Space.getSpaceForObject(newObject).getName());
- Log.writeln("]");
- }
- return newObject;
- }
- }
-
- /**
- * Return true if this object is live in this GC
- *
- * @param object The object in question
- * @return True if this object is live in this GC (has it been forwarded?)
- */
- public boolean isLive(ObjectReference object) {
- return ForwardingWord.isForwarded(object);
- }
-
- /**
- * Has the object in this space been reached during the current collection.
- * This is used for GC Tracing.
- *
- * @param object The object reference.
- * @return True if the object is reachable.
- */
- public boolean isReachable(ObjectReference object) {
- return !fromSpace || ForwardingWord.isForwarded(object);
- }
-
- /****************************************************************************
- *
- * Header manipulation
- */
-
- /**
- * Perform any required post-allocation initialization
- *
- * <i>Nothing to be done in this case</i>
- *
- * @param object the object ref to the storage to be initialized
- */
- @Inline
- public void postAlloc(ObjectReference object) {}
-
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/policy/ExplicitFreeListLocal.java b/vmkit/mmtk/java/src/org/mmtk/policy/ExplicitFreeListLocal.java
deleted file mode 100644
index adab83c..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/policy/ExplicitFreeListLocal.java
+++ /dev/null
@@ -1,77 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.policy;
-
-import org.mmtk.utility.alloc.SegregatedFreeListLocal;
-import org.mmtk.utility.Constants;
-
-import org.vmmagic.pragma.*;
-
-/**
- * This class implements unsynchronized (local) elements of an
- * explicity managed collector. Allocation is via the segregated free list
- * (@see org.mmtk.utility.alloc.SegregatedFreeList).<p>
- *
- * @see org.mmtk.utility.alloc.SegregatedFreeList
- * @see ExplicitFreeListSpace
- */
-@Uninterruptible
-public final class ExplicitFreeListLocal extends SegregatedFreeListLocal<ExplicitFreeListSpace> implements Constants {
-
- /****************************************************************************
- *
- * Class variables
- */
-
- /****************************************************************************
- *
- * Instance variables
- */
-
- /****************************************************************************
- *
- * Initialization
- */
-
- /**
- * Constructor
- *
- * @param space The rc space to which this allocator
- * instances is bound.
- */
- public ExplicitFreeListLocal(ExplicitFreeListSpace space) {
- super(space);
- }
-
- /****************************************************************************
- *
- * Allocation
- */
-
- /****************************************************************************
- *
- * Collection
- */
-
- /**
- * Prepare for a collection. If paranoid, perform a sanity check.
- */
- public void prepare() {
- flush();
- }
-
- /**
- * Finish up after a collection.
- */
- public void release() {}
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/policy/ExplicitFreeListSpace.java b/vmkit/mmtk/java/src/org/mmtk/policy/ExplicitFreeListSpace.java
deleted file mode 100644
index 9f3447c..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/policy/ExplicitFreeListSpace.java
+++ /dev/null
@@ -1,175 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.policy;
-
-import org.mmtk.plan.TransitiveClosure;
-import org.mmtk.utility.heap.*;
-import org.mmtk.utility.Constants;
-
-import org.vmmagic.pragma.*;
-import org.vmmagic.unboxed.*;
-
-/**
- * Each instance of this class corresponds to one *space*.
- * Each of the instance methods of this class may be called by any
- * thread (i.e. synchronization must be explicit in any instance or
- * class method). This contrasts with the MarkSweepLocal, where
- * instances correspond to *plan* instances and therefore to kernel
- * threads. Thus unlike this class, synchronization is not necessary
- * in the instance methods of MarkSweepLocal.
- */
-@Uninterruptible
-public final class ExplicitFreeListSpace extends SegregatedFreeListSpace implements Constants {
-
- /****************************************************************************
- *
- * Class variables
- */
- public static final int LOCAL_GC_BITS_REQUIRED = 0;
- public static final int GLOBAL_GC_BITS_REQUIRED = 0;
- public static final int GC_HEADER_WORDS_REQUIRED = 0;
-
- /****************************************************************************
- *
- * Initialization
- */
-
- /**
- * The caller specifies the region of virtual memory to be used for
- * this space. If this region conflicts with an existing space,
- * then the constructor will fail.
- *
- * @param name The name of this space (used when printing error messages etc)
- * @param pageBudget The number of pages this space may consume
- * before consulting the plan
- * @param vmRequest An object describing the virtual memory requested.
- */
- public ExplicitFreeListSpace(String name, int pageBudget, VMRequest vmRequest) {
- super(name, pageBudget, 0, vmRequest);
- }
-
- /**
- * Should SegregatedFreeListSpace manage a side bitmap to keep track of live objects?
- */
- @Inline
- protected boolean maintainSideBitmap() {
- return true;
- }
-
- /**
- * Do we need to preserve free lists as we move blocks around.
- */
- @Inline
- protected boolean preserveFreeList() {
- return false;
- }
-
- /****************************************************************************
- *
- * Collection
- */
-
- /**
- * Prepare the next block in the free block list for use by the free
- * list allocator. In the case of lazy sweeping this involves
- * sweeping the available cells. <b>The sweeping operation must
- * ensure that cells are pre-zeroed</b>, as this method must return
- * pre-zeroed cells.
- *
- * @param block The block to be prepared for use
- * @param sizeClass The size class of the block
- * @return The address of the first pre-zeroed cell in the free list
- * for this block, or zero if there are no available cells.
- */
- protected Address advanceToBlock(Address block, int sizeClass) {
- return makeFreeList(block, sizeClass);
- }
-
- /**
- * Notify that a new block has been installed. This is to ensure that
- * appropriate collection state can be initialized for the block
- *
- * @param block The new block
- * @param sizeClass The block's sizeclass.
- */
- protected void notifyNewBlock(Address block, int sizeClass) {
- clearLiveBits(block, sizeClass);
- }
-
- /**
- * Free an object.
- *
- * @param object The object to be freed.
- */
- @Inline
- public void free(ObjectReference object) {
- clearLiveBit(object);
- }
-
- /**
- * Prepare for a new collection increment.
- */
- public void prepare() {
- flushAvailableBlocks();
- }
-
- /**
- * A new collection increment has completed.
- */
- public void release() {
- sweepConsumedBlocks(true);
- }
-
- /**
- * Release an allocated page or pages
- *
- * @param start The address of the start of the page or pages
- */
- @Inline
- public void release(Address start) {
- ((FreeListPageResource) pr).releasePages(start);
- }
-
- /****************************************************************************
- *
- * Object processing and tracing
- */
-
- /**
- * Trace a reference to an object under a mark sweep collection
- * policy. If the object header is not already marked, mark the
- * object in either the bitmap or by moving it off the treadmill,
- * and enqueue the object for subsequent processing. The object is
- * marked as (an atomic) side-effect of checking whether already
- * marked.
- *
- * @param object The object to be traced.
- * @return The object (there is no object forwarding in this
- * collector, so we always return the same object: this could be a
- * void method but for compliance to a more general interface).
- */
- @Inline
- public ObjectReference traceObject(TransitiveClosure trace, ObjectReference object) {
- return object;
- }
-
- /**
- *
- * @param object The object in question
- * @return True if this object is known to be live (i.e. it is marked)
- */
- @Inline
- public boolean isLive(ObjectReference object) {
- return liveBitSet(object);
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/policy/ExplicitLargeObjectSpace.java b/vmkit/mmtk/java/src/org/mmtk/policy/ExplicitLargeObjectSpace.java
deleted file mode 100644
index d35d448..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/policy/ExplicitLargeObjectSpace.java
+++ /dev/null
@@ -1,193 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.policy;
-
-import org.mmtk.plan.TransitiveClosure;
-import org.mmtk.utility.heap.FreeListPageResource;
-import org.mmtk.utility.heap.VMRequest;
-import org.mmtk.utility.DoublyLinkedList;
-
-import org.mmtk.vm.VM;
-
-import org.vmmagic.pragma.*;
-import org.vmmagic.unboxed.*;
-
-/**
- * Each instance of this class corresponds to one explicitly managed
- * large object space.
- */
-@Uninterruptible
-public final class ExplicitLargeObjectSpace extends BaseLargeObjectSpace {
-
- /****************************************************************************
- *
- * Instance variables
- */
- private final DoublyLinkedList cells;
-
- /****************************************************************************
- *
- * Initialization
- */
-
- /**
- * The caller specifies the region of virtual memory to be used for
- * this space. If this region conflicts with an existing space,
- * then the constructor will fail.
- *
- * @param name The name of this space (used when printing error messages etc)
- * @param pageBudget The number of pages this space may consume
- * before consulting the plan
- * @param vmRequest An object describing the virtual memory requested.
- */
- public ExplicitLargeObjectSpace(String name, int pageBudget, VMRequest vmRequest) {
- super(name, pageBudget, vmRequest);
- cells = new DoublyLinkedList(LOG_BYTES_IN_PAGE, true);
- }
-
-
- /****************************************************************************
- *
- * Collection
- */
-
- /**
- * Prepare for a new collection increment.
- */
- public void prepare() {
- }
-
- /**
- * A new collection increment has completed.
- */
- public void release() {
- }
-
- /**
- * Release a group of pages that were allocated together.
- *
- * @param first The first page in the group of pages that were
- * allocated together.
- */
- @Inline
- public void release(Address first) {
- ((FreeListPageResource) pr).releasePages(first);
- }
-
- /**
- * Perform any required initialization of the GC portion of the header.
- *
- * @param object the object ref to the storage to be initialized
- * @param alloc is this initialization occuring due to (initial) allocation
- * (true) or due to copying (false)?
- */
- @Inline
- public void initializeHeader(ObjectReference object, boolean alloc) {
- Address cell = VM.objectModel.objectStartRef(object);
- cells.add(DoublyLinkedList.midPayloadToNode(cell));
- }
-
- /****************************************************************************
- *
- * Object processing and tracing
- */
-
- /**
- * Trace a reference to an object under a mark sweep collection
- * policy. If the object header is not already marked, mark the
- * object in either the bitmap or by moving it off the treadmill,
- * and enqueue the object for subsequent processing. The object is
- * marked as (an atomic) side-effect of checking whether already
- * marked.
- *
- * @param trace The trace being conducted.
- * @param object The object to be traced.
- * @return The object (there is no object forwarding in this
- * collector, so we always return the same object: this could be a
- * void method but for compliance to a more general interface).
- */
- @Inline
- public ObjectReference traceObject(TransitiveClosure trace, ObjectReference object) {
- return object;
- }
-
- /**
- * @param object The object in question
- * @return True if this object is known to be live (i.e. it is marked)
- */
- @Inline
- public boolean isLive(ObjectReference object) {
- return true;
- }
-
- /**
- * Return the size of the per-superpage header required by this
- * system. In this case it is just the underlying superpage header
- * size.
- *
- * @return The size of the per-superpage header required by this
- * system.
- */
- @Inline
- protected int superPageHeaderSize() {
- return DoublyLinkedList.headerSize();
- }
-
- /**
- * Return the size of the per-cell header for cells of a given class
- * size.
- *
- * @return The size of the per-cell header for cells of a given class
- * size.
- */
- @Inline
- protected int cellHeaderSize() { return 0; }
-
- /**
- * Sweep through all the objects in this space.
- *
- * @param sweeper The sweeper callback to use.
- */
- @Inline
- public void sweep(Sweeper sweeper) {
- Address cell = cells.getHead();
- while (!cell.isZero()) {
- Address next = cells.getNext(cell);
- ObjectReference obj = VM.objectModel.getObjectFromStartAddress(cell.plus(DoublyLinkedList.headerSize()));
- if (sweeper.sweepLargeObject(obj)) {
- free(obj);
- }
- cell = next;
- }
- }
-
- /**
- * Free an object
- *
- * @param object The object to be freed.
- */
- @Inline
- public void free(ObjectReference object) {
- Address cell = getSuperPage(VM.objectModel.refToAddress(object));
- cells.remove(cell);
- release(cell);
- }
-
- /**
- * A callback used to perform sweeping of the large object space.
- */
- @Uninterruptible
- public abstract static class Sweeper {
- public abstract boolean sweepLargeObject(ObjectReference object);
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/policy/ImmortalLocal.java b/vmkit/mmtk/java/src/org/mmtk/policy/ImmortalLocal.java
deleted file mode 100644
index 82daf57..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/policy/ImmortalLocal.java
+++ /dev/null
@@ -1,37 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.policy;
-
-import org.mmtk.utility.alloc.BumpPointer;
-
-import org.vmmagic.pragma.*;
-
-/**
- * This class implements unsynchronized (local) elements of an
- * immortal space. Allocation is via the bump pointer
- * (@see BumpPointer).
- *
- * @see BumpPointer
- * @see ImmortalSpace
- */
-@Uninterruptible public final class ImmortalLocal extends BumpPointer {
-
- /**
- * Constructor
- *
- * @param space The space to bump point into.
- */
- public ImmortalLocal(ImmortalSpace space) {
- super(space, true);
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/policy/ImmortalSpace.java b/vmkit/mmtk/java/src/org/mmtk/policy/ImmortalSpace.java
deleted file mode 100644
index d1fca7b..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/policy/ImmortalSpace.java
+++ /dev/null
@@ -1,172 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.policy;
-
-import org.mmtk.plan.Plan;
-import org.mmtk.plan.TransitiveClosure;
-import org.mmtk.utility.heap.MonotonePageResource;
-import org.mmtk.utility.heap.VMRequest;
-import org.mmtk.utility.Constants;
-import org.mmtk.utility.HeaderByte;
-
-import org.mmtk.vm.VM;
-
-import org.vmmagic.unboxed.*;
-import org.vmmagic.pragma.*;
-
-/**
- * This class implements tracing for a simple immortal collection
- * policy. Under this policy all that is required is for the
- * "collector" to propogate marks in a liveness trace. It does not
- * actually collect. This class does not hold any state, all methods
- * are static.
- */
-@Uninterruptible public final class ImmortalSpace extends Space
- implements Constants {
-
- /****************************************************************************
- *
- * Class variables
- */
- static final byte GC_MARK_BIT_MASK = 1;
- private static final int META_DATA_PAGES_PER_REGION = CARD_META_PAGES_PER_REGION;
-
- /****************************************************************************
- *
- * Instance variables
- */
- private byte markState = 0; // when GC off, the initialization value
-
- /****************************************************************************
- *
- * Initialization
- */
- /**
- * The caller specifies the region of virtual memory to be used for
- * this space. If this region conflicts with an existing space,
- * then the constructor will fail.
- *
- * @param name The name of this space (used when printing error messages etc)
- * @param pageBudget The number of pages this space may consume
- * before consulting the plan
- * @param vmRequest An object describing the virtual memory requested.
- */
- public ImmortalSpace(String name, int pageBudget, VMRequest vmRequest) {
- super(name, false, true, vmRequest);
- if (vmRequest.isDiscontiguous()) {
- pr = new MonotonePageResource(pageBudget, this, META_DATA_PAGES_PER_REGION);
- } else {
- pr = new MonotonePageResource(pageBudget, this, start, extent, META_DATA_PAGES_PER_REGION);
- }
- }
-
- /** @return the current mark state */
- @Inline
- public Word getMarkState() { return Word.fromIntZeroExtend(markState); }
-
- /****************************************************************************
- *
- * Object header manipulations
- */
-
- /**
- * Initialize the object header post-allocation. We need to set the mark state
- * correctly and set the logged bit if necessary.
- *
- * @param object The newly allocated object instance whose header we are initializing
- */
- public void initializeHeader(ObjectReference object) {
- byte oldValue = VM.objectModel.readAvailableByte(object);
- byte newValue = (byte) ((oldValue & GC_MARK_BIT_MASK) | markState);
- if (HeaderByte.NEEDS_UNLOGGED_BIT) newValue |= HeaderByte.UNLOGGED_BIT;
- VM.objectModel.writeAvailableByte(object, newValue);
- }
-
- /**
- * Used to mark boot image objects during a parallel scan of objects during GC
- * Returns true if marking was done.
- */
- @Inline
- private static boolean testAndMark(ObjectReference object, byte value) {
- Word oldValue;
- do {
- oldValue = VM.objectModel.prepareAvailableBits(object);
- byte markBit = (byte) (oldValue.toInt() & GC_MARK_BIT_MASK);
- if (markBit == value) return false;
- } while (!VM.objectModel.attemptAvailableBits(object, oldValue,
- oldValue.xor(Word.fromIntZeroExtend(GC_MARK_BIT_MASK))));
- return true;
- }
-
- /**
- * Trace a reference to an object under an immortal collection
- * policy. If the object is not already marked, enqueue the object
- * for subsequent processing. The object is marked as (an atomic)
- * side-effect of checking whether already marked.
- *
- * @param trace The trace being conducted.
- * @param object The object to be traced.
- */
- @Inline
- public ObjectReference traceObject(TransitiveClosure trace, ObjectReference object) {
- if (testAndMark(object, markState))
- trace.processNode(object);
- return object;
- }
-
- /**
- * Prepare for a new collection increment. For the immortal
- * collector we must flip the state of the mark bit between
- * collections.
- */
- public void prepare() {
- markState = (byte) (GC_MARK_BIT_MASK - markState);
- }
-
- public void release() {}
-
- /**
- * Release an allocated page or pages. In this case we do nothing
- * because we only release pages enmasse.
- *
- * @param start The address of the start of the page or pages
- */
- @Inline
- public void release(Address start) {
- if (VM.VERIFY_ASSERTIONS)
- VM.assertions._assert(false); // this policy only releases pages enmasse
- }
-
- @Inline
- public boolean isLive(ObjectReference object) {
- return true;
- }
-
- /**
- * Returns if the object in question is currently thought to be reachable.
- * This is done by comparing the mark bit to the current mark state. For the
- * immortal collector reachable and live are different, making this method
- * necessary.
- *
- * @param object The address of an object in immortal space to test
- * @return True if <code>ref</code> may be a reachable object (e.g., having
- * the current mark state). While all immortal objects are live,
- * some may be unreachable.
- */
- public boolean isReachable(ObjectReference object) {
- if (Plan.SCAN_BOOT_IMAGE && this == Plan.vmSpace)
- return true; // ignore boot image "reachabilty" if we're not tracing it
- else
- return (VM.objectModel.readAvailableByte(object) & GC_MARK_BIT_MASK) == markState;
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/policy/LargeObjectLocal.java b/vmkit/mmtk/java/src/org/mmtk/policy/LargeObjectLocal.java
deleted file mode 100644
index be7a136..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/policy/LargeObjectLocal.java
+++ /dev/null
@@ -1,110 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.policy;
-
-import org.mmtk.utility.alloc.LargeObjectAllocator;
-import org.mmtk.utility.gcspy.drivers.TreadmillDriver;
-import org.mmtk.utility.Constants;
-
-import org.vmmagic.pragma.*;
-
-/**
- * Each instance of this class is intended to provide fast,
- * unsynchronized access to a treadmill. Therefore instances must not
- * be shared across truely concurrent threads (CPUs). Rather, one or
- * more instances of this class should be bound to each CPU. The
- * shared VMResource used by each instance is the point of global
- * synchronization, and synchronization only occurs at the granularity
- * of aquiring (and releasing) chunks of memory from the VMResource.
- *
- * If there are C CPUs and T TreadmillSpaces, there must be C X T
- * instances of this class, one for each CPU, TreadmillSpace pair.
- */
-@Uninterruptible
-public final class LargeObjectLocal extends LargeObjectAllocator implements Constants {
-
- /****************************************************************************
- *
- * Class variables
- */
-
- /****************************************************************************
- *
- * Instance variables
- */
-
- /****************************************************************************
- *
- * Initialization
- */
-
- /**
- * Constructor
- *
- * @param space The treadmill space to which this thread instance is
- * bound.
- */
- public LargeObjectLocal(BaseLargeObjectSpace space) {
- super(space);
- }
-
- /****************************************************************************
- *
- * Allocation
- */
-
- /****************************************************************************
- *
- * Collection
- */
-
- /**
- * Prepare for a collection. Clear the treadmill to-space head and
- * prepare the collector. If paranoid, perform a sanity check.
- */
- public void prepare(boolean fullHeap) {
- }
-
- /**
- * Finish up after a collection.
- */
- public void release(boolean fullHeap) {
- }
-
- /****************************************************************************
- *
- * Miscellaneous size-related methods
- */
-
- /**
- * Gather data for GCSpy from the nursery
- * @param event the gc event
- * @param losDriver the GCSpy space driver
- */
- public void gcspyGatherData(int event, TreadmillDriver losDriver) {
- // TODO: assumes single threaded
- // TODO: assumes non-explit LOS
- ((LargeObjectSpace)space).getTreadmill().gcspyGatherData(event, losDriver);
- }
-
- /**
- * Gather data for GCSpy for an older space
- * @param event the gc event
- * @param losDriver the GCSpy space driver
- * @param tospace gather from tospace?
- */
- public void gcspyGatherData(int event, TreadmillDriver losDriver, boolean tospace) {
- // TODO: assumes single threaded
- ((LargeObjectSpace)space).getTreadmill().gcspyGatherData(event, losDriver, tospace);
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/policy/LargeObjectSpace.java b/vmkit/mmtk/java/src/org/mmtk/policy/LargeObjectSpace.java
deleted file mode 100644
index 665854c..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/policy/LargeObjectSpace.java
+++ /dev/null
@@ -1,284 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.policy;
-
-import org.mmtk.plan.TransitiveClosure;
-import org.mmtk.utility.heap.FreeListPageResource;
-import org.mmtk.utility.heap.VMRequest;
-import org.mmtk.utility.HeaderByte;
-import org.mmtk.utility.Treadmill;
-
-import org.mmtk.vm.VM;
-
-import org.vmmagic.pragma.*;
-import org.vmmagic.unboxed.*;
-
-/**
- * Each instance of this class corresponds to one explicitly managed
- * large object space.
- */
-@Uninterruptible
-public final class LargeObjectSpace extends BaseLargeObjectSpace {
-
- /****************************************************************************
- *
- * Class variables
- */
- public static final int LOCAL_GC_BITS_REQUIRED = 2;
- public static final int GLOBAL_GC_BITS_REQUIRED = 0;
- private static final byte MARK_BIT = 1; // ...01
- private static final byte NURSERY_BIT = 2; // ...10
- private static final byte LOS_BIT_MASK = 3; // ...11
-
- /****************************************************************************
- *
- * Instance variables
- */
- private byte markState;
- private boolean inNurseryGC;
- private final Treadmill treadmill;
-
- /****************************************************************************
- *
- * Initialization
- */
-
- /**
- * The caller specifies the region of virtual memory to be used for
- * this space. If this region conflicts with an existing space,
- * then the constructor will fail.
- *
- * @param name The name of this space (used when printing error messages etc)
- * @param pageBudget The number of pages this space may consume
- * before consulting the plan
- * @param vmRequest An object describing the virtual memory requested.
- */
- public LargeObjectSpace(String name, int pageBudget, VMRequest vmRequest) {
- super(name, pageBudget, vmRequest);
- treadmill = new Treadmill(LOG_BYTES_IN_PAGE, true);
- markState = 0;
- }
-
- /****************************************************************************
- *
- * Collection
- */
-
- /**
- * Prepare for a new collection increment. For the mark-sweep
- * collector we must flip the state of the mark bit between
- * collections.
- */
- public void prepare(boolean fullHeap) {
- if (fullHeap) {
- if (VM.VERIFY_ASSERTIONS) {
- VM.assertions._assert(treadmill.fromSpaceEmpty());
- }
- markState = (byte) (MARK_BIT - markState);
- }
- treadmill.flip(fullHeap);
- inNurseryGC = !fullHeap;
- }
-
- /**
- * A new collection increment has completed. For the mark-sweep
- * collector this means we can perform the sweep phase.
- */
- public void release(boolean fullHeap) {
- // sweep the large objects
- sweepLargePages(true); // sweep the nursery
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(treadmill.nurseryEmpty());
- if (fullHeap) sweepLargePages(false); // sweep the mature space
- }
-
- /**
- * Sweep through the large pages, releasing all superpages on the
- * "from space" treadmill.
- */
- private void sweepLargePages(boolean sweepNursery) {
- while (true) {
- Address cell = sweepNursery ? treadmill.popNursery() : treadmill.pop();
- if (cell.isZero()) break;
- release(getSuperPage(cell));
- }
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(sweepNursery ? treadmill.nurseryEmpty() : treadmill.fromSpaceEmpty());
- }
-
- /**
- * Release a group of pages that were allocated together.
- *
- * @param first The first page in the group of pages that were
- * allocated together.
- */
- @Inline
- public void release(Address first) {
- ((FreeListPageResource) pr).releasePages(first);
- }
-
- /****************************************************************************
- *
- * Object processing and tracing
- */
-
- /**
- * Trace a reference to an object under a mark sweep collection
- * policy. If the object header is not already marked, mark the
- * object in either the bitmap or by moving it off the treadmill,
- * and enqueue the object for subsequent processing. The object is
- * marked as (an atomic) side-effect of checking whether already
- * marked.
- *
- * @param trace The trace being conducted.
- * @param object The object to be traced.
- * @return The object (there is no object forwarding in this
- * collector, so we always return the same object: this could be a
- * void method but for compliance to a more general interface).
- */
- @Inline
- public ObjectReference traceObject(TransitiveClosure trace, ObjectReference object) {
- boolean nurseryObject = isInNursery(object);
- if (!inNurseryGC || nurseryObject) {
- if (testAndMark(object, markState)) {
- internalMarkObject(object, nurseryObject);
- trace.processNode(object);
- }
- }
- return object;
- }
-
- /**
- * @param object The object in question
- * @return True if this object is known to be live (i.e. it is marked)
- */
- @Inline
- public boolean isLive(ObjectReference object) {
- return testMarkBit(object, markState);
- }
-
- /**
- * An object has been marked (identifiged as live). Large objects
- * are added to the to-space treadmill, while all other objects will
- * have a mark bit set in the superpage header.
- *
- * @param object The object which has been marked.
- */
- @Inline
- private void internalMarkObject(ObjectReference object, boolean nurseryObject) {
-
- Address cell = VM.objectModel.objectStartRef(object);
- Address node = Treadmill.midPayloadToNode(cell);
- treadmill.copy(node, nurseryObject);
- }
-
- /****************************************************************************
- *
- * Header manipulation
- */
-
- /**
- * Perform any required initialization of the GC portion of the header.
- *
- * @param object the object ref to the storage to be initialized
- * @param alloc is this initialization occuring due to (initial) allocation
- * (true) or due to copying (false)?
- */
- @Inline
- public void initializeHeader(ObjectReference object, boolean alloc) {
- byte oldValue = VM.objectModel.readAvailableByte(object);
- byte newValue = (byte) ((oldValue & ~LOS_BIT_MASK) | markState);
- if (alloc) newValue |= NURSERY_BIT;
- if (HeaderByte.NEEDS_UNLOGGED_BIT) newValue |= HeaderByte.UNLOGGED_BIT;
- VM.objectModel.writeAvailableByte(object, newValue);
- Address cell = VM.objectModel.objectStartRef(object);
- treadmill.addToTreadmill(Treadmill.midPayloadToNode(cell), alloc);
- }
-
- /**
- * Atomically attempt to set the mark bit of an object. Return true
- * if successful, false if the mark bit was already set.
- *
- * @param object The object whose mark bit is to be written
- * @param value The value to which the mark bit will be set
- */
- @Inline
- private boolean testAndMark(ObjectReference object, byte value) {
- Word oldValue;
- do {
- oldValue = VM.objectModel.prepareAvailableBits(object);
- byte markBit = (byte) (oldValue.toInt() & (inNurseryGC ? LOS_BIT_MASK : MARK_BIT));
- if (markBit == value) return false;
- } while (!VM.objectModel.attemptAvailableBits(object, oldValue,
- oldValue.and(Word.fromIntZeroExtend(LOS_BIT_MASK).not()).or(Word.fromIntZeroExtend(value))));
- return true;
- }
-
- /**
- * Return true if the mark bit for an object has the given value.
- *
- * @param object The object whose mark bit is to be tested
- * @param value The value against which the mark bit will be tested
- * @return True if the mark bit for the object has the given value.
- */
- @Inline
- private boolean testMarkBit(ObjectReference object, byte value) {
- return (byte) (VM.objectModel.readAvailableByte(object) & MARK_BIT) == value;
- }
-
- /**
- * Return true if the object is in the logical nursery
- *
- * @param object The object whose status is to be tested
- * @return True if the object is in the logical nursery
- */
- @Inline
- private boolean isInNursery(ObjectReference object) {
- return (byte)(VM.objectModel.readAvailableByte(object) & NURSERY_BIT) == NURSERY_BIT;
- }
-
- /**
- * Return the size of the per-superpage header required by this
- * system. In this case it is just the underlying superpage header
- * size.
- *
- * @return The size of the per-superpage header required by this
- * system.
- */
- @Inline
- protected int superPageHeaderSize() {
- return Treadmill.headerSize();
- }
-
- /**
- * Return the size of the per-cell header for cells of a given class
- * size.
- *
- * @return The size of the per-cell header for cells of a given class
- * size.
- */
- @Inline
- protected int cellHeaderSize() {
- return 0;
- }
-
- /**
- * This is the treadmill used by the large object space.
- *
- * Note that it depends on the specific local in use whether this
- * is being used.
- *
- * @return The treadmill associated with this large object space.
- */
- public Treadmill getTreadmill() {
- return this.treadmill;
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/policy/MarkCompactCollector.java b/vmkit/mmtk/java/src/org/mmtk/policy/MarkCompactCollector.java
deleted file mode 100644
index 597fc08..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/policy/MarkCompactCollector.java
+++ /dev/null
@@ -1,544 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.policy;
-
-import org.mmtk.plan.markcompact.MC;
-import org.mmtk.utility.Log;
-import org.mmtk.utility.alloc.Allocator;
-import org.mmtk.utility.alloc.BumpPointer;
-import org.mmtk.vm.VM;
-import org.vmmagic.pragma.Inline;
-import org.vmmagic.pragma.Uninterruptible;
-import org.vmmagic.unboxed.Address;
-import org.vmmagic.unboxed.Extent;
-import org.vmmagic.unboxed.ObjectReference;
-
-/**
- * This class implements unsynchronized (local) per-collector-thread elements of a
- * sliding mark-compact collector.
- *
- * Specifically, this class provides the methods that
- * - Calculate the forwarding pointers for heap objects, in a linear pass over
- * (part of) the heap
- * - Performs the compaction pass over the heap.
- *
- * Each collector thread maintains a private list of the pages that it compacts.
- * If it runs out of work during the calculateForwardingPointers pass, it requests
- * a new region from the global MarkCompactSpace. Regions compacted by a collector
- * remain local to the collector.
- *
- * @see MarkCompactSpace
- * @see MarkCompactLocal
- */
-@Uninterruptible
-public final class MarkCompactCollector {
-
- static final boolean VERBOSE = false;
-
- static final boolean VERY_VERBOSE = VERBOSE && false;
-
- private final MarkCompactSpace space;
-
- /**
- * This collector's work list
- */
- private Address regions = Address.zero();
-
- private final FromCursor fromCursor = new FromCursor();
- private final ToCursor toCursor = new ToCursor();
-
- /**
- * Constructor
- *
- * @param space The space to bump point into.
- */
- public MarkCompactCollector(MarkCompactSpace space) {
- this.space = space;
- }
-
- /* ********************************************************************************
- *
- * Cursor classes
- *
- */
-
- /**
- * Both the 'compact' and 'calculate' phases can be thought of as sweeping
- * a pair of cursors across a linked list of regions. Each cursor requires
- * maintaining pointers to the current region, the current address and the end of
- * the region. The regionCursor class maintains these 3 pointers, while the
- * subclasses ToCursor and FromCursor provide methods specific to the
- * read and write pointers.
- */
- @Uninterruptible
- private abstract static class RegionCursor {
-
- /** Name of the cursor - for debugging messages */
- private final String name;
-
- /**
- * The current region, or zero if the cursor is invalid (eg after advancing
- * past the end of the current work list
- */
- protected Address region;
-
- /**
- * The limit of the current region. When reading a populated region, this is the
- * address of the last used byte. When writing to a fresh region, this is the last
- * byte in the region.
- */
- protected Address limit;
-
- /** The current address */
- protected Address cursor;
-
- /**
- * @param name The name of the region - for debugging messages.
- */
- public RegionCursor(String name) {
- this.name = name;
- }
-
- /**
- * Hook to allow subclasses to initialize the cursor in different ways.
- *
- * @param region The region to be processed.
- */
- abstract void init(Address region);
-
- /**
- * Assert that the cursor is within the bounds of the region. Calls to this
- * must be guarded by {@code if (VM.VERIFY_ASSERTIONS)}
- */
- protected void assertCursorInBounds() {
- VM.assertions._assert(!region.isZero());
- VM.assertions._assert(cursor.GE(BumpPointer.getDataStart(region)),
- "Cursor is below start of region");
- VM.assertions._assert(cursor.LE(limit),"Cursor beyond end of region");
- }
-
- /**
- * Increment the cursor.
- * @param size Bytes to increment by
- */
- void inc(int size) {
- this.cursor = cursor.plus(size);
- if (VM.VERIFY_ASSERTIONS) assertCursorInBounds();
- }
-
- /**
- * Increment the cursor to a specific address
- * @param cursor Destination address
- */
- public void incTo(Address cursor) {
- if (VM.VERIFY_ASSERTIONS) assertCursorInBounds();
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(cursor.GE(this.cursor));
- this.cursor = cursor;
- }
-
- /**
- * @param other Other region
- * @return {@code true} if this cursor points to the same region as {@code other}
- */
- boolean sameRegion(RegionCursor other) {
- return region.EQ(other.getRegion());
- }
-
- /**
- * @param size Size in bytes
- * @return {@code true} if {@code size} bytes are available in the current region
- */
- boolean isAvailable(int size) {
- return cursor.plus(size).LE(limit);
- }
-
- /**
- * @return The current cursor
- */
- public Address get() {
- return cursor;
- }
-
- /**
- * @return The current region pointer
- */
- public Address getRegion() {
- return region;
- }
-
- /**
- * @return The current region limit
- */
- public Address getLimit() {
- return limit;
- }
-
- /**
- * Follow the linked-list of regions to the next region.
- */
- void advanceToNextRegion() {
- Address nextRegion = MarkCompactLocal.getNextRegion(region);
- if (nextRegion.isZero()) {
- region = Address.zero();
- } else {
- init(nextRegion);
- if (VM.VERIFY_ASSERTIONS) assertCursorInBounds();
- }
- }
-
- /**
- * @return {@code true} if we haven't advanced beyond the end of the region list
- */
- boolean isValid() {
- return !region.isZero();
- }
-
- /**
- * @param ref The object in question
- * @return {@code true} if the object's start address is in this region
- */
- @Inline
- boolean isInRegion(ObjectReference ref) {
- Address addr = VM.objectModel.refToAddress(ref);
- return addr.GE(BumpPointer.getDataStart(region)) && addr.LE(limit);
- }
-
- /**
- * Print the cursor - for debugging
- */
- void print() {
- Log.write(name); Log.write(" cursor:");
- Log.write(" region="); Log.write(region);
- Log.write(" limit="); Log.write(limit);
- Log.write(" cursor="); Log.write(cursor);
- Log.writeln();
-
- }
- }
-
- /**
- * Subclass for the read-only cursor that leads the scan of regions.
- */
- @Uninterruptible
- private static final class FromCursor extends RegionCursor {
- public FromCursor() {
- super("from");
- }
-
- /**
- * Initialize the cursor - the limit is the end of the allocated data
- */
- @Override
- void init(Address region) {
- if (VM.VERIFY_ASSERTIONS) BumpPointer.checkRegionMetadata(region);
- this.region = region;
- this.cursor = MarkCompactLocal.getDataStart(region);
- this.limit = MarkCompactLocal.getDataEnd(region);
- }
-
- /**
- * Advance from the cursor to the start of the next object.
- * @return The object reference of the next object.
- */
- @Inline
- ObjectReference advanceToObject() {
- ObjectReference current = VM.objectModel.getObjectFromStartAddress(cursor);
- cursor = VM.objectModel.objectStartRef(current);
- if (VM.VERIFY_ASSERTIONS) {
- Address lowBound = BumpPointer.getDataStart(region);
- VM.assertions._assert(cursor.GE(lowBound) && cursor.LE(limit),"Cursor outside region");
- }
- return current;
- }
-
- /**
- * Advance the cursor to the end of the given object.
- * @return The object reference of the next object.
- */
- @Inline
- void advanceToObjectEnd(ObjectReference current) {
- cursor = VM.objectModel.getObjectEndAddress(current);
- if (VM.VERIFY_ASSERTIONS) assertCursorInBounds();
- }
-
- /**
- * Advance the cursor either to the next region in the list,
- * or to a new region allocated from the global list.
- * @param m
- */
- void advanceToNextForwardableRegion(MarkCompactSpace space) {
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(get().EQ(getLimit()));
- Address nextRegion = BumpPointer.getNextRegion(region);
- if (nextRegion.isZero()) {
- nextRegion = space.getNextRegion();
- if (nextRegion.isZero()) {
- region = Address.zero();
- return;
- }
- MarkCompactLocal.setNextRegion(region,nextRegion);
- MarkCompactLocal.clearNextRegion(nextRegion);
- }
- init(nextRegion);
- if (VM.VERIFY_ASSERTIONS) assertCursorInBounds();
- }
-
- /**
- * Override the superclass with an additional assertion - we only advance
- * when we have read to the end, and the cursor must point *precisely*
- * to the last allocated byte in the region.
- */
- @Override
- void advanceToNextRegion() {
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(get().EQ(getLimit()));
- super.advanceToNextRegion();
- }
-
- /**
- * @return {@code true} if there are more objects in this region
- */
- boolean hasMoreObjects() {
- return cursor.LT(limit);
- }
- }
-
- /**
- * Subclass for the read-only cursor that follows the 'from' cursor,
- * writing or calculating the position of copied objects
- */
- @Uninterruptible
- private static final class ToCursor extends RegionCursor {
- public ToCursor() {
- super("to");
- }
-
- /**
- * Initialize the cursor to a given region. The limit is the limit of
- * available space in the region.
- */
- @Override
- void init(Address region) {
- if (VM.VERIFY_ASSERTIONS) BumpPointer.checkRegionMetadata(region);
- this.region = region;
- this.cursor = MarkCompactLocal.getDataStart(region);
- this.limit = MarkCompactLocal.getRegionLimit(region);
- if (VM.VERIFY_ASSERTIONS) assertCursorInBounds();
- }
-
- /**
- * Update the metadata of the current region with the current value
- * of the cursor. Zero the region from here to the end.
- */
- void finish() {
- if (VM.VERIFY_ASSERTIONS) assertCursorInBounds();
- Extent zeroBytes = limit.diff(cursor).toWord().toExtent();
- VM.memory.zero(cursor, zeroBytes);
- MarkCompactLocal.setDataEnd(region, cursor);
- MarkCompactLocal.checkRegionMetadata(region);
- }
-
- /**
- * Terminate the list of regions here.
- * @return The address of the (old) next region in the list.
- */
- Address snip() {
- Address nextRegion = BumpPointer.getNextRegion(region);
- BumpPointer.clearNextRegion(region);
- finish();
- return nextRegion;
- }
-
- /**
- * Copy an object to an address within this cursor's region.
- * @param from The source object
- * @param to The target object
- */
- @Inline
- void copy(ObjectReference from, ObjectReference to) {
- if (VM.VERIFY_ASSERTIONS) {
- VM.assertions._assert(MarkCompactSpace.getForwardingPointer(from).toAddress().EQ(to.toAddress()));
- VM.assertions._assert(cursor.GT(region) && cursor.LE(limit));
- }
- Address savedCursor = Address.zero();
- if (VM.VERIFY_ASSERTIONS) savedCursor = cursor;
- cursor = VM.objectModel.copyTo(from, to, cursor);
- if (VM.VERIFY_ASSERTIONS) {
- if (cursor.LT(BumpPointer.getDataStart(region)) || cursor.GT(limit)) {
- Log.write("Copy of "); Log.write(from);
- Log.write(" to "); Log.write(to);
- Log.write(" puts cursor at "); Log.write(cursor);
- Log.write(" (was: "); Log.write(savedCursor);
- Log.writeln(")");
- }
- VM.assertions._assert(cursor.GT(region) && cursor.LE(limit));
- }
- MarkCompactSpace.setForwardingPointer(to, ObjectReference.nullReference());
- if (VM.VERIFY_ASSERTIONS)
- VM.assertions._assert(VM.objectModel.getObjectEndAddress(to).LE(limit));
- }
-
- /**
- * Move to the next region, updating the metadata with the current 'write' state.
- */
- void finishAndAdvanceToNextRegion() {
- finish();
- advanceToNextRegion();
- }
-
- /**
- * Move to the next region, in read-only mode. Add the assertion of validity,
- * since we shouldn't be able to fall off the end of the list while writing.
- */
- @Override
- void advanceToNextRegion() {
- super.advanceToNextRegion();
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(isValid());
- }
- }
-
- /* ***************************************************************************************** */
-
- /**
- * Perform a linear scan through the objects allocated by this bump pointer,
- * calculating where each live object will be post collection.
- *
- * We maintain two cursors, {@code fromCursor} and {@code toCursor}, and simulate
- * copying live objects from the former to the latter. Initially, the cursors
- * point to the first region in this collector's local list, and increment in
- * lockstep until the first dead object is encountered. After that, the to cursor
- * trails the from cursor.
- *
- * The outer loop advances the 'from' pointer
- */
- public void calculateForwardingPointers() {
- if (regions.isZero()) {
- regions = space.getNextRegion();
- }
-
- if (regions.isZero())
- return;
-
- fromCursor.init(regions);
- toCursor.init(regions);
-
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(true);
-
- /* Loop through active regions or until the last region */
- while (fromCursor.isValid()) {
- if (VERBOSE) {
- fromCursor.print();
- toCursor.print();
- }
-
- /* Loop through the objects in the current 'from' region */
- while (fromCursor.hasMoreObjects()) {
- ObjectReference current = fromCursor.advanceToObject();
- fromCursor.advanceToObjectEnd(current);
-
- if (MarkCompactSpace.toBeCompacted(current)) {
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(MarkCompactSpace.getForwardingPointer(current).isNull());
-
- // Fake - allocate it.
- int size = VM.objectModel.getSizeWhenCopied(current);
- int align = VM.objectModel.getAlignWhenCopied(current);
- int offset = VM.objectModel.getAlignOffsetWhenCopied(current);
- // Move to the (aligned) start of the next object
- toCursor.incTo(Allocator.alignAllocationNoFill(toCursor.get(), align, offset));
-
- /*
- * If we're allocating into separate regions, and we've allocated beyond the end of the
- * current region, advance to the next one. We always allocate into regions we have
- * scanned in this collector.
- */
- if (!toCursor.sameRegion(fromCursor) && !toCursor.isAvailable(size)) {
- // The 'to' pointer always trails the 'from' pointer, guaranteeing that
- // there's a next region to advance to.
- toCursor.advanceToNextRegion();
- toCursor.incTo(Allocator.alignAllocationNoFill(toCursor.get(), align, offset));
- }
-
- ObjectReference target = VM.objectModel.getReferenceWhenCopiedTo(current, toCursor.get());
- if (toCursor.sameRegion(fromCursor) && target.toAddress().GE(current.toAddress())) {
- // Don't move the object.
- MarkCompactSpace.setForwardingPointer(current, current);
- toCursor.incTo(VM.objectModel.getObjectEndAddress(current));
- } else {
- MarkCompactSpace.setForwardingPointer(current, target);
- toCursor.inc(size);
- }
- }
- }
- fromCursor.advanceToNextForwardableRegion(space);
- }
- }
-
-
- /**
- * Perform the compacting phase of the collection.
- */
- public void compact() {
- if (regions.isZero()) return;
-
- toCursor.init(regions);
- fromCursor.init(regions);
-
- /* Loop through active regions or until the last region */
- while (fromCursor.isValid()) {
- if (VERBOSE) {
- Log.write("Compacting from region "); Log.write(fromCursor.getRegion());
- Log.write(" to region "); Log.writeln(toCursor.getRegion());
- }
-
- /* Loop through the objects in the region */
- while (fromCursor.hasMoreObjects()) {
- ObjectReference current = fromCursor.advanceToObject();
- fromCursor.advanceToObjectEnd(current);
-
- ObjectReference copyTo = MarkCompactSpace.getForwardingPointer(current);
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(!copyTo.toAddress().EQ(Address.fromIntZeroExtend(VM.ALIGNMENT_VALUE)));
-
- if (!copyTo.isNull() && Space.isInSpace(MC.MARK_COMPACT, copyTo)) {
- if (VM.VERIFY_ASSERTIONS) {
- if (MarkCompactSpace.isMarked(current)) {
- Log.write("Object "); Log.write(current);
- Log.writeln(" is marked during the compact phase");
- }
- VM.assertions._assert(!MarkCompactSpace.isMarked(current));
- }
- if (!toCursor.isInRegion(copyTo)) {
- // Update metadata and move on
- toCursor.finishAndAdvanceToNextRegion();
- }
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(toCursor.isInRegion(copyTo));
- toCursor.copy(current, copyTo);
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(toCursor.isInRegion(copyTo));
- MarkCompactSpace.setForwardingPointer(copyTo, ObjectReference.nullReference());
- }
- }
- fromCursor.advanceToNextRegion();
- }
-
- /* Fix up the last object pointer etc */
- toCursor.finish();
-
-
- /*
- * Return unused pages to the global page resource
- */
- Address region = toCursor.snip();
- while (!region.isZero()) {
- Address nextRegion = MarkCompactLocal.getNextRegion(region);
- space.release(region);
- region = nextRegion;
- }
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/policy/MarkCompactLocal.java b/vmkit/mmtk/java/src/org/mmtk/policy/MarkCompactLocal.java
deleted file mode 100644
index 27109d1..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/policy/MarkCompactLocal.java
+++ /dev/null
@@ -1,71 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.policy;
-
-import org.mmtk.utility.alloc.BumpPointer;
-import org.vmmagic.pragma.Uninterruptible;
-import org.vmmagic.unboxed.Extent;
-
-/**
- * This class implements unsynchronized (local) elements of a
- * sliding mark-compact collector. Allocation is via the bump pointer
- * (@see BumpPointer).
- *
- * @see BumpPointer
- * @see MarkCompactSpace
- */
-@Uninterruptible
-public final class MarkCompactLocal extends BumpPointer {
-
- /**
- * Constructor
- *
- * @param space The space to bump point into.
- */
- public MarkCompactLocal(MarkCompactSpace space) {
- super(space, true);
- }
-
- private MarkCompactSpace mcSpace() {
- return (MarkCompactSpace)space;
- }
-
- /**
- * Prepare for collection: update the metadata for the current region, and flush
- * this bump-pointer's allocations to the global page list.
- */
- public void prepare() {
- if (!initialRegion.isZero()) {
- setDataEnd(region,cursor);
- mcSpace().append(initialRegion);
- }
- reset();
- }
-
- /**
- * Flush this thread-local component in preparation for the mutator thread
- * to die.
- */
- public void flush() {
- prepare();
- }
-
- /**
- * Maximum size of a single region. Important for children that implement
- * load balancing or increments based on region size.
- * @return the maximum region size
- */
- @Override
- protected Extent maximumRegionSize() { return Extent.fromIntZeroExtend(4 << LOG_BLOCK_SIZE) ; }
-
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/policy/MarkCompactSpace.java b/vmkit/mmtk/java/src/org/mmtk/policy/MarkCompactSpace.java
deleted file mode 100644
index 65ec5d8..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/policy/MarkCompactSpace.java
+++ /dev/null
@@ -1,388 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.policy;
-
-import org.mmtk.plan.TraceLocal;
-import org.mmtk.plan.TransitiveClosure;
-import org.mmtk.utility.alloc.BumpPointer;
-import org.mmtk.utility.heap.*;
-import org.mmtk.utility.Constants;
-import org.mmtk.utility.Log;
-
-import org.mmtk.vm.Lock;
-import org.mmtk.vm.VM;
-
-import org.vmmagic.unboxed.*;
-import org.vmmagic.pragma.*;
-
-/**
- * This class implements functionality for a simple sliding mark-compact
- * space.
- */
-@Uninterruptible public final class MarkCompactSpace extends Space
- implements Constants {
-
- /****************************************************************************
- *
- * Class variables
- */
- public static final int LOCAL_GC_BITS_REQUIRED = 1;
- public static final int GLOBAL_GC_BITS_REQUIRED = 0;
- public static final int GC_HEADER_WORDS_REQUIRED = 1;
-
- private static final Word GC_MARK_BIT_MASK = Word.one();
- private static final Offset FORWARDING_POINTER_OFFSET = VM.objectModel.GC_HEADER_OFFSET();
-
- private static final Lock lock = VM.newLock("mcSpace");
-
- /** The list of occupied regions */
- private Address regionList = Address.zero();
-
- // TODO - maintain a separate list of partially allocated regions
- // for threads to allocate into immediately after a collection.
-
- /****************************************************************************
- *
- * Instance variables
- */
-
- /****************************************************************************
- *
- * Initialization
- */
-
- /**
- * The caller specifies the region of virtual memory to be used for
- * this space. If this region conflicts with an existing space,
- * then the constructor will fail.
- *
- * @param name The name of this space (used when printing error messages etc)
- * @param pageBudget The number of pages this space may consume
- * before consulting the plan
- * @param vmRequest An object describing the virtual memory requested.
- */
- public MarkCompactSpace(String name, int pageBudget, VMRequest vmRequest) {
- super(name, true, false, vmRequest);
- if (vmRequest.isDiscontiguous()) {
- pr = new FreeListPageResource(pageBudget, this, 0);
- } else {
- pr = new FreeListPageResource(pageBudget, this, start, extent, 0);
- }
- }
-
- /**
- * Prepare for a collection
- */
- public void prepare() {
- }
-
- /**
- * Release after a collection
- */
- public void release() {
- // nothing to do
- }
-
-
- /**
- * Release an allocated page or pages. In this case we do nothing
- * because we only release pages enmasse.
- *
- * @param start The address of the start of the page or pages
- */
- @Override
- @Inline
- public void release(Address start) {
- ((FreeListPageResource)pr).releasePages(start);
- }
-
- /**
- * Trace an object under a copying collection policy.
- * If the object is already copied, the copy is returned.
- * Otherwise, a copy is created and returned.
- * In either case, the object will be marked on return.
- *
- * @param trace The trace being conducted.
- * @param object The object to be forwarded.
- * @return The forwarded object.
- */
- @Override
- @Inline
- public ObjectReference traceObject(TransitiveClosure trace, ObjectReference object) {
- if (VM.VERIFY_ASSERTIONS)
- VM.assertions._assert(false);
- return null;
- }
-
- /**
- * Trace an object under a copying collection policy.
- * If the object is already copied, the copy is returned.
- * Otherwise, a copy is created and returned.
- * In either case, the object will be marked on return.
- *
- * @param trace The trace being conducted.
- * @param object The object to be forwarded.
- * @return The forwarded object.
- */
- @Inline
- public ObjectReference traceMarkObject(TraceLocal trace, ObjectReference object) {
- if (MarkCompactCollector.VERY_VERBOSE) {
- Log.write("marking "); Log.write(object);
- }
- if (testAndMark(object)) {
- trace.processNode(object);
- } else if (!getForwardingPointer(object).isNull()) {
- if (MarkCompactCollector.VERY_VERBOSE) {
- Log.write(" -> "); Log.writeln(getForwardingPointer(object));
- }
- return getForwardingPointer(object);
- }
- if (MarkCompactCollector.VERY_VERBOSE) {
- Log.writeln();
- }
- return object;
- }
-
- /**
- * Trace an object under a copying collection policy.
- * If the object is already copied, the copy is returned.
- * Otherwise, a copy is created and returned.
- * In either case, the object will be marked on return.
- *
- * @param trace The trace being conducted.
- * @param object The object to be forwarded.
- * @return The forwarded object.
- */
- @Inline
- public ObjectReference traceForwardObject(TraceLocal trace, ObjectReference object) {
- if (testAndClearMark(object)) {
- trace.processNode(object);
- }
- ObjectReference newObject = getForwardingPointer(object);
- if (MarkCompactCollector.VERY_VERBOSE) {
- Log.write("forwarding "); Log.write(object);
- Log.write(" -> "); Log.writeln(newObject);
- }
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(!newObject.isNull());
- return getForwardingPointer(object);
- }
-
- /**
- * Is this object live?
- *
- * @param object The object
- * @return True if the object is live
- */
- @Override
- public boolean isLive(ObjectReference object) {
- return isMarked(object);
- }
-
- /**
- * Has the object in this space been reached during the current collection.
- * This is used for GC Tracing.
- *
- * @param object The object reference.
- * @return True if the object is reachable.
- */
- @Override
- public boolean isReachable(ObjectReference object) {
- return isMarked(object);
- }
-
-
- /****************************************************************************
- *
- * Header manipulation
- */
-
- /**
- * Perform any required post-allocation initialization
- *
- * <i>Nothing to be done in this case</i>
- *
- * @param object the object ref to the storage to be initialized
- */
- @Inline
- public void postAlloc(ObjectReference object) {
- }
-
- /**
- * Non-atomic read of forwarding pointer
- *
- * @param object The object whose forwarding pointer is to be read
- * @return The forwarding pointer stored in <code>object</code>'s
- * header.
- */
- @Inline
- public static ObjectReference getForwardingPointer(ObjectReference object) {
- return object.toAddress().loadObjectReference(FORWARDING_POINTER_OFFSET);
- }
-
- /**
- * Initialise the header of the object.
- *
- * @param object The object to initialise
- */
- @Inline
- public void initializeHeader(ObjectReference object) {
- // nothing to do
- }
-
- /**
- * Used to mark boot image objects during a parallel scan of objects
- * during GC Returns true if marking was done.
- *
- * @param object The object to be marked
- */
- @Inline
- public static boolean testAndMark(ObjectReference object) {
- Word oldValue;
- do {
- oldValue = VM.objectModel.prepareAvailableBits(object);
- Word markBit = oldValue.and(GC_MARK_BIT_MASK);
- if (!markBit.isZero()) return false;
- } while (!VM.objectModel.attemptAvailableBits(object, oldValue,
- oldValue.or(GC_MARK_BIT_MASK)));
- return true;
- }
-
- /**
- * Used to mark boot image objects during a parallel scan of objects
- * during GC Returns true if marking was done.
- *
- * @param object The object to be marked
- */
- @Inline
- public static boolean isMarked(ObjectReference object) {
- Word oldValue = VM.objectModel.readAvailableBitsWord(object);
- Word markBit = oldValue.and(GC_MARK_BIT_MASK);
- return (!markBit.isZero());
- }
-
- /**
- * Used to mark boot image objects during a parallel scan of objects
- * during GC Returns true if marking was done.
- *
- * @param object The object to be marked
- */
- @Inline
- private static boolean testAndClearMark(ObjectReference object) {
- Word oldValue;
- do {
- oldValue = VM.objectModel.prepareAvailableBits(object);
- Word markBit = oldValue.and(GC_MARK_BIT_MASK);
- if (markBit.isZero()) return false;
- } while (!VM.objectModel.attemptAvailableBits(object, oldValue,
- oldValue.and(GC_MARK_BIT_MASK.not())));
- return true;
- }
-
-
- /**
- * Used to mark boot image objects during a parallel scan of objects
- * during GC Returns true if marking was done.
- *
- * @param object The object to be marked
- */
- @Inline
- public static boolean toBeCompacted(ObjectReference object) {
- Word oldValue = VM.objectModel.readAvailableBitsWord(object);
- Word markBit = oldValue.and(GC_MARK_BIT_MASK);
- return !markBit.isZero() && getForwardingPointer(object).isNull();
- }
-
- /**
- * Used to mark boot image objects during a parallel scan of objects
- * during GC Returns true if marking was done.
- *
- * @param object The object to be marked
- */
- @Inline
- public static void clearMark(ObjectReference object) {
- Word oldValue = VM.objectModel.readAvailableBitsWord(object);
- VM.objectModel.writeAvailableBitsWord(object, oldValue.and(GC_MARK_BIT_MASK.not()));
- }
-
- /**
- * Non-atomic write of forwarding pointer word (assumption, thread
- * doing the set has done attempt to forward and owns the right to
- * copy the object)
- *
- * @param object The object whose forwarding pointer is to be set
- * @param ptr The forwarding pointer to be stored in the object's
- * forwarding word
- */
- @Inline
- public static void setForwardingPointer(ObjectReference object,
- ObjectReference ptr) {
- object.toAddress().store(ptr.toAddress(), FORWARDING_POINTER_OFFSET);
- }
-
- /**
- * Non-atomic clear of forwarding pointer word (assumption, thread
- * doing the set has done attempt to forward and owns the right to
- * copy the object)
- *
- * @param object The object whose forwarding pointer is to be set
- */
- @Inline
- public static void clearForwardingPointer(ObjectReference object) {
- object.toAddress().store(Address.zero(), FORWARDING_POINTER_OFFSET);
- }
-
- /**
- * @return A region of this space that has net yet been compacted during
- * the current collection
- */
- public Address getNextRegion() {
- lock.acquire();
- if (regionList.isZero()) {
- lock.release();
- return Address.zero();
- }
- Address result = regionList;
- regionList = BumpPointer.getNextRegion(regionList);
- BumpPointer.clearNextRegion(result);
- lock.release();
- return result;
- }
-
- /**
- * Append a region or list of regions to the global list
- * @param region
- */
- public void append(Address region) {
- lock.acquire();
- if (MarkCompactCollector.VERBOSE) {
- Log.write("Appending region "); Log.write(region);
- Log.writeln(" to global list");
- }
- if (regionList.isZero()) {
- regionList = region;
- } else {
- appendRegion(regionList,region);
- }
- lock.release();
- }
-
- public static void appendRegion(Address listHead, Address region) {
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(!listHead.isZero());
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(!region.isZero());
- Address cursor = listHead;
- while (!BumpPointer.getNextRegion(cursor).isZero()) {
- cursor = BumpPointer.getNextRegion(cursor);
- }
- BumpPointer.setNextRegion(cursor,region);
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/policy/MarkSweepLocal.java b/vmkit/mmtk/java/src/org/mmtk/policy/MarkSweepLocal.java
deleted file mode 100644
index 356291e..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/policy/MarkSweepLocal.java
+++ /dev/null
@@ -1,76 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.policy;
-
-import org.mmtk.utility.alloc.SegregatedFreeListLocal;
-import org.mmtk.utility.Constants;
-
-import org.vmmagic.pragma.*;
-
-/**
- * This class implements unsynchronized (local) elements of a
- * mark-sweep collector. Allocation is via the segregated free list
- * (@see SegregatedFreeList). Marking is done using both a bit in
- * each header's object word, and a mark bitmap. Sweeping is
- * performed lazily.<p>
- *
- * A free list block is a contiguous region of memory containing cells
- * of a single size class, and is a construct of the
- * SegregatedFreeList. This class extends the block to include a mark
- * bitmap. During the mark phase, if an object is encountered with
- * the mark bit in its header unset, it is set and the mark bit in the
- * block header corresponding to that object is set. The rationale
- * behind this approach is that testing (and setting) the mark bit in
- * the object header is cheap, while using a bitmap makes sweeping
- * more efficient. This approach maximizes the speed of the common
- * case when marking, while also allowing for fast sweeping, with
- * minimal space overhead (2 bits per object).
- *
- * @see org.mmtk.utility.alloc.SegregatedFreeList
- * @see MarkSweepSpace
- */
-@Uninterruptible
-public final class MarkSweepLocal extends SegregatedFreeListLocal<MarkSweepSpace> implements Constants {
-
- /****************************************************************************
- *
- * Initialization
- */
-
- /**
- * Constructor
- *
- * @param space The mark-sweep space to which this allocator
- * instances is bound.
- */
- public MarkSweepLocal(MarkSweepSpace space) {
- super(space);
- }
-
- /****************************************************************************
- *
- * Collection
- */
-
- /**
- * Prepare for a collection. If paranoid, perform a sanity check.
- */
- public void prepare() {
- flush();
- }
-
- /**
- * Finish up after a collection.
- */
- public void release() {}
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/policy/MarkSweepSpace.java b/vmkit/mmtk/java/src/org/mmtk/policy/MarkSweepSpace.java
deleted file mode 100644
index 66bf063..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/policy/MarkSweepSpace.java
+++ /dev/null
@@ -1,389 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.policy;
-
-import org.mmtk.plan.TransitiveClosure;
-import org.mmtk.utility.heap.*;
-import org.mmtk.utility.options.Options;
-import org.mmtk.utility.options.MarkSweepMarkBits;
-import org.mmtk.utility.options.EagerCompleteSweep;
-import org.mmtk.utility.Constants;
-import org.mmtk.utility.HeaderByte;
-
-import org.mmtk.vm.VM;
-
-import org.vmmagic.pragma.*;
-import org.vmmagic.unboxed.*;
-
-/**
- * Each instance of this class corresponds to one mark-sweep *space*.
- * Each of the instance methods of this class may be called by any
- * thread (i.e. synchronization must be explicit in any instance or
- * class method). This contrasts with the MarkSweepLocal, where
- * instances correspond to *plan* instances and therefore to kernel
- * threads. Thus unlike this class, synchronization is not necessary
- * in the instance methods of MarkSweepLocal.
- */
-@Uninterruptible
-public final class MarkSweepSpace extends SegregatedFreeListSpace implements Constants {
-
- /****************************************************************************
- *
- * Class variables
- */
- /**
- * Select between using mark bits in a side bitmap, or mark bits
- * in the headers of object (or other sub-class scheme), and a single
- * mark bit per block.
- */
- public static final boolean HEADER_MARK_BITS = VM.config.HEADER_MARK_BITS;
- /** highest bit bits we may use */
- private static final int AVAILABLE_LOCAL_BITS = 8 - HeaderByte.USED_GLOBAL_BITS;
-
- /* mark bits */
- private static final int COUNT_BASE = 0;
-
- public static final int DEFAULT_MARKCOUNT_BITS = 4;
- public static final int MAX_MARKCOUNT_BITS = AVAILABLE_LOCAL_BITS - COUNT_BASE;
- private static final byte MARK_COUNT_INCREMENT = (byte) (1<<COUNT_BASE);
- private static final byte MARK_COUNT_MASK = (byte) (((1<<MAX_MARKCOUNT_BITS)-1) << COUNT_BASE);
-
- private static final boolean EAGER_MARK_CLEAR = HeaderByte.NEEDS_UNLOGGED_BIT;
-
- /* header requirements */
- public static final int LOCAL_GC_BITS_REQUIRED = MAX_MARKCOUNT_BITS;
- public static final int GLOBAL_GC_BITS_REQUIRED = 0;
- public static final int GC_HEADER_WORDS_REQUIRED = 0;
-
-
- /****************************************************************************
- *
- * Instance variables
- */
- private byte markState = 1;
- private byte allocState = 0;
- private boolean inMSCollection;
- private static final boolean usingStickyMarkBits = VM.activePlan.constraints().needsLogBitInHeader(); /* are sticky mark bits in use? */
- private boolean isAgeSegregated = false; /* is this space a nursery space? */
-
- /****************************************************************************
- *
- * Initialization
- */
-
- static {
- Options.markSweepMarkBits = new MarkSweepMarkBits();
- Options.eagerCompleteSweep = new EagerCompleteSweep();
- }
-
- /**
- * The caller specifies the region of virtual memory to be used for
- * this space. If this region conflicts with an existing space,
- * then the constructor will fail.
- *
- * @param name The name of this space (used when printing error messages etc)
- * @param pageBudget The number of pages this space may consume
- * before consulting the plan
- * @param vmRequest An object describing the virtual memory requested.
- */
- public MarkSweepSpace(String name, int pageBudget, VMRequest vmRequest) {
- super(name, pageBudget, 0, vmRequest);
- if (usingStickyMarkBits) allocState |= HeaderByte.UNLOGGED_BIT;
- }
-
- /**
- * This instance will be age-segregated using the sticky mark bits
- * algorithm. Perform appropriate initialization
- */
- public void makeAgeSegregatedSpace() {
- /* we must be using sticky mark bits */
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(usingStickyMarkBits);
- allocState &= ~HeaderByte.UNLOGGED_BIT; /* clear the unlogged bit for nursery allocs */
- isAgeSegregated = true;
- }
-
- /**
- * Should SegregatedFreeListSpace manage a side bitmap to keep track of live objects?
- */
- @Inline
- protected boolean maintainSideBitmap() {
- return !HEADER_MARK_BITS;
- }
-
- /**
- * Do we need to preserve free lists as we move blocks around.
- */
- @Inline
- protected boolean preserveFreeList() {
- return !LAZY_SWEEP;
- }
-
- /****************************************************************************
- *
- * Allocation
- */
-
- /**
- * Prepare the next block in the free block list for use by the free
- * list allocator. In the case of lazy sweeping this involves
- * sweeping the available cells. <b>The sweeping operation must
- * ensure that cells are pre-zeroed</b>, as this method must return
- * pre-zeroed cells.
- *
- * @param block The block to be prepared for use
- * @param sizeClass The size class of the block
- * @return The address of the first pre-zeroed cell in the free list
- * for this block, or zero if there are no available cells.
- */
- protected Address advanceToBlock(Address block, int sizeClass) {
- if (HEADER_MARK_BITS) {
- if (inMSCollection) markBlock(block);
- }
-
- if (LAZY_SWEEP) {
- return makeFreeList(block, sizeClass);
- } else {
- return getFreeList(block);
- }
- }
-
- /**
- * Notify that a new block has been installed. This is to ensure that
- * appropriate collection state can be initialized for the block
- *
- * @param block The new block
- * @param sizeClass The block's sizeclass.
- */
- protected void notifyNewBlock(Address block, int sizeClass) {
- if (HEADER_MARK_BITS) {
- if (inMSCollection) markBlock(block);
- }
- }
-
- /****************************************************************************
- *
- * Collection
- */
-
- /**
- * Prepare for a new collection increment. For the mark-sweep
- * collector we must flip the state of the mark bit between
- * collections.
- *
- * @param gcWholeMS True if we are going to collect the whole marksweep space
- */
- public void prepare(boolean gcWholeMS) {
- if (HEADER_MARK_BITS && Options.eagerCompleteSweep.getValue()) {
- consumeBlocks();
- } else {
- flushAvailableBlocks();
- }
- if (HEADER_MARK_BITS) {
- if (gcWholeMS) {
- allocState = markState;
- if (usingStickyMarkBits && !isAgeSegregated) /* if true, we allocate as "mature", not nursery */
- allocState |= HeaderByte.UNLOGGED_BIT;
- markState = deltaMarkState(true);
- if (EAGER_MARK_CLEAR)
- clearAllBlockMarks();
- }
- } else {
- zeroLiveBits();
- }
- inMSCollection = true;
- }
-
- /**
- * A new collection increment has completed. For the mark-sweep
- * collector this means we can perform the sweep phase.
- */
- public void release() {
- sweepConsumedBlocks(!EAGER_MARK_CLEAR);
- inMSCollection = false;
- }
-
- /**
- * Release an allocated page or pages
- *
- * @param start The address of the start of the page or pages
- */
- @Inline
- public void release(Address start) {
- ((FreeListPageResource) pr).releasePages(start);
- }
-
- /**
- * Should the sweep reclaim the cell containing this object. Is this object
- * live. This is only used when maintainSideBitmap is false.
- *
- * @param object The object to query
- * @return True if the cell should be reclaimed
- */
- @Inline
- protected boolean isCellLive(ObjectReference object) {
- if (!HEADER_MARK_BITS) {
- return super.isCellLive(object);
- }
- return testMarkState(object);
- }
-
- /****************************************************************************
- *
- * Object processing and tracing
- */
-
- /**
- * Trace a reference to an object under a mark sweep collection
- * policy. If the object header is not already marked, mark the
- * object in either the bitmap or by moving it off the treadmill,
- * and enqueue the object for subsequent processing. The object is
- * marked as (an atomic) side-effect of checking whether already
- * marked.
- *
- * @param object The object to be traced.
- * @return The object (there is no object forwarding in this
- * collector, so we always return the same object: this could be a
- * void method but for compliance to a more general interface).
- */
- @Inline
- public ObjectReference traceObject(TransitiveClosure trace, ObjectReference object) {
- if (HEADER_MARK_BITS) {
- if (testAndMark(object)) {
- markBlock(object);
- trace.processNode(object);
- }
- } else {
- if (testAndSetLiveBit(object)) {
- trace.processNode(object);
- }
- }
- return object;
- }
-
- /**
- *
- * @param object The object in question
- * @return True if this object is known to be live (i.e. it is marked)
- */
- @Inline
- public boolean isLive(ObjectReference object) {
- if (HEADER_MARK_BITS) {
- return testMarkState(object);
- } else {
- return liveBitSet(object);
- }
- }
-
- /**
- * Get the previous mark state.
- *
- * @return The previous mark state.
- */
- @Inline
- public byte getPreviousMarkState() {
- return deltaMarkState(false);
- }
-
- /**
- * Return the mark state incremented or decremented by one.
- *
- * @param increment If true, then return the incremented value else return the decremented value
- * @return the mark state incremented or decremented by one.
- */
- private byte deltaMarkState(boolean increment) {
- byte mask = (byte) (((1 << Options.markSweepMarkBits.getValue()) - 1)<<COUNT_BASE);
- byte rtn = (byte) (increment ? markState + MARK_COUNT_INCREMENT : markState - MARK_COUNT_INCREMENT);
- rtn &= mask;
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert((markState & ~MARK_COUNT_MASK) == 0);
- return rtn;
- }
-
- /****************************************************************************
- *
- * Header manipulation
- */
-
- /**
- * Perform any required post allocation initialization
- *
- * @param object the object ref to the storage to be initialized
- */
- @Inline
- public void postAlloc(ObjectReference object) {
- initializeHeader(object, true);
- }
-
- /**
- * Perform any required post copy (i.e. in-GC allocation) initialization.
- * This is relevant (for example) when MS is used as the mature space in
- * a copying GC.
- *
- * @param object the object ref to the storage to be initialized
- * @param majorGC Is this copy happening during a major gc?
- */
- @Inline
- public void postCopy(ObjectReference object, boolean majorGC) {
- initializeHeader(object, false);
- if (!HEADER_MARK_BITS) {
- testAndSetLiveBit(object);
- }
- }
-
- /**
- * Perform any required initialization of the GC portion of the header.
- *
- * @param object the object ref to the storage to be initialized
- * @param alloc is this initialization occuring due to (initial) allocation
- * (true) or due to copying (false)?
- */
- @Inline
- public void initializeHeader(ObjectReference object, boolean alloc) {
- if (HEADER_MARK_BITS) {
- byte oldValue = VM.objectModel.readAvailableByte(object);
- byte newValue = (byte) ((oldValue & ~MARK_COUNT_MASK) | (alloc ? allocState : markState));
- if (HeaderByte.NEEDS_UNLOGGED_BIT) newValue |= HeaderByte.UNLOGGED_BIT;
- VM.objectModel.writeAvailableByte(object, newValue);
- } else if (HeaderByte.NEEDS_UNLOGGED_BIT)
- HeaderByte.markAsUnlogged(object);
- }
-
- /**
- * Atomically attempt to set the mark bit of an object. Return true
- * if successful, false if the mark bit was already set.
- *
- * @param object The object whose mark bit is to be written
- * @param value The value to which the mark bits will be set
- */
- @Inline
- private boolean testAndMark(ObjectReference object) {
- byte oldValue, markBits;
- oldValue = VM.objectModel.readAvailableByte(object);
- markBits = (byte) (oldValue & MARK_COUNT_MASK);
- if (markBits == markState) return false;
- VM.objectModel.writeAvailableByte(object, (byte)((oldValue & ~MARK_COUNT_MASK) | markState));
- return true;
- }
-
- /**
- * Return true if the mark count for an object has the given value.
- *
- * @param object The object whose mark bit is to be tested
- * @param value The value against which the mark bit will be tested
- * @return True if the mark bit for the object has the given value.
- */
- @Inline
- private boolean testMarkState(ObjectReference object) {
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert((markState & ~MARK_COUNT_MASK) == 0);
- return (VM.objectModel.readAvailableByte(object) & MARK_COUNT_MASK) == markState;
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/policy/RawPageSpace.java b/vmkit/mmtk/java/src/org/mmtk/policy/RawPageSpace.java
deleted file mode 100644
index d667c17..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/policy/RawPageSpace.java
+++ /dev/null
@@ -1,85 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.policy;
-
-import org.mmtk.plan.TransitiveClosure;
-import org.mmtk.utility.heap.FreeListPageResource;
-import org.mmtk.utility.heap.VMRequest;
-import org.mmtk.utility.Constants;
-
-import org.mmtk.vm.VM;
-
-import org.vmmagic.pragma.*;
-import org.vmmagic.unboxed.*;
-
-/**
- * Each instance of this class corresponds to one raw page space.
- *
- * This class provides access to raw memory for managing internal meta
- * data.
- */
-@Uninterruptible public final class RawPageSpace extends Space
- implements Constants {
-
- /**
- * The caller specifies the region of virtual memory to be used for
- * this space. If this region conflicts with an existing space,
- * then the constructor will fail.
- *
- * @param name The name of this space (used when printing error messages etc)
- * @param pageBudget The number of pages this space may consume
- * before consulting the plan
- * @param vmRequest An object describing the virtual memory requested.
- */
- public RawPageSpace(String name, int pageBudget, VMRequest vmRequest) {
- super(name, false, false, vmRequest);
- if (vmRequest.isDiscontiguous()) {
- pr = new FreeListPageResource(pageBudget, this, 0);
- } else {
- pr = new FreeListPageResource(pageBudget, this, start, extent);
- }
- }
-
- public void prepare() { }
- public void release() { }
-
- /**
- * Release a group of pages that were allocated together.
- *
- * @param first The first page in the group of pages that were
- * allocated together.
- */
- @Inline
- public void release(Address first) {
- ((FreeListPageResource) pr).releasePages(first);
- }
-
- /**
- * Trace an object.
- *
- * This makes no sense for a raw page space and should never be
- * called.
- *
- * @param object The object to be traced.
- * @return <code>zero</code>: calling this is an error.
- */
- @Inline
- public ObjectReference traceObject(TransitiveClosure trace, ObjectReference object) {
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(false);
- return ObjectReference.nullReference();
- }
-
- public boolean isLive(ObjectReference object) {
- return true;
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/policy/SegregatedFreeListSpace.java b/vmkit/mmtk/java/src/org/mmtk/policy/SegregatedFreeListSpace.java
deleted file mode 100644
index d7ddc87..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/policy/SegregatedFreeListSpace.java
+++ /dev/null
@@ -1,1005 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.policy;
-
-import org.mmtk.utility.alloc.BlockAllocator;
-import org.mmtk.utility.alloc.EmbeddedMetaData;
-import org.mmtk.utility.heap.FreeListPageResource;
-import org.mmtk.utility.heap.Map;
-import org.mmtk.utility.heap.VMRequest;
-import org.mmtk.utility.Constants;
-import org.mmtk.utility.Conversions;
-import org.mmtk.utility.Memory;
-
-import org.mmtk.vm.Lock;
-import org.mmtk.vm.VM;
-
-import org.vmmagic.pragma.*;
-import org.vmmagic.unboxed.*;
-
-/**
- * Each instance of this class corresponds to one mark-sweep *space*.
- * Each of the instance methods of this class may be called by any
- * thread (i.e. synchronization must be explicit in any instance or
- * class method). This contrasts with the MarkSweepLocal, where
- * instances correspond to *plan* instances and therefore to kernel
- * threads. Thus unlike this class, synchronization is not necessary
- * in the instance methods of MarkSweepLocal.
- */
-@Uninterruptible
-public abstract class SegregatedFreeListSpace extends Space implements Constants {
-
- /****************************************************************************
- *
- * Class variables
- */
- protected static final boolean LAZY_SWEEP = true;
- private static final boolean COMPACT_SIZE_CLASSES = false;
- protected static final int MIN_CELLS = 6;
- protected static final int MAX_CELLS = 99; // (1<<(INUSE_BITS-1))-1;
- protected static final int MAX_CELL_SIZE = 8<<10;
- public static final int MAX_FREELIST_OBJECT_BYTES = MAX_CELL_SIZE;
-
- // live bits etc
- private static final int OBJECT_LIVE_SHIFT = LOG_MIN_ALIGNMENT; // 4 byte resolution
- private static final int LOG_BIT_COVERAGE = OBJECT_LIVE_SHIFT;
- private static final int LOG_LIVE_COVERAGE = LOG_BIT_COVERAGE + LOG_BITS_IN_BYTE;
- private static final int LIVE_BYTES_PER_REGION = 1 << (EmbeddedMetaData.LOG_BYTES_IN_REGION - LOG_LIVE_COVERAGE);
- private static final Word WORD_SHIFT_MASK = Word.one().lsh(LOG_BITS_IN_WORD).minus(Extent.one());
- private static final int LOG_LIVE_WORD_STRIDE = LOG_LIVE_COVERAGE + LOG_BYTES_IN_WORD;
- private static final Extent LIVE_WORD_STRIDE = Extent.fromIntSignExtend(1<<LOG_LIVE_WORD_STRIDE);
- private static final Word LIVE_WORD_STRIDE_MASK = LIVE_WORD_STRIDE.minus(1).toWord().not();
- private static final int NET_META_DATA_BYTES_PER_REGION = BlockAllocator.META_DATA_BYTES_PER_REGION + LIVE_BYTES_PER_REGION;
- protected static final int META_DATA_PAGES_PER_REGION_WITH_BITMAP = Conversions.bytesToPages(Extent.fromIntSignExtend(NET_META_DATA_BYTES_PER_REGION));
- protected static final int META_DATA_PAGES_PER_REGION_NO_BITMAP = Conversions.bytesToPages(Extent.fromIntSignExtend(BlockAllocator.META_DATA_BYTES_PER_REGION));
- private static final Extent META_DATA_OFFSET = BlockAllocator.META_DATA_EXTENT;
-
-
- // calculate worst case fragmentation very conservatively
- private static final int NEW_SIZECLASS_OVERHEAD = sizeClassCount(); // one page wasted per size class
- private static final int METADATA_OVERHEAD = META_DATA_PAGES_PER_REGION_WITH_BITMAP; // worst case scenario
- public static final float WORST_CASE_FRAGMENTATION = 1 + ((NEW_SIZECLASS_OVERHEAD + METADATA_OVERHEAD)/(float) EmbeddedMetaData.BYTES_IN_REGION);
-
- /****************************************************************************
- *
- * Instance variables
- */
- protected final Lock lock = VM.newLock("SegregatedFreeListGlobal");
- protected final AddressArray consumedBlockHead = AddressArray.create(sizeClassCount());
- protected final AddressArray flushedBlockHead = AddressArray.create(sizeClassCount());
- protected final AddressArray availableBlockHead = AddressArray.create(sizeClassCount());
-
- private final int[] cellSize = new int[sizeClassCount()];
- private final byte[] blockSizeClass = new byte[sizeClassCount()];
- private final int[] blockHeaderSize = new int[sizeClassCount()];
-
- /**
- * The caller specifies the region of virtual memory to be used for
- * this space. If this region conflicts with an existing space,
- * then the constructor will fail.
- *
- * @param name The name of this space (used when printing error messages etc)
- * @param pageBudget The number of pages this space may consume before consulting the plan
- * @param additionalMetadata The number of meta data bytes per region for the subclass.
- * @param vmRequest An object describing the virtual memory requested.
- */
- public SegregatedFreeListSpace(String name, int pageBudget, int additionalMetadata, VMRequest vmRequest) {
- super(name, false, false, vmRequest);
- initSizeClasses();
- int totalMetadata = additionalMetadata;
- if (maintainSideBitmap()) {
- totalMetadata += META_DATA_PAGES_PER_REGION_WITH_BITMAP;
- } else {
- totalMetadata += META_DATA_PAGES_PER_REGION_NO_BITMAP;
- }
- if (vmRequest.isDiscontiguous()) {
- pr = new FreeListPageResource(pageBudget, this, totalMetadata);
- } else {
- pr = new FreeListPageResource(pageBudget, this, start, extent, totalMetadata);
- }
- }
-
- /**
- * Should SegregatedFreeListSpace manage a side bitmap to keep track of live objects?
- */
- protected abstract boolean maintainSideBitmap();
-
- /**
- * Do we need to preserve free lists as we move blocks around.
- */
- protected abstract boolean preserveFreeList();
-
- /****************************************************************************
- *
- * Allocation
- */
-
- /**
- * Return a block to the global pool.
- *
- * @param block The block to return
- * @param sizeClass The size class
- */
- public void returnConsumedBlock(Address block, int sizeClass) {
- returnBlock(block, sizeClass, Address.zero());
- }
-
- /**
- * Return a block to the global pool.
- *
- * @param block The block to return
- * @param sizeClass The size class
- * @param freeCell The first free cell in the block.
- */
- public void returnBlock(Address block, int sizeClass, Address freeCell) {
- if (VM.VERIFY_ASSERTIONS) {
- VM.assertions._assert(BlockAllocator.getNext(block).isZero());
- }
- if (preserveFreeList()) {
- setFreeList(block, freeCell);
- }
- lock.acquire();
- BlockAllocator.setNext(block, consumedBlockHead.get(sizeClass));
- consumedBlockHead.set(sizeClass, block);
- lock.release();
- }
-
- /**
- * Acquire a new block from the global pool to allocate into. This method
- * with either return a non-empty free list, or zero when allocation
- * fails.
- *
- * This method will populate the passed in free list for the given size
- * class and return the address of the block.
- *
- * @param sizeClass The size class to allocate into
- * @param freeList The free list to populate
- * @return The address of the block
- */
- public Address getAllocationBlock(int sizeClass, AddressArray freeList) {
- lock.acquire();
- Address block;
- while(!(block = availableBlockHead.get(sizeClass)).isZero()) {
- availableBlockHead.set(sizeClass, BlockAllocator.getNext(block));
- lock.release();
-
- /* This block is no longer on any list */
- BlockAllocator.setNext(block, Address.zero());
-
- /* Can we allocate into this block? */
- Address cell = advanceToBlock(block, sizeClass);
- if (!cell.isZero()) {
- freeList.set(sizeClass, cell);
- return block;
- }
-
- /* Block was full */
- lock.acquire();
- BlockAllocator.setNext(block, consumedBlockHead.get(sizeClass));
- consumedBlockHead.set(sizeClass, block);
- }
- lock.release();
- return expandSizeClass(sizeClass, freeList);
- }
-
- /**
- * Expand a particular size class, allocating a new block, breaking
- * the block into cells and placing those cells on a free list for
- * that block. The block becomes the current head for this size
- * class and the address of the first available cell is returned.<p>
- *
- * <b>This is guaranteed to return pre-zeroed cells</b>
- *
- * @param sizeClass The size class to be expanded
- * @param freeList The free list to populate.
- * @return The block that was just allocated.
- */
- @Inline
- private Address expandSizeClass(int sizeClass, AddressArray freeList) {
- Address block = BlockAllocator.alloc(this, blockSizeClass[sizeClass]);
-
- if (block.isZero()) {
- return Address.zero();
- }
-
- BlockAllocator.setNext(block, Address.zero());
- BlockAllocator.setAllClientSizeClass(block, blockSizeClass[sizeClass], (byte) sizeClass);
-
- notifyNewBlock(block, sizeClass);
-
- int cellExtent = cellSize[sizeClass];
- int blockSize = BlockAllocator.blockSize(blockSizeClass[sizeClass]);
- int useableBlockSize = blockSize - blockHeaderSize[sizeClass];
- Address firstCell = block.plus(blockHeaderSize[sizeClass]);
- Address sentinel = block.plus(blockSize);
-
- /* pre-zero the block */
- VM.memory.zero(firstCell, Extent.fromIntZeroExtend(useableBlockSize));
-
- /* construct the free list */
- Address nextCell;
- Address cell = firstCell;
- while ((nextCell = cell.plus(cellExtent)).LT(sentinel)) {
- cell.store(nextCell);
- cell = nextCell;
- }
-
- /* Populate the free list */
- freeList.set(sizeClass, firstCell);
- return block;
- }
-
- /****************************************************************************
- *
- * Block management
- */
-
- /**
- * Initialize the size class data structures.
- */
- private void initSizeClasses() {
- for (int sc = 0; sc < sizeClassCount(); sc++) {
- cellSize[sc] = getBaseCellSize(sc);
- for (byte blk = 0; blk < BlockAllocator.BLOCK_SIZE_CLASSES; blk++) {
- int usableBytes = BlockAllocator.blockSize(blk);
- int cells = usableBytes / cellSize[sc];
- blockSizeClass[sc] = blk;
- /* cells must start at multiple of MIN_ALIGNMENT because
- cellSize is also supposed to be multiple, this should do
- the trick: */
- blockHeaderSize[sc] = BlockAllocator.blockSize(blk) - cells * cellSize[sc];
- if (((usableBytes < BYTES_IN_PAGE) && (cells*2 > MAX_CELLS)) ||
- ((usableBytes > (BYTES_IN_PAGE>>1)) && (cells > MIN_CELLS)))
- break;
- }
- }
- }
-
- /**
- * Get the size class for a given number of bytes.
- *
- * We use size classes based on a worst case internal fragmentation
- * loss target of 1/8. In fact, across sizes from 8 bytes to 512
- * the average worst case loss is 13.3%, giving an expected loss
- * (assuming uniform distribution) of about 7%. We avoid using the
- * Lea class sizes because they were so numerous and therefore
- * liable to lead to excessive inter-class-size fragmentation.<p>
- *
- * This method may segregate arrays and scalars (currently it does
- * not).<p>
- *
- * This method should be more intelligent and take alignment requests
- * into consideration. The issue with this is that the block header
- * which can be varied by subclasses can change the alignment of the
- * cells.<p>
- *
- * @param bytes The number of bytes required to accommodate the object
- * to be allocated.
- * @return The size class capable of accommodating the allocation request.
- */
- @Inline
- public final int getSizeClass(int bytes) {
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert((bytes > 0) && (bytes <= MAX_CELL_SIZE));
-
- int sz1 = bytes - 1;
-
- if (BYTES_IN_ADDRESS == 4) { // 32-bit
- if (COMPACT_SIZE_CLASSES)
- return (
- (sz1 <= 31) ? (sz1 >> 2) : // 4 bytes apart
- (sz1 <= 63) ? 4 + (sz1 >> 3) : // 8 bytes apart
- (sz1 <= 95) ? 8 + (sz1 >> 4) : // 16 bytes apart
- (sz1 <= 223) ? 14 + (sz1 >> 6) : // 64 bytes apart
- (sz1 <= 734) ? 17 + (sz1 >> 8) : // 256 bytes apart
- 20 + (sz1 >> 10)); // 1024 bytes apart
- else
- return (
- (sz1 <= 63) ? (sz1 >> 2) : // 4 bytes apart
- (sz1 <= 127) ? 12 + (sz1 >> 4) : // 16 bytes apart
- (sz1 <= 255) ? 16 + (sz1 >> 5) : // 32 bytes apart
- (sz1 <= 511) ? 20 + (sz1 >> 6) : // 64 bytes apart
- (sz1 <= 2047) ? 26 + (sz1 >> 8) : // 256 bytes apart
- 32 + (sz1 >> 10)); // 1024 bytes apart
- } else { // 64-bit
- if (COMPACT_SIZE_CLASSES)
- return (
- (sz1 <= 95) ? (sz1 >> 3) : // 8 bytes apart
- (sz1 <= 127) ? 6 + (sz1 >> 4) : // 16 bytes apart
- (sz1 <= 191) ? 10 + (sz1 >> 5) : // 32 bytes apart
- (sz1 <= 383) ? 13 + (sz1 >> 6) : // 64 bytes apart
- (sz1 <= 511) ? 16 + (sz1 >> 7) : // 128 bytes apart
- (sz1 <= 1023) ? 19 + (sz1 >> 9) : // 512 bytes apart
- 20 + (sz1 >> 10)); // 1024 bytes apart
- else
- return (
- (sz1 <= 111) ? (sz1 >> 3) : // 8 bytes apart
- (sz1 <= 223) ? 7 + (sz1 >> 4) : // 16 bytes apart
- (sz1 <= 319) ? 14 + (sz1 >> 5) : // 32 bytes apart
- (sz1 <= 575) ? 19 + (sz1 >> 6) : // 64 bytes apart
- (sz1 <= 2047) ? 26 + (sz1 >> 8) : // 256 bytes apart
- 32 + (sz1 >> 10)); // 1024 bytes apart
- }
- }
-
- /**
- * Return the size of a basic cell (i.e. not including any cell
- * header) for a given size class.
- *
- * @param sc The size class in question
- * @return The size of a basic cell (i.e. not including any cell
- * header).
- */
- @Inline
- public final int getBaseCellSize(int sc) {
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert((sc >= 0) && (sc < sizeClassCount()));
-
- if (BYTES_IN_ADDRESS == 4) { // 32-bit
- if (COMPACT_SIZE_CLASSES)
- return ((sc < 8) ? (sc + 1) << 2:
- (sc < 12) ? (sc - 3) << 3:
- (sc < 16) ? (sc - 7) << 4:
- (sc < 18) ? (sc - 13) << 6:
- (sc < 21) ? (sc - 16) << 8:
- (sc - 19) << 10);
- else
- return ((sc < 16) ? (sc + 1) << 2:
- (sc < 20) ? (sc - 11) << 4:
- (sc < 24) ? (sc - 15) << 5:
- (sc < 28) ? (sc - 19) << 6:
- (sc < 34) ? (sc - 25) << 8:
- (sc - 31) << 10);
- } else { // 64-bit
- if (COMPACT_SIZE_CLASSES)
- return ((sc < 12) ? (sc + 1) << 3:
- (sc < 14) ? (sc - 5) << 4:
- (sc < 16) ? (sc - 9) << 5:
- (sc < 19) ? (sc - 12) << 6:
- (sc < 20) ? (sc - 15) << 7:
- (sc < 21) ? (sc - 18) << 9:
- (sc - 19) << 10);
- else
- return ((sc < 14) ? (sc + 1) << 3:
- (sc < 21) ? (sc - 6) << 4:
- (sc < 24) ? (sc - 13) << 5:
- (sc < 28) ? (sc - 18) << 6:
- (sc < 34) ? (sc - 25) << 8:
- (sc - 31) << 10);
- }
- }
-
- /**
- * The number of distinct size classes.
- */
- @Inline
- public static int sizeClassCount() {
- return (COMPACT_SIZE_CLASSES) ? 28 : 40;
- }
-
- /****************************************************************************
- *
- * Preserving (saving & restoring) free lists
- */
-
- /**
- * Prepare a block for allocation, returning a free list into the block.
- *
- * @param block The new block
- * @param sizeClass The block's sizeclass.
- */
- protected abstract Address advanceToBlock(Address block, int sizeClass);
-
- /**
- * Notify that a new block has been installed.
- *
- * @param block The new block
- * @param sizeClass The block's sizeclass.
- */
- protected void notifyNewBlock(Address block, int sizeClass) {}
-
- /**
- * Should the sweep reclaim the cell containing this object. Is this object
- * live. This is only used when maintainSideBitmap is false.
- *
- * @param object The object to query
- * @return True if the cell should be reclaimed
- */
- protected boolean reclaimCellForObject(ObjectReference object) {
- VM.assertions.fail("Must implement reclaimCellForObject if not maintaining side bitmap");
- return false;
- }
-
- /****************************************************************************
- *
- * Metadata manipulation
- */
-
- /**
- * In the case where free lists associated with each block are
- * preserved, get the free list for a given block.
- *
- * @param block The block whose free list is to be found
- * @return The free list for this block
- */
- @Inline
- protected final Address getFreeList(Address block) {
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(preserveFreeList());
- return BlockAllocator.getFreeListMeta(block);
- }
-
- /**
- * In the case where free lists associated with each block are
- * preserved, set the free list for a given block.
- *
- * @param block The block whose free list is to be found
- * @param cell The head of the free list (i.e. the first cell in the
- * free list).
- */
- @Inline
- protected final void setFreeList(Address block, Address cell) {
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(preserveFreeList());
- BlockAllocator.setFreeListMeta(block, cell);
- }
-
- /****************************************************************************
- *
- * Collection
- */
-
- /**
- * Clear all block marks for this space. This method is important when
- * it is desirable to do partial collections, which man mean that block
- * marks need to be explicitly cleared when necessary.
- */
- protected final void clearAllBlockMarks() {
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(!maintainSideBitmap());
- for (int sizeClass = 0; sizeClass < sizeClassCount(); sizeClass++) {
- Extent blockSize = Extent.fromIntSignExtend(BlockAllocator.blockSize(blockSizeClass[sizeClass]));
- /* Flushed blocks */
- Address block = flushedBlockHead.get(sizeClass);
- while (!block.isZero()) {
- Address next = BlockAllocator.getNext(block);
- clearBlockMark(block, blockSize);
- block = next;
- }
- /* Available blocks */
- block = consumedBlockHead.get(sizeClass);
- while (!block.isZero()) {
- Address next = BlockAllocator.getNext(block);
- clearBlockMark(block, blockSize);
- block = next;
- }
- }
- }
-
- /**
- * Sweep all blocks for free objects.
- *
- * @param clearMarks should we clear block mark bits as we process.
- */
- protected final void sweepConsumedBlocks(boolean clearMarks) {
- for (int sizeClass = 0; sizeClass < sizeClassCount(); sizeClass++) {
- Extent blockSize = Extent.fromIntSignExtend(BlockAllocator.blockSize(blockSizeClass[sizeClass]));
- Address availableHead = Address.zero();
- /* Flushed blocks */
- Address block = flushedBlockHead.get(sizeClass);
- flushedBlockHead.set(sizeClass, Address.zero());
- while (!block.isZero()) {
- Address next = BlockAllocator.getNext(block);
- availableHead = sweepBlock(block, sizeClass, blockSize, availableHead, clearMarks);
- block = next;
- }
- /* Consumed blocks */
- block = consumedBlockHead.get(sizeClass);
- consumedBlockHead.set(sizeClass, Address.zero());
- while (!block.isZero()) {
- Address next = BlockAllocator.getNext(block);
- availableHead = sweepBlock(block, sizeClass, blockSize, availableHead, clearMarks);
- block = next;
- }
- /* Make blocks available */
- availableBlockHead.set(sizeClass, availableHead);
- }
- }
-
- /**
- * Sweep a block, freeing it and adding to the list given by availableHead
- * if it contains no free objects.
- *
- * @param clearMarks should we clear block mark bits as we process.
- */
- protected final Address sweepBlock(Address block, int sizeClass, Extent blockSize, Address availableHead, boolean clearMarks) {
- boolean liveBlock = containsLiveCell(block, blockSize, clearMarks);
- if (!liveBlock) {
- BlockAllocator.setNext(block, Address.zero());
- BlockAllocator.free(this, block);
- } else {
- BlockAllocator.setNext(block, availableHead);
- availableHead = block;
- if (!LAZY_SWEEP) {
- setFreeList(block, makeFreeList(block, sizeClass));
- }
- }
- return availableHead;
- }
-
- /**
- * Eagerly consume all remaining blocks.
- */
- protected final void consumeBlocks() {
- for (int sizeClass = 0; sizeClass < sizeClassCount(); sizeClass++) {
- while (!availableBlockHead.get(sizeClass).isZero()) {
- Address block = availableBlockHead.get(sizeClass);
- availableBlockHead.set(sizeClass, BlockAllocator.getNext(block));
- advanceToBlock(block, sizeClass);
- BlockAllocator.setNext(block, consumedBlockHead.get(sizeClass));
- consumedBlockHead.set(sizeClass, block);
- }
- }
- }
-
- /**
- * Flush all the allocation blocks to the consumed list.
- */
- protected final void flushAvailableBlocks() {
- for (int sizeClass = 0; sizeClass < sizeClassCount(); sizeClass++) {
- flushedBlockHead.set(sizeClass, availableBlockHead.get(sizeClass));
- availableBlockHead.set(sizeClass, Address.zero());
- }
- }
-
- /**
- * Does this block contain any live cells.
- *
- * @param block The block
- * @param blockSize The size of the block
- * @param clearMarks should we clear block mark bits as we process.
- * @return True if any cells in the block are live
- */
- @Inline
- protected boolean containsLiveCell(Address block, Extent blockSize, boolean clearMarks) {
- if (maintainSideBitmap()) {
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(alignToLiveStride(block).EQ(block));
- Address cursor = getLiveWordAddress(block);
- Address sentinel = getLiveWordAddress(block.plus(blockSize.minus(1)));
- while (cursor.LE(sentinel)) {
- Word live = cursor.loadWord();
- if (!live.isZero()) {
- return true;
- }
- cursor = cursor.plus(BYTES_IN_WORD);
- }
- return false;
- } else {
- boolean live = false;
- Address cursor = block;
- while(cursor.LT(block.plus(blockSize))) {
- live |= BlockAllocator.checkBlockMeta(cursor);
- if (clearMarks)
- BlockAllocator.clearBlockMeta(cursor);
- cursor = cursor.plus(1 << BlockAllocator.LOG_MIN_BLOCK);
- }
- return live;
- }
- }
-
-
- /**
- * Clear block marks for a block
- *
- * @param block The block
- * @param blockSize The size of the block
- */
- @Inline
- protected void clearBlockMark(Address block, Extent blockSize) {
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(!maintainSideBitmap());
- Address cursor = block;
- while(cursor.LT(block.plus(blockSize))) {
- BlockAllocator.clearBlockMeta(cursor);
- cursor = cursor.plus(1 << BlockAllocator.LOG_MIN_BLOCK);
- }
- }
-
- /**
- * In the cell containing this object live?
- *
- * @param object The object
- * @return True if the cell is live
- */
- @Inline
- protected boolean isCellLive(ObjectReference object) {
- /* Must override if not using the side bitmap */
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(maintainSideBitmap());
- return liveBitSet(object);
- }
-
- /**
- * Use the live bits for a block to infer free cells and thus
- * construct a free list for the block.
- *
- * @param block The block to be processed
- * @param sizeClass The size class for the block
- * @return The head of the new free list
- */
- @Inline
- protected final Address makeFreeList(Address block, int sizeClass) {
- Extent blockSize = Extent.fromIntSignExtend(BlockAllocator.blockSize(blockSizeClass[sizeClass]));
- Address cursor = block.plus(blockHeaderSize[sizeClass]);
- Address lastFree = Address.zero();
- Address firstFree = Address.zero();
- Address end = block.plus(blockSize);
- Extent cellExtent = Extent.fromIntSignExtend(cellSize[sizeClass]);
- while (cursor.LT(end)) {
- ObjectReference current = VM.objectModel.getObjectFromStartAddress(cursor);
- boolean free = true;
- if (!current.isNull()) {
- free = !isCellLive(current);
- }
- if (free) {
- if (firstFree.isZero()) {
- firstFree = cursor;
- } else {
- lastFree.store(cursor);
- }
- Memory.zeroSmall(cursor, cellExtent);
- lastFree = cursor;
- }
- cursor = cursor.plus(cellExtent);
- }
- return firstFree;
- }
-
- /**
- * Sweep all blocks for free objects.
- */
- public void sweepCells(Sweeper sweeper) {
- for (int sizeClass = 0; sizeClass < sizeClassCount(); sizeClass++) {
- Address availableHead = Address.zero();
- /* Flushed blocks */
- Address block = flushedBlockHead.get(sizeClass);
- flushedBlockHead.set(sizeClass, Address.zero());
- while (!block.isZero()) {
- Address next = BlockAllocator.getNext(block);
- availableHead = sweepCells(sweeper, block, sizeClass, availableHead);
- block = next;
- }
- /* Consumed blocks */
- block = consumedBlockHead.get(sizeClass);
- consumedBlockHead.set(sizeClass, Address.zero());
- while (!block.isZero()) {
- Address next = BlockAllocator.getNext(block);
- availableHead = sweepCells(sweeper, block, sizeClass, availableHead);
- block = next;
- }
- /* Make blocks available */
- availableBlockHead.set(sizeClass, availableHead);
- }
- }
-
- /**
- * Sweep a block, freeing it and adding to the list given by availableHead
- * if it contains no free objects.
- */
- private Address sweepCells(Sweeper sweeper, Address block, int sizeClass, Address availableHead) {
- boolean liveBlock = sweepCells(sweeper, block, sizeClass);
- if (!liveBlock) {
- BlockAllocator.setNext(block, Address.zero());
- BlockAllocator.free(this, block);
- } else {
- BlockAllocator.setNext(block, availableHead);
- availableHead = block;
- }
- return availableHead;
- }
-
- /**
- * Sweep a block, freeing it and making it available if any live cells were found.
- * if it contains no free objects.
- *
- * This is designed to be called in parallel by multiple collector threads.
- */
- public void parallelSweepCells(Sweeper sweeper) {
- for (int sizeClass = 0; sizeClass < sizeClassCount(); sizeClass++) {
- Address block;
- while(!(block = getSweepBlock(sizeClass)).isZero()) {
- boolean liveBlock = sweepCells(sweeper, block, sizeClass);
- if (!liveBlock) {
- BlockAllocator.setNext(block, Address.zero());
- BlockAllocator.free(this, block);
- } else {
- lock.acquire();
- BlockAllocator.setNext(block, availableBlockHead.get(sizeClass));
- availableBlockHead.set(sizeClass, block);
- lock.release();
- }
- }
- }
- }
-
- /**
- * Get a block for a parallel sweep.
- *
- * @param sizeClass The size class of the block to sweep.
- * @return The block or zero if no blocks remain to be swept.
- */
- private Address getSweepBlock(int sizeClass) {
- lock.acquire();
- Address block;
-
- /* Flushed blocks */
- block = flushedBlockHead.get(sizeClass);
- if (!block.isZero()) {
- flushedBlockHead.set(sizeClass, BlockAllocator.getNext(block));
- lock.release();
- BlockAllocator.setNext(block, Address.zero());
- return block;
- }
-
- /* Consumed blocks */
- block = consumedBlockHead.get(sizeClass);
- if (!block.isZero()) {
- flushedBlockHead.set(sizeClass, BlockAllocator.getNext(block));
- lock.release();
- BlockAllocator.setNext(block, Address.zero());
- return block;
- }
-
- /* All swept! */
- lock.release();
- return Address.zero();
- }
-
- /**
- * Does this block contain any live cells?
- */
- @Inline
- public boolean sweepCells(Sweeper sweeper, Address block, int sizeClass) {
- Extent blockSize = Extent.fromIntSignExtend(BlockAllocator.blockSize(blockSizeClass[sizeClass]));
- Address cursor = block.plus(blockHeaderSize[sizeClass]);
- Address end = block.plus(blockSize);
- Extent cellExtent = Extent.fromIntSignExtend(cellSize[sizeClass]);
- boolean containsLive = false;
- while (cursor.LT(end)) {
- ObjectReference current = VM.objectModel.getObjectFromStartAddress(cursor);
- boolean free = true;
- if (!current.isNull()) {
- free = !liveBitSet(current);
- if (!free) {
- free = sweeper.sweepCell(current);
- if (free) unsyncClearLiveBit(current);
- }
- }
- if (!free) {
- containsLive = true;
- }
- cursor = cursor.plus(cellExtent);
- }
- return containsLive;
- }
-
- /**
- * A callback used to perform sweeping of a free list space.
- */
- @Uninterruptible
- public abstract static class Sweeper {
- public abstract boolean sweepCell(ObjectReference object);
- }
-
- /****************************************************************************
- *
- * Live bit manipulation
- */
-
- /**
- * Atomically set the live bit for a given object
- *
- * @param object The object whose live bit is to be set.
- * @return True if the bit was changed to true.
- */
- @Inline
- public static boolean testAndSetLiveBit(ObjectReference object) {
- return updateLiveBit(VM.objectModel.objectStartRef(object), true, true);
- }
-
- /**
- * Set the live bit for the block containing the given object
- *
- * @param object The object whose blocks liveness is to be set.
- */
- @Inline
- protected static void markBlock(ObjectReference object) {
- BlockAllocator.markBlockMeta(object);
- }
-
- /**
- * Set the live bit for the given block.
- *
- * @param block The block whose liveness is to be set.
- */
- @Inline
- protected static void markBlock(Address block) {
- BlockAllocator.markBlockMeta(block);
- }
-
- /**
- * Set the live bit for a given object, without using
- * synchronization primitives---must only be used when contention
- * for live bit is strictly not possible
- *
- * @param object The object whose live bit is to be set.
- */
- @Inline
- public static boolean unsyncSetLiveBit(ObjectReference object) {
- return updateLiveBit(VM.objectModel.refToAddress(object), true, false);
- }
-
- /**
- * Set the live bit for a given address
- *
- * @param address The address whose live bit is to be set.
- * @param set True if the bit is to be set, as opposed to cleared
- * @param atomic True if we want to perform this operation atomically
- */
- @Inline
- private static boolean updateLiveBit(Address address, boolean set, boolean atomic) {
- Word oldValue, newValue;
- Address liveWord = getLiveWordAddress(address);
- Word mask = getMask(address, true);
- if (atomic) {
- do {
- oldValue = liveWord.prepareWord();
- newValue = (set) ? oldValue.or(mask) : oldValue.and(mask.not());
- } while (!liveWord.attempt(oldValue, newValue));
- } else {
- oldValue = liveWord.loadWord();
- liveWord.store(set ? oldValue.or(mask) : oldValue.and(mask.not()));
- }
- return oldValue.and(mask).NE(mask);
- }
-
- /**
- * Test the live bit for a given object
- *
- * @param object The object whose live bit is to be set.
- */
- @Inline
- protected static boolean liveBitSet(ObjectReference object) {
- return liveBitSet(VM.objectModel.refToAddress(object));
- }
-
- /**
- * Set the live bit for a given address
- *
- * @param address The address whose live bit is to be set.
- * @return true if this operation changed the state of the live bit.
- */
- @Inline
- protected static boolean liveBitSet(Address address) {
- Address liveWord = getLiveWordAddress(address);
- Word mask = getMask(address, true);
- Word value = liveWord.loadWord();
- return value.and(mask).EQ(mask);
- }
-
- /**
- * Clear the live bit for a given object
- *
- * @param object The object whose live bit is to be cleared.
- */
- @Inline
- protected static void clearLiveBit(ObjectReference object) {
- clearLiveBit(VM.objectModel.refToAddress(object));
- }
-
- /**
- * Clear the live bit for a given address
- *
- * @param address The address whose live bit is to be cleared.
- */
- @Inline
- protected static void clearLiveBit(Address address) {
- updateLiveBit(address, false, true);
- }
-
- /**
- * Clear the live bit for a given object
- *
- * @param object The object whose live bit is to be cleared.
- */
- @Inline
- protected static void unsyncClearLiveBit(ObjectReference object) {
- unsyncClearLiveBit(VM.objectModel.refToAddress(object));
- }
-
- /**
- * Clear the live bit for a given address
- *
- * @param address The address whose live bit is to be cleared.
- */
- @Inline
- protected static void unsyncClearLiveBit(Address address) {
- updateLiveBit(address, false, false);
- }
-
- /**
- * Clear all live bits for a block
- */
- protected void clearLiveBits(Address block, int sizeClass) {
- int blockSize = BlockAllocator.blockSize(blockSizeClass[sizeClass]);
- Address cursor = getLiveWordAddress(block);
- Address sentinel = getLiveWordAddress(block.plus(blockSize - 1));
- while (cursor.LE(sentinel)) {
- cursor.store(Word.zero());
- cursor = cursor.plus(BYTES_IN_WORD);
- }
- }
-
- protected void zeroLiveBits() {
- Extent bytes = Extent.fromIntSignExtend(EmbeddedMetaData.BYTES_IN_REGION>>LOG_LIVE_COVERAGE);
- if (contiguous) {
- Address end = ((FreeListPageResource)pr).getHighWater();
- Address cursor = start;
- while (cursor.LT(end)) {
- Address metadata = EmbeddedMetaData.getMetaDataBase(cursor).plus(META_DATA_OFFSET);
- VM.memory.zero(metadata, bytes);
- cursor = cursor.plus(EmbeddedMetaData.BYTES_IN_REGION);
- }
- } else {
- for(Address cursor = headDiscontiguousRegion; !cursor.isZero(); cursor = Map.getNextContiguousRegion(cursor)) {
- Address metadata = EmbeddedMetaData.getMetaDataBase(cursor).plus(META_DATA_OFFSET);
- VM.memory.zero(metadata, bytes);
- }
- }
- }
-
- /**
- * Align an address so that it corresponds to a live word boundary.
- * In other words, if the live bit for the given address is not the
- * zeroth bit of a live word, round the address down such that it
- * does.
- *
- * @param address The address to be aligned to a live word
- * @return The given address, aligned down so that it corresponds to
- * an address on a live word boundary.
- */
- private static Address alignToLiveStride(Address address) {
- return address.toWord().and(LIVE_WORD_STRIDE_MASK).toAddress();
- }
-
- /**
- * Given an address, produce a bit mask for the live table
- *
- * @param address The address whose live bit mask is to be established
- * @param set True if we want the mask for <i>setting</i> the bit,
- * false if we want the mask for <i>clearing</i> the bit.
- * @return The appropriate bit mask for object for the live table for.
- */
- @Inline
- private static Word getMask(Address address, boolean set) {
- int shift = address.toWord().rshl(OBJECT_LIVE_SHIFT).and(WORD_SHIFT_MASK).toInt();
- Word rtn = Word.one().lsh(shift);
- return (set) ? rtn : rtn.not();
- }
-
- /**
- * Given an address, return the address of the live word for
- * that address.
- *
- * @param address The address whose live word address is to be returned
- * @return The address of the live word for this object
- */
- @Inline
- private static Address getLiveWordAddress(Address address) {
- Address rtn = EmbeddedMetaData.getMetaDataBase(address);
- return rtn.plus(META_DATA_OFFSET).plus(EmbeddedMetaData.getMetaDataOffset(address, LOG_LIVE_COVERAGE, LOG_BYTES_IN_WORD));
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/policy/Space.java b/vmkit/mmtk/java/src/org/mmtk/policy/Space.java
deleted file mode 100644
index 2a2d916..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/policy/Space.java
+++ /dev/null
@@ -1,744 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.policy;
-
-import org.mmtk.plan.Plan;
-import org.mmtk.plan.TransitiveClosure;
-import org.mmtk.utility.heap.Map;
-import org.mmtk.utility.heap.Mmapper;
-import org.mmtk.utility.heap.PageResource;
-import org.mmtk.utility.heap.SpaceDescriptor;
-import org.mmtk.utility.heap.VMRequest;
-import org.mmtk.utility.options.Options;
-import org.mmtk.utility.Log;
-import org.mmtk.utility.Constants;
-
-import org.mmtk.vm.VM;
-
-import org.vmmagic.pragma.*;
-import org.vmmagic.unboxed.*;
-
-/**
- * This class defines and manages spaces. Each policy is an instance
- * of a space. A space is a region of virtual memory (contiguous or
- * discontigous) which is subject to the same memory management
- * regime. Multiple spaces (instances of this class or its
- * descendants) may have the same policy (eg there could be numerous
- * instances of CopySpace, each with different roles). Spaces are
- * defined in terms of a unique region of virtual memory, so no two
- * space instances ever share any virtual memory.<p>
- *
- * In addition to tracking virtual memory use and the mapping to
- * policy, spaces also manage memory consumption (<i>used</i> virtual
- * memory).<p>
- *
- */
-@Uninterruptible
-public abstract class Space implements Constants {
-
- /****************************************************************************
- *
- * Class variables
- */
-
- private static boolean DEBUG = false;
-
- // the following is somewhat arbitrary for the 64 bit system at this stage
- public static final int LOG_ADDRESS_SPACE = (BYTES_IN_ADDRESS == 4) ? 32 : 40;
- public static final int LOG_BYTES_IN_CHUNK = 22;
- public static final int BYTES_IN_CHUNK = 1 << LOG_BYTES_IN_CHUNK;
- public static final int PAGES_IN_CHUNK = 1 << (LOG_BYTES_IN_CHUNK - LOG_BYTES_IN_PAGE);
- private static final int LOG_MAX_CHUNKS = LOG_ADDRESS_SPACE - LOG_BYTES_IN_CHUNK;
- public static final int MAX_CHUNKS = 1 << LOG_MAX_CHUNKS;
- public static final int MAX_SPACES = 20; // quite arbitrary
-
- public static final Address HEAP_START = chunkAlign(VM.HEAP_START, true);
- public static final Address AVAILABLE_START = chunkAlign(VM.AVAILABLE_START, false);
- public static final Address AVAILABLE_END = chunkAlign(VM.AVAILABLE_END, true);
- public static final Extent AVAILABLE_BYTES = AVAILABLE_END.toWord().minus(AVAILABLE_START.toWord()).toExtent();
- public static final int AVAILABLE_PAGES = AVAILABLE_BYTES.toWord().rshl(LOG_BYTES_IN_PAGE).toInt();
- public static final Address HEAP_END = chunkAlign(VM.HEAP_END, false);
-
- private static final boolean FORCE_SLOW_MAP_LOOKUP = false;
-
- private static final int PAGES = 0;
- private static final int MB = 1;
- private static final int PAGES_MB = 2;
- private static final int MB_PAGES = 3;
-
- private static int spaceCount = 0;
- private static Space[] spaces = new Space[MAX_SPACES];
- private static Address heapCursor = HEAP_START;
- private static Address heapLimit = HEAP_END;
-
- /****************************************************************************
- *
- * Instance variables
- */
- private final String name;
- private final int nameLength;
- protected final int descriptor;
- private final int index;
- private final VMRequest vmRequest;
-
- protected final boolean immortal;
- protected final boolean movable;
- protected final boolean contiguous;
-
- protected PageResource pr;
- protected final Address start;
- protected final Extent extent;
- protected Address headDiscontiguousRegion;
-
- private boolean allocationFailed;
-
- /****************************************************************************
- *
- * Initialization
- */
-
- {
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(PAGES_IN_CHUNK > 1);
- }
-
- /**
- * This is the base constructor for <i>all</i> spaces.<p>
- *
- * @param name The name of this space (used when printing error messages etc)
- * @param movable Are objects in this space movable?
- * @param immortal Are objects in this space immortal (uncollected)?
- * @param vmRequest An object describing the virtual memory requested.
- */
- protected Space(String name, boolean movable, boolean immortal, VMRequest vmRequest) {
- this.name = name;
- this.nameLength = name.length(); // necessary to avoid calling length() in uninterruptible code
- this.movable = movable;
- this.immortal = immortal;
- this.vmRequest = vmRequest;
- this.index = spaceCount++;
- spaces[index] = this;
-
- if (vmRequest.type == VMRequest.REQUEST_DISCONTIGUOUS) {
- this.contiguous = false;
- this.descriptor = SpaceDescriptor.createDescriptor();
- this.start = Address.zero();
- this.extent = Extent.zero();
- this.headDiscontiguousRegion = Address.zero();
- VM.memory.setHeapRange(index, HEAP_START, HEAP_END); // this should really be refined! Once we have a code space, we can be a lot more specific about what is a valid code heap area
- return;
- }
-
- Address start;
- Extent extent;
-
- if (vmRequest.type == VMRequest.REQUEST_FRACTION) {
- extent = getFracAvailable(vmRequest.frac);
- } else {
- extent = vmRequest.extent;
- }
-
- if (extent.NE(chunkAlign(extent, false))) {
- VM.assertions.fail(name + " requested non-aligned extent: " + extent.toLong() + " bytes");
- }
-
- if (vmRequest.type == VMRequest.REQUEST_FIXED) {
- start = vmRequest.start;
- if (start.NE(chunkAlign(start, false))) {
- VM.assertions.fail(name + " starting on non-aligned boundary: " + start.toLong() + " bytes");
- }
- } else if (vmRequest.top) {
- heapLimit = heapLimit.minus(extent);
- start = heapLimit;
- } else {
- start = heapCursor;
- heapCursor = heapCursor.plus(extent);
- }
-
- if (heapCursor.GT(heapLimit)) {
- Log.write("Out of virtual address space allocating \"");
- Log.write(name); Log.write("\" at ");
- Log.write(heapCursor.minus(extent)); Log.write(" (");
- Log.write(heapCursor); Log.write(" > ");
- Log.write(heapLimit); Log.writeln(")");
- VM.assertions.fail("exiting");
- }
-
- this.contiguous = true;
- this.start = start;
- this.extent = extent;
- this.descriptor = SpaceDescriptor.createDescriptor(start, start.plus(extent));
-
- VM.memory.setHeapRange(index, start, start.plus(extent));
- Map.insert(start, extent, descriptor, this);
-
- if (DEBUG) {
- Log.write(name); Log.write(" ");
- Log.write(start); Log.write(" ");
- Log.write(start.plus(extent)); Log.write(" ");
- Log.writeln(extent.toWord());
- }
- }
-
- /****************************************************************************
- *
- * Accessor methods
- */
-
- /** Start of discontig getter @return The start of the discontiguous space */
- public static Address getDiscontigStart() { return heapCursor; }
-
- /** End of discontig getter @return The end of the discontiguous space */
- public static Address getDiscontigEnd() { return heapLimit.minus(1); }
-
- /** Name getter @return The name of this space */
- public final String getName() { return name; }
-
- /** Start getter @return The start address of this space */
- public final Address getStart() { return start; }
-
- /** Extent getter @return The size (extent) of this space */
- public final Extent getExtent() { return extent; }
-
- /** Descriptor method @return The integer descriptor for this space */
- public final int getDescriptor() { return descriptor; }
-
- /** Index getter @return The index (ordinal number) of this space */
- public final int getIndex() { return index; }
-
- /** Immortal getter @return True if this space is never collected */
- public final boolean isImmortal() { return immortal; }
-
- /** Movable getter @return True if objects in this space may move */
- public boolean isMovable() { return movable; }
-
- /** Allocationfailed getter @return true if an allocation has failed since GC */
- public final boolean allocationFailed() { return allocationFailed; }
-
- /** Clear Allocationfailed flag */
- public final void clearAllocationFailed() { allocationFailed = false; }
-
- /** ReservedPages getter @return The number of reserved pages */
- public final int reservedPages() { return pr.reservedPages(); }
-
- /** CommittedPages getter @return The number of committed pages */
- public final int committedPages() { return pr.committedPages(); }
-
- /** RequiredPages getter @return The number of required pages */
- public final int requiredPages() { return pr.requiredPages(); }
-
- /** AvailablePages getter @return The number of pages available for allocation */
- public final int availablePhysicalPages() { return pr.getAvailablePhysicalPages(); }
-
- /** Cumulative committed pages getter @return Cumulative committed pages. */
- public static long cumulativeCommittedPages() {
- return PageResource.cumulativeCommittedPages();
- }
-
- /****************************************************************************
- *
- * Object and address tests / accessors
- */
-
- /**
- * Return true if the given object is in an immortal (uncollected) space.
- *
- * @param object The object in question
- * @return True if the given object is in an immortal (uncollected) space.
- */
- public static boolean isImmortal(ObjectReference object) {
- Space space = getSpaceForObject(object);
- if (space == null)
- return true;
- else
- return space.isImmortal();
- }
-
- /**
- * Return true if the given object is in space that moves objects.
- *
- * @param object The object in question
- * @return True if the given object is in space that moves objects.
- */
- @Inline
- public static boolean isMovable(ObjectReference object) {
- Space space = getSpaceForObject(object);
- if (space == null)
- return true;
- else
- return space.isMovable();
- }
-
- /**
- * Return true if the given object is in a space managed by MMTk.
- *
- * @param object The object in question
- * @return True if the given object is in a space managed by MMTk.
- */
- @Inline
- public static boolean isMappedObject(ObjectReference object) {
- return !object.isNull() && (getSpaceForObject(object) != null) && Mmapper.objectIsMapped(object);
- }
-
- /**
- * Return true if the given address is in a space managed by MMTk.
- *
- * @param address The address in question
- * @return True if the given address is in a space managed by MMTk.
- */
- @Inline
- public static boolean isMappedAddress(Address address) {
- return Map.getSpaceForAddress(address) != null && Mmapper.addressIsMapped(address);
- }
-
- /**
- * Return true if the given object is the space associated with the
- * given descriptor.
- *
- * @param descriptor The descriptor for a space
- * @param object The object in question
- * @return True if the given object is in the space associated with
- * the descriptor.
- */
- @Inline
- public static boolean isInSpace(int descriptor, ObjectReference object) {
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(!object.isNull());
- return isInSpace(descriptor, VM.objectModel.refToAddress(object));
- }
-
- /**
- * Return true if the given address is the space associated with the
- * given descriptor.
- *
- * @param descriptor The descriptor for a space
- * @param address The address in question.
- * @return True if the given address is in the space associated with
- * the descriptor.
- */
- @Inline
- public static boolean isInSpace(int descriptor, Address address) {
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(!address.isZero());
- if (FORCE_SLOW_MAP_LOOKUP || !SpaceDescriptor.isContiguous(descriptor)) {
- return Map.getDescriptorForAddress(address) == descriptor;
- } else {
- Address start = SpaceDescriptor.getStart(descriptor);
- if (!VM.VERIFY_ASSERTIONS &&
- SpaceDescriptor.isContiguousHi(descriptor))
- return address.GE(start);
- else {
- Extent size = Word.fromIntSignExtend(SpaceDescriptor.getChunks(descriptor)).lsh(LOG_BYTES_IN_CHUNK).toExtent();
- Address end = start.plus(size);
- return address.GE(start) && address.LT(end);
- }
- }
- }
-
- /**
- * Return the space for a given object
- *
- * @param object The object in question
- * @return The space containing the object
- */
- @Inline
- public static Space getSpaceForObject(ObjectReference object) {
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(!object.isNull());
- return Map.getSpaceForAddress(VM.objectModel.refToAddress(object));
- }
-
- /**
- * Return the space for a given address, not necessarily the
- * start address of an object.
- *
- * @param addr The address in question
- * @return The space containing the address
- */
- public static Space getSpaceForAddress(Address addr) {
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(!addr.isZero());
- return Map.getSpaceForAddress(addr);
- }
-
- /****************************************************************************
- *
- * Page management
- */
-
- /**
- * Acquire a number of pages from the page resource, returning
- * either the address of the first page, or zero on failure.<p>
- *
- * This may trigger a GC if necessary.<p>
- *
- * First the page budget is checked to see whether polling the GC is
- * necessary. If so, the GC is polled. If a GC is required then the
- * request fails and zero is returned.<p>
- *
- * If the check of the page budget does not lead to GC being
- * triggered, then a request is made for specific pages in virtual
- * memory. If the page manager cannot satisify this request, then
- * the request fails, a GC is forced, and zero is returned.
- * Otherwise the address of the first page is returned.<p>
- *
- * @param pages The number of pages requested
- * @return The start of the first page if successful, zero on
- * failure.
- */
- public final Address acquire(int pages) {
- boolean allowPoll = !Plan.gcInProgress() && Plan.isInitialized() && !VM.collection.isEmergencyAllocation();
-
- /* First check page budget and poll if necessary */
- if (!pr.reservePages(pages)) {
- /* Need to poll, either fixing budget or requiring GC */
- if (allowPoll && VM.activePlan.global().poll(false, this)) {
- pr.clearRequest(pages);
- return Address.zero(); // GC required, return failure
- }
- }
-
- /* Page budget is ok, try to acquire virtual memory */
- Address rtn = pr.getNewPages(pages);
- if (rtn.isZero()) {
- /* Failed, so force a GC */
- if (VM.collection.isEmergencyAllocation()) {
- pr.clearRequest(pages);
- VM.assertions.fail("Failed emergency allocation");
- }
- if (!allowPoll) VM.assertions.fail("Physical allocation failed during special (collection/emergency) allocation!");
- allocationFailed = true;
- VM.collection.reportPhysicalAllocationFailed();
- VM.activePlan.global().poll(true, this);
- pr.clearRequest(pages);
- return Address.zero();
- }
-
- if (allowPoll) VM.collection.reportAllocationSuccess();
- return rtn;
- }
-
- /**
- * Extend the virtual memory associated with a particular discontiguous
- * space. This simply involves requesting a suitable number of chunks
- * from the pool of chunks available to discontiguous spaces.
- *
- * @param chunks The number of chunks by which the space needs to be extended
- * @return The address of the new discontiguous space.
- */
- public Address growDiscontiguousSpace(int chunks) {
- return headDiscontiguousRegion = Map.allocateContiguousChunks(descriptor, this, chunks, headDiscontiguousRegion);
- }
-
- /**
- * Return the number of chunks required to satisfy a request for a certain number of pages
- *
- * @param pages The number of pages desired
- * @return The number of chunks needed to satisfy the request
- */
- public static int requiredChunks(int pages) {
- Extent extent = chunkAlign(Extent.fromIntZeroExtend(pages<<LOG_BYTES_IN_PAGE), false);
- return extent.toWord().rshl(LOG_BYTES_IN_CHUNK).toInt();
- }
-
- /**
- * This hook is called by page resources each time a space grows. The space may
- * tap into the hook to monitor heap growth. The call is made from within the
- * page resources' critical region, immediately before yielding the lock.
- *
- * @param start The start of the newly allocated space
- * @param bytes The size of the newly allocated space
- * @param newChunk True if the new space encroached upon or started a new chunk or chunks.
- */
- public void growSpace(Address start, Extent bytes, boolean newChunk) {}
-
- /**
- * Release one or more contiguous chunks associated with a discontiguous
- * space.
- *
- * @param chunk THe address of the start of the contiguous chunk or chunks
- * @return The number of chunks freed
- */
- public int releaseDiscontiguousChunks(Address chunk) {
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(chunk.EQ(chunkAlign(chunk, true)));
- if (chunk.EQ(headDiscontiguousRegion)) {
- headDiscontiguousRegion = Map.getNextContiguousRegion(chunk);
- }
- return Map.freeContiguousChunks(chunk);
- }
-
- /**
- * Release a unit of allocation (a page or pages)
- *
- * @param start The address of the start of the region to be released
- */
- public abstract void release(Address start);
-
- /**
- * Clear the allocation failed flag for all spaces.
- *
- */
- public static void clearAllAllocationFailed() {
- for (int i = 0; i < spaceCount; i++) {
- spaces[i].clearAllocationFailed();
- }
- }
-
- /**
- * Get the total number of pages reserved by all of the spaces
- *
- * @return the total number of pages reserved by all of the spaces
- */
- private static int getPagesReserved() {
- int pages = 0;
- for (int i = 0; i < spaceCount; i++) {
- pages += spaces[i].reservedPages();
- }
- return pages;
- }
-
- /****************************************************************************
- *
- * Debugging / printing
- */
-
- /**
- * Print out the memory used by all spaces, in megabytes
- */
- public static void printUsageMB() { printUsage(MB); }
-
- /**
- * Print out the memory used by all spaces, in megabytes
- */
- public static void printUsagePages() { printUsage(PAGES); }
-
- /**
- * Print out a map of virtual memory useage by all spaces
- */
- public static void printVMMap() {
- Log.writeln("Key: (I)mmortal (N)onmoving (D)iscontiguous (E)xtent (F)raction");
- Log.write(" HEAP_START "); Log.writeln(HEAP_START);
- Log.write("AVAILABLE_START "); Log.writeln(AVAILABLE_START);
- for (int i = 0; i < spaceCount; i++) {
- Space space = spaces[i];
-
- for (int s = 0; s < 11 - space.nameLength; s++)
- Log.write(" ");
- Log.write(space.name); Log.write(" ");
- Log.write(space.immortal ? "I" : " ");
- Log.write(space.movable ? " " : "N");
-
- if (space.contiguous) {
- Log.write(" ");
- Log.write(space.start); Log.write("->");
- Log.write(space.start.plus(space.extent.minus(1)));
- if (space.vmRequest.type == VMRequest.REQUEST_EXTENT) {
- Log.write(" E "); Log.write(space.vmRequest.extent);
- } else if (space.vmRequest.type == VMRequest.REQUEST_FRACTION) {
- Log.write(" F "); Log.write(space.vmRequest.frac);
- }
- Log.writeln();
- } else {
- Log.write("D [");
- for(Address a = space.headDiscontiguousRegion; !a.isZero(); a = Map.getNextContiguousRegion(a)) {
- Log.write(a); Log.write("->");
- Log.write(a.plus(Map.getContiguousRegionSize(a).minus(1)));
- if (Map.getNextContiguousRegion(a) != Address.zero())
- Log.write(", ");
- }
- Log.writeln("]");
- }
- }
- Log.write(" AVAILABLE_END "); Log.writeln(AVAILABLE_END);
- Log.write(" HEAP_END "); Log.writeln(HEAP_END);
- }
-
- /**
- * Interface to use to implement the Visitor Pattern for Spaces.
- */
- public static interface SpaceVisitor {
- void visit(Space s);
- }
-
- /**
- * Implement the Visitor Pattern for Spaces.
- * @param v The visitor to perform on each Space instance
- */
- @Interruptible
- public static void visitSpaces(SpaceVisitor v) {
- for (int i = 0; i < spaceCount; i++) {
- v.visit(spaces[i]);
- }
- }
-
-
- /**
- * Ensure that all MMTk spaces (all spaces aside from the VM space)
- * are mapped. Demand zero map all of them if they are not already
- * mapped.
- */
- @Interruptible
- public static void eagerlyMmapMMTkSpaces() {
- eagerlyMmapMMTkContiguousSpaces();
- eagerlyMmapMMTkDiscontiguousSpaces();
- }
-
-
- /**
- * Ensure that all contiguous MMTk spaces are mapped. Demand zero map
- * all of them if they are not already mapped.
- */
- @Interruptible
- public static void eagerlyMmapMMTkContiguousSpaces() {
- for (int i = 0; i < spaceCount; i++) {
- Space space = spaces[i];
- if (space != VM.memory.getVMSpace()) {
- if (Options.verbose.getValue() > 2) {
- Log.write("Mapping ");
- Log.write(space.name);
- Log.write(" ");
- Log.write(space.start);
- Log.write("->");
- Log.writeln(space.start.plus(space.extent.minus(1)));
- }
- Mmapper.ensureMapped(space.start, space.extent.toInt()>>LOG_BYTES_IN_PAGE);
- }
- }
- }
-
- /**
- * Ensure that all discontiguous MMTk spaces are mapped. Demand zero map
- * all of them if they are not already mapped.
- */
- @Interruptible
- public static void eagerlyMmapMMTkDiscontiguousSpaces() {
- Address regionStart = Space.getDiscontigStart();
- Address regionEnd = Space.getDiscontigEnd();
- int pages = regionEnd.diff(regionStart).toInt()>>LOG_BYTES_IN_PAGE;
- Log.write("Mapping discontiguous spaces ");
- Log.write(regionStart);
- Log.write("->");
- Log.writeln(regionEnd.minus(1));
- Mmapper.ensureMapped(getDiscontigStart(), pages);
- }
-
- /**
- * Print out the memory used by all spaces in either megabytes or
- * pages.
- *
- * @param mode An enumeration type that specifies the format for the
- * prining (PAGES, MB, PAGES_MB, or MB_PAGES).
- */
- private static void printUsage(int mode) {
- Log.write("used = ");
- printPages(getPagesReserved(), mode);
- boolean first = true;
- for (int i = 0; i < spaceCount; i++) {
- Space space = spaces[i];
- Log.write(first ? " = " : " + ");
- first = false;
- Log.write(space.name); Log.write(" ");
- printPages(space.reservedPages(), mode);
- }
- Log.writeln();
- }
-
- /**
- * Print out the number of pages and or megabytes, depending on the mode.
- *
- * @param pages The number of pages
- * @param mode An enumeration type that specifies the format for the
- * prining (PAGES, MB, PAGES_MB, or MB_PAGES).
- */
- private static void printPages(int pages, int mode) {
- double mb = (double) (pages << LOG_BYTES_IN_PAGE) / (double) (1 << 20);
- switch (mode) {
- case PAGES: Log.write(pages); Log.write(" pgs"); break;
- case MB: Log.write(mb); Log.write(" Mb"); break;
- case PAGES_MB: Log.write(pages); Log.write(" pgs ("); Log.write(mb); Log.write(" Mb)"); break;
- case MB_PAGES: Log.write(mb); Log.write(" Mb ("); Log.write(pages); Log.write(" pgs)"); break;
- default: VM.assertions.fail("writePages passed illegal printing mode");
- }
- }
-
- /****************************************************************************
- *
- * Miscellaneous
- */
-
- /**
- * Trace an object as part of a collection and return the object,
- * which may have been forwarded (if a copying collector).
- *
- * @param trace The trace being conducted.
- * @param object The object to trace
- * @return The object, forwarded, if appropriate
- */
- public abstract ObjectReference traceObject(TransitiveClosure trace, ObjectReference object);
-
-
- /**
- * Has the object in this space been reached during the current collection.
- * This is used for GC Tracing.
- *
- * @param object The object reference.
- * @return True if the object is reachable.
- */
- public boolean isReachable(ObjectReference object) {
- return isLive(object);
- }
-
-
- /**
- * Is the object in this space alive?
- *
- * @param object The object reference.
- * @return True if the object is live.
- */
- public abstract boolean isLive(ObjectReference object);
-
- /**
- * Align an address to a space chunk
- *
- * @param addr The address to be aligned
- * @param down If true the address will be rounded down, otherwise
- * it will rounded up.
- * @return The chunk-aligned address
- */
- public static Address chunkAlign(Address addr, boolean down) {
- if (!down) addr = addr.plus(BYTES_IN_CHUNK - 1);
- return addr.toWord().rshl(LOG_BYTES_IN_CHUNK).lsh(LOG_BYTES_IN_CHUNK).toAddress();
- }
-
- /**
- * Align an extent to a space chunk
- *
- * @param bytes The extent to be aligned
- * @param down If true the extent will be rounded down, otherwise
- * it will rounded up.
- * @return The chunk-aligned extent
- */
- public static Extent chunkAlign(Extent bytes, boolean down) {
- if (!down) bytes = bytes.plus(BYTES_IN_CHUNK - 1);
- return bytes.toWord().rshl(LOG_BYTES_IN_CHUNK).lsh(LOG_BYTES_IN_CHUNK).toExtent();
- }
-
- /**
- * Convert a fraction into a number of bytes according to the
- * fraction of available bytes.
- *
- * @param frac The fraction of available virtual memory desired
- * @return The corresponding number of bytes, chunk-aligned.
- */
- public static Extent getFracAvailable(float frac) {
- long bytes = (long) (frac * AVAILABLE_BYTES.toLong());
- Word mb = Word.fromIntSignExtend((int) (bytes >> LOG_BYTES_IN_MBYTE));
- Extent rtn = mb.lsh(LOG_BYTES_IN_MBYTE).toExtent();
- return chunkAlign(rtn, false);
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/policy/immix/Block.java b/vmkit/mmtk/java/src/org/mmtk/policy/immix/Block.java
deleted file mode 100644
index 6e71257..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/policy/immix/Block.java
+++ /dev/null
@@ -1,203 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.policy.immix;
-
-import static org.mmtk.policy.immix.ImmixConstants.*;
-
-import org.mmtk.utility.Constants;
-import org.mmtk.vm.VM;
-
-import org.vmmagic.pragma.Uninterruptible;
-import org.vmmagic.unboxed.Address;
-import org.vmmagic.unboxed.Extent;
-import org.vmmagic.unboxed.Offset;
-
-/**
- * This class defines operations over block-granularity meta-data
- *
- */
-@Uninterruptible
-public class Block implements Constants {
-
- static Address align(final Address ptr) {
- return ptr.toWord().and(BLOCK_MASK.not()).toAddress();
- }
-
- public static boolean isAligned(final Address address) {
- return address.EQ(align(address));
- }
-
- private static int getChunkIndex(final Address block) {
- return block.toWord().and(CHUNK_MASK).rshl(LOG_BYTES_IN_BLOCK).toInt();
- }
-
- /***************************************************************************
- * Block marking
- */
- public static boolean isUnused(final Address address) {
- return getBlockMarkState(address) == UNALLOCATED_BLOCK_STATE;
- }
-
- static boolean isUnusedState(Address cursor) {
- return cursor.loadShort() == UNALLOCATED_BLOCK_STATE;
- }
-
- static short getMarkState(Address cursor) {
- return cursor.loadShort();
- }
-
- static void setState(Address cursor, short value) {
- cursor.store(value);
- }
-
- public static short getBlockMarkState(Address address) {
- return getBlockMarkStateAddress(address).loadShort();
- }
-
- static void setBlockAsInUse(Address address) {
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(isUnused(address));
- setBlockState(address, UNMARKED_BLOCK_STATE);
- }
-
- public static void setBlockAsReused(Address address) {
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(!isUnused(address));
- setBlockState(address, REUSED_BLOCK_STATE);
- }
-
- static void setBlockAsUnallocated(Address address) {
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(!isUnused(address));
- getBlockMarkStateAddress(address).store(UNALLOCATED_BLOCK_STATE);
- }
-
- private static void setBlockState(Address address, short value) {
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(value != UNALLOCATED_BLOCK_STATE);
- getBlockMarkStateAddress(address).store(value);
- }
-
- static Address getBlockMarkStateAddress(Address address) {
- Address chunk = Chunk.align(address);
- int index = getChunkIndex(address);
- Address rtn = chunk.plus(Chunk.BLOCK_STATE_TABLE_OFFSET).plus(index<<LOG_BYTES_IN_BLOCK_STATE_ENTRY);
- if (VM.VERIFY_ASSERTIONS) {
- Address block = chunk.plus(index<<LOG_BYTES_IN_BLOCK);
- VM.assertions._assert(isAligned(block));
- boolean valid = rtn.GE(chunk.plus(Chunk.BLOCK_STATE_TABLE_OFFSET)) && rtn.LT(chunk.plus(Chunk.BLOCK_STATE_TABLE_OFFSET+BLOCK_STATE_TABLE_BYTES));
- VM.assertions._assert(valid);
- }
- return rtn;
- }
-
- /***************************************************************************
- * Sweeping
- */
- static short sweepOneBlock(Address block, int[] markHistogram, final byte markState, final boolean resetMarkState) {
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(isAligned(block));
-
- final boolean unused = isUnused(block);
- if (unused && !SANITY_CHECK_LINE_MARKS)
- return 0;
-
- Address markTable = Line.getBlockMarkTable(block);
-
- short markCount = 0;
- short conservativeSpillCount = 0;
- byte mark, lastMark = 0;
- for (int offset = 0; offset < (LINES_IN_BLOCK<<Line.LOG_BYTES_IN_LINE_STATUS); offset += Line.BYTES_IN_LINE_STATUS) {
- if (VM.VERIFY_ASSERTIONS) {
- VM.assertions._assert(markTable.plus(offset).GE(Chunk.align(block).plus(Chunk.LINE_MARK_TABLE_OFFSET)));
- VM.assertions._assert(markTable.plus(offset).LT(Chunk.align(block).plus(Chunk.LINE_MARK_TABLE_OFFSET+Line.LINE_MARK_TABLE_BYTES)));
- }
- mark = markTable.loadByte(Offset.fromIntZeroExtend(offset));
- if (resetMarkState)
- markTable.store((byte) (mark == markState ? RESET_LINE_MARK_STATE : 0), Offset.fromIntZeroExtend(offset));
-
- if (mark == markState)
- markCount++;
- else if (lastMark == markState)
- conservativeSpillCount++;
- else if (SANITY_CHECK_LINE_MARKS && lastMark != markState) {
- VM.memory.zero(block.plus(offset<<(LOG_BYTES_IN_LINE-Line.LOG_BYTES_IN_LINE_STATUS)),Extent.fromIntZeroExtend(BYTES_IN_LINE));
- }
-
- lastMark = mark;
- }
- if (VM.VERIFY_ASSERTIONS) {
- VM.assertions._assert(markCount <= LINES_IN_BLOCK);
- VM.assertions._assert(markCount + conservativeSpillCount <= LINES_IN_BLOCK);
- VM.assertions._assert(markCount == 0 || !isUnused(block));
- }
-
- getDefragStateAddress(block).store(conservativeSpillCount);
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(markCount >= conservativeSpillCount);
- markHistogram[conservativeSpillCount] += markCount;
-
- markCount = (short) (markCount + conservativeSpillCount);
-
- return markCount;
- }
-
- /****************************************************************************
- * Block defrag state
- */
- public static boolean isDefragSource(Address address) {
- return getDefragStateAddress(address).loadShort() == BLOCK_IS_DEFRAG_SOURCE;
- }
-
- static void clearConservativeSpillCount(Address address) {
- getDefragStateAddress(address).store((short) 0);
- }
-
- static short getConservativeSpillCount(Address address) {
- return getDefragStateAddress(address).loadShort();
- }
-
- static Address getDefragStateAddress(Address address) {
- Address chunk = Chunk.align(address);
- int index = getChunkIndex(address);
- Address rtn = chunk.plus(Chunk.BLOCK_DEFRAG_STATE_TABLE_OFFSET).plus(index<<LOG_BYTES_IN_BLOCK_DEFRAG_STATE_ENTRY);
- if (VM.VERIFY_ASSERTIONS) {
- Address block = chunk.plus(index<<LOG_BYTES_IN_BLOCK);
- VM.assertions._assert(isAligned(block));
- boolean valid = rtn.GE(chunk.plus(Chunk.BLOCK_DEFRAG_STATE_TABLE_OFFSET)) && rtn.LT(chunk.plus(Chunk.BLOCK_DEFRAG_STATE_TABLE_OFFSET+BLOCK_DEFRAG_STATE_TABLE_BYTES));
- VM.assertions._assert(valid);
- }
- return rtn;
- }
-
- static void resetLineMarksAndDefragStateTable(short threshold, Address markStateBase, Address defragStateBase,
- Address lineMarkBase, int block) {
- Offset csOffset = Offset.fromIntZeroExtend(block<<LOG_BYTES_IN_BLOCK_DEFRAG_STATE_ENTRY);
- short state = defragStateBase.loadShort(csOffset);
- short defragState = BLOCK_IS_NOT_DEFRAG_SOURCE;
- if (state >= threshold) defragState = BLOCK_IS_DEFRAG_SOURCE;
- defragStateBase.store(defragState, csOffset);
- }
-
- private static final short UNALLOCATED_BLOCK_STATE = 0;
- private static final short UNMARKED_BLOCK_STATE = (short) (MAX_BLOCK_MARK_STATE + 1);
- private static final short REUSED_BLOCK_STATE = (short) (MAX_BLOCK_MARK_STATE + 2);
-
- private static final short BLOCK_IS_NOT_DEFRAG_SOURCE = 0;
- private static final short BLOCK_IS_DEFRAG_SOURCE = 1;
-
- /* block states */
- static final int LOG_BYTES_IN_BLOCK_STATE_ENTRY = LOG_BYTES_IN_SHORT; // use a short for now
- static final int BYTES_IN_BLOCK_STATE_ENTRY = 1<<LOG_BYTES_IN_BLOCK_STATE_ENTRY;
- static final int BLOCK_STATE_TABLE_BYTES = BLOCKS_IN_CHUNK<<LOG_BYTES_IN_BLOCK_STATE_ENTRY;
-
- /* per-block defrag state */
- static final int LOG_BYTES_IN_BLOCK_DEFRAG_STATE_ENTRY = LOG_BYTES_IN_SHORT;
- static final int BYTES_IN_BLOCK_DEFRAG_STATE_ENTRY = 1<<LOG_BYTES_IN_BLOCK_DEFRAG_STATE_ENTRY;
-
- static final int BLOCK_DEFRAG_STATE_TABLE_BYTES = BLOCKS_IN_CHUNK<<LOG_BYTES_IN_BLOCK_DEFRAG_STATE_ENTRY;
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/policy/immix/Chunk.java b/vmkit/mmtk/java/src/org/mmtk/policy/immix/Chunk.java
deleted file mode 100644
index 4af85c4..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/policy/immix/Chunk.java
+++ /dev/null
@@ -1,166 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.policy.immix;
-
-import static org.mmtk.policy.Space.BYTES_IN_CHUNK;
-import static org.mmtk.policy.immix.ImmixConstants.*;
-
-import org.mmtk.utility.Constants;
-import org.mmtk.utility.Conversions;
-import org.mmtk.utility.heap.Mmapper;
-import org.mmtk.vm.VM;
-
-import org.vmmagic.pragma.Uninterruptible;
-import org.vmmagic.unboxed.Address;
-import org.vmmagic.unboxed.Extent;
-
-@Uninterruptible
-public class Chunk implements Constants {
-
- public static Address align(Address ptr) {
- return ptr.toWord().and(CHUNK_MASK.not()).toAddress();
- }
-
- static boolean isAligned(Address ptr) {
- return ptr.EQ(align(ptr));
- }
-
- static int getByteOffset(Address ptr) {
- return ptr.toWord().and(CHUNK_MASK).toInt();
- }
-
- /**
- * Return the number of pages of metadata required per chunk.
- */
- static int getRequiredMetaDataPages() {
- Extent bytes = Extent.fromIntZeroExtend(ROUNDED_METADATA_BYTES_PER_CHUNK);
- return Conversions.bytesToPagesUp(bytes);
- }
-
- static void sweep(Address chunk, Address end, ImmixSpace space, int[] markHistogram, final byte markValue, final boolean resetMarks) {
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(isAligned(chunk));
- Address start = getFirstUsableBlock(chunk);
- Address cursor = Block.getBlockMarkStateAddress(start);
- for (int index = FIRST_USABLE_BLOCK_INDEX; index < BLOCKS_IN_CHUNK; index++) {
- Address block = chunk.plus(index<<LOG_BYTES_IN_BLOCK);
- if (block.GT(end)) break;
- final boolean defragSource = space.inImmixDefragCollection() && Block.isDefragSource(block);
- short marked = Block.sweepOneBlock(block, markHistogram, markValue, resetMarks);
- if (marked == 0) {
- if (!Block.isUnusedState(cursor)) {
- space.release(block);
- if (defragSource) Defrag.defragBytesFreed.inc(BYTES_IN_BLOCK);
- }
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(Block.isUnused(block));
- } else {
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(marked > 0 && marked <= LINES_IN_BLOCK);
- Block.setState(cursor, marked);
- if (defragSource) Defrag.defragBytesNotFreed.inc(BYTES_IN_BLOCK);
- }
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(Block.isUnused(block) || (Block.getBlockMarkState(block) == marked && marked > 0 && marked <= MAX_BLOCK_MARK_STATE));
- cursor = cursor.plus(Block.BYTES_IN_BLOCK_STATE_ENTRY);
- }
- }
-
- static void clearMetaData(Address chunk) {
- if (VM.VERIFY_ASSERTIONS) {
- VM.assertions._assert(isAligned(chunk));
- VM.assertions._assert(Conversions.isPageAligned(chunk));
- VM.assertions._assert(Conversions.isPageAligned(ROUNDED_METADATA_BYTES_PER_CHUNK));
- }
- Mmapper.ensureMapped(chunk, ROUNDED_METADATA_PAGES_PER_CHUNK);
- VM.memory.zero(chunk, Extent.fromIntZeroExtend(ROUNDED_METADATA_BYTES_PER_CHUNK));
- if (VM.VERIFY_ASSERTIONS) checkMetaDataCleared(chunk, chunk);
- }
-
- private static void checkMetaDataCleared(Address chunk, Address value) {
- VM.assertions._assert(isAligned(chunk));
- Address block = Chunk.getHighWater(chunk);
- if (value.EQ(chunk)) {
- VM.assertions._assert(block.isZero());
- block = chunk.plus(Chunk.ROUNDED_METADATA_BYTES_PER_CHUNK);
- } else {
- block = block.plus(BYTES_IN_BLOCK); // start at first block after highwater
- VM.assertions._assert(Block.align(block).EQ(block));
- }
- while (block.LT(chunk.plus(BYTES_IN_CHUNK))) {
- VM.assertions._assert(Chunk.align(block).EQ(chunk));
- VM.assertions._assert(Block.isUnused(block));
- block = block.plus(BYTES_IN_BLOCK);
- }
- }
-
- static void updateHighWater(Address value) {
- Address chunk = align(value);
- if (getHighWater(chunk).LT(value)) {
- setHighWater(chunk, value);
- }
- }
-
- private static void setHighWater(Address chunk, Address value) {
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(isAligned(chunk));
- chunk.plus(HIGHWATER_OFFSET).store(value);
- }
-
- public static Address getHighWater(Address chunk) {
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(isAligned(chunk));
- return chunk.plus(HIGHWATER_OFFSET).loadAddress();
- }
-
- static void setMap(Address chunk, int value) {
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(isAligned(chunk));
- chunk.plus(MAP_OFFSET).store(value);
- }
-
- static int getMap(Address chunk) {
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(isAligned(chunk));
- int rtn = chunk.plus(MAP_OFFSET).loadInt();
- return (rtn < 0) ? -rtn : rtn;
- }
-
- static void resetLineMarksAndDefragStateTable(Address chunk, short threshold) {
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(isAligned(chunk));
- Address markStateBase = Block.getBlockMarkStateAddress(chunk);
- Address defragStateBase = Block.getDefragStateAddress(chunk);
- Address lineMarkBase = Line.getChunkMarkTable(chunk);
- for (int b = FIRST_USABLE_BLOCK_INDEX; b < BLOCKS_IN_CHUNK; b++) {
- Block.resetLineMarksAndDefragStateTable(threshold, markStateBase, defragStateBase, lineMarkBase, b);
- }
- }
-
- static Address getFirstUsableBlock(Address chunk) {
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(isAligned(chunk));
- Address rtn = chunk.plus(ROUNDED_METADATA_BYTES_PER_CHUNK);
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(rtn.EQ(Block.align(rtn)));
- return rtn;
- }
-
- private static final int LOG_BYTES_IN_HIGHWATER_ENTRY = LOG_BYTES_IN_ADDRESS;
- private static final int HIGHWATER_BYTES = 1<<LOG_BYTES_IN_HIGHWATER_ENTRY;
- private static final int LOG_BYTES_IN_MAP_ENTRY = LOG_BYTES_IN_INT;
- private static final int MAP_BYTES = 1<<LOG_BYTES_IN_MAP_ENTRY;
-
- /* byte offsets for each type of metadata */
- static final int LINE_MARK_TABLE_OFFSET = 0;
- static final int BLOCK_STATE_TABLE_OFFSET = LINE_MARK_TABLE_OFFSET + Line.LINE_MARK_TABLE_BYTES;
- static final int BLOCK_DEFRAG_STATE_TABLE_OFFSET = BLOCK_STATE_TABLE_OFFSET + Block.BLOCK_STATE_TABLE_BYTES;
- static final int HIGHWATER_OFFSET = BLOCK_DEFRAG_STATE_TABLE_OFFSET + Block.BLOCK_DEFRAG_STATE_TABLE_BYTES;
- static final int MAP_OFFSET = HIGHWATER_OFFSET + HIGHWATER_BYTES;
- static final int METADATA_BYTES_PER_CHUNK = MAP_OFFSET + MAP_BYTES;
-
- /* FIXME we round the metadata up to block sizes just to ensure the underlying allocator gives us aligned requests */
- private static final int BLOCK_MASK = (1<<LOG_BYTES_IN_BLOCK) - 1;
- static final int ROUNDED_METADATA_BYTES_PER_CHUNK = (METADATA_BYTES_PER_CHUNK + BLOCK_MASK) & ~BLOCK_MASK;
- static final int ROUNDED_METADATA_PAGES_PER_CHUNK = ROUNDED_METADATA_BYTES_PER_CHUNK>>LOG_BYTES_IN_PAGE;
- public static final int FIRST_USABLE_BLOCK_INDEX = ROUNDED_METADATA_BYTES_PER_CHUNK>>LOG_BYTES_IN_BLOCK;
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/policy/immix/ChunkList.java b/vmkit/mmtk/java/src/org/mmtk/policy/immix/ChunkList.java
deleted file mode 100644
index 973be82..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/policy/immix/ChunkList.java
+++ /dev/null
@@ -1,183 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.policy.immix;
-
-import org.mmtk.plan.Plan;
-import org.mmtk.policy.Space;
-import org.mmtk.utility.Constants;
-import org.mmtk.vm.VM;
-import org.vmmagic.pragma.Uninterruptible;
-import org.vmmagic.unboxed.Address;
-import org.vmmagic.unboxed.AddressArray;
-
-@Uninterruptible
-public final class ChunkList implements Constants {
- private static final int LOG_PAGES_IN_CHUNK_MAP_BLOCK = 0;
- private static final int ENTRIES_IN_CHUNK_MAP_BLOCK = (BYTES_IN_PAGE<<LOG_PAGES_IN_CHUNK_MAP_BLOCK)>>LOG_BYTES_IN_ADDRESS;
- private static final int CHUNK_MAP_BLOCKS = 1<<4;
- private static final int MAX_ENTRIES_IN_CHUNK_MAP = ENTRIES_IN_CHUNK_MAP_BLOCK * CHUNK_MAP_BLOCKS;
- private AddressArray chunkMap = AddressArray.create(CHUNK_MAP_BLOCKS);
- private int chunkMapLimit = -1;
- private int chunkMapCursor = -1;
-
- void reset() {
- chunkMapLimit = chunkMapCursor;
- }
-
- public Address getHeadChunk() {
- if (chunkMapLimit < 0)
- return Address.zero();
- else
- return getMapAddress(0).loadAddress();
- }
-
- public Address getTailChunk() {
- if (chunkMapLimit < 0)
- return Address.zero();
- else
- return getMapAddress(chunkMapLimit).loadAddress();
- }
-
- void addNewChunkToMap(Address chunk) {
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(Chunk.isAligned(chunk));
- if (chunkMapCursor == MAX_ENTRIES_IN_CHUNK_MAP - 1)
- consolidateMap();
- chunkMapCursor++;
- int index = getChunkIndex(chunkMapCursor);
- int map = getChunkMap(chunkMapCursor);
- if (map >= CHUNK_MAP_BLOCKS) {
- Space.printUsageMB();
- VM.assertions.fail("Overflow of chunk map!");
- }
- if (chunkMap.get(map).isZero()) {
- Address tmp = Plan.metaDataSpace.acquire(1<<LOG_PAGES_IN_CHUNK_MAP_BLOCK);
- if (tmp.isZero()) {
- Space.printUsageMB();
- VM.assertions.fail("Failed to allocate space for chunk map. Is metadata virtual memory exhausted?");
- }
- chunkMap.set(map, tmp);
- }
- Address entry = chunkMap.get(map).plus(index<<LOG_BYTES_IN_ADDRESS);
- entry.store(chunk);
- Chunk.setMap(chunk, chunkMapCursor);
- if (VM.VERIFY_ASSERTIONS) checkMap();
- }
-
- void removeChunkFromMap(Address chunk) {
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(Chunk.isAligned(chunk));
- int entry = Chunk.getMap(chunk);
- getMapAddress(entry).store(Address.zero()); // zero it it
- Chunk.setMap(chunk, -entry);
- if (VM.VERIFY_ASSERTIONS) checkMap();
- }
-
- private int getChunkIndex(int entry) { return entry & (ENTRIES_IN_CHUNK_MAP_BLOCK - 1);}
- private int getChunkMap(int entry) {return entry & ~(ENTRIES_IN_CHUNK_MAP_BLOCK - 1);}
-
- private Address getMapAddress(int entry) {
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(entry >= 0);
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(entry <= chunkMapCursor);
- int index = getChunkIndex(entry);
- int map = getChunkMap(entry);
- return chunkMap.get(map).plus(index<<LOG_BYTES_IN_ADDRESS);
- }
-
- /**
- * A chunk iterator. Return the next chunk in sequence, or null if the
- * next chunk is the same chunk (ie there is only one chunk in the iterator).
- *
- * @param chunk The chunk
- * @return The next chunk in the sequence, or null if next is chunk.
- */
- public Address nextChunk(Address chunk) {
- return nextChunk(chunk, chunk);
- }
-
- /**
- * A chunk iterator. Return the next chunk in sequence, or null if the
- * next chunk is limit.
- *
- * @param chunk The chunk
- * @param limit The starting point (if next is equal to this, we're done)
- * @return The next chunk in the sequence, or null if next is limit.
- */
- private Address nextChunk(final Address chunk, final Address limit) {
- return nextChunk(chunk, Chunk.getMap(limit), 1);
- }
-
- /**
- * A chunk iterator. Return the next chunk in sequence, strided
- * by stride steps, or null if the next chunk is start.
- *
- * @param chunk The chunk
- * @param start The point where this iterator started, which defines its end-point
- * @param stride The stride by which the iterator should be stepped
- * @return The next chunk in the sequence, or null if next is start.
- */
- public Address nextChunk(final Address chunk, final int start, final int stride) {
- if (VM.VERIFY_ASSERTIONS) checkMap();
- return nextChunk(Chunk.getMap(chunk), start, stride);
- }
-
- /**
- * A chunk iterator. Return the next chunk in sequence, strided
- * by stride steps, or null if the next chunk is start.
- *
- * @param entry The entry we're currently up to
- * @param start The point where this iterator started, which defines its end-point
- * @param stride The stride by which the iterator should be stepped
- * @return The next chunk in the sequence, or null if next is start.
- */
- private Address nextChunk(int entry, final int start, final int stride) {
- if (VM.VERIFY_ASSERTIONS) checkMap();
- Address chunk;
- do {
- entry += stride;
- if (entry > chunkMapLimit) { entry = entry % stride; }
- chunk = getMapAddress(entry).loadAddress();
- } while (chunk.isZero() && entry != start);
- return entry == start ? Address.zero() : chunk;
- }
-
- public Address firstChunk(int ordinal, int stride) {
- if (ordinal > chunkMapCursor) return Address.zero();
- if (VM.VERIFY_ASSERTIONS) checkMap();
- Address chunk = getMapAddress(ordinal).loadAddress();
- return chunk.isZero() ? nextChunk(ordinal, ordinal, stride) : chunk;
- }
-
- private void checkMap() {
- VM.assertions._assert(chunkMapLimit <= chunkMapCursor);
- for (int entry = 0; entry <= chunkMapCursor; entry++) {
- Address chunk = getMapAddress(entry).loadAddress();
- if (!chunk.isZero())
- VM.assertions._assert(Chunk.getMap(chunk) == entry);
- }
- }
-
- public void consolidateMap() {
- int oldCursor = 0;
- int newCursor = -1;
- while (oldCursor <= chunkMapCursor) {
- Address chunk = getMapAddress(oldCursor).loadAddress();
- if (!chunk.isZero()) {
- getMapAddress(++newCursor).store(chunk);
- Chunk.setMap(chunk, newCursor);
- }
- oldCursor++;
- }
- chunkMapCursor = newCursor;
- chunkMapLimit = newCursor;
- if (VM.VERIFY_ASSERTIONS) checkMap();
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/policy/immix/CollectorLocal.java b/vmkit/mmtk/java/src/org/mmtk/policy/immix/CollectorLocal.java
deleted file mode 100644
index cf65acc..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/policy/immix/CollectorLocal.java
+++ /dev/null
@@ -1,114 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.policy.immix;
-
-import static org.mmtk.policy.immix.ImmixConstants.*;
-
-import org.mmtk.utility.Constants;
-import org.mmtk.vm.VM;
-
-import org.vmmagic.pragma.*;
-import org.vmmagic.unboxed.Address;
-
-/**
- * This class implements unsynchronized (local) elements of an
- * immix collector. Marking is done using both a bit in
- * each header's object word, and a mark byte. Sweeping is
- * performed lazily.<p>
- *
- */
-@Uninterruptible
-public final class CollectorLocal implements Constants {
-
- /****************************************************************************
- *
- * Class variables
- */
-
-
- /****************************************************************************
- *
- * Instance variables
- */
- private final ImmixSpace immixSpace;
- private final ChunkList chunkMap;
- private final Defrag defrag;
-
-
- /****************************************************************************
- *
- * Initialization
- */
-
- /**
- * Constructor
- *
- * @param space The mark-sweep space to which this allocator
- * instances is bound.
- */
- public CollectorLocal(ImmixSpace space) {
- immixSpace = space;
- chunkMap = immixSpace.getChunkMap();
- defrag = immixSpace.getDefrag();
- }
-
- /****************************************************************************
- *
- * Collection
- */
-
- /**
- * Prepare for a collection. If paranoid, perform a sanity check.
- */
- public void prepare(boolean majorGC) {
- int ordinal = VM.collection.activeGCThreadOrdinal();
- if (majorGC) {
- if (immixSpace.inImmixDefragCollection()) {
- short threshold = Defrag.defragSpillThreshold;
- resetLineMarksAndDefragStateTable(ordinal, threshold);
- }
- }
- }
-
- private void resetLineMarksAndDefragStateTable(int ordinal, final short threshold) {
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(immixSpace.inImmixDefragCollection());
- int stride = VM.collection.activeGCThreads();
- Address chunk = chunkMap.firstChunk(ordinal, stride);
- while (!chunk.isZero()) {
- Chunk.resetLineMarksAndDefragStateTable(chunk, threshold);
- chunk = chunkMap.nextChunk(chunk, ordinal, stride);
- }
- }
-
- /**
- * Finish up after a collection.
- *
- * We help sweeping all the blocks in parallel.
- */
- public void release(boolean majorGC) {
- sweepAllBlocks(majorGC);
- }
-
- private void sweepAllBlocks(boolean majorGC) {
- int stride = VM.collection.activeGCThreads();
- int ordinal = VM.collection.activeGCThreadOrdinal();
- int[] markSpillHisto = defrag.getAndZeroSpillMarkHistogram(ordinal);
- Address chunk = chunkMap.firstChunk(ordinal, stride);
- final byte markValue = immixSpace.lineMarkState;
- final boolean resetMarks = majorGC && markValue == MAX_LINE_MARK_STATE;
- while (!chunk.isZero()) {
- Chunk.sweep(chunk, Chunk.getHighWater(chunk), immixSpace, markSpillHisto, markValue, resetMarks);
- chunk = chunkMap.nextChunk(chunk, ordinal, stride);
- }
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/policy/immix/Defrag.java b/vmkit/mmtk/java/src/org/mmtk/policy/immix/Defrag.java
deleted file mode 100644
index a6feb96..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/policy/immix/Defrag.java
+++ /dev/null
@@ -1,189 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-
-package org.mmtk.policy.immix;
-
-import static org.mmtk.policy.immix.ImmixConstants.*;
-
-
-import org.mmtk.utility.Constants;
-import org.mmtk.utility.Log;
-import org.mmtk.utility.heap.FreeListPageResource;
-import org.mmtk.utility.options.DefragFreeHeadroom;
-import org.mmtk.utility.options.DefragFreeHeadroomFraction;
-import org.mmtk.utility.options.DefragHeadroom;
-import org.mmtk.utility.options.DefragHeadroomFraction;
-import org.mmtk.utility.options.DefragLineReuseRatio;
-import org.mmtk.utility.options.DefragSimpleSpillThreshold;
-import org.mmtk.utility.options.DefragStress;
-import org.mmtk.utility.options.Options;
-import org.mmtk.utility.statistics.EventCounter;
-import org.mmtk.utility.statistics.SizeCounter;
-import org.mmtk.vm.Collection;
-import org.mmtk.vm.VM;
-import org.vmmagic.pragma.Uninterruptible;
-
-@Uninterruptible
-public class Defrag implements Constants {
-
-
- private int defragHeadroomPages = 0;
- private int defragFreeHeadroomPages = 0;
- private boolean inDefragCollection = false;
- private int debugBytesDefraged = 0;
- private int availableCleanPagesForDefrag;
- private boolean defragSpaceExhausted = true;
- private int[][] spillMarkHistograms = new int[MAX_COLLECTORS][SPILL_HISTOGRAM_BUCKETS];
- private int[] spillAvailHistogram = new int[SPILL_HISTOGRAM_BUCKETS];
- public static SizeCounter defragCleanBytesUsed = new SizeCounter("cleanUsed");
- /* verbose stats (used only on stats runs since they induce overhead when gathred) */
- public static SizeCounter defragBytesNotFreed = new SizeCounter("bytesNotFreed");
- public static SizeCounter defragBytesFreed = new SizeCounter("bytesFreed");
- public static SizeCounter defragCleanBytesAvailable = new SizeCounter("cleanAvail");
-
- private final FreeListPageResource pr;
- private boolean debugCollectionTypeDetermined = false;
- static short defragSpillThreshold = 0;
- static short defragReusableMarkStateThreshold = 0;
- public static EventCounter defrags = new EventCounter("defrags");
-
- static {
- Options.defragLineReuseRatio = new DefragLineReuseRatio();
- Options.defragHeadroom = new DefragHeadroom();
- Options.defragHeadroomFraction = new DefragHeadroomFraction();
- Options.defragFreeHeadroom = new DefragFreeHeadroom();
- Options.defragFreeHeadroomFraction = new DefragFreeHeadroomFraction();
- Options.defragSimpleSpillThreshold = new DefragSimpleSpillThreshold();
- Options.defragStress = new DefragStress();
- defragReusableMarkStateThreshold = (short) (Options.defragLineReuseRatio.getValue() * MAX_BLOCK_MARK_STATE);
- }
-
- Defrag(FreeListPageResource pr) {
- this.pr = pr;
- }
-
- boolean inDefrag() { return inDefragCollection; }
-
- void prepare(ChunkList chunkMap, ImmixSpace space) {
- if (defragHeadroomPages > 0)
- pr.unconditionallyReleasePages(defragHeadroomPages);
-
- availableCleanPagesForDefrag = VM.activePlan.global().getTotalPages() - VM.activePlan.global().getPagesReserved();
- if (availableCleanPagesForDefrag < 0) availableCleanPagesForDefrag = 0;
- defragSpaceExhausted = false;
- availableCleanPagesForDefrag += defragFreeHeadroomPages;
- if (inDefragCollection) {
- if (Options.verbose.getValue() > 0) {
- Log.write("[Defrag]");
- }
- chunkMap.consolidateMap();
- establishDefragSpillThreshold(chunkMap, space);
- defrags.inc();
- defragCleanBytesAvailable.inc(availableCleanPagesForDefrag<<LOG_BYTES_IN_PAGE);
- }
- availableCleanPagesForDefrag += VM.activePlan.global().getCollectionReserve();
- }
-
- void globalRelease() {
- if (Options.defragHeadroom.getPages() > 0)
- defragHeadroomPages = Options.defragHeadroom.getPages();
- else if (Options.defragHeadroomFraction.getValue() > 0)
- defragHeadroomPages = (int) (pr.reservedPages() * Options.defragHeadroomFraction.getValue());
- else
- defragHeadroomPages = 0;
- if (Options.defragFreeHeadroom.getPages() > 0)
- defragFreeHeadroomPages = Options.defragFreeHeadroom.getPages();
- else if (Options.defragFreeHeadroomFraction.getValue() > 0)
- defragFreeHeadroomPages = (int) (pr.reservedPages() * Options.defragFreeHeadroomFraction.getValue());
- else
- defragFreeHeadroomPages = 0;
-
- if (defragHeadroomPages > 0)
- pr.unconditionallyReservePages(defragHeadroomPages);
-
- if (inDefragCollection && Options.verbose.getValue() > 2) {
- Log.write("(Defrag summary: cu: "); defragCleanBytesUsed.printCurrentVolume();
- Log.write(" nf: "); defragBytesNotFreed.printCurrentVolume();
- Log.write(" fr: "); defragBytesFreed.printCurrentVolume();
- Log.write(" av: "); defragCleanBytesAvailable.printCurrentVolume();
- Log.write(")");
- }
-
- inDefragCollection = false;
- debugCollectionTypeDetermined = false;
- }
-
- void decideWhetherToDefrag(boolean emergencyCollection, boolean collectWholeHeap, int collectionAttempt, int collectionTrigger, boolean exhaustedReusableSpace) {
- boolean userTriggered = collectionTrigger == Collection.EXTERNAL_GC_TRIGGER && Options.fullHeapSystemGC.getValue();
- inDefragCollection = (collectionAttempt > 1) ||
- emergencyCollection ||
- collectWholeHeap && (Options.defragStress.getValue() || userTriggered);
- if (inDefragCollection) {
- debugBytesDefraged = 0;
- }
- debugCollectionTypeDetermined = true;
- }
-
- boolean determined(boolean inDefrag) { return debugCollectionTypeDetermined && !(inDefrag ^ inDefragCollection); }
-
- void getBlock() {
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(!inDefragCollection || !defragSpaceExhausted);
- if (availableCleanPagesForDefrag <= 0)
- defragSpaceExhausted = true;
- availableCleanPagesForDefrag -= PAGES_IN_BLOCK;
- debugBytesDefraged += BYTES_IN_BLOCK;
- Defrag.defragCleanBytesUsed.inc(BYTES_IN_BLOCK);
- }
-
- private void establishDefragSpillThreshold(ChunkList chunkMap, ImmixSpace space) {
- int cleanLines = space.getAvailableLines(spillAvailHistogram);
- int availableLines = cleanLines + availableCleanPagesForDefrag<<(LOG_BYTES_IN_PAGE - LOG_BYTES_IN_LINE);
-
- int requiredLines = 0;
- short threshold = (short) MAX_CONSV_SPILL_COUNT;
- int limit = (int) (availableLines / Options.defragLineReuseRatio.getValue());
- if (VM.VERIFY_ASSERTIONS && Options.verbose.getValue() > 2) {
- Log.write("[threshold: "); Log.write("cl: "); Log.write(cleanLines);
- Log.write(" al: "); Log.write(availableLines);
- Log.write(" lm: "); Log.write(limit);
- }
- int collectors = VM.activePlan.collectorCount();
- for (short index = MAX_CONSV_SPILL_COUNT; index >= TMP_MIN_SPILL_THRESHOLD && limit > requiredLines; index--) {
- threshold = (short) index;
- int thisBucketMark = 0;
- int thisBucketAvail = 0;
- for (int c = 0; c < collectors; c++) thisBucketMark += spillMarkHistograms[c][threshold];
-
- thisBucketAvail = spillAvailHistogram[threshold];
- limit -= thisBucketAvail;
- requiredLines += thisBucketMark;
- if (VM.VERIFY_ASSERTIONS && Options.verbose.getValue() > 2) {
- Log.write(" ("); Log.write(index); Log.write(" "); Log.write(limit); Log.write(","); Log.write(requiredLines); Log.write(")");
- }
- }
- if (VM.VERIFY_ASSERTIONS && Options.verbose.getValue() > 2) {
- Log.write(" threshold: "); Log.write(threshold); Log.write("]");
- }
- defragSpillThreshold = threshold;
- }
-
-
- boolean spaceExhausted() { return defragSpaceExhausted; }
-
- int[] getAndZeroSpillMarkHistogram(int ordinal) {
- int[] rtn = spillMarkHistograms[ordinal];
- for (int i = 0; i < SPILL_HISTOGRAM_BUCKETS; i++)
- rtn[i] = 0;
- return rtn;
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/policy/immix/ImmixConstants.java b/vmkit/mmtk/java/src/org/mmtk/policy/immix/ImmixConstants.java
deleted file mode 100644
index 13bc077..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/policy/immix/ImmixConstants.java
+++ /dev/null
@@ -1,78 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.policy.immix;
-
-import static org.mmtk.policy.Space.BYTES_IN_CHUNK;
-import static org.mmtk.policy.Space.LOG_BYTES_IN_CHUNK;
-import static org.mmtk.utility.Constants.LOG_BYTES_IN_PAGE;
-
-import org.mmtk.plan.Plan;
-import org.mmtk.vm.VM;
-import org.vmmagic.unboxed.Word;
-
-public class ImmixConstants {
- public static final boolean BUILD_FOR_STICKYIMMIX = Plan.NEEDS_LOG_BIT_IN_HEADER;
-
- /* start temporary experimental constants --- should not be allowed to lurk longer than necessary */
- public static final int TMP_MIN_SPILL_THRESHOLD = 2;
- public static final boolean TMP_PREFER_COPY_ON_NURSERY_GC = true;
- /* end temporary experimental constants */
-
- static final byte MAX_LINE_MARK_STATE = 127;
- static final byte RESET_LINE_MARK_STATE = 1;
-
- public static final boolean MARK_LINE_AT_SCAN_TIME = true; // else do it at mark time
-
- public static final boolean SANITY_CHECK_LINE_MARKS = false && VM.VERIFY_ASSERTIONS;
-
- public static final float DEFAULT_LINE_REUSE_RATIO = (float) 0.99;
- public static final float DEFAULT_DEFRAG_LINE_REUSE_RATIO = (float) 0.99;
- public static final float DEFAULT_SIMPLE_SPILL_THRESHOLD = (float) 0.25;
- public static final int DEFAULT_DEFRAG_HEADROOM = 0; // number of pages.
- public static final float DEFAULT_DEFRAG_HEADROOM_FRACTION = (float) 0.020;
- public static final int DEFAULT_DEFRAG_FREE_HEADROOM = 0; // number of pages. This should only deviate from zero for analytical purposes. Otherwise the defragmenter is cheating!
- public static final float DEFAULT_DEFRAG_FREE_HEADROOM_FRACTION = (float) 0.0;
- /* sizes etc */
- static final int LOG_BYTES_IN_BLOCK = (LOG_BYTES_IN_PAGE > 15 ? LOG_BYTES_IN_PAGE : 15);
- public static final int BYTES_IN_BLOCK = 1<<LOG_BYTES_IN_BLOCK;
- static final int LOG_PAGES_IN_BLOCK = LOG_BYTES_IN_BLOCK - LOG_BYTES_IN_PAGE;
- static final int PAGES_IN_BLOCK = 1<<LOG_PAGES_IN_BLOCK;
- static final int LOG_BLOCKS_IN_CHUNK = LOG_BYTES_IN_CHUNK-LOG_BYTES_IN_BLOCK;
- static final int BLOCKS_IN_CHUNK = 1<<LOG_BLOCKS_IN_CHUNK;
-
- public static final int LOG_BYTES_IN_LINE = 8;
- static final int LOG_LINES_IN_BLOCK = LOG_BYTES_IN_BLOCK - LOG_BYTES_IN_LINE;
- public static final short LINES_IN_BLOCK = (short) (1<<LOG_LINES_IN_BLOCK);
- static final int LOG_LINES_IN_CHUNK = LOG_BYTES_IN_CHUNK - LOG_BYTES_IN_LINE;
- static final int LINES_IN_CHUNK = 1<<LOG_LINES_IN_CHUNK;
-
- public static final int BYTES_IN_LINE = 1<<LOG_BYTES_IN_LINE;
-
- public static final int MAX_IMMIX_OBJECT_BYTES = BYTES_IN_BLOCK>>1;
-
- private static final int LOG_BLOCKS_IN_RECYCLE_ALLOC_CHUNK = 4; // 3 + 15 -> 19 (512KB)
- private static final int LOG_BYTES_IN_RECYCLE_ALLOC_CHUNK = LOG_BLOCKS_IN_RECYCLE_ALLOC_CHUNK + LOG_BYTES_IN_BLOCK;
- static final int BYTES_IN_RECYCLE_ALLOC_CHUNK = 1<<LOG_BYTES_IN_RECYCLE_ALLOC_CHUNK;
-
- public static final short MAX_BLOCK_MARK_STATE = LINES_IN_BLOCK;
- static final short MAX_CONSV_SPILL_COUNT = (short) (LINES_IN_BLOCK/2);
- public static final short SPILL_HISTOGRAM_BUCKETS = (short) (MAX_CONSV_SPILL_COUNT + 1);
- public static final short MARK_HISTOGRAM_BUCKETS = (short) (LINES_IN_BLOCK + 1);
- static final short MAX_COLLECTORS = 16; // nothing special here---we can increase this at the cost of a few hundred bites at build time.
-
- public static final Word RECYCLE_ALLOC_CHUNK_MASK = Word.fromIntZeroExtend(BYTES_IN_RECYCLE_ALLOC_CHUNK - 1);
- protected static final Word CHUNK_MASK = Word.fromIntZeroExtend(BYTES_IN_CHUNK - 1);
- public static final Word BLOCK_MASK = Word.fromIntZeroExtend(BYTES_IN_BLOCK - 1);
- protected static final Word LINE_MASK = Word.fromIntZeroExtend(BYTES_IN_LINE - 1);
-
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/policy/immix/ImmixSpace.java b/vmkit/mmtk/java/src/org/mmtk/policy/immix/ImmixSpace.java
deleted file mode 100644
index bc63064..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/policy/immix/ImmixSpace.java
+++ /dev/null
@@ -1,760 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.policy.immix;
-
-import static org.mmtk.policy.immix.ImmixConstants.*;
-
-import org.mmtk.plan.Plan;
-import org.mmtk.plan.TransitiveClosure;
-import org.mmtk.policy.Space;
-import org.mmtk.utility.heap.*;
-import org.mmtk.utility.options.LineReuseRatio;
-import org.mmtk.utility.options.Options;
-import org.mmtk.utility.Constants;
-import org.mmtk.utility.ForwardingWord;
-import org.mmtk.utility.HeaderByte;
-import org.mmtk.utility.Log;
-
-import org.mmtk.vm.Lock;
-import org.mmtk.vm.VM;
-
-import org.vmmagic.pragma.*;
-import org.vmmagic.unboxed.*;
-
-/**
- * Each instance of this class corresponds to one immix *space*.
- * Each of the instance methods of this class may be called by any
- * thread (i.e. synchronization must be explicit in any instance or
- * class method). This contrasts with the SquishLocal, where
- * instances correspond to *plan* instances and therefore to kernel
- * threads. Thus unlike this class, synchronization is not necessary
- * in the instance methods of SquishLocal.
- *
- */
-@Uninterruptible
-public final class ImmixSpace extends Space implements Constants {
-
- /****************************************************************************
- *
- * Class variables
- */
- private static short reusableMarkStateThreshold = 0;
-
- /****************************************************************************
- *
- * Instance variables
- */
- private byte markState = ObjectHeader.MARK_BASE_VALUE;
- byte lineMarkState = RESET_LINE_MARK_STATE;
- private byte lineUnavailState = RESET_LINE_MARK_STATE;
- private boolean inCollection;
- private int linesConsumed = 0;
-
- private Lock mutatorLock = VM.newLock(getName()+"mutator");
- private Lock gcLock = VM.newLock(getName()+"gc");
-
- private Address allocBlockCursor = Address.zero();
- private Address allocBlockSentinel = Address.zero();
- private boolean exhaustedReusableSpace = true;
-
- private final ChunkList chunkMap = new ChunkList();
- private final Defrag defrag;
-
- /****************************************************************************
- *
- * Initialization
- */
-
- static {
- Options.lineReuseRatio = new LineReuseRatio();
- reusableMarkStateThreshold = (short) (Options.lineReuseRatio.getValue() * MAX_BLOCK_MARK_STATE);
- }
-
- /**
- * The caller specifies the region of virtual memory to be used for
- * this space. If this region conflicts with an existing space,
- * then the constructor will fail.
- *
- * @param name The name of this space (used when printing error messages etc)
- * @param pageBudget The number of pages this space may consume before consulting the plan
- * @param vmRequest The virtual memory request
- */
- public ImmixSpace(String name, int pageBudget, VMRequest vmRequest) {
- super(name, false, false, vmRequest);
- if (vmRequest.isDiscontiguous())
- pr = new FreeListPageResource(pageBudget, this, Chunk.getRequiredMetaDataPages());
- else
- pr = new FreeListPageResource(pageBudget, this, start, extent, Chunk.getRequiredMetaDataPages());
- defrag = new Defrag((FreeListPageResource) pr);
- }
-
- /****************************************************************************
- *
- * Global prepare and release
- */
-
- /**
- * Prepare for a new collection increment.
- */
- public void prepare(boolean majorGC) {
- if (majorGC) {
- markState = ObjectHeader.deltaMarkState(markState, true);
- lineMarkState++;
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(lineMarkState <= MAX_LINE_MARK_STATE);
- }
- chunkMap.reset();
- defrag.prepare(chunkMap, this);
- inCollection = true;
-
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(VM.activePlan.collectorCount() <= MAX_COLLECTORS);
- }
-
- /**
- * A new collection increment has completed. Release global resources.
- * @param majorGC TODO
- */
- public boolean release(boolean majorGC) {
- boolean didDefrag = defrag.inDefrag();
- if (majorGC) {
- if (lineMarkState == MAX_LINE_MARK_STATE)
- lineMarkState = RESET_LINE_MARK_STATE;
- lineUnavailState = lineMarkState;
- }
- chunkMap.reset();
- defrag.globalRelease();
- inCollection = false;
-
- /* set up reusable space */
- if (allocBlockCursor.isZero()) allocBlockCursor = chunkMap.getHeadChunk();
- allocBlockSentinel = allocBlockCursor;
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(isRecycleAllocChunkAligned(allocBlockSentinel));
- exhaustedReusableSpace = allocBlockCursor.isZero();
- if (VM.VERIFY_ASSERTIONS && Options.verbose.getValue() >= 9) {
- Log.write("gr[allocBlockCursor: "); Log.write(allocBlockCursor); Log.write(" allocBlockSentinel: "); Log.write(allocBlockSentinel); Log.writeln("]");
- }
-
- /* really just want this to happen once after options are booted, but no harm in re-doing it */
- reusableMarkStateThreshold = (short) (Options.lineReuseRatio.getValue() * MAX_BLOCK_MARK_STATE);
- Defrag.defragReusableMarkStateThreshold = (short) (Options.defragLineReuseRatio.getValue() * MAX_BLOCK_MARK_STATE);
-
- linesConsumed = 0;
- return didDefrag;
- }
-
- /**
- * Determine the collection kind.
- *
- * @param emergencyCollection Is this collection an emergency (last did not yield enough)?
- * @param collectWholeHeap Is this a whole heap collection?
- * @param collectionAttempt Which attempt is this to collect?
- * @param collectionTrigger What is triggering the collection?
- */
- public void decideWhetherToDefrag(boolean emergencyCollection, boolean collectWholeHeap, int collectionAttempt, int collectionTrigger) {
- defrag.decideWhetherToDefrag(emergencyCollection, collectWholeHeap, collectionAttempt, collectionTrigger, exhaustedReusableSpace);
- }
-
- /****************************************************************************
- *
- * Collection state access methods
- */
-
- /**
- * Return true if this space is currently being collected.
- *
- * @return True if this space is currently being collected.
- */
- @Inline
- public boolean inImmixCollection() {
- return inCollection;
- }
-
- /**
- * Return true if this space is currently being defraged.
- *
- * @return True if this space is currently being defraged.
- */
- @Inline
- public boolean inImmixDefragCollection() {
- return inCollection && defrag.inDefrag();
- }
-
- /**
- * Return the number of pages allocated since the last collection
- *
- * @return The number of pages allocated since the last collection
- */
- public int getPagesAllocated() {
- return linesConsumed>>(LOG_BYTES_IN_PAGE-LOG_BYTES_IN_LINE);
- }
-
- /**
- * Return the reusable mark state threshold, which determines how
- * eagerly lines should be recycled (by default these values are
- * set so that all lines are recycled).
- *
- * @param forDefrag The query is the context of a defragmenting collection
- * @return The reusable mark state threshold
- */
- @Inline
- public static short getReusuableMarkStateThreshold(boolean forDefrag) {
- return forDefrag ? Defrag.defragReusableMarkStateThreshold : reusableMarkStateThreshold;
- }
-
- /****************************************************************************
- *
- * Allocation
- */
-
- /**
- * Return a pointer to a set of new usable blocks, or null if none are available.
- * Use different block selection heuristics depending on whether the allocation
- * request is "hot" or "cold".
- *
- * @param hot True if the requesting context is for hot allocations (used for
- * allocations from high allocation volume sites).
- * @return The pointer into the alloc table containing usable blocks.
- */
- public Address getSpace(boolean hot, boolean copy, int lineUseCount) {
- Address rtn;
- if (copy)
- defrag.getBlock();
-
- linesConsumed += lineUseCount;
-
- rtn = acquire(PAGES_IN_BLOCK);
-
- if (VM.VERIFY_ASSERTIONS) {
- VM.assertions._assert(Block.isAligned(rtn));
- VM.assertions._assert(!(copy && Block.isDefragSource(rtn)));
- }
-
- if (!rtn.isZero()) {
- Block.setBlockAsInUse(rtn);
- Chunk.updateHighWater(rtn);
- if (VM.VERIFY_ASSERTIONS && Options.verbose.getValue() >= 9) {
- Log.write("gs["); Log.write(rtn); Log.write(" -> "); Log.write(rtn.plus(BYTES_IN_BLOCK-1)); Log.write(" copy: "); Log.write(copy); Log.writeln("]");
- }
- }
-
- return rtn;
- }
-
- /**
- * This hook is called by page resources each time a space grows. The space may
- * tap into the hook to monitor heap growth. The call is made from within the
- * page resources' critical region, immediately before yielding the lock.
- *
- * @param start The start of the newly allocated space
- * @param bytes The size of the newly allocated space
- * @param newChunk True if the new space encroached upon or started a new chunk or chunks.
- */
- @Override
- public void growSpace(Address start, Extent bytes, boolean newChunk) {
- super.growSpace(start, bytes, newChunk);
- if (newChunk) {
- Address chunk = chunkAlign(start.plus(bytes), true);
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(chunkAlign(start.plus(bytes), true).EQ(chunk));
- Chunk.clearMetaData(chunk);
- chunkMap.addNewChunkToMap(chunk);
- }
- }
-
- public Address acquireReusableBlocks() {
- if (VM.VERIFY_ASSERTIONS) {
- VM.assertions._assert(isRecycleAllocChunkAligned(allocBlockCursor));
- VM.assertions._assert(isRecycleAllocChunkAligned(allocBlockSentinel));
- }
- Address rtn;
-
- lock();
- if (exhaustedReusableSpace)
- rtn = Address.zero();
- else {
- rtn = allocBlockCursor;
- Address lastAllocChunk = chunkAlign(allocBlockCursor, true);
- allocBlockCursor = allocBlockCursor.plus(BYTES_IN_RECYCLE_ALLOC_CHUNK);
- if (allocBlockCursor.GT(Chunk.getHighWater(lastAllocChunk)))
- allocBlockCursor = chunkMap.nextChunk(lastAllocChunk);
- if (VM.VERIFY_ASSERTIONS && Options.verbose.getValue() >= 9) {
- Log.write("arb[ rtn: "); Log.write(rtn); Log.write(" allocBlockCursor: "); Log.write(allocBlockCursor); Log.write(" allocBlockSentinel: "); Log.write(allocBlockSentinel); Log.writeln("]");
- }
-
- if (allocBlockCursor.isZero() || allocBlockCursor.EQ(allocBlockSentinel)) {
- exhaustedReusableSpace = true;
- if (VM.VERIFY_ASSERTIONS && Options.verbose.getValue() >= 9) {
- Log.writeln("[Reusable space exhausted]");
- }
- }
- }
- unlock();
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(isRecycleAllocChunkAligned(rtn));
- return rtn;
- }
-
- /**
- * Release a block. A block is free, so call the underlying page allocator
- * to release the associated storage.
- *
- * @param block The address of the block to be released
- */
- @Inline
- public void release(Address block) {
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(Block.isAligned(block));
- Block.setBlockAsUnallocated(block);
- ((FreeListPageResource) pr).releasePages(block);
- }
-
- /**
- * Release one or more contiguous chunks associated with a discontiguous
- * space. This hook is called by the page level allocators whenever a
- * complete discontiguous chunk is released.
- *
- * @param chunk THe address of the start of the contiguous chunk or chunks
- * @return The number of chunks freed
- */
- @Override
- public int releaseDiscontiguousChunks(Address chunk) {
- chunkMap.removeChunkFromMap(chunk);
- return super.releaseDiscontiguousChunks(chunk);
- }
-
- /****************************************************************************
- *
- * Header manipulation
- */
-
- /**
- * Perform any required post allocation initialization
- *
- * @param object the object ref to the storage to be initialized
- */
- @Inline
- public void postAlloc(ObjectReference object, int bytes) {
- if (bytes > BYTES_IN_LINE)
- ObjectHeader.markAsStraddling(object);
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(ObjectHeader.isNewObject(object));
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(!ForwardingWord.isForwardedOrBeingForwarded(object));
- }
-
- /**
- * Perform any required post copy (i.e. in-GC allocation) initialization.
- * This is relevant (for example) when Squish is used as the mature space in
- * a copying GC.
- *
- * @param object the object ref to the storage to be initialized
- * @param majorGC Is this copy happening during a major gc?
- */
- @Inline
- public void postCopy(ObjectReference object, int bytes, boolean majorGC) {
- ObjectHeader.writeMarkState(object, markState, bytes > BYTES_IN_LINE);
- if (!MARK_LINE_AT_SCAN_TIME && majorGC) markLines(object);
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(!ForwardingWord.isForwardedOrBeingForwarded(object));
- if (VM.VERIFY_ASSERTIONS && HeaderByte.NEEDS_UNLOGGED_BIT) VM.assertions._assert(HeaderByte.isUnlogged(object));
- }
-
- /****************************************************************************
- *
- * Object tracing
- */
-
- /**
- * Trace a reference to an object. If the object header is not already
- * marked, mark the object and enqueue it for subsequent processing.
- *
- * @param trace The trace performing the transitive closure
- * @param object The object to be traced.
- * @param allocator The allocator to which any copying should be directed
- * @return The object, which may have been moved.
- */
- @Inline
- public ObjectReference traceObject(TransitiveClosure trace, ObjectReference object, int allocator) {
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(defrag.determined(true));
-
- ObjectReference rtn = object;
- if (isDefragSource(object))
- rtn = traceObjectWithOpportunisticCopy(trace, object, allocator, false);
- else
- traceObjectWithoutMoving(trace, object);
-
- if (VM.VERIFY_ASSERTIONS) {
- VM.assertions._assert(!rtn.isNull());
- VM.assertions._assert(defrag.spaceExhausted() || !isDefragSource(rtn) || (ObjectHeader.isPinnedObject(rtn)));
- }
- return rtn;
- }
-
- /**
- * Trace a reference to an object in the context of a non-moving collection. This
- * call is optimized for the simpler non-moving case.
- *
- * @param trace The trace performing the transitive closure
- * @param object The object to be traced.
- * @return The object (there is no object forwarding in this
- * trace method, so we always return the same object: this could be a
- * void method but for compliance to a more general interface).
- */
- @Inline
- public ObjectReference fastTraceObject(TransitiveClosure trace, ObjectReference object) {
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(defrag.determined(false));
- traceObjectWithoutMoving(trace, object);
- return object;
- }
-
- /**
- * Trace a reference to an object during a nursery collection for
- * a sticky mark bits implementation of immix. If the object header
- * is not already marked, mark the object and enqueue it for subsequent
- * processing.
- *
- * @param trace The trace performing the transitive closure
- * @param object The object to be traced.
- * @param allocator The allocator to which any copying should be directed
- * @return Either the object or a forwarded object, depending on
- * the policy in place.
- */
- @Inline
- public ObjectReference nurseryTraceObject(TransitiveClosure trace, ObjectReference object, int allocator) {
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(!defrag.inDefrag());
- if (TMP_PREFER_COPY_ON_NURSERY_GC)
- return traceObjectWithOpportunisticCopy(trace, object, allocator, true);
- else
- return fastTraceObject(trace, object);
- }
-
- /**
- * Trace a reference to an object. This interface is not supported by immix, since
- * we require the allocator to be identified except for the special case of the fast
- * trace.
- *
- * @param trace The trace performing the transitive closure
- * @param object The object to be traced.
- * @return null and fail.
- */
- public ObjectReference traceObject(TransitiveClosure trace, ObjectReference object) {
- VM.assertions.fail("unsupported interface");
- return null;
- }
-
- /**
- * Trace a reference to an object in the context of a non-moving collection. This
- * call is optimized for the simpler non-moving case.
- *
- * @param trace The trace performing the transitive closure
- * @param object The object to be traced.
- */
- @Inline
- private void traceObjectWithoutMoving(TransitiveClosure trace, ObjectReference object) {
- byte markValue = markState;
- byte oldMarkState = ObjectHeader.testAndMark(object, markValue);
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(!defrag.inDefrag() || defrag.spaceExhausted() || !isDefragSource(object));
- if (oldMarkState != markValue) {
- if (!MARK_LINE_AT_SCAN_TIME)
- markLines(object);
- trace.processNode(object);
- }
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(!ForwardingWord.isForwardedOrBeingForwarded(object));
- if (VM.VERIFY_ASSERTIONS && HeaderByte.NEEDS_UNLOGGED_BIT) VM.assertions._assert(HeaderByte.isUnlogged(object));
- }
-
- /**
- * Trace a reference to an object, forwarding the object if appropriate
- * If the object is not already marked, mark the object and enqueue it
- * for subsequent processing.
- *
- * @param trace The trace performing the transitive closure
- * @param object The object to be traced.
- * @param allocator The allocator to which any copying should be directed
- * @return Either the object or a forwarded object, if it was forwarded.
- */
- @Inline
- private ObjectReference traceObjectWithOpportunisticCopy(TransitiveClosure trace, ObjectReference object, int allocator, boolean nurseryCollection) {
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(nurseryCollection || (defrag.determined(true) && isDefragSource(object)));
-
- /* now race to be the (potential) forwarder */
- Word priorStatusWord = ForwardingWord.attemptToForward(object);
- if (ForwardingWord.stateIsForwardedOrBeingForwarded(priorStatusWord)) {
- /* We lost the race; the object is either forwarded or being forwarded by another thread. */
- /* Note that the concurrent attempt to forward the object may fail, so the object may remain in-place */
- ObjectReference rtn = ForwardingWord.spinAndGetForwardedObject(object, priorStatusWord);
- if (VM.VERIFY_ASSERTIONS && rtn == object) VM.assertions._assert((nurseryCollection && ObjectHeader.testMarkState(object, markState)) || defrag.spaceExhausted() || ObjectHeader.isPinnedObject(object));
- if (VM.VERIFY_ASSERTIONS && rtn != object) VM.assertions._assert(nurseryCollection || !isDefragSource(rtn));
- if (VM.VERIFY_ASSERTIONS && HeaderByte.NEEDS_UNLOGGED_BIT) VM.assertions._assert(HeaderByte.isUnlogged(rtn));
- return rtn;
- } else {
- byte priorState = (byte) (priorStatusWord.toInt() & 0xFF);
- /* the object is unforwarded, either because this is the first thread to reach it, or because the object can't be forwarded */
- if (ObjectHeader.testMarkState(priorState, markState)) {
- /* the object has not been forwarded, but has the correct mark state; unlock and return unmoved object */
- /* Note that in a sticky mark bits collector, the mark state does not change at each GC, so correct mark state does not imply another thread got there first */
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(nurseryCollection || defrag.spaceExhausted() || ObjectHeader.isPinnedObject(object));
- ObjectHeader.returnToPriorStateAndEnsureUnlogged(object, priorState); // return to uncontested state
- if (VM.VERIFY_ASSERTIONS && Plan.NEEDS_LOG_BIT_IN_HEADER) VM.assertions._assert(HeaderByte.isUnlogged(object));
- return object;
- } else {
- /* we are the first to reach the object; either mark in place or forward it */
- ObjectReference newObject;
- if (ObjectHeader.isPinnedObject(object) || defrag.spaceExhausted()) {
- /* mark in place */
- ObjectHeader.setMarkStateUnlogAndUnlock(object, priorState, markState);
- newObject = object;
- if (VM.VERIFY_ASSERTIONS && Plan.NEEDS_LOG_BIT_IN_HEADER) VM.assertions._assert(HeaderByte.isUnlogged(newObject));
- } else {
- /* forward */
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(!ObjectHeader.isPinnedObject(object));
- newObject = ForwardingWord.forwardObject(object, allocator);
- if (VM.VERIFY_ASSERTIONS && Plan.NEEDS_LOG_BIT_IN_HEADER) VM.assertions._assert(HeaderByte.isUnlogged(newObject));
- }
- if (VM.VERIFY_ASSERTIONS && Options.verbose.getValue() >= 9) {
- Log.write("C["); Log.write(object); Log.write("/");
- Log.write(getName()); Log.write("] -> ");
- Log.write(newObject); Log.write("/");
- Log.write(Space.getSpaceForObject(newObject).getName());
- Log.writeln("]");
- }
- if (!MARK_LINE_AT_SCAN_TIME)
- markLines(newObject);
- trace.processNode(newObject);
- if (VM.VERIFY_ASSERTIONS) {
- if (!((getSpaceForObject(newObject) != this) ||
- (newObject == object) ||
- (nurseryCollection && willNotMoveThisNurseryGC(newObject)) ||
- (defrag.inDefrag() && willNotMoveThisGC(newObject))
- )) {
- Log.write(" object: "); Log.writeln(object);
- Log.write("newObject: "); Log.writeln(newObject);
- Log.write(" space: "); Log.writeln(getName());
- Log.write(" nursery?: "); Log.writeln(nurseryCollection);
- Log.write(" mature?: "); Log.writeln(ObjectHeader.isMatureObject(object));
- Log.write(" wnmngc?: "); Log.writeln(willNotMoveThisNurseryGC(newObject));
- Log.write(" pinned?: "); Log.writeln(ObjectHeader.isPinnedObject(object));
- Space otherSpace = getSpaceForObject(newObject);
- Log.write(" space(o): "); Log.writeln(otherSpace == null ? "<NULL>" : otherSpace.getName());
- VM.assertions._assert(false);
- }
- }
- return newObject;
- }
- }
- }
-
- /**
- * Mark the line/s associated with a given object. This is distinct from the
- * above tracing code because line marks are stored separately from the
- * object headers (thus both must be set), and also because we found empirically
- * that it was more efficient to perform the line mark of the object during
- * the scan phase (which occurs after the trace phase), presumably because
- * the latency of the associated memory operations was better hidden in the
- * context of that code
- *
- * @param object The object which is live and for which the associated lines
- * must be marked.
- */
- public void markLines(ObjectReference object) {
- Address address = VM.objectModel.objectStartRef(object);
- Line.mark(address, lineMarkState);
- if (ObjectHeader.isStraddlingObject(object))
- Line.markMultiLine(address, object, lineMarkState);
- }
-
- public int getNextUnavailableLine(Address baseLineAvailAddress, int line) {
- return Line.getNextUnavailable(baseLineAvailAddress, line, lineUnavailState);
- }
-
- public int getNextAvailableLine(Address baseLineAvailAddress, int line) {
- return Line.getNextAvailable(baseLineAvailAddress, line, lineUnavailState);
- }
-
- /****************************************************************************
- *
- * Establish available lines
- */
-
- /**
- * Establish the number of recyclable lines lines available for allocation
- * during defragmentation, populating the spillAvailHistogram, which buckets
- * available lines according to the number of holes on the block on which
- * the available lines reside.
- *
- * @param spillAvailHistogram A histogram of availability to be populated
- * @return The number of available recyclable lines
- */
- int getAvailableLines(int[] spillAvailHistogram) {
- int availableLines;
- if (allocBlockCursor.isZero() || exhaustedReusableSpace) {
- availableLines = 0;
- } else {
- if (allocBlockCursor.EQ(allocBlockSentinel)) {
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(!exhaustedReusableSpace);
- allocBlockCursor = chunkMap.getHeadChunk();
- allocBlockSentinel = allocBlockCursor;
- }
- availableLines = getUsableLinesInRegion(allocBlockCursor, allocBlockSentinel, spillAvailHistogram);
- }
- return availableLines;
- }
-
- /**
- * Return the number of lines usable for allocation during defragmentation in the
- * address range specified by start and end. Populate a histogram to indicate where
- * the usable lines reside as a function of block hole count.
- *
- * @param start The start of the region to be checked for availability
- * @param end The end of the region to be checked for availability
- * @param spillAvailHistogram The histogram which will be populated
- * @return The number of usable lines
- */
- private int getUsableLinesInRegion(Address start, Address end, int[] spillAvailHistogram) {
- int usableLines = 0;
- Address blockCursor = Chunk.isAligned(start) ? start.plus(Chunk.FIRST_USABLE_BLOCK_INDEX<<LOG_BYTES_IN_BLOCK) : start;
- Address blockStateCursor = Block.getBlockMarkStateAddress(blockCursor);
- Address chunkCursor = Chunk.align(blockCursor);
- if (Chunk.getByteOffset(end) < Chunk.FIRST_USABLE_BLOCK_INDEX<<LOG_BYTES_IN_BLOCK)
- end = Chunk.align(end).plus(Chunk.FIRST_USABLE_BLOCK_INDEX<<LOG_BYTES_IN_BLOCK);
-
- for (int i = 0; i <= MAX_CONSV_SPILL_COUNT; i++) spillAvailHistogram[i] = 0;
-
- Address highwater = Chunk.getHighWater(chunkCursor);
- do {
- short markState = blockStateCursor.loadShort();
- if (markState != 0 && markState <= reusableMarkStateThreshold) {
- int usable = LINES_IN_BLOCK - markState;
- short bucket = (short) Block.getConservativeSpillCount(blockCursor);
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(bucket >= 0 && bucket <= MAX_CONSV_SPILL_COUNT);
- spillAvailHistogram[bucket] += usable;
- usableLines += usable;
- }
- blockCursor = blockCursor.plus(BYTES_IN_BLOCK);
- if (blockCursor.GT(highwater)) {
- chunkCursor = chunkMap.nextChunk(chunkCursor);
- if (chunkCursor.isZero()) break;
- blockCursor = chunkCursor.plus(Chunk.FIRST_USABLE_BLOCK_INDEX<<LOG_BYTES_IN_BLOCK);
- blockStateCursor = Block.getBlockMarkStateAddress(blockCursor);
- highwater = Chunk.getHighWater(chunkCursor);
- } else
- blockStateCursor = blockStateCursor.plus(Block.BYTES_IN_BLOCK_STATE_ENTRY);
- } while (blockCursor.NE(end));
-
- return usableLines;
- }
-
- /****************************************************************************
- *
- * Object state
- */
-
- /**
- * Generic test of the liveness of an object
- *
- * @param object The object in question
- * @return True if this object is known to be live (i.e. it is marked)
- */
- @Inline
- public boolean isLive(ObjectReference object) {
- if (defrag.inDefrag() && isDefragSource(object))
- return ForwardingWord.isForwardedOrBeingForwarded(object) || ObjectHeader.testMarkState(object, markState);
- else
- return ObjectHeader.testMarkState(object, markState);
- }
-
- /**
- * Test the liveness of an object during copying sticky mark bits collection
- *
- * @param object The object in question
- * @return True if this object is known to be live (i.e. it is marked)
- */
- @Inline
- public boolean copyNurseryIsLive(ObjectReference object) {
- return ForwardingWord.isForwardedOrBeingForwarded(object) || ObjectHeader.testMarkState(object, markState);
- }
-
- /**
- * Test the liveness of an object during defragmentation
- *
- * @param object The object in question
- * @return True if this object is known to be live (i.e. it is marked)
- */
- @Inline
- public boolean fastIsLive(ObjectReference object) {
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(!defrag.inDefrag());
- return ObjectHeader.testMarkState(object, markState);
- }
-
- @Inline
- public boolean willNotMoveThisGC(ObjectReference object) {
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(getSpaceForObject(object) == this && defrag.inDefrag());
- return ObjectHeader.isPinnedObject(object) || willNotMoveThisGC(VM.objectModel.refToAddress(object));
- }
-
- @Inline
- public boolean willNotMoveThisNurseryGC(ObjectReference object) {
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(getSpaceForObject(object) == this);
- return ObjectHeader.isMatureObject(object);
- }
-
- @Inline
- private boolean isDefragSource(ObjectReference object) {
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(getSpaceForObject(object) == this);
- return isDefragSource(VM.objectModel.refToAddress(object));
- }
-
- @Inline
- public boolean willNotMoveThisGC(Address address) {
- return !defrag.inDefrag() || defrag.spaceExhausted() || !isDefragSource(address);
- }
-
- @Inline
- public boolean isDefragSource(Address address) {
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(getSpaceForObject(address.toObjectReference()) == this);
- return Block.isDefragSource(address);
- }
-
-
- /****************************************************************************
- *
- * Locks
- */
-
- /**
- * Acquire the appropriate lock depending on whether the context is
- * GC or mutator.
- */
- private void lock() {
- if (inCollection)
- gcLock.acquire();
- else
- mutatorLock.acquire();
- }
-
- /**
- * Release the appropriate lock depending on whether the context is
- * GC or mutator.
- */
- private void unlock() {
- if (inCollection)
- gcLock.release();
- else
- mutatorLock.release();
- }
-
-
- /****************************************************************************
- *
- * Misc
- */
- public static boolean isRecycleAllocChunkAligned(Address ptr) {
- return ptr.toWord().and(RECYCLE_ALLOC_CHUNK_MASK).EQ(Word.zero());
- }
-
- ChunkList getChunkMap() { return chunkMap; }
- Defrag getDefrag() { return defrag; }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/policy/immix/Line.java b/vmkit/mmtk/java/src/org/mmtk/policy/immix/Line.java
deleted file mode 100644
index 984bc60..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/policy/immix/Line.java
+++ /dev/null
@@ -1,125 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.policy.immix;
-
-import static org.mmtk.policy.immix.ImmixConstants.*;
-
-import org.mmtk.utility.Constants;
-import org.mmtk.vm.VM;
-
-import org.vmmagic.pragma.Inline;
-import org.vmmagic.pragma.Uninterruptible;
-import org.vmmagic.unboxed.Address;
-import org.vmmagic.unboxed.ObjectReference;
-import org.vmmagic.unboxed.Offset;
-
-@Uninterruptible
-public class Line implements Constants {
-
- public static Address align(Address ptr) {
- return ptr.toWord().and(LINE_MASK.not()).toAddress();
- }
-
- public static boolean isAligned(Address address) {
- return address.EQ(align(address));
- }
-
- static int getChunkIndex(Address line) {
- return line.toWord().and(CHUNK_MASK).rshl(LOG_BYTES_IN_LINE).toInt();
- }
-
- /***************************************************************************
- * Line marking
- */
- static void mark(Address address, final byte markValue) {
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(!Block.isUnused(Block.align(address)));
- getMarkAddress(address).store(markValue);
- }
-
- static void markMultiLine(Address start, ObjectReference object, final byte markValue) {
- /* endLine is the address of the last (highest) line touched by this object */
- Address endLine = Line.align(VM.objectModel.getObjectEndAddress(object).minus(1));
- Address line = Line.align(start.plus(BYTES_IN_LINE));
- while (line.LT(endLine)) {
- if (VM.VERIFY_ASSERTIONS)
- VM.assertions._assert(Block.align(start).EQ(Block.align(line)));
- mark(line, markValue);
- line = line.plus(BYTES_IN_LINE);
- }
- }
-
- /***************************************************************************
- * Scanning through avail lines
- */
- public static Address getChunkMarkTable(Address chunk) {
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(Chunk.isAligned(chunk));
- return getMarkAddress(chunk);
- }
-
- public static Address getBlockMarkTable(Address block) {
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(Block.isAligned(block));
- return getMarkAddress(block);
- }
-
- @Inline
- public static int getNextUnavailable(Address baseLineAvailAddress, int line, final byte unavailableState) {
- while (line < LINES_IN_BLOCK &&
- baseLineAvailAddress.loadByte(Offset.fromIntZeroExtend(line<<Line.LOG_BYTES_IN_LINE_STATUS)) < unavailableState)
- line++;
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(line >= 0 && line <= LINES_IN_BLOCK);
- return line;
- }
-
- @Inline
- public static int getNextAvailable(Address baseLineAvailAddress, int line, final byte unavailableState) {
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(line >= 0 && line < LINES_IN_BLOCK);
- byte last = baseLineAvailAddress.loadByte(Offset.fromIntZeroExtend(line<<Line.LOG_BYTES_IN_LINE_STATUS));
- byte thisline;
- line++;
- while (line < LINES_IN_BLOCK) {
- thisline = baseLineAvailAddress.loadByte(Offset.fromIntZeroExtend(line<<Line.LOG_BYTES_IN_LINE_STATUS));
- if (thisline < unavailableState && last < unavailableState)
- break;
- last = thisline;
- line++;
- }
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(line >= 0 && line <= LINES_IN_BLOCK);
- return line;
- }
-
- private static Address getMetaAddress(Address address, final int tableOffset) {
- Address chunk = Chunk.align(address);
- int index = getChunkIndex(address);
- Address rtn = chunk.plus(tableOffset + (index<<LOG_BYTES_IN_LINE_STATUS));
- if (VM.VERIFY_ASSERTIONS) {
- Address line = chunk.plus(index<<LOG_BYTES_IN_LINE);
- VM.assertions._assert(isAligned(line));
- VM.assertions._assert(align(address).EQ(line));
- boolean valid = rtn.GE(chunk.plus(tableOffset)) && rtn.LT(chunk.plus(tableOffset + LINE_MARK_TABLE_BYTES));
- VM.assertions._assert(valid);
- }
- return rtn;
- }
-
- private static Address getMarkAddress(Address address) {
- return getMetaAddress(address, Chunk.LINE_MARK_TABLE_OFFSET);
- }
-
- /* per-line mark bytes */
- static final int LOG_BYTES_IN_LINE_STATUS = 0;
- static final int BYTES_IN_LINE_STATUS = 1<<LOG_BYTES_IN_LINE_STATUS;
-
- static final int LINE_MARK_TABLE_BYTES = LINES_IN_CHUNK<<LOG_BYTES_IN_LINE_STATUS;
- static final int LOG_LINE_MARK_BYTES_PER_BLOCK = LOG_LINES_IN_BLOCK+LOG_BYTES_IN_LINE_STATUS;
- static final int LINE_MARK_BYTES_PER_BLOCK = (1<<LOG_LINE_MARK_BYTES_PER_BLOCK);
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/policy/immix/MutatorLocal.java b/vmkit/mmtk/java/src/org/mmtk/policy/immix/MutatorLocal.java
deleted file mode 100644
index e0b5a9c..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/policy/immix/MutatorLocal.java
+++ /dev/null
@@ -1,55 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.policy.immix;
-
-import org.mmtk.utility.alloc.ImmixAllocator;
-import org.mmtk.utility.Constants;
-
-import org.vmmagic.pragma.*;
-
-/**
- *
- */
-@Uninterruptible
-public final class MutatorLocal extends ImmixAllocator
- implements Constants {
- /**
- * Constructor
- *
- * @param space The mark-sweep space to which this allocator
- * instances is bound.
- * @param hot TODO
- */
- public MutatorLocal(ImmixSpace space, boolean hot) {
- super(space, hot, false);
- }
-
- /****************************************************************************
- *
- * Collection
- */
-
- /**
- * Prepare for a collection. If paranoid, perform a sanity check.
- */
- public void prepare() {
- reset();
- }
-
- /**
- * Finish up after a collection.
- */
- public void release() {
- reset();
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/policy/immix/ObjectHeader.java b/vmkit/mmtk/java/src/org/mmtk/policy/immix/ObjectHeader.java
deleted file mode 100644
index a40694a..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/policy/immix/ObjectHeader.java
+++ /dev/null
@@ -1,176 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.policy.immix;
-
-import org.mmtk.utility.ForwardingWord;
-import org.mmtk.utility.HeaderByte;
-import org.mmtk.vm.VM;
-import org.vmmagic.pragma.Inline;
-import org.vmmagic.pragma.Uninterruptible;
-import org.vmmagic.unboxed.ObjectReference;
-
-@Uninterruptible
-public class ObjectHeader {
- /** number of header bits we may use */
- static final int AVAILABLE_LOCAL_BITS = 8 - HeaderByte.USED_GLOBAL_BITS;
-
- /* header requirements */
- public static final int LOCAL_GC_BITS_REQUIRED = AVAILABLE_LOCAL_BITS;
- public static final int GLOBAL_GC_BITS_REQUIRED = 0;
- public static final int GC_HEADER_WORDS_REQUIRED = 0;
-
- /* local status bits */
- static final byte NEW_OBJECT_MARK = 0; // using zero means no need for explicit initialization on allocation
-
- public static final int PINNED_BIT_NUMBER = ForwardingWord.FORWARDING_BITS;
- public static final byte PINNED_BIT = 1<<PINNED_BIT_NUMBER;
-
- private static final int STRADDLE_BIT_NUMBER = PINNED_BIT_NUMBER + 1;
- public static final byte STRADDLE_BIT = 1<<STRADDLE_BIT_NUMBER;
-
- /* mark bits */
- private static final int MARK_BASE = STRADDLE_BIT_NUMBER+1;
- static final int MAX_MARKCOUNT_BITS = AVAILABLE_LOCAL_BITS-MARK_BASE;
- private static final byte MARK_INCREMENT = 1<<MARK_BASE;
- public static final byte MARK_MASK = (byte) (((1<<MAX_MARKCOUNT_BITS)-1)<<MARK_BASE);
- private static final byte MARK_AND_FORWARDING_MASK = (byte) (MARK_MASK | ForwardingWord.FORWARDING_MASK);
- public static final byte MARK_BASE_VALUE = MARK_INCREMENT;
-
-
- /****************************************************************************
- *
- * Marking
- */
-
- /**
- * Non-atomically test and set the mark bit of an object. Return true
- * if successful, false if the mark bit was already set.
- *
- * @param object The object whose mark bit is to be written
- * @param markState The value to which the mark bits will be set
- */
- static byte testAndMark(ObjectReference object, byte markState) {
- byte oldValue, newValue, oldMarkState;
-
- oldValue = VM.objectModel.readAvailableByte(object);
- oldMarkState = (byte) (oldValue & MARK_MASK);
- if (oldMarkState != markState) {
- newValue = (byte) ((oldValue & ~MARK_MASK) | markState);
- if (HeaderByte.NEEDS_UNLOGGED_BIT)
- newValue |= HeaderByte.UNLOGGED_BIT;
- VM.objectModel.writeAvailableByte(object, newValue);
- }
- return oldMarkState;
- }
-
- static void setMarkStateUnlogAndUnlock(ObjectReference object, byte originalHeaderByte, byte markState) {
- byte oldValue = originalHeaderByte;
- byte newValue = (byte) ((oldValue & ~MARK_AND_FORWARDING_MASK) | markState);
- if (HeaderByte.NEEDS_UNLOGGED_BIT)
- newValue |= HeaderByte.UNLOGGED_BIT;
- VM.objectModel.writeAvailableByte(object, newValue);
- if (VM.VERIFY_ASSERTIONS)
- VM.assertions._assert((oldValue & MARK_MASK) != markState);
- }
-
- /**
- * Return true if the mark count for an object has the given value.
- *
- * @param object The object whose mark bit is to be tested
- * @param value The value against which the mark bit will be tested
- * @return True if the mark bit for the object has the given value.
- */
- static boolean testMarkState(ObjectReference object, byte value) {
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert((value & MARK_MASK) == value);
- return (VM.objectModel.readAvailableByte(object) & MARK_MASK) == value;
- }
-
- static boolean testMarkState(byte forwardingWord, byte value) {
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert((value & MARK_MASK) == value);
- return (forwardingWord & MARK_MASK) == value;
- }
-
- static boolean isNewObject(ObjectReference object) {
- return (VM.objectModel.readAvailableByte(object) & MARK_AND_FORWARDING_MASK) == NEW_OBJECT_MARK;
- }
-
- static boolean isMatureObject(ObjectReference object) {
- byte status = (byte) (VM.objectModel.readAvailableByte(object) & MARK_AND_FORWARDING_MASK);
- boolean unforwarded = (status & ForwardingWord.FORWARDING_MASK) == 0;
- boolean newObj = (status == NEW_OBJECT_MARK);
- return unforwarded && !newObj;
- }
-
- @Inline
- static void markAsStraddling(ObjectReference object) {
- byte old = VM.objectModel.readAvailableByte(object);
- VM.objectModel.writeAvailableByte(object, (byte) (old | STRADDLE_BIT));
- }
-
- @Inline
- static boolean isStraddlingObject(ObjectReference object) {
- return (VM.objectModel.readAvailableByte(object) & STRADDLE_BIT) == STRADDLE_BIT;
- }
-
- @Inline
- public static void pinObject(ObjectReference object) {
- byte old = VM.objectModel.readAvailableByte(object);
- VM.objectModel.writeAvailableByte(object, (byte) (old | PINNED_BIT));
- }
-
- @Inline
- static boolean isPinnedObject(ObjectReference object) {
- return (VM.objectModel.readAvailableByte(object) & PINNED_BIT) == PINNED_BIT;
- }
-
- /**
- * Write the allocState into the mark state fields of an object non-atomically.
- * This is appropriate for collection time initialization.
- *
- * @param object The object whose mark state is to be written
- * @param markState TODO: what am I?
- * @param straddle TODO: what am I?
- */
- static void writeMarkState(ObjectReference object, byte markState, boolean straddle) {
- byte oldValue = VM.objectModel.readAvailableByte(object);
- byte markValue = markState;
- byte newValue = (byte) (oldValue & ~MARK_AND_FORWARDING_MASK);
- if (HeaderByte.NEEDS_UNLOGGED_BIT)
- newValue |= HeaderByte.UNLOGGED_BIT;
- newValue |= markValue;
- if (straddle)
- newValue |= STRADDLE_BIT;
- VM.objectModel.writeAvailableByte(object, newValue);
- }
-
- static void returnToPriorStateAndEnsureUnlogged(ObjectReference object, byte status) {
- if (HeaderByte.NEEDS_UNLOGGED_BIT) status |= HeaderByte.UNLOGGED_BIT;
- VM.objectModel.writeAvailableByte(object, status);
- }
-
- /**
- * Return the mark state incremented or decremented by one.
- *
- * @param increment If true, then return the incremented value else return the decremented value
- * @return the mark state incremented or decremented by one.
- */
- static byte deltaMarkState(byte state, boolean increment) {
- byte rtn = state;
- do {
- rtn = (byte) (increment ? rtn + MARK_INCREMENT : rtn - MARK_INCREMENT);
- rtn &= MARK_MASK;
- } while (rtn < MARK_BASE_VALUE);
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(rtn != state);
- return rtn;
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/utility/BaseGenericFreeList.java b/vmkit/mmtk/java/src/org/mmtk/utility/BaseGenericFreeList.java
deleted file mode 100644
index a3cc93e..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/utility/BaseGenericFreeList.java
+++ /dev/null
@@ -1,366 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.utility;
-
-import org.mmtk.vm.VM;
-
-import org.vmmagic.pragma.*;
-
-/**
- * This is a very simple, generic malloc-free allocator. It works
- * abstractly, in "units", which the user may associate with some
- * other allocatable resource (e.g. heap blocks). The user issues
- * requests for N units and the allocator returns the index of the
- * first of a contiguous set of N units or fails, returning -1. The
- * user frees the block of N units by calling <code>free()</code> with
- * the index of the first unit as the argument.<p>
- *
- * Properties/Constraints:<ul>
- * <li> The allocator consumes one word per allocatable unit (plus
- * a fixed overhead of about 128 words).</li>
- * <li> The allocator can only deal with MAX_UNITS units (see below for
- * the value).</li>
- * </ul>
- *
- * The basic data structure used by the algorithm is a large table,
- * with one word per allocatable unit. Each word is used in a
- * number of different ways, some combination of "undefined" (32),
- * "free/used" (1), "multi/single" (1), "prev" (15), "next" (15) &
- * "size" (15) where field sizes in bits are in parenthesis.
- * <pre>
- * +-+-+-----------+-----------+
- * |f|m| prev | next/size |
- * +-+-+-----------+-----------+
- *
- * - single free unit: "free", "single", "prev", "next"
- * - single used unit: "used", "single"
- * - contiguous free units
- * . first unit: "free", "multi", "prev", "next"
- * . second unit: "free", "multi", "size"
- * . last unit: "free", "multi", "size"
- * - contiguous used units
- * . first unit: "used", "multi", "prev", "next"
- * . second unit: "used", "multi", "size"
- * . last unit: "used", "multi", "size"
- * - any other unit: undefined
- *
- * +-+-+-----------+-----------+
- * top sentinel |0|0| tail | head | [-1]
- * +-+-+-----------+-----------+
- * ....
- * /-------- +-+-+-----------+-----------+
- * | |1|1| prev | next | [j]
- * | +-+-+-----------+-----------+
- * | |1|1| | size | [j+1]
- * free multi +-+-+-----------+-----------+
- * unit block | ... | ...
- * | +-+-+-----------+-----------+
- * | |1|1| | size |
- * >-------- +-+-+-----------+-----------+
- * single free unit |1|0| prev | next |
- * >-------- +-+-+-----------+-----------+
- * single used unit |0|0| |
- * >-------- +-+-+-----------------------+
- * | |0|1| |
- * | +-+-+-----------+-----------+
- * | |0|1| | size |
- * used multi +-+-+-----------+-----------+
- * unit block | ... |
- * | +-+-+-----------+-----------+
- * | |0|1| | size |
- * \-------- +-+-+-----------+-----------+
- * ....
- * +-+-+-----------------------+
- * bottom sentinel |0|0| | [N]
- * +-+-+-----------------------+
- * </pre>
- * The sentinels serve as guards against out of range coalescing
- * because they both appear as "used" blocks and so will never
- * coalesce. The top sentinel also serves as the head and tail of
- * the doubly linked list of free blocks.
- */
-@Uninterruptible abstract class BaseGenericFreeList implements Constants {
-
- /****************************************************************************
- *
- * Public instance methods
- */
-
- /**
- * Allocate <code>size</code> units. Return the unit ID
- *
- * @param size The number of units to be allocated
- * @return The index of the first of the <code>size</code>
- * contiguous units, or -1 if the request can't be satisfied
- */
- public final int alloc(int size) {
- // Note: -1 is both the default return value *and* the start sentinel index
- int unit = head; // HEAD = -1
- int s = 0;
- while (((unit = getNext(unit)) != head) && ((s = getSize(unit)) < size));
-
- return (unit == head) ? FAILURE : alloc(size, unit, s);
- }
-
- /**
- * Would an allocation of <code>size</code> units succeed?
- *
- * @param size The number of units to test for
- * @return True if such a request could be satisfied.
- */
- public final boolean couldAlloc(int size) {
- // Note: -1 is both the default return value *and* the start sentinel index
- int unit = head; // HEAD = -1
- while (((unit = getNext(unit)) != head) && (getSize(unit) < size));
-
- return (unit != head);
- }
-
- /**
- * Allocate <code>size</code> units. Return the unit ID
- *
- * @param size The number of units to be allocated
- * @return The index of the first of the <code>size</code>
- * contiguous units, or -1 if the request can't be satisfied
- */
- public final int alloc(int size, int unit) {
- int s = 0;
-
- if (getFree(unit) && (s = getSize(unit)) >= size)
- return alloc(size, unit, s);
- else
- return FAILURE;
- }
-
- /**
- * Allocate <code>size</code> units. Return the unit ID
- *
- * @param size The number of units to be allocated
- * @return The index of the first of the <code>size</code>
- * contiguous units, or -1 if the request can't be satisfied
- */
- private int alloc(int size, int unit, int unitSize) {
- if (unitSize >= size) {
- if (unitSize > size)
- split(unit, size);
- removeFromFree(unit);
- setFree(unit, false);
- }
-
- if (DEBUG) dbgPrintFree();
-
- return unit;
- }
-
- /**
- * Free a previously allocated contiguous lump of units.
- *
- * @param unit The index of the first unit.
- * @return return the size of the unit which was freed.
- */
- public final int free(int unit) {
- return free(unit, false);
- }
-
- /**
- * Free a previously allocated contiguous lump of units.
- *
- * @param unit The index of the first unit.
- * @param returnCoalescedSize if true, return the coalesced size
- * @return The number of units freed. if returnCoalescedSize is
- * false, return the size of the unit which was freed. Otherwise
- * return the size of the unit now available (the coalesced size)
- */
- public final int free(int unit, boolean returnCoalescedSize) {
- int freed = getSize(unit);
- int left = getLeft(unit);
- int start = isCoalescable(unit) && getFree(left) ? left : unit;
- int right = getRight(unit);
- int end = isCoalescable(right) && getFree(right) ? right : unit;
- if (start != end)
- coalesce(start, end);
-
- if (returnCoalescedSize)
- freed = getSize(start);
- addToFree(start);
-
- if (DEBUG) dbgPrintFree();
- return freed;
- }
-
- /**
- * Return the size of the specified lump of units
- *
- * @param unit The index of the first unit in the lump.
- * @return The size of the lump, in units.
- */
- public final int size(int unit) {
- return getSize(unit);
- }
-
- /****************************************************************************
- *
- * Private fields and methods
- */
-
- /**
- * Initialize a new heap. Fabricate a free list entry containing
- * everything
- *
- * @param units The number of units in the heap
- */
- protected final void initializeHeap(int units) {
- initializeHeap(units, units);
- }
-
- /**
- * Initialize a new heap. Fabricate a free list entry containing
- * everything
- *
- * @param units The number of units in the heap
- */
- protected final void initializeHeap(int units, int grain) {
- // Initialize the sentinels
- for (int i = 1; i <= heads; i++)
- setSentinel(-i);
- setSentinel(units);
-
- // create the free list item
- int offset = units % grain;
- int cursor = units - offset;
- if (offset > 0) {
- setSize(cursor, offset);
- addToFree(cursor);
- }
- cursor -= grain;
- while (cursor >= 0) {
- setSize(cursor, grain);
- addToFree(cursor);
- cursor -= grain;
- }
- if (DEBUG) dbgPrintFree();
- }
-
- /**
- * Reduce a lump of units to size, freeing any excess.
- *
- * @param unit The index of the first unit
- * @param size The size of the first part
- */
- private void split(int unit, int size) {
- int basesize = getSize(unit);
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(basesize > size);
- setSize(unit, size);
- setSize(unit + size, basesize - size);
- addToFree(unit + size);
- if (DEBUG) dbgPrintFree();
- }
-
- /**
- * Coalesce two or three contiguous lumps of units, removing start
- * and end lumps from the free list as necessary.
- * @param start The index of the start of the first lump
- * @param end The index of the start of the last lump
- */
- private void coalesce(int start, int end) {
- if (getFree(end))
- removeFromFree(end);
- if (getFree(start))
- removeFromFree(start);
-
- setSize(start, end - start + getSize(end));
- }
-
- /**
- * Add a lump of units to the free list
- *
- * @param unit The first unit in the lump of units to be added
- */
- private void addToFree(int unit) {
- setFree(unit, true);
- int next = getNext(head);
- setNext(unit, next);
- setNext(head, unit);
- setPrev(unit, head);
- setPrev(next, unit);
- }
-
- /**
- * Remove a lump of units from the free list
- *
- * @param unit The first unit in the lump of units to be removed
- */
- private void removeFromFree(int unit) {
- int next = getNext(unit);
- int prev = getPrev(unit);
- setNext(prev, next);
- setPrev(next, prev);
- if (DEBUG) dbgPrintFree();
- }
-
- /**
- * Get the lump to the "right" of the current lump (i.e. "below" it)
- *
- * @param unit The index of the first unit in the lump in question
- * @return The index of the first unit in the lump to the
- * "right"/"below" the lump in question.
- */
- private int getRight(int unit) {
- return unit + getSize(unit);
- }
-
-
- /**
- * Print the free list (for debugging purposes)
- */
- void dbgPrintFree() {
- if (DEBUG) {
- Log.write("FL[");
- int i = head;
- while ((i = getNext(i)) != head) {
- boolean f = getFree(i);
- int s = getSize(i);
- if (!f)
- Log.write("->");
- Log.write(i);
- if (!f)
- Log.write("<-");
- Log.write("(");
- Log.write(s);
- Log.write(")");
- Log.write(" ");
- Log.flush();
- }
- Log.writeln("]FL");
- }
- }
-
- abstract void setSentinel(int unit);
- abstract int getSize(int unit);
- abstract void setSize(int unit, int size);
- abstract boolean getFree(int unit);
- abstract void setFree(int unit, boolean isFree);
- abstract int getNext(int unit);
- abstract void setNext(int unit, int next);
- abstract int getPrev(int unit);
- abstract void setPrev(int unit, int prev);
- abstract int getLeft(int unit);
- abstract boolean isCoalescable(int unit);
-
- protected static final boolean DEBUG = false;
- public static final int FAILURE = -1;
- protected static final int MAX_HEADS = 128; // somewhat arbitrary
-
- protected int heads = 1;
- protected int head = -heads;
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/utility/CallSite.java b/vmkit/mmtk/java/src/org/mmtk/utility/CallSite.java
deleted file mode 100644
index e55016c..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/utility/CallSite.java
+++ /dev/null
@@ -1,18 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.utility;
-
-/*
- */
-public class CallSite {
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/utility/Constants.java b/vmkit/mmtk/java/src/org/mmtk/utility/Constants.java
deleted file mode 100644
index 217fb11..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/utility/Constants.java
+++ /dev/null
@@ -1,146 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.utility;
-
-import org.mmtk.utility.alloc.EmbeddedMetaData;
-import org.mmtk.vm.VM;
-
-/**
- * MMTk follows the pattern set by Jikes RVM for defining sizes of
- * primitive types thus:
- *
- * <pre>
- * static final int LOG_BYTES_IN_INT = 2;
- * static final int BYTES_IN_INT = 1<<LOG_BYTES_IN_INT;
- * static final int LOG_BITS_IN_INT = LOG_BITS_IN_BYTE + LOG_BYTES_IN_INT;
- * static final int BITS_IN_INT = 1<<LOG_BITS_IN_INT;
- * </pre>
- */
-public interface Constants {
-
- /****************************************************************************
- *
- * MMTk constants
- */
- int INSTANCE_FIELD = 0;
- int ARRAY_ELEMENT = 1;
-
-
- /****************************************************************************
- *
- * Generic sizes
- */
- byte LOG_BYTES_IN_BYTE = 0;
- int BYTES_IN_BYTE = 1;
- byte LOG_BITS_IN_BYTE = 3;
- int BITS_IN_BYTE = 1 << LOG_BITS_IN_BYTE;
-
- byte LOG_BYTES_IN_MBYTE = 20;
- int BYTES_IN_MBYTE = 1 << LOG_BYTES_IN_MBYTE;
-
- byte LOG_BYTES_IN_KBYTE = 10;
- int BYTES_IN_KBYTE = 1 << LOG_BYTES_IN_KBYTE;
-
- /****************************************************************************
- *
- * Card scanning
- */
- boolean SUPPORT_CARD_SCANNING = false;
- int LOG_CARD_META_SIZE = 2;// each card consumes four bytes of metadata
- int LOG_CARD_UNITS = 10; // number of units tracked per card
- int LOG_CARD_GRAIN = 0; // track at byte grain, save shifting
- int LOG_CARD_BYTES = LOG_CARD_UNITS + LOG_CARD_GRAIN;
- int LOG_CARD_META_BYTES = EmbeddedMetaData.LOG_BYTES_IN_REGION - LOG_CARD_BYTES + LOG_CARD_META_SIZE;
- int LOG_CARD_META_PAGES = LOG_CARD_META_BYTES - VM.LOG_BYTES_IN_PAGE;
- int CARD_META_PAGES_PER_REGION = SUPPORT_CARD_SCANNING ? (1<<LOG_CARD_META_PAGES) : 0;
- int CARD_MASK = (1<<LOG_CARD_BYTES) - 1;
-
-
- /****************************************************************************
- *
- * Java-specific sizes currently required by MMTk
- *
- * TODO MMTk should really become independent of these Java types
- */
- byte LOG_BYTES_IN_CHAR= 1;
- int BYTES_IN_CHAR = 1 << LOG_BYTES_IN_CHAR;
- byte LOG_BITS_IN_CHAR = LOG_BITS_IN_BYTE + LOG_BYTES_IN_CHAR;
- int BITS_IN_CHAR = 1 << LOG_BITS_IN_CHAR;
-
- byte LOG_BYTES_IN_SHORT = 1;
- int BYTES_IN_SHORT = 1 << LOG_BYTES_IN_SHORT;
- byte LOG_BITS_IN_SHORT = LOG_BITS_IN_BYTE + LOG_BYTES_IN_SHORT;
- int BITS_IN_SHORT = 1 << LOG_BITS_IN_SHORT;
-
- byte LOG_BYTES_IN_INT = 2;
- int BYTES_IN_INT = 1 << LOG_BYTES_IN_INT;
- byte LOG_BITS_IN_INT = LOG_BITS_IN_BYTE + LOG_BYTES_IN_INT;
- int BITS_IN_INT = 1 << LOG_BITS_IN_INT;
-
- int MAX_INT = 0x7fffffff;
- int MIN_INT = 0x80000000;
-
- /****************************************************************************
- *
- * VM-Specific sizes
- */
- byte LOG_BYTES_IN_ADDRESS = VM.LOG_BYTES_IN_ADDRESS;
- int BYTES_IN_ADDRESS = 1 << LOG_BYTES_IN_ADDRESS;
- int LOG_BITS_IN_ADDRESS = LOG_BITS_IN_BYTE + LOG_BYTES_IN_ADDRESS;
- int BITS_IN_ADDRESS = 1 << LOG_BITS_IN_ADDRESS;
-
- // Note that in MMTk we currently define WORD & ADDRESS to be the same size
- byte LOG_BYTES_IN_WORD = LOG_BYTES_IN_ADDRESS;
- int BYTES_IN_WORD = 1 << LOG_BYTES_IN_WORD;
- int LOG_BITS_IN_WORD = LOG_BITS_IN_BYTE + LOG_BYTES_IN_WORD;
- int BITS_IN_WORD = 1 << LOG_BITS_IN_WORD;
-
- byte LOG_BYTES_IN_PAGE = VM.LOG_BYTES_IN_PAGE;
- int BYTES_IN_PAGE = 1 << LOG_BYTES_IN_PAGE;
- int LOG_BITS_IN_PAGE = LOG_BITS_IN_BYTE + LOG_BYTES_IN_PAGE;
- int BITS_IN_PAGE = 1 << LOG_BITS_IN_PAGE;
-
- /* Assume byte-addressability */
- byte LOG_BYTES_IN_ADDRESS_SPACE = (byte) BITS_IN_ADDRESS;
-
- /**
- * This value specifies the <i>minimum</i> allocation alignment
- * requirement of the VM. When making allocation requests, both
- * <code>align</code> and <code>offset</code> must be multiples of
- * <code>MIN_ALIGNMENT</code>.
- *
- * This value is required to be a power of 2.
- */
- byte LOG_MIN_ALIGNMENT = VM.LOG_MIN_ALIGNMENT;
- int MIN_ALIGNMENT = 1 << LOG_MIN_ALIGNMENT;
-
- /**
- * The maximum alignment request the vm will make. This must be a
- * power of two multiple of the minimum alignment.
- */
- int MAX_ALIGNMENT = MIN_ALIGNMENT<<VM.MAX_ALIGNMENT_SHIFT;
-
- /**
- * The VM will add at most this value minus BYTES_IN_INT bytes of
- * padding to the front of an object that it places in a region of
- * memory. This value must be a power of 2.
- */
- int MAX_BYTES_PADDING = VM.MAX_BYTES_PADDING;
-
- /**
- * The VM will add at most this value minus BYTES_IN_INT bytes of
- * padding to the front of an object that it places in a region of
- * memory. This value must be a power of 2.
- */
- int ALIGNMENT_VALUE = VM.ALIGNMENT_VALUE;
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/utility/Conversions.java b/vmkit/mmtk/java/src/org/mmtk/utility/Conversions.java
deleted file mode 100644
index a9e93cc..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/utility/Conversions.java
+++ /dev/null
@@ -1,163 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.utility;
-
-import org.mmtk.utility.heap.*;
-
-import org.mmtk.vm.VM;
-
-import org.vmmagic.unboxed.*;
-import org.vmmagic.pragma.*;
-
-/*
- import org.jikesrvm.Offset;
- * Conversions between different units.
- */
-@Uninterruptible public class Conversions implements Constants {
-
- // public static Address roundDownVM(Address addr) {
- // return roundDown(addr.toWord(), VMResource.LOG_BYTES_IN_REGION).toAddress();
- // }
-
- // public static Extent roundDownVM(Extent bytes) {
- // return roundDown(bytes.toWord(), VMResource.LOG_BYTES_IN_REGION).toExtent();
- // }
-
- public static Address roundDownMB(Address addr) {
- return roundDown(addr.toWord(), LOG_BYTES_IN_MBYTE).toAddress();
- }
-
- public static Extent roundDownMB(Extent bytes) {
- return roundDown(bytes.toWord(), LOG_BYTES_IN_MBYTE).toExtent();
- }
-
- private static Word roundDown(Word value, int logBase) {
- Word mask = Word.one().lsh(logBase).minus(Word.one()).not();
- return value.and(mask);
- }
-
- public static int roundDown(int value, int alignment) {
- return value & ~(alignment - 1);
- }
-
- // Round up (if necessary)
- //
- public static int MBToPages(int megs) {
- if (LOG_BYTES_IN_PAGE <= LOG_BYTES_IN_MBYTE)
- return (megs << (LOG_BYTES_IN_MBYTE - LOG_BYTES_IN_PAGE));
- else
- return (megs + ((BYTES_IN_PAGE >>> LOG_BYTES_IN_MBYTE) - 1)) >>> (LOG_BYTES_IN_PAGE - LOG_BYTES_IN_MBYTE);
- }
-
- public static int bytesToMmapChunksUp(Extent bytes) {
- return bytes.plus(Mmapper.MMAP_CHUNK_BYTES - 1).toWord().rshl(Mmapper.LOG_MMAP_CHUNK_BYTES).toInt();
- }
-
- public static int pagesToMmapChunksUp(int pages) {
- return bytesToMmapChunksUp(pagesToBytes(pages));
- }
-
- public static int addressToMmapChunksDown(Address addr) {
- Word chunk = addr.toWord().rshl(Mmapper.LOG_MMAP_CHUNK_BYTES);
- return chunk.toInt();
- }
-
- public static int addressToPagesDown(Address addr) {
- Word chunk = addr.toWord().rshl(LOG_BYTES_IN_PAGE);
- return chunk.toInt();
- }
-
- public static int addressToPages(Address addr) {
- int page = addressToPagesDown(addr);
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(pagesToAddress(page).EQ(addr));
- return page;
- }
-
- public static Address pagesToAddress(int pages) {
- return Word.fromIntZeroExtend(pages).lsh(LOG_BYTES_IN_PAGE).toAddress();
- }
-
- public static int addressToMmapChunksUp(Address addr) {
- Word chunk = addr.plus(Mmapper.MMAP_CHUNK_BYTES - 1).toWord().rshl(Mmapper.LOG_MMAP_CHUNK_BYTES);
- return chunk.toInt();
- }
-
- public static Extent pagesToBytes(int pages) {
- return Word.fromIntZeroExtend(pages).lsh(LOG_BYTES_IN_PAGE).toExtent();
- }
-
- public static int pagesToMBytes(int pages) {
- return pages >> (LOG_BYTES_IN_MBYTE - LOG_BYTES_IN_PAGE);
- }
-
- public static int pagesToKBytes(int pages) {
- return pages << (LOG_BYTES_IN_PAGE - LOG_BYTES_IN_KBYTE);
- }
-
- /**
- @deprecated : use int bytesToPagesUp(Extent bytes) if possible
- */
- @Deprecated
- public static int bytesToPagesUp(int bytes) {
- return bytesToPagesUp(Extent.fromIntZeroExtend(bytes));
- }
-
- /**
- @deprecated : use int bytesToPagesUp(Extent bytes) if possible
- */
- @Deprecated
- public static int bytesToPages(int bytes) {
- return bytesToPages(Extent.fromIntZeroExtend(bytes));
- }
-
- public static int bytesToPagesUp(Extent bytes) {
- return bytes.plus(BYTES_IN_PAGE-1).toWord().rshl(LOG_BYTES_IN_PAGE).toInt();
- }
-
- public static int bytesToPages(Extent bytes) {
- int pages = bytesToPagesUp(bytes);
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(pagesToAddress(pages).toWord().toExtent().EQ(bytes));
- return pages;
- }
-
- public static int bytesToPages(Offset bytes) {
- if (VM.VERIFY_ASSERTIONS) {
- long val = bytes.toLong();
- VM.assertions._assert(val >= MIN_INT && val <= MAX_INT);
- }
- if (bytes.sGE(Offset.zero()))
- return bytesToPagesUp(Extent.fromIntSignExtend(bytes.toInt()));
- else
- return -bytesToPagesUp(Extent.fromIntSignExtend(-bytes.toInt()));
- }
-
- public static Address mmapChunksToAddress(int chunk) {
- return Word.fromIntZeroExtend(chunk).lsh(Mmapper.LOG_MMAP_CHUNK_BYTES).toAddress();
- }
-
- public static Address pageAlign(Address address) {
- return address.toWord().rshl(LOG_BYTES_IN_PAGE).lsh(LOG_BYTES_IN_PAGE).toAddress();
- }
-
- public static int pageAlign(int value) {
- return (value>>LOG_BYTES_IN_PAGE)<<LOG_BYTES_IN_PAGE;
- }
-
- public static boolean isPageAligned(Address address) {
- return pageAlign(address).EQ(address);
- }
-
- public static boolean isPageAligned(int value) {
- return pageAlign(value) == value;
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/utility/CycleDetector.java b/vmkit/mmtk/java/src/org/mmtk/utility/CycleDetector.java
deleted file mode 100644
index 9d46838..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/utility/CycleDetector.java
+++ /dev/null
@@ -1,32 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.utility;
-
-import org.mmtk.utility.options.*;
-
-import org.vmmagic.unboxed.*;
-import org.vmmagic.pragma.*;
-
-/*
- */
-@Uninterruptible abstract class CycleDetector {
-
- static {
- Options.cycleFilterThreshold = new CycleFilterThreshold();
- Options.cycleMetaDataLimit = new CycleMetaDataLimit();
- Options.cycleTriggerThreshold = new CycleTriggerThreshold();
- }
-
- abstract boolean collectCycles(boolean primary, boolean time);
- abstract void possibleCycleRoot(ObjectReference object);
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/utility/DoublyLinkedList.java b/vmkit/mmtk/java/src/org/mmtk/utility/DoublyLinkedList.java
deleted file mode 100644
index c7b05fa..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/utility/DoublyLinkedList.java
+++ /dev/null
@@ -1,208 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.utility;
-
-import org.mmtk.utility.gcspy.drivers.AbstractDriver;
-
-import org.mmtk.vm.Lock;
-import org.mmtk.vm.VM;
-
-import org.vmmagic.pragma.*;
-import org.vmmagic.unboxed.*;
-
-/**
- * FIXME This class must be re-written as it makes the assumption that
- * the implementation language (Java) and the language being
- * implemented are the same. This is true in the case of Jikes RVM,
- * but it is not true for any VM implementing a language other than
- * Java.
- *
- *
- * Each instance of this class is a doubly-linked list, in which
- * each item or node is a piece of memory. The first two words of each node
- * contains the forward and backward links. The third word contains
- * the treadmill. The remaining portion is the payload.
- *
- * The treadmill object itself must not be moved.
- *
- * Access to the instances may be synchronized depending on the
- * constructor argument.
- */
-@Uninterruptible public final class DoublyLinkedList implements Constants {
-
- /****************************************************************************
- *
- * Class variables
- */
-
- /****************************************************************************
- *
- * Instance variables
- */
- private Address head;
- private final Lock lock;
- private final int logGranularity; // Each node on the treadmill is guaranteed to be a multiple of granularity.
-
- /****************************************************************************
- *
- * Instance Methods
- */
-
- /**
- * Constructor
- */
- public DoublyLinkedList(int logGranularity, boolean shared) {
- head = Address.zero();
- lock = shared ? VM.newLock("DoublyLinkedList") : null;
- this.logGranularity = logGranularity;
-
- // ensure that granularity is big enough for midPayloadToNode to work
- Word tmp = Word.one().lsh(logGranularity);
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(tmp.and(nodeMask).EQ(tmp));
- }
-
- // Offsets are relative to the node (not the payload)
- //
- private static final Offset PREV_OFFSET = Offset.fromIntSignExtend(0 * BYTES_IN_ADDRESS);
- private static Offset NEXT_OFFSET = Offset.fromIntSignExtend(1 * BYTES_IN_ADDRESS);
- private static Offset HEADER_SIZE = Offset.fromIntSignExtend(2 * BYTES_IN_ADDRESS);
-
- private static final Word nodeMask;
- static {
- Word mask = Word.one();
- while (mask.LE(HEADER_SIZE.plus(MAX_BYTES_PADDING).toWord())) mask = mask.lsh(1);
- nodeMask = mask.minus(Word.one()).not();
- }
-
- @Inline
- public static int headerSize() {
- return HEADER_SIZE.toInt();
- }
-
- public boolean isNode(Address node) {
- return node.toWord().rshl(logGranularity).lsh(logGranularity).EQ(node.toWord());
- }
-
- @Inline
- public static Address nodeToPayload(Address node) {
- return node.plus(HEADER_SIZE);
- }
-
- @Inline
- public static Address midPayloadToNode(Address payload) {
- // This method words as long as you are less than MAX_BYTES_PADDING into the payload.
- return payload.toWord().and(nodeMask).toAddress();
- }
-
- @Inline
- public void add(Address node) {
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(isNode(node));
- if (lock != null) lock.acquire();
- node.store(Address.zero(), PREV_OFFSET);
- node.store(head, NEXT_OFFSET);
- if (!head.isZero())
- head.store(node, PREV_OFFSET);
- head = node;
- if (lock != null) lock.release();
- }
-
- @Inline
- public void remove(Address node) {
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(isNode(node));
- if (lock != null) lock.acquire();
- Address prev = node.loadAddress(PREV_OFFSET);
- Address next = node.loadAddress(NEXT_OFFSET);
- // Splice the node out of the list
- if (!next.isZero())
- next.store(prev, PREV_OFFSET);
- if (prev.isZero())
- head = next;
- else
- prev.store(next, NEXT_OFFSET);
- // Null out node's reference to the list
- node.store(Address.zero(), PREV_OFFSET);
- node.store(Address.zero(), NEXT_OFFSET);
- if (lock != null) lock.release();
- }
-
- @Inline
- public Address getHead() {
- return head;
- }
-
- @Inline
- public Address getNext(Address node) {
- return node.loadAddress(NEXT_OFFSET);
- }
-
- @Inline
- public Address pop() {
- Address first = head;
- if (!first.isZero())
- remove(first);
- return first;
- }
-
- @Inline
- public boolean isEmpty() {
- return head.isZero();
- }
-
- /**
- * Return true if a cell is on a given treadmill
- *
- * @param node The cell being searched for
- * @return True if the cell is found on the treadmill
- */
- public boolean isMember(Address node) {
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(isNode(node));
- boolean result = false;
- if (lock != null) lock.acquire();
- Address cur = head;
- while (!cur.isZero()) {
- if (cur.EQ(node)) {
- result = true;
- break;
- }
- cur = cur.loadAddress(NEXT_OFFSET);
- }
- if (lock != null) lock.release();
- return result;
- }
-
- public void show() {
- if (lock != null) lock.acquire();
- Address cur = head;
- Log.write(cur);
- while (!cur.isZero()) {
- cur = cur.loadAddress(NEXT_OFFSET);
- Log.write(" -> "); Log.write(cur);
- }
- Log.writeln();
- if (lock != null) lock.release();
- }
-
-
- /**
- * Gather data for GCSpy
- * @param driver the GCSpy space driver
- */
- void gcspyGatherData(AbstractDriver driver) {
- // GCSpy doesn't need a lock (in its stop the world config)
- Address cur = head;
- while (!cur.isZero()) {
- driver.scan(cur);
- cur = cur.loadAddress(NEXT_OFFSET);
- }
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/utility/ForwardingWord.java b/vmkit/mmtk/java/src/org/mmtk/utility/ForwardingWord.java
deleted file mode 100644
index 6771b2b..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/utility/ForwardingWord.java
+++ /dev/null
@@ -1,163 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.utility;
-
-import org.mmtk.vm.VM;
-import org.vmmagic.pragma.Inline;
-import org.vmmagic.pragma.Uninterruptible;
-import org.vmmagic.unboxed.ObjectReference;
-import org.vmmagic.unboxed.Word;
-
-/**
- * This class provides generic support for object forwarding, which is specific
- * to a few policies that support copying. The broad idea is two-fold: 1) the
- * two low-order bits of the GC byte (which are also the two low-order bits of
- * the header word) are used to indicate whether an object has been forwarded
- * or is being forwarded, and 2) if an object has been forwarded then the entire
- * header word of the dead object is used to store a pointer to the forwarded
- * pointer. This is a standard implementation of forwarding.<p>
- *
- * The two lowest order bits are used for object forwarding because forwarding
- * generally must steal the unused two low order bits of the forwarding pointer.
- */
-@Uninterruptible
-public class ForwardingWord {
- /*
- * The forwarding process uses three states to deal with a GC race:
- * 1. !FORWARDED: Unforwarded
- * 2. BEING_FORWARDED: Being forwarded (forwarding is underway)
- * 3. FORWARDED: Forwarded
- */
- /** If this bit is set, then forwarding of this object is incomplete */
- private static final byte BEING_FORWARDED = 2; // ...10
- /** If this bit is set, then forwarding of this object has commenced */
- private static final byte FORWARDED = 3; // ...11
- /** This mask is used to reveal which state this object is in with respect to forwarding */
- public static final byte FORWARDING_MASK = 3; // ...11
-
- public static final int FORWARDING_BITS = 2;
-
-
- /**
- * Either return the forwarding pointer if the object is already
- * forwarded (or being forwarded) or write the bit pattern that
- * indicates that the object is being forwarded
- *
- * @param object The object to be forwarded
- * @return The forwarding pointer for the object if it has already
- * been forwarded.
- */
- @Inline
- public static Word attemptToForward(ObjectReference object) {
- Word oldValue;
- do {
- oldValue = VM.objectModel.prepareAvailableBits(object);
- if ((byte) (oldValue.toInt() & FORWARDING_MASK) == FORWARDED)
- return oldValue;
- } while (!VM.objectModel.attemptAvailableBits(object, oldValue,
- oldValue.or(Word.fromIntZeroExtend(BEING_FORWARDED))));
- return oldValue;
- }
-
- public static ObjectReference spinAndGetForwardedObject(ObjectReference object, Word statusWord) {
- /* We must wait (spin) if the object is not yet fully forwarded */
- while ((statusWord.toInt() & FORWARDING_MASK) == BEING_FORWARDED)
- statusWord = VM.objectModel.readAvailableBitsWord(object);
-
- /* Now extract the object reference from the forwarding word and return it */
- if ((statusWord.toInt() & FORWARDING_MASK) == FORWARDED)
- return statusWord.and(Word.fromIntZeroExtend(FORWARDING_MASK).not()).toAddress().toObjectReference();
- else
- return object;
- }
-
- public static ObjectReference forwardObject(ObjectReference object, int allocator) {
- ObjectReference newObject = VM.objectModel.copy(object, allocator);
- VM.objectModel.writeAvailableBitsWord(object, newObject.toAddress().toWord().or(Word.fromIntZeroExtend(FORWARDED)));
- return newObject;
- }
-
- /**
- * Non-atomic write of forwarding pointer word (assumption, thread
- * doing the set has done attempt to forward and owns the right to
- * copy the object)
- *
- * @param object The object whose forwarding pointer is to be set
- * @param ptr The forwarding pointer to be stored in the object's
- * forwarding word
- */
- @Inline
- public static void setForwardingPointer(ObjectReference object,
- ObjectReference ptr) {
- VM.objectModel.writeAvailableBitsWord(object, ptr.toAddress().toWord().or(Word.fromIntZeroExtend(FORWARDED)));
- }
-
- /**
- * Has an object been forwarded?
- *
- * @param object The object to be checked
- * @return True if the object has been forwarded
- */
- @Inline
- public static boolean isForwarded(ObjectReference object) {
- return (VM.objectModel.readAvailableByte(object) & FORWARDING_MASK) == FORWARDED;
- }
-
- /**
- * Has an object been forwarded or is it being forwarded?
- *
- * @param object The object to be checked
- * @return True if the object has been forwarded
- */
- @Inline
- public static boolean isForwardedOrBeingForwarded(ObjectReference object) {
- return (VM.objectModel.readAvailableByte(object) & FORWARDING_MASK) != 0;
- }
-
- /**
- * Has an object been forwarded or being forwarded?
- *
- * @param object The object to be checked
- * @return True if the object has been forwarded
- */
- @Inline
- public static boolean stateIsForwardedOrBeingForwarded(Word header) {
- return (header.toInt() & FORWARDING_MASK) != 0;
- }
-
- /**
- * Has an object been forwarded or being forwarded?
- *
- * @param object The object to be checked
- * @return True if the object has been forwarded
- */
- @Inline
- public static boolean stateIsBeingForwarded(Word header) {
- return (header.toInt() & FORWARDING_MASK) == BEING_FORWARDED;
- }
-
- /**
- * Clear the GC forwarding portion of the header for an object.
- *
- * @param object the object ref to the storage to be initialized
- */
- @Inline
- public static void clearForwardingBits(ObjectReference object) {
- VM.objectModel.writeAvailableByte(object, (byte) (VM.objectModel.readAvailableByte(object) & ~FORWARDING_MASK));
- }
-
- @Inline
- public static ObjectReference extractForwardingPointer(Word forwardingWord) {
- return forwardingWord.and(Word.fromIntZeroExtend(FORWARDING_MASK).not()).toAddress().toObjectReference();
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/utility/GenericFreeList.java b/vmkit/mmtk/java/src/org/mmtk/utility/GenericFreeList.java
deleted file mode 100644
index 95a0645..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/utility/GenericFreeList.java
+++ /dev/null
@@ -1,383 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.utility;
-
-import org.mmtk.plan.Plan;
-import org.mmtk.vm.VM;
-
-import org.vmmagic.pragma.*;
-
-/**
- * This is a very simple, generic malloc-free allocator. It works
- * abstractly, in "units", which the user may associate with some
- * other allocatable resource (e.g. heap blocks). The user issues
- * requests for N units and the allocator returns the index of the
- * first of a contiguous set of N units or fails, returning -1. The
- * user frees the block of N units by calling <code>free()</code> with
- * the index of the first unit as the argument.<p>
- *
- * Properties/Constraints:<ul>
- * <li> The allocator consumes one word per allocatable unit (plus
- * a fixed overhead of about 128 words).</li>
- * <li> The allocator can only deal with MAX_UNITS units (see below for
- * the value).</li>
- * </ul>
- *
- * The basic data structure used by the algorithm is a large table,
- * with one word per allocatable unit. Each word is used in a
- * number of different ways, some combination of "undefined" (32),
- * "free/used" (1), "multi/single" (1), "prev" (15), "next" (15) &
- * "size" (15) where field sizes in bits are in parenthesis.
- * <pre>
- * +-+-+-----------+-----------+
- * |f|m| prev | next/size |
- * +-+-+-----------+-----------+
- *
- * - single free unit: "free", "single", "prev", "next"
- * - single used unit: "used", "single"
- * - contiguous free units
- * . first unit: "free", "multi", "prev", "next"
- * . second unit: "free", "multi", "size"
- * . last unit: "free", "multi", "size"
- * - contiguous used units
- * . first unit: "used", "multi", "prev", "next"
- * . second unit: "used", "multi", "size"
- * . last unit: "used", "multi", "size"
- * - any other unit: undefined
- *
- * +-+-+-----------+-----------+
- * top sentinel |0|0| tail | head | [-1]
- * +-+-+-----------+-----------+
- * ....
- * /-------- +-+-+-----------+-----------+
- * | |1|1| prev | next | [j]
- * | +-+-+-----------+-----------+
- * | |1|1| | size | [j+1]
- * free multi +-+-+-----------+-----------+
- * unit block | ... | ...
- * | +-+-+-----------+-----------+
- * | |1|1| | size |
- * >-------- +-+-+-----------+-----------+
- * single free unit |1|0| prev | next |
- * >-------- +-+-+-----------+-----------+
- * single used unit |0|0| |
- * >-------- +-+-+-----------------------+
- * | |0|1| |
- * | +-+-+-----------+-----------+
- * | |0|1| | size |
- * used multi +-+-+-----------+-----------+
- * unit block | ... |
- * | +-+-+-----------+-----------+
- * | |0|1| | size |
- * \-------- +-+-+-----------+-----------+
- * ....
- * +-+-+-----------------------+
- * bottom sentinel |0|0| | [N]
- * +-+-+-----------------------+
- * </pre>
- * The sentinels serve as guards against out of range coalescing
- * because they both appear as "used" blocks and so will never
- * coalesce. The top sentinel also serves as the head and tail of
- * the doubly linked list of free blocks.
- */
-@Uninterruptible
-public final class GenericFreeList extends BaseGenericFreeList implements Constants {
-
- /****************************************************************************
- *
- * Public instance methods
- */
-
- /**
- * Constructor
- *
- * @param units The number of allocatable units for this free list
- */
- public GenericFreeList(int units) {
- this(units, units);
- }
-
- /**
- * Constructor
- *
- * @param units The number of allocatable units for this free list
- * @param grain Units are allocated such that they will never cross this granularity boundary
- */
- public GenericFreeList(int units, int grain) {
- this(units, grain, 1);
- }
-
- /**
- * Constructor
- *
- * @param units The number of allocatable units for this free list
- * @param grain Units are allocated such that they will never cross this granularity boundary
- * @param heads The number of free lists which will share this instance
- */
- public GenericFreeList(int units, int grain, int heads) {
- this.parent = null;
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(units <= MAX_UNITS && heads <= MAX_HEADS);
- this.heads = heads;
- head = -1;
-
- // allocate the data structure, including space for top & bottom sentinels
- table = new int[(units + 1 + heads) << 1];
- initializeHeap(units, grain);
- }
-
- /**
- * Resize the free list for a parent free list.
- * This must not be called dynamically (ie not after bootstrap).
- *
- * @param units The number of allocatable units for this free list
- * @param grain Units are allocated such that they will never cross this granularity boundary
- */
- @Interruptible
- public void resizeFreeList(int units, int grain) {
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(parent == null && !Plan.isInitialized());
- table = new int[(units + 1 + heads) << 1];
- initializeHeap(units, grain);
- }
-
- /**
- * Resize the free list for a child free list.
- * This must not be called dynamically (ie not after bootstrap).
- */
- @Interruptible
- public void resizeFreeList() {
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(parent != null && !Plan.isInitialized());
- table = parent.getTable();
- }
-
- /**
- * Constructor
- *
- * @param parent The parent, owning the data structures this instance will share
- * @param ordinal The ordinal number of this child
- */
- public GenericFreeList(GenericFreeList parent, int ordinal) {
- this.parent = parent;
- this.table = parent.getTable();
- this.heads = parent.getHeads();
- this.head = -(1 + ordinal);
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(-this.head <= this.heads);
- }
-
- /** Getter */
- int[] getTable() { return table; }
- int getHeads() { return heads; }
-
- /**
- * Initialize a unit as a sentinel
- *
- * @param unit The unit to be initialized
- */
- protected void setSentinel(int unit) {
- setLoEntry(unit, NEXT_MASK & unit);
- setHiEntry(unit, PREV_MASK & unit);
- }
-
- /**
- * Get the size of a lump of units
- *
- * @param unit The first unit in the lump of units
- * @return The size of the lump of units
- */
- protected int getSize(int unit) {
- if ((getHiEntry(unit) & MULTI_MASK) == MULTI_MASK)
- return (getHiEntry(unit + 1) & SIZE_MASK);
- else
- return 1;
- }
-
- /**
- * Set the size of lump of units
- *
- * @param unit The first unit in the lump of units
- * @param size The size of the lump of units
- */
- protected void setSize(int unit, int size) {
- if (size > 1) {
- setHiEntry(unit, getHiEntry(unit) | MULTI_MASK);
- setHiEntry(unit + 1, MULTI_MASK | size);
- setHiEntry(unit + size - 1, MULTI_MASK | size);
- } else
- setHiEntry(unit, getHiEntry(unit) & ~MULTI_MASK);
- }
-
- /**
- * Establish whether a lump of units is free
- *
- * @param unit The first or last unit in the lump
- * @return True if the lump is free
- */
- protected boolean getFree(int unit) {
- return ((getLoEntry(unit) & FREE_MASK) == FREE_MASK);
- }
-
- /**
- * Set the "free" flag for a lump of units (both the first and last
- * units in the lump are set.
- *
- * @param unit The first unit in the lump
- * @param isFree True if the lump is to be marked as free
- */
- protected void setFree(int unit, boolean isFree) {
- int size;
- if (isFree) {
- setLoEntry(unit, getLoEntry(unit) | FREE_MASK);
- if ((size = getSize(unit)) > 1)
- setLoEntry(unit + size - 1, getLoEntry(unit + size - 1) | FREE_MASK);
- } else {
- setLoEntry(unit, getLoEntry(unit) & ~FREE_MASK);
- if ((size = getSize(unit)) > 1)
- setLoEntry(unit + size - 1, getLoEntry(unit + size - 1) & ~FREE_MASK);
- }
- }
-
- /**
- * Get the next lump in the doubly linked free list
- *
- * @param unit The index of the first unit in the current lump
- * @return The index of the first unit of the next lump of units in the list
- */
- protected int getNext(int unit) {
- int next = getHiEntry(unit) & NEXT_MASK;
- return (next <= MAX_UNITS) ? next : head;
- }
-
- /**
- * Set the next lump in the doubly linked free list
- *
- * @param unit The index of the first unit in the lump to be set
- * @param next The value to be set.
- */
- protected void setNext(int unit, int next) {
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert((next >= -heads) && (next <= MAX_UNITS));
- int oldValue = getHiEntry(unit);
- int newValue = (oldValue & ~NEXT_MASK) | (next & NEXT_MASK);
- setHiEntry(unit, newValue);
- }
-
- /**
- * Get the previous lump in the doubly linked free list
- *
- * @param unit The index of the first unit in the current lump
- * @return The index of the first unit of the previous lump of units
- * in the list
- */
- protected int getPrev(int unit) {
- int prev = getLoEntry(unit) & PREV_MASK;
- return (prev <= MAX_UNITS) ? prev : head;
- }
-
- /**
- * Set the previous lump in the doubly linked free list
- *
- * @param unit The index of the first unit in the lump to be set
- * @param prev The value to be set.
- */
- protected void setPrev(int unit, int prev) {
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert((prev >= -heads) && (prev <= MAX_UNITS));
- int oldValue = getLoEntry(unit);
- int newValue = (oldValue & ~PREV_MASK) | (prev & PREV_MASK);
- setLoEntry(unit, newValue);
- }
-
- /**
- * Set the uncoalescable bit associated with this unit.
- * This ensures this unit cannot be coalesced with units below
- * it.
- *
- * @param unit The unit whose uncoalescable bit is to be set
- */
- public void setUncoalescable(int unit) {
- setLoEntry(unit, getLoEntry(unit) | COALESC_MASK);
- }
-
- /**
- * Clear the uncoalescable bit associated with this unit.
- * This allows this unit to be coalesced with units below
- * it.
- *
- * @param unit The unit whose uncoalescable bit is to be cleared
- */
- public void clearUncoalescable(int unit) {
- setLoEntry(unit, getLoEntry(unit) & ~COALESC_MASK);
- }
-
- /**
- * Return true if this unit may be coalesced with the unit below it.
- *
- * @param unit The unit in question
- * @return True if this unit may be coalesced with the unit below it.
- */
- @Override
- public boolean isCoalescable(int unit) {
- return (getLoEntry(unit) & COALESC_MASK) == 0;
- }
-
- /**
- * Get the lump to the "left" of the current lump (i.e. "above" it)
- *
- * @param unit The index of the first unit in the lump in question
- * @return The index of the first unit in the lump to the
- * "left"/"above" the lump in question.
- */
- protected int getLeft(int unit) {
- if ((getHiEntry(unit - 1) & MULTI_MASK) == MULTI_MASK)
- return unit - (getHiEntry(unit - 1) & SIZE_MASK);
- else
- return unit - 1;
- }
-
-
- /**
- * Get the contents of an entry
- *
- * @param unit The index of the unit
- * @return The contents of the unit
- */
- private int getLoEntry(int unit) {
- return table[(unit + heads) << 1];
- }
- private int getHiEntry(int unit) {
- return table[((unit + heads) << 1) + 1];
- }
-
- /**
- * Set the contents of an entry
- *
- * @param unit The index of the unit
- * @param value The contents of the unit
- */
- private void setLoEntry(int unit, int value) {
- table[(unit + heads) << 1] = value;
- }
- private void setHiEntry(int unit, int value) {
- table[((unit + heads) << 1) + 1] = value;
- }
-
- private static final int TOTAL_BITS = 32;
- private static final int UNIT_BITS = (TOTAL_BITS - 2);
- public static final int MAX_UNITS = (int) (((((long) 1) << UNIT_BITS) - 1) - MAX_HEADS - 1);
- private static final int NEXT_MASK = (int) ((((long) 1) << UNIT_BITS) - 1);
- private static final int PREV_MASK = (int) ((((long) 1) << UNIT_BITS) - 1);
- private static final int FREE_MASK = 1 << (TOTAL_BITS - 1);
- private static final int MULTI_MASK = 1 << (TOTAL_BITS - 1);
- private static final int COALESC_MASK = 1 << (TOTAL_BITS - 2);
- private static final int SIZE_MASK = (int) ((((long) 1) << UNIT_BITS) - 1);
-
- private int[] table;
- private final GenericFreeList parent;
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/utility/HeaderByte.java b/vmkit/mmtk/java/src/org/mmtk/utility/HeaderByte.java
deleted file mode 100644
index aba8620..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/utility/HeaderByte.java
+++ /dev/null
@@ -1,89 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.utility;
-
-import org.mmtk.vm.VM;
-import org.vmmagic.pragma.Uninterruptible;
-import org.vmmagic.unboxed.Address;
-import org.vmmagic.unboxed.ObjectReference;
-
-/**
- * This class provides generic support for operations over the GC byte
- * within each object's header word. Specifically this class manages
- * global status bits which cut across policies (for example the logging bit).<p>
- *
- * The general pattern for use of the GC byte is that the high order bits
- * successively reserved for global use, as necessary. Any GC policy may use
- * those bits that are not reserved for global use.<p>
- */
-@Uninterruptible
-public class HeaderByte {
- private static final int TOTAL_BITS = 8;
-
- public static final boolean NEEDS_UNLOGGED_BIT = VM.activePlan.constraints().needsLogBitInHeader();
- private static final int UNLOGGED_BIT_NUMBER = TOTAL_BITS - (NEEDS_UNLOGGED_BIT ? 1 : 0);
- public static final byte UNLOGGED_BIT = (byte) (1<<UNLOGGED_BIT_NUMBER);
- public static final int USED_GLOBAL_BITS = TOTAL_BITS - UNLOGGED_BIT_NUMBER;
-
-
- /**
- * Perform any required initialization of the GC portion of the header.
- * Called for objects created at boot time.
- *
- * @param ref the object ref to the storage to be initialized
- * @param typeRef the type reference for the instance being created
- * @param size the number of bytes allocated by the GC system for
- * this object.
- * @param status the initial value of the status word
- * @return The new value of the status word
- */
- public static byte setBuildTimeGCByte(Address object, ObjectReference typeRef, int size) {
- byte status = 0;
-
- if (NEEDS_UNLOGGED_BIT)
- status |= UNLOGGED_BIT;
- return status;
- }
-
-
- public static void markAsUnlogged(ObjectReference object) {
- byte value = VM.objectModel.readAvailableByte(object);
- VM.objectModel.writeAvailableByte(object, (byte) (value | UNLOGGED_BIT));
- }
-
- /**
- * Mark an object as logged. Since duplicate logging does
- * not raise any correctness issues, we do <i>not</i> worry
- * about synchronization and allow threads to race to log the
- * object, potentially including it twice (unlike reference
- * counting where duplicates would lead to incorrect reference
- * counts).
- *
- * @param object The object to be marked as logged
- */
- public static void markAsLogged(ObjectReference object) {
- byte value = VM.objectModel.readAvailableByte(object);
- VM.objectModel.writeAvailableByte(object, (byte) (value & ~UNLOGGED_BIT));
- }
-
- /**
- * Return true if the specified object needs to be logged.
- *
- * @param object The object in question
- * @return True if the object in question needs to be logged (remembered).
- */
- public static boolean isUnlogged(ObjectReference object) {
- byte value = VM.objectModel.readAvailableByte(object);
- return (value & UNLOGGED_BIT) == UNLOGGED_BIT;
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/utility/Log.java b/vmkit/mmtk/java/src/org/mmtk/utility/Log.java
deleted file mode 100644
index c6adf0b..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/utility/Log.java
+++ /dev/null
@@ -1,842 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.utility;
-
-import org.mmtk.vm.VM;
-
-import org.vmmagic.unboxed.*;
-import org.vmmagic.pragma.*;
-
-/**
- * Error and trace logging.
- */
-@Uninterruptible
-public class Log implements Constants {
-
- /****************************************************************************
- *
- * Class variables
- */
-
- /**
- * characters in the write buffer for the caller's message. This
- * does not include characters reserved for the overflow message.
- *
- * This needs to be large because Jikes RVM's implementation of Lock.java
- * logs a lot of information when there is potential GC deadlock.
- */
- private static final int MESSAGE_BUFFER_SIZE = 3000;
-
- /** message added when the write buffer has overflown */
- private static final String OVERFLOW_MESSAGE = "... WARNING: Text truncated.\n";
-
- private static final char OVERFLOW_MESSAGE_FIRST_CHAR = OVERFLOW_MESSAGE.charAt(0);
-
- /** characters in the overflow message, including the (optional) final
- * newline */
- private static final int OVERFLOW_SIZE = OVERFLOW_MESSAGE.length();
-
- /**
- * characters in buffer for building string representations of
- * longs. A long is a signed 64-bit integer in the range -2^63 to
- * 2^63+1. The number of digits in the decimal representation of
- * 2^63 is ceiling(log10(2^63)) == ceiling(63 * log10(2)) == 19. An
- * extra character may be required for a minus sign (-). So the
- * maximum number of characters is 20.
- */
- private static final int TEMP_BUFFER_SIZE = 20;
-
- /** string that prefixes numbers logged in hexadecimal */
- private static final String HEX_PREFIX = "0x";
-
- /**
- * log2 of number of bits represented by a single hexidemimal digit
- */
- private static final int LOG_BITS_IN_HEX_DIGIT = 2;
-
- /**
- * log2 of number of digits in the unsigned hexadecimal
- * representation of a byte
- */
- private static final int LOG_HEX_DIGITS_IN_BYTE = LOG_BITS_IN_BYTE - LOG_BITS_IN_HEX_DIGIT;
-
- /**
- * map of hexadecimal digit values to their character representations
- */
- private static final char [] hexDigitCharacter =
- { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
-
- /** new line character. Emitted by writeln methods. */
- private static final char NEW_LINE_CHAR = '\n';
-
- /** log instance used at build time. */
- private static Log log = new Log();
-
- /****************************************************************************
- *
- * Instance variables
- */
-
- /** buffer to store written message until flushing */
- private char [] buffer = new char[MESSAGE_BUFFER_SIZE + OVERFLOW_SIZE];
-
- /** location of next character to be written */
- private int bufferIndex = 0;
-
- /** <code>true</code> if the buffer has overflown */
- private boolean overflow = false;
-
- /** The last character that was written by #addToBuffer(char). This is
- used to check whether we want to newline-terminate the text. */
- private char overflowLastChar = '\0';
-
- /** <code>true</code> if a thread id will be prepended */
- private boolean threadIdFlag = false;
-
- /** buffer for building string representations of longs */
- private char[] tempBuffer = new char[TEMP_BUFFER_SIZE];
-
- /** constructor */
- public Log() {
- for (int i = 0; i < OVERFLOW_SIZE; i++) {
- buffer[MESSAGE_BUFFER_SIZE + i] = OVERFLOW_MESSAGE.charAt(i);
- }
- }
-
- /**
- * writes a boolean. Either "true" or "false" is logged.
- *
- * @param b boolean value to be logged.
- */
- public static void write(boolean b) {
- write(b ? "true" : "false");
- }
-
- /**
- * writes a character
- *
- * @param c character to be logged
- */
- public static void write(char c) {
- add(c);
- }
-
- /**
- * writes a long, in decimal. The value is not padded and no
- * thousands seperator is logged. If the value is negative a
- * leading minus sign (-) is logged.
- *
- *
- * @param l long value to be logged
- */
- public static void write(long l) {
- boolean negative = l < 0;
- int nextDigit;
- char nextChar;
- int index = TEMP_BUFFER_SIZE - 1;
- char[] intBuffer = getIntBuffer();
-
- nextDigit = (int) (l % 10);
- nextChar = hexDigitCharacter[negative ? - nextDigit : nextDigit];
- intBuffer[index--] = nextChar;
- l = l / 10;
-
- while (l != 0) {
- nextDigit = (int) (l % 10);
- nextChar = hexDigitCharacter[negative ? - nextDigit : nextDigit];
- intBuffer[index--] = nextChar;
- l = l / 10;
- }
-
- if (negative) {
- intBuffer[index--] = '-';
- }
-
- for (index++; index < TEMP_BUFFER_SIZE; index++) {
- add(intBuffer[index]);
- }
- }
-
- /**
- * writes a <code>double</code>. Two digits after the decimal point
- * are always logged. The value is not padded and no thousands
- * seperator is used. If the value is negative a leading
- * hyphen-minus (-) is logged. The decimal point is a full stop
- * (.).
- *
- * @param d the double to be logged
- */
- public static void write(double d) { write(d, 2); }
-
- /**
- * writes a <code>double</code>. The number of digits after the
- * decimal point is determined by <code>postDecimalDigits</code>.
- * The value is not padded and not thousands seperator is used. If
- * the value is negative a leading hyphen-minus (-) is logged. The
- * decimal point is a full stop (.) and is logged even if
- * <postDecimcalDigits</code> is zero. If <code>d</code> is greater
- * than the largest representable value of type <code>int</code>, it
- * is logged as "TooBig". Similarly, if it is less than
- * the negative of the largest representable value, it is logged as
- * "TooSmall". If <code>d</code> is NaN is is logged as "NaN".
- *
- * @param d the double to be logged
- * @param postDecimalDigits the number of digits to be logged after
- * the decimal point. If less than or equal to zero no digits are
- * logged, but the decimal point is.
- */
- public static void write(double d, int postDecimalDigits) {
- if (d != d) {
- write("NaN");
- return;
- }
- if (d > Integer.MAX_VALUE) {
- write("TooBig");
- return;
- }
- if (d < -Integer.MAX_VALUE) {
- write("TooSmall");
- return;
- }
-
- boolean negative = (d < 0.0);
- d = negative ? (-d) : d; // Take absolute value
- int ones = (int) d;
- int multiplier = 1;
- while (postDecimalDigits-- > 0)
- multiplier *= 10;
- int remainder = (int) (multiplier * (d - ones));
- if (remainder < 0) remainder = 0;
- if (negative) write('-');
- write(ones);
- write('.');
- while (multiplier > 1) {
- multiplier /= 10;
- write(remainder / multiplier);
- remainder %= multiplier;
- }
- }
-
- /**
- * writes an array of characters
- *
- * @param c the array of characters to be logged
- */
- public static void write(char[] c) {
- write(c, c.length);
- }
-
- /**
- * writes the start of an array of characters
- *
- * @param c the array of characters
- * @param len the number of characters to be logged, starting with
- * the first character
- */
- public static void write(char[] c, int len) {
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(len <= c.length);
- for (int i = 0; i < len; i++) {
- add(c[i]);
- }
- }
-
- /**
- * writes an array of bytes. The bytes are interpretted
- * as characters.
- *
- * @param b the array of bytes to be logged
- */
- public static void write(byte[] b) {
- for (int i = 0; i < b.length; i++) {
- add((char)b[i]);
- }
- }
-
- /**
- * writes a string
- *
- * @param s the string to be logged
- */
- public static void write(String s) {
- add(s);
- }
-
- /**
- * writes a word, in hexadecimal. It is zero-padded to the size of
- * an address.
- *
- * @param w the word to be logged
- */
- public static void write(Word w) {
- writeHex(w, BYTES_IN_ADDRESS);
- }
-
- /**
- * writes a word, in decimal.
- *
- * @param w the word to be logged
- */
- public static void writeDec(Word w) {
- if (BYTES_IN_ADDRESS == 4) {
- write(w.toInt());
- } else {
- write(w.toLong());
- }
- }
-
- /**
- * writes an address, in hexademical. It is zero-padded.
- *
- * @param a the address to be logged
- */
- public static void write(Address a) {
- writeHex(a.toWord(), BYTES_IN_ADDRESS);
- }
-
- /**
- * writes a string followed by an address, in hexademical.
- * @see #write(String)
- * @see #write(Address)
- *
- * @param s the string to be logged
- * @param a the address to be logged
- */
- public static void write(String s, Address a) {
- write(s);
- write(a);
- }
-
- /**
- * Write a string followed by a long
- * @see #write(String)
- * @see #write(long)
- *
- * @param s the string to be logged
- * @param l the long to be logged
- */
- public static void write(String s, long l) {
- write(s);
- write(l);
- }
-
- /**
- * writes an object reference, in hexademical. It is zero-padded.
- *
- * @param o the object reference to be logged
- */
- public static void write(ObjectReference o) {
- writeHex(o.toAddress().toWord(), BYTES_IN_ADDRESS);
- }
-
- /**
- * writes an offset, in hexademical. It is zero-padded.
- *
- * @param o the offset to be logged
- */
- public static void write(Offset o) {
- writeHex(o.toWord(), BYTES_IN_ADDRESS);
- }
-
- /**
- * writes an extent, in hexademical. It is zero-padded.
- *
- * @param e the extent to be logged
- */
- public static void write(Extent e) {
- writeHex(e.toWord(), BYTES_IN_ADDRESS);
- }
-
- /**
- * write a new-line and flushes the buffer
- */
- public static void writeln() {
- writelnWithFlush(true);
- }
-
- /**
- * writes a boolean and a new-line, then flushes the buffer.
- * @see #write(boolean)
- *
- * @param b boolean value to be logged.
- */
- public static void writeln(boolean b) { writeln(b, true); }
-
- /**
- * writes a character and a new-line, then flushes the buffer.
- * @see #write(char)
- *
- * @param c character to be logged
- */
- public static void writeln(char c) { writeln(c, true); }
-
- /**
- * writes a long, in decimal, and a new-line, then flushes the buffer.
- * @see #write(long)
- *
- * @param l long value to be logged
- */
- public static void writeln(long l) { writeln(l, true); }
-
- /**
- * writes a <code>double</code> and a new-line, then flushes the buffer.
- * @see #write(double)
- *
- * @param d the double to be logged
- */
- public static void writeln(double d) { writeln(d, true); }
-
- /**
- * writes a <code>double</code> and a new-line, then flushes the buffer.
- * @see #write(double, int)
- *
- * @param d the double to be logged
- */
- public static void writeln(double d, int postDecimalDigits) {
- writeln(d, postDecimalDigits, true); }
-
- /**
- * writes an array of characters and a new-line, then flushes the buffer.
- * @see #write(char [])
- *
- * @param ca the array of characters to be logged
- */
- public static void writeln(char [] ca) { writeln(ca, true); }
-
- /**
- * writes the start of an array of characters and a new-line, then
- * flushes the buffer.
- * @see #write(char[], int)
- *
- * @param ca the array of characters
- * @param len the number of characters to be logged, starting with
- * the first character
- */
- public static void writeln(char [] ca, int len) { writeln(ca, len, true); }
-
- /**
- * writes an array of bytes and a new-line, then
- * flushes the buffer.
- * @see #write(byte[])
- *
- * @param b the array of bytes to be logged
- */
- public static void writeln(byte [] b) { writeln(b, true); }
-
- /**
- * writes a string and a new-line, then flushes the buffer.
- *
- * @param s the string to be logged
- */
- public static void writeln(String s) { writeln(s, true); }
-
- /**
- * writes a word, in hexadecimal, and a new-line, then flushes the buffer.
- * @see #write(Word)
- *
- * @param w the word to be logged
- */
- public static void writeln(Word w) { writeln(w, true); }
-
- /**
- * writes an address, in hexademical, and a new-line, then flushes
- * the buffer.
- * @see #write(Address)
- *
- * @param a the address to be logged
- */
- public static void writeln(Address a) { writeln(a, true); }
-
- /**
- * writes an object reference, in hexademical, and a new-line, then
- * flushes the buffer.
- * @see #write(ObjectReference)
- *
- * @param o the object reference to be logged
- */
- public static void writeln(ObjectReference o) { writeln(o, true); }
-
- /**
- * writes an offset, in hexademical, and a new-line, then flushes the buffer.
- * @see #write(Offset)
- *
- * @param o the offset to be logged
- */
- public static void writeln(Offset o) { writeln(o, true); }
-
- /**
- * writes an extent, in hexademical, and a new-line, then flushes the buffer.
- * @see #write(Extent)
- *
- * @param e the extent to be logged
- */
- public static void writeln(Extent e) { writeln(e, true); }
-
- /**
- * writes a new-line without flushing the buffer
- */
- public static void writelnNoFlush() {
- writelnWithFlush(false);
- }
-
- /**
- * writes a boolean and a new-line, then optionally flushes the buffer.
- * @see #write(boolean)
- *
- * @param b boolean value to be logged.
- * @param flush if <code>true</code> then flushes the buffer
- */
- public static void writeln(boolean b, boolean flush) {
- write(b);
- writelnWithFlush(flush);
- }
-
- /**
- * writes a character and a new-line, then optionally flushes the
- * buffer.
- * @see #write(char)
- *
- * @param c character to be logged
- * @param flush if <code>true</code> then flushes the buffer
- */
- public static void writeln(char c, boolean flush) {
- write(c);
- writelnWithFlush(flush);
- }
-
- /**
- * writes a long, in decimal, and a new-line, then optionally flushes
- * the buffer.
- * @see #write(long)
- *
- * @param l long value to be logged
- * @param flush if <code>true</code> then flushes the buffer
- */
- public static void writeln(long l, boolean flush) {
- write(l);
- writelnWithFlush(flush);
- }
-
- /**
- * writes a <code>double</code> and a new-line, then optionally flushes
- * the buffer.
- * @see #write(double)
- *
- * @param d the double to be logged
- * @param flush if <code>true</code> then flush the buffer
- */
- public static void writeln(double d, boolean flush) {
- write(d);
- writelnWithFlush(flush);
- }
-
- /**
- * writes a <code>double</code> and a new-line, then optionally flushes
- * the buffer.
- * @see #write(double, int)
- *
- * @param d the double to be logged
- * @param flush if <code>true</code> then flushes the buffer
- */
- public static void writeln(double d, int postDecimalDigits, boolean flush) {
- write(d, postDecimalDigits);
- writelnWithFlush(flush);
- }
-
-
- /**
- * writes an array of characters and a new-line, then optionally
- * flushes the buffer.
- * @see #write(char [])
- *
- * @param ca the array of characters to be logged
- * @param flush if <code>true</code> then flushes the buffer
- */
- public static void writeln(char[] ca, boolean flush) {
- write(ca);
- writelnWithFlush(flush);
- }
-
- /**
- * writes the start of an array of characters and a new-line, then
- * optionally flushes the buffer.
- * @see #write(char[], int)
- *
- * @param ca the array of characters
- * @param len the number of characters to be logged, starting with
- * the first character
- * @param flush if <code>true</code> then flushes the buffer
- */
- public static void writeln(char[] ca, int len, boolean flush) {
- write(ca, len);
- writelnWithFlush(flush);
- }
-
- /**
- * writes an array of bytes and a new-line, then optionally flushes the
- * buffer.
- * @see #write(byte[])
- *
- * @param b the array of bytes to be logged
- * @param flush if <code>true</code> then flushes the buffer
- */
- public static void writeln(byte[] b, boolean flush) {
- write(b);
- writelnWithFlush(flush);
- }
-
- /**
- * writes a string and a new-line, then optionally flushes the buffer.
- *
- * @param s the string to be logged
- * @param flush if <code>true</code> then flushes the buffer
- */
- public static void writeln(String s, boolean flush) {
- write(s);
- writelnWithFlush(flush);
- }
-
- public static void writeln(String s, long l) {
- write(s);
- writeln(l);
- }
-
-
- /**
- * writes a word, in hexadecimal, and a new-line, then optionally
- * flushes the buffer.
- * @see #write(Word)
- *
- * @param w the word to be logged
- * @param flush if <code>true</code> then flushes the buffer
- */
- public static void writeln(Word w, boolean flush) {
- write(w);
- writelnWithFlush(flush);
- }
-
-
- /**
- * writes an address, in hexademical, and a new-line, then optionally
- * flushes the buffer.
- * @see #write(Address)
- *
- * @param a the address to be logged
- * @param flush if <code>true</code> then flushes the buffer
- */
- public static void writeln(Address a, boolean flush) {
- write(a);
- writelnWithFlush(flush);
- }
-
- /**
- * writes an object reference, in hexademical, and a new-line, then
- * optionally flushes the buffer.
- * @see #write(ObjectReference)
- *
- * @param o the object reference to be logged
- * @param flush if <code>true</code> then flushes the buffer
- */
- public static void writeln(ObjectReference o, boolean flush) {
- write(o);
- writelnWithFlush(flush);
- }
-
- /**
- * writes an offset, in hexademical, and a new-line, then optionally
- * flushes the buffer.
- * @see #write(Offset)
- *
- * @param o the offset to be logged
- * @param flush if <code>true</code> then flushes the buffer
- */
- public static void writeln(Offset o, boolean flush) {
- write(o);
- writelnWithFlush(flush);
- }
-
- /**
- * writes an extent, in hexademical, and a new-line, then optionally
- * flushes the buffer.
- * @see #write(Extent)
- *
- * @param e the extent to be logged
- * @param flush if <code>true</code> then flushes the buffer
- */
- public static void writeln(Extent e, boolean flush) {
- write(e);
- writelnWithFlush(flush);
- }
-
- /**
- * writes a string followed by a Address
- * @see #write(String)
- * @see #write(Address)
- *
- * @param s the string to be logged
- * @param a the Address to be logged
- */
- public static void writeln(String s, Address a) {
- write(s);
- writeln(a);
- }
-
- /**
- * Log a thread identifier at the start of the next message flushed.
- */
- public static void prependThreadId() {
- getLog().setThreadIdFlag();
- }
-
- /**
- * flushes the buffer. The buffered effected of writes since the last
- * flush will be logged in one block without output from other
- * thread's logging interleaving.
- */
- public static void flush() {
- getLog().flushBuffer();
- }
-
- /**
- * writes a new-line and optionally flushes the buffer
- *
- * @param flush if <code>true</code> the buffer is flushed
- */
- private static void writelnWithFlush(boolean flush) {
- add(NEW_LINE_CHAR);
- if (flush) {
- flush();
- }
- }
-
- /**
- * writes a <code>long</code> in hexadecimal
- *
- * @param w the Word to be logged
- * @param bytes the number of bytes from the long to be logged. If
- * less than 8 then the least significant bytes are logged and some
- * of the most significant bytes are ignored.
- */
- private static void writeHex(Word w, int bytes) {
- int hexDigits = bytes * (1 << LOG_HEX_DIGITS_IN_BYTE);
- int nextDigit;
-
- write(HEX_PREFIX);
-
- for (int digitNumber = hexDigits - 1; digitNumber >= 0; digitNumber--) {
- nextDigit = w.rshl(digitNumber << LOG_BITS_IN_HEX_DIGIT).toInt() & 0xf;
- char nextChar = hexDigitCharacter[nextDigit];
- add(nextChar);
- }
- }
-
- /**
- * adds a character to the buffer
- *
- * @param c the character to add
- */
- private static void add(char c) {
- getLog().addToBuffer(c);
- }
-
- /**
- * adds a string to the buffer
- *
- * @param s the string to add
- */
- private static void add(String s) {
- getLog().addToBuffer(s);
- }
-
- private static Log getLog() {
- if (VM.assertions.runningVM()) {
- return VM.activePlan.log();
- } else {
- return log;
- }
- }
-
- /**
- * adds a character to the buffer
- *
- * @param c the character to add
- */
- private void addToBuffer(char c) {
- if (bufferIndex < MESSAGE_BUFFER_SIZE) {
- buffer[bufferIndex++] = c;
- } else {
- overflow = true;
- overflowLastChar = c;
- }
- }
-
- /**
- * adds a string to the buffer
- *
- * @param s the string to add
- */
- private void addToBuffer(String s) {
- if (bufferIndex < MESSAGE_BUFFER_SIZE) {
- bufferIndex += VM.strings.copyStringToChars(s, buffer, bufferIndex, MESSAGE_BUFFER_SIZE + 1);
- if (bufferIndex == MESSAGE_BUFFER_SIZE + 1) {
- overflow = true;
- // We don't bother setting OVERFLOW_LAST_CHAR, since we don't have an
- // MMTk method that lets us peek into a string. Anyway, it's just a
- // convenience to get the newline right.
- buffer[MESSAGE_BUFFER_SIZE] = OVERFLOW_MESSAGE_FIRST_CHAR;
- bufferIndex--;
- }
- } else {
- overflow = true;
- }
- }
-
- /**
- * flushes the buffer
- */
- private void flushBuffer() {
- int newlineAdjust = overflowLastChar == NEW_LINE_CHAR ? 0 : -1;
- int totalMessageSize = overflow ? (MESSAGE_BUFFER_SIZE + OVERFLOW_SIZE + newlineAdjust) : bufferIndex;
- if (threadIdFlag) {
- VM.strings.writeThreadId(buffer, totalMessageSize);
- } else {
- VM.strings.write(buffer, totalMessageSize);
- }
- threadIdFlag = false;
- overflow = false;
- overflowLastChar = '\0';
- bufferIndex = 0;
- }
-
- /**
- * sets the flag so that a thread identifier will be included before
- * the logged message
- */
- private void setThreadIdFlag() {
- threadIdFlag = true;
- }
-
- /**
- * gets the buffer for building string representations of integers.
- * There is one of these buffers for each Log instance.
- */
- private static char[] getIntBuffer() {
- return getLog().getTempBuffer();
- }
-
- /**
- * gets the buffer for building string representations of integers.
- */
- private char[] getTempBuffer() {
- return tempBuffer;
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/utility/Memory.java b/vmkit/mmtk/java/src/org/mmtk/utility/Memory.java
deleted file mode 100644
index fb863ef..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/utility/Memory.java
+++ /dev/null
@@ -1,216 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.utility;
-
-import org.mmtk.vm.VM;
-
-import org.vmmagic.unboxed.*;
-import org.vmmagic.pragma.*;
-
-/**
- * This class implements basic memory copying, setting and clearing
- * operations.
- *
- * NOTE: Most of the operations in this class are performed at teh
- * granularity of a Java integer (ie 4-byte units)
- *
- * FIXME: Why can't these operations be performed at word-granularity?
- */
-@Uninterruptible
-public class Memory implements Constants {
-
- /****************************************************************************
- *
- * Class variables
- */
-
- /** zero operations greater than this size are done using the
- * underlying OS implementation of zero() */
- private static final int SMALL_REGION_THRESHOLD = 1<<8; // empirically chosen
-
-
- /****************************************************************************
- *
- * Basic memory setting and zeroing operations
- */
-
- /**
- * Zero a region of memory
- *
- * @param start The start of the region to be zeroed (must be 4-byte aligned)
- * @param bytes The number of bytes to be zeroed (must be 4-byte aligned)
- */
- @Inline
- public static void zero(Address start, Extent bytes) {
- if (VM.VERIFY_ASSERTIONS) {
- assertAligned(start);
- assertAligned(bytes);
- }
- if (bytes.GT(Extent.fromIntZeroExtend(SMALL_REGION_THRESHOLD)))
- VM.memory.zero(start, bytes);
- else
- zeroSmall(start, bytes);
- }
-
- /**
- * Zero a small region of memory
- *
- * @param start The start of the region to be zeroed (must be 4-byte aligned)
- * @param bytes The number of bytes to be zeroed (must be 4-byte aligned)
- */
- @Inline
- public static void zeroSmall(Address start, Extent bytes) {
- if (VM.VERIFY_ASSERTIONS) {
- assertAligned(start);
- assertAligned(bytes);
- }
- Address end = start.plus(bytes);
- for (Address addr = start; addr.LT(end); addr = addr.plus(BYTES_IN_INT))
- addr.store(0);
- }
-
- /**
- * Set a region of memory
- *
- * @param start The start of the region to be zeroed (must be 4-byte aligned)
- * @param bytes The number of bytes to be zeroed (must be 4-byte aligned)
- * @param value The value to which the integers in the region should be set
- */
- @Inline
- public static void set(Address start, int bytes, int value) {
- if (VM.VERIFY_ASSERTIONS) {
- assertAligned(start);
- assertAligned(bytes);
- }
- Address end = start.plus(bytes);
- for (Address addr = start; addr.LT(end); addr = addr.plus(BYTES_IN_INT))
- addr.store(value);
- }
-
-
- /****************************************************************************
- *
- * Helper methods
- */
-
- /**
- * Check that a memory range is zeroed
- *
- * @param start The start address of the range to be checked
- * @param bytes The size of the region to be checked, in bytes
- * @return True if the region is zeroed
- */
- @Inline
- public static boolean IsZeroed(Address start, int bytes) {
- return isSet(start, bytes, false, 0);
- }
-
- /**
- * Assert that a memory range is zeroed. An assertion failure will
- * occur if the region is not zeroed.
- *
- * this is in the inline allocation sequence when
- * VM.VERIFY_ASSERTIONS is true, it is carefully written to
- * reduce the impact on code space.
- *
- * @param start The start address of the range to be checked
- * @param bytes The size of the region to be checked, in bytes
- */
- @NoInline
- public static void assertIsZeroed(Address start, int bytes) {
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(isSet(start, bytes, true, 0));
- }
-
- /**
- * Verbosely check and return true if a memory range is set to some
- * integer value
- *
- * @param start The start address of the range to be checked
- * @param bytes The size of the region to be checked, in bytes
- * @param value The value to which this region should be set
- * @return True if the region has been correctly set
- */
- @Inline
- public static boolean isSet(Address start, int bytes, int value) {
- return isSet(start, bytes, true, value);
- }
-
- /**
- * Assert appropriate alignment, triggering an assertion failure if
- * the value does not satisify the alignment requirement of the
- * memory operations.
- *
- * @param value The value to be tested
- */
- private static void assertAligned(int value) {
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert((value & (BYTES_IN_INT - 1)) == 0);
- }
-
- private static void assertAligned(Word value) {
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(value.and(Word.fromIntSignExtend(BYTES_IN_INT-1)).isZero());
- }
-
- private static void assertAligned(Extent value) {
- assertAligned(value.toWord());
- }
-
- private static void assertAligned(Address value) {
- assertAligned(value.toWord());
- }
-
- /**
- * Test whether a memory range is set to a given integer value
- *
- * @param start The address to start checking at
- * @param bytes The size of the region to check, in bytes
- * @param verbose If true, produce verbose output
- * @param value The value to which the memory should be set
- */
- @NoInline
- private static boolean isSet(Address start, int bytes, boolean verbose,
- int value)
- /* Inlining this loop into the uninterruptible code can
- * cause/encourage the GCP into moving a get_obj_tib into the
- * interruptible region where the tib is being installed via an
- * int_store
- */ {
- if (VM.VERIFY_ASSERTIONS) assertAligned(bytes);
- for (int i = 0; i < bytes; i += BYTES_IN_INT)
- if (start.loadInt(Offset.fromIntSignExtend(i)) != value) {
- if (verbose) {
- Log.prependThreadId();
- Log.write("VM range does not contain only value ");
- Log.writeln(value);
- Log.write("Non-zero range: "); Log.write(start);
- Log.write(" .. "); Log.writeln(start.plus(bytes));
- Log.write("First bad value at "); Log.writeln(start.plus(i));
- dumpMemory(start, 0, bytes);
- }
- return false;
- }
- return true;
- }
-
- /**
- * Dump the contents of memory around a given address
- *
- * @param addr The address around which the memory should be dumped
- * @param beforeBytes The number of bytes before the address to be
- * included in the dump
- * @param afterBytes The number of bytes after the address to be
- * included in the dump
- */
- public static void dumpMemory(Address addr, int beforeBytes, int afterBytes) {
- VM.memory.dumpMemory(addr, beforeBytes, afterBytes);
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/utility/SimpleHashtable.java b/vmkit/mmtk/java/src/org/mmtk/utility/SimpleHashtable.java
deleted file mode 100644
index bd3dfc3..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/utility/SimpleHashtable.java
+++ /dev/null
@@ -1,232 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.utility;
-
-import org.mmtk.policy.RawPageSpace;
-import org.mmtk.vm.VM;
-
-import org.vmmagic.pragma.*;
-import org.vmmagic.unboxed.*;
-
-/**
- * This class implements a simple hashtable. It is intended for use
- * in sanity checking or debugging, not high-performance algorithms.<p>
- *
- * This class is not thread safe.
- */
-@Uninterruptible public abstract class SimpleHashtable implements Constants {
- /** The number of low order bits to ignore */
- private static final int HASH_SHIFT = 3;
-
- /** Offset to the key */
- private static final Offset KEY_OFFSET = Offset.zero();
-
- /** Offset to the data */
- private static final Offset DATA_OFFSET = Offset.fromIntSignExtend(BYTES_IN_WORD);
-
- /** The size of each entry in the table */
- private final Extent entrySize;
-
- /** The mask to use to get the hash code */
- private final Word mask;
-
- /** The start address of the data table */
- private Address base;
-
- /** The full size of the table */
- private final Extent size;
-
- /** The space to use for allocating the data structure */
- private final RawPageSpace space;
-
- /** Is this table valid (created) */
- private boolean valid;
-
- /**
- * Create a new data table of a specified size.
- *
- * @param rps The space to acquire the data structure from.
- * @param logSize The log of the number of table entries.
- * @param es The size of each entry.
- */
- protected SimpleHashtable(RawPageSpace rps, int logSize, Extent es) {
- mask = Word.fromIntZeroExtend((1 << logSize) - 1);
- entrySize = es.plus(BYTES_IN_WORD);
- size = Extent.fromIntZeroExtend((1 << logSize) * entrySize.toInt());
- base = Address.zero();
- space = rps;
- valid = false;
- }
-
- /**
- * Create a (zeroed) table.
- */
- public final void acquireTable() {
- base = space.acquire(Conversions.bytesToPages(size));
- VM.memory.zero(base, size);
- valid = true;
- }
-
- /**
- * Drop the table (after collection).
- */
- public final void releaseTable() {
- space.release(base);
- valid = false;
- }
-
- /**
- * @return True if this table has backing data and is ready for use.
- */
- public final boolean isValid() {
- return valid;
- }
-
- /**
- * Retrieve a pointer to the entry for the given object, or zero if one
- * does not exist, unless create is passed.<p>
- *
- * If create is true, the return is guaranteed to be non-null.
- *
- * @param key The key used to lookup.
- * @param create Create a new entry if not found.
- * @return A pointer to the reference or null.
- */
- @Inline
- public final Address getEntry(Word key, boolean create) {
- int startIndex = computeHash(key);
- int index = startIndex;
- Word curAddress;
- Address entry;
- do {
- entry = getEntry(index);
- curAddress = entry.loadWord(KEY_OFFSET);
- index = (index + 1) & mask.toInt();
- } while(curAddress.NE(key) &&
- !curAddress.isZero() &&
- index != startIndex);
-
- if (index == startIndex) {
- VM.assertions.fail("No room left in table!");
- }
-
- if (curAddress.isZero()) {
- if (!create) return Address.zero();
- entry.store(key, KEY_OFFSET);
- }
-
- return entry;
- }
-
- /**
- * Compute the hashtable index for a given object.
- *
- * @param key The key.
- * @return The index.
- */
- @Inline
- private int computeHash(Word key) {
- return key.rshl(HASH_SHIFT).and(mask).toInt();
- }
-
- /**
- * Return the address of a specified entry in the table.
- *
- * @param index The index of the entry.
- * @return An address to the entry.
- */
- @Inline
- private Address getEntry(int index) {
- return base.plus(Extent.fromIntZeroExtend(index * entrySize.toInt()));
- }
-
- /**
- * Does the passed object have an entry in the table?
- *
- * @param key The key to find an entry for
- * @return True if there is an entry for that object.
- */
- public final boolean contains(Word key) {
- return !getEntry(key, false).isZero();
- }
-
- /**
- * @return The first non-zero element in the table, or null if
- * the table is empty.
- */
- public final Address getFirst() {
- return getNext(base.minus(entrySize));
- }
-
- /**
- * The next element in the table after the passed entry, or
- * null if it is the last entry.
- *
- * @param curr The object to look for the next entry from.
- * @return The next entry or null.
- */
- public final Address getNext(Address curr) {
- Address entry = curr.plus(entrySize);
- while (entry.LT(base.plus(size))) {
- if (!entry.loadWord().isZero()) return entry;
- entry = entry.plus(entrySize);
- }
- return Address.zero();
- }
-
- /**
- * Given an address of an entry, return a pointer to the payload.
- *
- * @param entry The entry
- * @return The object reference.
- */
- public static Address getPayloadAddress(Address entry) {
- return entry.plus(DATA_OFFSET);
- }
-
- /**
- * Given a key, return a pointer to the payload.
- *
- * @param key The key
- * @return The object reference.
- */
- public final Address getPayloadAddress(Word key) {
- Address entry = getEntry(key, false);
- if (entry.isZero()) return Address.zero();
-
- return entry.plus(DATA_OFFSET);
- }
-
-
- /**
- * Return the key for a given entry.
- *
- * @param entry The entry.
- * @return The key.
- */
- public static Word getKey(Address entry) {
- return entry.loadWord(KEY_OFFSET);
- }
-
- /**
- * Update the key for a given entry. This operation is not
- * safe without rehashing
- *
- * @param entry The entry to update.
- * @param key The new key.
- */
- public static void replaceKey(Address entry, Word key) {
- entry.store(key, KEY_OFFSET);
- }
-
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/utility/Synchronize.java b/vmkit/mmtk/java/src/org/mmtk/utility/Synchronize.java
deleted file mode 100644
index c613f76..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/utility/Synchronize.java
+++ /dev/null
@@ -1,22 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.utility;
-
-import org.vmmagic.pragma.*;
-
-/*
- */
-@Uninterruptible public class Synchronize{
-
-
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/utility/TraceGenerator.java b/vmkit/mmtk/java/src/org/mmtk/utility/TraceGenerator.java
deleted file mode 100644
index dbcc424..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/utility/TraceGenerator.java
+++ /dev/null
@@ -1,410 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.utility;
-
-import org.mmtk.plan.Plan;
-import org.mmtk.plan.semispace.gctrace.GCTrace;
-import org.mmtk.plan.TraceLocal;
-import org.mmtk.policy.Space;
-import org.mmtk.utility.deque.*;
-import org.mmtk.utility.options.Options;
-import org.mmtk.utility.options.TraceRate;
-
-import org.mmtk.vm.VM;
-import org.mmtk.vm.Collection;
-
-import org.vmmagic.pragma.*;
-import org.vmmagic.unboxed.*;
-
-/**
- * Class that supports scanning Objects and Arrays for references
- * during tracing, handling those references, and computing death times
- */
-@Uninterruptible public final class TraceGenerator
- implements Constants, TracingConstants {
-
-
- /***********************************************************************
- *
- * Class variables
- */
-
- /* Type of lifetime analysis to be used */
- public static final boolean MERLIN_ANALYSIS = true;
-
- /* include the notion of build-time allocation to our list of allocators */
- private static final int ALLOC_BOOT = GCTrace.ALLOCATORS;
- private static final int ALLOCATORS = ALLOC_BOOT + 1;
-
- /* Fields for tracing */
- private static SortTODSharedDeque tracePool; // Buffers to hold raw trace
- private static TraceBuffer trace;
- private static boolean traceBusy; // If we are building the trace
- private static Word lastGC; // Last time GC was performed
- private static ObjectReferenceArray objectLinks; // Lists of active objs
-
- /* Fields needed for Merlin lifetime analysis */
- private static SortTODSharedDeque workListPool; // Holds objs to process
- private static SortTODObjectReferenceStack worklist; // Objs to process
- private static Word agePropagate; // Death time propagating
-
- static {
- traceBusy = false;
- lastGC = Word.fromIntZeroExtend(4);
- Options.traceRate = new TraceRate();
- }
-
-
- /***********************************************************************
- *
- * Public analysis methods
- */
-
- /**
- * This is called at "build-time" and passes the necessary build image
- * objects to the trace processor.
- *
- * @param worklist_ The dequeue that serves as the worklist for
- * death time propagation
- * @param trace_ The dequeue used to store and then output the trace
- */
- @Interruptible
- public static void init(SortTODSharedDeque worklist_,
- SortTODSharedDeque trace_) {
- /* Objects are only needed for merlin tracing */
- if (MERLIN_ANALYSIS) {
- workListPool = worklist_;
- worklist = new SortTODObjectReferenceStack(workListPool);
- }
-
- /* Trace objects */
- tracePool = trace_;
- trace = new TraceBuffer(tracePool);
- objectLinks = ObjectReferenceArray.create(Space.MAX_SPACES);
- }
-
- /**
- * This is called immediately before Jikes terminates. It will perform
- * any death time processing that the analysis requires and then output
- * any remaining information in the trace buffer.
- *
- * @param value The integer value for the reason Jikes is terminating
- */
- public static void notifyExit(int value) {
- if (MERLIN_ANALYSIS)
- findDeaths();
- trace.process();
- }
-
- /**
- * Add a newly allocated object into the linked list of objects in a region.
- * This is typically called after each object allocation.
- *
- * @param ref The address of the object to be added to the linked list
- * @param linkSpace The region to which the object should be added
- */
- public static void addTraceObject(ObjectReference ref, int linkSpace) {
- VM.traceInterface.setLink(ref, objectLinks.get(linkSpace));
- objectLinks.set(linkSpace, ref);
- }
-
- /**
- * Do the work necessary following each garbage collection. This HAS to be
- * called after EACH collection.
- */
- public static void postCollection() {
- /* Find and output the object deaths */
- traceBusy = true;
- findDeaths();
- traceBusy = false;
- trace.process();
- }
-
-
- /***********************************************************************
- *
- * Trace generation code
- */
-
- /**
- * Add the information in the bootImage to the trace. This should be
- * called before any allocations and pointer updates have occured.
- *
- * @param bootStart The address at which the bootimage starts
- */
- public static void boot(Address bootStart) {
- Word nextOID = VM.traceInterface.getOID();
- ObjectReference trav = VM.traceInterface.getBootImageLink().plus(bootStart.toWord().toOffset()).toObjectReference();
- objectLinks.set(ALLOC_BOOT, trav);
- /* Loop through all the objects within boot image */
- while (!trav.isNull()) {
- ObjectReference next = VM.traceInterface.getLink(trav);
- Word thisOID = VM.traceInterface.getOID(trav);
- /* Add the boot image object to the trace. */
- trace.push(TRACE_BOOT_ALLOC);
- trace.push(thisOID);
- trace.push(nextOID.minus(thisOID).lsh(LOG_BYTES_IN_ADDRESS));
- nextOID = thisOID;
- /* Move to the next object & adjust for starting address of
- the bootImage */
- if (!next.isNull()) {
- next = next.toAddress().plus(bootStart.toWord().toOffset()).toObjectReference();
- VM.traceInterface.setLink(trav, next);
- }
- trav = next;
- }
- }
-
- /**
- * Do any tracing work required at each a pointer store operation. This
- * will add the pointer store to the trace buffer and, when Merlin lifetime
- * analysis is being used, performs the necessary timestamping.
- *
- * @param isScalar If this is a pointer store to a scalar object
- * @param src The address of the source object
- * @param slot The address within <code>src</code> into which
- * <code>tgt</code> will be stored
- * @param tgt The target of the pointer store
- */
- @NoInline
- public static void processPointerUpdate(boolean isScalar,
- ObjectReference src,
- Address slot, ObjectReference tgt) {
- // The trace can be busy only if this is a pointer update as a result of
- // the garbage collection needed by tracing. For the moment, we will
- // not report these updates.
- if (!traceBusy) {
- /* Process the old target potentially becoming unreachable when needed. */
- if (MERLIN_ANALYSIS) {
- ObjectReference oldTgt = slot.loadObjectReference();
- if (!oldTgt.isNull())
- VM.traceInterface.updateDeathTime(oldTgt);
- }
-
- traceBusy = true;
- /* Add the pointer store to the trace */
- Offset traceOffset = VM.traceInterface.adjustSlotOffset(isScalar, src, slot);
- if (isScalar)
- trace.push(TRACE_FIELD_SET);
- else
- trace.push(TRACE_ARRAY_SET);
- trace.push(VM.traceInterface.getOID(src));
- trace.push(traceOffset.toWord());
- if (tgt.isNull())
- trace.push(Word.zero());
- else
- trace.push(VM.traceInterface.getOID(tgt));
- traceBusy = false;
- }
- }
-
- /**
- * Do any tracing work required at each object allocation. This will add the
- * object allocation to the trace buffer, triggers the necessary collection
- * work at exact allocations, and output the data in the trace buffer.
- *
- * @param ref The address of the object just allocated.
- * @param typeRef the type reference for the instance being created
- * @param bytes The size of the object being allocated
- */
- @LogicallyUninterruptible
- @NoInline
- public static void traceAlloc(boolean isImmortal, ObjectReference ref,
- ObjectReference typeRef, int bytes) {
- boolean gcAllowed = VM.traceInterface.gcEnabled() && Plan.isInitialized() && !Plan.gcInProgress();
- /* Test if it is time/possible for an exact allocation. */
- Word oid = VM.traceInterface.getOID(ref);
- Word allocType;
- if (gcAllowed && (oid.GE(lastGC.plus(Word.fromIntZeroExtend(Options.traceRate.getValue())))))
- allocType = TRACE_EXACT_ALLOC;
- else {
- allocType = TRACE_ALLOC;
- }
- /* Add the allocation into the trace. */
- traceBusy = true;
- /* When legally permissible, add the record to the trace buffer */
- if (MERLIN_ANALYSIS) {
- Address fp = (TraceBuffer.OMIT_ALLOCS) ? Address.zero() : VM.traceInterface.skipOwnFramesAndDump(typeRef);
-
- if (isImmortal && allocType.EQ(TRACE_EXACT_ALLOC))
- trace.push(TRACE_EXACT_IMMORTAL_ALLOC);
- else if (isImmortal)
- trace.push(TRACE_IMMORTAL_ALLOC);
- else
- trace.push(allocType);
- trace.push(VM.traceInterface.getOID(ref));
- trace.push(Word.fromIntZeroExtend(bytes - VM.traceInterface.getHeaderSize()));
- trace.push(fp.toWord());
- trace.push(Word.zero()); /* Magic.getThreadId() */
- trace.push(TRACE_TIB_SET);
- trace.push(VM.traceInterface.getOID(ref));
- trace.push(VM.traceInterface.getOID(typeRef));
- }
- /* Perform the necessary work for death times. */
- if (allocType.EQ(TRACE_EXACT_ALLOC)) {
- if (MERLIN_ANALYSIS) {
- lastGC = VM.traceInterface.getOID(ref);
- VM.traceInterface.updateTime(lastGC);
- VM.collection.triggerCollection(Collection.INTERNAL_GC_TRIGGER);
- } else {
- VM.collection.triggerCollection(Collection.RESOURCE_GC_TRIGGER);
- lastGC = VM.traceInterface.getOID(ref);
- }
- }
- /* Add the allocation record to the buffer if we have not yet done so. */
- if (!MERLIN_ANALYSIS) {
- Address fp = (TraceBuffer.OMIT_ALLOCS) ? Address.zero() : VM.traceInterface.skipOwnFramesAndDump(typeRef);
- if (isImmortal && allocType.EQ(TRACE_EXACT_ALLOC))
- trace.push(TRACE_EXACT_IMMORTAL_ALLOC);
- else if (isImmortal)
- trace.push(TRACE_IMMORTAL_ALLOC);
- else
- trace.push(allocType);
- trace.push(VM.traceInterface.getOID(ref));
- trace.push(Word.fromIntZeroExtend(bytes - VM.traceInterface.getHeaderSize()));
- trace.push(fp.toWord());
- trace.push(Word.zero()); /* Magic.getThreadId() */
- trace.push(TRACE_TIB_SET);
- trace.push(VM.traceInterface.getOID(ref));
- trace.push(VM.traceInterface.getOID(typeRef));
- }
- trace.process();
- traceBusy = false;
- }
-
- /***********************************************************************
- *
- * Merlin lifetime analysis methods
- */
-
- /**
- * This computes and adds to the trace buffer the unreachable time for
- * all of the objects that are _provably_ unreachable. This method
- * should be called after garbage collection (but before the space has
- * been reclaimed) and at program termination.
- */
- private static void findDeaths() {
- /* Only the merlin analysis needs to compute death times */
- if (MERLIN_ANALYSIS) {
- /* Start with an empty stack. */
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(worklist.isEmpty());
- /* Scan the linked list of objects within each region */
- for (int allocator = 0; allocator < ALLOCATORS; allocator++) {
- ObjectReference thisRef = objectLinks.get(allocator);
- /* Start at the top of each linked list */
- while (!thisRef.isNull()) {
- /* Add the unreachable objects onto the worklist. */
- if (!getTraceLocal().isReachable(thisRef))
- worklist.push(thisRef);
- thisRef = VM.traceInterface.getLink(thisRef);
- }
- }
- /* Sort the objects on the worklist by their timestamp */
- if (!worklist.isEmpty())
- worklist.sort();
- /* Now compute the death times. */
- computeTransitiveClosure();
- }
- /* Output the death times for each object */
- for (int allocator = 0; allocator < ALLOCATORS; allocator++) {
- ObjectReference thisRef = objectLinks.get(allocator);
- ObjectReference prevRef = ObjectReference.nullReference(); // the last live object seen
- while (!thisRef.isNull()) {
- ObjectReference nextRef = VM.traceInterface.getLink(thisRef);
- /* Maintain reachable objects on the linked list of allocated objects */
- if (getTraceLocal().isReachable(thisRef)) {
- thisRef = getTraceLocal().getForwardedReference(thisRef);
- VM.traceInterface.setLink(thisRef, prevRef);
- prevRef = thisRef;
- } else {
- /* For brute force lifetime analysis, objects become
- unreachable "now" */
- Word deadTime;
- if (MERLIN_ANALYSIS)
- deadTime = VM.traceInterface.getDeathTime(thisRef);
- else
- deadTime = lastGC;
- /* Add the death record to the trace for unreachable objects. */
- trace.push(TRACE_DEATH);
- trace.push(VM.traceInterface.getOID(thisRef));
- trace.push(deadTime);
- }
- thisRef = nextRef;
- }
- /* Purge the list of unreachable objects... */
- objectLinks.set(allocator, prevRef);
- }
- }
-
- /**
- * This method is called for each root-referenced object at every Merlin
- * root enumeration. The method will update the death time of the parameter
- * to the current trace time.
- *
- * @param obj The root-referenced object
- */
- public static void rootEnumerate(ObjectReference obj) {
- VM.traceInterface.updateDeathTime(obj);
- }
-
- /**
- * This propagates the death time being computed to the object passed as an
- * address. If we find the unreachable time for the parameter, it will be
- * pushed on to the processing stack.
- *
- * @param ref The address of the object to examine
- */
- public static void propagateDeathTime(ObjectReference ref) {
- /* If this death time is more accurate, set it. */
- if (VM.traceInterface.getDeathTime(ref).LT(agePropagate)) {
- /* If we should add the object for further processing. */
- if (!getTraceLocal().isReachable(ref)) {
- VM.traceInterface.setDeathTime(ref, agePropagate);
- worklist.push(ref);
- } else {
- VM.traceInterface.setDeathTime(getTraceLocal().getForwardedReference(ref), agePropagate);
- }
- }
- }
-
- /**
- * This finds all object death times by computing the (limited)
- * transitive closure of the dead objects. Death times are computed
- * as the latest reaching death time to an object.
- */
- private static void computeTransitiveClosure() {
- if (!worklist.isEmpty()) {
- /* The latest time an object can die. */
- agePropagate = Word.max();
- /* Process through the entire buffer. */
- ObjectReference ref = worklist.pop();
- while (!ref.isNull()) {
- Word currentAge = VM.traceInterface.getDeathTime(ref);
- /* This is a cheap and simple test to process objects only once. */
- if (currentAge.LE(agePropagate)) {
- /* Set the "new" dead age. */
- agePropagate = currentAge;
- /* Scan the object, pushing the survivors */
- VM.scanning.scanObject(getTraceLocal(), ref);
- }
- /* Get the next object to process */
- ref = worklist.pop();
- }
- }
- }
-
- private static TraceLocal getTraceLocal() {
- return VM.activePlan.collector().getCurrentTrace();
- }
-
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/utility/TracingConstants.java b/vmkit/mmtk/java/src/org/mmtk/utility/TracingConstants.java
deleted file mode 100644
index 10169e7..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/utility/TracingConstants.java
+++ /dev/null
@@ -1,41 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.utility;
-
-import org.vmmagic.unboxed.*;
-
-/**
- * The constants needed when storing events and then generating the trace.
- */
-public interface TracingConstants {
- Word TRACE_EXACT_ALLOC = Word.zero();
- Word TRACE_BOOT_ALLOC = Word.one().lsh(0);
- Word TRACE_ALLOC = Word.one().lsh(1);
- Word TRACE_DEATH = Word.one().lsh(2);
- Word TRACE_FIELD_SET = Word.one().lsh(3);
- Word TRACE_ARRAY_SET = Word.one().lsh(4);
- Word TRACE_TIB_SET = Word.one().lsh(5);
- Word TRACE_STATIC_SET = Word.one().lsh(6);
- Word TRACE_BOOTSTART = Word.one().lsh(7);
- Word TRACE_BOOTEND = Word.one().lsh(8);
- Word TRACE_GCSTART = Word.one().lsh(9);
- Word TRACE_GCEND = Word.one().lsh(10);
- Word TRACE_GCROOT = Word.one().lsh(11);
- Word TRACE_GCBAR = Word.one().lsh(12);
- Word TRACE_THREAD_SWITCH = Word.one().lsh(13);
- Word TRACE_STACKDELTA = Word.one().lsh(14);
- Word TRACE_ROOTPTR = Word.one().lsh(15);
- Word TRACE_EXACT_IMMORTAL_ALLOC = Word.one().lsh(16);
- Word TRACE_IMMORTAL_ALLOC = Word.one().lsh(17);
-}
-
diff --git a/vmkit/mmtk/java/src/org/mmtk/utility/Treadmill.java b/vmkit/mmtk/java/src/org/mmtk/utility/Treadmill.java
deleted file mode 100644
index e4081e1..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/utility/Treadmill.java
+++ /dev/null
@@ -1,187 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.utility;
-
-import org.mmtk.utility.gcspy.drivers.TreadmillDriver;
-
-import org.vmmagic.unboxed.*;
-import org.vmmagic.pragma.*;
-
-/**
- * FIXME The DoublyLinkedList class, upon which this depends, must be
- * re-written as it makes the assumption that the implementation
- * language (Java) and the language being implemented are the same.
- * This is true in the case of Jikes RVM, but it is not true for any
- * VM implementing a language other than Java.
- *
- * Each instance of this class is a doubly-linked list, in which
- * each item or node is a piece of memory. The first two words of each node
- * contains the forward and backward links. The third word contains
- * the treadmill. The remaining portion is the payload.
- *
- * The treadmill object itself must not be moved.
- *
- * Access to the instances may be synchronized depending on the constructor argument.
- */
-@Uninterruptible
-public final class Treadmill implements Constants {
-
- /****************************************************************************
- *
- * Instance variables
- */
- private DoublyLinkedList fromSpace;
- private DoublyLinkedList toSpace;
- private DoublyLinkedList collectNursery;
- private DoublyLinkedList allocNursery;
-
- /****************************************************************************
- *
- * Initialization
- */
-
- /**
- * Constructor
- */
- public Treadmill(int granularity, boolean shared) {
- fromSpace = new DoublyLinkedList(granularity, shared);
- toSpace = new DoublyLinkedList(granularity, shared);
- allocNursery = new DoublyLinkedList(granularity, shared);
- collectNursery = new DoublyLinkedList(granularity, shared);
- }
-
- /**
- * Add a node to the treadmill. This is usually performed on allocation.
- */
- @Inline
- public void addToTreadmill(Address node, boolean nursery) {
- if (nursery)
- allocNursery.add(node);
- else
- toSpace.add(node);
- }
-
- /**
- * Remove a node from the nursery list.
- */
- @Inline
- public Address popNursery() {
- return collectNursery.pop();
- }
-
- /**
- * Remove a node from the mature list.
- */
- @Inline
- public Address pop() {
- return fromSpace.pop();
- }
-
- /**
- * Copy a node (during gc tracing).
- */
- @Inline
- public void copy(Address node, boolean isInNursery) {
- if (isInNursery) {
- collectNursery.remove(node);
- } else {
- fromSpace.remove(node);
- }
- toSpace.add(node);
- }
-
- /**
- * Is the to-space empty?
- */
- @Inline
- public boolean toSpaceEmpty() {
- return toSpace.isEmpty();
- }
-
- /**
- * Is the from-space empty?
- */
- @Inline
- public boolean fromSpaceEmpty() {
- return fromSpace.isEmpty();
- }
-
- /**
- * Is the nursery empty?
- */
- @Inline
- public boolean nurseryEmpty() {
- return collectNursery.isEmpty();
- }
-
- /**
- * Flip the roles of the spaces in preparation for a collection.
- */
- public void flip(boolean fullHeap) {
- DoublyLinkedList tmp = allocNursery;
- allocNursery = collectNursery;
- collectNursery = tmp;
- if (fullHeap) {
- tmp = fromSpace;
- fromSpace = toSpace;
- toSpace = tmp;
- }
- }
-
- /****************************************************************************
- *
- * Misc header manipulation
- */
-
- @Inline
- public static int headerSize() {
- return DoublyLinkedList.headerSize();
- }
-
- @Inline
- public static Address nodeToPayload(Address payload) {
- return DoublyLinkedList.nodeToPayload(payload);
- }
-
- @Inline
- public static Address midPayloadToNode(Address payload) {
- return DoublyLinkedList.midPayloadToNode(payload);
- }
-
- /****************************************************************************
- *
- * GCSpy
- */
-
- /**
- * Gather data for GCSpy from the nursery
- * @param event the gc event
- * @param tmDriver the GCSpy space driver
- */
- public void gcspyGatherData(int event, TreadmillDriver tmDriver) {
- this.allocNursery.gcspyGatherData(tmDriver);
- }
-
- /**
- * Gather data for GCSpy
- * @param event the gc event
- * @param tmDriver the GCSpy space driver
- * @param tospace gather from tospace?
- */
- public void gcspyGatherData(int event, TreadmillDriver tmDriver, boolean tospace) {
- if (tospace)
- toSpace.gcspyGatherData(tmDriver);
- else
- fromSpace.gcspyGatherData(tmDriver);
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/utility/alloc/Allocator.java b/vmkit/mmtk/java/src/org/mmtk/utility/alloc/Allocator.java
deleted file mode 100644
index 404ed86..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/utility/alloc/Allocator.java
+++ /dev/null
@@ -1,263 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.utility.alloc;
-
-import org.mmtk.plan.Plan;
-import org.mmtk.policy.Space;
-import org.mmtk.utility.*;
-import org.mmtk.utility.statistics.*;
-
-import org.mmtk.vm.VM;
-
-import org.vmmagic.unboxed.*;
-import org.vmmagic.pragma.*;
-
-/**
- * This abstract base class provides the basis for processor-local
- * allocation. The key functionality provided is the retry mechanism
- * that is necessary to correctly handle the fact that a "slow-path"
- * allocation can cause a GC which violate the uninterruptability assumption.
- * This results in the thread being moved to a different processor so that
- * the allocator object it is using is not actually the one for the processor
- * it is running on.
- *
- * This class also includes functionality to assist allocators with
- * ensuring that requests are aligned according to requests.
- *
- * Failing to handle this properly will lead to very hard to trace bugs
- * where the allocation that caused a GC or allocations immediately following
- * GC are run incorrectly.
- */
-@Uninterruptible public abstract class Allocator implements Constants {
-
- /**
- * Return the space this allocator is currently bound to.
- *
- * @return The Space.
- */
- protected abstract Space getSpace();
-
- /**
- * Aligns up an allocation request. The allocation request accepts a
- * region, that must be at least particle aligned, an alignment
- * request (some power of two number of particles) and an offset (a
- * number of particles). There is also a knownAlignment parameter to
- * allow a more optimised check when the particular allocator in use
- * always aligns at a coarser grain than individual particles, such
- * as some free lists.
- *
- * @param region The region to align up.
- * @param alignment The requested alignment
- * @param offset The offset from the alignment
- * @param knownAlignment The statically known minimum alignment.
- * @return The aligned up address.
- */
- @Inline
- public static Address alignAllocation(Address region, int alignment, int offset, int knownAlignment, boolean fillAlignmentGap) {
- if (VM.VERIFY_ASSERTIONS) {
- VM.assertions._assert(knownAlignment >= MIN_ALIGNMENT);
- VM.assertions._assert(MIN_ALIGNMENT >= BYTES_IN_INT);
- VM.assertions._assert(!(fillAlignmentGap && region.isZero()));
- VM.assertions._assert(alignment <= MAX_ALIGNMENT);
- VM.assertions._assert(offset >= 0);
- VM.assertions._assert(region.toWord().and(Word.fromIntSignExtend(MIN_ALIGNMENT-1)).isZero());
- VM.assertions._assert((alignment & (MIN_ALIGNMENT - 1)) == 0);
- VM.assertions._assert((offset & (MIN_ALIGNMENT - 1)) == 0);
- }
-
- // No alignment ever required.
- if (alignment <= knownAlignment || MAX_ALIGNMENT <= MIN_ALIGNMENT)
- return region;
-
- // May require an alignment
- Word mask = Word.fromIntSignExtend(alignment - 1);
- Word negOff = Word.fromIntSignExtend(-offset);
- Offset delta = negOff.minus(region.toWord()).and(mask).toOffset();
-
- if (fillAlignmentGap && ALIGNMENT_VALUE != 0) {
- if ((MAX_ALIGNMENT - MIN_ALIGNMENT) == BYTES_IN_WORD) {
- // At most a single hole
- if (delta.toInt() == (BYTES_IN_WORD)) {
- region.store(Word.fromIntSignExtend(ALIGNMENT_VALUE));
- region = region.plus(delta);
- return region;
- }
- } else {
- while (delta.toInt() >= (BYTES_IN_WORD)) {
- region.store(Word.fromIntSignExtend(ALIGNMENT_VALUE));
- region = region.plus(BYTES_IN_WORD);
- delta = delta.minus(BYTES_IN_WORD);
- }
- }
- }
-
- return region.plus(delta);
- }
-
- /**
- * Fill the specified region with the alignment value.
- *
- * @param start The start of the region.
- * @param end A pointer past the end of the region.
- */
- @Inline
- public static void fillAlignmentGap(Address start, Address end) {
- if ((MAX_ALIGNMENT - MIN_ALIGNMENT) == BYTES_IN_INT) {
- // At most a single hole
- if (!end.diff(start).isZero()) {
- start.store(ALIGNMENT_VALUE);
- }
- } else {
- while (start.LT(end)) {
- start.store(ALIGNMENT_VALUE);
- start = start.plus(BYTES_IN_INT);
- }
- }
- }
-
- /**
- * Aligns up an allocation request. The allocation request accepts a
- * region, that must be at least particle aligned, an alignment
- * request (some power of two number of particles) and an offset (a
- * number of particles).
- *
- * @param region The region to align up.
- * @param alignment The requested alignment
- * @param offset The offset from the alignment
- * @return The aligned up address.
- */
- @Inline
- public static Address alignAllocation(Address region, int alignment, int offset) {
- return alignAllocation(region, alignment, offset, MIN_ALIGNMENT, true);
- }
-
- /**
- * Aligns up an allocation request. The allocation request accepts a
- * region, that must be at least particle aligned, an alignment
- * request (some power of two number of particles) and an offset (a
- * number of particles).
- *
- * @param region The region to align up.
- * @param alignment The requested alignment
- * @param offset The offset from the alignment
- * @return The aligned up address.
- */
- @Inline
- public static Address alignAllocationNoFill(Address region, int alignment, int offset) {
- return alignAllocation(region, alignment, offset, MIN_ALIGNMENT, false);
- }
-
- /**
- * This method calculates the minimum size that will guarantee the allocation
- * of a specified number of bytes at the specified alignment.
- *
- * @param size The number of bytes (not aligned).
- * @param alignment The requested alignment (some factor of 2).
- */
- @Inline
- public static int getMaximumAlignedSize(int size, int alignment) {
- return getMaximumAlignedSize(size, alignment, MIN_ALIGNMENT);
- }
-
- /**
- * This method calculates the minimum size that will guarantee the allocation
- * of a specified number of bytes at the specified alignment.
- *
- * @param size The number of bytes (not aligned).
- * @param alignment The requested alignment (some factor of 2).
- * @param knownAlignment The known minimum alignment. Specifically for use in
- * allocators that enforce greater than particle alignment. It is a <b>precondition</b>
- * that size is aligned to knownAlignment, and that knownAlignment >= MIN_ALGINMENT.
- */
- @Inline
- public static int getMaximumAlignedSize(int size, int alignment, int knownAlignment) {
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(size == Conversions.roundDown(size, knownAlignment));
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(knownAlignment >= MIN_ALIGNMENT);
-
- if (MAX_ALIGNMENT <= MIN_ALIGNMENT || alignment <= knownAlignment) {
- return size;
- } else {
- return size + alignment - knownAlignment;
- }
- }
-
- /**
- * Single slow path allocation attempt. This is called by allocSlow.
- *
- * @param bytes The size of the allocation request
- * @param alignment The required alignment
- * @param offset The alignment offset
- * @return The start address of the region, or zero if allocation fails
- */
- protected abstract Address allocSlowOnce(int bytes, int alignment, int offset);
-
- /**
- * <b>Out-of-line</b> slow path allocation. This method forces slow path
- * allocation to be out of line (typically desirable, but not when the
- * calling context is already explicitly out-of-line).
- *
- * @param bytes The size of the allocation request
- * @param alignment The required alignment
- * @param offset The alignment offset
- * @return The start address of the region, or zero if allocation fails
- */
- @NoInline
- public final Address allocSlow(int bytes, int alignment, int offset) {
- return allocSlowInline(bytes, alignment, offset);
- }
-
- /**
- * <b>Inline</b> slow path allocation. This method attempts allocSlowOnce
- * several times, and allows collection to occur, and ensures that execution
- * safely resumes by taking care of potential thread/mutator context affinity
- * changes. All allocators should use this as the trampoline for slow
- * path allocation.
- *
- * @param bytes The size of the allocation request
- * @param alignment The required alignment
- * @param offset The alignment offset
- * @return The start address of the region, or zero if allocation fails
- */
- @Inline
- public final Address allocSlowInline(int bytes, int alignment, int offset) {
- int gcCountStart = Stats.gcCount();
- Allocator current = this;
- Space space = current.getSpace();
- for (int i = 0; i < Plan.MAX_COLLECTION_ATTEMPTS; i++) {
- Address result = current.allocSlowOnce(bytes, alignment, offset);
- if (!result.isZero()) {
- return result;
- }
- if (!Plan.gcInProgress()) {
- /* This is in case a GC occurs, and our mutator context is stale.
- * In some VMs the scheduler can change the affinity between the
- * current thread and the mutator context. This is possible for
- * VMs that dynamically multiplex Java threads onto multiple mutator
- * contexts, */
- current = VM.activePlan.mutator().getAllocatorFromSpace(space);
- }
- }
- Log.write("GC Error: Allocator.allocSlow failed on request of ");
- Log.write(bytes);
- Log.write(" on space ");
- Log.writeln(space.getName());
- Log.write("gcCountStart = ");
- Log.writeln(gcCountStart);
- Log.write("gcCount (now) = ");
- Log.writeln(Stats.gcCount());
- Space.printUsageMB();
- VM.assertions.fail("Allocation Failed!");
- /* NOTREACHED */
- return Address.zero();
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/utility/alloc/BlockAllocator.java b/vmkit/mmtk/java/src/org/mmtk/utility/alloc/BlockAllocator.java
deleted file mode 100644
index 97dcdd1..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/utility/alloc/BlockAllocator.java
+++ /dev/null
@@ -1,335 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.utility.alloc;
-
-import org.mmtk.policy.Space;
-import org.mmtk.utility.*;
-
-import org.mmtk.vm.VM;
-
-import org.vmmagic.pragma.*;
-import org.vmmagic.unboxed.*;
-
-/**
- * This class implements "block" data structures of various sizes.<p>
- *
- * Blocks are a non-shared (thread-local) coarse-grained unit of
- * storage. Blocks are available in power-of-two sizes.
- *
- * Virtual memory space is taken from a VM resource, and pages
- * consumed by blocks are accounted for by a memory resource.
- */
-@Uninterruptible
-public final class BlockAllocator implements Constants {
- /****************************************************************************
- *
- * Class variables
- */
-
- // block freelist
- public static final int LOG_MIN_BLOCK = 12; // 4K bytes
- public static final int LOG_MAX_BLOCK = 15; // 32K bytes
- public static final byte MAX_BLOCK_SIZE_CLASS = LOG_MAX_BLOCK - LOG_MIN_BLOCK;
- public static final int BLOCK_SIZE_CLASSES = MAX_BLOCK_SIZE_CLASS + 1;
-
- // metadata
- private static final Offset NEXT_OFFSET = Offset.zero();
- private static final Offset BMD_OFFSET = NEXT_OFFSET.plus(BYTES_IN_ADDRESS);
- private static final Offset CSC_OFFSET = BMD_OFFSET.plus(1);
- private static final Offset IU_OFFSET = CSC_OFFSET.plus(1);
- private static final Offset FL_META_OFFSET = IU_OFFSET.plus(BYTES_IN_SHORT);
- private static final byte BLOCK_SC_MASK = 0xf; // lower 4 bits
- private static final int BLOCK_PAGE_OFFSET_SHIFT = 4; // higher 4 bits
- private static final int MAX_BLOCK_PAGE_OFFSET = (1<<4)-1; // 4 bits
- private static final int LOG_BYTES_IN_BLOCK_META = LOG_BYTES_IN_ADDRESS + 2;
- private static final int LOG_BYTE_COVERAGE = LOG_MIN_BLOCK - LOG_BYTES_IN_BLOCK_META;
-
- public static final int META_DATA_BYTES_PER_REGION = 1 << (EmbeddedMetaData.LOG_BYTES_IN_REGION - LOG_BYTE_COVERAGE);
- public static final Extent META_DATA_EXTENT = Extent.fromIntSignExtend(META_DATA_BYTES_PER_REGION);
-
- /****************************************************************************
- *
- * Allocation & freeing
- */
-
- /**
- * Allocate a block, returning the address of the first usable byte
- * in the block.
- *
- * @param blockSizeClass The size class for the block to be allocated.
- * @return The address of the first usable byte in the block, or
- * zero on failure.
- */
- public static Address alloc(Space space, int blockSizeClass) {
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert((blockSizeClass >= 0) && (blockSizeClass <= MAX_BLOCK_SIZE_CLASS));
- int pages = pagesForSizeClass(blockSizeClass);
- Address result = space.acquire(pages);
- if (!result.isZero()) {
- setBlkSizeMetaData(result, (byte) blockSizeClass);
- }
- return result;
- }
-
- /**
- * Free a block. If the block is a sub-page block and the page is
- * not completely free, then the block is added to the free list.
- * Otherwise the block is returned to the virtual memory resource.
- *
- * @param block The address of the block to be freed
- */
- public static void free(Space space, Address block) {
- space.release(block);
- }
-
- /**
- * Return the size in bytes of a block of a given size class
- *
- * @param blockSizeClass The size class in question
- * @return The size in bytes of a block of this size class
- */
- @Inline
- public static int blockSize(int blockSizeClass) {
- return 1 << (LOG_MIN_BLOCK + blockSizeClass);
- }
-
- /**
- * Return the number of pages required when allocating space for
- * this size class.
- *
- * @param blockSizeClass The size class in question
- * @return The number of pages required when allocating a block (or
- * blocks) of this size class.
- */
- @Inline
- private static int pagesForSizeClass(int blockSizeClass) {
- return 1 << (LOG_MIN_BLOCK + blockSizeClass - LOG_BYTES_IN_PAGE);
- }
-
- /****************************************************************************
- *
- * Block meta-data manipulation
- */
-
- /**
- * Set the <i>block size class</i> meta data field for a given
- * address (all blocks on a given page are homogeneous with respect
- * to block size class).
- *
- * @param block The address of interest
- * @param sc The value to which this field is to be set
- */
- @Inline
- private static void setBlkSizeMetaData(Address block, byte sc) {
- if (VM.VERIFY_ASSERTIONS) {
- VM.assertions._assert(block.EQ(Conversions.pageAlign(block)));
- VM.assertions._assert(pagesForSizeClass(sc) - 1 <= MAX_BLOCK_PAGE_OFFSET);
- }
- Address address = block;
- for (int i = 0; i < pagesForSizeClass(sc); i++) {
- byte value = (byte) ((i << BLOCK_PAGE_OFFSET_SHIFT) | sc);
- getMetaAddress(address).store(value, BMD_OFFSET);
- if (VM.VERIFY_ASSERTIONS) {
- VM.assertions._assert(getBlkStart(address).EQ(block));
- VM.assertions._assert(getBlkSizeClass(address) == sc);
- }
- address = address.plus(1<<VM.LOG_BYTES_IN_PAGE);
- }
- }
-
- /**
- * Get the <i>block size class</i> meta data field for a given page
- * (all blocks on a given page are homogeneous with respect to block
- * size class).
- *
- * @param address The address of interest
- * @return The size class field for the block containing the given address
- */
- @Inline
- private static byte getBlkSizeClass(Address address) {
- address = Conversions.pageAlign(address);
- byte rtn = (byte) (getMetaAddress(address).loadByte(BMD_OFFSET) & BLOCK_SC_MASK);
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(rtn >= 0 && rtn <= MAX_BLOCK_SIZE_CLASS);
- return rtn;
- }
-
- /**
- * Get the <i>address of the start of a block size class</i> a given page
- * within the block.
- *
- * @param address The address of interest
- * @return The address of the block containing the address
- */
- @Inline
- public static Address getBlkStart(Address address) {
- address = Conversions.pageAlign(address);
- byte offset = (byte) (getMetaAddress(address).loadByte(BMD_OFFSET) >>> BLOCK_PAGE_OFFSET_SHIFT);
- return address.minus(offset<<LOG_BYTES_IN_PAGE);
- }
-
- /**
- * Set the <i>client size class</i> meta data field for a given
- * address (all blocks on a given page are homogeneous with respect
- * to block size class).
- *
- * @param block The address of interest
- * @param sc The value to which this field is to be set
- */
- @Inline
- public static void setAllClientSizeClass(Address block, int blocksc, byte sc) {
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(block.EQ(Conversions.pageAlign(block)));
- Address address = block;
- for (int i = 0; i < pagesForSizeClass(blocksc); i++) {
- getMetaAddress(address).store(sc, CSC_OFFSET);
- address = address.plus(1<<VM.LOG_BYTES_IN_PAGE);
- }
- }
-
- /**
- * Get the <i>client size class</i> meta data field for a given page
- * (all blocks on a given page are homogeneous with respect to block
- * size class).
- *
- * @param address The address of interest
- * @return The size class field for the block containing the given address
- */
- @Inline
- public static byte getClientSizeClass(Address address) {
- address = Conversions.pageAlign(address);
- byte rtn = getMetaAddress(address).loadByte(CSC_OFFSET);
- return rtn;
- }
-
- /**
- * Set the free list meta data field for a given address (this is
- * per-block meta data that is stored along with the block metadata
- * but not used by the block allocator).
- *
- * @param address The address of interest
- * @param value The value to which this field is to be set
- */
- @Inline
- public static void setFreeListMeta(Address address, Address value) {
- getMetaAddress(address).plus(FL_META_OFFSET).store(value);
- }
-
- /**
- * Get the free list meta data field for a given address (this is
- * per-block meta data that is stored along with the block metadata
- * but not used by the block allocator).
- *
- * @param address The address of interest
- * @return The free list meta data field for the block containing
- * the given address
- */
- @Inline
- public static Address getFreeListMeta(Address address) {
- return getMetaAddress(address).plus(FL_META_OFFSET).loadAddress();
- }
-
- /**
- * Set the <i>prev</i> meta data field for a given address
- *
- * @param address The address of interest
- * @param prev The value to which this field is to be set
- */
- @Inline
- public static void setNext(Address address, Address prev) {
- getMetaAddress(address, NEXT_OFFSET).store(prev);
- }
-
- /**
- * Get the <i>prev</i> meta data field for a given address
- *
- * @param address The address of interest
- * @return The prev field for the block containing the given address
- */
- @Inline
- public static Address getNext(Address address) {
- return getMetaAddress(address, NEXT_OFFSET).loadAddress();
- }
-
- /**
- * Get the address of some metadata given the address for which the
- * metadata is required and the offset into the metadata that is of
- * interest.
- *
- * @param address The address for which the metadata is required
- * @return The address of the specified meta data
- */
- @Inline
- private static Address getMetaAddress(Address address) {
- return getMetaAddress(address, Offset.zero());
- }
-
- /**
- * Get the address of some metadata given the address for which the
- * metadata is required and the offset into the metadata that is of
- * interest.
- *
- * @param address The address for which the metadata is required
- * @param offset The offset (in bytes) into the metadata block (eg
- * for the prev pointer, or next pointer)
- * @return The address of the specified meta data
- */
- @Inline
- private static Address getMetaAddress(Address address, Offset offset) {
- return EmbeddedMetaData.getMetaDataBase(address).plus(
- EmbeddedMetaData.getMetaDataOffset(address, LOG_BYTE_COVERAGE, LOG_BYTES_IN_BLOCK_META)).plus(offset);
- }
-
- /****************************************************************************
- *
- * Block marking
- */
-
- /**
- * Mark the metadata for this block.
- *
- * @param ref
- */
- @Inline
- public static void markBlockMeta(ObjectReference ref) {
- getMetaAddress(VM.objectModel.refToAddress(ref)).plus(FL_META_OFFSET).store(Word.one());
- }
-
- /**
- * Mark the metadata for this block.
- *
- * @param block The block address
- */
- @Inline
- public static void markBlockMeta(Address block) {
- getMetaAddress(block).plus(FL_META_OFFSET).store(Word.one());
- }
-
- /**
- * Return true if the metadata for this block was set.
- *
- * @param block The block address
- * @return value of the meta data.
- */
- @Inline
- public static boolean checkBlockMeta(Address block) {
- return getMetaAddress(block).plus(FL_META_OFFSET).loadWord().EQ(Word.one());
- }
-
- /**
- * Clear the metadata for this block
- *
- * @param block The block address
- */
- @Inline
- public static void clearBlockMeta(Address block) {
- getMetaAddress(block).plus(FL_META_OFFSET).store(Word.zero());
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/utility/alloc/BumpPointer.java b/vmkit/mmtk/java/src/org/mmtk/utility/alloc/BumpPointer.java
deleted file mode 100644
index e2c1210..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/utility/alloc/BumpPointer.java
+++ /dev/null
@@ -1,618 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.utility.alloc;
-
-import org.mmtk.policy.Space;
-import org.mmtk.utility.Constants;
-import org.mmtk.utility.Conversions;
-import org.mmtk.utility.Log;
-import org.mmtk.utility.gcspy.drivers.LinearSpaceDriver;
-import org.mmtk.vm.VM;
-import org.vmmagic.pragma.Inline;
-import org.vmmagic.pragma.NoInline;
-import org.vmmagic.pragma.Uninterruptible;
-import org.vmmagic.unboxed.Address;
-import org.vmmagic.unboxed.Extent;
-import org.vmmagic.unboxed.ObjectReference;
-import org.vmmagic.unboxed.Offset;
-import org.vmmagic.unboxed.Word;
-
-/**
- * This class implements a bump pointer allocator that allows linearly
- * scanning through the allocated objects. In order to achieve this in the
- * face of parallelism it maintains a header at a region (1 or more blocks)
- * granularity.
- *
- * Intra-block allocation is fast, requiring only a load, addition comparison
- * and store. If a block boundary is encountered the allocator will
- * request more memory (virtual and actual).
- *
- * In the current implementation the scanned objects maintain affinity
- * with the thread that allocated the objects in the region. In the future
- * it is anticipated that subclasses should be allowed to choose to improve
- * load balancing during the parallel scan.
- *
- * Each region is laid out as follows:
- *
- * +-------------+-------------+-------------+---------------
- * | Region End | Next Region | Data End | Data -->
- * +-------------+-------------+-------------+---------------
- *
- * The minimum region size is 32768 bytes, so the 3 or 4 word overhead is
- * less than 0.05% of all space.
- *
- * An intended enhancement is to facilitate a reallocation operation
- * where a second cursor is maintained over earlier regions (and at the
- * limit a lower location in the same region). This would be accompianied
- * with an alternative slow path that would allow reuse of empty regions.
- *
- * This class relies on the supporting virtual machine implementing the
- * getNextObject and related operations.
- */
-@Uninterruptible public class BumpPointer extends Allocator
- implements Constants {
-
- /****************************************************************************
- *
- * Class variables
- */
-
- // Block size defines slow path periodicity.
- private static final int LOG_DEFAULT_STEP_SIZE = 30; // 1G: let the external slow path dominate
- private static final int STEP_SIZE = 1<<(SUPPORT_CARD_SCANNING ? LOG_CARD_BYTES : LOG_DEFAULT_STEP_SIZE);
- protected static final int LOG_BLOCK_SIZE = LOG_BYTES_IN_PAGE + 3;
- protected static final Word BLOCK_MASK = Word.one().lsh(LOG_BLOCK_SIZE).minus(Word.one());
- private static final int BLOCK_SIZE = (1<<LOG_BLOCK_SIZE);
-
-
- // Offsets into header
- protected static final Offset REGION_LIMIT_OFFSET = Offset.zero();
- protected static final Offset NEXT_REGION_OFFSET = REGION_LIMIT_OFFSET.plus(BYTES_IN_ADDRESS);
- protected static final Offset DATA_END_OFFSET = NEXT_REGION_OFFSET.plus(BYTES_IN_ADDRESS);
-
- // Data must start particle-aligned.
- protected static final Offset DATA_START_OFFSET = alignAllocationNoFill(
- Address.zero().plus(DATA_END_OFFSET.plus(BYTES_IN_ADDRESS)),
- MIN_ALIGNMENT, 0).toWord().toOffset();
- protected static final Offset MAX_DATA_START_OFFSET = alignAllocationNoFill(
- Address.zero().plus(DATA_END_OFFSET.plus(BYTES_IN_ADDRESS)),
- MAX_ALIGNMENT, 0).toWord().toOffset();
-
- public static final int MINIMUM_DATA_SIZE = (1 << LOG_BLOCK_SIZE) - MAX_DATA_START_OFFSET.toInt();
-
- private static final boolean VERBOSE = false;
-
- /****************************************************************************
- *
- * Instance variables
- */
- protected Address cursor; // insertion point
- private Address internalLimit; // current internal slow-path sentinal for bump pointer
- private Address limit; // current external slow-path sentinal for bump pointer
- protected Space space; // space this bump pointer is associated with
- protected Address initialRegion; // first contiguous region
- protected final boolean allowScanning; // linear scanning is permitted if true
- protected Address region; // current contiguous region
-
-
- /**
- * Constructor.
- *
- * @param space The space to bump point into.
- * @param allowScanning Allow linear scanning of this region of memory.
- */
- protected BumpPointer(Space space, boolean allowScanning) {
- this.space = space;
- this.allowScanning = allowScanning;
- reset();
- }
-
- /**
- * Reset the allocator. Note that this does not reset the space.
- * This is must be done by the caller.
- */
- public final void reset() {
- cursor = Address.zero();
- limit = Address.zero();
- internalLimit = Address.zero();
- initialRegion = Address.zero();
- region = Address.zero();
- }
-
- /**
- * Re-associate this bump pointer with a different space. Also
- * reset the bump pointer so that it will use the new space
- * on the next call to <code>alloc</code>.
- *
- * @param space The space to associate the bump pointer with.
- */
- public final void rebind(Space space) {
- reset();
- this.space = space;
- }
-
- /**
- * Allocate space for a new object. This is frequently executed code and
- * the coding is deliberaetly sensitive to the optimizing compiler.
- * After changing this, always check the IR/MC that is generated.
- *
- * @param bytes The number of bytes allocated
- * @param align The requested alignment
- * @param offset The offset from the alignment
- * @return The address of the first byte of the allocated region
- */
- @Inline
- public final Address alloc(int bytes, int align, int offset) {
- Address start = alignAllocationNoFill(cursor, align, offset);
- Address end = start.plus(bytes);
- if (end.GT(internalLimit))
- return allocSlow(start, end, align, offset);
- fillAlignmentGap(cursor, start);
- cursor = end;
- return start;
- }
-
- /**
- * Internal allocation slow path. This is called whenever the bump
- * pointer reaches the internal limit. The code is forced out of
- * line. If required we perform an external slow path take, which
- * we inline into this method since this is already out of line.
- *
- * @param start The start address for the pending allocation
- * @param end The end address for the pending allocation
- * @param align The requested alignment
- * @param offset The offset from the alignment
- * @return The address of the first byte of the allocated region
- */
- @NoInline
- private Address allocSlow(Address start, Address end, int align,
- int offset) {
- Address rtn = null;
- Address card = null;
- if (SUPPORT_CARD_SCANNING)
- card = getCard(start.plus(CARD_MASK)); // round up
- if (end.GT(limit)) { /* external slow path */
- rtn = allocSlowInline(end.diff(start).toInt(), align, offset);
- if (SUPPORT_CARD_SCANNING && card.NE(getCard(rtn.plus(CARD_MASK))))
- card = getCard(rtn); // round down
- } else { /* internal slow path */
- while (internalLimit.LE(end))
- internalLimit = internalLimit.plus(STEP_SIZE);
- if (internalLimit.GT(limit))
- internalLimit = limit;
- fillAlignmentGap(cursor, start);
- cursor = end;
- rtn = start;
- }
- if (SUPPORT_CARD_SCANNING && !rtn.isZero())
- createCardAnchor(card, rtn, end.diff(start).toInt());
- return rtn;
- }
-
- /**
- * Given an allocation which starts a new card, create a record of
- * where the start of the object is relative to the start of the
- * card.
- *
- * @param card An address that lies within the card to be marked
- * @param start The address of an object which creates a new card.
- * @param bytes The size of the pending allocation in bytes (used for debugging)
- */
- private void createCardAnchor(Address card, Address start, int bytes) {
- if (VM.VERIFY_ASSERTIONS) {
- VM.assertions._assert(allowScanning);
- VM.assertions._assert(card.EQ(getCard(card)));
- VM.assertions._assert(start.diff(card).sLE(MAX_DATA_START_OFFSET));
- VM.assertions._assert(start.diff(card).toInt() >= -CARD_MASK);
- }
- while (bytes > 0) {
- int offset = start.diff(card).toInt();
- getCardMetaData(card).store(offset);
- card = card.plus(1 << LOG_CARD_BYTES);
- bytes -= (1 << LOG_CARD_BYTES);
- }
- }
-
- /**
- * Return the start of the card corresponding to a given address.
- *
- * @param address The address for which the card start is required
- * @return The start of the card containing the address
- */
- private static Address getCard(Address address) {
- return address.toWord().and(Word.fromIntSignExtend(CARD_MASK).not()).toAddress();
- }
-
- /**
- * Return the address of the metadata for a card, given the address of the card.
- * @param card The address of some card
- * @return The address of the metadata associated with that card
- */
- private static Address getCardMetaData(Address card) {
- Address metadata = EmbeddedMetaData.getMetaDataBase(card);
- return metadata.plus(EmbeddedMetaData.getMetaDataOffset(card, LOG_CARD_BYTES-LOG_CARD_META_SIZE, LOG_CARD_META_SIZE));
- }
-
- /**
- * External allocation slow path (called by superclass when slow path is
- * actually taken. This is necessary (rather than a direct call
- * from the fast path) because of the possibility of a thread switch
- * and corresponding re-association of bump pointers to kernel
- * threads.
- *
- * @param bytes The number of bytes allocated
- * @param offset The offset from the alignment
- * @param align The requested alignment
- * @return The address of the first byte of the allocated region or
- * zero on failure
- */
- @Override
- protected final Address allocSlowOnce(int bytes, int align, int offset) {
- /* Check we have been bound to a space */
- if (space == null) {
- VM.assertions.fail("Allocation on unbound bump pointer.");
- }
-
- /* Check if we already have a block to use */
- if (allowScanning && !region.isZero()) {
- Address nextRegion = getNextRegion(region);
- if (!nextRegion.isZero()) {
- return consumeNextRegion(nextRegion, bytes, align, offset);
- }
- }
-
- /* Acquire space, block aligned, that can accommodate the request */
- Extent blockSize = Word.fromIntZeroExtend(bytes).plus(BLOCK_MASK)
- .and(BLOCK_MASK.not()).toExtent();
- Address start = space.acquire(Conversions.bytesToPages(blockSize));
-
- if (start.isZero()) return start; // failed allocation
-
- if (!allowScanning) { // simple allocator
- if (start.NE(limit)) cursor = start; // discontiguous
- updateLimit(start.plus(blockSize), start, bytes);
- } else // scannable allocator
- updateMetaData(start, blockSize, bytes);
- return alloc(bytes, align, offset);
- }
-
- /**
- * Update the limit pointer. As a side effect update the internal limit
- * pointer appropriately.
- *
- * @param newLimit The new value for the limit pointer
- * @param start The start of the region to be allocated into
- * @param bytes The size of the pending allocation (if any).
- */
- @Inline
- protected final void updateLimit(Address newLimit, Address start, int bytes) {
- limit = newLimit;
- internalLimit = start.plus(STEP_SIZE);
- if (internalLimit.GT(limit))
- internalLimit = limit;
- else {
- while (internalLimit.LT(cursor.plus(bytes)))
- internalLimit = internalLimit.plus(STEP_SIZE);
- if (VM.VERIFY_ASSERTIONS)
- VM.assertions._assert(internalLimit.LE(limit));
- }
- }
-
- /**
- * A bump pointer chunk/region has been consumed but the contiguous region
- * is available, so consume it and then return the address of the start
- * of a memory region satisfying the outstanding allocation request. This
- * is relevant when re-using memory, as in a mark-compact collector.
- *
- * @param nextRegion The region to be consumed
- * @param bytes The number of bytes allocated
- * @param align The requested alignment
- * @param offset The offset from the alignment
- * @return The address of the first byte of the allocated region or
- * zero on failure
- */
- private Address consumeNextRegion(Address nextRegion, int bytes, int align,
- int offset) {
- setNextRegion(region,cursor);
- region = nextRegion;
- cursor = getDataStart(nextRegion);
- updateLimit(getRegionLimit(nextRegion), nextRegion, bytes);
- setDataEnd(nextRegion,Address.zero());
- VM.memory.zero(cursor, limit.diff(cursor).toWord().toExtent());
- reusePages(Conversions.bytesToPages(limit.diff(region)));
-
- return alloc(bytes, align, offset);
- }
-
- /******************************************************************************
- *
- * Accessor methods for the region metadata fields.
- *
- */
-
- /**
- * The first offset in a region after the header
- * @param region The region
- * @return The lowest address at which data can be stored
- */
- @Inline
- public static Address getDataStart(Address region) {
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(!region.isZero());
- return region.plus(DATA_START_OFFSET);
- }
-
- /**
- * The next region in the linked-list of regions
- * @param region The region
- * @return The next region in the list
- */
- @Inline
- public static Address getNextRegion(Address region) {
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(!region.isZero());
- Address result = region.plus(NEXT_REGION_OFFSET).loadAddress();
- return result;
- }
-
- /**
- * Set the next region in the linked-list of regions
- * @param region The region
- * @param the next region in the list
- */
- @Inline
- public static void setNextRegion(Address region, Address nextRegion) {
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(!region.isZero());
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(!nextRegion.EQ(Address.fromIntZeroExtend(0xdeadbeef)));
- region.store(nextRegion,NEXT_REGION_OFFSET);
- }
-
- /**
- * Clear the next region pointer in the linked-list of regions
- * @param region The region
- */
- @Inline
- public static void clearNextRegion(Address region) {
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(!region.isZero());
- region.store(Address.zero(),NEXT_REGION_OFFSET);
- }
-
- /**
- * @param region The bump-pointer region
- * @return The DATA_END address from the region header
- */
- @Inline
- public static Address getDataEnd(Address region) {
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(!region.isZero());
- return region.plus(DATA_END_OFFSET).loadAddress();
- }
-
- /**
- * @param region The bump-pointer region
- * @param endAddress The new DATA_END address from the region header
- */
- public static void setDataEnd(Address region, Address endAddress) {
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(!region.isZero());
- region.store(endAddress, DATA_END_OFFSET);
- if (VERBOSE) {
- Log.write("setDataEnd(");
- Log.write(region);
- Log.write(",");
- Log.write(endAddress);
- Log.writeln(")");
- }
- }
-
- /**
- * Return the end address of the given region.
- * @param region The region.
- * @return the allocation limit of the region.
- */
- public static Address getRegionLimit(Address region) {
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(!region.isZero());
- return region.plus(REGION_LIMIT_OFFSET).loadAddress();
- }
-
- /**
- * Return the end address of the given region.
- * @param region The region.
- * @return the allocation limit of the region.
- */
- public static void setRegionLimit(Address region, Address limit) {
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(!region.isZero());
- region.plus(REGION_LIMIT_OFFSET).store(limit);
- }
-
- /**
- * @param region The region.
- * @return {@code true} if the address is region-aligned
- */
- public static boolean isRegionAligned(Address region) {
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(!region.isZero());
- return region.toWord().and(BLOCK_MASK).isZero();
- }
-
- /**
- * Sanity check a region header
- * @param region Region to check
- */
- public static void checkRegionMetadata(Address region) {
- if (VM.VERIFY_ASSERTIONS) {
- Address nextRegion = getNextRegion(region);
- Address dataStart = getDataStart(region);
- Address dataEnd = getDataEnd(region);
- Address regionLimit = getRegionLimit(region);
-
- VM.assertions._assert(nextRegion.isZero() || isRegionAligned(nextRegion));
- VM.assertions._assert(dataEnd.GE(dataStart));
- if (dataEnd.GT(regionLimit)) {
- Log.write("dataEnd="); Log.write(dataEnd);
- Log.write(", regionLimit="); Log.writeln(regionLimit);
- }
- VM.assertions._assert(dataEnd.LE(regionLimit));
- VM.assertions._assert(regionLimit.EQ(region.plus(BLOCK_SIZE)));
- }
-
- }
- /**
- * Update the metadata to reflect the addition of a new region.
- *
- * @param start The start of the new region
- * @param size The size of the new region (rounded up to block-alignment)
- */
- @Inline
- private void updateMetaData(Address start, Extent size, int bytes) {
- if (initialRegion.isZero()) {
- /* this is the first allocation */
- initialRegion = start;
- region = start;
- cursor = region.plus(DATA_START_OFFSET);
- } else if (limit.NE(start) ||
- region.diff(start.plus(size)).toWord().toExtent().GT(maximumRegionSize())) {
- /* non contiguous or over-size, initialize new region */
- setNextRegion(region,start);
- setDataEnd(region,cursor);
- region = start;
- cursor = start.plus(DATA_START_OFFSET);
- }
- updateLimit(start.plus(size), start, bytes);
- setRegionLimit(region,limit);
- }
-
- /**
- * Gather data for GCspy. <p>
- * This method calls the drivers linear scanner to scan through
- * the objects allocated by this bump pointer.
- *
- * @param driver The GCspy driver for this space.
- */
- public void gcspyGatherData(LinearSpaceDriver driver) {
- //driver.setRange(space.getStart(), cursor);
- driver.setRange(space.getStart(), limit);
- this.linearScan(driver.getScanner());
- }
-
- /**
- * Gather data for GCspy. <p>
- * This method calls the drivers linear scanner to scan through
- * the objects allocated by this bump pointer.
- *
- * @param driver The GCspy driver for this space.
- * @param scanSpace The space to scan
- */
- public void gcspyGatherData(LinearSpaceDriver driver, Space scanSpace) {
- //TODO can scanSpace ever be different to this.space?
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(scanSpace == space, "scanSpace != space");
-
- //driver.setRange(scanSpace.getStart(), cursor);
- Address start = scanSpace.getStart();
- driver.setRange(start, limit);
-
- if (false) {
- Log.write("\nBumpPointer.gcspyGatherData set Range "); Log.write(scanSpace.getStart());
- Log.write(" to "); Log.writeln(limit);
- Log.write("BumpPointergcspyGatherData scan from "); Log.writeln(initialRegion);
- }
-
- linearScan(driver.getScanner());
- }
-
-
- /**
- * Perform a linear scan through the objects allocated by this bump pointer.
- *
- * @param scanner The scan object to delegate scanning to.
- */
- @Inline
- public final void linearScan(LinearScan scanner) {
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(allowScanning);
- /* Has this allocator ever allocated anything? */
- if (initialRegion.isZero()) return;
-
- /* Loop through active regions or until the last region */
- Address start = initialRegion;
- while (!start.isZero()) {
- scanRegion(scanner, start); // Scan this region
- start = getNextRegion(start); // Move on to next
- }
- }
-
- /**
- * Perform a linear scan through a single contiguous region
- *
- * @param scanner The scan object to delegate to.
- * @param start The start of this region
- */
- @Inline
- private void scanRegion(LinearScan scanner, Address start) {
- /* Get the end of this region */
- Address dataEnd = start.plus(DATA_END_OFFSET).loadAddress();
-
- /* dataEnd = zero represents the current region. */
- Address currentLimit = (dataEnd.isZero() ? cursor : dataEnd);
- if (currentLimit.EQ(start.plus(DATA_END_OFFSET).plus(BYTES_IN_ADDRESS))) {
- /* Empty region, so we can not call getObjectFromStartAddress() */
- return;
- }
-
- ObjectReference current = VM.objectModel.getObjectFromStartAddress(start.plus(DATA_START_OFFSET));
-
- /* Loop through each object up to the limit */
- do {
- /* Read end address first, as scan may be destructive */
- Address currentObjectEnd = VM.objectModel.getObjectEndAddress(current);
- scanner.scan(current);
- if (currentObjectEnd.GE(currentLimit)) {
- /* We have scanned the last object */
- break;
- }
- /* Find the next object from the start address (dealing with alignment gaps, etc.) */
- ObjectReference next = VM.objectModel.getObjectFromStartAddress(currentObjectEnd);
- if (VM.VERIFY_ASSERTIONS) {
- /* Must be monotonically increasing */
- VM.assertions._assert(next.toAddress().GT(current.toAddress()));
- }
- current = next;
- } while (true);
- }
-
- /**
- * Some pages are about to be re-used to satisfy a slow path request.
- * @param pages The number of pages.
- */
- protected void reusePages(int pages) {
- VM.assertions.fail("Subclasses that reuse regions must override this method.");
- }
-
- /**
- * Maximum size of a single region. Important for children that implement
- * load balancing or increments based on region size.
- * @return the maximum region size
- */
- protected Extent maximumRegionSize() { return Extent.max(); }
-
- /** @return the current cursor value */
- public final Address getCursor() { return cursor; }
- /** @return the space associated with this bump pointer */
- @Override
- public final Space getSpace() { return space; }
-
- /**
- * Print out the status of the allocator (for debugging)
- */
- public final void show() {
- Log.write("cursor = "); Log.write(cursor);
- if (allowScanning) {
- Log.write(" region = "); Log.write(region);
- }
- Log.write(" limit = "); Log.writeln(limit);
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/utility/alloc/DumpLinearScan.java b/vmkit/mmtk/java/src/org/mmtk/utility/alloc/DumpLinearScan.java
deleted file mode 100644
index 0746712..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/utility/alloc/DumpLinearScan.java
+++ /dev/null
@@ -1,38 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.utility.alloc;
-
-import org.mmtk.vm.VM;
-import org.mmtk.utility.Log;
-
-import org.vmmagic.unboxed.*;
-import org.vmmagic.pragma.*;
-
-/**
- * Simple linear scan to dump object information.
- */
-@Uninterruptible
-public final class DumpLinearScan extends LinearScan {
- /**
- * Scan an object.
- *
- * @param object The object to scan
- */
- @Inline
- public void scan(ObjectReference object) {
- Log.write("[");
- Log.write(object.toAddress());
- Log.write("], SIZE = ");
- Log.writeln(VM.objectModel.getCurrentSize(object));
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/utility/alloc/EmbeddedMetaData.java b/vmkit/mmtk/java/src/org/mmtk/utility/alloc/EmbeddedMetaData.java
deleted file mode 100644
index 18574f2..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/utility/alloc/EmbeddedMetaData.java
+++ /dev/null
@@ -1,74 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.utility.alloc;
-
-import org.mmtk.utility.Constants;
-
-import org.vmmagic.unboxed.*;
-import org.vmmagic.pragma.*;
-
-/**
- * This plan implements constants and access methods for meta data
- * that is embeded in allocation spaces (rather than kept on the
- * side). The basic idea is that meta data be embeded at a very
- * coarse power of two granularity for fast access, minimal wastage
- * and by making the regions coarse, the contiguous meta-data will be
- * relatively large and thus the probability of L1 conflict misses
- * will be reduced (as compared with embedding meta-data at the start
- * of each page which will cause those few cache lines corresponding
- * to the start of each page to be heavily conflicted).
- */
-@Uninterruptible public final class EmbeddedMetaData implements Constants {
-
- /* The (log of the) size of each region of meta data management */
- public static final int LOG_BYTES_IN_REGION = 22;
- public static final int BYTES_IN_REGION = 1 << LOG_BYTES_IN_REGION;
- private static final Word REGION_MASK = Word.fromIntSignExtend(BYTES_IN_REGION - 1);
- public static final int LOG_PAGES_IN_REGION = LOG_BYTES_IN_REGION - LOG_BYTES_IN_PAGE;
- public static final int PAGES_IN_REGION = 1 << LOG_PAGES_IN_REGION;
-
- /**
- * Given an address, return the begining of the meta data for the
- * region containing the address. This is a fast operation because
- * it only involves masking out low order bits.
- *
- * @param address The address whose meta data is sought.
- * @return The address of the start of the meta data for the meta
- * region in which the address is located.
- */
- @Inline
- public static Address getMetaDataBase(Address address) {
- return address.toWord().and(REGION_MASK.not()).toAddress();
- }
-
- /**
- * Given an address, the density (coverage) of a meta data type, and
- * the granularity (alignment) of the meta data, return the offset
- * into the meta data the address.
- *
- * @param address The address whose meta data offset is sought.
- * @param logCoverage The log base two of the coverage of the meta
- * data in question. For example, a value of 4 would indicate a
- * coverage of 16; one metadata byte for every 16 bytes of data.
- * @param logAlign The log base two of the aligment or granularity
- * of the meta-data (it may be arranged in bytes, words, double
- * words etc).
- * @return The offset into the meta-data for this region, given the
- * specified address and coverage and aligment requirements.
- */
- public static Extent getMetaDataOffset(Address address,
- int logCoverage,
- int logAlign) {
- return address.toWord().and(REGION_MASK).rshl(logCoverage+logAlign).lsh(logAlign).toExtent();
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/utility/alloc/ImmixAllocator.java b/vmkit/mmtk/java/src/org/mmtk/utility/alloc/ImmixAllocator.java
deleted file mode 100644
index 3ca0981..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/utility/alloc/ImmixAllocator.java
+++ /dev/null
@@ -1,331 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-
-package org.mmtk.utility.alloc;
-
-import org.mmtk.policy.Space;
-import org.mmtk.policy.immix.Block;
-import org.mmtk.policy.immix.Chunk;
-import org.mmtk.policy.immix.Line;
-import org.mmtk.policy.immix.ImmixSpace;
-import static org.mmtk.policy.immix.ImmixConstants.*;
-
-import org.mmtk.utility.Constants;
-import org.mmtk.utility.Log;
-import org.mmtk.utility.options.Options;
-import org.mmtk.vm.VM;
-
-import org.vmmagic.unboxed.*;
-import org.vmmagic.pragma.*;
-
-/**
- *
- */
-@Uninterruptible
-public class ImmixAllocator extends Allocator implements Constants {
-
- /****************************************************************************
- *
- * Instance variables
- */
- protected final ImmixSpace space; /* space this allocator is associated with */
- private final boolean hot;
- private final boolean copy;
-
- private Address cursor; /* bump pointer */
- private Address limit; /* limit for bump pointer */
- private Address largeCursor; /* bump pointer for large objects */
- private Address largeLimit; /* limit for bump pointer for large objects */
- private boolean requestForLarge; /* is the current request for large or small? */
- private boolean straddle; /* did the last allocation straddle a line? */
- private int lineUseCount; /* approximation to bytes allocated (measured at 99% accurate) 07/10/30 */
- private Address markTable;
- private Address recyclableBlock;
- private int line;
- private boolean recyclableExhausted;
-
- /**
- * Constructor.
- *
- * @param space The space to bump point into.
- * @param hot TODO
- * @param copy TODO
- */
- public ImmixAllocator(ImmixSpace space, boolean hot, boolean copy) {
- this.space = space;
- this.hot = hot;
- this.copy = copy;
- reset();
- }
-
- /**
- * Reset the allocator. Note that this does not reset the space.
- */
- public void reset() {
- cursor = Address.zero();
- limit = Address.zero();
- largeCursor = Address.zero();
- largeLimit = Address.zero();
- markTable = Address.zero();
- recyclableBlock = Address.zero();
- requestForLarge = false;
- recyclableExhausted = false;
- line = LINES_IN_BLOCK;
- lineUseCount = 0;
- }
-
- /*****************************************************************************
- *
- * Public interface
- */
-
- /**
- * Allocate space for a new object. This is frequently executed code and
- * the coding is deliberaetly sensitive to the optimizing compiler.
- * After changing this, always check the IR/MC that is generated.
- *
- * @param bytes The number of bytes allocated
- * @param align The requested alignment
- * @param offset The offset from the alignment
- * @return The address of the first byte of the allocated region
- */
- @Inline
- public final Address alloc(int bytes, int align, int offset) {
- /* establish how much we need */
- Address start = alignAllocationNoFill(cursor, align, offset);
- Address end = start.plus(bytes);
-
- /* check whether we've exceeded the limit */
- if (end.GT(limit)) {
- if (bytes > BYTES_IN_LINE)
- return overflowAlloc(bytes, align, offset);
- else
- return allocSlowHot(bytes, align, offset);
- }
-
- /* sufficient memory is available, so we can finish performing the allocation */
- fillAlignmentGap(cursor, start);
- cursor = end;
-
- return start;
- }
-
- /**
- * Allocate space for a new object. This is frequently executed code and
- * the coding is deliberaetly sensitive to the optimizing compiler.
- * After changing this, always check the IR/MC that is generated.
- *
- * @param bytes The number of bytes allocated
- * @param align The requested alignment
- * @param offset The offset from the alignment
- * @return The address of the first byte of the allocated region
- */
- public final Address overflowAlloc(int bytes, int align, int offset) {
- /* establish how much we need */
- Address start = alignAllocationNoFill(largeCursor, align, offset);
- Address end = start.plus(bytes);
-
- /* check whether we've exceeded the limit */
- if (end.GT(largeLimit)) {
- requestForLarge = true;
- Address rtn = allocSlowInline(bytes, align, offset);
- requestForLarge = false;
- return rtn;
- }
-
- /* sufficient memory is available, so we can finish performing the allocation */
- fillAlignmentGap(largeCursor, start);
- largeCursor = end;
-
- return start;
- }
-
- @Inline
- public final boolean getLastAllocLineStraddle() {
- return straddle;
- }
-
- /**
- * External allocation slow path (called by superclass when slow path is
- * actually taken. This is necessary (rather than a direct call
- * from the fast path) because of the possibility of a thread switch
- * and corresponding re-association of bump pointers to kernel
- * threads.
- *
- * @param bytes The number of bytes allocated
- * @param align The requested alignment
- * @param offset The offset from the alignment
- * @return The address of the first byte of the allocated region or
- * zero on failure
- */
- protected final Address allocSlowOnce(int bytes, int align, int offset) {
- boolean success = false;
- while (!success) {
- Address ptr = space.getSpace(hot, copy, lineUseCount);
-
- if (ptr.isZero()) {
- lineUseCount = 0;
- return ptr; // failed allocation --- we will need to GC
- }
-
- /* we have been given a clean block */
- success = true;
- lineUseCount = LINES_IN_BLOCK;
- if (VM.VERIFY_ASSERTIONS)
- VM.assertions._assert(Block.isAligned(ptr));
- zeroBlock(ptr);
- if (requestForLarge) {
- largeCursor = ptr;
- largeLimit = ptr.plus(BYTES_IN_BLOCK);
- } else {
- cursor = ptr;
- limit = ptr.plus(BYTES_IN_BLOCK);
- }
- }
- return alloc(bytes, align, offset);
- }
-
- /****************************************************************************
- *
- * Bump allocation
- */
-
- /**
- * Internal allocation slow path. This is called whenever the bump
- * pointer reaches the internal limit. The code is forced out of
- * line. If required we perform an external slow path take, which
- * we inline into this method since this is already out of line.
- *
- * @param bytes The number of bytes allocated
- * @param align The requested alignment
- * @param offset The offset from the alignment
- * @return The address of the first byte of the allocated region
- */
- @NoInline
- private Address allocSlowHot(int bytes, int align, int offset) {
- if (acquireRecyclableLines(bytes, align, offset))
- return alloc(bytes, align, offset);
- else
- return allocSlowInline(bytes, align, offset);
- }
-
- private boolean acquireRecyclableLines(int bytes, int align, int offset) {
- while (line < LINES_IN_BLOCK || acquireRecyclableBlock()) {
- line = space.getNextAvailableLine(markTable, line);
- if (line < LINES_IN_BLOCK) {
- int endLine = space.getNextUnavailableLine(markTable, line);
- cursor = recyclableBlock.plus(Extent.fromIntSignExtend(line<<LOG_BYTES_IN_LINE));
- limit = recyclableBlock.plus(Extent.fromIntSignExtend(endLine<<LOG_BYTES_IN_LINE));
- if (SANITY_CHECK_LINE_MARKS) {
- Address tmp = cursor;
- while (tmp.LT(limit)) {
- if (tmp.loadByte() != (byte) 0) {
- Log.write("cursor: "); Log.writeln(cursor);
- Log.write(" limit: "); Log.writeln(limit);
- Log.write("current: "); Log.write(tmp);
- Log.write(" value: "); Log.write(tmp.loadByte());
- Log.write(" line: "); Log.write(line);
- Log.write("endline: "); Log.write(endLine);
- Log.write(" chunk: "); Log.write(Chunk.align(cursor));
- Log.write(" hw: "); Log.write(Chunk.getHighWater(Chunk.align(cursor)));
- Log.writeln(" values: ");
- Address tmp2 = cursor;
- while(tmp2.LT(limit)) { Log.write(tmp2.loadByte()); Log.write(" ");}
- Log.writeln();
- }
- VM.assertions._assert(tmp.loadByte() == (byte) 0);
- tmp = tmp.plus(1);
- }
- }
- if (VM.VERIFY_ASSERTIONS && bytes <= BYTES_IN_LINE) {
- Address start = alignAllocationNoFill(cursor, align, offset);
- Address end = start.plus(bytes);
- VM.assertions._assert(end.LE(limit));
- }
- VM.memory.zero(cursor, limit.diff(cursor).toWord().toExtent());
- if (VM.VERIFY_ASSERTIONS && Options.verbose.getValue() >= 9) {
- Log.write("Z["); Log.write(cursor); Log.write("->"); Log.write(limit); Log.writeln("]");
- }
-
- line = endLine;
- if (VM.VERIFY_ASSERTIONS && copy) VM.assertions._assert(!Block.isDefragSource(cursor));
- return true;
- }
- }
- return false;
- }
-
- private boolean acquireRecyclableBlock() {
- boolean rtn;
- rtn = acquireRecyclableBlockAddressOrder();
- if (rtn) {
- markTable = Line.getBlockMarkTable(recyclableBlock);
- line = 0;
- }
- return rtn;
- }
-
- @Inline
- private boolean acquireRecyclableBlockAddressOrder() {
- if (recyclableExhausted) {
- if (VM.VERIFY_ASSERTIONS && Options.verbose.getValue() >= 9) {
- Log.writeln("[no recyclable available]");
- }
- return false;
- }
- int markState = 0;
- boolean usable = false;
- while (!usable) {
- Address next = recyclableBlock.plus(BYTES_IN_BLOCK);
- if (recyclableBlock.isZero() || ImmixSpace.isRecycleAllocChunkAligned(next)) {
- recyclableBlock = space.acquireReusableBlocks();
- if (recyclableBlock.isZero()) {
- recyclableExhausted = true;
- if (VM.VERIFY_ASSERTIONS && Options.verbose.getValue() >= 9) {
- Log.writeln("[recyclable exhausted]");
- }
- line = LINES_IN_BLOCK;
- return false;
- }
- } else {
- recyclableBlock = next;
- }
- markState = Block.getBlockMarkState(recyclableBlock);
- usable = (markState > 0 && markState <= ImmixSpace.getReusuableMarkStateThreshold(copy));
- if (copy && Block.isDefragSource(recyclableBlock))
- usable = false;
- }
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(!Block.isUnused(recyclableBlock));
- Block.setBlockAsReused(recyclableBlock);
-
- lineUseCount += (LINES_IN_BLOCK-markState);
- return true; // found something good
- }
-
- private void zeroBlock(Address block) {
- // FIXME: efficiency check here!
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(block.toWord().and(Word.fromIntSignExtend(BYTES_IN_BLOCK-1)).isZero());
- VM.memory.zero(block, Extent.fromIntZeroExtend(BYTES_IN_BLOCK));
- }
-
- /** @return the space associated with this squish allocator */
- public final Space getSpace() { return space; }
-
- /**
- * Print out the status of the allocator (for debugging)
- */
- public final void show() {
- Log.write("cursor = "); Log.write(cursor);
- Log.write(" limit = "); Log.writeln(limit);
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/utility/alloc/LargeObjectAllocator.java b/vmkit/mmtk/java/src/org/mmtk/utility/alloc/LargeObjectAllocator.java
deleted file mode 100644
index 3a399e9..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/utility/alloc/LargeObjectAllocator.java
+++ /dev/null
@@ -1,113 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.utility.alloc;
-
-import org.mmtk.policy.BaseLargeObjectSpace;
-import org.mmtk.utility.Constants;
-
-import org.vmmagic.unboxed.*;
-import org.vmmagic.pragma.*;
-
-/**
- * This abstract class implements core functionality for a generic
- * large object allocator. The shared VMResource used by each instance
- * is the point of global synchronization, and synchronization only
- * occurs at the granularity of aquiring (and releasing) chunks of
- * memory from the VMResource. Subclasses may require finer grained
- * synchronization during a marking phase, for example.<p>
- *
- * This is a first cut implementation, with plenty of room for
- * improvement...
- */
-@Uninterruptible
-public abstract class LargeObjectAllocator extends Allocator implements Constants {
-
- /****************************************************************************
- *
- * Instance variables
- */
- protected final BaseLargeObjectSpace space;
-
- /****************************************************************************
- *
- * Initialization
- */
-
- /**
- * Constructor
- *
- * @param space The space with which this large object allocator
- * will be associated.
- */
- public LargeObjectAllocator(BaseLargeObjectSpace space) {
- this.space = space;
- }
-
- /**
- * Return the space this allocator is currently bound to.
- *
- * @return The Space.
- */
- protected final BaseLargeObjectSpace getSpace() {
- return this.space;
- }
-
- /****************************************************************************
- *
- * Allocation
- */
-
- /**
- * Allocate space for an object
- *
- * @param bytes The number of bytes allocated
- * @param align The requested alignment.
- * @param offset The alignment offset.
- * @return The address of the first byte of the allocated cell Will
- * not return zero.
- */
- @NoInline
- public final Address alloc(int bytes, int align, int offset) {
- Address cell = allocSlow(bytes, align, offset);
- return alignAllocation(cell, align, offset);
- }
-
- /**
- * Allocate a large object. Large objects are directly allocted and
- * freed in page-grained units via the vm resource. This routine
- * returned zeroed memory.
- *
- * @param bytes The required size of this space in bytes.
- * @param offset The alignment offset.
- * @param align The requested alignment.
- * @return The address of the start of the newly allocated region at
- * least <code>bytes</code> bytes in size.
- */
- protected final Address allocSlowOnce(int bytes, int align, int offset) {
- int header = space.getHeaderSize();
- int maxbytes = getMaximumAlignedSize(bytes + header, align);
- int pages = (maxbytes + BYTES_IN_PAGE - 1) >> LOG_BYTES_IN_PAGE;
- Address sp = space.acquire(pages);
- if (sp.isZero()) return sp;
- Address cell = sp.plus(header);
- return cell;
- }
-
- /****************************************************************************
- *
- * Miscellaneous
- */
- public void show() {
- }
-}
-
diff --git a/vmkit/mmtk/java/src/org/mmtk/utility/alloc/LinearScan.java b/vmkit/mmtk/java/src/org/mmtk/utility/alloc/LinearScan.java
deleted file mode 100644
index 306b5f1..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/utility/alloc/LinearScan.java
+++ /dev/null
@@ -1,30 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.utility.alloc;
-
-import org.vmmagic.unboxed.*;
-import org.vmmagic.pragma.*;
-
-/**
- * Callbacks from BumpPointer during a linear scan are dispatched through
- * a subclass of this object.
- */
-@Uninterruptible
-public abstract class LinearScan {
- /**
- * Scan an object.
- *
- * @param object The object to scan
- */
- public abstract void scan(ObjectReference object);
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/utility/alloc/SegregatedFreeList.java b/vmkit/mmtk/java/src/org/mmtk/utility/alloc/SegregatedFreeList.java
deleted file mode 100644
index 9ae3d20..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/utility/alloc/SegregatedFreeList.java
+++ /dev/null
@@ -1,119 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.utility.alloc;
-
-import org.mmtk.policy.SegregatedFreeListSpace;
-import org.mmtk.utility.*;
-
-import org.vmmagic.pragma.*;
-import org.vmmagic.unboxed.*;
-
-/**
- * This abstract class implements the fast past for a segregated free list.
- */
-@Uninterruptible
-public abstract class SegregatedFreeList<S extends SegregatedFreeListSpace> extends Allocator implements Constants {
-
- /****************************************************************************
- *
- * Instance variables
- */
-
- /** The space */
- protected final S space;
-
- /** The current free lists for the size classes */
- protected final AddressArray freeList;
-
- /****************************************************************************
- *
- * Initialization
- */
-
- /**
- * Constructor
- *
- * @param space The space with which this allocator will be associated
- */
- public SegregatedFreeList(S space) {
- this.space = space;
- this.freeList = AddressArray.create(sizeClassCount());
- }
-
- /**
- * Return the space this allocator is currently bound to.
- *
- * @return The Space.
- */
- protected final S getSpace() {
- return this.space;
- }
-
- /****************************************************************************
- *
- * Allocation
- */
-
- /**
- * Allocate <code>bytes</code> contiguous bytes of zeroed memory.<p>
- *
- * This code implements the fast path, and on failure delegates to the slow path.
- *
- * @param bytes The size of the object to occupy this space, in bytes.
- * @param align The requested alignment.
- * @param offset The alignment offset.
- * @return The address of the first word or zero on failure
- */
- @Inline
- public final Address alloc(int bytes, int align, int offset) {
- int alignedBytes = getMaximumAlignedSize(bytes, align);
- int sizeClass = getSizeClass(alignedBytes);
- Address cell = freeList.get(sizeClass);
- if (!cell.isZero()) {
- freeList.set(sizeClass, cell.loadAddress());
- /* Clear the free list link */
- cell.store(Address.zero());
- if (alignedBytes != bytes) {
- /* Ensure aligned as requested. */
- cell = alignAllocation(cell, align, offset);
- }
- return cell;
- }
- return allocSlow(bytes, align, offset);
- }
-
- /**
- * The number of distinct size classes.
- *
- * NOTE: For optimal performance this call must be implemented in a way
- * it can be inlined and optimized within the allocation sequence.
- */
- @Inline
- private int sizeClassCount() {
- return SegregatedFreeListSpace.sizeClassCount();
- }
-
- /**
- * Get the size class for a given number of bytes.
- *
- * NOTE: For optimal performance this call must be implemented in a way
- * it can be inlined and optimized within the allocation sequence.
- *
- * @param bytes The number of bytes required to accommodate the object
- * @return The size class capable of accommodating the allocation request.
- */
- @Inline
- private int getSizeClass(int bytes) {
- return space.getSizeClass(bytes);
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/utility/alloc/SegregatedFreeListLocal.java b/vmkit/mmtk/java/src/org/mmtk/utility/alloc/SegregatedFreeListLocal.java
deleted file mode 100644
index 30fd964..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/utility/alloc/SegregatedFreeListLocal.java
+++ /dev/null
@@ -1,162 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.utility.alloc;
-
-import org.mmtk.policy.SegregatedFreeListSpace;
-import org.mmtk.utility.*;
-
-import org.mmtk.vm.VM;
-
-import org.vmmagic.pragma.*;
-import org.vmmagic.unboxed.*;
-
-/**
- * This abstract class implements a simple segregated free list.<p>
- *
- * See: Wilson, Johnstone, Neely and Boles "Dynamic Storage
- * Allocation: A Survey and Critical Review", IWMM 1995, for an
- * overview of free list allocation and the various implementation
- * strategies, including segregated free lists.<p>
- *
- * We maintain a number of size classes, each size class having a free
- * list of available objects of that size (the list may be empty). We
- * call the storage elements "cells". Cells reside within chunks of
- * memory called "blocks". All cells in a given block are of the same
- * size (i.e. blocks are homogeneous with respect to size class).
- * Each block maintains its own free list (free cells within that
- * block). For each size class a list of blocks is maintained, one of
- * which will serve the role of the current free list. When the free
- * list on the current block is exhausted, the next block for that
- * size class becomes the current block and its free list is used. If
- * there are no more blocks the a new block is allocated.<p>
- */
-@Uninterruptible
-public abstract class SegregatedFreeListLocal<S extends SegregatedFreeListSpace> extends SegregatedFreeList<S>
- implements Constants {
-
- /****************************************************************************
- *
- * Class variables
- */
-
- /****************************************************************************
- *
- * Instance variables
- */
- protected final AddressArray currentBlock;
-
- /****************************************************************************
- *
- * Initialization
- */
-
- /**
- * Constructor
- *
- * @param space The space with which this allocator will be associated
- */
- public SegregatedFreeListLocal(S space) {
- super(space);
- this.currentBlock = AddressArray.create(space.sizeClassCount());
- }
-
- /****************************************************************************
- *
- * Allocation
- */
-
- /**
- * Allocate <code>bytes</code> contiguous bytes of non-zeroed
- * memory. First check if the fast path works. This is needed
- * since this method may be called in the context when the fast
- * version was NOT just called. If this fails, it will try finding
- * another block with a non-empty free list, or allocating a new
- * block.<p>
- *
- * This code should be relatively infrequently executed, so it is
- * forced out of line to reduce pressure on the compilation of the
- * core alloc routine.<p>
- *
- * Precondition: None
- *
- * Postconditions: A new cell has been allocated (not zeroed), and
- * the block containing the cell has been placed on the appropriate
- * free list data structures. The free list itself is not updated
- * (the caller must do so).<p>
- *
- * @param bytes The size of the object to occupy this space, in bytes.
- * @param offset The alignment offset.
- * @param align The requested alignment.
- * @return The address of the first word or zero on failure.
- */
- @NoInline
- public final Address allocSlowOnce(int bytes, int align, int offset) {
- // Did a collection occur and provide a free cell?
- bytes = getMaximumAlignedSize(bytes, align);
- int sizeClass = space.getSizeClass(bytes);
- Address cell = freeList.get(sizeClass);
-
- if (cell.isZero()) {
- Address block = currentBlock.get(sizeClass);
- if (!block.isZero()) {
- // Return the block if we currently own one
- space.returnConsumedBlock(block, sizeClass);
- currentBlock.set(sizeClass, Address.zero());
- }
-
- // Get a new block for allocation, if returned, it is guaranteed to have a free cell
- block = space.getAllocationBlock(sizeClass, freeList);
-
- if (!block.isZero()) {
- // We have a new current block and free list.
- currentBlock.set(sizeClass, block);
- cell = freeList.get(sizeClass);
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(!cell.isZero());
- } else {
- // Allocation Failure
- return Address.zero();
- }
- }
-
- freeList.set(sizeClass, cell.loadAddress());
- /* Clear the free list link */
- cell.store(Address.zero());
- return alignAllocation(cell, align, offset);
- }
-
- /****************************************************************************
- *
- * Preserving (saving & restoring) free lists
- */
-
- /**
- * Zero all of the current free list pointers, and refresh the
- * <code>currentBlock</code> values, so instead of the free list
- * pointing to free cells, it points to the block containing the
- * free cells. Then the free lists for each cell can be
- * reestablished during GC. If the free lists are being preserved
- * on a per-block basis (eager mark-sweep and reference counting),
- * then free lists are remembered for each block.
- */
- public final void flush() {
- for (int sizeClass = 0; sizeClass < space.sizeClassCount(); sizeClass++) {
- Address block = currentBlock.get(sizeClass);
- if (!block.isZero()) {
- Address cell = freeList.get(sizeClass);
- space.returnBlock(block, sizeClass, cell);
- currentBlock.set(sizeClass, Address.zero());
- freeList.set(sizeClass, Address.zero());
- }
- }
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/utility/deque/AddressDeque.java b/vmkit/mmtk/java/src/org/mmtk/utility/deque/AddressDeque.java
deleted file mode 100644
index 06d85db..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/utility/deque/AddressDeque.java
+++ /dev/null
@@ -1,120 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.utility.deque;
-
-import org.mmtk.utility.Constants;
-
-import org.mmtk.vm.VM;
-
-import org.vmmagic.unboxed.*;
-import org.vmmagic.pragma.*;
-
-/**
- * This supports <i>unsynchronized</i> enqueuing and dequeuing of addresses
- */
-@Uninterruptible public class AddressDeque extends LocalDeque
- implements Constants {
-
- /****************************************************************************
- *
- * Public instance methods
- */
- public final String name;
-
- /**
- * Constructor
- *
- * @param queue The shared queue to which this queue will append
- * its buffers (when full or flushed) and from which it will aquire new
- * buffers when it has exhausted its own.
- */
- public AddressDeque(String n, SharedDeque queue) {
- super(queue);
- name = n;
- }
-
- /**
- * Insert an address into the address queue.
- *
- * @param addr the address to be inserted into the address queue
- */
- @Inline
- public final void insert(Address addr) {
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(!addr.isZero());
- checkTailInsert(1);
- uncheckedTailInsert(addr);
- }
-
- /**
- * Insert an address into the address queue, force this out of line
- * ("OOL"), in some circumstnaces it is too expensive to have the
- * insert inlined, so this call is made.
- *
- * @param addr the address to be inserted into the address queue
- */
- @NoInline
- public final void insertOOL(Address addr) {
- insert(addr);
- }
-
- /**
- * Push an address onto the address queue.
- *
- * @param addr the address to be pushed onto the address queue
- */
- @Inline
- public final void push(Address addr) {
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(!addr.isZero());
- checkHeadInsert(1);
- uncheckedHeadInsert(addr);
- }
-
- /**
- * Push an address onto the address queue, force this out of line
- * ("OOL"), in some circumstnaces it is too expensive to have the
- * push inlined, so this call is made.
- *
- * @param addr the address to be pushed onto the address queue
- */
- @NoInline
- public final void pushOOL(Address addr) {
- push(addr);
- }
-
- /**
- * Pop an address from the address queue, return zero if the queue
- * is empty.
- *
- * @return The next address in the address queue, or zero if the
- * queue is empty
- */
- @Inline
- public final Address pop() {
- if (checkDequeue(1)) {
- return uncheckedDequeue();
- } else {
- return Address.zero();
- }
- }
-
- @Inline
- public final boolean isEmpty() {
- return !checkDequeue(1);
- }
-
- @Inline
- public final boolean isNonEmpty() {
- return checkDequeue(1);
- }
-
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/utility/deque/AddressPairDeque.java b/vmkit/mmtk/java/src/org/mmtk/utility/deque/AddressPairDeque.java
deleted file mode 100644
index 5b3500e..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/utility/deque/AddressPairDeque.java
+++ /dev/null
@@ -1,98 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.utility.deque;
-
-import org.mmtk.utility.Constants;
-
-import org.mmtk.vm.VM;
-
-import org.vmmagic.unboxed.*;
-import org.vmmagic.pragma.*;
-
-/**
- * This supports <i>unsynchronized</i> enqueuing and dequeuing of
- * address pairs
- */
-@Uninterruptible public class AddressPairDeque extends LocalDeque implements Constants {
-
- /****************************************************************************
- *
- * Public instance methods
- */
-
- /**
- * Constructor
- *
- * @param queue The shared queue to which this queue will append
- * its buffers (when full or flushed) and from which it will aquire new
- * buffers when it has exhausted its own.
- */
- public AddressPairDeque(SharedDeque queue) {
- super(queue);
- }
-
- /**
- * Insert an address pair into the address queue.
- *
- * @param addr1 the first address to be inserted into the address queue
- * @param addr2 the second address to be inserted into the address queue
- */
- public final void insert(Address addr1, Address addr2) {
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(!addr1.isZero());
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(!addr2.isZero());
- checkTailInsert(2);
- uncheckedTailInsert(addr1);
- uncheckedTailInsert(addr2);
- }
-
- /**
- * Push an address pair onto the address queue.
- *
- * @param addr1 the first value to be pushed onto the address queue
- * @param addr2 the second value to be pushed onto the address queue
- */
- public final void push(Address addr1, Address addr2) {
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(!addr1.isZero());
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(!addr2.isZero());
- checkHeadInsert(2);
- uncheckedHeadInsert(addr2);
- uncheckedHeadInsert(addr1);
- }
-
- /**
- * Pop the first address in a pair from the address queue, return
- * zero if the queue is empty.
- *
- * @return The next address in the address queue, or zero if the
- * queue is empty
- */
- public final Address pop1() {
- if (checkDequeue(2))
- return uncheckedDequeue();
- else
- return Address.zero();
- }
-
- /**
- * Pop the second address in a pair from the address queue.
- *
- * @return The next address in the address queue
- */
- public final Address pop2() {
- return uncheckedDequeue();
- }
-
- public final boolean isEmpty() {
- return !checkDequeue(2);
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/utility/deque/AddressTripleDeque.java b/vmkit/mmtk/java/src/org/mmtk/utility/deque/AddressTripleDeque.java
deleted file mode 100644
index d6cb899..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/utility/deque/AddressTripleDeque.java
+++ /dev/null
@@ -1,111 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.utility.deque;
-
-import org.mmtk.utility.Constants;
-
-import org.mmtk.vm.VM;
-
-import org.vmmagic.unboxed.*;
-import org.vmmagic.pragma.Uninterruptible;
-
-
-/**
- * This supports <i>unsynchronized</i> enqueuing and dequeuing of
- * address triples
- */
-@Uninterruptible public class AddressTripleDeque extends LocalDeque implements Constants {
-
- /****************************************************************************
- *
- * Public instance methods
- */
-
- /**
- * Constructor
- *
- * @param queue The shared queue to which this queue will append its
- * buffers (when full or flushed) and from which it will aquire new
- * buffers when it has exhausted its own.
- */
- AddressTripleDeque(SharedDeque queue) {
- super(queue);
- }
-
- /**
- * Insert an address triple into the address queue.
- *
- * @param addr1 the first address to be inserted into the address queue
- * @param addr2 the second address to be inserted into the address queue
- * @param addr3 the third address to be inserted into the address queue
- */
- public final void insert(Address addr1, Address addr2,
- Address addr3) {
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(!addr1.isZero());
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(!addr2.isZero());
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(!addr3.isZero());
- checkTailInsert(3);
- uncheckedTailInsert(addr1);
- uncheckedTailInsert(addr2);
- uncheckedTailInsert(addr3);
- }
- /**
- * Push an address pair onto the address queue.
- *
- * @param addr1 the first value to be pushed onto the address queue
- * @param addr2 the second value to be pushed onto the address queue
- * @param addr3 the third address to be pushed onto the address queue
- */
- public final void push(Address addr1, Address addr2, Address addr3) {
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(!addr1.isZero());
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(!addr2.isZero());
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(!addr3.isZero());
- checkHeadInsert(3);
- uncheckedHeadInsert(addr3);
- uncheckedHeadInsert(addr2);
- uncheckedHeadInsert(addr1);
- }
-
- /**
- * Pop the first address in a triple from the address queue, return
- * zero if the queue is empty.
- *
- * @return The next address in the address queue, or zero if the
- * queue is empty
- */
- public final Address pop1() {
- if (checkDequeue(3))
- return uncheckedDequeue();
- else
- return Address.zero();
- }
-
- /**
- * Pop the second address in a triple from the address queue.
- *
- * @return The next address in the address queue
- */
- public final Address pop2() {
- return uncheckedDequeue();
- }
-
-
- /**
- * Pop the third address in a triple from the address queue.
- *
- * @return The next address in the address queue
- */
- public final Address pop3() {
- return uncheckedDequeue();
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/utility/deque/Deque.java b/vmkit/mmtk/java/src/org/mmtk/utility/deque/Deque.java
deleted file mode 100644
index 8d17c30..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/utility/deque/Deque.java
+++ /dev/null
@@ -1,79 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.utility.deque;
-
-import org.mmtk.utility.Constants;
-
-import org.vmmagic.unboxed.*;
-import org.vmmagic.pragma.*;
-
-/**
- * Class that defines a doubly-linked double-ended queue (deque). The
- * double-linking increases the space demands slightly, but makes it far
- * more efficient to dequeue buffers and, for example, enables sorting of
- * its contents.
- */
-@Uninterruptible class Deque implements Constants {
-
- /****************************************************************************
- *
- * Protected instance methods
- *
- * protected int enqueued;
- */
-
- @Inline
- protected final Offset bufferOffset(Address buf) {
- return buf.toWord().and(BUFFER_MASK).toOffset();
- }
- @Inline
- protected final Address bufferStart(Address buf) {
- return buf.toWord().and(BUFFER_MASK.not()).toAddress();
- }
- @Inline
- protected final Address bufferEnd(Address buf) {
- return bufferStart(buf).plus(USABLE_BUFFER_BYTES);
- }
- @Inline
- protected final Address bufferFirst(Address buf) {
- return bufferStart(buf);
- }
- @Inline
- protected final Address bufferLast(Address buf, int arity) {
- return bufferStart(buf).plus(bufferLastOffset(arity));
- }
- @Inline
- protected final Address bufferLast(Address buf) {
- return bufferLast(buf, 1);
- }
- @Inline
- protected final Offset bufferLastOffset(int arity) {
- return Offset.fromIntZeroExtend(USABLE_BUFFER_BYTES - BYTES_IN_ADDRESS -
- (USABLE_BUFFER_BYTES % (arity << LOG_BYTES_IN_ADDRESS)));
- }
-
- /****************************************************************************
- *
- * Private and protected static final fields (aka constants)
- */
- protected static final int LOG_PAGES_PER_BUFFER = 0;
- protected static final int PAGES_PER_BUFFER = 1 << LOG_PAGES_PER_BUFFER;
- private static final int LOG_BUFFER_SIZE = (LOG_BYTES_IN_PAGE + LOG_PAGES_PER_BUFFER);
- protected static final int BUFFER_SIZE = 1 << LOG_BUFFER_SIZE;
- protected static final Word BUFFER_MASK = Word.one().lsh(LOG_BUFFER_SIZE).minus(Word.one());
- protected static final int NEXT_FIELD_OFFSET = BYTES_IN_ADDRESS;
- protected static final int META_DATA_SIZE = 2 * BYTES_IN_ADDRESS;
- protected static final int USABLE_BUFFER_BYTES = BUFFER_SIZE - META_DATA_SIZE;
- protected static final Address TAIL_INITIAL_VALUE = Address.zero();
- protected static final Address HEAD_INITIAL_VALUE = Address.zero();
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/utility/deque/LocalDeque.java b/vmkit/mmtk/java/src/org/mmtk/utility/deque/LocalDeque.java
deleted file mode 100644
index c2a1477..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/utility/deque/LocalDeque.java
+++ /dev/null
@@ -1,158 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.utility.deque;
-
-import org.mmtk.plan.Plan;
-import org.mmtk.utility.Constants;
-
-import org.mmtk.vm.VM;
-
-import org.vmmagic.unboxed.*;
-import org.vmmagic.pragma.*;
-
-/**
- * Note this may perform poorly when being used as a FIFO structure with
- * insertHead and pop operations operating on the same buffer. This
- * only uses the fields inherited from <code>LocalQueue</code>, but adds
- * the ability for entries to be added to the head of the deque and popped
- * from the rear.
- */
-@Uninterruptible public class LocalDeque extends LocalQueue
- implements Constants {
-
- /****************************************************************************
- *
- * Public instance methods
- */
-
- /**
- * Constructor
- *
- * @param queue The shared deque to which this local deque will append
- * its buffers (when full or flushed).
- */
- LocalDeque(SharedDeque queue) {
- super(queue);
- }
-
- /**
- * Flush the buffer to the shared deque (this will make any entries
- * in the buffer visible to any other consumer associated with the
- * shared deque).
- */
- @Override
- public final void flushLocal() {
- super.flushLocal();
- if (head.NE(Deque.HEAD_INITIAL_VALUE)) {
- closeAndInsertHead(queue.getArity());
- head = Deque.HEAD_INITIAL_VALUE;
- }
- }
-
- /****************************************************************************
- *
- * Protected instance methods
- */
-
- /**
- * Check whether there is space in the buffer for a pending insert.
- * If there is not sufficient space, allocate a new buffer
- * (dispatching the full buffer to the shared deque if not null).
- *
- * @param arity The arity of the values stored in this deque: the
- * buffer must contain enough space for this many words.
- */
- @Inline
- protected final void checkHeadInsert(int arity) {
- if (bufferOffset(head).EQ(bufferSentinel(arity)) ||
- head.EQ(HEAD_INITIAL_VALUE))
- headOverflow(arity);
- else if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(bufferOffset(head).sLE(bufferLastOffset(arity)));
- }
-
- /**
- * Insert a value at the front of the deque (and buffer). This is
- * <i>unchecked</i>. The caller must first call
- * <code>checkHeadInsert()</code> to ensure the buffer can accommodate
- * the insertion.
- *
- * @param value the value to be inserted.
- */
- @Inline
- protected final void uncheckedHeadInsert(Address value) {
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(bufferOffset(head).sLT(bufferSentinel(queue.getArity())));
- head.store(value);
- head = head.plus(BYTES_IN_ADDRESS);
- // if (Interface.VerifyAssertions) enqueued++;
- }
-
- /****************************************************************************
- *
- * Private instance methods and fields
- */
-
- /**
- * Buffer space has been exhausted, allocate a new buffer and enqueue
- * the existing buffer (if any).
- *
- * @param arity The arity of this buffer (used for sanity test only).
- */
- private void headOverflow(int arity) {
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(arity == queue.getArity());
- if (head.NE(Deque.HEAD_INITIAL_VALUE))
- closeAndInsertHead(arity);
-
- head = queue.alloc();
- Plan.checkForAsyncCollection(); // possible side-effect of alloc()
- }
-
- /**
- * Close the head buffer and enqueue it at the front of the
- * shared buffer deque.
- *
- * @param arity The arity of this buffer.
- */
- @Inline
- private void closeAndInsertHead(int arity) {
- queue.enqueue(head, arity, false);
- }
-
- /**
- * The tail is empty (or null), and the shared deque has no buffers
- * available. If the head has sufficient entries, consume the head.
- * Otherwise try wait on the shared deque until either all other
- * clients of the reach exhaustion or a buffer becomes
- * available.
- *
- * @param arity The arity of this buffer
- * @return True if the consumer has eaten all of the entries
- */
- @SuppressWarnings("unused")
- private boolean tailStarved(int arity) {
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(arity == queue.getArity());
- // entries in tail, so consume tail
- if (!bufferOffset(head).isZero()) {
- tailBufferEnd = head;
- tail = bufferStart(tailBufferEnd);
- head = Deque.HEAD_INITIAL_VALUE;
- return false;
- }
-
- // Wait for another entry to materialize...
- tailBufferEnd = queue.dequeueAndWait(arity, true);
- tail = bufferStart(tail);
-
- // return true if a) there is not a tail buffer or b) it is empty
- return (tail.EQ(Deque.TAIL_INITIAL_VALUE) || tail.EQ(tailBufferEnd));
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/utility/deque/LocalQueue.java b/vmkit/mmtk/java/src/org/mmtk/utility/deque/LocalQueue.java
deleted file mode 100644
index 64c4825..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/utility/deque/LocalQueue.java
+++ /dev/null
@@ -1,158 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.utility.deque;
-
-import org.mmtk.utility.Constants;
-
-import org.mmtk.vm.VM;
-
-import org.vmmagic.pragma.*;
-import org.vmmagic.unboxed.*;
-
-/**
- * This class implements a local (<i>unsynchronized</i>) queue.
- * A queue is strictly FIFO.<p>
- *
- * Each instance stores word-sized values into a local buffer. When
- * the buffer is full, or if the <code>flushLocal()</code> method is
- * called, the buffer enqueued at the tail of a
- * <code>SharedDeque</code>.
- *
- * The implementation is intended to be as efficient as possible, in
- * time and space, and is the basis for the <code>TraceBuffer</code> used by
- * heap trace generation. Each instance adds a single field to those inherited
- * from the SSB: a bump pointer.
- *
- * Preconditions: Buffers are always aligned on buffer-size address
- * boundaries.<p>
- *
- * Invariants: Buffers are filled such that tuples (of the specified
- * arity) are packed to the low end of the buffer. Thus buffer
- * underflows will always arise when then cursor is buffer-size aligned.
- */
-@Uninterruptible class LocalQueue extends LocalSSB implements Constants {
-
- /**
- * Constructor
- *
- * @param queue The shared queue to which this local ssb will append
- * its buffers (when full or flushed).
- */
- LocalQueue(SharedDeque queue) {
- super(queue);
- }
-
- /****************************************************************************
- *
- * Protected instance methods and fields
- */
- @Entrypoint
- protected Address head; // the start of the buffer
-
- /**
- * Reset the local buffer (throwing away any local entries).
- */
- public void resetLocal() {
- super.resetLocal();
- head = Deque.HEAD_INITIAL_VALUE;
- }
-
- /**
- * Check whether there are values in the buffer for a pending dequeue.
- * If there is not data, grab the first buffer on the shared queue
- * (after freeing the buffer).
- *
- * @param arity The arity of the values stored in this queue: the
- * buffer must contain enough space for this many words.
- */
- @Inline
- protected final boolean checkDequeue(int arity) {
- if (bufferOffset(head).isZero()) {
- return dequeueUnderflow(arity);
- } else {
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(bufferOffset(head).sGE(Word.fromIntZeroExtend(arity).lsh(LOG_BYTES_IN_ADDRESS).toOffset()));
- return true;
- }
- }
-
- /**
- * Dequeue a value from the buffer. This is <i>unchecked</i>. The
- * caller must first call <code>checkDequeue()</code> to ensure the
- * buffer has and entry to be removed.
- *
- * @return The first entry on the queue.
- */
- @Inline
- protected final Address uncheckedDequeue(){
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(bufferOffset(head).sGE(Offset.fromIntZeroExtend(BYTES_IN_ADDRESS)));
- head = head.minus(BYTES_IN_ADDRESS);
- return head.loadAddress();
- }
-
- /**
- * The head is empty (or null), and the shared queue has no buffers
- * available. If the tail has sufficient entries, consume the tail.
- * Otherwise try wait on the global queue until either all other
- * clients of the queue reach exhaustion or a buffer becomes
- * available.
- *
- * @param arity The arity of this buffer
- * @return True if the consumer has eaten all the entries
- */
- protected final boolean headStarved(int arity) {
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(arity == queue.getArity());
-
- // If the tail has entries...
- if (tail.NE(tailBufferEnd)) {
- head = normalizeTail(arity).plus(BYTES_IN_ADDRESS);
- tail = Deque.TAIL_INITIAL_VALUE;
- tailBufferEnd = Deque.TAIL_INITIAL_VALUE;
- // Return that we acquired more entries
- return false;
- }
- // Wait for another entry to materialize...
- head = queue.dequeueAndWait(arity);
- // return true if a) there is a head buffer, and b) it is non-empty
- return (head.EQ(Deque.HEAD_INITIAL_VALUE) || bufferOffset(head).isZero());
- }
-
- /****************************************************************************
- *
- * Private instance methods
- */
-
- /**
- * There are not sufficient entries in the head buffer for a pending
- * dequeue. Acquire a new head buffer. If the shared queue has no
- * buffers available, consume the tail if necessary. Return false
- * if entries cannot be acquired.
- *
- * @param arity The arity of this buffer (used for sanity test only).
- * @return True if there the head buffer has been successfully
- * replenished.
- */
- @NoInline
- private boolean dequeueUnderflow(int arity) {
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(arity == queue.getArity());
- do {
- if (head.NE(Deque.HEAD_INITIAL_VALUE))
- queue.free(head);
- head = queue.dequeue(arity);
- } while (head.NE(Deque.HEAD_INITIAL_VALUE) && bufferOffset(head).isZero());
-
- if (head.EQ(Deque.HEAD_INITIAL_VALUE))
- return !headStarved(arity);
-
- return true;
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/utility/deque/LocalSSB.java b/vmkit/mmtk/java/src/org/mmtk/utility/deque/LocalSSB.java
deleted file mode 100644
index bea04f1..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/utility/deque/LocalSSB.java
+++ /dev/null
@@ -1,214 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.utility.deque;
-
-import org.mmtk.plan.Plan;
-import org.mmtk.utility.Constants;
-
-import org.mmtk.vm.VM;
-
-import org.vmmagic.pragma.*;
-import org.vmmagic.unboxed.*;
-
-/**
- * This class implements a local (<i>unsynchronized</i>) sequential
- * store buffer. An SSB is strictly FIFO (although this class does
- * not implement dequeuing).<p>
- *
- * Each instance stores word-sized values into a local buffer. When
- * the buffer is full, or if the <code>flushLocal()</code> method is
- * called, the buffer enqueued at the tail of a
- * <code>SharedDeque</code>. This class provides no mechanism for
- * dequeing.<p>
- *
- * The implementation is intended to be as efficient as possible, in
- * time and space, as it is used in critical code such as the GC work
- * queue and the write buffer used by many "remembering"
- * collectors. Each instance has just two fields: a bump pointer and a
- * pointer to the <code>SharedDeque</code><p>
- *
- * Preconditions: Buffers are always aligned on buffer-size address
- * boundaries.<p>
- *
- * Invariants: Buffers are filled such that tuples (of the specified
- * arity) are packed to the low end of the buffer. Thus buffer
- * overflows on inserts and pops (underflow actually) will always arise
- * when then cursor is buffer-size aligned.
- */
-@Uninterruptible class LocalSSB extends Deque implements Constants {
-
- /****************************************************************************
- *
- * Public instance methods
- */
-
- /**
- * Constructor
- *
- * @param queue The shared queue to which this local ssb will append
- * its buffers (when full or flushed).
- */
- LocalSSB(SharedDeque queue) {
- this.queue = queue;
- resetLocal();
- }
-
- /**
- * Flush the buffer and add it to the shared queue (this will
- * make any entries in the buffer visible to any consumer associated
- * with the shared queue).
- */
- public void flushLocal() {
- if (tail.NE(Deque.TAIL_INITIAL_VALUE)) {
- closeAndEnqueueTail(queue.getArity());
- tail = Deque.TAIL_INITIAL_VALUE;
- tailBufferEnd = Deque.TAIL_INITIAL_VALUE;
- }
- }
-
- public void reset() {
- resetLocal();
- }
-
- /****************************************************************************
- *
- * Protected instance methods and fields
- */
- @Entrypoint
- protected Address tail; // the location in the buffer
- protected Address tailBufferEnd; // the end of the buffer
- protected final SharedDeque queue; // the shared queue
-
- /**
- * Reset the local buffer (throwing away any local entries).
- */
- public void resetLocal() {
- tail = Deque.TAIL_INITIAL_VALUE;
- tailBufferEnd = Deque.TAIL_INITIAL_VALUE;
- }
-
- /**
- * Check whether there is space in the buffer for a pending insert.
- * If there is not sufficient space, allocate a new buffer
- * (dispatching the full buffer to the shared queue if not null).
- *
- * @param arity The arity of the values stored in this SSB: the
- * buffer must contain enough space for this many words.
- */
- @Inline(value=Inline.When.AssertionsDisabled)
- protected final void checkTailInsert(int arity) {
- if (bufferOffset(tail).isZero())
- tailOverflow(arity);
- else if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(bufferOffset(tail).sGE(Word.fromIntZeroExtend(arity).lsh(LOG_BYTES_IN_ADDRESS).toOffset()));
- }
-
- /**
- * Insert a value into the buffer. This is <i>unchecked</i>. The
- * caller must first call <code>checkInsert()</code> to ensure the
- * buffer can accommodate the insertion.
- *
- * @param value the value to be inserted.
- */
- @Inline(value=Inline.When.AssertionsDisabled)
- protected final void uncheckedTailInsert(Address value) {
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(bufferOffset(tail).sGE(Offset.fromIntZeroExtend(BYTES_IN_ADDRESS)));
- tail = tail.minus(BYTES_IN_ADDRESS);
- tail.store(value);
- // if (Interface.VerifyAssertions) enqueued++;
- }
-
- /**
- * In the case where a buffer must be flushed before being
- * filled (either to the queue or to the head), the entries must be
- * slid to the base of the buffer in order to preserve the invariant
- * that all non-tail buffers will have entries starting at the base
- * (which allows a simple test against the base to be used when
- * popping entries). This is <i>expensive</i>, so should be
- * avoided.
- *
- * @param arity The arity of the buffer in question
- * @return The last slot in the normalized buffer that contains an entry
- */
- protected final Address normalizeTail(int arity) {
- Address src = tail;
- Address tgt = bufferFirst(tail);
- Address last = tgt.plus(bufferLastOffset(arity).minus(bufferOffset(tail)));
- while (tgt.LE(last)) {
- tgt.store(src.loadAddress());
- src = src.plus(BYTES_IN_ADDRESS);
- tgt = tgt.plus(BYTES_IN_ADDRESS);
- }
- return last;
- }
-
- /**
- * Return the sentinel offset for a buffer of a given arity. This is used
- * both to compute the address at the end of the buffer.
- *
- * @param arity The arity of this buffer
- * @return The sentinel offset value for a buffer of the given arity.
- */
- @Inline
- protected final Offset bufferSentinel(int arity) {
- return bufferLastOffset(arity).plus(BYTES_IN_ADDRESS);
- }
-
- /****************************************************************************
- *
- * Private instance methods
- */
-
- /**
- * Buffer space has been exhausted, allocate a new buffer and enqueue
- * the existing buffer (if any).
- *
- * @param arity The arity of this buffer (used for sanity test only).
- */
- private void tailOverflow(int arity) {
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(arity == queue.getArity());
- if (tail.NE(Deque.TAIL_INITIAL_VALUE)) {
- closeAndEnqueueTail(arity);
- }
- tail = queue.alloc().plus(bufferSentinel(arity));
- tailBufferEnd = tail;
- Plan.checkForAsyncCollection(); // possible side-effect of alloc()
- }
-
- /**
- * Close the tail buffer (normalizing if necessary), and enqueue it
- * at the tail of the shared buffer queue.
- *
- * @param arity The arity of this buffer.
- */
- @NoInline
- private void closeAndEnqueueTail(int arity) {
- Address last;
- if (!bufferOffset(tail).isZero()) {
- // prematurely closed
- last = normalizeTail(arity);
- } else {
- // a full tail buffer
- last = tailBufferEnd.minus(BYTES_IN_ADDRESS);
- }
- queue.enqueue(last.plus(BYTES_IN_ADDRESS), arity, true);
- }
-
- /**
- * Return true if this SSB is locally empty
- *
- * @return true if this SSB is locally empty
- */
- public final boolean isFlushed() {
- return tail.EQ(Deque.TAIL_INITIAL_VALUE);
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/utility/deque/ObjectReferenceBuffer.java b/vmkit/mmtk/java/src/org/mmtk/utility/deque/ObjectReferenceBuffer.java
deleted file mode 100644
index a3254df..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/utility/deque/ObjectReferenceBuffer.java
+++ /dev/null
@@ -1,128 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.utility.deque;
-
-import org.mmtk.plan.TransitiveClosure;
-import org.mmtk.utility.Constants;
-import org.mmtk.vm.VM;
-
-import org.vmmagic.pragma.*;
-import org.vmmagic.unboxed.*;
-
-/**
- * This class is a combination of a Deque and a TraceStep, designed to include
- * intelligent processing of child references as objects are scanned.
- *
- * @see org.mmtk.plan.TransitiveClosure
- */
-@Uninterruptible
-public abstract class ObjectReferenceBuffer extends TransitiveClosure implements Constants {
- /****************************************************************************
- *
- * Instance variables
- */
- private final ObjectReferenceDeque values;
-
- /****************************************************************************
- *
- * Initialization
- */
-
- /**
- * Constructor
- *
- * @param name The name of the underlying deque.
- * @param queue The shared deque that is used.
- */
- public ObjectReferenceBuffer(String name, SharedDeque queue) {
- values = new ObjectReferenceDeque(name, queue);
- }
-
- /**
- * Trace an edge during GC.
- *
- * @param source The source of the reference.
- * @param slot The location containing the object reference.
- */
- @Inline
- public final void processEdge(ObjectReference source, Address slot) {
- ObjectReference object = VM.activePlan.global().loadObjectReference(slot);
- process(object);
- }
-
- /**
- * This is the method that ensures
- *
- * @param object The object to process.
- */
- protected abstract void process(ObjectReference object);
-
- /**
- * Process each of the child objects for the passed object.
- *
- * @param object The object to process the children of.
- */
- @Inline
- public final void processChildren(ObjectReference object) {
- VM.scanning.scanObject(this, object);
- }
-
- /**
- * Pushes an object onto the queue, forcing an inlined sequence.
- *
- * @param object The object to push.
- */
- @Inline
- public final void push(ObjectReference object) {
- values.push(object);
- }
-
- /**
- * Pushes an object onto the queue, forcing an out of line sequence.
- *
- * @param object The object to push.
- */
- @Inline
- public final void pushOOL(ObjectReference object) {
- values.pushOOL(object);
- }
-
- /**
- * Retrives an object.
- *
- * @return The object retrieved.
- */
- @Inline
- public final ObjectReference pop() {
- return values.pop();
- }
-
- @Inline
- public final boolean isEmpty() {
- return values.isEmpty();
- }
-
- /**
- * Flushes all local state back to the shared queue.
- */
- public final void flushLocal() {
- values.flushLocal();
- }
-
- /**
- * Return true if this buffer is locally empty
- */
- public final boolean isFlushed() {
- return values.isFlushed();
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/utility/deque/ObjectReferenceDeque.java b/vmkit/mmtk/java/src/org/mmtk/utility/deque/ObjectReferenceDeque.java
deleted file mode 100644
index 7ed6cf0..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/utility/deque/ObjectReferenceDeque.java
+++ /dev/null
@@ -1,109 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.utility.deque;
-
-import org.mmtk.utility.Constants;
-
-import org.mmtk.vm.VM;
-
-import org.vmmagic.unboxed.*;
-import org.vmmagic.pragma.*;
-
-/**
- * This supports <i>unsynchronized</i> enqueuing and dequeuing of
- * object references
- */
-@Uninterruptible public class ObjectReferenceDeque extends LocalDeque
- implements Constants {
-
- /****************************************************************************
- *
- * Public instance methods
- */
- public final String name;
-
- /**
- * Constructor
- *
- * @param queue The shared queue to which this queue will append
- * its buffers (when full or flushed) and from which it will aquire new
- * buffers when it has exhausted its own.
- */
- public ObjectReferenceDeque(String n, SharedDeque queue) {
- super(queue);
- name = n;
- }
-
- /**
- * Insert an object into the object queue.
- *
- * @param object the object to be inserted into the object queue
- */
- @Inline
- public final void insert(ObjectReference object) {
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(!object.isNull());
- checkTailInsert(1);
- uncheckedTailInsert(object.toAddress());
- }
-
- /**
- * Push an object onto the object queue.
- *
- * @param object the object to be pushed onto the object queue
- */
- @Inline
- public final void push(ObjectReference object) {
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(!object.isNull());
- checkHeadInsert(1);
- uncheckedHeadInsert(object.toAddress());
- }
-
- /**
- * Push an object onto the object queue, force this out of line
- * ("OOL"), in some circumstnaces it is too expensive to have the
- * push inlined, so this call is made.
- *
- * @param object the object to be pushed onto the object queue
- */
- @NoInline
- public final void pushOOL(ObjectReference object) {
- push(object);
- }
-
- /**
- * Pop an object from the object queue, return zero if the queue
- * is empty.
- *
- * @return The next object in the object queue, or zero if the
- * queue is empty
- */
- @Inline
- public final ObjectReference pop() {
- if (checkDequeue(1)) {
- return uncheckedDequeue().toObjectReference();
- } else {
- return ObjectReference.nullReference();
- }
- }
-
- @Inline
- public final boolean isEmpty() {
- return !checkDequeue(1);
- }
-
- @Inline
- public final boolean isNonEmpty() {
- return checkDequeue(1);
- }
-
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/utility/deque/SharedDeque.java b/vmkit/mmtk/java/src/org/mmtk/utility/deque/SharedDeque.java
deleted file mode 100644
index 0d53570..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/utility/deque/SharedDeque.java
+++ /dev/null
@@ -1,497 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.utility.deque;
-
-import org.mmtk.policy.RawPageSpace;
-import org.mmtk.policy.Space;
-import org.mmtk.utility.Constants;
-import org.mmtk.utility.Log;
-import org.mmtk.vm.Lock;
-import org.mmtk.vm.VM;
-import org.vmmagic.pragma.Entrypoint;
-import org.vmmagic.pragma.Inline;
-import org.vmmagic.pragma.Uninterruptible;
-import org.vmmagic.unboxed.Address;
-import org.vmmagic.unboxed.Offset;
-
-/**
- * This supports <i>unsynchronized</i> enqueuing and dequeuing of buffers
- * for shared use. The data can be added to and removed from either end
- * of the deque.
- */
-@Uninterruptible
-public class SharedDeque extends Deque implements Constants {
- private static final boolean DISABLE_WAITING = true;
- private static final Offset NEXT_OFFSET = Offset.zero();
- private static final Offset PREV_OFFSET = Offset.fromIntSignExtend(BYTES_IN_ADDRESS);
-
- private static final boolean TRACE = false;
- private static final boolean TRACE_DETAIL = false;
- private static final boolean TRACE_BLOCKERS = false;
-
- /****************************************************************************
- *
- * Public instance methods
- */
-
- /**
- * Constructor
- */
- public SharedDeque(String name, RawPageSpace rps, int arity) {
- this.rps = rps;
- this.arity = arity;
- this.name = name;
- lock = VM.newLock("SharedDeque");
- clearCompletionFlag();
- head = HEAD_INITIAL_VALUE;
- tail = TAIL_INITIAL_VALUE;
- }
-
- /** Get the arity (words per entry) of this queue */
- @Inline
- final int getArity() { return arity; }
-
- /**
- * Enqueue a block on the head or tail of the shared queue
- *
- * @param buf
- * @param arity
- * @param toTail
- */
- final void enqueue(Address buf, int arity, boolean toTail) {
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(arity == this.arity);
- lock();
- if (toTail) {
- // Add to the tail of the queue
- setNext(buf, Address.zero());
- if (tail.EQ(TAIL_INITIAL_VALUE))
- head = buf;
- else
- setNext(tail, buf);
- setPrev(buf, tail);
- tail = buf;
- } else {
- // Add to the head of the queue
- setPrev(buf, Address.zero());
- if (head.EQ(HEAD_INITIAL_VALUE))
- tail = buf;
- else
- setPrev(head, buf);
- setNext(buf, head);
- head = buf;
- }
- bufsenqueued++;
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(checkDequeLength(bufsenqueued));
- unlock();
- }
-
- public final void clearDeque(int arity) {
- Address buf = dequeue(arity);
- while (!buf.isZero()) {
- free(bufferStart(buf));
- buf = dequeue(arity);
- }
- setCompletionFlag();
- }
-
- @Inline
- final Address dequeue(int arity) {
- return dequeue(arity, false);
- }
-
- final Address dequeue(int arity, boolean fromTail) {
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(arity == this.arity);
- return dequeue(false, fromTail);
- }
-
- @Inline
- final Address dequeueAndWait(int arity) {
- return dequeueAndWait(arity, false);
- }
-
- final Address dequeueAndWait(int arity, boolean fromTail) {
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(arity == this.arity);
- Address buf = dequeue(false, fromTail);
- if (buf.isZero() && (!complete())) {
- buf = dequeue(true, fromTail); // Wait inside dequeue
- }
- return buf;
- }
-
- /**
- * Prepare for parallel processing. All active GC threads will
- * participate, and pop operations will block until all work
- * is complete.
- */
- public final void prepare() {
- if (DISABLE_WAITING) {
- prepareNonBlocking();
- } else {
- /* This should be the normal mode of operation once performance is fixed */
- prepare(VM.collection.activeGCThreads());
- }
- }
-
- /**
- * Prepare for processing where pop operations on the deques
- * will never block.
- */
- public final void prepareNonBlocking() {
- prepare(1);
- }
-
- /**
- * Prepare for parallel processing where a specific number
- * of threads take part.
- *
- * @param consumers # threads taking part.
- */
- private void prepare(int consumers) {
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(numConsumersWaiting == 0);
- setNumConsumers(consumers);
- clearCompletionFlag();
- }
-
- public final void reset() {
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(numConsumersWaiting == 0);
- clearCompletionFlag();
- setNumConsumersWaiting(0);
- assertExhausted();
- }
-
- public final void assertExhausted() {
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(head.isZero() && tail.isZero());
- }
-
- @Inline
- final Address alloc() {
- Address rtn = rps.acquire(PAGES_PER_BUFFER);
- if (rtn.isZero()) {
- Space.printUsageMB();
- VM.assertions.fail("Failed to allocate space for queue. Is metadata virtual memory exhausted?");
- }
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(rtn.EQ(bufferStart(rtn)));
- return rtn;
- }
-
- @Inline
- final void free(Address buf) {
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(buf.EQ(bufferStart(buf)) && !buf.isZero());
- rps.release(buf);
- }
-
- @Inline
- public final int enqueuedPages() {
- return (int) (bufsenqueued * PAGES_PER_BUFFER);
- }
-
- /****************************************************************************
- *
- * Private instance methods and fields
- */
-
- /** The name of this shared deque - for diagnostics */
- private final String name;
-
- /** Raw page space from which to allocate */
- private RawPageSpace rps;
-
- /** Number of words per entry */
- private final int arity;
-
- /** Completion flag - set when all consumers have arrived at the barrier */
- @Entrypoint
- private volatile int completionFlag;
-
- /** # active threads - processing is complete when # waiting == this */
- @Entrypoint
- private volatile int numConsumers;
-
- /** # threads waiting */
- @Entrypoint
- private volatile int numConsumersWaiting;
-
- /** Head of the shared deque */
- @Entrypoint
- protected volatile Address head;
-
- /** Tail of the shared deque */
- @Entrypoint
- protected volatile Address tail;
- @Entrypoint
- private volatile int bufsenqueued;
- private Lock lock;
-
- private static final long WARN_PERIOD = (long)(2*1E9);
- private static final long TIMEOUT_PERIOD = 10 * WARN_PERIOD;
-
- /**
- * Dequeue a block from the shared pool. If 'waiting' is true, and the
- * queue is empty, wait for either a new block to show up or all the
- * other consumers to join us.
- *
- * @param waiting
- * @param fromTail
- * @return the Address of the block
- */
- private Address dequeue(boolean waiting, boolean fromTail) {
- lock();
- Address rtn = ((fromTail) ? tail : head);
- if (rtn.isZero()) {
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(tail.isZero() && head.isZero());
- // no buffers available
- if (waiting) {
- int ordinal = TRACE ? 0 : VM.activePlan.collector().getId();
- setNumConsumersWaiting(numConsumersWaiting + 1);
- while (rtn.isZero()) {
- if (numConsumersWaiting == numConsumers)
- setCompletionFlag();
- if (TRACE) {
- Log.write("-- ("); Log.write(ordinal);
- Log.write(") joining wait queue of SharedDeque(");
- Log.write(name); Log.write(") ");
- Log.write(numConsumersWaiting); Log.write("/");
- Log.write(numConsumers);
- Log.write(" consumers waiting");
- if (complete()) Log.write(" WAIT COMPLETE");
- Log.writeln();
- if (TRACE_BLOCKERS)
- VM.assertions.dumpStack();
- }
- unlock();
- // Spin and wait
- spinWait(fromTail);
-
- if (complete()) {
- if (TRACE) {
- Log.write("-- ("); Log.write(ordinal); Log.writeln(") EXITING");
- }
- lock();
- setNumConsumersWaiting(numConsumersWaiting - 1);
- unlock();
- return Address.zero();
- }
- lock();
- // Re-get the list head/tail while holding the lock
- rtn = ((fromTail) ? tail : head);
- }
- setNumConsumersWaiting(numConsumersWaiting - 1);
- if (TRACE) {
- Log.write("-- ("); Log.write(ordinal); Log.write(") resuming work ");
- Log.write(" n="); Log.writeln(numConsumersWaiting);
- }
- } else {
- unlock();
- return Address.zero();
- }
- }
- if (fromTail) {
- // dequeue the tail buffer
- setTail(getPrev(tail));
- if (head.EQ(rtn)) {
- setHead(Address.zero());
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(tail.isZero());
- } else {
- setNext(tail, Address.zero());
- }
- } else {
- // dequeue the head buffer
- setHead(getNext(head));
- if (tail.EQ(rtn)) {
- setTail(Address.zero());
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(head.isZero());
- } else {
- setPrev(head, Address.zero());
- }
- }
- bufsenqueued--;
- unlock();
- return rtn;
- }
-
- /**
- * Spinwait for GC work to arrive
- *
- * @param fromTail Check the head or the tail ?
- */
- private void spinWait(boolean fromTail) {
- long startNano = 0;
- long lastElapsedNano = 0;
- while (true) {
- long startCycles = VM.statistics.cycles();
- long endCycles = startCycles + ((long) 1e9); // a few hundred milliseconds more or less.
- long nowCycles;
- do {
- VM.memory.isync();
- Address rtn = ((fromTail) ? tail : head);
- if (!rtn.isZero() || complete()) return;
- nowCycles = VM.statistics.cycles();
- } while (startCycles < nowCycles && nowCycles < endCycles); /* check against both ends to guard against CPU migration */
-
- /*
- * According to the cycle counter, we've been spinning for a while.
- * Time to check nanoTime and see if we should print a warning and/or fail.
- * We lock the deque while doing this to avoid interleaved messages from multiple threads.
- */
- lock();
- if (startNano == 0) {
- startNano = VM.statistics.nanoTime();
- } else {
- long nowNano = VM.statistics.nanoTime();
- long elapsedNano = nowNano - startNano;
- if (elapsedNano - lastElapsedNano > WARN_PERIOD) {
- Log.write("GC Warning: SharedDeque("); Log.write(name);
- Log.write(") wait has reached "); Log.write(VM.statistics.nanosToSecs(elapsedNano));
- Log.write(", "); Log.write(numConsumersWaiting); Log.write("/");
- Log.write(numConsumers); Log.writeln(" threads waiting");
- lastElapsedNano = elapsedNano;
- }
- if (elapsedNano > TIMEOUT_PERIOD) {
- unlock(); // To allow other GC threads to die in turn
- VM.assertions.fail("GC Error: SharedDeque Timeout");
- }
- }
- unlock();
- }
- }
-
- /**
- * Set the "next" pointer in a buffer forming the linked buffer chain.
- *
- * @param buf The buffer whose next field is to be set.
- * @param next The reference to which next should point.
- */
- private static void setNext(Address buf, Address next) {
- buf.store(next, NEXT_OFFSET);
- }
-
- /**
- * Get the "next" pointer in a buffer forming the linked buffer chain.
- *
- * @param buf The buffer whose next field is to be returned.
- * @return The next field for this buffer.
- */
- protected final Address getNext(Address buf) {
- return buf.loadAddress(NEXT_OFFSET);
- }
-
- /**
- * Set the "prev" pointer in a buffer forming the linked buffer chain.
- *
- * @param buf The buffer whose next field is to be set.
- * @param prev The reference to which prev should point.
- */
- private void setPrev(Address buf, Address prev) {
- buf.store(prev, PREV_OFFSET);
- }
-
- /**
- * Get the "next" pointer in a buffer forming the linked buffer chain.
- *
- * @param buf The buffer whose next field is to be returned.
- * @return The next field for this buffer.
- */
- protected final Address getPrev(Address buf) {
- return buf.loadAddress(PREV_OFFSET);
- }
-
- /**
- * Check the number of buffers in the work queue (for debugging
- * purposes).
- *
- * @param length The number of buffers believed to be in the queue.
- * @return True if the length of the queue matches length.
- */
- private boolean checkDequeLength(int length) {
- Address top = head;
- int l = 0;
- while (!top.isZero() && l <= length) {
- top = getNext(top);
- l++;
- }
- return l == length;
- }
-
- /**
- * Lock this shared queue. We use one simple low-level lock to
- * synchronize access to the shared queue of buffers.
- */
- private void lock() {
- lock.acquire();
- }
-
- /**
- * Release the lock. We use one simple low-level lock to synchronize
- * access to the shared queue of buffers.
- */
- private void unlock() {
- lock.release();
- }
-
- /**
- * Is the current round of processing complete ?
- */
- private boolean complete() {
- return completionFlag == 1;
- }
-
- /**
- * Set the completion flag.
- */
- @Inline
- private void setCompletionFlag() {
- if (TRACE_DETAIL) {
- Log.writeln("# setCompletionFlag: ");
- }
- completionFlag = 1;
- }
-
- /**
- * Clear the completion flag.
- */
- @Inline
- private void clearCompletionFlag() {
- if (TRACE_DETAIL) {
- Log.writeln("# clearCompletionFlag: ");
- }
- completionFlag = 0;
- }
-
- @Inline
- private void setNumConsumers(int newNumConsumers) {
- if (TRACE_DETAIL) {
- Log.write("# Num consumers "); Log.writeln(newNumConsumers);
- }
- numConsumers = newNumConsumers;
- }
-
- @Inline
- private void setNumConsumersWaiting(int newNCW) {
- if (TRACE_DETAIL) {
- Log.write("# Num consumers waiting "); Log.writeln(newNCW);
- }
- numConsumersWaiting = newNCW;
- }
-
- @Inline
- private void setHead(Address newHead) {
- head = newHead;
- VM.memory.sync();
- }
-
- @Inline
- private void setTail(Address newTail) {
- tail = newTail;
- VM.memory.sync();
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/utility/deque/SortSharedDeque.java b/vmkit/mmtk/java/src/org/mmtk/utility/deque/SortSharedDeque.java
deleted file mode 100644
index 9ef1b6c..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/utility/deque/SortSharedDeque.java
+++ /dev/null
@@ -1,372 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.utility.deque;
-
-import org.mmtk.policy.RawPageSpace;
-
-import org.mmtk.vm.VM;
-
-import org.vmmagic.pragma.*;
-import org.vmmagic.unboxed.*;
-
-/**
- * This supports <i>unsynchronized</i> enqueuing and dequeuing of buffers
- * for shared use. The data can be added to and removed from either end
- * of the deque. This class is based upon the SharedQueue class. The sorting
- * routines were modified from code written by Narendran Sachindran and
- * Matthew Hertz for GCTk.
- */
-@Uninterruptible public abstract class SortSharedDeque extends SharedDeque {
-
-
- private static final int BYTES_PUSHED = BYTES_IN_ADDRESS * 5;
- private static final int MAX_STACK_SIZE = BYTES_PUSHED * 64;
- private static final Offset INSERTION_SORT_LIMIT = Offset.fromIntSignExtend(80);
-
- /***********************************************************************
- *
- * Class variables
- */
-
- /**
- * Constructor
- *
- * @param rps The space from which the instance should obtain buffers.
- */
- public SortSharedDeque(String name, RawPageSpace rps, int arity) {
- super(name, rps, arity);
- stackBase = AddressArray.create(MAX_STACK_SIZE);
- stackLoc = 0;
- }
-
- /***********************************************************************
- *
- * Sorting methods, utilities, and instance variables
- */
-
-
- /**
- * Return the sorting key for the object passed as a parameter.
- *
- * @param obj The address of the object whose key is wanted
- * @return The value of the sorting key for this object
- */
- protected abstract Word getKey(Address obj);
-
- private static final Word mask16 = Word.fromIntZeroExtend(0xffff0000);
- private static final Word mask8 = Word.fromIntZeroExtend(0x0000ff00);
- private static final Word mask4 = Word.fromIntZeroExtend(0x000000f0);
- private static final Word mask2 = Word.fromIntZeroExtend(0x0000000c);
- private static final Word mask1 = Word.fromIntZeroExtend(0x00000002);
-
- /**
- * Find the highest bit that is set in a longword and return a mask
- * with only that bit set.
- *
- * @param addr Value for which the mask needs to be found
- * @return The highest bit set in the parameter
- */
- private static Word getBitMask(Word addr) {
- int shift = 0;
- if (!addr.and(mask16).isZero()) {
- addr = addr.rshl(16);
- shift += 16;
- }
- if (!addr.and(mask8).isZero()) {
- addr = addr.rshl(8);
- shift += 8;
- }
- if (!addr.and(mask4).isZero()) {
- addr = addr.rshl(4);
- shift += 4;
- }
- if (!addr.and(mask2).isZero()) {
- addr = addr.rshl(2);
- shift += 2;
- }
- if (!addr.and(mask1).isZero()) {
- shift += 1;
- }
- return (Word.one().lsh(shift));
- }
-
- /**
- * Perform insertion sort within an intra-block address range.
- *
- * @param begin Start address of the range to be sorted
- * @param end End address of the range to be sorted
- */
- private void insertionSort(Address begin, Address end) {
- Address rPtr = begin.minus(BYTES_IN_ADDRESS);
- Address lPtr;
-
- while (rPtr.GE(end)) {
- Address rSlot = rPtr.loadAddress();
- Word rKey = getKey(rSlot);
- lPtr = rPtr.plus(BYTES_IN_ADDRESS);
- while (lPtr.LE(begin)) {
- Address lSlot = lPtr.loadAddress();
- Word lKey = getKey(lSlot);
- if (lKey.GT(rKey)) {
- lPtr.minus(BYTES_IN_ADDRESS).store(lSlot);
- lPtr = lPtr.plus(BYTES_IN_ADDRESS);
- } else {
- break;
- }
- }
- lPtr.minus(BYTES_IN_ADDRESS).store(rSlot);
- rPtr = rPtr.minus(BYTES_IN_ADDRESS);
- }
- }
-
- /**
- * Sort objects using radix exchange sort. An explicit stack is
- * maintained to avoid using recursion.
- */
- public void sort() {
- Address startPtr, startLink, endPtr, endLink;
- Word bitMask;
- if (!head.EQ(HEAD_INITIAL_VALUE)) {
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(tail.NE(TAIL_INITIAL_VALUE));
- /* Obtain the bitmask for the first iteration and save the start &
- end pointers and the bitmask on the stack */
- initStack();
- startPtr = popStack();
- while (!startPtr.isZero()) {
- startLink = popStack();
- endPtr = popStack();
- endLink = popStack();
- bitMask = (popStack()).toWord();
- if (startLink.NE(endLink)) {
- partition(startPtr, startLink, endPtr, endLink, bitMask);
- } else if (startPtr.GT(endPtr)) {
- /* Use insertionSort for a limited number of objects within
- a single block */
- if (startPtr.diff(endPtr).sLT(INSERTION_SORT_LIMIT)) {
- insertionSort(startPtr, endPtr);
- } else {
- partition(startPtr, startLink, endPtr, endLink, bitMask);
- }
- }
- // Get the next set of data to sort
- startPtr = popStack();
- }
- }
- checkIfSorted();
- }
-
- /**
- * Partition the slots in an address range based on the value in
- * a particular bit. Place the start & end addresses of the two
- * partitions & a bitmask per partition (which indicates the highest
- * bit position at which the max & min of a partition differ) on the
- * stack. This works just like the partition in quick sort, except
- * that a bit value is being compared here
- *
- * @param startAddr The start address of the range to be sorted
- * @param startLinkAddr The address where the start block has its next field
- * @param endAddr The end address of the range to be sorted
- * @param endLinkAddr The address where the end block has its next field
- * @param bitMask The mask in which the bit to be commpared is set
- */
- private void partition(Address startAddr, Address startLinkAddr,
- Address endAddr, Address endLinkAddr,
- Word bitMask) {
- Address travPtr = endAddr;
- Address travLink = endLinkAddr;
- Address stopPtr = startAddr;
- Address stopLink = startLinkAddr;
- Address travSlot, stopSlot;
- Word travKey, stopKey;
- Word lmax = Word.zero(), rmax = Word.zero();
- Word lmin = Word.max(), rmin = Word.max();
-
- while (true) {
- /* Compute the address range within the current block to compute. */
- Address endOfBlock = travLink;
-
- /* Move the left pointer until the right pointer is reached
- or an address with a 0 value in the bit position is found. */
- while (true) {
- travSlot = travPtr.loadAddress();
- travKey = getKey(travSlot);
-
- /* If we reach the end. */
- if (travPtr.EQ(stopPtr))
- break;
- /* If we found a 0 in bit position, break. */
- if (travKey.and(bitMask).isZero())
- break;
- if (travKey.GT(rmax))
- rmax = travKey;
- if (travKey.LT(rmin))
- rmin = travKey;
- /* Move to the next entry. */
- travPtr = travPtr.plus(BYTES_IN_ADDRESS);
- /* If at end of remset block, move to next block */
- if (travPtr.EQ(endOfBlock)) {
- travLink = getPrev(travPtr);
- endOfBlock = travLink;
- travPtr = bufferStart(endOfBlock);
- }
- }
-
- /* Store the end of the block. */
- endOfBlock = bufferStart(stopPtr);
- /* Move the right pointer until the left pointer is reached
- or an address with a 1 value in the bit position is found. */
- while (true) {
- stopSlot = stopPtr.loadAddress();
- stopKey = getKey(stopSlot);
- /* Found a 1 in bit position, break. */
- if (!stopKey.and(bitMask).isZero())
- break;
- if (stopKey.GT(lmax))
- lmax = stopKey;
- if (stopKey.LT(lmin))
- lmin = stopKey;
- if (stopPtr.EQ(travPtr))
- break;
- /* Move to the next entry, which may be in the next block. */
- if (stopPtr.EQ(endOfBlock)) {
- stopLink = getNext(stopLink);
- stopPtr = stopLink;
- endOfBlock = bufferStart(stopPtr);
- }
- stopPtr = stopPtr.minus(BYTES_IN_ADDRESS);
- }
- if (stopPtr.EQ(travPtr))
- break;
- /* interchange the values pointed to by the left and right pointers */
- travPtr.store(stopSlot);
- stopPtr.store(travSlot);
- }
-
- /* If max value is not equal to the min value in the right partition,
- (not all slots are identical) push the right partition on to the stack */
- if (rmax.GT(rmin)) {
- if (travPtr.EQ(bufferStart(travPtr))) {
- stopLink = getNext(travLink);
- stopPtr = stopLink;
- } else {
- stopLink = travLink;
- stopPtr = travPtr;
- }
- pushOnStack(getBitMask(rmax.xor(rmin)).toAddress());
- pushOnStack(endLinkAddr);
- pushOnStack(endAddr);
- pushOnStack(stopLink);
- pushOnStack(stopPtr.minus(BYTES_IN_ADDRESS));
- }
- /* if max value is not equal to the min value in the left partition,
- (not all slots are identical) push the left partition on to the stack */
- if (lmax.GT(lmin)) {
- pushOnStack(getBitMask(lmax.xor(lmin)).toAddress());
- pushOnStack(travLink);
- pushOnStack(travPtr);
- pushOnStack(startLinkAddr);
- pushOnStack(startAddr);
- }
- }
-
- /*************************************************************************
- *
- * Sorting Stack management routines
- */
- private int stackLoc;
- private AddressArray stackBase;
-
- /*
- * Allocate memory for the stack and intialize it with the first range
- * to partition
- */
- private void initStack() {
- stackLoc = 0;
-
- Address endOfBlock = tail;
- Address startPtr = bufferStart(endOfBlock);
- Word min = Word.max();
- Word max = Word.zero();
- // Find the max. and min addresses in the object buffer
- while (endOfBlock.NE(HEAD_INITIAL_VALUE)) {
- startPtr = bufferStart(endOfBlock);
- while (startPtr.LT(endOfBlock)) {
- Address startSlot = startPtr.loadAddress();
- Word startKey = getKey(startSlot);
- if (startKey.GT(max))
- max = startKey;
- if (startKey.LT(min))
- min = startKey;
- startPtr = startPtr.plus(BYTES_IN_ADDRESS);
- }
- endOfBlock = getPrev(startPtr);
- }
-
- // If max and min are different (not all elements are equal), push the
- // start, end and bitmask values on the stack
- if (max.GT(min)) {
- pushOnStack(getBitMask(max.xor(min)).toAddress());
- pushOnStack(tail);
- pushOnStack(bufferStart(tail));
- pushOnStack(startPtr);
- pushOnStack(startPtr.minus(BYTES_IN_ADDRESS));
- }
- }
-
- /**
- * Push an address on to the stack
- *
- * @param val The address to be pushed
- */
- private void pushOnStack(Address val) {
- stackBase.set(stackLoc, val);
- stackLoc++;
- }
-
- /**
- * Pop an address from the stack
- *
- * @return The address at the top of the stack, or 0 if stack is empty
- */
- private Address popStack() {
- if (stackLoc == 0)
- return Address.zero();
- stackLoc--;
- return stackBase.get(stackLoc);
- }
-
- /**
- * Debug routine, used to check if the object buffer is sorted correctly in
- * decreasing final reference deletion time
- */
- private void checkIfSorted() {
- if (VM.VERIFY_ASSERTIONS) {
- Address buf, end;
- Word prevKey = Word.max();
- end = tail;
- buf = bufferStart(end);
- while (buf.NE(HEAD_INITIAL_VALUE)) {
- // iterate through the block
- while (buf.LT(end)) {
- Address slot = buf.loadAddress();
- Word key = getKey(slot);
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(key.LE(prevKey));
- prevKey = key;
- buf = buf.plus(BYTES_IN_ADDRESS);
- }
- end = getPrev(end);
- buf = bufferStart(end);
- }
- }
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/utility/deque/SortTODAddressStack.java b/vmkit/mmtk/java/src/org/mmtk/utility/deque/SortTODAddressStack.java
deleted file mode 100644
index 349d5fa..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/utility/deque/SortTODAddressStack.java
+++ /dev/null
@@ -1,91 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.utility.deque;
-
-import org.mmtk.utility.Constants;
-
-import org.mmtk.vm.VM;
-
-import org.vmmagic.unboxed.*;
-import org.vmmagic.pragma.*;
-
-/**
- * This supports <i>unsynchronized</i> pushing and popping of addresses.
- * In addition, this can sort the entries currently on the shared stack.
- */
-@Uninterruptible public class SortTODAddressStack extends LocalDeque
- implements Constants {
-
- /****************************************************************************
- *
- * Public instance methods
- */
-
- /**
- * Constructor
- *
- * @param queue The shared stack to which this stack will append
- * its buffers (when full or flushed) and from which it will aquire new
- * buffers when it has exhausted its own.
- */
- public SortTODAddressStack(SortTODSharedDeque queue) {
- super(queue);
- }
-
- /**
- * Sort the address on the shared stack.
- */
- public final void sort() {
- flushLocal();
- ((SortTODSharedDeque) queue).sort();
- }
-
- /**
- * Push an address onto the address stack.
- *
- * @param addr the address to be pushed onto the address queue
- */
- @Inline
- public final void push(Address addr) {
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(!addr.isZero());
- checkHeadInsert(1);
- uncheckedHeadInsert(addr);
- }
-
- /**
- * Pop an address from the address stack, return zero if the stack
- * is empty.
- *
- * @return The next address in the address stack, or zero if the
- * stack is empty
- */
- @Inline
- public final Address pop() {
- if (checkDequeue(1)) {
- return uncheckedDequeue();
- } else {
- return Address.zero();
- }
- }
-
- /**
- * Check if the (local and shared) stacks are empty.
- *
- * @return True if there are no more entries on the local & shared stack,
- * false otherwise.
- */
- @Inline
- public final boolean isEmpty() {
- return !checkDequeue(1);
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/utility/deque/SortTODObjectReferenceStack.java b/vmkit/mmtk/java/src/org/mmtk/utility/deque/SortTODObjectReferenceStack.java
deleted file mode 100644
index 427b131..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/utility/deque/SortTODObjectReferenceStack.java
+++ /dev/null
@@ -1,93 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.utility.deque;
-
-import org.mmtk.utility.Constants;
-
-import org.mmtk.vm.VM;
-
-import org.vmmagic.unboxed.*;
-import org.vmmagic.pragma.*;
-
-/**
- * This supports <i>unsynchronized</i> pushing and popping of object
- * references. In addition, this can sort the entries currently on
- * the shared stack.
- */
-@Uninterruptible public class SortTODObjectReferenceStack extends LocalDeque
- implements Constants {
-
- /****************************************************************************
- *
- * Public instance methods
- */
-
- /**
- * Constructor
- *
- * @param queue The shared stack to which this stack will append
- * its buffers (when full or flushed) and from which it will aquire new
- * buffers when it has exhausted its own.
- */
- public SortTODObjectReferenceStack(SortTODSharedDeque queue) {
- super(queue);
- }
-
- /**
- * Sort the address on the shared stack.
- */
- public final void sort() {
- flushLocal();
- ((SortTODSharedDeque) queue).sort();
- }
-
- /**
- * Push an address onto the address stack.
- *
- * @param object the object to be pushed onto the object queue
- */
- @Inline
- public final void push(ObjectReference object) {
- Address addr = object.toAddress();
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(!addr.isZero());
- checkHeadInsert(1);
- uncheckedHeadInsert(addr);
- }
-
- /**
- * Pop an address from the address stack, return zero if the stack
- * is empty.
- *
- * @return The next address in the address stack, or zero if the
- * stack is empty
- */
- @Inline
- public final ObjectReference pop() {
- if (checkDequeue(1)) {
- return uncheckedDequeue().toObjectReference();
- } else {
- return ObjectReference.nullReference();
- }
- }
-
- /**
- * Check if the (local and shared) stacks are empty.
- *
- * @return True if there are no more entries on the local & shared stack,
- * false otherwise.
- */
- @Inline
- public final boolean isEmpty() {
- return !checkDequeue(1);
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/utility/deque/SortTODSharedDeque.java b/vmkit/mmtk/java/src/org/mmtk/utility/deque/SortTODSharedDeque.java
deleted file mode 100644
index a976796..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/utility/deque/SortTODSharedDeque.java
+++ /dev/null
@@ -1,47 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.utility.deque;
-
-import org.mmtk.policy.RawPageSpace;
-import org.mmtk.vm.VM;
-
-import org.vmmagic.unboxed.*;
-import org.vmmagic.pragma.*;
-
-/**
- * This class specializes SortSharedQueue to sort objects according to
- * their time of death (TOD).
- */
-@Uninterruptible
-public final class SortTODSharedDeque extends SortSharedDeque {
-
- /**
- * Constructor
- *
- * @param rps The space from which the instance should obtain buffers.
- * @param arity The arity of the data to be enqueued
- */
- public SortTODSharedDeque(String name, RawPageSpace rps, int arity) {
- super(name, rps, arity);
- }
-
- /**
- * Return the sorting key for the object passed as a parameter.
- *
- * @param obj The address of the object whose key is wanted
- * @return The value of the sorting key for this object
- */
- protected Word getKey(Address obj) {
- return VM.traceInterface.getDeathTime(obj.toObjectReference());
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/utility/deque/TraceBuffer.java b/vmkit/mmtk/java/src/org/mmtk/utility/deque/TraceBuffer.java
deleted file mode 100644
index 9b73bb2..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/utility/deque/TraceBuffer.java
+++ /dev/null
@@ -1,235 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.utility.deque;
-
-import org.mmtk.utility.Log;
-import org.mmtk.utility.TracingConstants;
-import org.mmtk.vm.VM;
-import org.mmtk.utility.Constants;
-
-import org.vmmagic.pragma.*;
-import org.vmmagic.unboxed.*;
-
-/**
- * This supports <i>unsynchronized</i> enqueuing and dequeuing of tracing data
- * and bulk processing of the buffer.
- */
-@Uninterruptible public class TraceBuffer extends LocalQueue
- implements Constants, TracingConstants {
-
- /***********************************************************************
- *
- * Class based constants
- */
- private static final Word TRACE_NEW_RECORD = Word.fromIntSignExtend(3);
- private static final Word TRACE_ALLOC_SIZE = Word.fromIntSignExtend(5);
-// private static final Word TRACE_ALLOC_NAME = Word.fromIntSignExtend(6);
- private static final Word TRACE_ALLOC_FP = Word.fromIntSignExtend(7);
- private static final Word TRACE_ALLOC_THREAD = Word.fromIntSignExtend(9);
- private static final Word TRACE_TIB_VALUE = Word.fromIntSignExtend(10);
- private static final Word TRACE_DEATH_TIME = Word.fromIntSignExtend(11);
- private static final Word TRACE_FIELD_TARGET = Word.fromIntSignExtend(12);
- private static final Word TRACE_ARRAY_TARGET = Word.fromIntSignExtend(13);
- private static final Word TRACE_FIELD_SLOT = Word.fromIntSignExtend(14);
- private static final Word TRACE_ARRAY_ELEMENT = Word.fromIntSignExtend(15);
- private static final Word TRACE_STATIC_TARGET = Word.fromIntSignExtend(17);
- private static final Word TRACE_BOOT_ALLOC_SIZE = Word.fromIntSignExtend(18);
-
- /*
- * Debugging and trace reducing constants
- */
- public static final boolean OMIT_ALLOCS=false;
- public static final boolean OMIT_UPDATES=false;
- public static final boolean OMIT_BOOTALLOCS=false;
- public static final boolean OMIT_UNREACHABLES=false;
- public static final boolean OMIT_OTHERS=false;
- public static final boolean OMIT_OUTPUT=OMIT_ALLOCS && OMIT_UPDATES &&
- OMIT_OTHERS;
-
-
- /***********************************************************************
- *
- * Public methods
- */
-
- /**
- * Constructor
- *
- * @param pool The shared queue to which this queue will append its
- * buffers (when full or flushed) and from which it will aquire new
- * buffers when it has exhausted its own.
- */
- public TraceBuffer(SharedDeque pool) {
- super(pool);
- }
-
- /**
- * Push word onto the tracing queue.
- *
- * @param i The data to be pushed onto the tracing queue
- */
- @Inline
- public final void push(Word i) {
- checkTailInsert(1);
- uncheckedTailInsert(i.toAddress());
- }
-
- /**
- * Process the data in the tracing buffer, output information as needed.
- */
- public final void process() {
- Word traceState = TRACE_NEW_RECORD;
- int entriesNotFlushed = 0;
- boolean loggedRecord = false;
- /* First we must flush any remaining data */
- if (!OMIT_OUTPUT) Log.writeln();
-
- /* Process through the entire buffer. */
- while (checkDequeue(1)) {
- /* For speed and efficiency, we will actually process the data buffer by
- buffer and not by dequeue-ing each entry. */
- while (!bufferOffset(head).isZero()) {
- head = head.minus(BYTES_IN_ADDRESS);
- Word val = head.loadWord();
- if (traceState.EQ(TRACE_NEW_RECORD)) {
- loggedRecord = false;
- if (val.EQ(TRACE_GCSTART)) {
- if (!OMIT_OTHERS) {
- Log.write('G');
- Log.write('C');
- Log.writeln('B', true);
- }
- } else if (val.EQ(TRACE_GCEND)) {
- if (!OMIT_OTHERS) {
- Log.write('G');
- Log.write('C');
- Log.writeln('E', true);
- }
- } else {
- traceState = val;
- }
- } else {
- if (traceState.EQ(TRACE_EXACT_ALLOC) ||
- traceState.EQ(TRACE_ALLOC)) {
- if (!OMIT_ALLOCS) {
- Log.write((traceState.EQ(TRACE_EXACT_ALLOC)) ? 'A' : 'a');
- Log.write(' ');
- Log.write(val);
- loggedRecord = true;
- }
- traceState = TRACE_ALLOC_SIZE;
- } else if (traceState.EQ(TRACE_EXACT_IMMORTAL_ALLOC) ||
- traceState.EQ(TRACE_IMMORTAL_ALLOC)) {
- if (!OMIT_ALLOCS) {
- Log.write((traceState.EQ(TRACE_EXACT_IMMORTAL_ALLOC)) ? 'I' : 'i');
- Log.write(' ');
- Log.write(val);
- loggedRecord = true;
- }
- traceState = TRACE_ALLOC_SIZE;
- } else if (traceState.EQ(TRACE_BOOT_ALLOC)) {
- if (!OMIT_BOOTALLOCS) {
- Log.write('B');
- Log.write(' ');
- Log.write(val);
- loggedRecord = true;
- }
- traceState = TRACE_BOOT_ALLOC_SIZE;
- } else if (traceState.EQ(TRACE_DEATH)) {
- if (!OMIT_UNREACHABLES) {
- Log.write('D');
- Log.write(' ');
- Log.write(val);
- loggedRecord = true;
- }
- traceState = TRACE_DEATH_TIME;
- } else if (traceState.EQ(TRACE_BOOT_ALLOC_SIZE)) {
- if (!OMIT_BOOTALLOCS)
- Log.write(val);
- traceState = TRACE_NEW_RECORD;
- } else if (traceState.EQ(TRACE_ALLOC_SIZE)) {
- if (!OMIT_ALLOCS)
- Log.write(val);
- traceState = TRACE_ALLOC_FP;
- } else if (traceState.EQ(TRACE_ALLOC_FP)) {
- if (!OMIT_ALLOCS)
- Log.write(val);
- traceState = TRACE_ALLOC_THREAD;
- } else if (traceState.EQ(TRACE_ALLOC_THREAD)) {
- if (!OMIT_ALLOCS)
- Log.write(val);
- traceState = TRACE_NEW_RECORD;
- } else if (traceState.EQ(TRACE_TIB_SET)) {
- if (!OMIT_UPDATES) {
- Log.write('T');
- Log.write(' ');
- Log.write(val);
- loggedRecord = true;
- }
- traceState = TRACE_TIB_VALUE;
- } else if (traceState.EQ(TRACE_STATIC_SET)) {
- if (!OMIT_UPDATES) {
- Log.write('S');
- Log.write(' ');
- Log.write(val);
- loggedRecord = true;
- }
- traceState = TRACE_STATIC_TARGET;
- } else if (traceState.EQ(TRACE_TIB_VALUE) ||
- traceState.EQ(TRACE_STATIC_TARGET)) {
- if (!OMIT_UPDATES)
- Log.write(val);
- traceState = TRACE_NEW_RECORD;
- } else if (traceState.EQ(TRACE_DEATH_TIME)) {
- if (!OMIT_UNREACHABLES)
- Log.write(val);
- traceState = TRACE_NEW_RECORD;
- } else if (traceState.EQ(TRACE_FIELD_SET) ||
- traceState.EQ(TRACE_ARRAY_SET)) {
- if (!OMIT_UPDATES) {
- Log.write('U');
- Log.write(' ');
- Log.write(val);
- loggedRecord = true;
- }
- traceState = TRACE_FIELD_SLOT;
- } else if (traceState.EQ(TRACE_FIELD_TARGET) ||
- traceState.EQ(TRACE_ARRAY_TARGET)) {
- if (!OMIT_UPDATES)
- Log.write(val);
- traceState = TRACE_NEW_RECORD;
- } else if (traceState.EQ(TRACE_FIELD_SLOT) ||
- traceState.EQ(TRACE_ARRAY_ELEMENT)) {
- if (!OMIT_UPDATES)
- Log.write(val);
- traceState = TRACE_FIELD_TARGET;
- } else {
- VM.assertions.fail("Cannot understand directive!\n");
- }
- if (traceState.EQ(TRACE_NEW_RECORD) && loggedRecord) {
- entriesNotFlushed++;
- Log.writeln();
- } else if (loggedRecord) {
- Log.write(' ');
- }
- }
- if (entriesNotFlushed == 10) {
- if (!OMIT_OUTPUT)
- Log.flush();
- entriesNotFlushed = 0;
- }
- }
- }
- resetLocal();
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/utility/deque/WriteBuffer.java b/vmkit/mmtk/java/src/org/mmtk/utility/deque/WriteBuffer.java
deleted file mode 100644
index 9d916db..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/utility/deque/WriteBuffer.java
+++ /dev/null
@@ -1,51 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.utility.deque;
-
-import org.mmtk.utility.Constants;
-
-import org.vmmagic.unboxed.*;
-import org.vmmagic.pragma.*;
-
-/**
- * This supports <i>unsynchronized</i> insertion of write buffer values.
- */
-@Uninterruptible public class WriteBuffer extends LocalSSB
- implements Constants {
-
- /****************************************************************************
- *
- * Public instance methods
- */
-
- /**
- * Constructor
- *
- * @param queue The shared queue to which this local ssb will append
- * its buffers (when full or flushed).
- */
- public WriteBuffer(SharedDeque queue) {
- super(queue);
- }
-
- /**
- * Insert a value to be remembered into the write buffer.
- *
- * @param addr the value to be inserted into the write buffer
- */
- @NoInline
- public final void insert(Address addr) {
- checkTailInsert(1);
- uncheckedTailInsert(addr);
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/utility/gcspy/Color.java b/vmkit/mmtk/java/src/org/mmtk/utility/gcspy/Color.java
deleted file mode 100644
index 320ddfa..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/utility/gcspy/Color.java
+++ /dev/null
@@ -1,100 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.utility.gcspy;
-
-import org.mmtk.vm.VM;
-
-import org.vmmagic.pragma.*;
-
-/**
- * Color.java
- *
- * Cut-down implementation of java.awt.Color sufficient to provide
- * the server side (Stream) with colours
- */
-@Uninterruptible public class Color {
-
- /**
- * Some gcspy standard colours (taken from gcspy_color_db.c).
- */
- public static final Color Black = new Color(0, 0, 0);
- public static final Color Blue = new Color(0, 0, 255);
- public static final Color Cyan = new Color(0, 255, 255);
- public static final Color DarkGray = new Color(64, 64, 64);
- public static final Color Gray = new Color(128, 128, 128);
- public static final Color Green = new Color(0, 255, 0);
- public static final Color LightGray = new Color(192, 192, 192);
- public static final Color Magenta = new Color(255, 0, 255);
- public static final Color MidGray = new Color(160, 160, 160);
- public static final Color NavyBlue = new Color(0, 0, 150);
- public static final Color OffWhite = new Color(230, 230, 230);
- public static final Color Orange = new Color(255, 200, 0);
- public static final Color Pink = new Color(255, 175, 175);
- public static final Color Red = new Color(255, 0, 0);
- public static final Color White = new Color(255, 255, 255);
- public static final Color Yellow = new Color(255, 255, 0);
-
- private short r; // red component
- private short g; // green component
- private short b; // blue component
-
- /**
- * Constructor for a simple RGB colour model.
- *
- * @param r red component
- * @param g green component
- * @param b blue component
- */
- public Color(short r, short g, short b) {
- if (VM.VERIFY_ASSERTIONS)
- VM.assertions._assert((0 <= r) && (r <= 255) &&
- (0 <= g) && (g <= 255) &&
- (0 <= b) && (b <= 255));
- this.r = r;
- this.g = g;
- this.b = b;
- }
-
- /**
- * Constructor for a simple RGB colour model.
- *
- * @param r red component
- * @param g green component
- * @param b blue component
- */
- private Color(int r, int g, int b) {
- this((short) r, (short) g, (short) b);
- }
-
-
- /**
- * Red component
- *
- * @return the red component
- */
- public short getRed() { return r; }
-
- /**
- * Green component
- *
- * @return the green component
- */
- public short getGreen() { return g; }
-
- /**
- * Blue component
- *
- * @return the blue component
- */
- public short getBlue() { return b; }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/utility/gcspy/GCspy.java b/vmkit/mmtk/java/src/org/mmtk/utility/gcspy/GCspy.java
deleted file mode 100644
index 16fa3fb..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/utility/gcspy/GCspy.java
+++ /dev/null
@@ -1,95 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.utility.gcspy;
-
-import org.mmtk.utility.Log;
-import org.mmtk.utility.options.*;
-import org.mmtk.vm.VM;
-import org.mmtk.vm.gcspy.ServerInterpreter;
-import org.mmtk.vm.gcspy.Util;
-
-import org.vmmagic.pragma.*;
-
-/**
- * This class implements collector-independent GCspy functionality to start
- * the GCspy server. It handles command-line parameters for port number,
- * whether the VM should wait for a GCspy client to connect, and tile size.
- * Most importantly, it calls the Plan's startGCspyServer method which
- * creates a new ServerInterpreter, and adds events and space drivers.
- */
-@Uninterruptible public class GCspy {
-
- /****************************************************************************
- *
- * Class variables
- */
-
- public static final Util util = VM.newGCspyUtil();
- public static final ServerInterpreter server = VM.newGCspyServerInterpreter();
-
- /****************************************************************************
- *
- * Initialization
- */
-
- @Interruptible
- public static void createOptions() {
- Options.gcspyPort = new GCspyPort();
- Options.gcspyWait = new GCspyWait();
- Options.gcspyTileSize = new GCspyTileSize();
- }
-
- /**
- * The boot method is called by the runtime immediately after
- * command-line arguments are available. Note that allocation must
- * be supported prior to this point because the runtime
- * infrastructure may require allocation in order to parse the
- * command line arguments.
- */
- public static void postBoot() { }
-
- /**
- * Get the number of the port that GCspy communicates on
- *
- * @return the GCspy port number
- */
- public static int getGCspyPort() {
- return Options.gcspyPort.getValue();
- }
-
- /**
- * Should the VM wait for GCspy to connect?
- *
- * @return whether the VM should wait for the visualiser to connect
- */
- public static boolean getGCspyWait() {
- return Options.gcspyWait.getValue();
- }
-
- /**
- * Start the GCspy server.
- * WARNING: allocates memory indirectly
- */
- @Interruptible
- public static void startGCspyServer() {
- int port = getGCspyPort();
- Log.write("GCspy.startGCspyServer, port="); Log.write(port);
- Log.write(", wait=");
- Log.writeln(getGCspyWait());
- if (port > 0) {
- VM.activePlan.global().startGCspyServer(port, getGCspyWait());
- //Log.writeln("gcspy thread booted");
- }
- }
-}
-
diff --git a/vmkit/mmtk/java/src/org/mmtk/utility/gcspy/LinearScan.java b/vmkit/mmtk/java/src/org/mmtk/utility/gcspy/LinearScan.java
deleted file mode 100644
index 2ccd5ad..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/utility/gcspy/LinearScan.java
+++ /dev/null
@@ -1,42 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.utility.gcspy;
-
-import org.mmtk.utility.gcspy.drivers.AbstractDriver;
-
-import org.vmmagic.unboxed.*;
-import org.vmmagic.pragma.*;
-
-/**
- * This class is only necessary because we cannot implement
- * org.mmtk.utility.alloc.LinearScan as an interface since the invokeinterface
- * bytecode is forbidden in uninterruptible code.
- */
-@Uninterruptible public class LinearScan extends org.mmtk.utility.alloc.LinearScan {
-
- private final AbstractDriver driver;
-
- /**
- * Create a new scanner.
- * @param d The GCspy driver that provides the callback.
- */
- public LinearScan(AbstractDriver d) { driver = d; }
-
- /**
- * Scan an object. The object reference is passed to the scan method of the
- * GCspy driver registered with this scanner.
- * @param obj The object to scan.
- */
- public void scan(ObjectReference obj) { driver.scan(obj); }
-}
-
diff --git a/vmkit/mmtk/java/src/org/mmtk/utility/gcspy/StreamConstants.java b/vmkit/mmtk/java/src/org/mmtk/utility/gcspy/StreamConstants.java
deleted file mode 100644
index b1a99ee..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/utility/gcspy/StreamConstants.java
+++ /dev/null
@@ -1,60 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.utility.gcspy;
-
-/**
- * This interface provides constants used by the GCspy framweork.
- * These must correspond with values in gcspy_stream.h
- * Presentation
- * <table>
- <tr><td>PRESENTATION_PLAIN</td> <td>presented as is</td>
- <tr><td>PRESENTATION_PLUS</td> <td>as max+ if value exceeds max else as is</td>
- <tr><td>PRESENTATION_MAX_VAR</td> <td>ditto but takes max value from a specified stream</td>
- <tr><td>PRESENTATION_PERCENT</td> <td>as value (percent)</td>
- <tr><td>PRESENTATION_PERCENT_VAR</td><td>ditto but takes max value from a specified stream</td>
- <tr><td>PRESENTATION_ENUM </td> <td>chooses from an enumeration</td>
- </table>
- Paint style
- <table>
- <tr><td>PAINT_STYLE_PLAIN</td> <td>Paints as is</td>
- <tr><td>PAINT_STYLE_ZERO</td> <td>ditto but treats zero values specially</td>
- </table>
- Data types
- <table>
- <tr><td>BYTE_TYPE</td> <td>stream of bytes</td>
- <tr><td>SHORT_TYPE</td> <td>stream of shorts</td>
- <tr><td>INT_TYPE</td> <td>stream of ints</td>
- </table>
- * StreamConstants
- */
-
-public interface StreamConstants {
-
- int NAME_LEN = 40;
- int PRESENTATION_PLAIN = 0;
- int PRESENTATION_PLUS = 1;
- int PRESENTATION_MAX_VAR = 2;
- int PRESENTATION_PERCENT = 3;
- int PRESENTATION_PERCENT_VAR = 4;
- int PRESENTATION_ENUM = 5;
-
- int PAINT_STYLE_PLAIN = 0;
- int PAINT_STYLE_ZERO = 1;
-
- int BYTE_TYPE = 0;
- int SHORT_TYPE = 1;
- int INT_TYPE = 2;
-
- int ENUM_MAX_LEN = 20;
- int ENUM_MAX_NUM = 5;
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/utility/gcspy/Subspace.java b/vmkit/mmtk/java/src/org/mmtk/utility/gcspy/Subspace.java
deleted file mode 100644
index ab76498..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/utility/gcspy/Subspace.java
+++ /dev/null
@@ -1,236 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.utility.gcspy;
-
-import org.mmtk.utility.Log;
-import org.mmtk.vm.gcspy.Util;
-
-import org.vmmagic.unboxed.*;
-import org.vmmagic.pragma.*;
-
-
-
-/**
- * This class is an abstraction of a contiguous region of a Space. For
- * example, a semispace collector might choose to model the heap as a
- * single Space, but within that Space it could model each semispace by
- * a Subspace.<p>
- * Subspace provides a number of useful facilities to many drivers, and
- * is useful even if the Space comprises just a single contiguous region.<p>
- *
- * A subspace keeps track of the start and end address of the region,
- * the index of its first block, the size of the blocks in this space,
- * and the number of blocks in this subspace.
- */
-@Uninterruptible public class Subspace {
-
- private Address start_; // The Subspace spans the address range [start_, end_)
- private Address end_;
- private int firstIndex_; // The index of the block in which start_ lies
- private int blockSize_; // The block size
- private int blockNum_; // The number of blocks in this space
-
- private static final boolean DEBUG = false;
-
- /**
- * Create a new subspace
- *
- * @param start The address of the start of the subspace
- * @param end The address of the end of the subspace
- * @param firstIndex The index of the first block of the subspace
- * @param blockSize The size of blocks in this space
- * @param blockNum The number of blocks in this subspace
- */
- public Subspace(Address start,
- Address end,
- int firstIndex,
- int blockSize,
- int blockNum) {
- reset(start, end, firstIndex, blockSize, blockNum);
- }
-
-
- //------------------Methods to reset a subspace----------------------
-
- /**
- * Reset a subspace.
- *
- * @param start The address of the start of the subspace
- * @param end The address of the end of the subspace
- * @param firstIndex The index of the first block of the subspace
- * @param blockSize The size of blocks in this subspace
- * @param blockNum The number of blocks in this subspace
- */
- private void reset(Address start,
- Address end,
- int firstIndex,
- int blockSize,
- int blockNum) {
- //TODO sanity check on addresses and block size and number
- reset(start, end, firstIndex, blockNum);
- blockSize_ = blockSize;
-
- if (DEBUG) dump();
- }
-
- /**
- * Reset a new subspace
- *
- * @param start The address of the start of the subspace
- * @param end The address of the end of the subspace
- * @param firstIndex The index of the first block of the subspace
- * @param blockNum The number of blocks in this subspace
- */
- public void reset(Address start,
- Address end,
- int firstIndex,
- int blockNum) {
- start_ = start;
- end_ = end;
- firstIndex_ = firstIndex;
- blockNum_ = blockNum;
- }
-
- /**
- * Reset a new subspace.
- *
- * @param start The address of the start of the subspace
- * @param end The address of the end of the subspace
- * @param blockNum The number of blocks in this subspace
- */
- public void reset(Address start, Address end, int blockNum) {
- start_ = start;
- end_ = end;
- blockNum_ = blockNum;
- }
-
- /**
- * Reset a new subspace.
- *
- * @param firstIndex The index of the first block of the subspace
- * @param blockNum The number of blocks in this subspace
- */
- public void reset(int firstIndex, int blockNum) {
- firstIndex_ = firstIndex;
- blockNum_ = blockNum;
- }
-
-
- //----------------Facilities to query a subspace-----------------
-
- /**
- * Is an index in the range of this subspace?
- *
- * @param index The index of the block
- * @return true if this block lies in this subspace
- */
- public boolean indexInRange(int index) {
- return index >= firstIndex_ &&
- index < firstIndex_ + blockNum_;
- }
-
- /**
- * Is address in the range of this subspace?
- *
- * @param addr An address
- * @return true if this address is in a block in this subspace
- */
- public boolean addressInRange(Address addr) {
- return addr.GE(start_) && addr.LT(end_);
- }
-
-
- /**
- * Get the block index from an address
- *
- * @param addr The address
- * @return The index of the block holding this address
- */
- public int getIndex(Address addr) {
- if (DEBUG) {
- Log.write("start_ ", start_);
- Log.write(" end_ ", end_);
- Log.write(" blockSize_ ", blockSize_);
- Log.write(" firstIndex_ ", firstIndex_);
- Log.write(" + ", addr.diff(start_).toInt() / blockSize_);
- Log.writeln(" addr ", addr);
- }
- return firstIndex_ + addr.diff(start_).toInt() / blockSize_;
- }
-
- /**
- * Get the address of start of block from its index
- *
- * @param index The index of the block
- * @return The address of the start of the block
- */
- public Address getAddress(int index) {
- return start_.plus(index - firstIndex_ * blockSize_);
- }
-
- //--------------Accessors-------------------------
-
- /**
- * Get the start of the subspace
- * @return The start of this subspace
- */
- public Address getStart() { return start_; }
-
- /**
- * Get the end of this subspace
- * @return The address of the end of this subspace
- */
- public Address getEnd() { return end_; }
-
- /**
- * Get the first index of subspace
- * @return the firstIndex of this subspace
- */
- public int getFirstIndex() { return firstIndex_; }
-
- /**
- * Get the blocksize for this subspace
- * @return The size of a tile
- */
- public int getBlockSize() { return blockSize_; }
-
- /**
- * Get the number of tiles in this subspace
- * @return The number of tiles in this subspace
- */
- public int getBlockNum() { return blockNum_; }
-
- /**
- * Calculate the space remaining in a block after this address
- *
- * @param addr the Address
- * @return the remainder
- */
- public int spaceRemaining(Address addr) {
- int nextIndex = getIndex(addr) + 1;
- Address nextTile = start_.plus(blockSize_ * (nextIndex - firstIndex_));
- return nextTile.diff(addr).toInt();
- }
-
- /**
- * Dump a representation of the subspace
- */
- private void dump() {
- Log.write("GCspy Subspace: ");
- Util.dumpRange(start_, end_);
- Log.writeln("\n -- firstIndex=", firstIndex_);
- Log.writeln(" -- blockNum=", blockNum_);
- }
-}
-
-
diff --git a/vmkit/mmtk/java/src/org/mmtk/utility/gcspy/drivers/AbstractDriver.java b/vmkit/mmtk/java/src/org/mmtk/utility/gcspy/drivers/AbstractDriver.java
deleted file mode 100644
index dfca464..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/utility/gcspy/drivers/AbstractDriver.java
+++ /dev/null
@@ -1,502 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.utility.gcspy.drivers;
-
-import org.mmtk.policy.Space;
-import org.mmtk.utility.Log;
-import org.mmtk.utility.gcspy.GCspy;
-import org.mmtk.utility.gcspy.Subspace;
-import org.mmtk.vm.gcspy.ServerSpace;
-import org.mmtk.vm.gcspy.ServerInterpreter;
-import org.mmtk.vm.gcspy.Stream;
-import org.mmtk.vm.VM;
-
-import org.vmmagic.unboxed.*;
-import org.vmmagic.pragma.*;
-
-/**
- * Abstract GCspy driver for MMTk collectors.
- *
- * This class implements for the MMTk a base driver for a GCspy space.
- * All drivers for GCspy spaces should inherit from this class.
- */
-@Uninterruptible
-public abstract class AbstractDriver {
-
- /****************************************************************************
- *
- * Class variables
- */
-
- // Controls used for tile presentation
- /** The tile is used */
- protected static final byte CONTROL_USED = 1;
- /** The tile is a background tile */
- protected static final byte CONTROL_BACKGROUND = 2;
- /** The tile is unused */
- protected static final byte CONTROL_UNUSED = 4;
- /** The tile is a separator */
- protected static final byte CONTROL_SEPARATOR = 8;
- /** The tile is a link */
- protected static final byte CONTROL_LINK = 16;
-
-
- private static final int MAX_STREAMS = 64; // Max number of streams
-
- private static final boolean DEBUG = false;
- protected String myClass; // used in debugging messages
-
-
- /****************************************************************************
- *
- * Instance variables
- */
-
- /** The owning GCspy server */
- protected final ServerInterpreter server;
- /** The name of the GCspy space driver */
- protected final String name;
- /** The GCspy space abstraction */
- protected final ServerSpace serverSpace;
- /** The MMTK space */
- protected final Space mmtkSpace;
- /** The GCspy space's block size */
- protected int blockSize;
- /** The maximum number of tiles in this GCspy space */
- protected int maxTileNum;
- /** This space's streams */
- protected Stream[] streams;
- /** control values for tiles in this space */
- protected byte[] control;
- /** Has this space changed? */
- protected boolean changed = true;
-
-
- /**
- * Create a new driver for this collector.
- *
- * @param server The ServerInterpreter that owns this GCspy space.
- * @param name The name of this driver.
- * @param mmtkSpace The MMTk space represented by this driver.
- * @param blockSize The tile size.
- * @param mainSpace Is this the main space?
- */
- public AbstractDriver(ServerInterpreter server,
- String name,
- Space mmtkSpace,
- int blockSize,
- boolean mainSpace) {
- this.server = server;
- this.name = name;
- this.mmtkSpace = mmtkSpace;
- this.blockSize = blockSize;
- myClass = getClass().getName();
- maxTileNum = countTileNum(mmtkSpace.getExtent(), blockSize);
- control = (byte[])GCspy.util.createDataArray(new byte[0], maxTileNum);
- // to avoid allocation during GC we preallocate the streams array
- streams = new Stream[MAX_STREAMS];
- serverSpace = createServerSpace(server, name, maxTileNum, mainSpace);
- }
-
- /**
- * Create a subspace for this space.
- * Subspace provide useful facilities for contiguous spaces, even if
- * a space contains only one.
- * @param mmtkSpace The MMTk space
- */
- @Interruptible
- protected Subspace createSubspace(Space mmtkSpace) {
- Address start = mmtkSpace.getStart();
- return new Subspace(start, start, 0, blockSize, 0);
- }
-
- /**
- * Create a new GCspy ServerSpace and add it to the ServerInterpreter.
- * @param server the GCspy ServerInterpreter.
- * @param spaceName The name of this driver.
- * @param maxTileNum the maximum number of tiles in this space.
- * @param mainSpace Is this the main space?
- */
- @Interruptible
- protected ServerSpace createServerSpace(ServerInterpreter server,
- String spaceName,
- int maxTileNum,
- boolean mainSpace) {
- // Set the block label
- String tmp = "Block Size: " + ((blockSize < 1024) ?
- blockSize + " bytes\n":
- (blockSize / 1024) + " Kbytes\n");
-
- // Create a single GCspy Space
- return VM.newGCspyServerSpace(server, // the server
- spaceName, // space name
- getDriverName(), // driver (space) name
- "Block ", // space title
- tmp, // block info
- maxTileNum, // number of tiles
- "UNUSED", // the label for unused blocks
- mainSpace); // main space
- }
-
- /**
- * Get the name of this driver type.
- * @return The name of this driver.
- */
- protected abstract String getDriverName();
-
- /**
- * Get the maximum number of tiles in this space.
- * @return the maximum number of tiles in the space.
- */
- public int getMaxTileNum() {
- return maxTileNum;
- }
-
- /**
- * The GCspy space managed by this driver.
- * @return the GCspy server space.
- */
- public ServerSpace getServerSpace() { return serverSpace; }
-
- /**
- * Add a stream to the driver. This also sets the stream's id
- * (unique for this space).
- * @param stream The stream
- * @exception IndexOutOfBoundsException if more than MAX_STREAMS are added
- */
- @Interruptible
- public void addStream(Stream stream) {
- int id = 0;
- while (id < MAX_STREAMS) {
- if (streams[id] == null) {
- streams[id] = stream;
- if (DEBUG) { Log.write("Adding stream with id="); Log.writeln(id); }
- Address stream_ = serverSpace.addStream(id);
- stream.setStream(id, stream_);
- return;
- }
- id++;
- }
- throw new IndexOutOfBoundsException("Too many streams added to driver "+name);
- }
-
- /**
- * Count number of tiles in an address range.
- * @param start The start of the range.
- * @param end The end of the range.
- * @param tileSize The size of each tile.
- * @return The number of tiles in this range.
- */
- protected int countTileNum(Address start, Address end, int tileSize) {
- if (end.LE(start)) return 0;
- int diff = end.diff(start).toInt();
- return countTileNum(diff, tileSize);
- }
-
- /**
- * Count number of tiles in an address range.
- * @param extent The extent of the range.
- * @param tileSize The size of each tile.
- * @return The number of tiles in this range.
- */
- protected int countTileNum(Extent extent, int tileSize) {
- int diff = extent.toInt();
- return countTileNum(diff, tileSize);
- }
-
- private int countTileNum(int diff, int tileSize) {
- int tiles = diff / tileSize;
- if ((diff % tileSize) != 0)
- ++tiles;
- return tiles;
- }
-
- /**
- * Indicate the limits of a space.
- *
- * @param start the Address of the start of the space.
- * @param end the Address of the end of the space.
- */
- public void setRange(Address start, Address end) {}
-
- /**
- * Indicate the limits of a space.
- *
- * @param start the Address of the start of the space.
- * @param extent the extent of the space.
- */
- public void setRange(Address start, Extent extent) {
- setRange(start, start.plus(extent));
- }
-
- /**
- * Setup the tile names in a subspace. Tile names are typically
- * address ranges but may be anything (e.g. a size class if the
- * space is a segregated free-list manager, or a class name if the
- * space represents the class instances loaded).
- *
- * @param subspace the Subspace
- * @param numTiles the number of tiles to name
- */
- protected void setTilenames(Subspace subspace, int numTiles) {
- Address start = subspace.getStart();
- int first = subspace.getFirstIndex();
- int bs = subspace.getBlockSize();
-
- for (int i = 0; i < numTiles; ++i) {
- if (subspace.indexInRange(i))
- serverSpace.setTilename(i, start.plus((i - first) * bs),
- start.plus((i + 1 - first) * bs));
- }
- }
-
- /**
- * The "typical" maximum number of objects in each tile.
- * @param blockSize The size of a tile
- * @return The maximum number of objects in a tile
- */
- public int maxObjectsPerBlock(int blockSize) {
- // Maybe a misuse of ServerInterpreter but it's a convenient
- // VM-dependent class
- return blockSize / GCspy.server.computeHeaderSize();
- }
-
- /**
- * Is the server connected to a GCspy client?
- * @param event The current event
- */
- public boolean isConnected(int event) {
- return server.isConnected(event);
- }
-
- /**
- * Reset the statistics for a space.
- * In this base driver, we simply note that the data has changed.
- */
- protected void resetData() { changed = true; }
-
- /**
- * Scan an object found at a location.
- * Collectors typically call this method to update GCspy statistics.
- * The driver may or may not accumulate values found, depending on
- * the value of total.
- * @param obj the reference to the object found
- * @param total Whether to total the statistics
- */
- public void scan(ObjectReference obj, boolean total) {}
-
- /**
- * Scan an object found at a location.
- * Collectors typically call this method to update GCspy statistics
- * The driver will accumulate values found.
- * @param obj the reference to the object found
- */
- public void scan(ObjectReference obj) { scan(obj, true); }
-
- /**
- * Scan an object found at a location.
- * Collectors typically call this method to update GCspy statistics.
- * The driver may or may not accumulate values found, depending on
- * the value of total.
- * @param obj the reference to the object found
- * @param total Whether to total the statistics
- */
- public void scan(Address obj, boolean total) {}
-
- /**
- * Scan an object found at a location.
- * Collectors typically call this method to update GCspy statistics
- * The driver will accumulate values found.
- * @param obj the reference to the object found
- */
- public void scan(Address obj) {}
-
- /**
- * Handle a direct reference from the immortal space.<p>
- * This is an empty implementation. Subclasses may override this method
- * to increment their <code>refFromImmortal</code> Stream.
- *
- * @param addr The Address
- * @return true if the given Address is in this subspace. Always false here.
- */
- public boolean handleReferenceFromImmortalSpace(Address addr) {
- return false;
- }
-
- /**
- * Set space info.
- * This simply reports the size of the current space.
- * Drivers that want to send something more complex than
- * "Current Size: size\n"
- * must override this method.
- *
- * @param size the size of the space
- */
- protected void setSpaceInfo(Offset size) {
- // - sprintf(tmp, "Current Size: %s\n", gcspy_formatSize(size));
- Address tmp = GCspy.util.formatSize("Current Size: %s\n", 128, size.toInt());
- serverSpace.spaceInfo(tmp);
- GCspy.util.free(tmp);
- }
-
-
- /****************************************************************************
- *
- * Control values
- */
-
- /**
- * Is a tile used?
- * @param val the control value.
- * @return true if the tile is used
- */
- protected static boolean controlIsUsed(byte val) {
- return (val & CONTROL_USED) != 0;
- }
-
- /**
- * Is a tile a background pseudo-tile?
- * @param val the control value.
- * @return true if the tile is a background tile
- */
- protected static boolean controlIsBackground(byte val) {
- return (val & CONTROL_BACKGROUND) != 0;
- }
-
- /**
- * Is a tile unused?
- * @param val the control value.
- * @return true if the tile is unused
- */
- protected static boolean controlIsUnused(byte val) {
- return (val & CONTROL_UNUSED) != 0;
- }
-
- /**
- * Is this a separator?
- * @param val the control value.
- * @return true if this is a separator
- */
- protected static boolean controlIsSeparator(byte val) {
- return (val & CONTROL_SEPARATOR) != 0;
- }
-
- /**
- * Initialise the value of a control.
- * @param index The index of the tile.
- * @param value The new value of the control
- */
- protected void initControl(int index, byte value) {
- control[index] = value;
- }
-
- /**
- * Add a control to the tile
- * @param index The index of the tile.
- * @param value The control to add.
- */
- protected void addControl(int index, byte value) {
- control[index] |= value;
- }
-
- /** Set the control
- * @param value The value to set
- */
- protected void setControl(int index, byte value) {
- control[index] &= value;
- }
-
- /**
- * Get the controls for a tile.
- * @param index The index of the tile.
- * @return The value of the controls
- */
- public byte getControl(int index) {
- return control[index];
- }
-
- /**
- * Initialise control values in all tiles
- */
- protected void initControls() {
- for (int index = 0; index < control.length; ++index) {
- initControl(index, CONTROL_USED);
- }
- }
-
- /**
- * Set the control value in each tile in a region.
- * @param tag The control tag.
- * @param start The start index of the region.
- * @param len The number of tiles in the region.
- */
- protected void controlValues(byte tag, int start, int len) {
- if (DEBUG) {
- Log.write("AbstractDriver.controlValues for space ");
- Log.write(name);
- Log.write(", control length=", control.length);
- Log.write(" writing controls from ", start);
- Log.writeln(" to ", start + len);
- }
- changed = true;
- for (int i = start; i < (start+len); ++i) {
- // Cannot be both USED and UNUSED or BACKGROUND
- if (controlIsBackground(tag) || controlIsUnused(tag))
- setControl(i, (byte)~CONTROL_USED);
- else if (controlIsUsed(tag))
- setControl(i, (byte)~CONTROL_UNUSED);
- addControl(i, tag);
- }
- }
-
- /**
- * Transmit the streams for this space. A driver will typically
- * <ol>
- * <li> Determine whether a GCspy client is connected and interested in
- * this event, e.g.
- * <pre>server.isConnected(event)</pre>
- * <li> Setup the summaries for each stream, e.g.
- * <pre>stream.setSummary(values...);</pre>
- * <li> Setup the control information for each tile. e.g.
- * <pre>controlValues(CONTROL_USED, start, numBlocks);</pre>
- * <pre>controlValues(CONTROL_UNUSED, end, remainingBlocks);</pre>
- * <li> Set up the space information, e.g.
- * <pre>setSpace(info);</pre>
- * <li> Send the data for all streams, e.g.
- * <pre>send(event, numTiles);</pre>
- * Note that AbstractDriver.send takes care of sending the information
- * for all streams (including control data).
- *
- * @param event The event
- */
- public abstract void transmit(int event);
-
- /**
- * Send all the streams for this space if it has changed.
- * Assume that the data has been gathered and that summary info
- * and control values have been set before this is called.
- *
- * @param event the event
- * @param numTiles the number of blocks in this space
- */
- protected void send(int event, int numTiles) {
- if (changed) {
- serverSpace.startCommunication();
- for (int i = 0; i < MAX_STREAMS; i++)
- if (streams[i] != null)
- streams[i].send(event, numTiles);
- serverSpace.sendControls(this, numTiles);
- serverSpace.endCommunication();
- }
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/utility/gcspy/drivers/GenImmortalSpaceDriver.java b/vmkit/mmtk/java/src/org/mmtk/utility/gcspy/drivers/GenImmortalSpaceDriver.java
deleted file mode 100644
index 8a4761f..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/utility/gcspy/drivers/GenImmortalSpaceDriver.java
+++ /dev/null
@@ -1,144 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.utility.gcspy.drivers;
-
-import org.mmtk.policy.Space;
-
-import org.mmtk.utility.gcspy.Color;
-import org.mmtk.utility.gcspy.StreamConstants;
-import org.mmtk.vm.VM;
-import org.mmtk.vm.gcspy.ShortStream;
-
-import org.mmtk.utility.Log;
-import org.mmtk.vm.gcspy.ServerInterpreter;
-
-import org.vmmagic.unboxed.*;
-import org.vmmagic.pragma.*;
-
-/**
- * GCspy driver for the MMTk generational immortal space.
- * Additional Stream for remset references.
- * This class extends ImmortalSpaceDriver, a simple driver for
- * the contiguous MMTk ImmortalSpace.
- */
-@Uninterruptible public class GenImmortalSpaceDriver extends ImmortalSpaceDriver {
-
- private static final boolean DEBUG = false;
-
- // The Stream for newly promoted objects
- protected ShortStream remsetStream;
- // Statistics for remset references
- protected int totalRemset = 0;
-
-
- /**
- * Create a new driver for a generational immortal space.
- *
- * @param server The GCspy ServerInterpreter
- * @param spaceName The name of this GCspy space
- * @param mmtkSpace The MMTk space
- * @param blockSize The tile size
- * @param mainSpace Is this the main space?
- */
- public GenImmortalSpaceDriver(
- ServerInterpreter server,
- String spaceName,
- Space mmtkSpace,
- int blockSize,
- boolean mainSpace) {
-
- super(server, spaceName, mmtkSpace, blockSize, mainSpace);
-
- // create additional stream
- remsetStream = createRemsetStream();
-
- if (DEBUG) {
- Log.write("GenImmortalSpaceDriver for "); Log.write(spaceName);
- Log.write(", blocksize="); Log.write(blockSize);
- Log.write(", start="); Log.write(mmtkSpace.getStart());
- Log.write(", extent="); Log.write(mmtkSpace.getExtent());
- Log.write(", maxTileNum="); Log.writeln(maxTileNum);
- }
-
- resetData();
- }
-
- /**
- * Get the name of this driver type.
- * @return The name, "MMTk GenImmortalSpaceDriver" for this driver.
- */
- protected String getDriverName() {
- return "MMTk GenImmortalSpaceDriver";
- }
-
- /**
- * Heelper methods to create the additional streams
- */
- @Interruptible
- private ShortStream createRemsetStream() {
- return VM.newGCspyShortStream(
- this,
- "Remembered set stream",
- (short)0,
- // Say, typical size = 4 * typical scalar size?
- (short)(maxObjectsPerBlock(blockSize)/8),
- (short)0,
- (short)0,
- "Remset references: ",
- " references",
- StreamConstants.PRESENTATION_PLUS,
- StreamConstants.PAINT_STYLE_ZERO,
- 0,
- Color.Cyan,
- true);
- }
-
- /**
- * Setup summaries part of the <code>transmit</code> method.<p>
- * Overrides method in superclass to handle additional Stream.
- */
- protected void setupSummaries() {
- super.setupSummaries();
- remsetStream.setSummary(totalRemset);
- }
-
- /**
- * Handle a remset address
- *
- * @param addr Remset Address
- * @return true if the given Address is in this subspace.
- */
- public boolean handleRemsetAddress(Address addr) {
- if(subspace.addressInRange(addr)) {
- // increment tile
- int index = subspace.getIndex(addr);
- remsetStream.increment(index, (short)1);
- // increment summary
- totalRemset++;
- return true;
- } else {
- return false;
- }
- }
-
- /**
- * Reset the remset Stream
- * The remset Stream has to be reset seperately because we do not
- * gather data in the usual way using scan().
- */
- public void resetRemsetStream() {
- remsetStream.resetData();
- totalRemset = 0;
- }
-
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/utility/gcspy/drivers/GenLOSDriver.java b/vmkit/mmtk/java/src/org/mmtk/utility/gcspy/drivers/GenLOSDriver.java
deleted file mode 100644
index 432d874..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/utility/gcspy/drivers/GenLOSDriver.java
+++ /dev/null
@@ -1,132 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.utility.gcspy.drivers;
-
-import org.mmtk.utility.gcspy.Color;
-import org.mmtk.utility.gcspy.StreamConstants;
-import org.mmtk.vm.VM;
-import org.mmtk.vm.gcspy.ShortStream;
-import org.mmtk.vm.gcspy.ServerInterpreter;
-
-import org.mmtk.policy.LargeObjectSpace;
-
-import org.vmmagic.unboxed.*;
-import org.vmmagic.pragma.*;
-
-
-/**
- * This class extends a simple driver for the MMTk LargeObjectSpace
- * for Generational Collectors.
- */
-@Uninterruptible public class GenLOSDriver extends TreadmillDriver {
-
- private static final boolean DEBUG = false;
-
- // The additional remset stream
- protected ShortStream remsetStream;
- // Additional overall statistic
- protected int totalRemset = 0; // total of remset Addresses
-
-
- /**
- * Create a new driver for this collector
- *
- * @param server The name of the GCspy server that owns this space
- * @param spaceName The name of this driver
- * @param lospace the large object space for this allocator
- * @param blockSize The tile size
- * @param threshold the size threshold of the LOS
- * @param mainSpace Is this the main space?
- */
- public GenLOSDriver(ServerInterpreter server,
- String spaceName,
- LargeObjectSpace lospace,
- int blockSize,
- int threshold,
- boolean mainSpace) {
- //TODO blocksize should be a multiple of treadmill granularity
- super(server, spaceName, lospace, blockSize, threshold, mainSpace);
- // create remset stream
- remsetStream = createRemsetStream();
- // Initialise the statistics
- resetData();
- }
-
- /**
- * Get the name of this driver type.
- * @return The name, "MMTk GenLOSDriver" for this driver.
- */
- protected String getDriverName() {
- return "MMTk GenLOSDriver";
- }
-
- // private creator methods for the streams
- @Interruptible
- private ShortStream createRemsetStream() {
- return VM.newGCspyShortStream(
- this,
- "Remembered set stream",
- (short)0,
- // Say, typical size = 4 * typical scalar size?
- (short)(maxObjectsPerBlock(blockSize)/8),
- (short)0,
- (short)0,
- "Remset references: ",
- " references",
- StreamConstants.PRESENTATION_PLUS,
- StreamConstants.PAINT_STYLE_ZERO,
- 0,
- Color.Cyan,
- true);
- }
-
- /**
- * Setup summaries part of the <code>transmit</code> method.<p>
- * Overrides <code>transmitSetupSummaries </code> of superclass to
- * handle additional streams.
- */
- protected void setupSummaries() {
- super.setupSummaries();
- remsetStream.setSummary(totalRemset);
- }
-
- /**
- * Handle a remset address.
- *
- * @param addr Remset Address
- * @return true if the given Address is in this subspace.
- */
- public boolean handleRemsetAddress(Address addr) {
- if(subspace.addressInRange(addr)) {
- // increment tile
- int index = subspace.getIndex(addr);
- remsetStream.increment(index, (short)1);
- // increment summary
- this.totalRemset++;
- return true;
- } else {
- return false;
- }
- }
-
- /**
- * Reset the remset Stream. <p>
- * The remset Stream has to be reset seperately because we do not
- * gather data in the usual way using <code>scan()</code>.
- */
- public void resetRemsetStream() {
- remsetStream.resetData();
- totalRemset = 0;
- }
-
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/utility/gcspy/drivers/ImmortalSpaceDriver.java b/vmkit/mmtk/java/src/org/mmtk/utility/gcspy/drivers/ImmortalSpaceDriver.java
deleted file mode 100644
index 64df4f6..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/utility/gcspy/drivers/ImmortalSpaceDriver.java
+++ /dev/null
@@ -1,123 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.utility.gcspy.drivers;
-
-import org.mmtk.plan.TransitiveClosure;
-import org.mmtk.policy.Space;
-import org.mmtk.utility.Log;
-import org.mmtk.vm.gcspy.ServerInterpreter;
-import org.mmtk.vm.VM;
-
-import org.vmmagic.unboxed.*;
-import org.vmmagic.pragma.*;
-
-/**
- * GCspy driver for the contiguous MMTk ImmortalSpace.
- * Adds features for the Immortal space.
- * <p>
- *
- * This class extends LinearSpaceDriver, a simple driver for contiguous MMTk spaces
- * such as CopySpace and ImmortalSpace.
- */
-@Uninterruptible public class ImmortalSpaceDriver extends LinearSpaceDriver {
-
- private static final boolean DEBUG = false;
-
- // Instance variables
- private AbstractDriver[] registeredDrivers;
- private ImmortalSpaceDriver.Closure closure;
-
- /**
- * Create a new driver for an immortal Contiguous MMTk space.
- *
- * @param server The GCspy ServerInterpreter
- * @param spaceName The name of this GCspy space
- * @param mmtkSpace The MMTk space
- * @param blockSize The tile size
- * @param mainSpace Is this the main space?
- */
- public ImmortalSpaceDriver(
- ServerInterpreter server,
- String spaceName,
- Space mmtkSpace,
- int blockSize,
- boolean mainSpace) {
-
- super(server, spaceName, mmtkSpace, blockSize, mainSpace);
-
- if (DEBUG) {
- Log.write("ImmortalSpaceDriver for "); Log.write(spaceName);
- Log.write(", blocksize="); Log.write(blockSize);
- Log.write(", start="); Log.write(mmtkSpace.getStart());
- Log.write(", extent="); Log.write(mmtkSpace.getExtent());
- Log.write(", maxTileNum="); Log.writeln(maxTileNum);
- }
-
- // initially no registered drivers for reference notification
- registeredDrivers = new AbstractDriver[0];
-
- closure = new ImmortalSpaceDriver.Closure();
- }
-
- /**
- * Get the name of this driver type.
- * @return The name, "MMTk ImmortalSpaceDriver" for this driver.
- */
- protected String getDriverName() {
- return "MMTk ImmortalSpaceDriver";
- }
-
- /**
- * Update the tile statistics. <br>
- * This method overrides <code> scan </code> iin its superclass to
- * add immortal space features.
- *
- * @param object The current object
- * @param total Whether to accumulate the values
- */
- public void scan(ObjectReference object, boolean total) {
- Address addr = object.toAddress();
-
- if (subspace.addressInRange(addr)) {
- VM.scanning.scanObject(closure, object);
- super.scan(object, total);
- }
- }
-
- /**
- * Register a set of AbstractDriver instances to be notified about direct references.
- *
- * @param drivers The array of driver objects.
- */
- public void registerDriversForReferenceNotification(AbstractDriver[] drivers) {
- this.registeredDrivers = drivers;
- }
-
- /**
- * Used to visit the edges in the immortal object.
- */
- @Uninterruptible
- private class Closure extends TransitiveClosure {
- /**
- * Process an edge.
- */
- public void processEdge(ObjectReference source, Address slot) {
- // Address in Range, locate references
- Address target = slot.loadAddress();
- // notify registered drivers
- for (int j = 0; j < registeredDrivers.length; j++) {
- registeredDrivers[j].handleReferenceFromImmortalSpace(target);
- }
- }
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/utility/gcspy/drivers/LinearSpaceDriver.java b/vmkit/mmtk/java/src/org/mmtk/utility/gcspy/drivers/LinearSpaceDriver.java
deleted file mode 100644
index c321dbd..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/utility/gcspy/drivers/LinearSpaceDriver.java
+++ /dev/null
@@ -1,508 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.utility.gcspy.drivers;
-
-import org.mmtk.policy.Space;
-import org.mmtk.utility.gcspy.Color;
-import org.mmtk.utility.gcspy.LinearScan;
-import org.mmtk.utility.gcspy.StreamConstants;
-import org.mmtk.utility.gcspy.Subspace;
-import org.mmtk.vm.gcspy.IntStream;
-import org.mmtk.vm.gcspy.ShortStream;
-
-import org.mmtk.utility.Log;
-import org.mmtk.vm.gcspy.ServerInterpreter;
-import org.mmtk.vm.VM;
-
-import org.vmmagic.unboxed.*;
-import org.vmmagic.pragma.*;
-
-/**
- * GCspy driver for the MMTk ContigousSpace.
- *
- * This class implements a simple driver for contiguous MMTk spaces
- * such as CopySpace and ImmortalSpace.
- */
-@Uninterruptible public class LinearSpaceDriver extends AbstractDriver {
-
- // The GCspy streams
- protected IntStream scalarUsedSpaceStream;
- protected IntStream arrayUsedSpaceStream;
- protected ShortStream scalarObjectsStream;
- protected ShortStream arrayObjectsStream;
- protected ShortStream arrayPrimitiveStream;
- protected ShortStream rootsStream;
- protected ShortStream refFromImmortalStream;
-
- protected Subspace subspace; // A subspace for all of this space
- protected int allTileNum; // total number of tiles
-
- // Overall statistics
- protected int totalScalarObjects = 0; // total number of objects allocated
- protected int totalArrayObjects = 0;
- protected int totalPrimitives = 0;
- protected int totalScalarUsedSpace = 0; // total space used
- protected int totalArrayUsedSpace = 0;
- protected int totalRoots = 0;
- protected int totalRefFromImmortal = 0;
-
- private final LinearScan scanner; // A scanner to trace objects
-
- // Debugging
- protected Address lastAddress = Address.zero();
- protected int lastSize = 0;
- private static final boolean DEBUG = false;
-
-
- /**
- * Create a new driver for a contiguous MMTk space.
- *
- * @param server The GCspy ServerInterpreter
- * @param spaceName The name of this GCspy space
- * @param mmtkSpace The MMTk space
- * @param blockSize The tile size
- * @param mainSpace Is this the main space?
- */
- public LinearSpaceDriver(ServerInterpreter server,
- String spaceName,
- Space mmtkSpace,
- int blockSize,
- boolean mainSpace) {
-
- super(server, spaceName, mmtkSpace, blockSize, mainSpace);
-
- if (DEBUG) {
- Log.write("LinearSpaceDriver for "); Log.write(spaceName);
- Log.write(", blocksize="); Log.write(blockSize);
- Log.write(", start="); Log.write(mmtkSpace.getStart());
- Log.write(", extent="); Log.write(mmtkSpace.getExtent());
- Log.write(", maxTileNum="); Log.writeln(maxTileNum);
- }
-
- // Initialise a subspace and 4 Streams
- subspace = createSubspace(mmtkSpace);
- allTileNum = 0;
- scalarUsedSpaceStream = createScalarUsedSpaceStream();
- arrayUsedSpaceStream = createArrayUsedSpaceStream();
- scalarObjectsStream = createScalarObjectsStream();
- arrayPrimitiveStream = createArrayPrimitiveStream();
- arrayObjectsStream = createArrayObjectsStream();
- rootsStream = createRootsStream();
- refFromImmortalStream = createRefFromImmortalStream();
- serverSpace.resize(0); // the collector must call resize() before gathering data
-
- // Initialise the statistics
- resetData();
- scanner = new LinearScan(this);
- }
-
- /**
- * Get the name of this driver type.
- * @return The name of this driver.
- */
- protected String getDriverName() { return "MMTk LinearSpaceDriver"; }
-
- /**
- * Private creator methods to create the Streams.
- */
- @Interruptible
- private IntStream createScalarUsedSpaceStream() {
- return VM.newGCspyIntStream(
- this,
- "Scalar Used Space stream", // stream name
- 0, // min. data value
- blockSize, // max. data value
- 0, // zero value
- 0, // default value
- "Scalars and primitive arrays: ", // value prefix
- " bytes", // value suffix
- StreamConstants.PRESENTATION_PERCENT, // presentation style
- StreamConstants.PAINT_STYLE_ZERO, // paint style
- 0, // index of max stream (only needed if the presentation is *_VAR)
- Color.Red, // tile colour
- true); // summary enabled
- }
-
- @Interruptible
- private IntStream createArrayUsedSpaceStream() {
- return VM.newGCspyIntStream(
- this,
- "Array Used Space stream",
- 0,
- blockSize,
- 0,
- 0,
- "Reference arrays: ",
- " bytes",
- StreamConstants.PRESENTATION_PERCENT,
- StreamConstants.PAINT_STYLE_ZERO,
- 0,
- Color.Blue,
- true);
- }
-
- @Interruptible
- private ShortStream createScalarObjectsStream() {
- return VM.newGCspyShortStream(
- this,
- "Scalar Objects stream",
- (short)0,
- // Say, max value = 50% of max possible
- (short)(maxObjectsPerBlock(blockSize)/2),
- (short)0,
- (short)0,
- "Scalars: ",
- " objects",
- StreamConstants.PRESENTATION_PLUS,
- StreamConstants.PAINT_STYLE_ZERO,
- 0,
- Color.Green,
- true);
- }
-
- @Interruptible
- private ShortStream createArrayPrimitiveStream() {
- return VM.newGCspyShortStream(
- this,
- "Array Primitive stream",
- (short)0,
- // Say, typical primitive array size = 4 * typical scalar size?
- (short)(maxObjectsPerBlock(blockSize)/8),
- (short)0,
- (short)0,
- "Primitive arrays: ",
- " objects",
- StreamConstants.PRESENTATION_PLUS,
- StreamConstants.PAINT_STYLE_ZERO,
- 0,
- Color.Yellow,
- true);
- }
-
- @Interruptible
- private ShortStream createArrayObjectsStream() {
- return VM.newGCspyShortStream(
- this,
- "Array Objects stream",
- (short)0,
- // Say, typical ref array size = 4 * typical scalar size?
- (short)(maxObjectsPerBlock(blockSize)/8),
- (short)0,
- (short)0,
- "Reference arrays: ",
- " objects",
- StreamConstants.PRESENTATION_PLUS,
- StreamConstants.PAINT_STYLE_ZERO,
- 0,
- Color.Cyan,
- true);
- }
-
- @Interruptible
- private ShortStream createRootsStream() {
- return VM.newGCspyShortStream(
- this,
- "Roots stream",
- (short)0,
- // Say, typical size = 4 * typical scalar size?
- (short)(maxObjectsPerBlock(blockSize)/8),
- (short)0,
- (short)0,
- "Roots: ",
- " objects",
- StreamConstants.PRESENTATION_PLUS,
- StreamConstants.PAINT_STYLE_ZERO,
- 0,
- Color.Blue,
- true);
- }
-
- @Interruptible
- private ShortStream createRefFromImmortalStream() {
- return VM.newGCspyShortStream(
- this,
- "References from immortal stream",
- (short)0,
- // Say, typical size = 4 * typical scalar size?
- (short)(maxObjectsPerBlock(blockSize)/8),
- (short)0,
- (short)0,
- "References from immortal space: ",
- " references",
- StreamConstants.PRESENTATION_PLUS,
- StreamConstants.PAINT_STYLE_ZERO,
- 0,
- Color.Blue,
- true);
- }
-
- /**
- * Reset the statistics for all the streams, including totals used for summaries
- */
- public void resetData() {
- super.resetData();
-
- // Reset all the streams
- scalarUsedSpaceStream.resetData();
- arrayUsedSpaceStream.resetData();
- scalarObjectsStream.resetData();
- arrayObjectsStream.resetData();
- arrayPrimitiveStream.resetData();
- refFromImmortalStream.resetData();
-
- // Reset the summary counts
- totalScalarObjects = 0;
- totalArrayObjects = 0;
- totalPrimitives = 0;
- totalScalarUsedSpace = 0;
- totalArrayUsedSpace = 0;
- totalRefFromImmortal = 0;
- }
-
- /**
- * BumpPointer.linearScan needs a LinearScan object, which we provide here.
- * @return the scanner for this driver
- */
- public LinearScan getScanner() { return scanner; }
-
- /**
- * Set the current address range of a contiguous space
- * @param start the start of the contiguous space
- * @param end the end of the contiguous space
- */
- public void setRange(Address start, Address end) {
- int current = subspace.getBlockNum();
- int required = countTileNum(start, end, subspace.getBlockSize());
-
- // Reset the subspace
- if(required != current)
- subspace.reset(start, end, 0, required);
-
- if (DEBUG) {
- Log.write("\nContiguousSpaceDriver.setRange for contiguous space: ");
- Log.write(subspace.getFirstIndex()); Log.write("-", subspace.getBlockNum());
- Log.write(" (", start); Log.write("-", end); Log.write(")");
- }
-
- // Reset the driver
- // Note release() only resets a CopySpace's cursor (and optionally zeroes
- // or mprotects the pages); it doesn't make the pages available to other
- // spaces. If pages were to be released, change the test here to
- // if (allTileNum != required) {
- if (allTileNum < required) {
- if (DEBUG) { Log.write(", resize from ", allTileNum); Log.write(" to ", required); }
- allTileNum = required;
- serverSpace.resize(allTileNum);
- setTilenames(subspace, allTileNum);
- }
- if (DEBUG) Log.writeln();
- }
-
-
- /**
- * Update the tile statistics
- * @param obj The current object
- */
- public void scan(ObjectReference obj) {
- scan(obj, true);
- }
-
- /**
- * Update the tile statistics
- * @param obj The current object
- * @param total Whether to accumulate the values
- */
- public void scan(ObjectReference obj, boolean total) {
- boolean isArray = VM.objectModel.isArray(obj);
- int length = VM.objectModel.getCurrentSize(obj);
- Address addr = obj.toAddress();
-
- if (VM.VERIFY_ASSERTIONS) {
- if(addr.LT(lastAddress.plus(lastSize))) {
- Log.write("\nContiguousSpaceDriver finds addresses going backwards: ");
- Log.write("last="); Log.write(lastAddress);
- Log.write(" last size="); Log.write(lastSize);
- Log.writeln(" current=", addr);
- }
- lastAddress = addr;
- lastSize = length;
- }
-
- // Update the stats
- if (subspace.addressInRange(addr)) {
- int index = subspace.getIndex(addr);
- int remainder = subspace.spaceRemaining(addr);
- if (isArray) {
- arrayObjectsStream.increment(index, (short)1);
- arrayUsedSpaceStream.distribute(index, remainder, blockSize, length);
- if (total) {
- totalArrayObjects++;
- totalArrayUsedSpace += length;
- }
- } else {
- if(!this.scanCheckPrimitiveArray(obj, index, total, length)) {
- // real object
- scalarObjectsStream.increment(index, (short)1);
- if (total) {
- totalScalarObjects++;
- totalScalarUsedSpace += length;
- }
- }
- scalarUsedSpaceStream.distribute(index, remainder, blockSize, length);
- }
- }
- }
-
- /**
- * Check if this Object is an array of primitives.<br>
- * Part of the public scan() method.
- *
- * @param obj The Object to check
- * @param index Index of the tile
- * @param total Increment summary
- * @param length Current size of the Object, will be added to array space summary.
- * @return True if this Object is an array of primitives.
- */
- protected boolean scanCheckPrimitiveArray(ObjectReference obj, int index, boolean total, int length) {
- if(VM.objectModel.isPrimitiveArray(obj)) {
- arrayPrimitiveStream.increment(index, (short)1);
- if (total) {
- totalPrimitives++;
- totalScalarUsedSpace += length;
- }
- return true;
- } else {
- return false;
- }
- }
-
- /**
- * Transmit the data if this event is of interest to the client.<p>
- * Implemented using the algorithm pattern, subclasses can override parts of it.
- * @param event The event, defined in the Plan
- */
- public void transmit(int event) {
- if (!server.isConnected(event))
- return;
-
- if (DEBUG) {
- Log.write("CONNECTED\n");
- Log.write(myClass);
- Log.write(".send: numTiles=", allTileNum);
- //Log.write("LinearSpaceDriver.transmit: numTiles=", allTileNum);
- Log.writeln(", control.length=", control.length);
- Log.flush();
- }
-
- // Setup the summaries
- setupSummaries();
-
- // Setup the control info
- setupControlInfo();
-
- // Setup the space info
- Offset size = subspace.getEnd().diff(subspace.getStart());
- setSpaceInfo(size);
-
- // Send the all streams
- send(event, allTileNum);
-
- // Debugging
- if (VM.VERIFY_ASSERTIONS) {
- lastAddress = Address.zero();
- lastSize = 0;
- }
- }
-
- /**
- * Setup summaries part of the <code>transmit</code> method.<p>
- * Override this method to setup summaries of additional streams in subclasses.
- */
- protected void setupSummaries() {
- scalarUsedSpaceStream.setSummary(totalScalarUsedSpace,
- subspace.getEnd().diff(subspace.getStart()).toInt());
- arrayUsedSpaceStream.setSummary(totalArrayUsedSpace,
- subspace.getEnd().diff(subspace.getStart()).toInt());
- scalarObjectsStream.setSummary(totalScalarObjects);
- arrayObjectsStream.setSummary(totalArrayObjects);
- arrayPrimitiveStream.setSummary(totalPrimitives);
- rootsStream.setSummary(totalRoots);
- refFromImmortalStream.setSummary(totalRefFromImmortal);
- }
-
- /**
- * Setup control info part of the <code>transmit</code> method.<p>
- * Override this method to change the controls for your own driver subclass.
- */
- protected void setupControlInfo() {
- int numBlocks = subspace.getBlockNum();
- controlValues(CONTROL_USED, subspace.getFirstIndex(), numBlocks);
- if (DEBUG) {
- Log.write("LinearSpaceDriver.transmitSetupControlInfo: allTileNum=", allTileNum);
- Log.writeln(", numBlocks=", numBlocks);
- }
- if (numBlocks < allTileNum)
- controlValues(CONTROL_UNUSED,
- subspace.getFirstIndex() + numBlocks,
- allTileNum - numBlocks);
- }
-
- /**
- * Handle a root address
- *
- * @param addr Root Address
- * @return true if the given Address is in this subspace.
- */
- public boolean handleRoot(Address addr) {
- if(subspace.addressInRange(addr)) {
- // increment tile
- int index = subspace.getIndex(addr);
- rootsStream.increment(index, (short)1);
- // increment summary
- this.totalRoots++;
- return true;
- } else {
- return false;
- }
- }
-
- /**
- * Reset the roots Stream
- * The roots Stream has to be reset seperately because we do not
- * gather data in the usual way using <code>scan()</code>.
- */
- public void resetRootsStream() {
- rootsStream.resetData();
- totalRoots = 0;
- }
-
- /**
- * Handle a direct reference from the immortal space.
- *
- * @param addr The Address
- * @return true if the given Address is in this subspace.
- */
- public boolean handleReferenceFromImmortalSpace(Address addr) {
- if(subspace.addressInRange(addr)) {
- // increment tile
- int index = subspace.getIndex(addr);
- refFromImmortalStream.increment(index, (short)1);
- // increment summary
- this.totalRefFromImmortal++;
- return true;
- } else {
- return false;
- }
- }
-
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/utility/gcspy/drivers/TreadmillDriver.java b/vmkit/mmtk/java/src/org/mmtk/utility/gcspy/drivers/TreadmillDriver.java
deleted file mode 100644
index 2cfe81a..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/utility/gcspy/drivers/TreadmillDriver.java
+++ /dev/null
@@ -1,326 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.utility.gcspy.drivers;
-
-import org.mmtk.policy.LargeObjectSpace;
-import org.mmtk.utility.gcspy.Color;
-import org.mmtk.utility.gcspy.StreamConstants;
-import org.mmtk.utility.gcspy.Subspace;
-import org.mmtk.vm.gcspy.IntStream;
-import org.mmtk.vm.gcspy.ShortStream;
-import org.mmtk.vm.gcspy.ServerInterpreter;
-import org.mmtk.utility.Conversions;
-import org.mmtk.utility.Log;
-import org.mmtk.vm.VM;
-
-import org.vmmagic.unboxed.*;
-import org.vmmagic.pragma.*;
-
-
-/**
- * This class implements a simple driver for the MMTk LargeObjectSpace.
- */
-@Uninterruptible public class TreadmillDriver extends AbstractDriver {
-
- private static final boolean DEBUG = false;
-
- // The streams
- protected IntStream usedSpaceStream;
- protected ShortStream objectsStream;
- protected ShortStream rootsStream;
- protected ShortStream refFromImmortalStream;
-
- protected Subspace subspace; // A single subspace for this space
- protected int allTileNum; // total number of tiles
-
- // Overall statistics
- protected int totalObjects = 0; // total number of objects allocated
- protected int totalUsedSpace = 0; // total space used
- protected int totalRoots = 0; // total of roots
- protected int totalRefFromImmortal = 0; // total direct references from the immortal space
- protected Address maxAddr; // the largest address seen
- protected int threshold;
-
-
- /**
- * Create a new driver for this collector
- *
- * @param server The name of the GCspy server that owns this space
- * @param spaceName The name of this driver
- * @param lospace the large object space for this allocator
- * @param blockSize The tile size
- * @param threshold the size threshold of the LOS
- * @param mainSpace Is this the main space?
- */
- public TreadmillDriver(
- ServerInterpreter server,
- String spaceName,
- LargeObjectSpace lospace,
- int blockSize,
- int threshold,
- boolean mainSpace) {
- //TODO blocksize should be a multiple of treadmill granularity
- super(server, spaceName, lospace, blockSize, mainSpace);
-
- if (DEBUG) {
- Log.write("TreadmillDriver for "); Log.write(spaceName);
- Log.write(", blocksize="); Log.write(blockSize);
- Log.write(", start="); Log.write(lospace.getStart());
- Log.write(", extent="); Log.write(lospace.getExtent());
- Log.write(", maxTileNum="); Log.writeln(maxTileNum);
- }
-
- this.threshold = threshold;
-
- // Initialise a subspace and 2 Streams
- subspace = createSubspace(lospace);
- allTileNum = 0;
- maxAddr = lospace.getStart();
- usedSpaceStream = createUsedSpaceStream();
- objectsStream = createObjectsStream();
- rootsStream = createRootsStream();
- refFromImmortalStream = createRefFromImmortalStream();
- serverSpace.resize(0); // the collector must call resize() before gathering data
-
- // Initialise the statistics
- resetData();
- }
-
- /**
- * Get the name of this driver type.
- * @return The name, "MMTk TreadmillDriver" for this driver.
- */
- protected String getDriverName() {
- return "MMTk TreadmillDriver";
- }
-
- // private creator methods for the streams
- @Interruptible
- private IntStream createUsedSpaceStream() {
- return VM.newGCspyIntStream(
- this,
- "Used Space stream", // stream name
- 0, // min. data value
- blockSize, // max. data value
- 0, // zero value
- 0, // default value
- "Space used: ", // value prefix
- " bytes", // value suffix
- StreamConstants.PRESENTATION_PERCENT, // presentation style
- StreamConstants.PAINT_STYLE_ZERO, // paint style
- 0, // index of the max stream (only needed if presentation is *_VAR)
- Color.Red, // tile colour
- true); // summary enabled
- }
-
- @Interruptible
- private ShortStream createObjectsStream() {
- return VM.newGCspyShortStream(
- this,
- "Objects stream",
- (short)0,
- (short)(blockSize/threshold),
- (short)0,
- (short)0,
- "No. of objects = ",
- " objects",
- StreamConstants.PRESENTATION_PLUS,
- StreamConstants.PAINT_STYLE_ZERO,
- 0,
- Color.Green,
- true);
- }
-
- @Interruptible
- private ShortStream createRootsStream() {
- return VM.newGCspyShortStream(
- this,
- "Roots stream",
- (short)0,
- // Say, typical size = 4 * typical scalar size?
- (short)(maxObjectsPerBlock(blockSize)/8),
- (short)0,
- (short)0,
- "Roots: ",
- " objects",
- StreamConstants.PRESENTATION_PLUS,
- StreamConstants.PAINT_STYLE_ZERO,
- 0,
- Color.Blue,
- true);
- }
-
- @Interruptible
- private ShortStream createRefFromImmortalStream() {
- return VM.newGCspyShortStream(
- this,
- "References from Immortal stream",
- (short)0,
- // Say, typical size = 4 * typical scalar size?
- (short)(maxObjectsPerBlock(blockSize)/8),
- (short)0,
- (short)0,
- "References from immortal space: ",
- " references",
- StreamConstants.PRESENTATION_PLUS,
- StreamConstants.PAINT_STYLE_ZERO,
- 0,
- Color.Blue,
- true);
- }
-
- /**
- * Reset the tile stats for all streams, including values used for summaries
- */
- public void resetData() {
- super.resetData();
-
- // Reset all the streams
- usedSpaceStream.resetData();
- objectsStream.resetData();
- refFromImmortalStream.resetData();
-
- // Reset the summary counts
- totalUsedSpace = 0;
- totalObjects = 0;
- totalRefFromImmortal = 0;
- }
-
- /**
- * Update the tile statistics
- * In this case, we are accounting for super-page objects, rather than
- * simply for the objects they contain.
- *
- * @param addr The address of the superpage
- */
- public void scan(Address addr) {
-
- int index = subspace.getIndex(addr);
- int length = ((LargeObjectSpace)mmtkSpace).getSize(addr).toInt();
-
- if (DEBUG) {
- Log.write("TreadmillDriver: super=", addr);
- Log.write(", index=", index);
- Log.write(", pages=", length);
- Log.write(", bytes=", Conversions.pagesToBytes(length).toInt());
- Log.writeln(", max=", usedSpaceStream.getMaxValue());
- }
-
- totalObjects++;
- totalUsedSpace += length;
- objectsStream.increment(index, (short)1);
- int remainder = subspace.spaceRemaining(addr);
- usedSpaceStream.distribute(index, remainder, blockSize, length);
-
- Address tmp = addr.plus(length);
- if (tmp.GT(maxAddr)) maxAddr = tmp;
- }
-
- /**
- * Transmit the data if this event is of interest to the client
- * @param event The event, either BEFORE_COLLECTION, SEMISPACE_COPIED
- * or AFTER_COLLECTION
- */
- public void transmit(int event) {
- if (!isConnected(event))
- return;
-
- // At this point, we've filled the tiles with data,
- // however, we don't know the size of the space
- // Calculate the highest indexed tile used so far, and update the subspace
- Address start = subspace.getStart();
- int required = countTileNum(start, maxAddr, blockSize);
- int current = subspace.getBlockNum();
- if (required > current || maxAddr != subspace.getEnd()) {
- subspace.reset(start, maxAddr, 0, required);
- allTileNum = required;
- serverSpace.resize(allTileNum);
- setTilenames(subspace, allTileNum);
- }
-
- // Set the summaries
- setupSummaries();
-
- // set the control info: all of space is USED
- controlValues(CONTROL_USED,
- subspace.getFirstIndex(), subspace.getBlockNum());
-
- // send the space info
- Offset size = subspace.getEnd().diff(subspace.getStart());
- setSpaceInfo(size);
-
- // Send the streams
- send(event, allTileNum);
- }
-
- /**
- * Setup summaries part of the <code>transmit</code> method.<p>
- * Override this method to setup summaries of additional streams in subclasses.
- */
- protected void setupSummaries() {
- usedSpaceStream.setSummary(totalUsedSpace,
- subspace.getEnd().diff(subspace.getStart()).toInt());
- objectsStream.setSummary(totalObjects);
- rootsStream.setSummary(totalRoots);
- refFromImmortalStream.setSummary(totalRefFromImmortal);
- }
-
-
- /**
- * Handle a root address
- *
- * @param addr Root Address
- * @return true if the given Address is in this subspace.
- */
- public boolean handleRoot(Address addr) {
- if(subspace.addressInRange(addr)) {
- // increment tile
- int index = subspace.getIndex(addr);
- rootsStream.increment(index, (short)1);
- // increment summary
- this.totalRoots++;
- return true;
- } else {
- return false;
- }
- }
-
- /**
- * Reset the roots Stream. <br>
- * The roots Stream has to be reset seperately because we do not
- * gather data in the usual way using <code>scan()</code>.
- */
- public void resetRootsStream() {
- rootsStream.resetData();
- totalRoots = 0;
- }
-
- /**
- * Handle a direct reference from the immortal space.
- *
- * @param addr The Address
- * @return true if the given Address is in this subspace.
- */
- public boolean handleReferenceFromImmortalSpace(Address addr) {
- if(subspace.addressInRange(addr)) {
- // increment tile
- int index = subspace.getIndex(addr);
- refFromImmortalStream.increment(index, (short)1);
- // increment summary
- this.totalRefFromImmortal++;
- return true;
- } else {
- return false;
- }
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/utility/heap/FreeListPageResource.java b/vmkit/mmtk/java/src/org/mmtk/utility/heap/FreeListPageResource.java
deleted file mode 100644
index e6ed14c..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/utility/heap/FreeListPageResource.java
+++ /dev/null
@@ -1,382 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.utility.heap;
-
-import org.mmtk.plan.Plan;
-import org.mmtk.policy.Space;
-import static org.mmtk.policy.Space.PAGES_IN_CHUNK;
-import org.mmtk.utility.alloc.EmbeddedMetaData;
-import org.mmtk.utility.Conversions;
-import org.mmtk.utility.GenericFreeList;
-import org.mmtk.vm.VM;
-import org.mmtk.utility.Constants;
-
-import org.vmmagic.unboxed.*;
-import org.vmmagic.pragma.*;
-
-/**
- * This class manages the allocation of pages for a space. When a
- * page is requested by the space both a page budget and the use of
- * virtual address space are checked. If the request for space can't
- * be satisfied (for either reason) a GC may be triggered.<p>
- */
-@Uninterruptible
-public final class FreeListPageResource extends PageResource implements Constants {
-
- private final GenericFreeList freeList;
- private int highWaterMark = 0;
- private final int metaDataPagesPerRegion;
- private int pagesCurrentlyOnFreeList = 0;
-
- /**
- * Constructor
- *
- * Contiguous free list resource. The address range is pre-defined at
- * initialization time and is immutable.
- *
- * @param pageBudget The budget of pages available to this memory
- * manager before it must poll the collector.
- * @param space The space to which this resource is attached
- * @param start The start of the address range allocated to this resource
- * @param bytes The size of the address rage allocated to this resource
- */
- public FreeListPageResource(int pageBudget, Space space, Address start,
- Extent bytes) {
- super(pageBudget, space, start);
- int pages = Conversions.bytesToPages(bytes);
- freeList = new GenericFreeList(pages);
- pagesCurrentlyOnFreeList = pages;
- this.metaDataPagesPerRegion = 0;
- }
-
- /**
- * Constructor
- *
- * Contiguous free list resource. The address range is pre-defined at
- * initialization time and is immutable.
- *
- * @param pageBudget The budget of pages available to this memory
- * manager before it must poll the collector.
- * @param space The space to which this resource is attached
- * @param start The start of the address range allocated to this resource
- * @param bytes The size of the address rage allocated to this resource
- * @param metaDataPagesPerRegion The number of pages of meta data
- * that are embedded in each region.
- */
- public FreeListPageResource(int pageBudget, Space space, Address start,
- Extent bytes, int metaDataPagesPerRegion) {
- super(pageBudget, space, start);
- this.metaDataPagesPerRegion = metaDataPagesPerRegion;
- int pages = Conversions.bytesToPages(bytes);
- freeList = new GenericFreeList(pages, EmbeddedMetaData.PAGES_IN_REGION);
- pagesCurrentlyOnFreeList = pages;
- reserveMetaData(space.getExtent());
- }
-
- /**
- * Constructor
- *
- * Discontiguous monotone resource. The address range is <i>not</i>
- * pre-defined at initialization time and is dynamically defined to
- * be some set of pages, according to demand and availability.
- *
- * @param pageBudget The budget of pages available to this memory
- * manager before it must poll the collector.
- * @param space The space to which this resource is attached
- */
- public FreeListPageResource(int pageBudget, Space space, int metaDataPagesPerRegion) {
- super(pageBudget, space);
- this.metaDataPagesPerRegion = metaDataPagesPerRegion;
- this.start = Space.AVAILABLE_START;
- freeList = new GenericFreeList(Map.globalPageMap, Map.getDiscontigFreeListPROrdinal(this));
- pagesCurrentlyOnFreeList = 0;
- }
-
- /**
- * Return the number of available physical pages for this resource.
- * This includes all pages currently free on the resource's free list.
- * If the resource is using discontiguous space it also includes
- * currently unassigned discontiguous space.<p>
- *
- * Note: This just considers physical pages (ie virtual memory pages
- * allocated for use by this resource). This calculation is orthogonal
- * to and does not consider any restrictions on the number of pages
- * this resource may actually use at any time (ie the number of
- * committed and reserved pages).<p>
- *
- * Note: The calculation is made on the assumption that all space that
- * could be assigned to this resource would be assigned to this resource
- * (ie the unused discontiguous space could just as likely be assigned
- * to another competing resource).
- *
- * @return The number of available physical pages for this resource.
- */
- @Override
- public int getAvailablePhysicalPages() {
- int rtn = pagesCurrentlyOnFreeList;
- if (!contiguous) {
- int chunks = Map.getAvailableDiscontiguousChunks()-Map.getChunkConsumerCount();
- if (chunks < 0) chunks = 0;
- rtn += chunks*(Space.PAGES_IN_CHUNK-metaDataPagesPerRegion);
- }
- return rtn;
- }
-
- /**
- * Allocate <code>pages</code> pages from this resource.<p>
- *
- * If the request can be satisfied, then ensure the pages are
- * mmpapped and zeroed before returning the address of the start of
- * the region. If the request cannot be satisfied, return zero.
- *
- * @param pages The number of pages to be allocated.
- * @return The start of the first page if successful, zero on
- * failure.
- */
- @Inline
- protected Address allocPages(int pages) {
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(metaDataPagesPerRegion == 0 || pages <= PAGES_IN_CHUNK - metaDataPagesPerRegion);
- lock();
- boolean newChunk = false;
- int pageOffset = freeList.alloc(pages);
- if (pageOffset == GenericFreeList.FAILURE && !contiguous) {
- pageOffset = allocateContiguousChunks(pages);
- newChunk = true;
- }
- if (pageOffset == -1) {
- unlock();
- return Address.zero();
- } else {
- pagesCurrentlyOnFreeList -= pages;
- if (pageOffset > highWaterMark) {
- if (highWaterMark == 0 || (pageOffset ^ highWaterMark) > EmbeddedMetaData.PAGES_IN_REGION) {
- int regions = 1 + ((pageOffset - highWaterMark) >> EmbeddedMetaData.LOG_PAGES_IN_REGION);
- int metapages = regions * metaDataPagesPerRegion;
- reserved += metapages;
- committed += metapages;
- newChunk = true;
- }
- highWaterMark = pageOffset;
- }
- Address rtn = start.plus(Conversions.pagesToBytes(pageOffset));
- Extent bytes = Conversions.pagesToBytes(pages);
- commitPages(pages, pages);
- space.growSpace(rtn, bytes, newChunk);
- unlock();
- Mmapper.ensureMapped(rtn, pages);
- VM.memory.zero(rtn, bytes);
- VM.events.tracePageAcquired(space, rtn, pages);
- return rtn;
- }
- }
-
- /**
- * Release a group of pages, associated with this page resource,
- * that were allocated together, optionally zeroing on release and
- * optionally memory protecting on release.
- *
- * @param first The first page in the group of pages that were
- * allocated together.
- */
- @Inline
- public void releasePages(Address first) {
- if (VM.VERIFY_ASSERTIONS)
- VM.assertions._assert(Conversions.isPageAligned(first));
-
- int pageOffset = Conversions.bytesToPages(first.diff(start));
-
- int pages = freeList.size(pageOffset);
- if (ZERO_ON_RELEASE)
- VM.memory.zero(first, Conversions.pagesToBytes(pages));
- /* Can't use protect here because of the chunk sizes involved!
- if (protectOnRelease.getValue())
- LazyMmapper.protect(first, pages);
- */
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(pages <= committed);
-
- lock();
- reserved -= pages;
- committed -= pages;
- int freed = freeList.free(pageOffset, true);
- pagesCurrentlyOnFreeList += pages;
-
- if (!contiguous) // only discontiguous spaces use chunks
- releaseFreeChunks(first, freed);
-
- unlock();
-
- VM.events.tracePageReleased(space, first, pages);
- }
-
- /**
- * The release of a page may have freed up an entire chunk or
- * set of chunks. We need to check whether any chunks can be
- * freed, and if so, free them.
- *
- * @param freedPage The address of the page that was just freed.
- * @param pagesFreed The number of pages made available when the page was freed.
- */
- private void releaseFreeChunks(Address freedPage, int pagesFreed) {
- int pageOffset = Conversions.bytesToPages(freedPage.diff(start));
-
- if (metaDataPagesPerRegion > 0) { // can only be a single chunk
- if (pagesFreed == (PAGES_IN_CHUNK - metaDataPagesPerRegion)) {
- freeContiguousChunk(Space.chunkAlign(freedPage, true));
- }
- } else { // may be multiple chunks
- if (pagesFreed % PAGES_IN_CHUNK == 0) { // necessary, but not sufficient condition
- /* grow a region of chunks, starting with the chunk containing the freed page */
- int regionStart = pageOffset & ~(PAGES_IN_CHUNK - 1);
- int nextRegionStart = regionStart + PAGES_IN_CHUNK;
- /* now try to grow (end point pages are marked as non-coalescing) */
- while (regionStart >= 0 && freeList.isCoalescable(regionStart))
- regionStart -= PAGES_IN_CHUNK;
- while (nextRegionStart < GenericFreeList.MAX_UNITS && freeList.isCoalescable(nextRegionStart))
- nextRegionStart += PAGES_IN_CHUNK;
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(regionStart >= 0 && nextRegionStart < GenericFreeList.MAX_UNITS);
- if (pagesFreed == nextRegionStart - regionStart) {
- freeContiguousChunk(start.plus(Conversions.pagesToBytes(regionStart)));
- }
- }
- }
- }
-
- /**
- * Allocate sufficient contiguous chunks within a discontiguous region to
- * satisfy the pending request. Note that this is purely about address space
- * allocation within a discontiguous region. This method does not reserve
- * individual pages, it merely assigns a suitably large region of virtual
- * memory from within the discontiguous region for use by a particular space.
- *
- * @param pages The number of pages currently being requested
- * @return A chunk number or GenericFreelist.FAILURE
- */
- private int allocateContiguousChunks(int pages) {
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(metaDataPagesPerRegion == 0 || pages <= PAGES_IN_CHUNK - metaDataPagesPerRegion);
- int rtn = GenericFreeList.FAILURE;
- int requiredChunks = Space.requiredChunks(pages);
- Address region = space.growDiscontiguousSpace(requiredChunks);
- if (!region.isZero()) {
- int regionStart = Conversions.bytesToPages(region.diff(start));
- int regionEnd = regionStart + (requiredChunks*Space.PAGES_IN_CHUNK) - 1;
- freeList.setUncoalescable(regionStart);
- freeList.setUncoalescable(regionEnd + 1);
- for (int p = regionStart; p < regionEnd; p += Space.PAGES_IN_CHUNK) {
- int liberated;
- if (p != regionStart)
- freeList.clearUncoalescable(p);
- liberated = freeList.free(p, true); // add chunk to our free list
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(liberated == Space.PAGES_IN_CHUNK + (p - regionStart));
- if (metaDataPagesPerRegion > 1)
- freeList.alloc(metaDataPagesPerRegion, p); // carve out space for metadata
- pagesCurrentlyOnFreeList += Space.PAGES_IN_CHUNK - metaDataPagesPerRegion;
- }
- rtn = freeList.alloc(pages); // re-do the request which triggered this call
- }
- return rtn;
- }
-
- /**
- * Release a single chunk from a discontiguous region. All this does is
- * release a chunk from the virtual address space associated with this
- * discontiguous space.
- *
- * @param chunk The chunk to be freed
- */
- private void freeContiguousChunk(Address chunk) {
- int numChunks = Map.getContiguousRegionChunks(chunk);
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(numChunks == 1 || metaDataPagesPerRegion == 0);
-
- /* nail down all pages associated with the chunk, so it is no longer on our free list */
- int chunkStart = Conversions.bytesToPages(chunk.diff(start));
- int chunkEnd = chunkStart + (numChunks*Space.PAGES_IN_CHUNK);
- while (chunkStart < chunkEnd) {
- freeList.setUncoalescable(chunkStart);
- if (metaDataPagesPerRegion > 0)
- freeList.free(chunkStart); // first free any metadata pages
- int tmp = freeList.alloc(Space.PAGES_IN_CHUNK, chunkStart); // then alloc the entire chunk
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(tmp == chunkStart);
- chunkStart += Space.PAGES_IN_CHUNK;
- pagesCurrentlyOnFreeList -= (Space.PAGES_IN_CHUNK - metaDataPagesPerRegion);
- }
- /* now return the address space associated with the chunk for global reuse */
- space.releaseDiscontiguousChunks(chunk);
- }
-
- /**
- * Reserve virtual address space for meta-data.
- *
- * @param extent The size of this space
- */
- private void reserveMetaData(Extent extent) {
- highWaterMark = 0;
- if (metaDataPagesPerRegion > 0) {
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(start.toWord().rshl(EmbeddedMetaData.LOG_BYTES_IN_REGION).lsh(EmbeddedMetaData.LOG_BYTES_IN_REGION).toAddress().EQ(start));
- Extent size = extent.toWord().rshl(EmbeddedMetaData.LOG_BYTES_IN_REGION).lsh(EmbeddedMetaData.LOG_BYTES_IN_REGION).toExtent();
- Address cursor = start.plus(size);
- while (cursor.GT(start)) {
- cursor = cursor.minus(EmbeddedMetaData.BYTES_IN_REGION);
- int unit = cursor.diff(start).toWord().rshl(LOG_BYTES_IN_PAGE).toInt();
- int tmp = freeList.alloc(metaDataPagesPerRegion, unit);
- pagesCurrentlyOnFreeList -= metaDataPagesPerRegion;
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(tmp == unit);
- }
- }
- }
-
- /**
- * Adjust a page request to include metadata requirements, if any. In the
- * case of a free-list allocator, meta-data is pre-allocated, so simply
- * return the un-adjusted request size.
- *
- * @param pages The size of the pending allocation in pages
- * @return The (unadjusted) request size, since metadata is pre-allocated
- */
- public int adjustForMetaData(int pages) { return pages; }
-
- public Address getHighWater() {
- return start.plus(Extent.fromIntSignExtend(highWaterMark<<LOG_BYTES_IN_PAGE));
- }
-
- /**
- * Return the size of the super page
- *
- * @param first the Address of the first word in the superpage
- * @return the size in bytes
- */
- @Inline
- public Extent getSize(Address first) {
- if (VM.VERIFY_ASSERTIONS)
- VM.assertions._assert(Conversions.isPageAligned(first));
-
- int pageOffset = Conversions.bytesToPages(first.diff(start));
- int pages = freeList.size(pageOffset);
- return Conversions.pagesToBytes(pages);
- }
-
- /**
- * Resize the free list associated with this resource and nail down
- * its start address. This method is called to re-set the free list
- * once the global free list (which it shares) is finalized and the
- * base address is finalized. There's a circular dependency, so we
- * need an explicit call-back to reset the free list size and start
- *
- * @param startAddress The final start address for the discontiguous space.
- */
- @Interruptible
- public void resizeFreeList(Address startAddress) {
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(!contiguous && !Plan.isInitialized());
- start = startAddress;
- freeList.resizeFreeList();
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/utility/heap/HeapGrowthManager.java b/vmkit/mmtk/java/src/org/mmtk/utility/heap/HeapGrowthManager.java
deleted file mode 100644
index e315a11..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/utility/heap/HeapGrowthManager.java
+++ /dev/null
@@ -1,293 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.utility.heap;
-
-import org.mmtk.plan.Plan;
-import org.mmtk.utility.*;
-import org.mmtk.utility.options.Options;
-
-import org.mmtk.vm.VM;
-
-import org.vmmagic.pragma.*;
-import org.vmmagic.unboxed.*;
-
-/**
- * This class is responsible for growing and shrinking the
- * heap size by observing heap utilization and GC load.
- */
-@Uninterruptible public abstract class HeapGrowthManager implements Constants {
-
- /**
- * The initial heap size (-Xms) in bytes
- */
- private static Extent initialHeapSize;
-
- /**
- * The maximum heap size (-Xms) in bytes
- */
- private static Extent maxHeapSize;
-
- /**
- * The current heap size in bytes
- */
- private static Extent currentHeapSize;
-
-
- private static final double[][] generationalFunction = {{0.00, 0.00, 0.10, 0.30, 0.60, 0.80, 1.00},
- { 0.00, 0.90, 0.90, 0.95, 1.00, 1.00, 1.00 },
- { 0.01, 0.90, 0.90, 0.95, 1.00, 1.00, 1.00 },
- { 0.02, 0.95, 0.95, 1.00, 1.00, 1.00, 1.00 },
- { 0.07, 1.00, 1.00, 1.10, 1.15, 1.20, 1.20 },
- { 0.15, 1.00, 1.00, 1.20, 1.25, 1.35, 1.30 },
- { 0.40, 1.00, 1.00, 1.25, 1.30, 1.50, 1.50 },
- { 1.00, 1.00, 1.00, 1.25, 1.30, 1.50, 1.50 } };
-
- private static final double[][] nongenerationalFunction = {{0.00, 0.00, 0.10, 0.30, 0.60, 0.80, 1.00},
- { 0.00, 0.90, 0.90, 0.95, 1.00, 1.00, 1.00 },
- { 0.02, 0.90, 0.90, 0.95, 1.00, 1.00, 1.00 },
- { 0.05, 0.95, 0.95, 1.00, 1.00, 1.00, 1.00 },
- { 0.15, 1.00, 1.00, 1.10, 1.15, 1.20, 1.20 },
- { 0.30, 1.00, 1.00, 1.20, 1.25, 1.35, 1.30 },
- { 0.50, 1.00, 1.00, 1.25, 1.30, 1.50, 1.50 },
- { 1.00, 1.00, 1.00, 1.25, 1.30, 1.50, 1.50 } };
-
- /**
- * An encoding of the function used to manage heap size.
- * The xaxis represents the live ratio at the end of a major collection.
- * The yaxis represents the GC load (GC time/total time).
- * The interior of the matrix represents a ratio to shrink or grow
- * the heap for a given pair of live ratio and GC load.
- * The constraints on the matrix are:
- * <ul>
- * <li> function[0][0] is ignored.
- * <li> All numbers in the first row must monotonically increase and
- * must be in the range from 0 to 1 inclusive.</li>
- * <li> All numbers in the first column must monotonically increase
- * and must be in the range from 0 to 1 inclusive.</li>
- * <li> There must be 0 and 1 values specified in both dimensions.
- * <li> For all interior points in the matrix, the value must be
- * greater than the liveRatio for that column.</li>
- * </ul>
- */
- private static final double[][] function =
- VM.activePlan.constraints().generational() ? generationalFunction : nongenerationalFunction;
-
- private static long endLastMajorGC;
- private static double accumulatedGCTime;
-
- /**
- * Initialize heap size parameters and the mechanisms
- * used to adaptively change heap size.
- */
- public static void boot(Extent initial, Extent max) {
- initialHeapSize = initial;
- maxHeapSize = max;
- if (initialHeapSize.GT(maxHeapSize))
- maxHeapSize = initialHeapSize;
- currentHeapSize = initialHeapSize;
- VM.events.heapSizeChanged(currentHeapSize);
- if (VM.VERIFY_ASSERTIONS) sanityCheck();
- endLastMajorGC = VM.statistics.nanoTime();
- }
-
- /**
- * @return the current heap size in bytes
- */
- public static Extent getCurrentHeapSize() {
- return currentHeapSize;
- }
-
- /**
- * Return the max heap size in bytes (as set by -Xmx).
- *
- * @return The max heap size in bytes (as set by -Xmx).
- */
- public static Extent getMaxHeapSize() {
- return maxHeapSize;
- }
-
- /**
- * Return the initial heap size in bytes (as set by -Xms).
- *
- * @return The initial heap size in bytes (as set by -Xms).
- */
- public static Extent getInitialHeapSize() {
- return initialHeapSize;
- }
-
- /**
- * Forcibly grow the heap by the given number of bytes.
- * Used to provide headroom when handling an OutOfMemory
- * situation.
- * @param size number of bytes to grow the heap
- */
- public static void overrideGrowHeapSize(Extent size) {
- currentHeapSize = currentHeapSize.plus(size);
- VM.events.heapSizeChanged(currentHeapSize);
- }
-
- /**
- * Record the time taken by the current GC;
- * used to compute gc load, one of the inputs
- * into the heap size management function
- */
- public static void recordGCTime(double time) {
- accumulatedGCTime += time;
- }
-
- /**
- * Reset timers used to compute gc load
- */
- public static void reset() {
- endLastMajorGC = VM.statistics.nanoTime();
- accumulatedGCTime = 0;
- }
-
- /**
- * Decide how to grow/shrink the heap to respond
- * to application's memory usage.
- * @return true if heap size was changed, false otherwise
- */
- public static boolean considerHeapSize() {
- Extent oldSize = currentHeapSize;
- Extent reserved = Plan.reservedMemory();
- double liveRatio = reserved.toLong() / ((double) currentHeapSize.toLong());
- double ratio = computeHeapChangeRatio(liveRatio);
- Extent newSize = Word.fromIntSignExtend((int)(ratio * (double) (oldSize.toLong()>>LOG_BYTES_IN_MBYTE))).lsh(LOG_BYTES_IN_MBYTE).toExtent(); // do arith in MB to avoid overflow
- if (newSize.LT(reserved)) newSize = reserved;
- newSize = newSize.plus(BYTES_IN_MBYTE - 1).toWord().rshl(LOG_BYTES_IN_MBYTE).lsh(LOG_BYTES_IN_MBYTE).toExtent(); // round to next megabyte
- if (newSize.GT(maxHeapSize)) newSize = maxHeapSize;
- if (newSize.NE(oldSize) && newSize.GT(Extent.zero())) {
- // Heap size is going to change
- currentHeapSize = newSize;
- if (Options.verbose.getValue() >= 2) {
- Log.write("GC Message: Heap changed from "); Log.writeDec(oldSize.toWord().rshl(LOG_BYTES_IN_KBYTE));
- Log.write("KB to "); Log.writeDec(newSize.toWord().rshl(LOG_BYTES_IN_KBYTE));
- Log.writeln("KB");
- }
- VM.events.heapSizeChanged(currentHeapSize);
- return true;
- } else {
- return false;
- }
- }
-
- private static double computeHeapChangeRatio(double liveRatio) {
- // (1) compute GC load.
- long totalNanos = VM.statistics.nanoTime() - endLastMajorGC;
- double totalTime = VM.statistics.nanosToMillis(totalNanos);
- double gcLoad = accumulatedGCTime / totalTime;
-
- if (liveRatio > 1) {
- // Perhaps indicates bad bookkeeping in MMTk?
- Log.write("GCWarning: Live ratio greater than 1: ");
- Log.writeln(liveRatio);
- liveRatio = 1;
- }
- if (gcLoad > 1) {
- if (gcLoad > 1.0001) {
- Log.write("GC Error: GC load was greater than 1!! ");
- Log.writeln(gcLoad);
- Log.write("GC Error:\ttotal time (ms) "); Log.writeln(totalTime);
- Log.write("GC Error:\tgc time (ms) "); Log.writeln(accumulatedGCTime);
- }
- gcLoad = 1;
- }
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(liveRatio >= 0);
- if (VM.VERIFY_ASSERTIONS && gcLoad < -0.0) {
- Log.write("gcLoad computed to be "); Log.writeln(gcLoad);
- Log.write("\taccumulateGCTime was (ms) "); Log.writeln(accumulatedGCTime);
- Log.write("\ttotalTime was (ms) "); Log.writeln(totalTime);
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(false);
- }
-
- if (Options.verbose.getValue() > 2) {
- Log.write("Live ratio "); Log.writeln(liveRatio);
- Log.write("GCLoad "); Log.writeln(gcLoad);
- }
-
- // (2) Find the 4 points surrounding gcLoad and liveRatio
- int liveRatioUnder = 1;
- int liveRatioAbove = function[0].length - 1;
- int gcLoadUnder = 1;
- int gcLoadAbove = function.length - 1;
- while (true) {
- if (function[0][liveRatioUnder+1] >= liveRatio) break;
- liveRatioUnder++;
- }
- while (true) {
- if (function[0][liveRatioAbove-1] <= liveRatio) break;
- liveRatioAbove--;
- }
- while (true) {
- if (function[gcLoadUnder+1][0] >= gcLoad) break;
- gcLoadUnder++;
- }
- while (true) {
- if (function[gcLoadAbove-1][0] <= gcLoad) break;
- gcLoadAbove--;
- }
-
- // (3) Compute the heap change ratio
- double factor = function[gcLoadUnder][liveRatioUnder];
- double liveRatioFraction =
- (liveRatio - function[0][liveRatioUnder]) /
- (function[0][liveRatioAbove] - function[0][liveRatioUnder]);
- double liveRatioDelta =
- function[gcLoadUnder][liveRatioAbove] - function[gcLoadUnder][liveRatioUnder];
- factor += (liveRatioFraction * liveRatioDelta);
- double gcLoadFraction =
- (gcLoad - function[gcLoadUnder][0]) /
- (function[gcLoadAbove][0] - function[gcLoadUnder][0]);
- double gcLoadDelta =
- function[gcLoadAbove][liveRatioUnder] - function[gcLoadUnder][liveRatioUnder];
- factor += (gcLoadFraction * gcLoadDelta);
-
- if (Options.verbose.getValue() > 2) {
- Log.write("Heap adjustment factor is ");
- Log.writeln(factor);
- }
- return factor;
- }
-
- /**
- * Check that function satisfies the invariants
- */
- private static void sanityCheck() {
- // Check live ratio
- double[] liveRatio = function[0];
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(liveRatio[1] == 0);
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(liveRatio[liveRatio.length-1] == 1);
- for (int i = 2; i < liveRatio.length; i++) {
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(liveRatio[i-1] < liveRatio[i]);
- for (int j = 1; j < function.length; j++) {
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(function[j][i] >= 1 || function[j][i] > liveRatio[i]);
- }
- }
-
- // Check GC load
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(function[1][0] == 0);
- int len = function.length;
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(function[len-1][0] == 1);
- for (int i = 2; i < len; i++) {
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(function[i-1][0] < function[i][0]);
- }
-
- // Check that we have a rectangular matrix
- for (int i = 1; i < function.length; i++) {
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(function[i-1].length == function[i].length);
- }
- }
-
-
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/utility/heap/Map.java b/vmkit/mmtk/java/src/org/mmtk/utility/heap/Map.java
deleted file mode 100644
index 0a19f32..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/utility/heap/Map.java
+++ /dev/null
@@ -1,355 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.utility.heap;
-
-import org.mmtk.policy.Space;
-import org.mmtk.utility.GenericFreeList;
-import org.mmtk.utility.Log;
-import org.mmtk.vm.Lock;
-import org.mmtk.vm.VM;
-import org.vmmagic.pragma.Inline;
-import org.vmmagic.pragma.Interruptible;
-import org.vmmagic.pragma.Uninterruptible;
-import org.vmmagic.unboxed.Address;
-import org.vmmagic.unboxed.Extent;
-import org.vmmagic.unboxed.Word;
-
-/**
- * This class manages the mapping of spaces to virtual memory ranges.<p>
- *
- */
-@Uninterruptible
-public class Map {
-
- /* set the map base address so that we have an unused (null) chunk at the bottome of the space for 64 bit */
- private static final Address MAP_BASE_ADDRESS = Space.BITS_IN_ADDRESS == 32 ? Address.zero() : Space.HEAP_START.minus(Space.BYTES_IN_CHUNK);
-
- /****************************************************************************
- *
- * Class variables
- */
- private static final int[] descriptorMap;
- private static final int[] prevLink;
- private static final int[] nextLink;
- private static final Space[] spaceMap;
- private static final GenericFreeList regionMap;
- public static final GenericFreeList globalPageMap;
- private static int sharedDiscontigFLCount = 0;
- private static final FreeListPageResource[] sharedFLMap;
- private static int totalAvailableDiscontiguousChunks = 0;
-
- private static final Lock lock = VM.newLock("Map lock");
-
- /****************************************************************************
- *
- * Initialization
- */
-
- /**
- * Class initializer. Create our two maps
- */
- static {
- descriptorMap = new int[Space.MAX_CHUNKS];
- prevLink = new int[Space.MAX_CHUNKS];
- nextLink = new int[Space.MAX_CHUNKS];
- spaceMap = new Space[Space.MAX_CHUNKS];
- regionMap = new GenericFreeList(Space.MAX_CHUNKS);
- globalPageMap = new GenericFreeList(1, 1, Space.MAX_SPACES);
- sharedFLMap = new FreeListPageResource[Space.MAX_SPACES];
- if (VM.VERIFY_ASSERTIONS)
- VM.assertions._assert(Space.BITS_IN_ADDRESS == Space.LOG_ADDRESS_SPACE ||
- Space.HEAP_END.diff(MAP_BASE_ADDRESS).toWord().rshl(Space.LOG_ADDRESS_SPACE).isZero());
- }
-
- /****************************************************************************
- *
- * Map accesses and insertion
- */
-
- /**
- * Insert a space and its descriptor into the map, associating it
- * with a particular address range.
- *
- * @param start The start address of the region to be associated
- * with this space.
- * @param extent The size of the region, in bytes
- * @param descriptor The descriptor for this space
- * @param space The space to be associated with this region
- */
- public static void insert(Address start, Extent extent, int descriptor,
- Space space) {
- Extent e = Extent.zero();
- while (e.LT(extent)) {
- int index = getChunkIndex(start.plus(e));
- if (descriptorMap[index] != 0) {
- Log.write("Conflicting virtual address request for space \"");
- Log.write(space.getName()); Log.write("\" at ");
- Log.writeln(start.plus(e));
- Space.printVMMap();
- VM.assertions.fail("exiting");
- }
- descriptorMap[index] = descriptor;
- VM.barriers.objectArrayStoreNoGCBarrier(spaceMap, index, space);
- e = e.plus(Space.BYTES_IN_CHUNK);
- }
- }
-
- /**
- * Allocate some number of contiguous chunks within a discontiguous region
- *
- * @param descriptor The descriptor for the space to which these chunks will be assigned
- * @param space The space to which these chunks will be assigned
- * @param chunks The number of chunks required
- * @param head The previous contgiuous set of chunks for this space (to create a linked list of contiguous regions for each space)
- * @return The address of the assigned memory. This always succeeds. If the request fails we fail right here.
- */
- public static Address allocateContiguousChunks(int descriptor, Space space, int chunks, Address head) {
- lock.acquire();
- int chunk = regionMap.alloc(chunks);
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(chunk != 0);
- if (chunk == -1) {
- Log.write("Unable to allocate virtual address space for space \"");
- Log.write(space.getName()); Log.write("\" for ");
- Log.write(chunks); Log.write(" chunks (");
- Log.write(chunks<<Space.LOG_BYTES_IN_CHUNK); Log.writeln(" bytes)");
- Space.printVMMap();
- VM.assertions.fail("exiting");
- }
- totalAvailableDiscontiguousChunks -= chunks;
- Address rtn = addressForChunkIndex(chunk);
- insert(rtn, Extent.fromIntZeroExtend(chunks<<Space.LOG_BYTES_IN_CHUNK), descriptor, space);
- if (head.isZero()) {
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(nextLink[chunk] == 0);
- } else {
- nextLink[chunk] = getChunkIndex(head);
- prevLink[getChunkIndex(head)] = chunk;
- }
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(prevLink[chunk] == 0);
- lock.release();
- return rtn;
- }
-
- /**
- * Return the address of the next contiguous region associated with some discontiguous space by following the linked list for that space.
- *
- * @param start The current region (return the next region in the list)
- * @return Return the next contiguous region after start in the linked list of regions
- */
- public static Address getNextContiguousRegion(Address start) {
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(start.EQ(Space.chunkAlign(start, true)));
- int chunk = getChunkIndex(start);
- return (chunk == 0) ? Address.zero() : (nextLink[chunk] == 0) ? Address.zero() : addressForChunkIndex(nextLink[chunk]);
- }
-
- /**
- * Return the size of a contiguous region in chunks.
- *
- * @param start The start address of the region whose size is being requested
- * @return The size of the region in question
- */
- public static int getContiguousRegionChunks(Address start) {
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(start.EQ(Space.chunkAlign(start, true)));
- int chunk = getChunkIndex(start);
- return regionMap.size(chunk);
- }
-
- /**
- * Return the size of a contiguous region in bytes.
- *
- * @param start The start address of the region whose size is being requested
- * @return The size of the region in question
- */
- public static Extent getContiguousRegionSize(Address start) {
- return Word.fromIntSignExtend(getContiguousRegionChunks(start)).lsh(Space.LOG_BYTES_IN_CHUNK).toExtent();
- }
-
- /**
- * Free all chunks in a linked list of contiguous chunks. This means starting
- * with one and then walking the chains of contiguous regions, freeing each.
- *
- * @param anyChunk Any chunk in the linked list of chunks to be freed
- */
- public static void freeAllChunks(Address anyChunk) {
- lock.acquire();
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(anyChunk.EQ(Space.chunkAlign(anyChunk, true)));
- if (!anyChunk.isZero()) {
- int chunk = getChunkIndex(anyChunk);
- while (nextLink[chunk] != 0) {
- freeContiguousChunks(nextLink[chunk]);
- }
- while (prevLink[chunk] != 0) {
- freeContiguousChunks(prevLink[chunk]);
- }
- freeContiguousChunks(chunk);
- }
- lock.release();
- }
-
- /**
- * Free some set of contiguous chunks, given the chunk address
- *
- * @param start The start address of the first chunk in the series
- * @return The number of chunks which were contiguously allocated
- */
- public static int freeContiguousChunks(Address start) {
- lock.acquire();
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(start.EQ(Space.chunkAlign(start, true)));
- int rtn = freeContiguousChunks(getChunkIndex(start));
- lock.release();
- return rtn;
- }
-
- /**
- * Free some set of contiguous chunks, given the chunk index
- *
- * @param chunk The chunk index of the region to be freed
- * @return The number of chunks freed
- */
- private static int freeContiguousChunks(int chunk) {
- int chunks = regionMap.free(chunk);
- totalAvailableDiscontiguousChunks += chunks;
- int next = nextLink[chunk];
- int prev = prevLink[chunk];
- if (next != 0) prevLink[next] = prev;
- if (prev != 0) nextLink[prev] = next;
- nextLink[chunk] = prevLink[chunk] = 0;
- for (int offset = 0; offset < chunks; offset++) {
- descriptorMap[chunk + offset] = 0;
- VM.barriers.objectArrayStoreNoGCBarrier(spaceMap, chunk + offset, null);
- }
- return chunks;
- }
-
- /**
- * Finalize the space map, establishing which virtual memory
- * is nailed down, and then placing the rest into a map to
- * be used by discontiguous spaces.
- */
- @Interruptible
- public static void finalizeStaticSpaceMap() {
- /* establish bounds of discontiguous space */
- Address startAddress = Space.getDiscontigStart();
- int firstChunk = getChunkIndex(startAddress);
- int lastChunk = getChunkIndex(Space.getDiscontigEnd());
- int unavailStartChunk = lastChunk + 1;
- int trailingChunks = Space.MAX_CHUNKS - unavailStartChunk;
- int pages = (1 + lastChunk - firstChunk) * Space.PAGES_IN_CHUNK;
- globalPageMap.resizeFreeList(pages, pages);
- for (int pr = 0; pr < sharedDiscontigFLCount; pr++)
- sharedFLMap[pr].resizeFreeList(startAddress);
-
- /* set up the region map free list */
- int allocedChunk = regionMap.alloc(firstChunk); // block out entire bottom of address range
- for (int chunkIndex = firstChunk; chunkIndex <= lastChunk; chunkIndex++)
- allocedChunk = regionMap.alloc(1); // Tentatively allocate all usable chunks
- allocedChunk = regionMap.alloc(trailingChunks); // block out entire top of address range
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(allocedChunk == unavailStartChunk);
-
- /* set up the global page map and place chunks on free list */
- int firstPage = 0;
- for (int chunkIndex = firstChunk; chunkIndex <= lastChunk; chunkIndex++) {
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(spaceMap[chunkIndex] == null);
- totalAvailableDiscontiguousChunks++;
- regionMap.free(chunkIndex); // put this chunk on the free list
- globalPageMap.setUncoalescable(firstPage);
- int allocedPages = globalPageMap.alloc(Space.PAGES_IN_CHUNK); // populate the global page map
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(allocedPages == firstPage);
- firstPage += Space.PAGES_IN_CHUNK;
- }
- }
-
- /**
- * Return the ordinal number for some free list space wishing to share a discontiguous region.
- * @return The ordinal number for a free list space wishing to share a discontiguous region
- */
- @Interruptible
- public static int getDiscontigFreeListPROrdinal(FreeListPageResource pr) {
- sharedFLMap[sharedDiscontigFLCount] = pr;
- sharedDiscontigFLCount++;
- return sharedDiscontigFLCount;
- }
-
- /**
- * Return the total number of chunks available (unassigned) within the
- * range of virtual memory apportioned to discontiguous spaces.
- *
- * @return The number of available chunks for use by discontiguous spaces.
- */
- public static int getAvailableDiscontiguousChunks() {
- return totalAvailableDiscontiguousChunks;
- }
-
- /**
- * Return the total number of clients contending for chunks. This
- * is useful when establishing conservative bounds on the number
- * of remaining chunks.
- *
- * @return The total number of clients who may contend for chunks.
- */
- public static int getChunkConsumerCount() {
- return sharedDiscontigFLCount;
- }
-
- /**
- * Return the space in which this address resides.
- *
- * @param address The address in question
- * @return The space in which the address resides
- */
- @Inline
- public static Space getSpaceForAddress(Address address) {
- int index = getChunkIndex(address);
- return spaceMap[index];
- }
-
- /**
- * Return the space descriptor for the space in which this object
- * resides.
- *
- * @param object The object in question
- * @return The space descriptor for the space in which the object
- * resides
- */
- @Inline
- public static int getDescriptorForAddress(Address object) {
- int index = getChunkIndex(object);
- return descriptorMap[index];
- }
-
- /**
- * Hash an address to a chunk (this is simply done via bit shifting)
- *
- * @param address The address to be hashed
- * @return The chunk number that this address hashes into
- */
- @Inline
- private static int getChunkIndex(Address address) {
- if (Space.BYTES_IN_ADDRESS == 8) {
- if (address.LT(Space.HEAP_START) || address.GE(Space.HEAP_END))
- return 0;
- else
- return address.diff(MAP_BASE_ADDRESS).toWord().rshl(Space.LOG_BYTES_IN_CHUNK).toInt();
- } else
- return address.toWord().rshl(Space.LOG_BYTES_IN_CHUNK).toInt();
- }
- @Inline
- private static Address addressForChunkIndex(int chunk) {
- if (Space.BYTES_IN_ADDRESS == 8) {
- if (chunk == 0)
- return Address.zero();
- else
- return MAP_BASE_ADDRESS.plus(Word.fromIntZeroExtend(chunk).lsh(Space.LOG_BYTES_IN_CHUNK).toExtent());
- } else
- return Word.fromIntZeroExtend(chunk).lsh(Space.LOG_BYTES_IN_CHUNK).toAddress();
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/utility/heap/Mmapper.java b/vmkit/mmtk/java/src/org/mmtk/utility/heap/Mmapper.java
deleted file mode 100644
index 93830e6..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/utility/heap/Mmapper.java
+++ /dev/null
@@ -1,237 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.utility.heap;
-
-import org.mmtk.utility.*;
-
-import org.mmtk.vm.Lock;
-import org.mmtk.vm.VM;
-
-import org.vmmagic.unboxed.*;
-import org.vmmagic.pragma.*;
-
-/**
- * This class implements mmapping and protection of virtual memory.
- */
-@Uninterruptible public final class Mmapper implements Constants {
-
- /****************************************************************************
- * Constants
- */
- public static final byte UNMAPPED = 0;
- public static final byte MAPPED = 1;
- public static final byte PROTECTED = 2; // mapped but not accessible
- public static final int LOG_MMAP_CHUNK_BYTES = 20;
- public static final int MMAP_CHUNK_BYTES = 1 << LOG_MMAP_CHUNK_BYTES; // the granularity VMResource operates at
- //TODO: 64-bit: this is not OK: value does not fit in int, but should, we do not want to create such big array
- private static final int MMAP_CHUNK_MASK = MMAP_CHUNK_BYTES - 1;
- private static final int MMAP_NUM_CHUNKS = 1 << (Constants.LOG_BYTES_IN_ADDRESS_SPACE - LOG_MMAP_CHUNK_BYTES);
- public static final boolean verbose = false;
-
- /****************************************************************************
- * Class variables
- */
- public static final Lock lock = VM.newLock("Mmapper");
- private static byte[] mapped;
-
-
- /****************************************************************************
- * Initialization
- */
-
- /**
- * Class initializer. This is executed <i>prior</i> to bootstrap
- * (i.e. at "build" time).
- */
- static {
- mapped = new byte[MMAP_NUM_CHUNKS];
- for (int c = 0; c < MMAP_NUM_CHUNKS; c++) {
- mapped[c] = UNMAPPED;
- }
- }
-
- /****************************************************************************
- * Generic mmap and protection functionality
- */
-
- /**
- * Given an address array describing the regions of virtual memory to be used
- * by MMTk, demand zero map all of them if they are not already mapped.
- *
- * @param spaceMap An address array containing a pairs of start and end
- * addresses for each of the regions to be mappe3d
- */
- public static void eagerlyMmapAllSpaces(AddressArray spaceMap) {
-
- /*for (int i = 0; i < spaceMap.length() / 2; i++) {
- Address regionStart = spaceMap.get(i * 2);
- Address regionEnd = spaceMap.get(i * 2 + 1);
- Log.write(regionStart); Log.write(" "); Log.writeln(regionEnd);
- if (regionEnd.EQ(Address.zero()) || regionStart.EQ(Address.fromIntSignExtend(-1)) ||regionEnd.EQ(Address.fromIntSignExtend(-1)))
- break;
- if (VM.VERIFY_ASSERTIONS) {
- VM.assertions._assert(regionStart.EQ(chunkAlignDown(regionStart)));
- VM.assertions._assert(regionEnd.EQ(chunkAlignDown(regionEnd)));
- }
- int pages = Conversions.bytesToPages(regionEnd.diff(regionStart));
- ensureMapped(regionStart, pages);
- }*/
- }
-
- /**
- * Mark a range of pages as having (already) been mapped. This is useful
- * where the VM has performed the mapping of the pages itself.
- *
- * @param start The start of the range to be marked as mapped
- * @param bytes The size of the range, in bytes.
- */
- public static void markAsMapped(Address start, int bytes) {
- int startChunk = Conversions.addressToMmapChunksDown(start);
- int endChunk = Conversions.addressToMmapChunksUp(start.plus(bytes));
- for (int i = startChunk; i <= endChunk; i++)
- mapped[i] = MAPPED;
- }
-
- /**
- * Ensure that a range of pages is mmapped (or equivalent). If the
- * pages are not yet mapped, demand-zero map them. Note that mapping
- * occurs at chunk granularity, not page granularity.<p>
- *
- * NOTE: There is a monotonicity assumption so that only updates require lock
- * acquisition.
- * TODO: Fix the above to support unmapping.
- *
- * @param start The start of the range to be mapped.
- * @param pages The size of the range to be mapped, in pages
- */
- public static void ensureMapped(Address start, int pages) {
- int startChunk = Conversions.addressToMmapChunksDown(start);
- int endChunk = Conversions.addressToMmapChunksUp(start.plus(Conversions.pagesToBytes(pages)));
- for (int chunk = startChunk; chunk < endChunk; chunk++) {
- if (mapped[chunk] == MAPPED) continue;
- Address mmapStart = Conversions.mmapChunksToAddress(chunk);
- lock.acquire();
-// Log.writeln(mmapStart);
- // might have become MAPPED here
- if (mapped[chunk] == UNMAPPED) {
- int errno = VM.memory.dzmmap(mmapStart, MMAP_CHUNK_BYTES);
- if (errno != 0) {
- lock.release();
- Log.write("ensureMapped failed with errno "); Log.write(errno);
- Log.write(" on address "); Log.writeln(mmapStart);
- VM.assertions.fail("Can't get more space with mmap()");
- } else {
- if (verbose) {
- Log.write("mmap succeeded at chunk "); Log.write(chunk); Log.write(" "); Log.write(mmapStart);
- Log.write(" with len = "); Log.writeln(MMAP_CHUNK_BYTES);
- }
- }
- }
- if (mapped[chunk] == PROTECTED) {
- if (!VM.memory.munprotect(mmapStart, MMAP_CHUNK_BYTES)) {
- lock.release();
- VM.assertions.fail("Mmapper.ensureMapped (unprotect) failed");
- } else {
- if (verbose) {
- Log.write("munprotect succeeded at chunk "); Log.write(chunk); Log.write(" "); Log.write(mmapStart);
- Log.write(" with len = "); Log.writeln(MMAP_CHUNK_BYTES);
- }
- }
- }
- mapped[chunk] = MAPPED;
- lock.release();
- }
-
- }
-
- /**
- * Memory protect a range of pages (using mprotect or equivalent). Note
- * that protection occurs at chunk granularity, not page granularity.
- *
- * @param start The start of the range to be protected.
- * @param pages The size of the range to be protected, in pages
- */
- public static void protect(Address start, int pages) {
- int startChunk = Conversions.addressToMmapChunksDown(start);
- int chunks = Conversions.pagesToMmapChunksUp(pages);
- int endChunk = startChunk + chunks;
- lock.acquire();
- for (int chunk = startChunk; chunk < endChunk; chunk++) {
- if (mapped[chunk] == MAPPED) {
- Address mmapStart = Conversions.mmapChunksToAddress(chunk);
- if (!VM.memory.mprotect(mmapStart, MMAP_CHUNK_BYTES)) {
- lock.release();
- VM.assertions.fail("Mmapper.mprotect failed");
- } else {
- if (verbose) {
- Log.write("mprotect succeeded at chunk "); Log.write(chunk); Log.write(" "); Log.write(mmapStart);
- Log.write(" with len = "); Log.writeln(MMAP_CHUNK_BYTES);
- }
- }
- mapped[chunk] = PROTECTED;
- } else {
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(mapped[chunk] == PROTECTED);
- }
- }
- lock.release();
- }
-
- /****************************************************************************
- * Utility functions
- */
-
- /**
- * Return true if the given address has been mmapped
- *
- * @param addr The address in question.
- * @return true if the given address has been mmapped
- */
- @Uninterruptible
- public static boolean addressIsMapped(Address addr) {
- int chunk = Conversions.addressToMmapChunksDown(addr);
- return mapped[chunk] == MAPPED;
- }
-
- /**
- * Return true if the given object has been mmapped
- *
- * @param object The object in question.
- * @return true if the given object has been mmapped
- */
- @Uninterruptible
- public static boolean objectIsMapped(ObjectReference object) {
- return addressIsMapped(VM.objectModel.refToAddress(object));
- }
-
- /**
- * Return a given address rounded up to an mmap chunk size
- *
- * @param addr The address to be aligned
- * @return The given address rounded up to an mmap chunk size
- */
- @SuppressWarnings("unused") // but might be useful someday
- private static Address chunkAlignUp(Address addr) {
- return chunkAlignDown(addr.plus(MMAP_CHUNK_MASK));
- }
-
- /**
- * Return a given address rounded down to an mmap chunk size
- *
- * @param addr The address to be aligned
- * @return The given address rounded down to an mmap chunk size
- */
- private static Address chunkAlignDown(Address addr) {
- return addr.toWord().and(Word.fromIntSignExtend(MMAP_CHUNK_MASK).not()).toAddress();
- }
-}
-
diff --git a/vmkit/mmtk/java/src/org/mmtk/utility/heap/MonotonePageResource.java b/vmkit/mmtk/java/src/org/mmtk/utility/heap/MonotonePageResource.java
deleted file mode 100644
index f6d06a0..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/utility/heap/MonotonePageResource.java
+++ /dev/null
@@ -1,307 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.utility.heap;
-
-import org.mmtk.utility.alloc.EmbeddedMetaData;
-import org.mmtk.utility.options.Options;
-import org.mmtk.policy.Space;
-import org.mmtk.utility.Conversions;
-import org.mmtk.utility.Constants;
-
-import org.mmtk.vm.VM;
-
-import org.vmmagic.pragma.*;
-import org.vmmagic.unboxed.*;
-
-/**
- * This class manages the allocation of pages for a space. When a
- * page is requested by the space both a page budget and the use of
- * virtual address space are checked. If the request for space can't
- * be satisfied (for either reason) a GC may be triggered.<p>
- */
-@Uninterruptible
-public final class MonotonePageResource extends PageResource
- implements Constants {
-
- /****************************************************************************
- *
- * Instance variables
- */
- private Address cursor;
- private Address sentinel;
- private final int metaDataPagesPerRegion;
- private Address currentChunk = Address.zero();
-
- /**
- * Constructor
- *
- * Contiguous monotone resource. The address range is pre-defined at
- * initialization time and is immutable.
- *
- * @param pageBudget The budget of pages available to this memory
- * manager before it must poll the collector.
- * @param space The space to which this resource is attached
- * @param start The start of the address range allocated to this resource
- * @param bytes The size of the address rage allocated to this resource
- * @param metaDataPagesPerRegion The number of pages of meta data
- * that are embedded in each region.
- */
- public MonotonePageResource(int pageBudget, Space space, Address start,
- Extent bytes, int metaDataPagesPerRegion) {
- super(pageBudget, space, start);
- this.cursor = start;
- this.sentinel = start.plus(bytes);
- this.metaDataPagesPerRegion = metaDataPagesPerRegion;
- }
-
- /**
- * Constructor
- *
- * Discontiguous monotone resource. The address range is <i>not</i>
- * pre-defined at initialization time and is dynamically defined to
- * be some set of pages, according to demand and availability.
- *
- * CURRENTLY UNIMPLEMENTED
- *
- * @param pageBudget The budget of pages available to this memory
- * manager before it must poll the collector.
- * @param space The space to which this resource is attached
- * @param metaDataPagesPerRegion The number of pages of meta data
- * that are embedded in each region.
- */
- public MonotonePageResource(int pageBudget, Space space, int metaDataPagesPerRegion) {
- super(pageBudget, space);
- /* unimplemented */
- this.start = Address.zero();
- this.cursor = Address.zero();
- this.sentinel = Address.zero();
- this.metaDataPagesPerRegion = metaDataPagesPerRegion;
- }
-
- /**
- * Return the number of available physical pages for this resource.
- * This includes all pages currently unused by this resource's page
- * cursor. If the resource is using discontiguous space it also includes
- * currently unassigned discontiguous space.<p>
- *
- * Note: This just considers physical pages (ie virtual memory pages
- * allocated for use by this resource). This calculation is orthogonal
- * to and does not consider any restrictions on the number of pages
- * this resource may actually use at any time (ie the number of
- * committed and reserved pages).<p>
- *
- * Note: The calculation is made on the assumption that all space that
- * could be assigned to this resource would be assigned to this resource
- * (ie the unused discontiguous space could just as likely be assigned
- * to another competing resource).
- *
- * @return The number of available physical pages for this resource.
- */
- @Override
- public int getAvailablePhysicalPages() {
- int rtn = Conversions.bytesToPages(sentinel.diff(cursor));
- if (!contiguous)
- rtn += Map.getAvailableDiscontiguousChunks()*Space.PAGES_IN_CHUNK;
- return rtn;
- }
-
- /**
- * Allocate <code>pages</code> pages from this resource. Simply
- * bump the cursor, and fail if we hit the sentinel.<p>
- *
- * If the request can be satisfied, then ensure the pages are
- * mmpapped and zeroed before returning the address of the start of
- * the region. If the request cannot be satisfied, return zero.
- *
- * @param requestPages The number of pages to be allocated.
- * @return The start of the first page if successful, zero on
- * failure.
- */
- @Inline
- protected Address allocPages(int requestPages) {
- int pages = requestPages;
- boolean newChunk = false;
- lock();
- Address rtn = cursor;
- if (Space.chunkAlign(rtn, true).NE(currentChunk)) {
- newChunk = true;
- currentChunk = Space.chunkAlign(rtn, true);
- }
-
- if (metaDataPagesPerRegion != 0) {
- /* adjust allocation for metadata */
- Address regionStart = getRegionStart(cursor.plus(Conversions.pagesToBytes(pages)));
- Offset regionDelta = regionStart.diff(cursor);
- if (regionDelta.sGE(Offset.zero())) {
- /* start new region, so adjust pages and return address accordingly */
- pages += Conversions.bytesToPages(regionDelta) + metaDataPagesPerRegion;
- rtn = regionStart.plus(Conversions.pagesToBytes(metaDataPagesPerRegion));
- }
- }
- Extent bytes = Conversions.pagesToBytes(pages);
- Address tmp = cursor.plus(bytes);
-
- if (!contiguous && tmp.GT(sentinel)) {
- /* we're out of virtual memory within our discontiguous region, so ask for more */
- int requiredChunks = Space.requiredChunks(pages);
- start = space.growDiscontiguousSpace(requiredChunks);
- cursor = start;
- sentinel = cursor.plus(start.isZero() ? 0 : requiredChunks<<Space.LOG_BYTES_IN_CHUNK);
- rtn = cursor;
- tmp = cursor.plus(bytes);
- newChunk = true;
- }
- if (VM.VERIFY_ASSERTIONS)
- VM.assertions._assert(rtn.GE(cursor) && rtn.LT(cursor.plus(bytes)));
- if (tmp.GT(sentinel)) {
- unlock();
- return Address.zero();
- } else {
- Address old = cursor;
- cursor = tmp;
- commitPages(requestPages, pages);
- space.growSpace(old, bytes, newChunk);
- unlock();
- Mmapper.ensureMapped(old, pages);
- VM.memory.zero(old, bytes);
- VM.events.tracePageAcquired(space, rtn, pages);
- return rtn;
- }
- }
-
- /**
- * Adjust a page request to include metadata requirements, if any.<p>
- *
- * In this case we simply report the expected page cost. We can't use
- * worst case here because we would exhaust our budget every time.
- *
- * @param pages The size of the pending allocation in pages
- * @return The number of required pages, inclusive of any metadata
- */
- public int adjustForMetaData(int pages) {
- return (metaDataPagesPerRegion * pages) / EmbeddedMetaData.PAGES_IN_REGION;
- }
-
- /**
- * Adjust a page request to include metadata requirements, if any.<p>
- *
- * Note that there could be a race here, with multiple threads each
- * adjusting their request on account of the same single metadata
- * region. This should not be harmful, as the failing requests will
- * just retry, and if multiple requests succeed, only one of them
- * will actually have the metadata accounted against it, the others
- * will simply have more space than they originally requested.
- *
- * @param pages The size of the pending allocation in pages
- * @param begin The start address of the region assigned to this pending
- * request
- * @return The number of required pages, inclusive of any metadata
- */
- public int adjustForMetaData(int pages, Address begin) {
- if (getRegionStart(begin).plus(metaDataPagesPerRegion<<LOG_BYTES_IN_PAGE).EQ(begin))
- pages += metaDataPagesPerRegion;
- return pages;
- }
-
- private static Address getRegionStart(Address addr) {
- return addr.toWord().and(Word.fromIntSignExtend(EmbeddedMetaData.BYTES_IN_REGION - 1).not()).toAddress();
- }
-
- /**
- * Reset this page resource, freeing all pages and resetting
- * reserved and committed pages appropriately.
- */
- @Inline
- public void reset() {
- lock();
- reserved = 0;
- committed = 0;
- releasePages();
- unlock();
- }
-
- /**
- * Notify that several pages are no longer in use.
- *
- * @param pages The number of pages
- */
- public void unusePages(int pages) {
- lock();
- reserved -= pages;
- committed -= pages;
- unlock();
- }
-
- /**
- * Notify that previously unused pages are in use again.
- *
- * @param pages The number of pages
- */
- public void reusePages(int pages) {
- lock();
- reserved += pages;
- committed += pages;
- unlock();
- }
-
- /**
- * Release all pages associated with this page resource, optionally
- * zeroing on release and optionally memory protecting on release.
- */
- @Inline
- private void releasePages() {
- Address first = start;
- do {
- Extent bytes = cursor.diff(start).toWord().toExtent();
- releasePages(start, bytes);
- cursor = start;
- } while (!contiguous && moveToNextChunk());
- if (!contiguous) {
- sentinel = Address.zero();
- Map.freeAllChunks(first);
- }
- }
-
- /**
- * Adjust the start and cursor fields to point to the next chunk
- * in the linked list of chunks tied down by this page resource.
- *
- * @return True if we moved to the next chunk; false if we hit the
- * end of the linked list.
- */
- private boolean moveToNextChunk() {
- start = Map.getNextContiguousRegion(start);
- if (start.isZero())
- return false;
- else {
- cursor = start.plus(Map.getContiguousRegionSize(start));
- return true;
- }
- }
-
- /**
- * Release a range of pages associated with this page resource, optionally
- * zeroing on release and optionally memory protecting on release.
- */
- @Inline
- private void releasePages(Address first, Extent bytes) {
- int pages = Conversions.bytesToPages(bytes);
- if (VM.VERIFY_ASSERTIONS)
- VM.assertions._assert(bytes.EQ(Conversions.pagesToBytes(pages)));
- if (ZERO_ON_RELEASE)
- VM.memory.zero(first, bytes);
- if (Options.protectOnRelease.getValue())
- Mmapper.protect(first, pages);
- VM.events.tracePageReleased(space, first, pages);
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/utility/heap/PageResource.java b/vmkit/mmtk/java/src/org/mmtk/utility/heap/PageResource.java
deleted file mode 100644
index 2f4a47b..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/utility/heap/PageResource.java
+++ /dev/null
@@ -1,320 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.utility.heap;
-
-import org.mmtk.plan.Plan;
-import org.mmtk.policy.Space;
-import org.mmtk.utility.Constants;
-import org.mmtk.utility.options.ProtectOnRelease;
-import org.mmtk.utility.options.Options;
-
-import org.mmtk.vm.Lock;
-import org.mmtk.vm.VM;
-
-import org.vmmagic.pragma.*;
-import org.vmmagic.unboxed.*;
-
-/**
- * This class manages the allocation of pages for a space. When a
- * page is requested by the space both a page budget and the use of
- * virtual address space are checked. If the request for space can't
- * be satisfied (for either reason) a GC may be triggered.<p>
- *
- * This class is abstract, and is subclassed with monotone and
- * freelist variants, which reflect monotonic and ad hoc space usage
- * respectively. Monotonic use is easier to manage, but is obviously
- * more restrictive (useful for copying collectors which allocate
- * monotonically before freeing the entire space and starting over).
- */
-@Uninterruptible
-public abstract class PageResource implements Constants {
-
- /****************************************************************************
- *
- * Class variables
- */
- protected static final boolean ZERO_ON_RELEASE = false; // debugging
-
- private static final Lock classLock;
- private static long cumulativeCommitted = 0;
-
-
- /****************************************************************************
- *
- * Instance variables
- */
-
- // page budgeting
- protected int reserved;
- protected int committed;
- protected int required;
- private final int pageBudget;
-
- protected final boolean contiguous;
- protected final Space space;
- protected Address start; // only for contiguous
-
- // locking
- private final Lock gcLock; // used during GC
- private final Lock mutatorLock; // used by mutators
-
- /****************************************************************************
- *
- * Initialization
- */
- static {
- classLock = VM.newLock("PageResource");
- Options.protectOnRelease = new ProtectOnRelease();
- }
-
- /**
- * Constructor
- *
- * @param pageBudget The budget of pages available to this memory
- * manager before it must poll the collector.
- * @param space The space to which this resource is attached
- */
- private PageResource(int pageBudget, Space space, boolean contiguous) {
- this.pageBudget = pageBudget;
- this.contiguous = contiguous;
- this.space = space;
- gcLock = VM.newLock(space.getName() + ".gcLock");
- mutatorLock = VM.newLock(space.getName() + ".mutatorLock");
- }
-
- /**
- * Constructor for discontiguous spaces
- *
- * @param pageBudget The budget of pages available to this memory
- * manager before it must poll the collector.
- * @param space The space to which this resource is attached
- */
- PageResource(int pageBudget, Space space) {
- this(pageBudget, space, false);
- }
-
- /**
- * Constructor for contiguous spaces
- *
- * @param pageBudget The budget of pages available to this memory
- * manager before it must poll the collector.
- * @param space The space to which this resource is attached
- */
- PageResource(int pageBudget, Space space, Address start) {
- this(pageBudget, space, true);
- this.start = start;
- }
-
- /**
- * Return the number of available physical pages for this resource.
- *
- * Note: This just considers physical pages (ie virtual memory pages
- * allocated for use by this resource). This calculation is orthogonal
- * to and does not consider any restrictions on the number of pages
- * this resource may actually use at any time (ie the number of
- * committed and reserved pages).<p>
- *
- * Note: The calculation is made on the assumption that all space that
- * could be assigned to this resource would be assigned to this resource
- * (ie the unused discontiguous space could just as likely be assigned
- * to another competing resource).
- *
- * @return The number of available physical pages for this resource.
- */
- public abstract int getAvailablePhysicalPages();
-
- /**
- * Reserve pages.<p>
- *
- * The role of reserving pages is that it allows the request to be
- * noted as pending (the difference between committed and reserved
- * indicates pending requests). If the request would exceed the
- * page budget then the caller must poll in case a GC is necessary.
- *
- * @param pages The number of pages requested
- * @return True if the page budget could satisfy the request.
- */
- @Inline
- public final boolean reservePages(int pages) {
- lock();
- required += adjustForMetaData(pages);
- reserved = committed + required;
- boolean satisfied = reserved <= pageBudget;
- unlock();
- return satisfied;
- }
-
- /**
- * Remove a request to the space.
- *
- * @param pages The number of pages in the request.
- */
- @Inline
- public final void clearRequest(int pages) {
- lock();
- required -= adjustForMetaData(pages);
- unlock();
- }
-
- /**
- * Reserve pages unconditionally.<p>
- *
- * An example of where this is useful is in cases where it is
- * desirable to put some space aside as head-room. By
- * unconditionally reserving the pages, the pages are counted
- * against the collectors budget. When the space is actually
- * needed, the pages can be unconditionally released, freeing
- * the pages for other purposes.
- *
- * @param pages The number of pages to be unconditionally
- * reserved.
- */
- public final void unconditionallyReservePages(int pages) {
- lock();
- committed += pages;
- reserved += pages;
- unlock();
- }
-
- /**
- * Release pages unconditionally.<p>
- *
- * This call allows pages to be unconditionally removed from
- * the collectors page budget.
- *
- * @see #unconditionallyReservePages
- * @param pages The number of pages to be unconditionally
- * released.
- */
- public final void unconditionallyReleasePages(int pages) {
- lock();
- committed -= pages;
- reserved -= pages;
- unlock();
- }
-
- abstract Address allocPages(int pages);
-
- /**
- * Adjust a page request to include metadata requirements for a request
- * of the given size. This must be a pure function, that is it does not
- * depend on the state of the PageResource.
- *
- * @param pages The size of the pending allocation in pages
- * @return The number of required pages, inclusive of any metadata
- */
- public abstract int adjustForMetaData(int pages);
-
- /**
- * Allocate pages in virtual memory, returning zero on failure.<p>
- *
- * If the request cannot be satisfied, zero is returned and it
- * falls to the caller to trigger the GC.
- *
- * Call <code>allocPages</code> (subclass) to find the pages in
- * virtual memory. If successful then commit the pending page
- * request and return the address of the first page.
- *
- * @param pages The number of pages requested
- * @return The address of the first of <code>pages</code> pages, or
- * zero on failure.
- */
- @Inline
- public final Address getNewPages(int pages) {
- return allocPages(pages);
- }
-
- /**
- * Commit pages to the page budget. This is called after
- * successfully determining that the request can be satisfied by
- * both the page budget and virtual memory. This simply accounts
- * for the descrepency between <code>committed</code> and
- * <code>reserved</code> while the request was pending.
- *
- * This *MUST* be called by each PageResource during the
- * allocPages, and the caller must hold the lock.
- *
- * @param requestedPages The number of pages from this request
- * @param totalPages The number of pages
- */
- protected void commitPages(int requestedPages, int totalPages) {
- int predictedPages = adjustForMetaData(requestedPages);
- int delta = totalPages - predictedPages;
- required -= predictedPages;
- reserved += delta;
- committed += totalPages;
- if (!Plan.gcInProgress())
- addToCommitted(totalPages); // only count mutator pages
- }
-
- /**
- * Return the number of reserved pages
- *
- * @return The number of reserved pages.
- */
- public final int reservedPages() { return reserved; }
-
- /**
- * Return the number of committed pages
- *
- * @return The number of committed pages.
- */
- public final int committedPages() { return committed; }
-
- /**
- * Return the number of required pages
- *
- * @return The number of required pages.
- */
- public final int requiredPages() { return required; }
-
- /**
- * Return the cumulative number of committed pages
- *
- * @return The cumulative number of committed pages.
- */
- public static long cumulativeCommittedPages() { return cumulativeCommitted; }
-
- /**
- * Add to the total cumulative committed page count.
- *
- * @param pages The number of pages to be added.
- */
- private static void addToCommitted(int pages) {
- classLock.acquire();
- cumulativeCommitted += pages;
- classLock.release();
- }
-
- /**
- * Acquire the appropriate lock depending on whether the context is
- * GC or mutator.
- */
- protected final void lock() {
- if (Plan.gcInProgress())
- gcLock.acquire();
- else
- mutatorLock.acquire();
- }
-
- /**
- * Release the appropriate lock depending on whether the context is
- * GC or mutator.
- */
- protected final void unlock() {
- if (Plan.gcInProgress())
- gcLock.release();
- else
- mutatorLock.release();
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/utility/heap/SpaceDescriptor.java b/vmkit/mmtk/java/src/org/mmtk/utility/heap/SpaceDescriptor.java
deleted file mode 100644
index 131b7d6..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/utility/heap/SpaceDescriptor.java
+++ /dev/null
@@ -1,166 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.utility.heap;
-
-import org.mmtk.policy.Space;
-import org.mmtk.utility.Constants;
-
-import org.mmtk.vm.VM;
-
-import org.vmmagic.pragma.*;
-import org.vmmagic.unboxed.*;
-
-/**
- * This class manages the encoding and decoding of space descriptors.<p>
- *
- * Space descriptors are integers that encode a space's mapping into
- * virtual memory. For discontiguous spaces, they indicate
- * discontiguity and mapping must be done by consulting the space map.
- * For contiguous spaces, the space's address range is encoded into
- * the integer (using a fixed point notation).<p>
- *
- * The purpose of this class is to allow <code>static final int</code>
- * space descriptors to exist for each space, which can then be used
- * in tests to determine whether an object is in a space. A good
- * compiler can perform this decoding at compile time and produce
- * optimal code for the test.
- */
-@Uninterruptible public class SpaceDescriptor implements Constants {
-
- /****************************************************************************
- *
- * Class variables
- */
-
- private static final int TYPE_BITS = 2;
- private static final int TYPE_SHARED = 0;
- private static final int TYPE_CONTIGUOUS = 1;
- private static final int TYPE_CONTIGUOUS_HI = 3;
- private static final int TYPE_MASK = (1 << TYPE_BITS) - 1;
- private static final int SIZE_SHIFT = TYPE_BITS;
- private static final int SIZE_BITS = 10;
- private static final int SIZE_MASK = ((1 << SIZE_BITS) - 1) << SIZE_SHIFT;
- private static final int EXPONENT_SHIFT = SIZE_SHIFT + SIZE_BITS;
- private static final int EXPONENT_BITS = 5;
- private static final int EXPONENT_MASK = ((1 << EXPONENT_BITS) - 1) << EXPONENT_SHIFT;
- private static final int MANTISSA_SHIFT = EXPONENT_SHIFT + EXPONENT_BITS;
- private static final int MANTISSA_BITS = 14;
- private static final int BASE_EXPONENT = BITS_IN_INT - MANTISSA_BITS;
-
- private static int discontiguousSpaceIndex = 0;
- private static final int DISCONTIG_INDEX_INCREMENT = 1<<TYPE_BITS;
-
- /****************************************************************************
- *
- * Descriptor creation
- */
-
- /**
- * Create a descriptor for a <i>contiguous</i> space
- *
- * @param start The start address of the space
- * @param end The end address of the space
- * @return An integer descriptor encoding the region of virtual
- * memory occupied by the space
- */
- public static int createDescriptor(Address start, Address end) {
- int chunks = end.diff(start).toWord().rshl(Space.LOG_BYTES_IN_CHUNK).toInt();
- if (VM.VERIFY_ASSERTIONS)
- VM.assertions._assert(!start.isZero() && chunks > 0 && chunks < (1 << SIZE_BITS));
- boolean top = end.EQ(Space.HEAP_END);
- Word tmp = start.toWord();
- tmp = tmp.rshl(BASE_EXPONENT);
- int exponent = 0;
- while (!tmp.isZero() && tmp.and(Word.one()).isZero()) {
- tmp = tmp.rshl(1);
- exponent++;
- }
- int mantissa = tmp.toInt();
- if (VM.VERIFY_ASSERTIONS)
- VM.assertions._assert(tmp.lsh(BASE_EXPONENT + exponent).EQ(start.toWord()));
- return (mantissa<<MANTISSA_SHIFT) |
- (exponent<<EXPONENT_SHIFT) |
- (chunks << SIZE_SHIFT) |
- ((top) ? TYPE_CONTIGUOUS_HI : TYPE_CONTIGUOUS);
- }
-
- /**
- * Create a descriptor for a <i>dis-contiguous</i> (shared) space
- *
- * @return An integer descriptor reflecting the fact that this space
- * is shared (and thus discontiguous and so must be established via
- * maps).
- */
- public static int createDescriptor() {
- discontiguousSpaceIndex += DISCONTIG_INDEX_INCREMENT;
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert((discontiguousSpaceIndex & TYPE_CONTIGUOUS) != TYPE_CONTIGUOUS);
- return discontiguousSpaceIndex;
- }
-
- /****************************************************************************
- *
- * Descriptor interrogation
- */
-
- /**
- * Return true if this descriptor describes a contiguous space
- *
- * @param descriptor
- * @return True if this descriptor describes a contiguous space
- */
- @Inline
- public static boolean isContiguous(int descriptor) {
- return ((descriptor & TYPE_CONTIGUOUS) == TYPE_CONTIGUOUS);
- }
-
- /**
- * Return true if this descriptor describes a contiguous space that
- * is at the top of the virtual address space
- *
- * @param descriptor
- * @return True if this descriptor describes a contiguous space that
- * is at the top of the virtual address space
- */
- @Inline
- public static boolean isContiguousHi(int descriptor) {
- return ((descriptor & TYPE_MASK) == TYPE_CONTIGUOUS_HI);
- }
-
- /**
- * Return the start of this region of memory encoded in this descriptor
- *
- * @param descriptor
- * @return The start of this region of memory encoded in this descriptor
- */
- @Inline
- public static Address getStart(int descriptor) {
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(isContiguous(descriptor));
- Word mantissa = Word.fromIntSignExtend(descriptor >>> MANTISSA_SHIFT);
- int exponent = (descriptor & EXPONENT_MASK) >>> EXPONENT_SHIFT;
- return mantissa.lsh(BASE_EXPONENT + exponent).toAddress();
- }
-
- /**
- * Return the size of the region of memory encoded in this
- * descriptor, in chunks
- *
- * @param descriptor
- * @return The size of the region of memory encoded in this
- * descriptor, in chunks
- */
- @Inline
- public static int getChunks(int descriptor) {
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(isContiguous(descriptor));
- return (descriptor & SIZE_MASK) >>> SIZE_SHIFT;
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/utility/heap/VMRequest.java b/vmkit/mmtk/java/src/org/mmtk/utility/heap/VMRequest.java
deleted file mode 100644
index ab799db..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/utility/heap/VMRequest.java
+++ /dev/null
@@ -1,126 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.utility.heap;
-
-import org.mmtk.utility.Constants;
-
-import org.vmmagic.unboxed.*;
-
-/**
- * This class manages the encoding and decoding of virtual memory requests.
- *
- * By encapsulating this aspect of the construction of a space, we greatly
- * reduce the number of constructors required.
- */
-public final class VMRequest implements Constants {
-
- public static final int REQUEST_DISCONTIGUOUS = 0;
- public static final int REQUEST_FIXED = 1;
- public static final int REQUEST_EXTENT = 3;
- public static final int REQUEST_FRACTION = 4;
-
- public final int type;
- public final Address start;
- public final Extent extent;
- public final float frac;
- public final boolean top;
-
- private VMRequest(int type, Address start, Extent bytes, float frac, boolean top) {
- this.type = type;
- this.start = start;
- this.extent = bytes;
- this.frac = frac;
- this.top = top;
- }
-
- /**
- * Is this a discontiguous space request?
- * @return true if this is a discontiguous space request, false otherwise
- */
- public boolean isDiscontiguous() {
- return type == REQUEST_DISCONTIGUOUS;
- }
-
- /**
- * A request for a discontiguous region of memory
- *
- * @return The request object
- */
- public static VMRequest create() {
- return new VMRequest(REQUEST_DISCONTIGUOUS, Address.zero(), Extent.zero(), 0f, false);
- }
-
- /**
- * A request for an explicit region of memory
- *
- * @param start The start of the region
- * @param extent The size of the region
- * @return The request object
- */
- public static VMRequest create(Address start, Extent extent) {
- return new VMRequest(REQUEST_FIXED, start, extent, 0f, false);
- }
-
- /**
- * A request for a number of megabytes of memory
- *
- * @param mb The number of megabytes
- * @return The request object
- */
- public static VMRequest create(int mb) {
- return create(mb, false);
- }
-
- /**
- * A request for a fraction of available memory
- *
- * @param frac The fraction
- * @return The request object
- */
- public static VMRequest create(float frac) {
- return create(frac, false);
- }
-
- /**
- * A request for a number of megabytes of memory, optionally requesting the highest available.
- *
- * @param mb The number of megabytes
- * @param top True to request high memory
- * @return The request object
- */
- public static VMRequest create(int mb, boolean top) {
- return new VMRequest(REQUEST_EXTENT, Address.zero(), Word.fromIntSignExtend(mb).lsh(LOG_BYTES_IN_MBYTE).toExtent(), 0f, top);
- }
-
- /**
- * A request for a fraction of available memory, optionally requesting the highest available.
- *
- * @param frac The fraction
- * @param top True to request high memory
- * @return The request object
- */
- public static VMRequest create(float frac, boolean top) {
- return new VMRequest(REQUEST_FRACTION, Address.zero(), Extent.zero(), frac, top);
- }
-
- /**
- * A request for a number of bytes of memory, optionally requesting the highest available.
- *
- * @param extent The number of bytes
- * @param top True to request high memory
- * @return The request object
- */
- public static VMRequest create(Extent extent, boolean top) {
- return new VMRequest(REQUEST_EXTENT, Address.zero(), extent, 0f, top);
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/utility/options/BoundedNursery.java b/vmkit/mmtk/java/src/org/mmtk/utility/options/BoundedNursery.java
deleted file mode 100644
index 780202f..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/utility/options/BoundedNursery.java
+++ /dev/null
@@ -1,37 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.utility.options;
-
-import org.mmtk.plan.Plan;
-
-/**
- * Provide an upper bound on nursery size. This option is not intended to
- * be created directly, but via NurserySize.
- */
-public final class BoundedNursery extends org.vmutil.options.PagesOption {
- /**
- * Create the option.
- */
- public BoundedNursery() {
- super(Options.set, "Bounded Nursery",
- "Bound the maximum size of the nursery to this value",
- Plan.DEFAULT_MAX_NURSERY);
- }
-
- /**
- * Nursery can not be empty.
- */
- protected void validate() {
- failIf(value <= 0, "Can not have an empty nursery");
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/utility/options/ConcurrentTrigger.java b/vmkit/mmtk/java/src/org/mmtk/utility/options/ConcurrentTrigger.java
deleted file mode 100644
index 96dfe30..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/utility/options/ConcurrentTrigger.java
+++ /dev/null
@@ -1,35 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.utility.options;
-
-/**
- * Concurrent trigger percentage
- */
-public class ConcurrentTrigger extends org.vmutil.options.IntOption {
- /**
- * Create the option.
- */
- public ConcurrentTrigger() {
- super(Options.set, "Concurrent Trigger",
- "Concurrent trigger percentage",
- 50);
- }
-
- /**
- * Only accept values between 1 and 100 (inclusive)
- */
- protected void validate() {
- failIf(this.value <= 0, "Trigger must be between 1 and 100");
- failIf(this.value > 100, "Trigger must be between 1 and 100");
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/utility/options/CycleFilterThreshold.java b/vmkit/mmtk/java/src/org/mmtk/utility/options/CycleFilterThreshold.java
deleted file mode 100644
index 1317363..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/utility/options/CycleFilterThreshold.java
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.utility.options;
-
-/**
- * Trigger cycle buffer filtering if the space available falls below this threshold.
- */
-public final class CycleFilterThreshold extends org.vmutil.options.PagesOption {
- /**
- * Create the option.
- */
- public CycleFilterThreshold() {
- super(Options.set, "Cycle Filter Threshold",
- "Trigger cycle buffer filtering if the space available falls below this threshold",
- 512);
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/utility/options/CycleMetaDataLimit.java b/vmkit/mmtk/java/src/org/mmtk/utility/options/CycleMetaDataLimit.java
deleted file mode 100644
index fadede5..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/utility/options/CycleMetaDataLimit.java
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.utility.options;
-
-/**
- * Trigger cycle detection if the meta data volume grows to this limit.
- */
-public final class CycleMetaDataLimit extends org.vmutil.options.PagesOption {
- /**
- * Create the option.
- */
- public CycleMetaDataLimit() {
- super(Options.set, "Cycle Meta Data Limit",
- "Trigger cycle detection if the meta data volume grows to this limit",
- 4096);
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/utility/options/CycleTriggerThreshold.java b/vmkit/mmtk/java/src/org/mmtk/utility/options/CycleTriggerThreshold.java
deleted file mode 100644
index 9a266b0..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/utility/options/CycleTriggerThreshold.java
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.utility.options;
-
-/**
- * Trigger cycle detection if the space available falls below this threshold.
- */
-public final class CycleTriggerThreshold extends org.vmutil.options.PagesOption {
- /**
- * Create the option.
- */
- public CycleTriggerThreshold() {
- super(Options.set, "Cycle Trigger Threshold",
- "Trigger cycle detection if the space available falls below this threshold",
- 512);
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/utility/options/DebugAddress.java b/vmkit/mmtk/java/src/org/mmtk/utility/options/DebugAddress.java
deleted file mode 100644
index 3004b0e..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/utility/options/DebugAddress.java
+++ /dev/null
@@ -1,29 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.utility.options;
-
-import org.vmmagic.unboxed.Address;
-
-/**
- * Allow an address to be specified on the command line for use in debugging.
- */
-public final class DebugAddress extends org.vmutil.options.AddressOption {
- /**
- * Create the option
- */
- public DebugAddress() {
- super(Options.set, "Debug Address",
- "Specify an address at runtime for use in debugging",
- Address.zero());
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/utility/options/DefragFreeHeadroom.java b/vmkit/mmtk/java/src/org/mmtk/utility/options/DefragFreeHeadroom.java
deleted file mode 100644
index cd5228e..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/utility/options/DefragFreeHeadroom.java
+++ /dev/null
@@ -1,26 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.utility.options;
-
-import static org.mmtk.policy.immix.ImmixConstants.DEFAULT_DEFRAG_FREE_HEADROOM;
-
-public class DefragFreeHeadroom extends org.vmutil.options.PagesOption {
- /**
- * Create the option.
- */
- public DefragFreeHeadroom() {
- super(Options.set, "Defrag Free Headroom",
- "Allow the defragmenter this amount of free headroom during defrag. For analysis purposes only!",
- DEFAULT_DEFRAG_FREE_HEADROOM);
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/utility/options/DefragFreeHeadroomFraction.java b/vmkit/mmtk/java/src/org/mmtk/utility/options/DefragFreeHeadroomFraction.java
deleted file mode 100644
index 7c95149..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/utility/options/DefragFreeHeadroomFraction.java
+++ /dev/null
@@ -1,33 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.utility.options;
-
-import static org.mmtk.policy.immix.ImmixConstants.DEFAULT_DEFRAG_FREE_HEADROOM_FRACTION;
-
-public class DefragFreeHeadroomFraction extends org.vmutil.options.FloatOption {
- /**
- * Create the option.
- */
- public DefragFreeHeadroomFraction() {
- super(Options.set, "Defrag Free Headroom Fraction",
- "Allow the defragmenter this fraction of the heap size as free headroom during defrag. For analysis purposes only!",
- DEFAULT_DEFRAG_FREE_HEADROOM_FRACTION);
- }
-
- /**
- * Ensure the value is valid.
- */
- protected void validate() {
- failIf((this.value < 0 || this.value > 1.0), "Ratio must be a float between 0 and 1");
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/utility/options/DefragHeadroom.java b/vmkit/mmtk/java/src/org/mmtk/utility/options/DefragHeadroom.java
deleted file mode 100644
index 9bd3a51..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/utility/options/DefragHeadroom.java
+++ /dev/null
@@ -1,28 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.utility.options;
-
-import static org.mmtk.policy.immix.ImmixConstants.DEFAULT_DEFRAG_HEADROOM;
-
-/**
- */
-public class DefragHeadroom extends org.vmutil.options.PagesOption {
- /**
- * Create the option.
- */
- public DefragHeadroom() {
- super(Options.set, "Defrag Headroom",
- "Allow the defragmenter this amount of headroom during defrag.",
- DEFAULT_DEFRAG_HEADROOM);
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/utility/options/DefragHeadroomFraction.java b/vmkit/mmtk/java/src/org/mmtk/utility/options/DefragHeadroomFraction.java
deleted file mode 100644
index 975915c..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/utility/options/DefragHeadroomFraction.java
+++ /dev/null
@@ -1,33 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.utility.options;
-
-import static org.mmtk.policy.immix.ImmixConstants.DEFAULT_DEFRAG_HEADROOM_FRACTION;
-
-public class DefragHeadroomFraction extends org.vmutil.options.FloatOption {
- /**
- * Create the option.
- */
- public DefragHeadroomFraction() {
- super(Options.set, "Defrag Headroom Fraction",
- "Allow the defrag this fraction of the heap as headroom during defrag.",
- DEFAULT_DEFRAG_HEADROOM_FRACTION);
- }
-
- /**
- * Ensure the value is valid.
- */
- protected void validate() {
- failIf((this.value < 0 || this.value > 1.0), "Ratio must be a float between 0 and 1");
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/utility/options/DefragLineReuseRatio.java b/vmkit/mmtk/java/src/org/mmtk/utility/options/DefragLineReuseRatio.java
deleted file mode 100644
index 333c171..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/utility/options/DefragLineReuseRatio.java
+++ /dev/null
@@ -1,33 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.utility.options;
-
-import static org.mmtk.policy.immix.ImmixConstants.DEFAULT_DEFRAG_LINE_REUSE_RATIO;
-
-public class DefragLineReuseRatio extends org.vmutil.options.FloatOption {
- /**
- * Create the option.
- */
- public DefragLineReuseRatio() {
- super(Options.set, "Defrag Line Reuse Ratio",
- "Blocks with this fraction marked may be reused for defrag allocation",
- DEFAULT_DEFRAG_LINE_REUSE_RATIO);
- }
-
- /**
- * Ensure the value is valid.
- */
- protected void validate() {
- failIf((this.value <= 0 || this.value > 1.0), "Ratio must be a float between 0 and 1");
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/utility/options/DefragSimpleSpillThreshold.java b/vmkit/mmtk/java/src/org/mmtk/utility/options/DefragSimpleSpillThreshold.java
deleted file mode 100644
index ed32210..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/utility/options/DefragSimpleSpillThreshold.java
+++ /dev/null
@@ -1,33 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.utility.options;
-
-import static org.mmtk.policy.immix.ImmixConstants.DEFAULT_SIMPLE_SPILL_THRESHOLD;
-
-public class DefragSimpleSpillThreshold extends org.vmutil.options.FloatOption {
- /**
- * Create the option.
- */
- public DefragSimpleSpillThreshold() {
- super(Options.set, "Defrag Simple Spill Threshold",
- "Blocks with this fraction spilled will be defrag sources",
- DEFAULT_SIMPLE_SPILL_THRESHOLD);
- }
-
- /**
- * Ensure the value is valid.
- */
- protected void validate() {
- failIf((this.value <= 0 || this.value > 1.0), "Ratio must be a float between 0 and 1");
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/utility/options/DefragStress.java b/vmkit/mmtk/java/src/org/mmtk/utility/options/DefragStress.java
deleted file mode 100644
index b369ada..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/utility/options/DefragStress.java
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.utility.options;
-
-/**
- * Should we force degfrag every time the immix space is collected?
- */
-public final class DefragStress extends org.vmutil.options.BooleanOption {
- /**
- * Create the option.
- */
- public DefragStress() {
- super(Options.set, "Defrag Stress",
- "Should we force degfrag every time the immix space is collected?",
- false);
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/utility/options/DummyEnum.java b/vmkit/mmtk/java/src/org/mmtk/utility/options/DummyEnum.java
deleted file mode 100644
index e1b9cc7..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/utility/options/DummyEnum.java
+++ /dev/null
@@ -1,33 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.utility.options;
-
-/**
- * A sample enumeration for testing.
- */
-public final class DummyEnum extends org.vmutil.options.EnumOption {
-
- // enumeration values.
- public final int FOO = 0;
- public final int BAR = 1;
-
- /**
- * Create the option.
- */
- public DummyEnum() {
- super(Options.set, "Dummy Enum",
- "This is a sample enumeration to test the options system",
- new String[] {"foo", "bar"},
- "foo");
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/utility/options/EagerCompleteSweep.java b/vmkit/mmtk/java/src/org/mmtk/utility/options/EagerCompleteSweep.java
deleted file mode 100644
index 6c0b084..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/utility/options/EagerCompleteSweep.java
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.utility.options;
-
-/**
- * Should we eagerly finish sweeping at the start of a collection
- */
-public final class EagerCompleteSweep extends org.vmutil.options.BooleanOption {
- /**
- * Create the option.
- */
- public EagerCompleteSweep() {
- super(Options.set, "Eager Complete Sweep",
- "Should we eagerly finish sweeping at the start of a collection",
- false);
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/utility/options/EagerMmapSpaces.java b/vmkit/mmtk/java/src/org/mmtk/utility/options/EagerMmapSpaces.java
deleted file mode 100644
index 9768956..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/utility/options/EagerMmapSpaces.java
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.utility.options;
-
-/**
- * Should spaces be eagerly demand zero mmapped?
- */
-public final class EagerMmapSpaces extends org.vmutil.options.BooleanOption {
- /**
- * Create the option.
- */
- public EagerMmapSpaces() {
- super(Options.set, "Eager Mmap Spaces",
- "If true, all spaces are eagerly demand zero mmapped at boot time",
- false);
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/utility/options/EchoOptions.java b/vmkit/mmtk/java/src/org/mmtk/utility/options/EchoOptions.java
deleted file mode 100644
index 2d407c9..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/utility/options/EchoOptions.java
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.utility.options;
-
-/**
- * Echo when options are set?
- */
-public final class EchoOptions extends org.vmutil.options.BooleanOption {
- /**
- * Create the option.
- */
- public EchoOptions() {
- super(Options.set, "Echo Options",
- "Echo when options are set?",
- false);
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/utility/options/FixedNursery.java b/vmkit/mmtk/java/src/org/mmtk/utility/options/FixedNursery.java
deleted file mode 100644
index 1e8a9bf..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/utility/options/FixedNursery.java
+++ /dev/null
@@ -1,44 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.utility.options;
-
-import org.mmtk.plan.Plan;
-
-/**
- * Provide an lower and upper bound on nursery size.
- *
- * This option is not intended to be created directly, but via NurserySize.
- */
-public final class FixedNursery extends org.vmutil.options.PagesOption {
- // values
- BoundedNursery boundedNursery;
-
- /**
- * Create the option
- */
- public FixedNursery(BoundedNursery boundedNursery) {
- super(Options.set, "Fixed Nursery",
- "Fix the minimum and maximum size of the nursery to this value",
- Plan.DEFAULT_MIN_NURSERY);
- this.boundedNursery = boundedNursery;
- }
-
- /**
- * Nursery can not be empty.
- */
- protected void validate() {
- failIf(value <= 0, "Can not have an empty nursery");
- // Update upper bound.
- boundedNursery.setBytes(this.getBytes());
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/utility/options/FragmentationStats.java b/vmkit/mmtk/java/src/org/mmtk/utility/options/FragmentationStats.java
deleted file mode 100644
index c4ca085..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/utility/options/FragmentationStats.java
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.utility.options;
-
-/**
- * Option to print fragmentation information for the free list.
- */
-public final class FragmentationStats extends org.vmutil.options.BooleanOption {
- /**
- * Create the option.
- */
- public FragmentationStats() {
- super(Options.set, "Fragmentation Stats",
- "Should we print fragmentation statistics for the free list allocator?",
- false);
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/utility/options/FullHeapSystemGC.java b/vmkit/mmtk/java/src/org/mmtk/utility/options/FullHeapSystemGC.java
deleted file mode 100644
index 3738567..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/utility/options/FullHeapSystemGC.java
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.utility.options;
-
-/**
- * Should a major GC be performed when a system GC is triggered?
- */
-public final class FullHeapSystemGC extends org.vmutil.options.BooleanOption {
- /**
- * Create the option.
- */
- public FullHeapSystemGC() {
- super(Options.set, "Full Heap System GC",
- "Should a major GC be performed when a system GC is triggered?",
- false);
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/utility/options/GCTimeCap.java b/vmkit/mmtk/java/src/org/mmtk/utility/options/GCTimeCap.java
deleted file mode 100644
index 871c5af..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/utility/options/GCTimeCap.java
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.utility.options;
-
-/**
- * Try to limit reference counting collections to this time cap.
- */
-public final class GCTimeCap extends org.vmutil.options.MicrosecondsOption {
- /**
- * Create the option.
- */
- public GCTimeCap() {
- super(Options.set, "GC Time Cap",
- "Try to limit reference counting collections to this time cap",
- 1000000);
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/utility/options/GCspyPort.java b/vmkit/mmtk/java/src/org/mmtk/utility/options/GCspyPort.java
deleted file mode 100644
index c12c338..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/utility/options/GCspyPort.java
+++ /dev/null
@@ -1,34 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.utility.options;
-
-/**
- * Port number for GCSpy server to connect with visualiser.
- */
-public final class GCspyPort extends org.vmutil.options.IntOption {
- /**
- * Create the option.
- */
- public GCspyPort() {
- super(Options.set, "GCSpy Port",
- "Port number for GCSpy server to connect with visualiser",
- 0);
- }
-
- /**
- * Ensure the port is valid.
- */
- protected void validate() {
- failIf(this.value <= 0, "Unreasonable GCSpy port value");
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/utility/options/GCspyTileSize.java b/vmkit/mmtk/java/src/org/mmtk/utility/options/GCspyTileSize.java
deleted file mode 100644
index 29d383e..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/utility/options/GCspyTileSize.java
+++ /dev/null
@@ -1,34 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.utility.options;
-
-/**
- * GCspy Tile Size.
- */
-public final class GCspyTileSize extends org.vmutil.options.IntOption {
- /**
- * Create the option.
- */
- public GCspyTileSize() {
- super(Options.set, "GCspy Tile Size",
- "GCspy Tile Size",
- 131072);
- }
-
- /**
- * Ensure the tile size is positive
- */
- protected void validate() {
- failIf(this.value <= 0, "Unreasonable gcspy tilesize");
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/utility/options/GCspyWait.java b/vmkit/mmtk/java/src/org/mmtk/utility/options/GCspyWait.java
deleted file mode 100644
index 06108cb..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/utility/options/GCspyWait.java
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.utility.options;
-
-/**
- * Should the VM wait for the visualiser to connect?
- */
-public final class GCspyWait extends org.vmutil.options.BooleanOption {
- /**
- * Create the option
- */
- public GCspyWait() {
- super(Options.set, "GCSpy Wait",
- "Should the VM wait for the visualiser to connect?",
- false);
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/utility/options/GenCycleDetection.java b/vmkit/mmtk/java/src/org/mmtk/utility/options/GenCycleDetection.java
deleted file mode 100644
index 9279261..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/utility/options/GenCycleDetection.java
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.utility.options;
-
-/**
- * Should we use a generational approach to cycle detection?
- */
-public final class GenCycleDetection extends org.vmutil.options.BooleanOption {
- /**
- * Create the option.
- */
- public GenCycleDetection() {
- super(Options.set, "Gen Cycle Detection",
- "Should we use a generational approach to cycle detection?",
- false);
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/utility/options/HarnessAll.java b/vmkit/mmtk/java/src/org/mmtk/utility/options/HarnessAll.java
deleted file mode 100644
index a688a6f..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/utility/options/HarnessAll.java
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.utility.options;
-
-/**
- * Should we wrap the entire execution with a harnessBegin/harnessEnd?
- */
-public final class HarnessAll extends org.vmutil.options.BooleanOption {
- /**
- * Create the option.
- */
- public HarnessAll() {
- super(Options.set, "Harness All",
- "Should we wrap the entire execution inside calls to harnessBegin and harnessEnd?",
- false);
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/utility/options/IgnoreSystemGC.java b/vmkit/mmtk/java/src/org/mmtk/utility/options/IgnoreSystemGC.java
deleted file mode 100644
index 1f2d7ca..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/utility/options/IgnoreSystemGC.java
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.utility.options;
-
-/**
- * Should we ignore calls to java.lang.System.gc?
- */
-public final class IgnoreSystemGC extends org.vmutil.options.BooleanOption {
- /**
- * Create the option.
- */
- public IgnoreSystemGC() {
- super(Options.set, "Ignore System GC",
- "Should we ignore calls to java.lang.System.gc?",
- false);
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/utility/options/LineReuseRatio.java b/vmkit/mmtk/java/src/org/mmtk/utility/options/LineReuseRatio.java
deleted file mode 100644
index ca676b9..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/utility/options/LineReuseRatio.java
+++ /dev/null
@@ -1,35 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.utility.options;
-
-import static org.mmtk.policy.immix.ImmixConstants.DEFAULT_LINE_REUSE_RATIO;
-
-/**
- */
-public class LineReuseRatio extends org.vmutil.options.FloatOption {
- /**
- * Create the option.
- */
- public LineReuseRatio() {
- super(Options.set, "Line Reuse Ratio",
- "Blocks with this fraction marked may be reused for allocation",
- DEFAULT_LINE_REUSE_RATIO);
- }
-
- /**
- * Ensure the value is valid.
- */
- protected void validate() {
- failIf((this.value <= 0 || this.value > 1.0), "Ratio must be a float between 0 and 1");
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/utility/options/MarkSweepMarkBits.java b/vmkit/mmtk/java/src/org/mmtk/utility/options/MarkSweepMarkBits.java
deleted file mode 100644
index 53212cd..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/utility/options/MarkSweepMarkBits.java
+++ /dev/null
@@ -1,37 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.utility.options;
-
-import org.mmtk.policy.MarkSweepSpace;
-
-/**
- * Number of bits to use for the header cycle of mark sweep spaces.
- */
-public final class MarkSweepMarkBits extends org.vmutil.options.IntOption {
- /**
- * Create the option.
- */
- public MarkSweepMarkBits() {
- super(Options.set, "Mark Sweep Mark Bits",
- "Number of bits to use for the header cycle of mark sweep spaces",
- MarkSweepSpace.DEFAULT_MARKCOUNT_BITS);
- }
-
- /**
- * Ensure the value is valid.
- */
- protected void validate() {
- failIf(this.value <= 0, "Must provide at least one bit");
- failIf(this.value > MarkSweepSpace.MAX_MARKCOUNT_BITS , "Only "+MarkSweepSpace.MAX_MARKCOUNT_BITS+" bits are reserved in MarkSweepSpace");
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/utility/options/MetaDataLimit.java b/vmkit/mmtk/java/src/org/mmtk/utility/options/MetaDataLimit.java
deleted file mode 100644
index f4f6477..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/utility/options/MetaDataLimit.java
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.utility.options;
-
-/**
- * Provide a bound on how much metadata is allowed before a GC is triggered.
- */
-public final class MetaDataLimit extends org.vmutil.options.PagesOption {
- /**
- * Create the option.
- */
- public MetaDataLimit() {
- super(Options.set, "Meta Data Limit",
- "Trigger a GC if the meta data volume grows to this limit",
- 4096);
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/utility/options/NoFinalizer.java b/vmkit/mmtk/java/src/org/mmtk/utility/options/NoFinalizer.java
deleted file mode 100644
index e08e28b..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/utility/options/NoFinalizer.java
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.utility.options;
-
-/**
- * Should finalization be disabled?
- */
-public final class NoFinalizer extends org.vmutil.options.BooleanOption {
- /**
- * Create the option.
- */
- public NoFinalizer() {
- super(Options.set, "No Finalizer",
- "Should finalization be disabled?",
- false);
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/utility/options/NoReferenceTypes.java b/vmkit/mmtk/java/src/org/mmtk/utility/options/NoReferenceTypes.java
deleted file mode 100644
index 3351c6c..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/utility/options/NoReferenceTypes.java
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.utility.options;
-
-/**
- * Should reference type processing be disabled?
- */
-public final class NoReferenceTypes extends org.vmutil.options.BooleanOption {
- /**
- * Create the option.
- */
- public NoReferenceTypes() {
- super(Options.set, "No Reference Types",
- "Should reference type processing be disabled?",
- false);
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/utility/options/NurserySize.java b/vmkit/mmtk/java/src/org/mmtk/utility/options/NurserySize.java
deleted file mode 100644
index 81e6e7b..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/utility/options/NurserySize.java
+++ /dev/null
@@ -1,53 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.utility.options;
-
-import org.vmmagic.pragma.*;
-
-/**
- * A composite option that provides a min/max interface to MMTk,
- * and a fixed/bounded option interface to the VM/user.
- */
-public final class NurserySize {
- // values
- private FixedNursery fixedNursery;
- private BoundedNursery boundedNursery;
-
- /**
- * Create the options.
- */
- public NurserySize() {
- boundedNursery = new BoundedNursery();
- fixedNursery = new FixedNursery(boundedNursery);
- }
-
- /**
- * Read the upper bound of the nursery size.
- *
- * @return maximum number of pages in the nursery.
- */
- @Uninterruptible
- public int getMaxNursery() {
- return boundedNursery.getPages();
- }
-
- /**
- * Read the lower bound of the nursery size.
- *
- * @return minimum number of pages in the nursery.
- */
- @Uninterruptible
- public int getMinNursery() {
- return fixedNursery.getPages();
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/utility/options/Options.java b/vmkit/mmtk/java/src/org/mmtk/utility/options/Options.java
deleted file mode 100644
index eea65ec..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/utility/options/Options.java
+++ /dev/null
@@ -1,67 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.utility.options;
-
-import org.vmutil.options.OptionSet;
-
-/**
- * Repository for all option instances.
- */
-public final class Options {
- public static OptionSet set;
-
- /* Other options */
- public static BoundedNursery boundedNursery;
- public static ConcurrentTrigger concurrentTrigger;
- public static CycleFilterThreshold cycleFilterThreshold;
- public static CycleMetaDataLimit cycleMetaDataLimit;
- public static CycleTriggerThreshold cycleTriggerThreshold;
- public static DebugAddress debugAddress;
- public static DummyEnum dummyEnum;
- public static DefragHeadroom defragHeadroom;
- public static DefragHeadroomFraction defragHeadroomFraction;
- public static DefragFreeHeadroom defragFreeHeadroom;
- public static DefragFreeHeadroomFraction defragFreeHeadroomFraction;
- public static DefragLineReuseRatio defragLineReuseRatio;
- public static DefragSimpleSpillThreshold defragSimpleSpillThreshold;
- public static DefragStress defragStress;
- public static EagerCompleteSweep eagerCompleteSweep;
- public static EagerMmapSpaces eagerMmapSpaces;
- public static FixedNursery fixedNursery;
- public static FragmentationStats fragmentationStats;
- public static FullHeapSystemGC fullHeapSystemGC;
- public static GCspyPort gcspyPort;
- public static GCspyTileSize gcspyTileSize;
- public static GCspyWait gcspyWait;
- public static GCTimeCap gcTimeCap;
- public static GenCycleDetection genCycleDetection;
- public static HarnessAll harnessAll;
- public static IgnoreSystemGC ignoreSystemGC;
- public static LineReuseRatio lineReuseRatio;
- public static MarkSweepMarkBits markSweepMarkBits;
- public static MetaDataLimit metaDataLimit;
- public static NoFinalizer noFinalizer;
- public static NoReferenceTypes noReferenceTypes;
- public static NurserySize nurserySize;
- public static PerfEvents perfEvents;
- public static PrintPhaseStats printPhaseStats;
- public static ProtectOnRelease protectOnRelease;
- public static SanityCheck sanityCheck;
- public static StressFactor stressFactor;
- public static TraceRate traceRate;
- public static VariableSizeHeap variableSizeHeap;
- public static VerboseFragmentationStats verboseFragmentationStats;
- public static Verbose verbose;
- public static VerboseTiming verboseTiming;
- public static XmlStats xmlStats;
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/utility/options/PerfEvents.java b/vmkit/mmtk/java/src/org/mmtk/utility/options/PerfEvents.java
deleted file mode 100644
index fe28a30..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/utility/options/PerfEvents.java
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.utility.options;
-
-/**
- * Performance counter options.
- */
-public class PerfEvents extends org.vmutil.options.StringOption {
- /**
- * Create the option.
- */
- public PerfEvents() {
- super(Options.set, "Perf Events",
- "Use this to specify a comma seperated list of performance events to measure",
- "");
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/utility/options/PrintPhaseStats.java b/vmkit/mmtk/java/src/org/mmtk/utility/options/PrintPhaseStats.java
deleted file mode 100644
index ab56ad9..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/utility/options/PrintPhaseStats.java
+++ /dev/null
@@ -1,28 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.utility.options;
-
-/**
- * When printing statistics, should statistics for each
- * gc-mutator phase be printed?
- */
-public final class PrintPhaseStats extends org.vmutil.options.BooleanOption {
- /**
- * Create the option.
- */
- public PrintPhaseStats() {
- super(Options.set, "Print Phase Stats",
- "When printing statistics, should statistics for each gc-mutator phase be printed?",
- false);
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/utility/options/ProtectOnRelease.java b/vmkit/mmtk/java/src/org/mmtk/utility/options/ProtectOnRelease.java
deleted file mode 100644
index 4d8bc71..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/utility/options/ProtectOnRelease.java
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.utility.options;
-
-/**
- * Should memory be protected on release?
- */
-public final class ProtectOnRelease extends org.vmutil.options.BooleanOption {
- /**
- * Create the option.
- */
- public ProtectOnRelease() {
- super(Options.set, "Protect On Release",
- "Should memory be protected on release?",
- false);
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/utility/options/SanityCheck.java b/vmkit/mmtk/java/src/org/mmtk/utility/options/SanityCheck.java
deleted file mode 100644
index c939b46..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/utility/options/SanityCheck.java
+++ /dev/null
@@ -1,28 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.utility.options;
-
-
-/**
- * Should a major GC be performed when a system GC is triggered?
- */
-public final class SanityCheck extends org.vmutil.options.BooleanOption {
- /**
- * Create the option.
- */
- public SanityCheck() {
- super(Options.set, "Sanity Check",
- "Perform sanity checks before and after each collection?",
- false);
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/utility/options/StressFactor.java b/vmkit/mmtk/java/src/org/mmtk/utility/options/StressFactor.java
deleted file mode 100644
index 82705d0..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/utility/options/StressFactor.java
+++ /dev/null
@@ -1,38 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.utility.options;
-
-import org.mmtk.plan.Plan;
-import org.mmtk.utility.Constants;
-
-/**
- * Force frequent collections after amounts of allocation.
- */
-public final class StressFactor extends org.vmutil.options.PagesOption {
- /**
- * Create the option, defaulting to the maximum possible value.
- */
- public StressFactor() {
- super(Options.set, "Stress Factor",
- "Force a collection after this much allocation",
- Integer.MAX_VALUE >>> Constants.LOG_BYTES_IN_PAGE);
- }
-
- /**
- * Ensure that the value is sensible.
- */
- public void validate() {
- failIf(this.value < Plan.DEFAULT_POLL_FREQUENCY,
- "Stress Factor must be at least equal to plan's poll frequency");
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/utility/options/TraceRate.java b/vmkit/mmtk/java/src/org/mmtk/utility/options/TraceRate.java
deleted file mode 100644
index 9b54262..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/utility/options/TraceRate.java
+++ /dev/null
@@ -1,47 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.utility.options;
-
-import org.vmmagic.pragma.*;
-
-/**
- * The granularity of the trace being produced.
- */
-public final class TraceRate extends org.vmutil.options.IntOption
- implements org.mmtk.utility.Constants {
- /**
- * Create the option.
- */
- public TraceRate() {
- super(Options.set, "Trace Rate",
- "The granularity of the trace being produced. By default, the trace has the maximum possible granularity.",
- Integer.MAX_VALUE);
- }
-
- /**
- * Return the appropriate value.
- *
- * @return the trace rate.
- */
- @Uninterruptible
- public int getValue() {
- return (this.value < BYTES_IN_ADDRESS) ? 1 : (this.value >> LOG_BYTES_IN_ADDRESS);
- }
-
- /**
- * Trace rate must be positive.
- */
- protected void validate() {
- failIf(value <= 0, "Can not have a negative trace rate");
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/utility/options/VariableSizeHeap.java b/vmkit/mmtk/java/src/org/mmtk/utility/options/VariableSizeHeap.java
deleted file mode 100644
index 8fd46ed..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/utility/options/VariableSizeHeap.java
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.utility.options;
-
-/**
- * Should we shrink/grow the heap to adjust to application working set?
- */
-public final class VariableSizeHeap extends org.vmutil.options.BooleanOption {
- /**
- * Create the option.
- */
- public VariableSizeHeap() {
- super(Options.set, "Variable Size Heap",
- "Should we shrink/grow the heap to adjust to application working set?",
- true);
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/utility/options/Verbose.java b/vmkit/mmtk/java/src/org/mmtk/utility/options/Verbose.java
deleted file mode 100644
index be7fd85..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/utility/options/Verbose.java
+++ /dev/null
@@ -1,34 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.utility.options;
-
-/**
- * GC verbosity level.
- */
-public final class Verbose extends org.vmutil.options.IntOption {
- /**
- * Create the option.
- */
- public Verbose() {
- super(Options.set, "Verbose",
- "GC verbosity level",
- 0);
- }
-
- /**
- * Only accept non-negative values.
- */
- protected void validate() {
- failIf(this.value < 0, "Unreasonable verbosity level");
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/utility/options/VerboseFragmentationStats.java b/vmkit/mmtk/java/src/org/mmtk/utility/options/VerboseFragmentationStats.java
deleted file mode 100644
index fcecb89..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/utility/options/VerboseFragmentationStats.java
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.utility.options;
-
-/**
- * Should we print verbose fragmentation statistics for the free list allocator?
- */
-public final class VerboseFragmentationStats extends org.vmutil.options.BooleanOption {
- /**
- * Create the option.
- */
- public VerboseFragmentationStats() {
- super(Options.set, "Verbose Fragmentation Stats",
- "Should we print verbose fragmentation statistics for the free list allocator?",
- false);
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/utility/options/VerboseTiming.java b/vmkit/mmtk/java/src/org/mmtk/utility/options/VerboseTiming.java
deleted file mode 100644
index 08746df..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/utility/options/VerboseTiming.java
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.utility.options;
-
-/**
- * Should we display detailed breakdown of where GC time is spent?
- */
-public final class VerboseTiming extends org.vmutil.options.BooleanOption {
- /**
- * Create the option.
- */
- public VerboseTiming() {
- super(Options.set, "Verbose Timing",
- "Should we display detailed breakdown of where GC time is spent?",
- false);
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/utility/options/XmlStats.java b/vmkit/mmtk/java/src/org/mmtk/utility/options/XmlStats.java
deleted file mode 100644
index 95abeb0..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/utility/options/XmlStats.java
+++ /dev/null
@@ -1,28 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.utility.options;
-
-/**
- * Display statistics and options in XML rather than himan-readable
- * format.
- */
-public final class XmlStats extends org.vmutil.options.BooleanOption {
-
- /**
- * Create the option.
- */
- public XmlStats() {
- super(Options.set, "Xml Stats", "Print end-of-run statistics in XML format", false);
- }
-
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/utility/sanitychecker/SanityChecker.java b/vmkit/mmtk/java/src/org/mmtk/utility/sanitychecker/SanityChecker.java
deleted file mode 100644
index 2580dbe..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/utility/sanitychecker/SanityChecker.java
+++ /dev/null
@@ -1,253 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.utility.sanitychecker;
-
-import org.mmtk.plan.Plan;
-import org.mmtk.plan.Trace;
-import org.mmtk.plan.Simple;
-import org.mmtk.plan.TraceLocal;
-import org.mmtk.policy.Space;
-import org.mmtk.utility.Constants;
-import org.mmtk.utility.Log;
-
-import org.mmtk.vm.VM;
-
-import org.vmmagic.pragma.*;
-import org.vmmagic.unboxed.*;
-
-/**
- * This class performs sanity checks for Simple collectors.
- */
-@Uninterruptible
-public final class SanityChecker implements Constants {
-
- /* Counters */
- public static long referenceCount;
- public static long rootReferenceCount;
- public static long danglingReferenceCount;
- public static long nullReferenceCount;
- public static long liveObjectCount;
-
- public static final int DEAD = -2;
- public static final int ALIVE = -1;
- public static final int UNSURE = 0;
-
- public static final int LOG_SANITY_DATA_SIZE = 24;
-
- /* Tracing */
- public Trace rootTrace;
- public Trace checkTrace;
- private final SanityDataTable sanityTable;
- private boolean preGCSanity;
-
- /* Local, but we only run the check trace single-threaded. */
- final SanityTraceLocal checkTraceLocal;
-
- /* Linear scanning */
- private final SanityLinearScan scanner = new SanityLinearScan(this);
-
- /****************************************************************************
- * Constants
- */
- public SanityChecker() {
- sanityTable = new SanityDataTable(Plan.sanitySpace, LOG_SANITY_DATA_SIZE);
- checkTrace = new Trace(Plan.sanitySpace);
- rootTrace = new Trace(Plan.sanitySpace);
- checkTraceLocal = new SanityTraceLocal(checkTrace, this);
- }
-
- /**
- * Perform any sanity checking collection phases.
- *
- * @param phaseId The id to proces
- * @return True if the phase was handled.
- */
- @NoInline
- public boolean collectionPhase(int phaseId) {
- if (phaseId == Simple.SANITY_SET_PREGC) {
- preGCSanity = true;
- return true;
- }
-
- if (phaseId == Simple.SANITY_SET_POSTGC) {
- preGCSanity = false;
- return true;
- }
-
- if (phaseId == Simple.SANITY_PREPARE) {
- Log.writeln("");
- Log.write("============================== GC Sanity Checking ");
- Log.writeln("==============================");
- Log.writeln(preGCSanity ? "Performing Pre-GC Sanity Checks..." : "Performing Post-GC Sanity Checks...");
-
- // Reset counters
- referenceCount = 0;
- nullReferenceCount = 0;
- liveObjectCount = 0;
- danglingReferenceCount = 0;
- rootReferenceCount = 0;
-
- // Clear data space
- sanityTable.acquireTable();
-
- // Root trace
- rootTrace.prepareNonBlocking();
-
- // Checking trace
- checkTrace.prepareNonBlocking();
- checkTraceLocal.prepare();
- return true;
- }
-
- if (phaseId == Simple.SANITY_ROOTS) {
- VM.scanning.resetThreadCounter();
- return true;
- }
-
- if (phaseId == Simple.SANITY_BUILD_TABLE) {
- // Trace, checking for dangling pointers
- checkTraceLocal.completeTrace();
- return true;
- }
-
- if (phaseId == Simple.SANITY_CHECK_TABLE) {
- // Iterate over the reachable objects.
- Address curr = sanityTable.getFirst();
- while (!curr.isZero()) {
- ObjectReference ref = SanityDataTable.getObjectReference(curr);
- int normalRC = SanityDataTable.getNormalRC(curr);
- int rootRC = SanityDataTable.getRootRC(curr);
- if (!preGCSanity) {
- int expectedRC = VM.activePlan.global().sanityExpectedRC(ref, rootRC);
- switch (expectedRC) {
- case SanityChecker.ALIVE:
- case SanityChecker.UNSURE:
- // Always ok.
- break;
- case SanityChecker.DEAD:
- // Never ok.
- Log.write("ERROR: SanityRC = ");
- Log.write(normalRC);
- Log.write(", SpaceRC = 0 ");
- SanityChecker.dumpObjectInformation(ref);
- break;
- default:
- // A mismatch in an RC space
- if (normalRC != expectedRC && VM.activePlan.global().lastCollectionFullHeap()) {
- Log.write("WARNING: SanityRC = ");
- Log.write(normalRC);
- Log.write(", SpaceRC = ");
- Log.write(expectedRC);
- Log.write(" ");
- SanityChecker.dumpObjectInformation(ref);
- break;
- }
- }
- }
- curr = sanityTable.getNext(curr);
- }
-
- if (!preGCSanity && VM.activePlan.global().lastCollectionFullHeap()) {
- VM.activePlan.global().sanityLinearScan(scanner);
- }
- return true;
- }
-
- if (phaseId == Simple.SANITY_RELEASE) {
- checkTrace.release();
- sanityTable.releaseTable();
- checkTraceLocal.release();
-
- Log.writeln("roots\tobjects\trefs\tnull");
- Log.write(rootReferenceCount);Log.write("\t");
- Log.write(liveObjectCount);Log.write("\t");
- Log.write(referenceCount);Log.write("\t");
- Log.writeln(nullReferenceCount);
-
- Log.write("========================================");
- Log.writeln("========================================");
-
- return true;
- }
-
- return false;
- }
-
- /**
- * Process an object during a linear scan of the heap. We have already checked
- * all objects in the table. So we are only interested in objects that are not in
- * the sanity table here. We are therefore only looking for leaks here.
- *
- * @param object The object being scanned.
- */
- public void scanProcessObject(ObjectReference object) {
- if (sanityTable.getEntry(object, false).isZero()) {
- // Is this a leak?
- int expectedRC = VM.activePlan.global().sanityExpectedRC(object, 0);
-
- if (expectedRC == SanityChecker.UNSURE) {
- // Probably not.
- return;
- }
-
- // Possibly
- Log.write("WARNING: Possible leak, SpaceRC = ");
- Log.write(expectedRC);
- Log.write(" ");
- SanityChecker.dumpObjectInformation(object);
- }
- }
-
- /**
- * Process an object during sanity checking, validating data,
- * incrementing counters and enqueuing if this is the first
- * visit to the object.
- *
- * @param object The object to mark.
- * @param root True If the object is a root.
- */
- public void processObject(TraceLocal trace, ObjectReference object, boolean root) {
- SanityChecker.referenceCount++;
- if (root) SanityChecker.rootReferenceCount++;
-
- if (object.isNull()) {
- SanityChecker.nullReferenceCount++;
- return;
- }
-
- if (Plan.SCAN_BOOT_IMAGE && Space.isInSpace(Plan.VM_SPACE, object)) {
- return;
- }
-
- // Get the table entry.
- Address tableEntry = sanityTable.getEntry(object, true);
-
- if (SanityDataTable.incRC(tableEntry, root)) {
- SanityChecker.liveObjectCount++;
- trace.processNode(object);
- }
- }
-
- /**
- * Print out object information (used for warning and error messages)
- *
- * @param object The object to dump info for.
- */
- public static void dumpObjectInformation(ObjectReference object) {
- Log.write(object);
- Log.write(" [");
- Log.write(Space.getSpaceForObject(object).getName());
- Log.write("] ");
- Log.writeln(VM.objectModel.getTypeDescriptor(object));
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/utility/sanitychecker/SanityCheckerLocal.java b/vmkit/mmtk/java/src/org/mmtk/utility/sanitychecker/SanityCheckerLocal.java
deleted file mode 100644
index a6b0936..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/utility/sanitychecker/SanityCheckerLocal.java
+++ /dev/null
@@ -1,78 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.utility.sanitychecker;
-
-import org.mmtk.plan.Plan;
-import org.mmtk.plan.Simple;
-import org.mmtk.utility.Constants;
-
-import org.mmtk.vm.VM;
-
-import org.vmmagic.pragma.*;
-
-/**
- * This class performs sanity checks for Simple collectors.
- */
-@Uninterruptible
-public final class SanityCheckerLocal implements Constants {
-
- /* Trace */
- final SanityRootTraceLocal rootTraceLocal;
-
- /****************************************************************************
- * Constants
- */
- public SanityCheckerLocal() {
- rootTraceLocal = new SanityRootTraceLocal(Plan.sanityChecker.rootTrace);
- }
-
- /**
- * Perform any sanity checking collection phases.
- *
- * @param phaseId The id to proces
- * @param primary Perform local single threaded actions on this thread
- * @return True if the phase was handled.
- */
- @NoInline
- public boolean collectionPhase(int phaseId, boolean primary) {
- if (phaseId == Simple.SANITY_PREPARE) {
- rootTraceLocal.prepare();
- return true;
- }
-
- if (phaseId == Simple.SANITY_ROOTS) {
- VM.scanning.computeGlobalRoots(rootTraceLocal);
- VM.scanning.computeThreadRoots(rootTraceLocal);
- VM.scanning.computeStaticRoots(rootTraceLocal);
- if (Plan.SCAN_BOOT_IMAGE) {
- VM.scanning.computeBootImageRoots(rootTraceLocal);
- }
- rootTraceLocal.flush();
- return true;
- }
-
- if (phaseId == Simple.SANITY_COPY_ROOTS) {
- if (primary) {
- rootTraceLocal.copyRootValuesTo(Plan.sanityChecker.checkTraceLocal);
- }
- return true;
- }
-
- if (phaseId == Simple.SANITY_RELEASE) {
- rootTraceLocal.release();
- return true;
- }
-
- return false;
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/utility/sanitychecker/SanityDataTable.java b/vmkit/mmtk/java/src/org/mmtk/utility/sanitychecker/SanityDataTable.java
deleted file mode 100644
index b367fb1..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/utility/sanitychecker/SanityDataTable.java
+++ /dev/null
@@ -1,161 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.utility.sanitychecker;
-
-import org.mmtk.plan.TraceLocal;
-import org.mmtk.policy.RawPageSpace;
-import org.mmtk.utility.Constants;
-import org.mmtk.utility.deque.*;
-import org.mmtk.utility.SimpleHashtable;
-
-import org.vmmagic.pragma.*;
-import org.vmmagic.unboxed.*;
-
-/**
- * This class implements a simple hashtable to store and retrieve per
- * object information for sanity checking. <p>
- *
- * This class is not thread safe.
- */
-@Uninterruptible
-public final class SanityDataTable extends SimpleHashtable implements Constants {
-
- /** The number of bits for the normal reference count */
- private static final int NORMAL_RC_BITS = 25;
-
- /** The mask for the normal reference count */
- private static final int NORMAL_RC_MASK = (1 << 25) - 1;
-
- /** The shift for the root reference count */
- private static final int ROOT_RC_SHIFT = NORMAL_RC_BITS;
-
- /** The increment to use for normal increments */
- private static final int NORMAL_RC_INC = 1;
-
- /** The increment to use for root increments */
- private static final int ROOT_RC_INC = 1 << ROOT_RC_SHIFT;
-
- /**
- * Create a new data table of a specified size.
- *
- * @param rps The space to acquire the data structure from.
- * @param logSize The log of the number of table entries.
- */
- public SanityDataTable(RawPageSpace rps, int logSize) {
- super(rps, logSize, Extent.fromIntSignExtend(BYTES_IN_WORD));
- }
-
- /**
- * Increment the data word for an object.
- *
- * @param entry The table entry.
- * @param root True if this is a root reference.
- * @return True if this is the first ref to that object.
- */
- @Inline
- public static boolean incRC(Address entry, boolean root) {
- Address data = SimpleHashtable.getPayloadAddress(entry);
- int old = data.loadInt();
- data.store(old + (root ? ROOT_RC_INC : NORMAL_RC_INC));
- return (old == 0);
- }
-
- /**
- * Push any entries that are only in this table, and not the
- * passed table. This does not compare values.
- *
- * @param other The table to use for comparison.
- * @param deque The buffer to push results onto.
- */
- public void pushNotInOther(SanityDataTable other,
- ObjectReferenceDeque deque) {
- Address entry = getFirst();
- while (!entry.isZero()) {
- Word key = SimpleHashtable.getKey(entry);
- if (!other.contains(key)) {
- deque.push(key.toAddress().toObjectReference());
- }
- entry = getNext(entry);
- }
- }
-
-
- /**
- * Given an address of an entry, read the reference count,
- * excluding root references.
- *
- * @param entry The entry
- * @return The reference count.
- */
- public static int getNormalRC(Address entry) {
- return SimpleHashtable.getPayloadAddress(entry).loadInt() & NORMAL_RC_MASK;
- }
-
- /**
- * Given an address of an entry, read the root reference count.
- *
- * @param entry The entry
- * @return The root reference count.
- */
- public static int getRootRC(Address entry) {
- return SimpleHashtable.getPayloadAddress(entry).loadInt() >>> ROOT_RC_SHIFT;
- }
-
- /**
- * Given an address of an entry, read the total reference count.
- *
- * @param entry The entry
- * @return The total reference count.
- */
- public static int getRC(Address entry) {
- int val = SimpleHashtable.getPayloadAddress(entry).loadInt();
- return (val & NORMAL_RC_MASK) + val >>> ROOT_RC_SHIFT;
- }
-
- /**
- * Given an address of an entry, read the reference component.
- *
- * @param entry The entry
- * @return The object reference.
- */
- public static ObjectReference getObjectReference(Address entry) {
- return SimpleHashtable.getKey(entry).toAddress().toObjectReference();
- }
-
- /**
- * Forward data table using the supplied trace. Note that the data is
- * not hashed correctly, so only enumeration can be used without
- * rehashing.
- *
- * @param trace The trace to use.
- */
- public void forwardTable(TraceLocal trace) {
- Address entry = getFirst();
- while (!entry.isZero()) {
- ObjectReference obj = getObjectReference(entry);
- SimpleHashtable.replaceKey(entry, trace.getForwardedReference(obj).toAddress().toWord());
- entry = getNext(entry);
- }
- }
-
- /**
- * Get an entry for an object.
- *
- * @param object The object to find an entry for.
- * @param create Create an entry if none exists?
- * @return The entry address.
- */
- public Address getEntry(ObjectReference object, boolean create) {
- return super.getEntry(object.toAddress().toWord(), create);
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/utility/sanitychecker/SanityLinearScan.java b/vmkit/mmtk/java/src/org/mmtk/utility/sanitychecker/SanityLinearScan.java
deleted file mode 100644
index 6691f77..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/utility/sanitychecker/SanityLinearScan.java
+++ /dev/null
@@ -1,34 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.utility.sanitychecker;
-
-import org.mmtk.utility.alloc.LinearScan;
-
-import org.vmmagic.pragma.*;
-import org.vmmagic.unboxed.ObjectReference;
-
-/**
- * This class performs sanity checks for Simple collectors.
- */
-@Uninterruptible
-final class SanityLinearScan extends LinearScan {
-
- private final SanityChecker sanityChecker;
- public SanityLinearScan(SanityChecker sanityChecker) {
- this.sanityChecker = sanityChecker;
- }
-
- public void scan(ObjectReference object) {
- sanityChecker.scanProcessObject(object);
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/utility/sanitychecker/SanityRootTraceLocal.java b/vmkit/mmtk/java/src/org/mmtk/utility/sanitychecker/SanityRootTraceLocal.java
deleted file mode 100644
index 9e2b514..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/utility/sanitychecker/SanityRootTraceLocal.java
+++ /dev/null
@@ -1,101 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.utility.sanitychecker;
-
-import org.mmtk.plan.TraceLocal;
-import org.mmtk.plan.Trace;
-import org.mmtk.vm.VM;
-
-import org.vmmagic.pragma.*;
-import org.vmmagic.unboxed.*;
-
-/**
- * This class implements the parallel root-gathering part of a sanity check.
- */
-@Uninterruptible
-public final class SanityRootTraceLocal extends TraceLocal {
-
- /**
- * Constructor
- */
- public SanityRootTraceLocal(Trace trace) {
- super(trace);
- }
-
- /****************************************************************************
- *
- * Object processing and tracing
- */
-
- /**
- * Copy root values across to the 'real' single-threaded trace that will do
- * the sanity checking.
- */
- @Inline
- public void copyRootValuesTo(TraceLocal trace) {
- while (!rootLocations.isEmpty()) {
- ObjectReference object = rootLocations.pop().loadObjectReference();
- if (!object.isNull()) {
- trace.traceObject(object, true);
- }
- }
- while (!values.isEmpty()) {
- trace.traceObject(values.pop(), true);
- }
- }
-
- /**
- * Process delayed roots. This does not make sense for SanityRootTraceLocal.
- * are empty.
- */
- @Inline
- public void processRoots() {
- VM.assertions.fail("SanityRootTraceLocal.processRoots called.");
- }
-
- /**
- * Finishing processing all GC work. This does not make sense for SanityRootTraceLocal.
- */
- @Inline
- public void completeTrace() {
- VM.assertions.fail("SanityRootTraceLocal.completeTrace called.");
- }
-
- /**
- * This method is the core method during the trace of the object graph.
- * The role of this method is to:
- *
- * @param object The object to be traced.
- * @param root Is this object a root?
- * @return The new reference to the same object instance.
- */
- @Inline
- public ObjectReference traceObject(ObjectReference object, boolean root) {
- if (!root) VM.assertions.fail("SanityRootTraceLocal.traceObject called for non-root object.");
- if (!object.isNull()) {
- values.push(object);
- }
- return object;
- }
-
- /**
- * Will this object move from this point on, during the current trace ?
- *
- * @param object The object to query.
- * @return True if the object will not move.
- */
- public boolean willNotMoveInCurrentCollection(ObjectReference object) {
- // We never move objects!
- return true;
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/utility/sanitychecker/SanityTraceLocal.java b/vmkit/mmtk/java/src/org/mmtk/utility/sanitychecker/SanityTraceLocal.java
deleted file mode 100644
index 672c8d1..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/utility/sanitychecker/SanityTraceLocal.java
+++ /dev/null
@@ -1,66 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.utility.sanitychecker;
-
-import org.mmtk.plan.TraceLocal;
-import org.mmtk.plan.Trace;
-
-import org.vmmagic.pragma.*;
-import org.vmmagic.unboxed.*;
-
-/**
- * This class implements the simply sanity closure.
- */
-@Uninterruptible
-public final class SanityTraceLocal extends TraceLocal {
-
- private final SanityChecker sanityChecker;
-
- /**
- * Constructor
- */
- public SanityTraceLocal(Trace trace, SanityChecker sanityChecker) {
- super(trace);
- this.sanityChecker = sanityChecker;
- }
-
- /****************************************************************************
- *
- * Object processing and tracing
- */
-
- /**
- * This method is the core method during the trace of the object graph.
- * The role of this method is to:
- *
- * @param object The object to be traced.
- * @param root Is this object a root?
- * @return The new reference to the same object instance.
- */
- @Inline
- public ObjectReference traceObject(ObjectReference object, boolean root) {
- sanityChecker.processObject(this, object, root);
- return object;
- }
-
- /**
- * Will this object move from this point on, during the current trace ?
- *
- * @param object The object to query.
- * @return True if the object will not move.
- */
- public boolean willNotMoveInCurrentCollection(ObjectReference object) {
- // We never move objects!
- return true;
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/utility/statistics/BooleanCounter.java b/vmkit/mmtk/java/src/org/mmtk/utility/statistics/BooleanCounter.java
deleted file mode 100644
index 881063e..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/utility/statistics/BooleanCounter.java
+++ /dev/null
@@ -1,200 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.utility.statistics;
-
-import org.mmtk.utility.Log;
-
-import org.mmtk.vm.VM;
-
-import org.vmmagic.pragma.*;
-
-/**
- * This class implements a simple boolean counter (counting number of
- * phases where some boolean event is true).
- */
-@Uninterruptible public class BooleanCounter extends Counter {
-
- /****************************************************************************
- *
- * Instance variables
- */
-
- private final boolean[] state;
-
- protected int total = 0;
- private boolean running = false;
-
- /****************************************************************************
- *
- * Initialization
- */
-
- /**
- * Constructor
- *
- * @param name The name to be associated with this counter
- */
- public BooleanCounter(String name) {
- this(name, true, false);
- }
-
- /**
- * Constructor
- *
- * @param name The name to be associated with this counter
- * @param start True if this counter is to be implicitly started
- * when <code>startAll()</code> is called (otherwise the counter
- * must be explicitly started).
- */
- public BooleanCounter(String name, boolean start) {
- this(name, start, false);
- }
-
- /**
- * Constructor
- *
- * @param name The name to be associated with this counter
- * @param start True if this counter is to be implicitly started
- * when <code>startAll()</code> is called (otherwise the counter
- * must be explicitly started).
- * @param mergephases True if this counter does not separately
- * report GC and Mutator phases.
- */
- public BooleanCounter(String name, boolean start, boolean mergephases) {
- super(name, start, mergephases);
- state = new boolean[Stats.MAX_PHASES];
- for (int i = 0; i < Stats.MAX_PHASES; i++)
- state[i] = false;
- }
-
- /****************************************************************************
- *
- * Counter-specific methods
- */
-
- /**
- * Set the boolean to true for this phase, increment the total.
- */
- public void set() {
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(Stats.phase == Stats.MAX_PHASES -1 || !state[Stats.phase]);
- state[Stats.phase] = true;
- total++;
- }
-
- /****************************************************************************
- *
- * Generic counter control methods: start, stop, print etc
- */
-
- /**
- * Start this counter
- */
- protected void start() {
- if (!Stats.gatheringStats) return;
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(!running);
- running = true;
- }
-
- /**
- * Stop this counter
- */
- protected void stop() {
- if (!Stats.gatheringStats) return;
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(running);
- running = false;
- }
-
- /**
- * The phase has changed (from GC to mutator or mutator to GC).
- * Take action with respect to the last phase if necessary.
- * <b>Do nothing in this case.</b>
- *
- * @param oldPhase The last phase
- */
- void phaseChange(int oldPhase) {}
-
- /**
- * Print the value of this counter for the given phase. Print '0'
- * for false, '1' for true.
- *
- * @param phase The phase to be printed
- */
- protected final void printCount(int phase) {
- if (VM.VERIFY_ASSERTIONS && mergePhases())
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert((phase | 1) == (phase + 1));
- if (mergePhases())
- printValue((state[phase] || state[phase + 1]) ? 1 : 0);
- else
- printValue((state[phase]) ? 1 : 0);
- }
-
- /**
- * Print the current total number of 'true' phases for this counter
- */
- protected final void printTotal() {
- int total = 0;
- for (int p = 0; p <= Stats.phase; p++) {
- total += (state[p]) ? 1 : 0;
- }
- printValue(total);
- }
-
- /**
- * Print the current total number of 'true' phases for either the
- * mutator or GC phase
- *
- * @param mutator True if the total for the mutator phases is to be
- * printed (otherwise the total for the GC phases will be printed).
- */
- protected final void printTotal(boolean mutator) {
- int total = 0;
- for (int p = (mutator) ? 0 : 1; p <= Stats.phase; p += 2) {
- total += (state[p]) ? 1 : 0;
- }
- printValue(total);
- }
-
- /**
- * Print the current minimum value for either the mutator or GC
- * phase. <b>Do nothing in this case.</b>
- *
- * @param mutator True if the minimum for the mutator phase is to be
- * printed (otherwise the minimum for the GC phase will be printed).
- */
- protected final void printMin(boolean mutator) {}
-
- /**
- * Print the current maximum value for either the mutator or GC
- * phase. <b>Do nothing in this case.</b>
- *
- * @param mutator True if the maximum for the mutator phase is to be
- * printed (otherwise the maximum for the GC phase will be printed).
- */
- protected final void printMax(boolean mutator) {}
-
- /**
- * Print the given value
- *
- * @param value The value to be printed
- */
- void printValue(int value) {
- Log.write(value);
- }
-
- /**
- * Print statistics for the most recent phase
- */
- public void printLast() {
- if (Stats.phase > 0) printCount(Stats.phase - 1);
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/utility/statistics/Counter.java b/vmkit/mmtk/java/src/org/mmtk/utility/statistics/Counter.java
deleted file mode 100644
index eb43429..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/utility/statistics/Counter.java
+++ /dev/null
@@ -1,179 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.utility.statistics;
-
-import org.vmmagic.pragma.*;
-
-/**
- *
- * This abstract class describes the interface of a generic counter.
- */
-@Uninterruptible public abstract class Counter {
-
- /****************************************************************************
- *
- * Instance variables
- */
-
- private final String name;
- private final boolean start;
- private final boolean mergephases;
-
- /**
- * Allow for counters whose values are too complex to be simply printed out.
- */
- protected boolean complex = false;
-
- /****************************************************************************
- *
- * Initialization
- */
-
- /**
- * Constructor
- *
- * @param name The name to be associated with this counter
- */
- Counter(String name) {
- this(name, true, false);
- }
-
- /**
- * Constructor
- *
- * @param name The name to be associated with this counter
- * @param start True if this counter is to be implicitly started
- * when <code>startAll()</code> is called (otherwise the counter
- * must be explicitly started).
- */
- Counter(String name, boolean start) {
- this(name, start, false);
- }
-
- /**
- * Constructor
- *
- * @param name The name to be associated with this counter
- * @param start True if this counter is to be implicitly started
- * when <code>startAll()</code> is called (otherwise the counter
- * must be explicitly started).
- * @param mergephases True if this counter does not separately
- * report GC and Mutator phases.
- */
- Counter(String name, boolean start, boolean mergephases) {
- this.name = name;
- this.start = start;
- this.mergephases = mergephases;
- Stats.newCounter(this);
- }
-
- /****************************************************************************
- *
- * Counter control methods: start, stop, print etc
- */
-
- /**
- * Start this counter
- */
- abstract void start();
-
- /**
- * Stop this counter
- */
- abstract void stop();
-
- /**
- * The phase has changed (from GC to mutator or mutator to GC).
- * Take action with respect to the last phase if necessary.
- *
- * @param oldPhase The last phase
- */
- abstract void phaseChange(int oldPhase);
-
- /**
- * Print the value of this counter for the given phase
- *
- * @param phase The phase to be printed
- */
- abstract void printCount(int phase);
-
- /**
- * Print the current total for this counter
- */
- abstract void printTotal();
-
- /**
- * Print the current total for either the mutator or GC phase
- *
- * @param mutator True if the total for the mutator phases is to be
- * printed (otherwise the total for the GC phases will be printed).
- */
- abstract void printTotal(boolean mutator);
-
- /**
- * Print the current minimum value for either the mutator or GC phase
- *
- * @param mutator True if the minimum for the mutator phase is to be
- * printed (otherwise the minimum for the GC phase will be printed).
- */
- abstract void printMin(boolean mutator);
-
- /**
- * Print the current maximum value for either the mutator or GC phase
- *
- * @param mutator True if the maximum for the mutator phase is to be
- * printed (otherwise the maximum for the GC phase will be printed).
- */
- abstract void printMax(boolean mutator);
-
- /**
- * Print statistics for the most recent phase
- */
- public void printLast() {
- if (Stats.phase > 0) printCount(Stats.phase - 1);
- }
-
-
- /****************************************************************************
- *
- * Accessor methods
- */
-
- /**
- * Return the name of this counter
- * @return The name of this counter
- */
- String getName() { return name; }
-
- /**
- * Return the (option) suffix to be used when reporting this counter
- * @return The suffix
- */
- String getColumnSuffix() { return ""; }
-
- /**
- * Return true if this counter is implicitly started when
- * <code>startAll()</code> is called.
- * @return True if this counter is implicitly started when
- * <code>startAll()</code> is called.
- */
- boolean getStart() { return start; }
-
- /**
- * Return true if this counter will merge stats for GC and mutator phases.
- * @return True if this counter will merge stats for GC and mutator phases.
- */
- boolean mergePhases() { return mergephases; }
-
- boolean isComplex() { return complex; }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/utility/statistics/EventCounter.java b/vmkit/mmtk/java/src/org/mmtk/utility/statistics/EventCounter.java
deleted file mode 100644
index 2eab0dc..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/utility/statistics/EventCounter.java
+++ /dev/null
@@ -1,230 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.utility.statistics;
-
-import org.mmtk.utility.Log;
-
-import org.mmtk.vm.VM;
-
-import org.vmmagic.pragma.*;
-
-/**
- * This class implements a simple event counter (counting number
- * events that occur for each phase).
- */
-@Uninterruptible public class EventCounter extends Counter {
-
- /****************************************************************************
- *
- * Instance variables
- */
-
- private final long[] count;
-
- protected long totalCount = 0;
- private boolean running = false;
-
- /****************************************************************************
- *
- * Initialization
- */
-
- /**
- * Constructor
- *
- * @param name The name to be associated with this counter
- */
- public EventCounter(String name) {
- this(name, true, false);
- }
-
- /**
- * Constructor
- *
- * @param name The name to be associated with this counter
- * @param start True if this counter is to be implicitly started
- * when <code>startAll()</code> is called (otherwise the counter
- * must be explicitly started).
- */
- public EventCounter(String name, boolean start) {
- this(name, start, false);
- }
-
- /**
- * Constructor
- *
- * @param name The name to be associated with this counter
- * @param start True if this counter is to be implicitly started
- * when <code>startAll()</code> is called (otherwise the counter
- * must be explicitly started).
- * @param mergephases True if this counter does not separately
- * report GC and Mutator phases.
- */
- public EventCounter(String name, boolean start, boolean mergephases) {
- super(name, start, mergephases);
- count = new long[Stats.MAX_PHASES];
- }
-
- /****************************************************************************
- *
- * Counter-specific methods
- */
-
- /**
- * Increment the event counter
- */
- public void inc() {
- if (running) inc(1);
- }
-
- /**
- * Increment the event counter by <code>value</code>
- *
- * @param value The amount by which the counter should be incremented.
- */
- public void inc(int value) {
- if (running) totalCount += value;
- }
-
- /****************************************************************************
- *
- * Generic counter control methods: start, stop, print etc
- */
-
- /**
- * Start this counter
- */
- protected void start() {
- if (!Stats.gatheringStats) return;
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(!running);
- running = true;
- }
-
- /**
- * Stop this counter
- */
- protected void stop() {
- if (!Stats.gatheringStats) return;
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(running);
- running = false;
- }
-
- /**
- * The phase has changed (from GC to mutator or mutator to GC).
- * Take action with respect to the last phase if necessary.
- * <b>Do nothing in this case.</b>
- *
- * @param oldPhase The last phase
- */
- void phaseChange(int oldPhase) {
- if (running) {
- count[oldPhase] = totalCount;
- totalCount = 0;
- }
- }
-
- /**
- * Print the value of this counter for the given phase. Print '0'
- * for false, '1' for true.
- *
- * @param phase The phase to be printed
- */
- protected final void printCount(int phase) {
- if (VM.VERIFY_ASSERTIONS && mergePhases())
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert((phase | 1) == (phase + 1));
- if (mergePhases())
- printValue(count[phase] + count[phase + 1]);
- else
- printValue(count[phase]);
- }
-
- /**
- * Print the current value for this counter (mid-phase)
- */
- public final void printCurrent() {
- printValue(totalCount);
- }
-
- /**
- * Print the current total for this counter
- */
- public final void printTotal() {
- long total = 0;
- for (int p = 0; p <= Stats.phase; p++) {
- total += count[p];
- }
- printValue(total);
- }
-
- /**
- * Print the current total for either the mutator or GC phase
- *
- * @param mutator True if the total for the mutator phases is to be
- * printed (otherwise the total for the GC phases will be printed).
- */
- protected final void printTotal(boolean mutator) {
- long total = 0;
- for (int p = (mutator) ? 0 : 1; p <= Stats.phase; p += 2) {
- total += count[p];
- }
- printValue(total);
- }
-
- /**
- * Print the current minimum value for either the mutator or GC
- * phase.
- *
- * @param mutator True if the minimum for the mutator phase is to be
- * printed (otherwise the minimum for the GC phase will be printed).
- */
- protected final void printMin(boolean mutator) {
- int p = (mutator) ? 0 : 1;
- long min = count[p];
- for (; p < Stats.phase; p += 2) {
- if (count[p] < min) min = count[p];
- }
- printValue(min);
- }
-
- /**
- * Print the current maximum value for either the mutator or GC
- * phase.
- *
- * @param mutator True if the maximum for the mutator phase is to be
- * printed (otherwise the maximum for the GC phase will be printed).
- */
- protected final void printMax(boolean mutator) {
- int p = (mutator) ? 0 : 1;
- long max = count[p];
- for (; p < Stats.phase; p += 2) {
- if (count[p] > max) max = count[p];
- }
- printValue(max);
- }
-
- /**
- * Print the given value
- *
- * @param value The value to be printed
- */
- void printValue(long value) {
- Log.write(value);
- }
-
- /**
- * Print statistics for the most recent phase
- */
- public void printLast() {
- if (Stats.phase > 0) printCount(Stats.phase - 1);
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/utility/statistics/LongCounter.java b/vmkit/mmtk/java/src/org/mmtk/utility/statistics/LongCounter.java
deleted file mode 100644
index 96b096a..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/utility/statistics/LongCounter.java
+++ /dev/null
@@ -1,215 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.utility.statistics;
-
-import org.mmtk.utility.Log;
-
-import org.mmtk.vm.VM;
-
-import org.vmmagic.pragma.*;
-
-/**
- * This abstract class implements a simple counter (counting some
- * integer (long) value for each phase).
- */
-@Uninterruptible public abstract class LongCounter extends Counter {
-
- /****************************************************************************
- *
- * Instance variables
- */
-
- private final long[] count;
-
- private long startValue = 0;
- protected long totalCount = 0;
- private boolean running = false;
-
- /****************************************************************************
- *
- * Initialization
- */
-
- /**
- * Constructor
- *
- * @param name The name to be associated with this counter
- */
- LongCounter(String name) {
- this(name, true, false);
- }
-
- /**
- * Constructor
- *
- * @param name The name to be associated with this counter
- * @param start True if this counter is to be implicitly started
- * when <code>startAll()</code> is called (otherwise the counter
- * must be explicitly started).
- */
- LongCounter(String name, boolean start) {
- this(name, start, false);
- }
-
- /**
- * Constructor
- *
- * @param name The name to be associated with this counter
- * @param start True if this counter is to be implicitly started
- * when <code>startAll()</code> is called (otherwise the counter
- * must be explicitly started).
- * @param mergephases True if this counter does not separately
- * report GC and Mutator phases.
- */
- LongCounter(String name, boolean start, boolean mergephases) {
- super(name, start, mergephases);
- count = new long[Stats.MAX_PHASES];
- }
-
- /****************************************************************************
- *
- * Counter-specific methods
- */
- protected abstract long getCurrentValue();
-
- /****************************************************************************
- *
- * Generic counter control methods: start, stop, print etc
- */
-
- /**
- * Start this counter
- */
- public void start() {
- if (!Stats.gatheringStats) return;
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(!running);
- running = true;
- startValue = getCurrentValue();
- }
-
- /**
- * Stop this counter
- */
- public void stop() {
- if (!Stats.gatheringStats) return;
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(running);
- running = false;
- long delta = getCurrentValue() - startValue;
- count[Stats.phase] += delta;
- totalCount += delta;
- }
-
- /**
- * The phase has changed (from GC to mutator or mutator to GC).
- * Take action with respect to the last phase if necessary.
- * <b>Do nothing in this case.</b>
- *
- * @param oldPhase The last phase
- */
- protected void phaseChange(int oldPhase) {
- if (running) {
- long now = getCurrentValue();
- long delta = now - startValue;
- count[oldPhase] += delta;
- totalCount += delta;
- startValue = now;
- }
- }
-
- /**
- * Print the value of this counter for the given phase. Print '0'
- * for false, '1' for true.
- *
- * @param phase The phase to be printed
- */
- protected final void printCount(int phase) {
- if (VM.VERIFY_ASSERTIONS && mergePhases())
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert((phase | 1) == (phase + 1));
- if (mergePhases())
- printValue(count[phase] + count[phase + 1]);
- else
- printValue(count[phase]);
- }
-
- /**
- * Print the current total for this counter
- */
- public final void printTotal() {
- printValue(totalCount);
- }
-
-
- /**
- * Get the total as at the lasts phase
- *
- * @return The total as at the last phase
- */
- long getLastTotal() {
- return totalCount;
- }
-
- /**
- * Print the current total for either the mutator or GC phase
- *
- * @param mutator True if the total for the mutator phases is to be
- * printed (otherwise the total for the GC phases will be printed).
- */
- protected final void printTotal(boolean mutator) {
- long total = 0;
- for (int p = (mutator) ? 0 : 1; p <= Stats.phase; p += 2) {
- total += count[p];
- }
- printValue(total);
- }
-
- /**
- * Print the current minimum value for either the mutator or GC
- * phase.
- *
- * @param mutator True if the minimum for the mutator phase is to be
- * printed (otherwise the minimum for the GC phase will be printed).
- */
- protected final void printMin(boolean mutator) {
- int p = (mutator) ? 0 : 1;
- long min = count[p];
- for (; p < Stats.phase; p += 2) {
- if (count[p] < min) min = count[p];
- }
- printValue(min);
- }
-
- /**
- * Print the current maximum value for either the mutator or GC
- * phase.
- *
- * @param mutator True if the maximum for the mutator phase is to be
- * printed (otherwise the maximum for the GC phase will be printed).
- */
- protected final void printMax(boolean mutator) {
- int p = (mutator) ? 0 : 1;
- long max = count[p];
- for (; p < Stats.phase; p += 2) {
- if (count[p] > max) max = count[p];
- }
- printValue(max);
- }
-
- /**
- * Print the given value
- *
- * @param value The value to be printed
- */
- void printValue(long value) {
- Log.write(value);
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/utility/statistics/PerfEvent.java b/vmkit/mmtk/java/src/org/mmtk/utility/statistics/PerfEvent.java
deleted file mode 100644
index 1fed1e2..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/utility/statistics/PerfEvent.java
+++ /dev/null
@@ -1,116 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.utility.statistics;
-
-import org.mmtk.utility.Log;
-import org.mmtk.vm.VM;
-import org.vmmagic.pragma.Uninterruptible;
-
-/**
- * This class represents a perf event, such as cache misses, etc.
- */
-@Uninterruptible
-public final class PerfEvent extends LongCounter {
- /** True if the counter did not run due to contention for a physical counter */
- private boolean contended;
-
- /** True if the counter did not run all of the time and has been scaled appropriately */
- private boolean scaled;
-
- /** True if the counter overflowed */
- private boolean overflowed;
-
- /** The index of the counter in the native array */
- private int index;
-
- /** The previously read value of the counter (used to detect overflow) */
- private long previousValue;
-
- /** A buffer passed to the native code when reading values, returns the tuple RAW_COUNT, TIME_ENABLED, TIME_RUNNING */
- private final long[] readBuffer = new long[3];
- private static final int RAW_COUNT = 0;
- private static final int TIME_ENABLED = 1;
- private static final int TIME_RUNNING = 2;
-
- /** Three 64 bit values is 24 bytes */
- private static final int BYTES_TO_READ = 24;
-
- /** True if any data was scaled */
- public static boolean dataWasScaled = false;
-
- public PerfEvent(int index, String name) {
- super(name, true, false);
- this.index = index;
- }
-
- /**
- * Counters are 64 bit unsigned in the kernel but only 63 bits are available in Java
- */
- @Override
- protected long getCurrentValue() {
- VM.statistics.perfEventRead(index, readBuffer);
- if (readBuffer[RAW_COUNT] < 0 || readBuffer[TIME_ENABLED] < 0 || readBuffer[TIME_RUNNING] < 0) {
- // Negative implies they have exceeded 63 bits.
- overflowed = true;
- }
- if (readBuffer[TIME_ENABLED] == 0) {
- // Counter never run (assume contention)
- contended = true;
- }
- // Was the counter scaled?
- if (readBuffer[TIME_ENABLED] != readBuffer[TIME_RUNNING]) {
- scaled = true;
- dataWasScaled = true;
- double scaleFactor;
- if (readBuffer[TIME_RUNNING] == 0) {
- scaleFactor = 0;
- } else {
- scaleFactor = readBuffer[TIME_ENABLED] / readBuffer[TIME_RUNNING];
- }
- readBuffer[RAW_COUNT] = (long) (readBuffer[RAW_COUNT] * scaleFactor);
- }
- if (readBuffer[RAW_COUNT] < previousValue) {
- // value should monotonically increase
- overflowed = true;
- }
- previousValue = readBuffer[RAW_COUNT];
- return readBuffer[RAW_COUNT];
- }
-
- /**
- * Print the given value
- * @param value The value to be printed
- */
- @Override
- void printValue(long value) {
- if (overflowed) {
- Log.write("OVERFLOWED");
- } else if (contended) {
- Log.write("CONTENDED");
- } else {
- Log.write(value);
- if (scaled) {
- Log.write(" (SCALED)");
- }
- }
- }
-
- public String getColumnSuffix() {
- return
- overflowed ? "overflowed" :
- contended ? "contended" :
- scaled ? ".scaled" :
- "";
- }
-}
-
diff --git a/vmkit/mmtk/java/src/org/mmtk/utility/statistics/SizeCounter.java b/vmkit/mmtk/java/src/org/mmtk/utility/statistics/SizeCounter.java
deleted file mode 100644
index f131c25..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/utility/statistics/SizeCounter.java
+++ /dev/null
@@ -1,138 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.utility.statistics;
-
-import org.vmmagic.pragma.*;
-
-/**
- * This class implements a simple counter of events of different sizes
- * (eg object allocations, where total number of objects and total
- * volume of objects would be counted).
- *
- * The counter is trivially composed from two event counters (one for
- * counting the number of events, the other for counting the volume).
- */
-@Uninterruptible public class SizeCounter {
-
- /****************************************************************************
- *
- * Instance variables
- */
- private EventCounter units;
- private EventCounter volume;
-
- /****************************************************************************
- *
- * Initialization
- */
-
- /**
- * Constructor
- *
- * @param name The name to be associated with this counter
- */
- public SizeCounter(String name) {
- this(name, true, false);
- }
-
- /**
- * Constructor
- *
- * @param name The name to be associated with this counter
- * @param start True if this counter is to be implicitly started
- * when <code>startAll()</code> is called (otherwise the counter
- * must be explicitly started).
- */
- public SizeCounter(String name, boolean start) {
- this(name, start, false);
- }
-
- /**
- * Constructor
- *
- * @param name The name to be associated with this counter
- * @param start True if this counter is to be implicitly started
- * when <code>startAll()</code> is called (otherwise the counter
- * must be explicitly started).
- * @param mergephases True if this counter does not separately
- * report GC and Mutator phases.
- */
- public SizeCounter(String name, boolean start, boolean mergephases) {
- units = new EventCounter(name, start, mergephases);
- volume = new EventCounter(name + "Volume", start, mergephases);
- }
-
- /****************************************************************************
- *
- * Counter-specific methods
- */
-
- /**
- * Increment the event counter by <code>value</code>
- *
- * @param value The amount by which the counter should be incremented.
- */
- public void inc(int value) {
- units.inc();
- volume.inc(value);
- }
-
- /****************************************************************************
- *
- * Generic counter control methods: start, stop, print etc
- */
-
- /**
- * Start this counter
- */
- public void start() {
- units.start();
- volume.start();
- }
-
- /**
- * Stop this counter
- */
- public void stop() {
- units.stop();
- volume.stop();
- }
-
- /**
- * Print current (mid-phase) units
- */
- public void printCurrentUnits() {
- units.printCurrent();
- }
-
- /**
- * Print (mid-phase) volume
- */
- public void printCurrentVolume() {
- volume.printCurrent();
- }
-
- /**
- * Print units
- */
- public void printUnits() {
- units.printTotal();
- }
-
- /**
- * Print volume
- */
- public void printVolume() {
- volume.printTotal();
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/utility/statistics/Stats.java b/vmkit/mmtk/java/src/org/mmtk/utility/statistics/Stats.java
deleted file mode 100644
index 40a794f..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/utility/statistics/Stats.java
+++ /dev/null
@@ -1,384 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.utility.statistics;
-
-import org.mmtk.plan.Plan;
-import org.mmtk.utility.Log;
-import org.mmtk.utility.options.Options;
-import org.mmtk.utility.options.PrintPhaseStats;
-import org.mmtk.utility.options.XmlStats;
-
-import org.mmtk.vm.VM;
-
-import org.vmmagic.pragma.*;
-
-/**
- * This class implements basic statistics functionality
- */
-@Uninterruptible public class Stats {
-
- /****************************************************************************
- *
- * Class variables
- */
-
- public static final boolean GATHER_MARK_CONS_STATS = false;
-
- /** Maximum number of gc/mutator phases that can be counted */
- static final int MAX_PHASES = 1 << 12;
- /** Maximum number of counters that can be in operation */
- static final int MAX_COUNTERS = 100;
-
- private static int counters = 0;
- private static Counter[] counter;
- static int phase = 0;
- private static int gcCount = 0;
- static boolean gatheringStats = false;
- static boolean exceededPhaseLimit = false;
-
- /****************************************************************************
- *
- * Initialization
- */
-
- /**
- * Class initializer. This is executed <i>prior</i> to bootstrap
- * (i.e. at "build" time). This is where key <i>global</i>
- * instances are allocated. These instances will be incorporated
- * into the boot image by the build process.
- */
- static {
- counter = new Counter[MAX_COUNTERS];
- Options.printPhaseStats = new PrintPhaseStats();
- Options.xmlStats = new XmlStats();
- }
-
- /**
- * Add a new counter to the set of managed counters.
- *
- * @param ctr The counter to be added.
- */
- @Interruptible
- static void newCounter(Counter ctr) {
- if (counters < (MAX_COUNTERS - 1)) {
- counter[counters++] = ctr;
- } else {
- Log.writeln("Warning: number of stats counters exceeds maximum");
- }
- }
-
- /**
- * Start a new GC phase. This means notifying each counter of the
- * phase change.
- */
- public static void startGC() {
- gcCount++;
- if (!gatheringStats) return;
- if (phase < MAX_PHASES - 1) {
- for (int c = 0; c < counters; c++) {
- counter[c].phaseChange(phase);
- }
- phase++;
- } else if (!exceededPhaseLimit) {
- Log.writeln("Warning: number of GC phases exceeds MAX_PHASES");
- exceededPhaseLimit = true;
- }
- }
-
- /**
- * End a GC phase. This means notifying each counter of the phase
- * change.
- */
- public static void endGC() {
- if (!gatheringStats) return;
- if (phase < MAX_PHASES - 1) {
- for (int c = 0; c < counters; c++) {
- counter[c].phaseChange(phase);
- }
- phase++;
- } else if (!exceededPhaseLimit) {
- Log.writeln("Warning: number of GC phases exceeds MAX_PHASES");
- exceededPhaseLimit = true;
- }
- }
-
- /**
- * Start all implicitly started counters (i.e. those for whom
- * <code>start == true</code>).
- */
- public static void startAll() {
- if (gatheringStats) {
- Log.writeln("Error: calling Stats.startAll() while stats running");
- Log.writeln(" verbosity > 0 and the harness mechanism may be conflicitng");
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(false);
- }
- gatheringStats = true;
- for (int c = 0; c < counters; c++) {
- if (counter[c].getStart())
- counter[c].start();
- }
-
- if (Options.xmlStats.getValue()) {
- Xml.begin();
- Xml.openTag("mmtk-stats");
- Xml.end();
- }
- }
-
- /**
- * Stop all counters
- */
- @Interruptible
- public static void stopAll() {
- stopAllCounters();
- Stats.printStats();
- if (Options.xmlStats.getValue()) {
- Xml.begin();
- Xml.closeTag("mmtk-stats");
- Xml.end();
- }
- }
-
- /**
- * Stop all counters
- */
- private static void stopAllCounters() {
- for (int c = 0; c < counters; c++) {
- if (counter[c].getStart())
- counter[c].stop();
- }
- gatheringStats = false;
- }
-
- @Interruptible
- public static void printStats() {
- if (exceededPhaseLimit) {
- Log.writeln("Warning: number of GC phases exceeds MAX_PHASES. Statistics are truncated.");
- }
- if (Options.xmlStats.getValue())
- printStatsXml();
- else
- printStatsPlain();
- }
-
- /**
- * Print out statistics
- */
- @Interruptible
- public static void printStatsPlain() {
- if (Options.printPhaseStats.getValue())
- printPhases();
- printTotals();
- }
-
- /**
- * Print out statistics totals
- */
- @Interruptible
- public static void printTotals() {
- Log.writeln("============================ MMTk Statistics Totals ============================");
- printColumnNames();
- Log.write(phase/2); Log.write("\t");
- for (int c = 0; c < counters; c++) {
- if (counter[c].mergePhases()) {
- counter[c].printTotal(); Log.write("\t");
- } else {
- counter[c].printTotal(true); Log.write("\t");
- counter[c].printTotal(false); Log.write("\t");
- }
- }
- Log.writeln();
- Log.write("Total time: ");
- Plan.totalTime.printTotal(); Log.writeln(" ms");
- Log.writeln("------------------------------ End MMTk Statistics -----------------------------");
- }
-
- /**
- * Print out statistics for each mutator/gc phase
- */
- @Interruptible
- public static void printPhases() {
- Log.writeln("--------------------- MMTk Statistics Per GC/Mutator Phase ---------------------");
- printColumnNames();
- for (int p = 0; p <= phase; p += 2) {
- Log.write((p/2)+1); Log.write("\t");
- for (int c = 0; c < counters; c++) {
- if (counter[c].mergePhases()) {
- counter[c].printCount(p); Log.write("\t");
- } else {
- counter[c].printCount(p); Log.write("\t");
- counter[c].printCount(p+1); Log.write("\t");
- }
- }
- Log.writeln();
- }
- }
-
- /**
- * Print out statistics column names
- */
- @Interruptible
- private static void printColumnNames() {
- Log.write("GC\t");
- for (int c = 0; c < counters; c++) {
- if (counter[c].mergePhases()) {
- Log.write(counter[c].getName());
- Log.write(counter[c].getColumnSuffix());
- Log.write("\t");
- } else {
- Log.write(counter[c].getName());
- Log.write(counter[c].getColumnSuffix());
- Log.write(".mu\t");
- Log.write(counter[c].getName());
- Log.write(counter[c].getColumnSuffix());
- Log.write(".gc\t");
- }
- }
- Log.writeln();
- }
-
- /* ****************************************************************
- *
- * Statistics output in xml format
- */
-
- /**
- * Print command-line options and statistics in XML format
- */
- @Interruptible
- public static void printStatsXml() {
- Xml.begin();
- Options.set.logXml();
- VM.config.printConfigXml();
- if (Options.printPhaseStats.getValue())
- printPhasesXml();
- printTotalsXml();
- Xml.end();
- }
-
- private static void openStatXml(String name) {
- Xml.openMinorTag("stat");
- Xml.attribute("name", name);
- }
-
- private static void closeStatXml() {
- Xml.closeMinorTag();
- }
-
- enum Phase {
- MUTATOR("mu"), GC("gc"), COMBINED("all");
-
- private final String name;
- Phase(String name) {
- this.name = name;
- }
- public String toString() { return name; }
- }
-
- /**
- * Print out statistics totals in Xml format
- */
- @Interruptible
- public static void printTotalsXml() {
- Xml.openTag("mmtk-stats-totals");
- Xml.singleValue("gc", phase/2);
- for (int c = 0; c < counters; c++) {
- if (!counter[c].isComplex())
- if (counter[c].mergePhases()) {
- printTotalXml(counter[c],Phase.COMBINED);
- } else {
- printTotalXml(counter[c],Phase.MUTATOR);
- printTotalXml(counter[c],Phase.GC);
- }
- }
- Xml.singleValue("total-time",Plan.totalTime.getTotalMillis(),"ms");
- Xml.closeTag("mmtk-stats-totals");
- }
-
- /**
- * Print a single total in an xml tag
- *
- * @param c The counter
- * @param phase The phase
- */
- @Interruptible
- private static void printTotalXml(Counter c, Phase phase) {
- openStatXml(c.getName());
- Xml.attribute("suffix", c.getColumnSuffix());
- Xml.openAttribute("value");
- if (phase == Phase.COMBINED) {
- c.printTotal();
- } else {
- c.printTotal(phase == Phase.MUTATOR);
- Xml.closeAttribute();
- Xml.openAttribute("phase");
- Log.write(phase.toString());
- }
- Xml.closeAttribute();
- closeStatXml();
- }
-
- /**
- * Print a single phase counter in an xml tag
- *
- * @param c The counter
- * @param p The phase number
- * @param phase The phase (null, "mu" or "gc")
- */
- @Interruptible
- private static void printPhaseStatXml(Counter c, int p, Phase phase) {
- openStatXml(c.getName());
- Xml.attribute("suffix", c.getColumnSuffix());
- Xml.openAttribute("value");
- if (phase == Phase.COMBINED) {
- c.printCount(p);
- } else {
- c.printCount(p);
- Xml.closeAttribute();
- Xml.openAttribute("phase");
- Log.write(phase.name);
- }
- Xml.closeAttribute();
- closeStatXml();
- }
-
- /**
- * Print out statistics for each mutator/gc phase in Xml format
- */
- @Interruptible
- public static void printPhasesXml() {
- Xml.openTag("mmtk-stats-per-gc");
- for (int p = 0; p <= phase; p += 2) {
- Xml.openTag("phase",false);
- Xml.attribute("gc",(p/2)+1);
- Xml.closeMinorTag();
- for (int c = 0; c < counters; c++) {
- if (!counter[c].isComplex())
- if (counter[c].mergePhases()) {
- printPhaseStatXml(counter[c],p,Phase.COMBINED);
- } else {
- printPhaseStatXml(counter[c],p,Phase.MUTATOR);
- printPhaseStatXml(counter[c],p,Phase.GC);
- }
- }
- Xml.closeTag("phase");
- }
- Xml.closeTag("mmtk-stats-per-gc");
- }
-
- /** @return The GC count (inclusive of any in-progress GC) */
- public static int gcCount() { return gcCount; }
-
- /** @return True if currently gathering stats */
- public static boolean gatheringStats() { return gatheringStats; }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/utility/statistics/Timer.java b/vmkit/mmtk/java/src/org/mmtk/utility/statistics/Timer.java
deleted file mode 100644
index cb92c07..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/utility/statistics/Timer.java
+++ /dev/null
@@ -1,145 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.utility.statistics;
-
-import org.mmtk.utility.Log;
-import org.mmtk.vm.VM;
-
-import org.vmmagic.pragma.*;
-
-/**
- * This class implements a simple timer.
- */
-@Uninterruptible public class Timer extends LongCounter {
-
- /****************************************************************************
- *
- * Initialization
- */
-
- /**
- * Constructor
- *
- * @param name The name to be associated with this counter
- */
- public Timer(String name) {
- this(name, true, false);
- }
-
- /**
- * Constructor
- *
- * @param name The name to be associated with this counter
- * @param start True if this counter is to be implicitly started
- * when <code>startAll()</code> is called (otherwise the counter
- * must be explicitly started).
- */
- public Timer(String name, boolean start) {
- this(name, start, false);
- }
-
- /**
- * Constructor
- *
- * @param name The name to be associated with this counter
- * @param start True if this counter is to be implicitly started
- * when <code>startAll()</code> is called (otherwise the counter
- * must be explicitly started).
- * @param mergephases True if this counter does not separately
- * report GC and Mutator phases.
- */
- public Timer(String name, boolean start, boolean mergephases) {
- super(name, start, mergephases);
- }
-
- /****************************************************************************
- *
- * Counter-specific methods
- */
-
- /**
- * Get the current value for this timer
- *
- * @return The current value for this timer
- */
- @Inline
- protected final long getCurrentValue() {
- return VM.statistics.nanoTime();
- }
-
- /**
- * Print the total in microseconds
- */
- final void printTotalMicro() {
- printMicro(totalCount);
- }
-
- /**
- * Print the total in milliseconds
- */
- public final void printTotalMillis() {
- printMillis(totalCount);
- }
-
- /**
- * Print the total in seconds
- */
- public final void printTotalSecs() {
- printSecs(totalCount);
- }
-
- /**
- * Print a value (in milliseconds)
- *
- * @param value The value to be printed
- */
- final void printValue(long value) {
- printMillis(value);
- }
-
- /**
- * Print a value in microseconds
- *
- * @param value The value to be printed
- */
- final void printMicro(long value) {
- Log.write(1000 * VM.statistics.nanosToMillis(value));
- }
-
- /**
- * Print a value in milliseconds
- *
- * @param value The value to be printed
- */
- final void printMillis(long value) {
- Log.write(VM.statistics.nanosToMillis(value));
- }
-
- /**
- * Print a value in seconds
- *
- * @param value The value to be printed
- */
- final void printSecs(long value) {
- Log.write(VM.statistics.nanosToSecs(value));
- }
-
- /**
- * Get the current value of the timer in milliseconds
- */
- final double getTotalMillis() {
- return VM.statistics.nanosToMillis(totalCount);
- }
-
-}
-
diff --git a/vmkit/mmtk/java/src/org/mmtk/utility/statistics/Xml.java b/vmkit/mmtk/java/src/org/mmtk/utility/statistics/Xml.java
deleted file mode 100644
index 129ca39..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/utility/statistics/Xml.java
+++ /dev/null
@@ -1,300 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.utility.statistics;
-
-import org.mmtk.utility.Log;
-import org.vmmagic.pragma.Uninterruptible;
-import org.vmmagic.unboxed.Word;
-
-/**
- * Utility class for writing statistics out in XML format.
- */
-@Uninterruptible
-public class Xml {
- /**
- * Mark the start of XML output
- */
- public static void begin() {
- Log.writeln("<xml-begin/> <!-- Everything until xml-end is now valid xml -->");
- }
-
- /**
- * Mark the end of XML output
- */
- public static void end() {
- Log.writeln("<xml-end/> <!-- Non-xml data follows ... -->");
- }
-
- /**
- * Close the innermost XML tag and pop it from the stack.
- */
- public static void closeTag(String name) {
- Log.write("</"); Log.write(name); Log.writeln(">");
- }
-
- /**
- * Open an XML tag.
- *
- * @param name Tag name
- * @param endTag Should the tag be closed, or left open for
- * adding additional attributes
- */
- static void openTag(String name, boolean endTag) {
- openMinorTag(name);
- if (endTag)
- closeTag(false);
- }
-
- /**
- * Open a simple XML entity.
- *
- * @param name Name of the entity
- */
- static void openTag(String name) { openTag(name,true); }
-
- /**
- * Output a "stat" entity, with a given name, <code>double</code>value and optionally, units.
- *
- * @param name Name of the entity
- * @param value The value of the entity
- * @param units The units, or null for no units.
- */
- public static void singleValue(String name, double value, String units) {
- openMinorTag("stat");
- attribute("name",name);
- attribute("value",value);
- if (units != null) attribute("units",units);
- closeMinorTag();
- }
-
- /**
- * Convenience version of singleValue where units are not specified.
- *
- * @param name Name of the entity
- * @param value The value of the entity
- */
- public static void singleValue(String name, double value) {
- singleValue(name,value,null);
- }
-
- /**
- * Output a "config" entity, with a given name and <code>boolean</code>value.
- *
- * @param name Name of the entity
- * @param value The value of the entity
- */
- public static void configItem(String name, boolean value) {
- openMinorTag("conf");
- attribute("name",name);
- attribute("value",value);
- closeMinorTag();
- }
-
- /**
- * Output a "config" entity, with a given name and <code>String</code>value.
- *
- * @param name Name of the entity
- * @param value The value of the entity
- */
- public static void configItem(String name, String value) {
- openMinorTag("conf");
- attribute("name",name);
- attribute("value",value);
- closeMinorTag();
- }
-
- /**
- * Output a "stat" entity, with a given name, <code>long</code> value and
- * optionally, units.
- *
- * @param name Name of the entity
- * @param value The value of the entity
- * @param units The units, or null for no units.
- */
- public static void singleValue(String name, long value, String units) {
- openMinorTag("stat");
- attribute("name",name);
- attribute("value",value);
- if (units != null) attribute("units",units);
- closeMinorTag();
- }
-
- /**
- * Convenience version of singleValue where units are not specified.
- *
- * @param name Name of the entity
- * @param value The value of the entity
- */
- public static void singleValue(String name, long value) {
- singleValue(name,value,null);
- }
-
- /**
- * Add a word-valued attribute to an open XML tag.
- *
- * @param name Name of the entity
- * @param value The value of the entity
- */
- public static void attribute(String name, Word value) {
- openAttribute(name); Log.write(value); closeAttribute();
- }
-
- /**
- * Add a byte[]-valued attribute to an open XML tag.
- *
- * @param name Name of the entity
- * @param value The value of the entity
- */
- public static void attribute(String name, byte[] value) {
- openAttribute(name); Log.write(value); closeAttribute();
- }
-
- /**
- * Add a String-valued attribute to an open XML tag.
- *
- * @param name Name of the entity
- * @param value The value of the entity
- */
- public static void attribute(String name, String value) {
- openAttribute(name); Log.write(value); closeAttribute();
- }
-
- /**
- * Add a boolean-valued attribute to an open XML tag.
- *
- * @param name Name of the entity
- * @param value The value of the entity
- */
- public static void attribute(String name, boolean value) {
- openAttribute(name); Log.write(value); closeAttribute();
- }
-
- /**
- * Add a double-valued attribute to an open XML tag.
- *
- * @param name Name of the entity
- * @param value The value of the entity
- */
- public static void attribute(String name, double value) {
- openAttribute(name); Log.write(value); closeAttribute();
- }
-
- /**
- * Add a long-valued attribute to an open XML tag.
- *
- * @param name Name of the entity
- * @param value The value of the entity
- */
- public static void attribute(String name, long value) {
- openAttribute(name); Log.write(value); closeAttribute();
- }
-
- /**
- * Add an int-valued attribute to an open XML tag.
- *
- * @param name Name of the entity
- * @param value The value of the entity
- */
- public static void attribute(String name, int value) {
- openAttribute(name); Log.write(value); closeAttribute();
- }
-
- /**
- * Close an attribute (actually a simple close-quote)
- */
- public static void closeAttribute() {
- Log.write("\"");
- }
-
- /**
- * Open an attribute (write "{name}=\")
- *
- * @param name Name of the entity
- */
- public static void openAttribute(String name) {
- Log.write(" "); Log.write(name); Log.write("=\"");
- }
-
- /**
- * Start a tag
- */
- public static void startTag() {
- Log.write("<");
- }
-
- /**
- * End a tag, optionally closing it (if it is a simple entity)
- *
- * @param close If true, close the tag with "/>" rather than ">"
- */
- public static void closeTag(boolean close) {
- closeTag(close,true);
- }
-
- /**
- * End a tag, optionally closing it (if it is a simple entity),
- * and optionally printing end-of-line
- *
- * @param close If true, close the tag with "/>" rather than ">"
- * @param endLine If true end the current line.
- */
- public static void closeTag(boolean close, boolean endLine) {
- if (close) Log.write("/");
- Log.write(">");
- if (endLine) Log.writeln();
- }
-
- /**
- * Close a tag with a "/>"
- */
- public static void closeMinorTag() {
- closeTag(true,true);
- }
-
- /**
- * Open a tag without pushing it on the tag stack - must end this
- * with a call to closeMinorTag()
- *
- * @param name Name of the entity
- */
- public static void openMinorTag(String name) {
- Log.write("<"); Log.write(name);
- }
-
- /**
- * Open an XML comment
- */
- public static void openComment() {
- Log.write("<!-- ");
- }
-
- /**
- * Close an XML comment
- */
- public static void closeComment() {
- Log.write(" -->");
- }
-
- /**
- * Add a comment, bracketing it with open- and close-comment tags.
- *
- * @param comment The comment.
- */
- public static void comment(String comment) {
- openComment();
- Log.write(comment);
- closeComment();
- Log.writeln();
- }
-
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/vm/ActivePlan.java b/vmkit/mmtk/java/src/org/mmtk/vm/ActivePlan.java
deleted file mode 100644
index 24c107b..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/vm/ActivePlan.java
+++ /dev/null
@@ -1,59 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.vm;
-
-import org.mmtk.plan.Plan;
-import org.mmtk.plan.CollectorContext;
-import org.mmtk.plan.MutatorContext;
-import org.mmtk.plan.PlanConstraints;
-
-import org.mmtk.utility.Log;
-
-import org.vmmagic.pragma.*;
-
-/**
- * Stub to give access to plan local, constraint and global instances
- */
-@Uninterruptible public abstract class ActivePlan {
-
- /** @return The active Plan instance. */
- public abstract Plan global();
-
- /** @return The active PlanConstraints instance. */
- public abstract PlanConstraints constraints();
-
- /** @return The active <code>CollectorContext</code> instance. */
- public abstract CollectorContext collector();
-
- /** @return The active <code>MutatorContext</code> instance. */
- public abstract MutatorContext mutator();
-
- /** @return The log for the active thread */
- public abstract Log log();
-
- /** @return The maximum number of collector threads that may participate in parallel GC. */
- public abstract int collectorCount();
-
- /** Reset the mutator iterator */
- public abstract void resetMutatorIterator();
-
- /**
- * Return the next <code>MutatorContext</code> in a
- * synchronized iteration of all mutators.
- *
- * @return The next <code>MutatorContext</code> in a
- * synchronized iteration of all mutators, or
- * <code>null</code> when all mutators have been done.
- */
- public abstract MutatorContext getNextMutator();
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/vm/Assert.java b/vmkit/mmtk/java/src/org/mmtk/vm/Assert.java
deleted file mode 100644
index 92ad10c..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/vm/Assert.java
+++ /dev/null
@@ -1,77 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.vm;
-
-import org.vmmagic.pragma.Uninterruptible;
-
-@Uninterruptible public abstract class Assert {
- /**
- * Logs a message and traceback, then exits.
- *
- * @param message the string to log
- */
- public abstract void fail(String message);
-
- /**
- * Checks that the given condition is true. If it is not, this
- * method does a traceback and exits. All calls to this method
- * must be guarded by <code>VM.VERIFY_ASSERTIONS</code>.
- *
- * @param cond the condition to be checked
- */
- public abstract void _assert(boolean cond);
-
- /**
- * Checks that the given condition is true. If it is not, this
- * method prints a message, does a traceback and exits. All calls
- * to this method must be guarded by <code>VM.VERIFY_ASSERTIONS</code>.
- *
- * @param cond the condition to be checked
- * @param message the message to print
- */
- public abstract void _assert(boolean cond, String message);
-
- /**
- * Print a stack trace
- */
- public abstract void dumpStack();
-
- /**
- * Checks if the virtual machine is running. This value changes, so
- * the call-through to the VM must be a method. In Jikes RVM, just
- * returns VM.runningVM.
- *
- * @return <code>true</code> if the virtual machine is running
- */
- public abstract boolean runningVM();
-
- /*
- * NOTE: The following methods must be implemented by subclasses of this
- * class, but are internal to the VM<->MM interface glue, so are never
- * called by MMTk users.
- */
- /** @return true if assertions should be verified */
- protected abstract boolean getVerifyAssertionsConstant();
-
- /*
- * NOTE: This method should not be called by anything other than the
- * reflective mechanisms in org.mmtk.vm.VM, and is not implemented by
- * subclasses.
- *
- * This hack exists only to allow us to declare getVerifyAssertions() as
- * a protected method.
- */
- static boolean verifyAssertionsTrapdoor(Assert a) {
- return a.getVerifyAssertionsConstant();
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/vm/Barriers.java b/vmkit/mmtk/java/src/org/mmtk/vm/Barriers.java
deleted file mode 100644
index 125c8da..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/vm/Barriers.java
+++ /dev/null
@@ -1,421 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.vm;
-
-import org.vmmagic.pragma.Uninterruptible;
-import org.vmmagic.unboxed.*;
-
-@Uninterruptible
-public abstract class Barriers {
- /**
- * Perform the actual write of a boolean write barrier.
- *
- * @param ref The object that has the boolean field
- * @param value The value that the slot will be updated to
- * @param metaDataA Opaque, VM-specific, meta-data identifying the slot
- * @param metaDataB Opaque, VM-specific, meta-data identifying the slot
- * @param mode The context in which the write is occurring
- */
- public abstract void booleanWrite(ObjectReference ref, boolean value, Word metaDataA, Word metaDataB, int mode);
-
- /**
- * Perform the actual read of a boolean read barrier.
- *
- * @param ref The object that has the boolean field
- * @param metaDataA Opaque, VM-specific, meta-data identifying the slot
- * @param metaDataB Opaque, VM-specific, meta-data identifying the slot
- * @param mode The context in which the write is occurring
- * @return the read value
- */
- public abstract boolean booleanRead(ObjectReference ref, Word metaDataA, Word metaDataB, int mode);
-
- /**
- * Perform the actual write of a byte write barrier.
- *
- * @param ref The object that has the byte field
- * @param value The value that the slot will be updated to
- * @param metaDataA Opaque, VM-specific, meta-data identifying the slot
- * @param metaDataB Opaque, VM-specific, meta-data identifying the slot
- * @param mode The context in which the write is occurring
- */
- public abstract void byteWrite(ObjectReference ref, byte value, Word metaDataA, Word metaDataB, int mode);
-
- /**
- * Perform the actual read of a byte read barrier.
- *
- * @param ref The object that has the byte field
- * @param metaDataA Opaque, VM-specific, meta-data identifying the slot
- * @param metaDataB Opaque, VM-specific, meta-data identifying the slot
- * @param mode The context in which the write is occurring
- * @return the read value
- */
- public abstract byte byteRead(ObjectReference ref, Word metaDataA, Word metaDataB, int mode);
-
- /**
- * Perform the actual write of a char write barrier.
- *
- * @param ref The object that has the char field
- * @param value The value that the slot will be updated to
- * @param metaDataA Opaque, VM-specific, meta-data identifying the slot
- * @param metaDataB Opaque, VM-specific, meta-data identifying the slot
- * @param mode The context in which the write is occurring
- */
- public abstract void charWrite(ObjectReference ref, char value, Word metaDataA, Word metaDataB, int mode);
-
- /**
- * Perform the actual read of a char read barrier.
- *
- * @param ref The object that has the char field
- * @param metaDataA Opaque, VM-specific, meta-data identifying the slot
- * @param metaDataB Opaque, VM-specific, meta-data identifying the slot
- * @param mode The context in which the write is occurring
- * @return the read value
- */
- public abstract char charRead(ObjectReference ref, Word metaDataA, Word metaDataB, int mode);
-
- /**
- * Perform the actual write of a short write barrier.
- *
- * @param ref The object that has the short field
- * @param value The value that the slot will be updated to
- * @param metaDataA Opaque, VM-specific, meta-data identifying the slot
- * @param metaDataB Opaque, VM-specific, meta-data identifying the slot
- * @param mode The context in which the write is occurring
- */
- public abstract void shortWrite(ObjectReference ref, short value, Word metaDataA, Word metaDataB, int mode);
-
- /**
- * Perform the actual read of a short read barrier.
- *
- * @param ref The object that has the short field
- * @param metaDataA Opaque, VM-specific, meta-data identifying the slot
- * @param metaDataB Opaque, VM-specific, meta-data identifying the slot
- * @param mode The context in which the write is occurring
- * @return the read value
- */
- public abstract short shortRead(ObjectReference ref, Word metaDataA, Word metaDataB, int mode);
-
- /**
- * Perform the actual write of a int write barrier.
- *
- * @param ref The object that has the int field
- * @param value The value that the slot will be updated to
- * @param metaDataA Opaque, VM-specific, meta-data identifying the slot
- * @param metaDataB Opaque, VM-specific, meta-data identifying the slot
- * @param mode The context in which the write is occurring
- */
- public abstract void intWrite(ObjectReference ref, int value, Word metaDataA, Word metaDataB, int mode);
-
- /**
- * Perform the actual read of a int read barrier.
- *
- * @param ref The object that has the int field
- * @param metaDataA Opaque, VM-specific, meta-data identifying the slot
- * @param metaDataB Opaque, VM-specific, meta-data identifying the slot
- * @param mode The context in which the write is occurring
- * @return the read value
- */
- public abstract int intRead(ObjectReference ref, Word metaDataA, Word metaDataB, int mode);
-
- /**
- * Attempt an atomic compare and exchange in a write barrier sequence.
- *
- * @param objref The object that has the int field
- * @param old The old int to be swapped out
- * @param value the new int
- * @param metaDataA Opaque, VM-specific, meta-data identifying the slot
- * @param metaDataB Opaque, VM-specific, meta-data identifying the slot
- * @param mode The context in which the write is occurring
- * @return True if the compare and swap was successful
- */
- public abstract boolean intTryCompareAndSwap(ObjectReference objref, int old, int value, Word metaDataA, Word metaDataB, int mode);
-
-
- /**
- * Perform the actual write of a long write barrier.
- *
- * @param ref The object that has the long field
- * @param value The value that the slot will be updated to
- * @param metaDataA Opaque, VM-specific, meta-data identifying the slot
- * @param metaDataB Opaque, VM-specific, meta-data identifying the slot
- * @param mode The context in which the write is occurring
- */
- public abstract void longWrite(ObjectReference ref, long value, Word metaDataA, Word metaDataB, int mode);
-
- /**
- * Perform the actual read of a long read barrier.
- *
- * @param ref The object that has the long field
- * @param metaDataA Opaque, VM-specific, meta-data identifying the slot
- * @param metaDataB Opaque, VM-specific, meta-data identifying the slot
- * @param mode The context in which the write is occurring
- * @return the read value
- */
- public abstract long longRead(ObjectReference ref, Word metaDataA, Word metaDataB, int mode);
-
- /**
- * Attempt an atomic compare and exchange in a write barrier sequence.
- *
- * @param objref The object that has the long field
- * @param old The old long to be swapped out
- * @param value the new long
- * @param metaDataA Opaque, VM-specific, meta-data identifying the slot
- * @param metaDataB Opaque, VM-specific, meta-data identifying the slot
- * @param mode The context in which the write is occurring
- * @return True if the compare and swap was successful
- */
- public abstract boolean longTryCompareAndSwap(ObjectReference objref, long old, long value, Word metaDataA, Word metaDataB, int mode);
-
- /**
- * Perform the actual write of a float write barrier.
- *
- * @param ref The object that has the float field
- * @param value The value that the slot will be updated to
- * @param metaDataA Opaque, VM-specific, meta-data identifying the slot
- * @param metaDataB Opaque, VM-specific, meta-data identifying the slot
- * @param mode The context in which the write is occurring
- */
- public abstract void floatWrite(ObjectReference ref, float value, Word metaDataA, Word metaDataB, int mode);
-
- /**
- * Perform the actual read of a float read barrier.
- *
- * @param ref The object that has the float field
- * @param metaDataA Opaque, VM-specific, meta-data identifying the slot
- * @param metaDataB Opaque, VM-specific, meta-data identifying the slot
- * @param mode The context in which the write is occurring
- * @return the read value
- */
- public abstract float floatRead(ObjectReference ref, Word metaDataA, Word metaDataB, int mode);
-
- /**
- * Perform the actual write of a double write barrier.
- *
- * @param ref The object that has the double field
- * @param value The value that the slot will be updated to
- * @param metaDataA Opaque, VM-specific, meta-data identifying the slot
- * @param metaDataB Opaque, VM-specific, meta-data identifying the slot
- * @param mode The context in which the write is occurring
- */
- public abstract void doubleWrite(ObjectReference ref, double value, Word metaDataA, Word metaDataB, int mode);
-
- /**
- * Perform the actual read of a double read barrier.
- *
- * @param ref The object that has the double field
- * @param metaDataA Opaque, VM-specific, meta-data identifying the slot
- * @param metaDataB Opaque, VM-specific, meta-data identifying the slot
- * @param mode The context in which the write is occurring
- * @return the read value
- */
- public abstract double doubleRead(ObjectReference ref, Word metaDataA, Word metaDataB, int mode);
-
- /**
- * Perform the actual write of an object reference write barrier.
- *
- * @param ref The object that has the reference field
- * @param value The value that the slot will be updated to
- * @param metaDataA Opaque, VM-specific, meta-data identifying the slot
- * @param metaDataB Opaque, VM-specific, meta-data identifying the slot
- * @param mode The context in which the write is occurring
- */
- public abstract void objectReferenceWrite(ObjectReference ref, ObjectReference value, Word metaDataA, Word metaDataB, int mode);
-
- /**
- * Perform the actual read of a read barrier.
- *
- * @param ref The object that has the reference field
- * @param metaDataA Opaque, VM-specific, meta-data identifying the slot
- * @param metaDataB Opaque, VM-specific, meta-data identifying the slot
- * @param mode The context in which the write is occurring
- * @return the read value
- */
- public abstract ObjectReference objectReferenceRead(ObjectReference ref, Word metaDataA, Word metaDataB, int mode);
-
- /**
- * Perform the actual write of the non-heap write barrier. This is
- * used when the store is not to an object, but to a non-heap location
- * such as statics or the stack.
- *
- * @param slot The address that contains the reference field
- * @param target The value that the slot will be updated to
- * @param metaDataA Opaque, VM-specific, meta-data identifying the slot
- * @param metaDataB Opaque, VM-specific, meta-data identifying the slot
- */
- public abstract void objectReferenceNonHeapWrite(Address slot, ObjectReference target, Word metaDataA, Word metaDataB);
-
- /**
- * Atomically write a reference field of an object or array and return
- * the old value of the reference field.
- *
- * @param ref The object that has the reference field
- * @param target The value that the slot will be updated to
- * @param metaDataA Opaque, VM-specific, meta-data identifying the slot
- * @param metaDataB Opaque, VM-specific, meta-data identifying the slot
- * @param mode The context in which the write is occurring
- * @return The value that was replaced by the write.
- */
- public abstract ObjectReference objectReferenceAtomicWrite(ObjectReference ref, ObjectReference target, Word metaDataA, Word metaDataB, int mode);
-
- /**
- * Attempt an atomic compare and exchange in a write barrier sequence.
- *
- * @param ref The object that has the reference field
- * @param old The old reference to be swapped out
- * @param target The value that the slot will be updated to
- * @param metaDataA Opaque, VM-specific, meta-data identifying the slot
- * @param metaDataB Opaque, VM-specific, meta-data identifying the slot
- * @param mode The context in which the write is occurring
- * @return True if the compare and swap was successful
- */
- public abstract boolean objectReferenceTryCompareAndSwap(ObjectReference ref, ObjectReference old, ObjectReference target, Word metaDataA, Word metaDataB, int mode);
-
- /**
- * Perform the actual write of the write barrier, writing the value as a raw Word.
- *
- * @param ref The object that has the Word field
- * @param target The value that the slot will be updated to
- * @param metaDataA Opaque, VM-specific, meta-data identifying the slot
- * @param metaDataB Opaque, VM-specific, meta-data identifying the slot
- * @param mode The context in which the write is occurring
- */
- public abstract void wordWrite(ObjectReference ref, Word target, Word metaDataA, Word metaDataB, int mode);
-
- /**
- * Atomically write a Word field of an object or array and return
- * the old value of the Word field.
- *
- * @param ref The object that has the Word field
- * @param target The value that the slot will be updated to
- * @param metaDataA Opaque, VM-specific, meta-data identifying the slot
- * @param metaDataB Opaque, VM-specific, meta-data identifying the slot
- * @param mode The context in which the write is occurring
- * @return The raw value that was replaced by the write.
- */
- public abstract Word wordAtomicWrite(ObjectReference ref, Word rawTarget, Word metaDataA, Word metaDataB, int mode);
-
- /**
- * Attempt an atomic compare and exchange in a write barrier sequence.
- *
- * @param ref The object that has the Word field
- * @param old The old Word to be swapped out
- * @param target The value that the slot will be updated to
- * @param metaDataA Opaque, VM-specific, meta-data identifying the slot
- * @param metaDataB Opaque, VM-specific, meta-data identifying the slot
- * @param mode The context in which the write is occurring
- * @return True if the compare and swap was successful
- */
- public abstract boolean wordTryCompareAndSwap(ObjectReference ref, Word old, Word target, Word metaDataA, Word metaDataB, int mode);
-
- /**
- * Perform the actual read of the read barrier, returning the value as a raw Word.
- *
- * @param ref The object that has the Word field
- * @param metaDataA Opaque, VM-specific, meta-data identifying the slot
- * @param metaDataB Opaque, VM-specific, meta-data identifying the slot
- * @param mode The context in which the write is occurring
- * @return the read value
- */
- public abstract Word wordRead(ObjectReference ref, Word metaDataA, Word metaDataB, int mode);
-
- /**
- * Perform the actual write of the write barrier, writing the value as a raw Address.
- *
- * @param ref The object that has the Address field
- * @param target The value that the slot will be updated to
- * @param metaDataA Opaque, VM-specific, meta-data identifying the slot
- * @param metaDataB Opaque, VM-specific, meta-data identifying the slot
- * @param mode The context in which the write is occurring
- */
- public abstract void addressWrite(ObjectReference ref, Address target, Word metaDataA, Word metaDataB, int mode);
-
- /**
- * Perform the actual read of the read barrier, returning the value as a raw Address.
- *
- * @param ref The object that has the Address field
- * @param metaDataA Opaque, VM-specific, meta-data identifying the slot
- * @param metaDataB Opaque, VM-specific, meta-data identifying the slot
- * @param mode The context in which the write is occurring
- * @return the read value
- */
- public abstract Address addressRead(ObjectReference ref, Word metaDataA, Word metaDataB, int mode);
-
- /**
- * Attempt an atomic compare and exchange in a write barrier sequence.
- *
- * @param ref The object that has the Address field
- * @param old The old address to be swapped out
- * @param target The value that the slot will be updated to
- * @param metaDataA Opaque, VM-specific, meta-data identifying the slot
- * @param metaDataB Opaque, VM-specific, meta-data identifying the slot
- * @param mode The context in which the write is occurring
- * @return True if the compare and swap was successful
- */
- public abstract boolean addressTryCompareAndSwap(ObjectReference ref, Address old, Address target, Word metaDataA, Word metaDataB, int mode);
-
- /**
- * Perform the actual write of the write barrier, writing the value as a raw Offset.
- *
- * @param ref The object that has the Offset field
- * @param target The value that the slot will be updated to
- * @param metaDataA Opaque, VM-specific, meta-data identifying the slot
- * @param metaDataB Opaque, VM-specific, meta-data identifying the slot
- * @param mode The context in which the write is occurring
- */
- public abstract void offsetWrite(ObjectReference ref, Offset target, Word metaDataA, Word metaDataB, int mode);
-
- /**
- * Perform the actual read of the read barrier, returning the value as a raw Offset.
- *
- * @param ref The object that has the Offset field
- * @param metaDataA Opaque, VM-specific, meta-data identifying the slot
- * @param metaDataB Opaque, VM-specific, meta-data identifying the slot
- * @param mode The context in which the write is occurring
- * @return the read value
- */
- public abstract Offset offsetRead(ObjectReference ref, Word metaDataA, Word metaDataB, int mode);
-
- /**
- * Perform the actual write of the write barrier, writing the value as a raw Extent.
- *
- * @param ref The object that has the Extent field
- * @param target The value that the slot will be updated to
- * @param metaDataA Opaque, VM-specific, meta-data identifying the slot
- * @param metaDataB Opaque, VM-specific, meta-data identifying the slot
- * @param mode The context in which the write is occurring
- */
- public abstract void extentWrite(ObjectReference ref, Extent target, Word metaDataA, Word metaDataB, int mode);
-
- /**
- * Perform the actual read of the read barrier, returning the value as a raw Extent.
- *
- * @param ref The object that has the Extent field
- * @param metaDataA Opaque, VM-specific, meta-data identifying the slot
- * @param metaDataB Opaque, VM-specific, meta-data identifying the slot
- * @param mode The context in which the write is occurring
- * @return the read value
- */
- public abstract Extent extentRead(ObjectReference ref, Word metaDataA, Word metaDataB, int mode);
-
- /**
- * Sets an element of an object array without invoking any write
- * barrier. This method is called by the Map class to ensure
- * potentially-allocation-triggering write barriers do not occur in
- * allocation slow path code.
- *
- * @param dst the destination array
- * @param index the index of the element to set
- * @param value the new value for the element
- */
- public abstract void objectArrayStoreNoGCBarrier(Object [] dst, int index, Object value);
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/vm/BuildTimeConfig.java b/vmkit/mmtk/java/src/org/mmtk/vm/BuildTimeConfig.java
deleted file mode 100644
index 2eaa48c..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/vm/BuildTimeConfig.java
+++ /dev/null
@@ -1,69 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.vm;
-
-/**
- * Build-time configuration constants for MMTk.
- */
-public abstract class BuildTimeConfig {
-
- /**
- * @return The name of the current MMTk plan
- */
- public abstract String getPlanName();
-
- /**
- * Return a property of type String
- * @param name The name of the property
- * @return The value of the property
- */
- public abstract String getStringProperty(String name);
-
- /**
- * Return a property of type String, with default.
- * @param name The name of the property
- * @param dflt Default value
- * @return The value of the property
- */
- public abstract String getStringProperty(String name, String dflt);
-
- /**
- * Return a property of type int
- * @param name The name of the property
- * @return The value of the property
- */
- public abstract int getIntProperty(String name);
-
- /**
- * Return a property of type String, with default.
- * @param name The name of the property
- * @param dflt Default value
- * @return The value of the property
- */
- public abstract int getIntProperty(String name, int dflt);
-
- /**
- * Return a property of type boolean
- * @param name The name of the property
- * @return The value of the property
- */
- public abstract boolean getBooleanProperty(String name);
-
- /**
- * Return a property of type boolean, with default.
- * @param name The name of the property
- * @param dflt Default value
- * @return The value of the property
- */
- public abstract boolean getBooleanProperty(String name, boolean dflt);
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/vm/Collection.java b/vmkit/mmtk/java/src/org/mmtk/vm/Collection.java
deleted file mode 100644
index 53484ff..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/vm/Collection.java
+++ /dev/null
@@ -1,160 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.vm;
-
-import org.mmtk.plan.CollectorContext;
-import org.mmtk.plan.MutatorContext;
-
-import org.vmmagic.pragma.*;
-
-@Uninterruptible public abstract class Collection {
-
- /****************************************************************************
- *
- * Class variables
- */
-
- /**
- * An unknown GC trigger reason. Signals a logic bug.
- */
- public static final int UNKNOWN_GC_TRIGGER = 0;
-
- /**
- * Concurrent collection phase trigger.
- */
- public static final int INTERNAL_PHASE_GC_TRIGGER = 1;
-
- /**
- * Externally triggered garbage collection (eg call to System.gc())
- */
- public static final int EXTERNAL_GC_TRIGGER = 2;
-
- /**
- * Resource triggered garbage collection. For example, an
- * allocation request would take the number of pages in use beyond
- * the number available.
- */
- public static final int RESOURCE_GC_TRIGGER = 3;
-
- /**
- * Internally triggered garbage collection. For example, the memory
- * manager attempting another collection after the first failed to
- * free space.
- */
- public static final int INTERNAL_GC_TRIGGER = 4;
-
- /**
- * The number of garbage collection trigger reasons.
- */
- public static final int TRIGGER_REASONS = 5;
-
- /** Short descriptions of the garbage collection trigger reasons. */
- protected static final String[] triggerReasons = {
- "unknown",
- "concurrent phase",
- "external request",
- "resource exhaustion",
- "internal request"
- };
-
- /**
- * Triggers a collection.
- *
- * @param why the reason why a collection was triggered. 0 to
- * <code>TRIGGER_REASONS - 1</code>.
- */
- @Unpreemptible
- public abstract void triggerCollection(int why);
-
- /**
- * Joins an already requested collection.
- */
- @Unpreemptible
- public abstract void joinCollection();
-
- /**
- * Trigger an asynchronous collection, checking for memory
- * exhaustion first.
- *
- * @param why the reason why a collection was triggered. 0 to
- * <code>TRIGGER_REASONS - 1</code>.
- */
- public abstract void triggerAsyncCollection(int why);
-
- /**
- * The maximum number collection attempts across threads.
- */
- public abstract int maximumCollectionAttempt();
-
- /**
- * Report that the allocation has succeeded.
- */
- public abstract void reportAllocationSuccess();
-
- /**
- * Report that a physical allocation has failed.
- */
- public abstract void reportPhysicalAllocationFailed();
-
- /**
- * Does the VM consider this an emergency alloction, where the normal
- * heap size rules can be ignored.
- */
- public abstract boolean isEmergencyAllocation();
-
- /**
- * Determine whether a collection cycle has fully completed (this is
- * used to ensure a GC is not in the process of completing, to
- * avoid, for example, an async GC being triggered on the switch
- * from GC to mutator thread before all GC threads have switched.
- *
- * @return True if GC is not in progress.
- */
- public abstract boolean noThreadsInGC();
-
- /**
- * Prepare a mutator for collection.
- *
- * @param m the mutator to prepare
- */
- public abstract void prepareMutator(MutatorContext m);
-
- /**
- * Prepare a collector for a collection.
- *
- * @param c the collector to prepare
- */
- public abstract void prepareCollector(CollectorContext c);
-
- /**
- * Rendezvous with all other processors, returning the rank
- * (that is, the order this processor arrived at the barrier).
- */
- public abstract int rendezvous(int where);
-
- /** @return The number of active collector threads */
- public abstract int activeGCThreads();
-
- /**
- * @return The ordinal ID of the running collector thread w.r.t.
- * the set of active collector threads (zero based)
- */
- public abstract int activeGCThreadOrdinal();
-
- /**
- * Request each mutator flush remembered sets. This method
- * will trigger the flush and then yield until all processors have
- * flushed.
- */
- public abstract void requestMutatorFlush();
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/vm/Config.java b/vmkit/mmtk/java/src/org/mmtk/vm/Config.java
deleted file mode 100644
index 71ae8c5..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/vm/Config.java
+++ /dev/null
@@ -1,43 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.vm;
-
-import org.mmtk.utility.Log;
-import org.mmtk.utility.statistics.Xml;
-
-public class Config {
- /* The name of the active plan */
- private final String ACTIVE_PLAN;
-
- /** Mark bit in the header or on the side ? */
- public final boolean HEADER_MARK_BITS;
-
- Config(BuildTimeConfig config) {
- ACTIVE_PLAN = config.getPlanName();
- HEADER_MARK_BITS = config.getBooleanProperty("mmtk.headerMarkBit",true);
- }
-
- public void printConfig() {
- Log.writeln("================ MMTk Configuration ================");
- Log.write("plan = "); Log.writeln(ACTIVE_PLAN);
- Log.write("HEADER_MARK_BITS = "); Log.writeln(HEADER_MARK_BITS);
- Log.writeln("====================================================");
- }
-
- public void printConfigXml() {
- Log.writeln("<config>");
- Xml.configItem("plan",ACTIVE_PLAN);
- Xml.configItem("header-mark-bit",HEADER_MARK_BITS);
- Log.writeln("</config>");
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/vm/Debug.java b/vmkit/mmtk/java/src/org/mmtk/vm/Debug.java
deleted file mode 100644
index fa53d7e..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/vm/Debug.java
+++ /dev/null
@@ -1,142 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.vm;
-
-import org.mmtk.plan.TraceLocal;
-import org.vmmagic.pragma.Uninterruptible;
-import org.vmmagic.unboxed.Address;
-import org.vmmagic.unboxed.ObjectReference;
-
-/**
- *
- */
-@Uninterruptible
-public abstract class Debug {
- /**
- * Global switch for debugging - if false the other methods of this
- * class are never called.
- * @return Whether debugging is enabled
- */
- public abstract boolean isEnabled();
-
- /**
- * A modbuf (object remembering barrier) entry has been
- * traced during collection.
- * @param object The modbuf entry
- */
- public void modbufEntry(ObjectReference object) { }
-
- /**
- * A remset (slot remembering barrier) entry has been
- * traced during collection.
- * @param slot The remset entry
- */
- public void remsetEntry(Address slot) { }
-
- /**
- * An array remset entry has been traced during collection. Implicitly
- * the slots from start (inclusive) through to guard (non-inclusive)
- * are traced as remset entries
- * @param start The entry start address
- * @param guard The guard
- */
- public void arrayRemsetEntry(Address start, Address guard) { }
-
- /**
- * A global GC collection phase
- * @param phaseId The phase ID
- * @param before true at the start of the phase, false at the end
- */
- public void globalPhase(short phaseId, boolean before) { }
-
- /**
- * A per-collector GC collection phase
- * @param phaseId The phase ID
- * @param ordinal The collector ID (within this collection)
- * @param before true at the start of the phase, false at the end
- */
- public void collectorPhase(short phaseId, int ordinal, boolean before) { }
-
- /**
- * A per-mutator GC collection phase
- * @param phaseId The phase ID
- * @param ordinal The mutator ID
- * @param before true at the start of the phase, false at the end
- */
- public void mutatorPhase(short phaseId, int ordinal, boolean before) { }
-
- /**
- * Trace an object during GC
- *
- * *** Non-standard, requires plumbing into a collector during debugging ***
- *
- * @param trace The trace being performed
- * @param object The object
- */
- public void traceObject(TraceLocal trace, ObjectReference object) { }
-
- /**
- * An entry has been inserted at the head of a queue
- *
- * *** Non-standard, requires plumbing into a collector during debugging ***
- *
- * @param queueName The name of the queue
- * @param value The value
- */
- public void queueHeadInsert(String queueName, Address value) {
- }
-
- /**
- * An entry has been inserted at the head of a queue
- *
- * *** Non-standard, requires plumbing into a collector during debugging ***
- *
- * @param queueName The name of the queue
- * @param value The value
- */
- public void queueTailInsert(String queueName, Address value) {
- }
-
- /**
- * An entry has been inserted at the head of a queue
- *
- * *** Non-standard, requires plumbing into a collector during debugging ***
- *
- * @param queueName The name of the queue
- * @param value The value
- */
- public void queueHeadRemove(String queueName, Address value) { }
-
- /**
- * An entry has been inserted at the head of a queue
- *
- * *** Non-standard, requires plumbing into a collector during debugging ***
- *
- * @param queueName The name of the queue
- * @param value The value
- */
- public void queueTailRemove(String queueName, Address value) { }
-
- /*
- * NOTE: These methods should not be called by anything other than the
- * reflective mechanisms in org.mmtk.vm.VM, and are not implemented by
- * subclasses.
- *
- * This hack exists only to allow us to declare the respective
- * methods as protected.
- */
- static final boolean isEnabledTrapdoor(Debug d) {
- return d.isEnabled();
- }
-
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/vm/Factory.java b/vmkit/mmtk/java/src/org/mmtk/vm/Factory.java
deleted file mode 100644
index be276af..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/vm/Factory.java
+++ /dev/null
@@ -1,347 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.vm;
-
-import org.vmutil.options.OptionSet;
-import org.mmtk.utility.gcspy.Color;
-import org.mmtk.utility.gcspy.drivers.AbstractDriver;
-import org.mmtk.vm.gcspy.ByteStream;
-import org.mmtk.vm.gcspy.IntStream;
-import org.mmtk.vm.gcspy.ServerInterpreter;
-import org.mmtk.vm.gcspy.ServerSpace;
-import org.mmtk.vm.gcspy.ShortStream;
-import org.mmtk.vm.gcspy.Util;
-
-/**
- * This class defines factory methods for VM-specific types which must
- * be instantiated within MMTk. Since the concrete type is defined at
- * build time, we leave it to a concrete vm-specific instance of this class
- * to perform the object instantiation.
- */
-public abstract class Factory {
-
- /**
- * Create or retrieve the OptionSet used for MMTk options.
- *
- * @return A concrete VM-specific OptionSet instance
- */
- public abstract OptionSet getOptionSet();
-
- /**
- * Create a new ActivePlan instance using the appropriate VM-specific
- * concrete ActivePlan sub-class.
- *
- * @see ActivePlan
- * @return A concrete VM-specific ActivePlan instance.
- */
- public abstract ActivePlan newActivePlan();
-
- /**
- * Create a new Assert instance using the appropriate VM-specific
- * concrete Assert sub-class.
- *
- * @see Assert
- * @return A concrete VM-specific Assert instance.
- */
- public abstract Assert newAssert();
-
- /**
- * Create a new Barriers instance using the appropriate VM-specific
- * concrete Barriers sub-class.
- *
- * @see Barriers
- * @return A concrete VM-specific Barriers instance.
- */
- public abstract Barriers newBarriers();
-
- /**
- * Create a new Collection instance using the appropriate VM-specific
- * concrete Collection sub-class.
- *
- * @see Collection
- * @return A concrete VM-specific Collection instance.
- */
- public abstract Collection newCollection();
-
- /**
- * Create a new Config instance using the appropriate VM-specific
- * concrete Config sub-class.
- *
- * @see Collection
- * @return A concrete VM-specific Collection instance.
- */
- public abstract BuildTimeConfig newBuildTimeConfig();
-
- /**
- * Create a new Lock instance using the appropriate VM-specific
- * concrete Lock sub-class.
- *
- * @see Lock
- * @param name The string to be associated with this lock instance
- * @return A concrete VM-specific Lock instance.
- */
- public abstract Lock newLock(String name);
-
- /**
- * Create a new Memory instance using the appropriate VM-specific
- * concrete Memory sub-class.
- *
- * @see Memory
- * @return A concrete VM-specific Memory instance.
- */
- public abstract Memory newMemory();
-
- /**
- * Create a new ObjectModel instance using the appropriate VM-specific
- * concrete ObjectModel sub-class.
- *
- * @see ObjectModel
- * @return A concrete VM-specific ObjectModel instance.
- */
- public abstract ObjectModel newObjectModel();
-
- /**
- * Create a new ReferenceProcessor instance using the appropriate VM-specific
- * concrete ReferenceProcessor sub-class.
- *
- * @see ReferenceProcessor
- * @return A concrete VM-specific ReferenceProcessor instance.
- */
- public abstract ReferenceProcessor newReferenceProcessor(ReferenceProcessor.Semantics semantics);
-
-
- /**
- * Create a new FinalizbleProcessor instance using the appropriate VM-specific
- * concrete FinalizableProcessor sub-class.
- *
- * @see FinalizableProcessor
- * @return A concrete VM-specific FinalizableProcessor instance.
- */
- public abstract FinalizableProcessor newFinalizableProcessor();
-
- /**
- * Create a new Scanning instance using the appropriate VM-specific
- * concrete Scanning sub-class.
- *
- * @see Scanning
- * @return A concrete VM-specific Scanning instance.
- */
- public abstract Scanning newScanning();
-
- /**
- * Create a new Statistics instance using the appropriate VM-specific
- * concrete Statistics sub-class.
- *
- * @see Statistics
- * @return A concrete VM-specific Statistics instance.
- */
- public abstract Statistics newStatistics();
-
- /**
- * Create a new Strings instance using the appropriate VM-specific
- * concrete Strings sub-class.
- *
- * @see Strings
- * @return A concrete VM-specific Strings instance.
- */
- public abstract Strings newStrings();
-
- /**
- * Create a new SynchronizedCounter instance using the appropriate
- * VM-specific concrete SynchronizedCounter sub-class.
- *
- * @see SynchronizedCounter
- *
- * @return A concrete VM-specific SynchronizedCounter instance.
- */
- public abstract SynchronizedCounter newSynchronizedCounter();
-
- /**
- * Create a new TraceInterface instance using the appropriate VM-specific
- * concrete TraceInterface sub-class.
- *
- * @see TraceInterface
- * @return A concrete VM-specific TraceInterface instance.
- */
- public abstract TraceInterface newTraceInterface();
-
- /**
- * Create a new MMTk_Events instance using the appropriate VM-specific
- * concrete MMTk_Events sub-class.
- */
- public abstract MMTk_Events newEvents();
-
- /**
- * Create a new debug object
- */
- public abstract Debug newDebug();
-
- /**********************************************************************
- * GCspy methods
- */
-
- /**
- * Create a new Util instance using the appropriate VM-specific
- * concrete Util sub-class.
- *
- * @see Util
- * @return A concrete VM-specific Util instance.
- */
- public abstract Util newGCspyUtil();
-
- /**
- * Create a new ServerInterpreter instance using the appropriate VM-specific
- * concrete ServerInterpreter sub-class.
- *
- * @see ServerInterpreter
- * @return A concrete VM-specific ServerInterpreter instance.
- */
- public abstract ServerInterpreter newGCspyServerInterpreter();
-
- /**
- * Create a new ServerSpace instance using the appropriate VM-specific
- * concrete ServerSpace sub-class.
- *
- * @param serverInterpreter The server that owns this space
- * @param serverName The server's name
- * @param driverName The space driver's name
- * @param title Title for the space
- * @param blockInfo A label for each block
- * @param tileNum Max number of tiles in this space
- * @param unused A label for unused blocks
- * @param mainSpace Whether this space is the main space
- *
- * @see ServerSpace
- * @return A concrete VM-specific ServerSpace instance.
- */
- public abstract ServerSpace newGCspyServerSpace(
- ServerInterpreter serverInterpreter,
- String serverName,
- String driverName,
- String title,
- String blockInfo,
- int tileNum,
- String unused,
- boolean mainSpace);
-
- /**
- * Create a new IntStream instance using the appropriate
- * VM-specific concrete IntStream sub-class.
- *
- * @param driver The driver that owns this Stream
- * @param name The name of the stream (e.g. "Used space")
- * @param minValue The minimum value for any item in this stream.
- * Values less than this will be represented as "minValue-"
- * @param maxValue The maximum value for any item in this stream.
- * Values greater than this will be represented as "maxValue+"
- * @param zeroValue The zero value for this stream
- * @param defaultValue The default value for this stream
- * @param stringPre A string to prefix values (e.g. "Used: ")
- * @param stringPost A string to suffix values (e.g. " bytes.")
- * @param presentation How a stream value is to be presented.
- * @param paintStyle How the value is to be painted.
- * @param indexMaxStream The index of the maximum stream if the presentation is *_VAR.
- * @param colour The default colour for tiles of this stream
- * @see IntStream
- *
- * @return A concrete VM-specific IntStream instance.
- */
- public abstract IntStream newGCspyIntStream(
- AbstractDriver driver,
- String name,
- int minValue,
- int maxValue,
- int zeroValue,
- int defaultValue,
- String stringPre,
- String stringPost,
- int presentation,
- int paintStyle,
- int indexMaxStream,
- Color colour,
- boolean summary);
-
- /**
- * Create a new ByteStream instance using the appropriate
- * VM-specific concrete ByteStream sub-class.
- *
- * @param driver The driver that owns this Stream
- * @param name The name of the stream (e.g. "Used space")
- * @param minValue The minimum value for any item in this stream.
- * Values less than this will be represented as "minValue-"
- * @param maxValue The maximum value for any item in this stream.
- * Values greater than this will be represented as "maxValue+"
- * @param zeroValue The zero value for this stream
- * @param defaultValue The default value for this stream
- * @param stringPre A string to prefix values (e.g. "Used: ")
- * @param stringPost A string to suffix values (e.g. " bytes.")
- * @param presentation How a stream value is to be presented.
- * @param paintStyle How the value is to be painted.
- * @param indexMaxStream The index of the maximum stream if the presentation is *_VAR.
- * @param colour The default colour for tiles of this stream
- * @see IntStream
- *
- * @return A concrete VM-specific ByteStream instance.
- */
- public abstract ByteStream newGCspyByteStream(
- AbstractDriver driver,
- String name,
- byte minValue,
- byte maxValue,
- byte zeroValue,
- byte defaultValue,
- String stringPre,
- String stringPost,
- int presentation,
- int paintStyle,
- int indexMaxStream,
- Color colour,
- boolean summary);
-
- /**
- * Create a new ShortStream instance using the appropriate
- * VM-specific concrete ShortStream sub-class.
- *
- * @param driver The driver that owns this Stream
- * @param name The name of the stream (e.g. "Used space")
- * @param minValue The minimum value for any item in this stream.
- * Values less than this will be represented as "minValue-"
- * @param maxValue The maximum value for any item in this stream.
- * Values greater than this will be represented as "maxValue+"
- * @param zeroValue The zero value for this stream
- * @param defaultValue The default value for this stream
- * @param stringPre A string to prefix values (e.g. "Used: ")
- * @param stringPost A string to suffix values (e.g. " bytes.")
- * @param presentation How a stream value is to be presented.
- * @param paintStyle How the value is to be painted.
- * @param indexMaxStream The index of the maximum stream if the presentation is *_VAR.
- * @param colour The default colour for tiles of this stream
- * @see IntStream
- *
- * @return A concrete VM-specific ShortStream instance.
- */
- public abstract ShortStream newGCspyShortStream(
- AbstractDriver driver,
- String name,
- short minValue,
- short maxValue,
- short zeroValue,
- short defaultValue,
- String stringPre,
- String stringPost,
- int presentation,
- int paintStyle,
- int indexMaxStream,
- Color colour,
- boolean summary);
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/vm/FinalizableProcessor.java b/vmkit/mmtk/java/src/org/mmtk/vm/FinalizableProcessor.java
deleted file mode 100644
index 66f0b29..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/vm/FinalizableProcessor.java
+++ /dev/null
@@ -1,42 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.vm;
-
-import org.mmtk.plan.TraceLocal;
-import org.vmmagic.pragma.Uninterruptible;
-
-/**
- * This class manages finalizable objects.
- */
-@Uninterruptible
-public abstract class FinalizableProcessor {
-
- /**
- * Clear the contents of the table. This is called when finalization is
- * disabled to make it easier for VMs to change this setting at runtime.
- */
- public abstract void clear();
-
- /**
- * Scan through the list of references.
- *
- * @param trace the thread local trace element.
- * @param nursery true if it is safe to only scan new references.
- */
- public abstract void scan(TraceLocal trace, boolean nursery);
-
- /**
- * Iterate over and forward entries in the table.
- */
- public abstract void forward(TraceLocal trace, boolean nursery);
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/vm/Lock.java b/vmkit/mmtk/java/src/org/mmtk/vm/Lock.java
deleted file mode 100644
index a8d65d9..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/vm/Lock.java
+++ /dev/null
@@ -1,47 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.vm;
-
-import org.vmmagic.pragma.Uninterruptible;
-
-/**
- * Simple, fair locks with deadlock detection.
- */
-@Uninterruptible public abstract class Lock {
-
- /**
- * Set the name of this lock instance
- *
- * @param str The name of the lock (for error output).
- */
- public abstract void setName(String str);
-
-
- /**
- * Try to acquire a lock and spin-wait until acquired.
- */
- public abstract void acquire();
-
- /**
- * Perform sanity checks on the lock. For debugging.
- *
- * @param w Identifies the code location in the debugging output.
- */
- public abstract void check(int w);
-
- /**
- * Release the lock by incrementing serving counter.
- */
- public abstract void release();
-
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/vm/MMTk_Events.java b/vmkit/mmtk/java/src/org/mmtk/vm/MMTk_Events.java
deleted file mode 100644
index 24f42fd..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/vm/MMTk_Events.java
+++ /dev/null
@@ -1,32 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-
-package org.mmtk.vm;
-
-import org.mmtk.policy.Space;
-import org.vmmagic.pragma.Uninterruptible;
-import org.vmmagic.unboxed.Address;
-import org.vmmagic.unboxed.Extent;
-
-/**
- * Event generation interface for MMTk.
- */
-@Uninterruptible
-public abstract class MMTk_Events {
- public abstract void tracePageAcquired(Space space, Address startAddress, int numPages);
-
- public abstract void tracePageReleased(Space space, Address startAddress, int numPages);
-
- public abstract void heapSizeChanged(Extent heapSize);
-
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/vm/Memory.java b/vmkit/mmtk/java/src/org/mmtk/vm/Memory.java
deleted file mode 100644
index 283eecc..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/vm/Memory.java
+++ /dev/null
@@ -1,211 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.vm;
-
-import org.mmtk.policy.ImmortalSpace;
-
-import org.vmmagic.unboxed.*;
-import org.vmmagic.pragma.*;
-
-@Uninterruptible public abstract class Memory {
-
- /**
- * Allows for the VM to reserve space between HEAP_START()
- * and AVAILABLE_START() for its own purposes. MMTk should
- * expect to encounter objects in this range, but may not
- * allocate in this range.
- *
- * MMTk expects the virtual address space between AVAILABLE_START()
- * and AVAILABLE_END() to be contiguous and unmapped.
- * Allows for the VM to reserve space between HEAP_END()
- * and AVAILABLE_END() for its own purposes. MMTk should
- * expect to encounter objects in this range, but may not
- * allocate in this range.
- *
- * MMTk expects the virtual address space between AVAILABLE_START()
- * and AVAILABLE_END() to be contiguous and unmapped.
- *
- * @return The high bound of the memory that MMTk can allocate.
- */
-
- /**
- * Return the space associated with/reserved for the VM. In the
- * case of Jikes RVM this is the boot image space.<p>
- *
- * @return The space managed by the virtual machine.
- */
- @Interruptible
- public abstract ImmortalSpace getVMSpace();
-
- /** Global preparation for a collection. */
- public abstract void globalPrepareVMSpace();
-
- /** Per-collector preparation for a collection. */
- public abstract void collectorPrepareVMSpace();
-
- /** Per-collector post-collection work. */
- public abstract void collectorReleaseVMSpace();
-
- /** Global post-collection work. */
- public abstract void globalReleaseVMSpace();
-
- /**
- * Sets the range of addresses associated with a heap.
- *
- * @param id the heap identifier
- * @param start the address of the start of the heap
- * @param end the address of the end of the heap
- */
- public abstract void setHeapRange(int id, Address start, Address end);
-
- /**
- * Demand zero mmaps an area of virtual memory.
- *
- * @param start the address of the start of the area to be mapped
- * @param size the size, in bytes, of the area to be mapped
- * @return 0 if successful, otherwise the system errno
- */
- public abstract int dzmmap(Address start, int size);
-
- /**
- * Protects access to an area of virtual memory.
- *
- * @param start the address of the start of the area to be mapped
- * @param size the size, in bytes, of the area to be mapped
- * @return <code>true</code> if successful, otherwise
- * <code>false</code>
- */
- public abstract boolean mprotect(Address start, int size);
-
- /**
- * Allows access to an area of virtual memory.
- *
- * @param start the address of the start of the area to be mapped
- * @param size the size, in bytes, of the area to be mapped
- * @return <code>true</code> if successful, otherwise
- * <code>false</code>
- */
- public abstract boolean munprotect(Address start, int size);
-
- /**
- * Zero a region of memory.
- * @param start Start of address range (inclusive)
- * @param len Length in bytes of range to zero
- * Returned: nothing
- */
- public abstract void zero(Address start, Extent len);
-
- /**
- * Zero a range of pages of memory.
- * @param start Start of address range (must be a page address)
- * @param len Length in bytes of range (must be multiple of page size)
- */
- public abstract void zeroPages(Address start, int len);
-
- /**
- * Logs the contents of an address and the surrounding memory to the
- * error output.
- *
- * @param start the address of the memory to be dumped
- * @param beforeBytes the number of bytes before the address to be
- * included
- * @param afterBytes the number of bytes after the address to be
- * included
- */
- public abstract void dumpMemory(Address start, int beforeBytes,
- int afterBytes);
-
- /**
- * Wait for preceeding cache flush/invalidate instructions to complete
- * on all processors. Ensures that all memory writes before this
- * point are visible to all processors.
- */
- @Inline
- public abstract void sync();
-
- /**
- * Wait for all preceeding instructions to complete and discard any
- * prefetched instructions on this processor. Also prevents the
- * compiler from performing code motion across this point.
- */
- @Inline
- public abstract void isync();
-
- /*
- * NOTE: The following methods must be implemented by subclasses of this
- * class, but are internal to the VM<->MM interface glue, so are never
- * called by MMTk users.
- */
- /** @return The lowest address in the virtual address space known to MMTk */
- protected abstract Address getHeapStartConstant();
- /** @return The highest address in the virtual address space known to MMTk */
- protected abstract Address getHeapEndConstant();
- /** @return The lowest address in the contiguous address space available to MMTk */
- protected abstract Address getAvailableStartConstant();
- /** @return The highest address in the contiguous address space available to MMTk */
- protected abstract Address getAvailableEndConstant();
- /** @return The log base two of the size of an address */
- protected abstract byte getLogBytesInAddressConstant();
- /** @return The log base two of the size of a word */
- protected abstract byte getLogBytesInWordConstant();
- /** @return The log base two of the size of an OS page */
- protected abstract byte getLogBytesInPageConstant();
- /** @return The log base two of the minimum allocation alignment */
- protected abstract byte getLogMinAlignmentConstant();
- /** @return The log base two of (MAX_ALIGNMENT/MIN_ALIGNMENT) */
- protected abstract byte getMaxAlignmentShiftConstant();
- /** @return The maximum number of bytes of padding to prepend to an object */
- protected abstract int getMaxBytesPaddingConstant();
- /** @return The value to store in alignment holes */
- protected abstract int getAlignmentValueConstant();
-
- /*
- * NOTE: These methods should not be called by anything other than the
- * reflective mechanisms in org.mmtk.vm.VM, and are not implemented by
- * subclasses. This hack exists only to allow us to declare the respective
- * methods as protected.
- */
- static Address heapStartTrapdoor(Memory m) {
- return m.getHeapStartConstant();
- }
- static Address heapEndTrapdoor(Memory m) {
- return m.getHeapEndConstant();
- }
- static Address availableStartTrapdoor(Memory m) {
- return m.getAvailableStartConstant();
- }
- static Address availableEndTrapdoor(Memory m) {
- return m.getAvailableEndConstant();
- }
- static byte logBytesInAddressTrapdoor(Memory m) {
- return m.getLogBytesInAddressConstant();
- }
- static byte logBytesInWordTrapdoor(Memory m) {
- return m.getLogBytesInWordConstant();
- }
- static byte logBytesInPageTrapdoor(Memory m) {
- return m.getLogBytesInPageConstant();
- }
- static byte logMinAlignmentTrapdoor(Memory m) {
- return m.getLogMinAlignmentConstant();
- }
- static byte maxAlignmentShiftTrapdoor(Memory m) {
- return m.getMaxAlignmentShiftConstant();
- }
- static int maxBytesPaddingTrapdoor(Memory m) {
- return m.getMaxBytesPaddingConstant();
- }
- static int alignmentValueTrapdoor(Memory m) {
- return m.getAlignmentValueConstant();
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/vm/ObjectModel.java b/vmkit/mmtk/java/src/org/mmtk/vm/ObjectModel.java
deleted file mode 100644
index 7a04160..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/vm/ObjectModel.java
+++ /dev/null
@@ -1,256 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.vm;
-
-import org.vmmagic.pragma.Uninterruptible;
-import org.vmmagic.unboxed.*;
-
-@Uninterruptible public abstract class ObjectModel {
- /**
- * Copy an object using a plan's allocCopy to get space and install
- * the forwarding pointer. On entry, <code>from</code> must have
- * been reserved for copying by the caller. This method calls the
- * plan's <code>getStatusForCopy()</code> method to establish a new
- * status word for the copied object and <code>postCopy()</code> to
- * allow the plan to perform any post copy actions.
- *
- * @param from the address of the object to be copied
- * @param allocator The allocator to use.
- * @return the address of the new object
- */
- public abstract ObjectReference copy(ObjectReference from, int allocator);
-
- /**
- * Copy an object to be pointer to by the to address. This is required
- * for delayed-copy collectors such as compacting collectors. During the
- * collection, MMTk reserves a region in the heap for an object as per
- * requirements found from ObjectModel and then asks ObjectModel to
- * determine what the object's reference will be post-copy.
- *
- * @param from the address of the object to be copied
- * @param to The target location.
- * @param region The start of the region that was reserved for this object
- * @return Address The address past the end of the copied object
- */
- public abstract Address copyTo(ObjectReference from, ObjectReference to, Address region);
-
- /**
- * Return the reference that an object will be refered to after it is copied
- * to the specified region. Used in delayed-copy collectors such as compacting
- * collectors.
- *
- * @param from The object to be copied.
- * @param to The region to be copied to.
- * @return The resulting reference.
- */
- public abstract ObjectReference getReferenceWhenCopiedTo(ObjectReference from, Address to);
-
-
- /**
- * Return the size required to copy an object
- *
- * @param object The object whose size is to be queried
- * @return The size required to copy <code>obj</code>
- */
- public abstract int getSizeWhenCopied(ObjectReference object);
-
- /**
- * Return the alignment requirement for a copy of this object
- *
- * @param object The object whose size is to be queried
- * @return The alignment required for a copy of <code>obj</code>
- */
- public abstract int getAlignWhenCopied(ObjectReference object);
-
- /**
- * Return the alignment offset requirements for a copy of this object
- *
- * @param object The object whose size is to be queried
- * @return The alignment offset required for a copy of <code>obj</code>
- */
- public abstract int getAlignOffsetWhenCopied(ObjectReference object);
-
-
- /**
- * Return the size used by an object
- *
- * @param object The object whose size is to be queried
- * @return The size of <code>obj</code>
- */
- public abstract int getCurrentSize(ObjectReference object);
-
- /**
- * Return the next object in the heap under contiguous allocation
- */
- public abstract ObjectReference getNextObject(ObjectReference object);
-
- /**
- * Return an object reference from knowledge of the low order word
- */
- public abstract ObjectReference getObjectFromStartAddress(Address start);
- /**
- * Gets a pointer to the address just past the end of the object.
- *
- * @param object The objecty.
- */
- public abstract Address getObjectEndAddress(ObjectReference object);
-
-
- /**
- * Get the type descriptor for an object.
- *
- * @param ref address of the object
- * @return byte array with the type descriptor
- */
- public abstract byte[] getTypeDescriptor(ObjectReference ref);
-
- /**
- * Is the passed object an array?
- *
- * @param object address of the object
- */
- public abstract boolean isArray(ObjectReference object);
-
- /**
- * Is the passed object a primitive array?
- *
- * @param object address of the object
- */
- public abstract boolean isPrimitiveArray(ObjectReference object);
-
- /**
- * Get the length of an array object.
- *
- * @param object address of the object
- * @return The array length, in elements
- */
- public abstract int getArrayLength(ObjectReference object);
-
- /**
- * Attempts to set the bits available for memory manager use in an
- * object. The attempt will only be successful if the current value
- * of the bits matches <code>oldVal</code>. The comparison with the
- * current value and setting are atomic with respect to other
- * allocators.
- *
- * @param object the address of the object
- * @param oldVal the required current value of the bits
- * @param newVal the desired new value of the bits
- * @return <code>true</code> if the bits were set,
- * <code>false</code> otherwise
- */
- public abstract boolean attemptAvailableBits(ObjectReference object,
- Word oldVal, Word newVal);
-
- /**
- * Gets the value of bits available for memory manager use in an
- * object, in preparation for setting those bits.
- *
- * @param object the address of the object
- * @return the value of the bits
- */
- public abstract Word prepareAvailableBits(ObjectReference object);
-
- /**
- * Sets the byte available for memory manager use in an object.
- *
- * @param object the address of the object
- * @param val the new value of the byte
- */
- public abstract void writeAvailableByte(ObjectReference object, byte val);
- /**
- * Read the byte available for memory manager use in an object.
- *
- * @param object the address of the object
- * @return the value of the byte
- */
- public abstract byte readAvailableByte(ObjectReference object);
-
- /**
- * Sets the bits available for memory manager use in an object.
- *
- * @param object the address of the object
- * @param val the new value of the bits
- */
- public abstract void writeAvailableBitsWord(ObjectReference object, Word val);
- /**
- * Read the bits available for memory manager use in an object.
- *
- * @param object the address of the object
- * @return the value of the bits
- */
- public abstract Word readAvailableBitsWord(ObjectReference object);
-
- /**
- * Gets the offset of the memory management header from the object
- * reference address. XXX The object model / memory manager
- * interface should be improved so that the memory manager does not
- * need to know this.
- *
- * @return the offset, relative the object reference address
- */
- public abstract Offset GC_HEADER_OFFSET();
-
- /**
- * Returns the lowest address of the storage associated with an object.
- *
- * @param object the reference address of the object
- * @return the lowest address of the object
- */
- public abstract Address objectStartRef(ObjectReference object);
-
- /**
- * Returns an address guaranteed to be inside the storage assocatied
- * with and object.
- *
- * @param object the reference address of the object
- * @return an address inside the object
- */
- public abstract Address refToAddress(ObjectReference object);
-
- /**
- * Checks if a reference of the given type in another object is
- * inherently acyclic. The type is given as a TIB.
- *
- * @return <code>true</code> if a reference of the type is
- * inherently acyclic
- */
- public abstract boolean isAcyclic(ObjectReference typeRef);
-
- /**
- * Dump debugging information for an object.
- *
- * @param object The object whose information is to be dumped
- */
- public abstract void dumpObject(ObjectReference object);
-
- /*
- * NOTE: The following methods must be implemented by subclasses of this
- * class, but are internal to the VM<->MM interface glue, so are never
- * called by MMTk users.
- */
- /** @return The offset from array reference to element zero */
- protected abstract Offset getArrayBaseOffset();
-
- /*
- * NOTE: These methods should not be called by anything other than the
- * reflective mechanisms in org.mmtk.vm.VM, and are not implemented by
- * subclasses.
- *
- * This hack exists only to allow us to declare the respective
- * methods as protected.
- */
- static Offset arrayBaseOffsetTrapdoor(ObjectModel o) {
- return o.getArrayBaseOffset();
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/vm/ReferenceProcessor.java b/vmkit/mmtk/java/src/org/mmtk/vm/ReferenceProcessor.java
deleted file mode 100644
index 5cc255e..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/vm/ReferenceProcessor.java
+++ /dev/null
@@ -1,50 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.vm;
-
-import org.mmtk.plan.TraceLocal;
-import org.vmmagic.pragma.Uninterruptible;
-
-/**
- * This class manages SoftReferences, WeakReferences, and
- * PhantomReferences.
- */
-@Uninterruptible
-public abstract class ReferenceProcessor {
-
- public enum Semantics { SOFT, WEAK, PHANTOM }
-
- /**
- * Clear the contents of the table. This is called when reference types are
- * disabled to make it easier for VMs to change this setting at runtime.
- */
- public abstract void clear();
-
- /**
- * Scan through the list of references.
- *
- * @param trace the thread local trace element.
- * @param nursery true if it is safe to only scan new references.
- */
- public abstract void scan(TraceLocal trace, boolean nursery);
-
- /**
- * Iterate over all references and forward.
- */
- public abstract void forward(TraceLocal trace, boolean nursery);
-
- /**
- * @return the number of references objects on the queue
- */
- public abstract int countWaitingReferences();
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/vm/Scanning.java b/vmkit/mmtk/java/src/org/mmtk/vm/Scanning.java
deleted file mode 100644
index d119db5..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/vm/Scanning.java
+++ /dev/null
@@ -1,137 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.vm;
-
-import org.mmtk.plan.TraceLocal;
-import org.mmtk.plan.TransitiveClosure;
-import org.mmtk.utility.Constants;
-
-import org.vmmagic.pragma.Uninterruptible;
-import org.vmmagic.unboxed.*;
-
-@Uninterruptible public abstract class Scanning implements Constants {
- /**
- * Delegated scanning of a object, processing each pointer field
- * encountered.
- *
- * @param object The object to be scanned.
- */
- public abstract void scanObject(TransitiveClosure trace, ObjectReference object);
-
- /**
- * Invoke a specialized scan method. Note that these methods must have been allocated
- * explicitly through Plan and PlanConstraints.
- *
- * @param id The specialized method id
- * @param trace The trace the method has been specialized for
- * @param object The object to be scanned
- */
- public abstract void specializedScanObject(int id, TransitiveClosure trace, ObjectReference object);
-
- /**
- * Delegated precopying of a object's children, processing each pointer field
- * encountered.
- *
- * @param trace The trace object to use for precopying.
- * @param object The object to be scanned.
- */
- public abstract void precopyChildren(TraceLocal trace, ObjectReference object);
-
- /**
- * Prepares for using the <code>computeAllRoots</code> method. The
- * thread counter allows multiple GC threads to co-operatively
- * iterate through the thread data structure (if load balancing
- * parallel GC threads were not important, the thread counter could
- * simply be replaced by a for loop).
- */
- public abstract void resetThreadCounter();
-
- /**
- * Pre-copy all potentially movable instances used in the course of
- * GC. This includes the thread objects representing the GC threads
- * themselves. It is crucial that these instances are forwarded
- * <i>prior</i> to the GC proper. Since these instances <i>are
- * not</i> enqueued for scanning, it is important that when roots
- * are computed the same instances are explicitly scanned and
- * included in the set of roots. The existence of this method
- * allows the actions of calculating roots and forwarding GC
- * instances to be decoupled.
- */
- public abstract void preCopyGCInstances(TraceLocal trace);
-
- /**
- * Computes static roots. This method establishes all such roots for
- * collection and places them in the root locations queue. This method
- * should not have side effects (such as copying or forwarding of
- * objects). There are a number of important preconditions:
- *
- * <ul>
- * <li> All objects used in the course of GC (such as the GC thread
- * objects) need to be "pre-copied" prior to calling this method.
- * <li> The <code>threadCounter</code> must be reset so that load
- * balancing parallel GC can share the work of scanning threads.
- * </ul>
- *
- * @param trace The trace to use for computing roots.
- */
- public abstract void computeStaticRoots(TraceLocal trace);
-
- /**
- * Computes global roots. This method establishes all such roots for
- * collection and places them in the root locations queue. This method
- * should not have side effects (such as copying or forwarding of
- * objects). There are a number of important preconditions:
- *
- * <ul>
- * <li> All objects used in the course of GC (such as the GC thread
- * objects) need to be "pre-copied" prior to calling this method.
- * <li> The <code>threadCounter</code> must be reset so that load
- * balancing parallel GC can share the work of scanning threads.
- * </ul>
- *
- * @param trace The trace to use for computing roots.
- */
- public abstract void computeGlobalRoots(TraceLocal trace);
-
- /**
- * Computes roots pointed to by threads, their associated registers
- * and stacks. This method places these roots in the root values,
- * root locations and interior root locations queues. This method
- * should not have side effects (such as copying or forwarding of
- * objects). There are a number of important preconditions:
- *
- * <ul>
- * <li> All objects used in the course of GC (such as the GC thread
- * objects) need to be "pre-copied" prior to calling this method.
- * <li> The <code>threadCounter</code> must be reset so that load
- * balancing parallel GC can share the work of scanning threads.
- * </ul>
- *
- * @param trace The trace to use for computing roots.
- */
- public abstract void computeThreadRoots(TraceLocal trace);
-
- /**
- * Compute all roots out of the VM's boot image (if any). This method is a no-op
- * in the case where the VM does not maintain an MMTk-visible Java space. However,
- * when the VM does maintain a space (such as a boot image) which is visible to MMTk,
- * that space could either be scanned by MMTk as part of its transitive closure over
- * the whole heap, or as a (considerable) performance optimization, MMTk could avoid
- * scanning the space if it is aware of all pointers out of that space. This method
- * is used to establish the root set out of the scannable space in the case where
- * such a space exists.
- *
- * @param trace The trace object to use to report root locations.
- */
- public abstract void computeBootImageRoots(TraceLocal trace);
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/vm/Statistics.java b/vmkit/mmtk/java/src/org/mmtk/vm/Statistics.java
deleted file mode 100644
index bb3ae23..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/vm/Statistics.java
+++ /dev/null
@@ -1,68 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.vm;
-
-import org.vmmagic.pragma.Interruptible;
-import org.vmmagic.pragma.Uninterruptible;
-
-
-@Uninterruptible
-public abstract class Statistics {
- /**
- * Returns the number of collections that have occurred.
- *
- * @return The number of collections that have occurred.
- */
- public abstract int getCollectionCount();
-
- /**
- * Read cycle counter
- */
- public abstract long nanoTime();
-
- /**
- * Convert nanoseconds to milliseconds
- */
- public abstract double nanosToMillis(long c);
-
- /**
- * Convert nanoseconds to seconds
- */
- public abstract double nanosToSecs(long c);
-
- /**
- * Convert milliseconds to nanoseconds
- */
- public abstract long millisToNanos(double t);
-
- /**
- * Convert seconds to nanoseconds
- */
- public abstract long secsToNanos(double t);
-
- /**
- * Read the cycle counter
- */
- public abstract long cycles();
-
- /**
- * Initialize performance events
- */
- @Interruptible
- public abstract void perfEventInit(String events);
-
- /**
- * Read a performance event value
- */
- public abstract void perfEventRead(int counter, long[] values);
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/vm/Strings.java b/vmkit/mmtk/java/src/org/mmtk/vm/Strings.java
deleted file mode 100644
index e8fa033..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/vm/Strings.java
+++ /dev/null
@@ -1,51 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.vm;
-
-import org.vmmagic.pragma.Uninterruptible;
-
-
-@Uninterruptible public abstract class Strings {
- /**
- * Log a message.
- *
- * @param c character array with message starting at index 0
- * @param len number of characters in message
- */
- public abstract void write(char [] c, int len);
-
- /**
- * Log a thread identifier and a message.
- *
- * @param c character array with message starting at index 0
- * @param len number of characters in message
- */
- public abstract void writeThreadId(char [] c, int len);
-
- /**
- * Copies characters from the string into the character array.
- * Thread switching is disabled during this method's execution.
- * <p>
- * <b>TODO:</b> There are special memory management semantics here that
- * someone should document.
- *
- * @param src the source string
- * @param dst the destination array
- * @param dstBegin the start offset in the desination array
- * @param dstEnd the index after the last character in the
- * destination to copy to
- * @return the number of characters copied.
- */
- public abstract int copyStringToChars(String src, char [] dst,
- int dstBegin, int dstEnd);
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/vm/SynchronizedCounter.java b/vmkit/mmtk/java/src/org/mmtk/vm/SynchronizedCounter.java
deleted file mode 100644
index ef272a8..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/vm/SynchronizedCounter.java
+++ /dev/null
@@ -1,43 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.vm;
-
-import org.vmmagic.pragma.Uninterruptible;
-
-
-/**
- * A counter that supports atomic increment and reset.
- */
-@Uninterruptible public abstract class SynchronizedCounter {
-
- /**
- * Reset the counter to 0, returning its previous value.
- *
- * @return The value of the counter, prior to reset.
- */
- public abstract int reset();
-
- /**
- * Adds 1 to the counter.
- *
- * @return the value before the add
- */
- public abstract int increment();
-
- /**
- * Peek at the counter
- *
- * @return The current value of the counter.
- */
- public abstract int peek();
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/vm/TraceInterface.java b/vmkit/mmtk/java/src/org/mmtk/vm/TraceInterface.java
deleted file mode 100644
index d6da3cb..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/vm/TraceInterface.java
+++ /dev/null
@@ -1,80 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.vm;
-
-import org.vmmagic.unboxed.*;
-import org.vmmagic.pragma.*;
-
-/**
- * Class that supports scanning Objects or Arrays for references
- * during tracing, handling those references, and computing death times
- */
-@Uninterruptible public abstract class TraceInterface {
-
-
- /***********************************************************************
- *
- * Public Methods
- */
-
- /**
- * Returns if the VM is ready for a garbage collection.
- *
- * @return True if the VM is ready for GC, false otherwise.
- */
- public abstract boolean gcEnabled();
-
- /**
- * This adjusts the offset into an object to reflect what it would look like
- * if the fields were laid out in memory space immediately after the object
- * pointer.
- *
- * @param isScalar If this is a pointer store to a scalar object
- * @param src The address of the source object
- * @param slot The address within <code>src</code> into which
- * the update will be stored
- * @return The easy to understand offset of the slot
- */
- public abstract Offset adjustSlotOffset(boolean isScalar,
- ObjectReference src,
- Address slot);
-
- /**
- * This skips over the frames added by the tracing algorithm, outputs
- * information identifying the method the containts the "new" call triggering
- * the allocation, and returns the address of the first non-trace, non-alloc
- * stack frame.
- *
- *@param typeRef The type reference (tib) of the object just allocated
- * @return The frame pointer address for the method that allocated the object
- */
- @Interruptible
- public abstract Address skipOwnFramesAndDump(ObjectReference typeRef);
-
- /***********************************************************************
- *
- * Wrapper methods
- */
- public abstract void updateDeathTime(ObjectReference obj);
- public abstract void setDeathTime(ObjectReference ref, Word time_);
- public abstract void setLink(ObjectReference ref, ObjectReference link);
- public abstract void updateTime(Word time_);
- public abstract Word getOID(ObjectReference ref);
- public abstract Word getDeathTime(ObjectReference ref);
- public abstract ObjectReference getLink(ObjectReference ref);
- public abstract Address getBootImageLink();
- public abstract Word getOID();
- public abstract void setOID(Word oid);
- public abstract int getHeaderSize();
- public abstract int getHeaderEndOffset();
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/vm/VM.java b/vmkit/mmtk/java/src/org/mmtk/vm/VM.java
deleted file mode 100644
index 025c609..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/vm/VM.java
+++ /dev/null
@@ -1,386 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.vm;
-
-import org.mmtk.utility.options.Options;
-import org.mmtk.utility.gcspy.Color;
-import org.mmtk.utility.gcspy.drivers.AbstractDriver;
-import org.mmtk.vm.gcspy.ByteStream;
-import org.mmtk.vm.gcspy.IntStream;
-import org.mmtk.vm.gcspy.ServerInterpreter;
-import org.mmtk.vm.gcspy.ServerSpace;
-import org.mmtk.vm.gcspy.ShortStream;
-import org.mmtk.vm.gcspy.Util;
-import org.vmmagic.pragma.Untraced;
-import org.vmmagic.unboxed.Address;
-import org.vmmagic.unboxed.Offset;
-
-/**
- * This class is responsible for all VM-specific functionality required
- * by MMTk.<p>
- *
- * The class has three major elements. First it defines VM-specific
- * constants which are used throughout MMTk, second, it declares
- * singleton instances of each of the abstract classes in this
- * package, and third, it provides factory methods for VM-specific
- * instances which are needed by MMTk (such as <code>Lock</code>).<p>
- *
- * Both the constants and the singleton instances are initialized to
- * VM-specific values at build time using reflection and a VM-specific
- * factory class. The system property <code>mmtk.hostjvm</code> is
- * interrogated at build time to establish concrete instantations of
- * the abstract classes in this package. By <b>convention</b>,
- * <code>mmtk.hostjvm</code> will identify a VM-provided package which
- * includes concrete instances of each of the abstract classes, with
- * each concrete class having the same base class name (but different
- * package name) as the abstract classes defined here. The class
- * initializer for this class then uses the system property
- * <code>mmtk.hostjvm</code> to load the VM-specific concrete classes
- * and initialize the constants and singletons defined here.
- */
-public final class VM {
- /*
- * VM-specific constant values
- */
- /** <code>true</code> if assertions should be verified */
- public static final boolean VERIFY_ASSERTIONS;
- /** The lowest address in virtual memory known to MMTk */
- public static final Address HEAP_START;
- /** The highest address in virtual memory known to MMTk */
- public static final Address HEAP_END;
- /** The lowest address in the contiguously available memory available to MMTk */
- public static final Address AVAILABLE_START;
- /** The highest address in the contiguously available memory available to MMTk */
- public static final Address AVAILABLE_END;
- /** The log base two of the size of an address */
- public static final byte LOG_BYTES_IN_ADDRESS;
- /** The log base two of the size of a word */
- public static final byte LOG_BYTES_IN_WORD;
- /** The log base two of the size of an OS page */
- public static final byte LOG_BYTES_IN_PAGE;
- /** The log base two of the minimum allocation alignment */
- public static final byte LOG_MIN_ALIGNMENT;
- /** The log base two of (MAX_ALIGNMENT/MIN_ALIGNMENT) */
- public static final byte MAX_ALIGNMENT_SHIFT;
- /** The maximum number of bytes of padding to prepend to an object */
- public static final int MAX_BYTES_PADDING;
- /** The value to store in alignment holes */
- public static final int ALIGNMENT_VALUE;
- /** The offset from an array reference to element zero */
- public static final Offset ARRAY_BASE_OFFSET;
- /** Global debugging switch */
- public static final boolean DEBUG;
-
- /*
- * VM-specific functionality captured in a series of singleton classs
- */
- @Untraced
- public static final ActivePlan activePlan;
- @Untraced
- public static final Assert assertions;
- @Untraced
- public static final Barriers barriers;
- @Untraced
- public static final Collection collection;
- @Untraced
- public static final Config config;
- @Untraced
- public static final Memory memory;
- @Untraced
- public static final ObjectModel objectModel;
- @Untraced
- public static final ReferenceProcessor weakReferences;
- @Untraced
- public static final ReferenceProcessor softReferences;
- @Untraced
- public static final ReferenceProcessor phantomReferences;
- @Untraced
- public static final FinalizableProcessor finalizableProcessor;
- @Untraced
- public static final Scanning scanning;
- @Untraced
- public static final Statistics statistics;
- @Untraced
- public static final Strings strings;
- @Untraced
- public static final TraceInterface traceInterface;
- @Untraced
- public static final MMTk_Events events;
- @Untraced
- public static final Debug debugging;
-
- /*
- * The remainder is does the static initialization of the
- * above, reflectively binding to the appropriate host jvm
- * classes.
- */
- private static final Factory factory;
- private static final String vmFactory;
-
- /**
- * This class initializer establishes a VM-specific factory class
- * using reflection, and then uses that to create VM-specific concrete
- * instances of all of the vm classes, initializing the singltons in
- * this class. Finally the constants declared in this class are
- * initialized using the VM-specific singletons.
- */
- static {
- /* Identify the VM-specific factory using reflection */
- vmFactory = System.getProperty("mmtk.hostjvm");
- Factory xfa = null;
- try {
- xfa = (Factory) Class.forName(vmFactory).newInstance();
- } catch (Exception e) {
- e.printStackTrace();
- System.exit(-1); // we must *not* go on if the above has failed
- }
- factory = xfa;
-
- /* Now instantiate the singletons using the factory */
- activePlan = factory.newActivePlan();
- assertions = factory.newAssert();
- barriers = factory.newBarriers();
- collection = factory.newCollection();
- memory = factory.newMemory();
- objectModel = factory.newObjectModel();
- Options.set = factory.getOptionSet();
- weakReferences = factory.newReferenceProcessor(ReferenceProcessor.Semantics.WEAK);
- softReferences = factory.newReferenceProcessor(ReferenceProcessor.Semantics.SOFT);
- phantomReferences = factory.newReferenceProcessor(ReferenceProcessor.Semantics.PHANTOM);
- finalizableProcessor = factory.newFinalizableProcessor();
- scanning = factory.newScanning();
- statistics = factory.newStatistics();
- strings = factory.newStrings();
- traceInterface = factory.newTraceInterface();
- events = factory.newEvents();
- debugging = factory.newDebug();
- config = new Config(factory.newBuildTimeConfig());
-
- /* Now initialize the constants using the vm-specific singletons */
- VERIFY_ASSERTIONS = Assert.verifyAssertionsTrapdoor(assertions);
- HEAP_START = Memory.heapStartTrapdoor(memory);
- HEAP_END = Memory.heapEndTrapdoor(memory);
- AVAILABLE_START = Memory.availableStartTrapdoor(memory);
- AVAILABLE_END = Memory.availableEndTrapdoor(memory);
- LOG_BYTES_IN_ADDRESS = Memory.logBytesInAddressTrapdoor(memory);
- LOG_BYTES_IN_WORD = Memory.logBytesInWordTrapdoor(memory);
- LOG_BYTES_IN_PAGE = Memory.logBytesInPageTrapdoor(memory);
- LOG_MIN_ALIGNMENT = Memory.logMinAlignmentTrapdoor(memory);
- MAX_ALIGNMENT_SHIFT = Memory.maxAlignmentShiftTrapdoor(memory);
- MAX_BYTES_PADDING = Memory.maxBytesPaddingTrapdoor(memory);
- ALIGNMENT_VALUE = Memory.alignmentValueTrapdoor(memory);
- ARRAY_BASE_OFFSET = ObjectModel.arrayBaseOffsetTrapdoor(objectModel);
- DEBUG = Debug.isEnabledTrapdoor(debugging);
- }
-
- /**
- * Create a new Lock instance using the appropriate VM-specific
- * concrete Lock sub-class.
- *
- * @see Lock
- *
- * @param name The string to be associated with this lock instance
- * @return A concrete VM-specific Lock instance.
- */
- public static Lock newLock(String name) {
- return factory.newLock(name);
- }
-
- /**
- * Create a new SynchronizedCounter instance using the appropriate
- * VM-specific concrete SynchronizedCounter sub-class.
- *
- * @see SynchronizedCounter
- *
- * @return A concrete VM-specific SynchronizedCounter instance.
- */
- public static SynchronizedCounter newSynchronizedCounter() {
- return factory.newSynchronizedCounter();
- }
-
- /**********************************************************************
- * GCspy methods
- */
-
- /**
- * Create a new Util instance using the appropriate
- * VM-specific concrete Util sub-class.
- *
- * @see Util
- *
- * @return A concrete VM-specific Util instance.
- */
- public static Util newGCspyUtil() {
- return factory.newGCspyUtil();
- }
-
- /**
- * Create a new ServerInterpreter instance using the appropriate
- * VM-specific concrete ServerInterpreter sub-class.
- *
- * @see ServerInterpreter
- *
- * @return A concrete VM-specific ServerInterpreter instance.
- */
- public static ServerInterpreter newGCspyServerInterpreter() {
- return factory.newGCspyServerInterpreter();
- }
-
- /**
- * Create a new ServerInterpreter instance using the appropriate
- * VM-specific concrete ServerInterpreter sub-class.
- *
- * @see ServerInterpreter
- *
- * @return A concrete VM-specific ServerInterpreter instance.
- */
- public static ServerSpace newGCspyServerSpace(
- ServerInterpreter serverInterpreter,
- String serverName,
- String driverName,
- String title,
- String blockInfo,
- int tileNum,
- String unused,
- boolean mainSpace) {
- return factory.newGCspyServerSpace(serverInterpreter, serverName, driverName,
- title, blockInfo, tileNum, unused,
- mainSpace);
- }
-
- /**
- * Create a new ByteStream instance using the appropriate
- * VM-specific concrete ByteStream sub-class.
- *
- * @param driver The driver that owns this Stream
- * @param name The name of the stream (e.g. "Used space")
- * @param minValue The minimum value for any item in this stream.
- * Values less than this will be represented as "minValue-"
- * @param maxValue The maximum value for any item in this stream.
- * Values greater than this will be represented as "maxValue+"
- * @param zeroValue The zero value for this stream
- * @param defaultValue The default value for this stream
- * @param stringPre A string to prefix values (e.g. "Used: ")
- * @param stringPost A string to suffix values (e.g. " bytes.")
- * @param presentation How a stream value is to be presented.
- * @param paintStyle How the value is to be painted.
- * @param indexMaxStream The index of the maximum stream if the presentation is *_VAR.
- * @param colour The default colour for tiles of this stream
- * @see IntStream
- *
- * @return A concrete VM-specific ByteStream instance.
- */
- public static ByteStream newGCspyByteStream(
- AbstractDriver driver,
- String name,
- byte minValue,
- byte maxValue,
- byte zeroValue,
- byte defaultValue,
- String stringPre,
- String stringPost,
- int presentation,
- int paintStyle,
- int indexMaxStream,
- Color colour,
- boolean summary) {
- return factory.newGCspyByteStream(driver, name, minValue, maxValue,
- zeroValue, defaultValue, stringPre, stringPost,
- presentation, paintStyle, indexMaxStream,
- colour, summary);
- }
-
- /**
- * Create a new IntStream instance using the appropriate
- * VM-specific concrete IntStream sub-class.
- *
- * @param driver The driver that owns this Stream
- * @param name The name of the stream (e.g. "Used space")
- * @param minValue The minimum value for any item in this stream.
- * Values less than this will be represented as "minValue-"
- * @param maxValue The maximum value for any item in this stream.
- * Values greater than this will be represented as "maxValue+"
- * @param zeroValue The zero value for this stream
- * @param defaultValue The default value for this stream
- * @param stringPre A string to prefix values (e.g. "Used: ")
- * @param stringPost A string to suffix values (e.g. " bytes.")
- * @param presentation How a stream value is to be presented.
- * @param paintStyle How the value is to be painted.
- * @param indexMaxStream The index of the maximum stream if the presentation is *_VAR.
- * @param colour The default colour for tiles of this stream
- * @see IntStream
- *
- * @return A concrete VM-specific IntStream instance.
- */
- public static IntStream newGCspyIntStream(
- AbstractDriver driver,
- String name,
- int minValue,
- int maxValue,
- int zeroValue,
- int defaultValue,
- String stringPre,
- String stringPost,
- int presentation,
- int paintStyle,
- int indexMaxStream,
- Color colour,
- boolean summary) {
- return factory.newGCspyIntStream(driver, name, minValue, maxValue,
- zeroValue, defaultValue, stringPre, stringPost,
- presentation, paintStyle, indexMaxStream,
- colour, summary);
- }
-
- /**
- * Create a new ShortStream instance using the appropriate
- * VM-specific concrete ShortStream sub-class.
- *
- * @param driver The driver that owns this Stream
- * @param name The name of the stream (e.g. "Used space")
- * @param minValue The minimum value for any item in this stream.
- * Values less than this will be represented as "minValue-"
- * @param maxValue The maximum value for any item in this stream.
- * Values greater than this will be represented as "maxValue+"
- * @param zeroValue The zero value for this stream
- * @param defaultValue The default value for this stream
- * @param stringPre A string to prefix values (e.g. "Used: ")
- * @param stringPost A string to suffix values (e.g. " bytes.")
- * @param presentation How a stream value is to be presented.
- * @param paintStyle How the value is to be painted.
- * @param indexMaxStream The index of the maximum stream if the presentation is *_VAR.
- * @param colour The default colour for tiles of this stream
- * @see IntStream
- *
- * @return A concrete VM-specific IntStream instance.
- */
- public static ShortStream newGCspyShortStream(
- AbstractDriver driver,
- String name,
- short minValue,
- short maxValue,
- short zeroValue,
- short defaultValue,
- String stringPre,
- String stringPost,
- int presentation,
- int paintStyle,
- int indexMaxStream,
- Color colour,
- boolean summary) {
- return factory.newGCspyShortStream(driver, name, minValue, maxValue,
- zeroValue, defaultValue, stringPre, stringPost,
- presentation, paintStyle, indexMaxStream,
- colour, summary);
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/vm/gcspy/ByteStream.java b/vmkit/mmtk/java/src/org/mmtk/vm/gcspy/ByteStream.java
deleted file mode 100644
index 992b32d..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/vm/gcspy/ByteStream.java
+++ /dev/null
@@ -1,147 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.vm.gcspy;
-
-import org.mmtk.utility.Log;
-import org.mmtk.utility.gcspy.Color;
-import org.mmtk.utility.gcspy.GCspy;
-import org.mmtk.utility.gcspy.StreamConstants;
-import org.mmtk.utility.gcspy.drivers.AbstractDriver;
-import org.mmtk.vm.VM;
-import org.vmmagic.pragma.*;
-
-/**
- * Set up a GCspy Stream with data type BYTE_TYPE
- */
-
-@Uninterruptible public abstract class ByteStream extends Stream {
-
- /****************************************************************************
- *
- * Instance variables
- */
- private byte[] data; // The stream data
- private byte defaultValue; // The default value for the data items
-
-
- /****************************************************************************
- *
- * Initialization
- */
-
- /**
- * Construct a new GCspy stream of BYTE_TYPE
- * @param driver The driver that owns this Stream
- * @param name The name of the stream (e.g. "Used space")
- * @param minValue The minimum value for any item in this stream.
- * Values less than this will be represented as "minValue-"
- * @param maxValue The maximum value for any item in this stream.
- * Values greater than this will be represented as "maxValue+"
- * @param zeroValue The zero value for this stream
- * @param defaultValue The default value for this stream
- * @param stringPre A string to prefix values (e.g. "Used: ")
- * @param stringPost A string to suffix values (e.g. " bytes.")
- * @param presentation How a stream value is to be presented.
- * @param paintStyle How the value is to be painted.
- * @param indexMaxStream The index of the maximum stream if the presentation is *_VAR.
- * @param colour The default colour for tiles of this stream
- */
- public ByteStream(
- AbstractDriver driver,
- String name,
- byte minValue,
- byte maxValue,
- byte zeroValue,
- byte defaultValue,
- String stringPre,
- String stringPost,
- int presentation,
- int paintStyle,
- int indexMaxStream,
- Color colour,
- boolean summary) {
-
- super(driver, StreamConstants.BYTE_TYPE, name,
- minValue, maxValue, zeroValue, defaultValue,
- stringPre, stringPost, presentation, paintStyle,
- indexMaxStream, colour, summary);
-
- data = (byte[])GCspy.util.createDataArray(new byte[0], driver.getMaxTileNum());
- this.defaultValue = defaultValue;
- }
-
- /**
- * Reset all data in this stream to default values.
- */
- public void resetData() {
- for (int i = 0; i < data.length; i++)
- data[i] = defaultValue;
- }
-
-
- /**
- * Distribute a value across a sequence of tiles. This handles the case
- * when when an object spans two or more tiles and its value is to be
- * attributed to each tile proportionally.
- *
- * @param start the index of the starting tile
- * @param remainder the value left in the starting tile
- * @param blockSize the size of each tile
- * @param value the value to distribute
- */
- public void distribute(int start, byte remainder, int blockSize, byte value) {
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(remainder <= blockSize);
- if (value <= remainder) { // fits in this tile
- data[start] += value;
- //checkspace(start, value, "scanObject fits in first tile");
- } else {
- data[start] += remainder;
- //checkspace(start, remainder, "scanObject remainder put in first tile");
- value -= remainder;
- start++;
- while (value >= blockSize) {
- data[start] += blockSize;
- //checkspace(start, blockSize, "scanObject subsequent tile");
- value -= blockSize;
- start++;
- }
- data[start] += value;
- //checkspace(start, value, "scanObject last tile");
- }
- }
-
- /**
- * Increment the value of a tile.
- * @param index the index
- * @param value the increment
- */
- public void increment(int index, byte value) { data[index] += value; }
-
- /**
- * Send the data and summary for this stream.
- * @param event The event
- * @param numTiles The number of tiles to send (which may be less than maxTileNum)
- * @see #ByteStream
- */
- public void send(int event, int numTiles) {
- if (DEBUG) {
- Log.write("sending "); Log.write(numTiles); Log.writeln(" int values");
- }
- serverSpace.stream(streamId, numTiles);
- for (int index = 0; index < numTiles; index++)
- serverSpace.streamByteValue(data[index]);
- serverSpace.streamEnd();
- sendSummary();
- }
-}
-
diff --git a/vmkit/mmtk/java/src/org/mmtk/vm/gcspy/IntStream.java b/vmkit/mmtk/java/src/org/mmtk/vm/gcspy/IntStream.java
deleted file mode 100644
index f25fe42..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/vm/gcspy/IntStream.java
+++ /dev/null
@@ -1,147 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.vm.gcspy;
-
-import org.mmtk.utility.Log;
-import org.mmtk.utility.gcspy.Color;
-import org.mmtk.utility.gcspy.GCspy;
-import org.mmtk.utility.gcspy.StreamConstants;
-import org.mmtk.utility.gcspy.drivers.AbstractDriver;
-import org.mmtk.vm.VM;
-import org.vmmagic.pragma.*;
-
-/**
- * Set up a GCspy Stream with data type INT_TYPE.
- */
-@Uninterruptible public abstract class IntStream extends Stream {
-
- /****************************************************************************
- *
- * Instance variables
- */
- private int[] data; // The stream data
- private int defaultValue; // The default value for the data items
-
-
- /****************************************************************************
- *
- * Initialization
- */
-
- /**
- * Construct a new GCspy stream of INT_TYPE
- * @param driver The driver that owns this Stream
- * @param name The name of the stream (e.g. "Used space")
- * @param minValue The minimum value for any item in this stream.
- * Values less than this will be represented as "minValue-"
- * @param maxValue The maximum value for any item in this stream.
- * Values greater than this will be represented as "maxValue+"
- * @param zeroValue The zero value for this stream
- * @param defaultValue The default value for this stream
- * @param stringPre A string to prefix values (e.g. "Used: ")
- * @param stringPost A string to suffix values (e.g. " bytes.")
- * @param presentation How a stream value is to be presented.
- * @param paintStyle How the value is to be painted.
- * @param indexMaxStream The index of the maximum stream if the presentation is *_VAR.
- * @param colour The default colour for tiles of this stream
- */
- public IntStream(
- AbstractDriver driver,
- String name,
- int minValue,
- int maxValue,
- int zeroValue,
- int defaultValue,
- String stringPre,
- String stringPost,
- int presentation,
- int paintStyle,
- int indexMaxStream,
- Color colour,
- boolean summary) {
-
- super(driver, StreamConstants.INT_TYPE, name,
- minValue, maxValue, zeroValue, defaultValue,
- stringPre, stringPost, presentation, paintStyle,
- indexMaxStream, colour, summary);
-
- data = (int[])GCspy.util.createDataArray(new int[0], driver.getMaxTileNum());
- this.defaultValue = defaultValue;
- }
-
- /**
- * Reset all data in this stream to default values.
- */
- public void resetData() {
- for (int i = 0; i < data.length; i++)
- data[i] = defaultValue;
- }
-
-
- /**
- * Distribute a value across a sequence of tiles. This handles the case
- * when when an object spans two or more tiles and its value is to be
- * attributed to each tile proportionally.
- *
- * @param start the index of the starting tile
- * @param remainder the value left in the starting tile
- * @param blockSize the size of each tile
- * @param value the value to distribute
- */
- public void distribute(int start, int remainder, int blockSize, int value) {
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(remainder <= blockSize);
- if (value <= remainder) { // fits in this tile
- data[start] += value;
- //checkspace(start, value, "scanObject fits in first tile");
- } else {
- data[start] += remainder;
- //checkspace(start, remainder, "scanObject remainder put in first tile");
- value -= remainder;
- start++;
- while (value >= blockSize) {
- data[start] += blockSize;
- //checkspace(start, blockSize, "scanObject subsequent tile");
- value -= blockSize;
- start++;
- }
- data[start] += value;
- //checkspace(start, value, "scanObject last tile");
- }
- }
-
- /**
- * Increment the value of a tile.
- * @param index the index
- * @param value the increment
- */
- public void increment(int index, int value) { data[index] += value; }
-
- /**
- * Send the data and summary for this stream.
- * @param event The event
- * @param numTiles The number of tiles to send (which may be less than maxTileNum)
- */
- public void send(int event, int numTiles) {
- if (DEBUG) {
- Log.write("sending "); Log.write(numTiles); Log.writeln(" int values");
- }
-
- serverSpace.stream(streamId, numTiles);
- for (int index = 0; index < numTiles; index++)
- serverSpace.streamIntValue(data[index]);
- serverSpace.streamEnd();
-
- sendSummary();
- }
-}
-
diff --git a/vmkit/mmtk/java/src/org/mmtk/vm/gcspy/ServerInterpreter.java b/vmkit/mmtk/java/src/org/mmtk/vm/gcspy/ServerInterpreter.java
deleted file mode 100644
index 79bf7e1..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/vm/gcspy/ServerInterpreter.java
+++ /dev/null
@@ -1,124 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.vm.gcspy;
-
-import org.vmmagic.pragma.*;
-import org.vmmagic.unboxed.Address;
-
-/**
- * Abstract class for the GCspy server interpreter
- *
- * Implementing classes will mostly forward calls to the C gcspy library.
- */
-@Uninterruptible public abstract class ServerInterpreter {
-
- protected static final int MAX_LEN = 64 * 1024; // Buffer size
- protected static final int MAX_SPACES = 32; // Maximum number of spaces
- protected static boolean initialised = false;
-
- protected ServerSpace[] spaces; // The server's spaces
- protected Address server; // a pointer to the c server, gcspy_main_server_t server
-
- protected static final boolean DEBUG = false;
-
- /**
- * Create a new ServerInterpreter singleton.
- * @param name The name of the server
- * @param port The number of the port on which to communicate
- * @param verbose Whether the server is to run verbosely
- */
- @Interruptible
- public abstract void init(String name, int port, boolean verbose);
-
- /**
- * Add an event to the ServerInterpreter.
- * @param num the event number
- * @param name the event name
- */
- public abstract void addEvent(int num, String name);
-
- /**
- * Set the general info for the ServerInterpreter.
- * @param info the information
- */
- public abstract void setGeneralInfo(String info);
-
- /**
- * Get a pointer to the C server, gcspy_main_server_t.
- * This address is used in alll calls to the server in the C library.
- * @return the address of the server
- */
- public Address getServerAddress() { return server; }
-
- /**
- * Add a GCspy ServerSpace to the ServerInterpreter.
- * This method returns a unique space ID for the ServerSpace
- * (again used in calls to the C library).
- *
- * @param space the ServerSpace to add
- * @return a unique id for this space
- * @exception IndexOutOfBoundsException on attempt to add more than
- * MAX_SPACES spaces
- */
- @Interruptible
- public int addSpace(ServerSpace space) {
- int id = 0;
- while (id < MAX_SPACES) {
- if (spaces[id] == null) {
- spaces[id] = space;
- return id;
- }
- id++;
- }
- throw new IndexOutOfBoundsException(
- "Too many spaces to add to interpreter.\nSet MAX_SPACES to higher value in ServerInterpreter.");
- }
-
- /**
- * Start the server, running its main loop in a pthread.
- * @param wait Whether to wait for the client to connect
- */
- public abstract void startServer(boolean wait);
-
- /**
- * Are we connected to a GCspy client?
- * @param event The current event
- * @return true if we are connected
- */
- public abstract boolean isConnected(int event);
-
- /**
- * Start compensation timer so that time spent gathering data is
- * not confused with the time spent in the application and the VM.
- */
- public abstract void startCompensationTimer();
-
- /**
- * Stop compensation timer so that time spent gathering data is
- * not confused with the time spent in the application and the VM.r
- */
- public abstract void stopCompensationTimer();
-
- /**
- * Indicate that we are at a server safe point (e.g. the end of a GC).
- * This is a point at which the server can pause, play one, etc.
- * @param event The current event
- */
- public abstract void serverSafepoint(int event);
-
- /**
- * Discover the smallest header size for objects.
- * @return the size in bytes
- */
- public abstract int computeHeaderSize();
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/vm/gcspy/ServerSpace.java b/vmkit/mmtk/java/src/org/mmtk/vm/gcspy/ServerSpace.java
deleted file mode 100644
index 3317f81..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/vm/gcspy/ServerSpace.java
+++ /dev/null
@@ -1,160 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.vm.gcspy;
-
-import org.mmtk.utility.Log;
-import org.mmtk.utility.gcspy.drivers.AbstractDriver;
-import org.vmmagic.unboxed.*;
-import org.vmmagic.pragma.*;
-
-/**
- * Abstract class for the GCspy Space abstraction.
- *
- * Implementing classes will largely forward calls to the gcspy C library.
- */
-@Uninterruptible public abstract class ServerSpace {
-
- /****************************************************************************
- *
- * Class variables
- */
- protected static final String DEFAULT_UNUSED_STRING = "NOT USED"; // The "unused" string
-
- /****************************************************************************
- *
- * Instance variables
- */
- protected int spaceId; // the space's ID
- protected Address driver; // a pointer to the C driver, gcspy_gc_drivert *driver;
- protected static final boolean DEBUG = false;
-
-
- /**
- * Get a pointer to the native driver
- * @return The address of the C driver, gcspy_gc_drivert *, used in all calls
- * to the C library.
- */
- Address getDriverAddress() {
- return driver;
- }
-
- /**
- * Tell the native driver the tile name.
- * @param i the number of the tile
- * @param start the starting address of the tile
- * @param end the end address
- */
- public abstract void setTilename(int i, Address start, Address end);
-
- /**
- * Tell the native driver the tile name.
- * @param i the number of the tile
- * @param format the name of the tile, a format string
- * @param value The value for the format string
- */
- public abstract void setTilename(int i, Address format, long value);
-
- /**
- * Tell the native driver the tile names.
- * @param i the number of the tile
- * @param format The name, including format tags
- * @param value The value for the format string
- */
- public abstract void setTilename(int i, String format, long value);
-
- /**
- * Tell the C driver to resize
- * @param size the new driver size
- */
- public abstract void resize(int size);
-
- /**
- * Start a transmission
- */
- public abstract void startCommunication();
-
- /**
- * Add a stream to the native driver
- * @param id the stream's ID
- * @return the address of the C gcspy_gc_stream_t
- */
- public abstract Address addStream(int id);
-
- /**
- * Start transmitting a stream.
- * @param id The stream's ID
- * @param len The number of items in the stream
- */
- public abstract void stream(int id, int len);
-
- /**
- * Send a byte
- * @param value The byte
- */
- public abstract void streamByteValue(byte value);
-
- /**
- * Send a short
- * @param value The short
- */
- public abstract void streamShortValue(short value);
-
- /**
- * Send an int
- * @param value The int
- */
- public abstract void streamIntValue(int value);
-
- /**
- * End of this stream
- */
- public abstract void streamEnd();
-
- /**
- * Start to send a summary
- * @param id The stream's ID
- * @param len The number of items to be sent
- */
- public abstract void summary(int id, int len);
-
- /**
- * Send a summary value
- * @param val The value
- */
- public abstract void summaryValue(int val);
-
- /**
- * End the summary
- */
- public abstract void summaryEnd();
-
- /**
- * Send all the control info for the space
- * @param space The GCspy driver for this space
- * @param tileNum The number of tiles
- */
- public abstract void sendControls(AbstractDriver space, int tileNum);
-
- /**
- * Send info for this space
- * @param info A pointer to the information (held as C string)
- */
- public abstract void spaceInfo(Address info);
-
- /**
- * End the transmission (for this event)
- */
- public void endCommunication() {
- if (DEBUG) Log.write("endComm\n");
- }
-}
diff --git a/vmkit/mmtk/java/src/org/mmtk/vm/gcspy/ShortStream.java b/vmkit/mmtk/java/src/org/mmtk/vm/gcspy/ShortStream.java
deleted file mode 100644
index 0853891..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/vm/gcspy/ShortStream.java
+++ /dev/null
@@ -1,146 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.vm.gcspy;
-
-import org.mmtk.utility.Log;
-import org.mmtk.utility.gcspy.Color;
-import org.mmtk.utility.gcspy.GCspy;
-import org.mmtk.utility.gcspy.StreamConstants;
-import org.mmtk.utility.gcspy.drivers.AbstractDriver;
-import org.mmtk.vm.VM;
-import org.vmmagic.pragma.*;
-
-/**
- * Set up a GCspy Stream with data type SHORT_TYPE.
- */
-@Uninterruptible public abstract class ShortStream extends Stream {
-
- /****************************************************************************
- *
- * Instance variables
- */
- private short[] data; // The stream data
- private short defaultValue; // The default value for the data items
-
- /****************************************************************************
- *
- * Initialization
- */
-
- /**
- * Construct a new GCspy stream of SHORT_TYPE
- * @param driver The driver that owns this Stream
- * @param name The name of the stream (e.g. "Used space")
- * @param minValue The minimum value for any item in this stream.
- * Values less than this will be represented as "minValue-"
- * @param maxValue The maximum value for any item in this stream.
- * Values greater than this will be represented as "maxValue+"
- * @param zeroValue The zero value for this stream
- * @param defaultValue The default value for this stream
- * @param stringPre A string to prefix values (e.g. "Used: ")
- * @param stringPost A string to suffix values (e.g. " bytes.")
- * @param presentation How a stream value is to be presented.
- * @param paintStyle How the value is to be painted.
- * @param indexMaxStream The index of the maximum stream if the presentation is *_VAR.
- * @param colour The default colour for tiles of this stream
- */
- public ShortStream(
- AbstractDriver driver,
- String name,
- short minValue,
- short maxValue,
- short zeroValue,
- short defaultValue,
- String stringPre,
- String stringPost,
- int presentation,
- int paintStyle,
- int indexMaxStream,
- Color colour,
- boolean summary) {
-
- super(driver, StreamConstants.SHORT_TYPE, name,
- minValue, maxValue, zeroValue, defaultValue,
- stringPre, stringPost, presentation, paintStyle,
- indexMaxStream, colour, summary);
-
- data = (short[])GCspy.util.createDataArray(new short[0], driver.getMaxTileNum());
- this.defaultValue = defaultValue;
- }
-
- /**
- * Reset all data in this stream to default values.
- */
- public void resetData() {
- for (int i = 0; i < data.length; i++)
- data[i] = defaultValue;
- }
-
-
- /**
- * Distribute a value across a sequence of tiles. This handles the case
- * when when an object spans two or more tiles and its value is to be
- * attributed to each tile proportionally.
- *
- * @param start the index of the starting tile
- * @param remainder the value left in the starting tile
- * @param blockSize the size of each tile
- * @param value the value to distribute
- */
- public void distribute(int start, short remainder, int blockSize, short value) {
- if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(remainder <= blockSize);
- if (value <= remainder) { // fits in this tile
- data[start] += value;
- //checkspace(start, value, "scanObject fits in first tile");
- } else {
- data[start] += remainder;
- //checkspace(start, remainder, "scanObject remainder put in first tile");
- value -= remainder;
- start++;
- while (value >= blockSize) {
- data[start] += blockSize;
- //checkspace(start, blockSize, "scanObject subsequent tile");
- value -= blockSize;
- start++;
- }
- data[start] += value;
- //checkspace(start, value, "scanObject last tile");
- }
- }
-
- /**
- * Increment the value of a tile.
- * @param index the index
- * @param value the increment
- */
- public void increment(int index, short value) { data[index] += value; }
-
- /**
- * Send the data and summary for this stream.
- * @param event The event
- * @param numTiles The number of tiles to send (which may be less than maxTileNum)
- */
- public void send(int event, int numTiles) {
- if (DEBUG) {
- Log.write("sending "); Log.write(numTiles); Log.writeln(" int values");
- }
- serverSpace.stream(streamId, numTiles);
- for (int index = 0; index < numTiles; index++)
- serverSpace.streamShortValue(data[index]);
- serverSpace.streamEnd();
-
- // send the summary
- sendSummary();
- }
-}
-
diff --git a/vmkit/mmtk/java/src/org/mmtk/vm/gcspy/Stream.java b/vmkit/mmtk/java/src/org/mmtk/vm/gcspy/Stream.java
deleted file mode 100644
index cfeb0b7..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/vm/gcspy/Stream.java
+++ /dev/null
@@ -1,217 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.vm.gcspy;
-
-import org.mmtk.utility.Log;
-import org.mmtk.utility.gcspy.Color;
-import org.mmtk.utility.gcspy.StreamConstants;
-import org.mmtk.utility.gcspy.drivers.AbstractDriver;
-import org.mmtk.vm.VM;
-import org.vmmagic.pragma.*;
-import org.vmmagic.unboxed.Address;
-
-/**
- *
- * Abstract class for a GCspy Stream.
- * Implementing classes will mostly forward calls
- * to the gcspy C library
- */
-
-@Uninterruptible public abstract class Stream {
-
- /****************************************************************************
- *
- * Instance variables
- */
-
- /**
- * The address of the C stream, gcspy_gc_stream_t *stream, used in all calls
- * to the C library
- */
- protected Address stream;
-
- /** The owning GCspy space */
- protected ServerSpace serverSpace;
-
- /** The stream's ID */
- protected int streamId;
-
- /**
- * A summary has 1 or 2 values depending on presentation style
- * (PERCENT* styles require 2 values).
- */
- protected int summaryLen;
-
- /** The first summary value */
- protected int summary0;
-
- /** The second summary value (if any) */
- protected int summary1;
-
- private int min; // The minimum value for tiles
-
- private int max; // The maximum value for tiles
-
- /** use summaries? */
- protected boolean summaryEnabled;
-
- /** the presentation style */
- protected int presentation;
-
- protected static final boolean DEBUG = false;
-
- /**
- * Construct a new GCspy stream.
- *
- * @param driver The AbstractDriver that owns this Stream
- * @param dataType The stream's data type, one of BYTE_TYPE, SHORT_TYPE or INT_TYPE
- * @param name The name of the stream (e.g. "Used space")
- * @param minValue The minimum value for any item in this stream. Values less than
- * this will be represented as "minValue-"
- * @param maxValue The maximum value for any item in this stream. Values greater than
- * this will be represented as "maxValue+"
- * @param zeroValue The zero value for this stream
- * @param defaultValue The default value for this stream
- * @param stringPre A string to prefix values (e.g. "Used: ")
- * @param stringPost A string to suffix values (e.g. " bytes.")
- * @param presentation How a stream value is to be presented.
- * @param paintStyle How the value is to be painted.
- * @param indexMaxStream The index for the maximum stream if the presentation is *_VAR.
- * @param colour The default colour for tiles of this stream
- * @param summary Is a summary enabled?
- */
- protected Stream(
- AbstractDriver driver,
- int dataType,
- String name,
- int minValue,
- int maxValue,
- int zeroValue,
- int defaultValue,
- String stringPre,
- String stringPost,
- int presentation,
- int paintStyle,
- int indexMaxStream,
- Color colour,
- boolean summary) {
-
- serverSpace = driver.getServerSpace();
- summaryEnabled = summary;
- this.presentation = presentation;
- if (summary)
- setupSummary(presentation);
- min = minValue;
- max = maxValue;
-
- driver.addStream(this);
- if (DEBUG) {
- Log.write("Adding stream ");
- Log.write(name);
- Log.writeln(" id=", streamId);
- }
- }
-
-
- /**
- * Set the stream address and id (called by AbstractDriver.addStream).
- * @param id the id
- * @param str the address of the gcspy C gcspy_gc_stream_t *stream
- */
- public void setStream(int id, Address str) {
- streamId = id;
- stream = str;
- }
-
- /**
- * Return the minimum value expected for this stream.
- * @return the minimum value
- */
- public int getMinValue() { return min; }
-
- /**
- * Return the maximum value expected for this stream.
- * @return the maximum value
- */
- public int getMaxValue() { return max; }
-
- /**
- * Setup the summary array.
- * @param presentation the presentation style
- */
- @Interruptible
- private void setupSummary(int presentation) {
- switch (presentation) {
- case StreamConstants.PRESENTATION_PLAIN:
- case StreamConstants.PRESENTATION_PLUS:
- case StreamConstants.PRESENTATION_MAX_VAR:
- case StreamConstants.PRESENTATION_ENUM:
- summaryLen = 1;
- break;
- case StreamConstants.PRESENTATION_PERCENT:
- case StreamConstants.PRESENTATION_PERCENT_VAR:
- summaryLen = 2;
- break;
- default:
- VM.assertions._assert(false);
- }
- }
-
- /**
- * Set the summary value for presentation styles with just one value
- * @param value0 the value
- */
- public void setSummary(int value0) {
- if (VM.VERIFY_ASSERTIONS)
- VM.assertions._assert(presentation != StreamConstants.PRESENTATION_PERCENT &&
- presentation != StreamConstants.PRESENTATION_PERCENT_VAR);
- summary0 = value0;
- }
-
- /**
- * Set the summary values for presentation styles with two values (i.e.
- * PRESENTATION_PERCENT and PRESENTATION_PERCENT_VAR).
- * @param value0 the numerator value
- * @param value1 the denominator value
- */
- public void setSummary(int value0, int value1) {
- if (VM.VERIFY_ASSERTIONS)
- VM.assertions._assert(presentation == StreamConstants.PRESENTATION_PERCENT ||
- presentation == StreamConstants.PRESENTATION_PERCENT_VAR);
- summary0 = value0;
- summary1 = value1;
- }
-
- /**
- * Send the data for this stream.
- * @param event the event.
- * @param numTiles the number of tiles to send.
- */
- public abstract void send(int event, int numTiles);
-
- /**
- * Send the summary data for this stream.
- */
- public void sendSummary() {
- if (summaryEnabled) {
- serverSpace.summary(streamId, summaryLen);
- serverSpace.summaryValue(summary0);
- if (summaryLen == 2)
- serverSpace.summaryValue(summary1);
- serverSpace.summaryEnd();
- }
- }
-
-}
-
-
diff --git a/vmkit/mmtk/java/src/org/mmtk/vm/gcspy/Util.java b/vmkit/mmtk/java/src/org/mmtk/vm/gcspy/Util.java
deleted file mode 100644
index efcc489..0000000
--- a/vmkit/mmtk/java/src/org/mmtk/vm/gcspy/Util.java
+++ /dev/null
@@ -1,166 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Eclipse Public License (EPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/eclipse-1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.mmtk.vm.gcspy;
-
-import org.mmtk.utility.Log;
-import org.vmmagic.unboxed.*;
-import org.vmmagic.pragma.*;
-
-/**
- * Abstract class that provides generally useful
- * methods.
- */
-@Uninterruptible public abstract class Util {
-
- /**
- * Allocate an array of bytes with malloc
- *
- * @param size The size to allocate
- * @return The start address of the memory allocated in C space
- * @see #free
- */
- public abstract Address malloc(int size);
-
- /**
- * Free an array of bytes previously allocated with malloc
- *
- * @param addr The address of some memory previously allocated with malloc
- * @see #malloc
- */
- public abstract void free(Address addr);
-
- /**
- * Dump a range in format [start,end)
- *
- * @param start The start of the range
- * @param end The end of the range
- */
- public static void dumpRange(Address start, Address end) {
- Log.write("["); Log.write(start);
- Log.write(","); Log.write(end);
- Log.write(')');
- }
-
- /**
- * Convert a String to a 0-terminated array of bytes
- *
- * @param str The string to convert
- * @return The address of a null-terminated array in C-space
- */
- public abstract Address getBytes(String str);
-
- /**
- * Pretty print a size, converting from bytes to kilo- or mega-bytes as appropriate
- *
- * @param buffer The buffer (in C space) in which to place the formatted size
- * @param size The size in bytes
- */
- public abstract void formatSize(Address buffer, int size);
-
- /**
- * Pretty print a size, converting from bytes to kilo- or mega-bytes as appropriate
- *
- * @param format A format string
- * @param bufsize The size of a buffer large enough to hold the formatted result
- * @param size The size in bytes
- */
- public abstract Address formatSize(String format, int bufsize, int size);
-
-// public abstract Address formatSize(String format, int bufsize, int size);
-
- /**
- * Place a string representation of a long in an array of bytes
- * without incurring allocation
- *
- * @param buffer The byte array
- * @param value The long to convert
- * @return The length of the string representation of the integer
- * -1 indicates some problem (e.g the char buffer was too small)
- */
- public static int numToBytes(byte[] buffer, long value) {
- return numToBytes(buffer, value, 10);
- }
-
- /**
- * Place a string representation of a long in an array of bytes
- * without incurring allocation
- *
- * @param buffer The byte array
- * @param value The long to convert
- * @param radix the base to use for conversion
- * @return The length of the string representation of the integer
- * -1 indicates some problem (e.g the char buffer was too small)
- */
- public static int numToBytes(byte[] buffer, long value, int radix) {
-
- if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX)
- radix = 10;
-
- if (value == 0) {
- buffer[0] = (byte)'0';
- return 1;
- }
-
- boolean negative;
- long longValue;
- int count;
- if (!(negative = (value < 0))) {
- longValue = -value;
- count = 1;
- } else {
- longValue = value;
- count = 2;
- }
-
- long j = longValue;
- while ((j /= radix) != 0) count++;
- if (count > buffer.length)
- return -1; // overflow
-
- int i = count;
- do {
- int ch = (int) -(longValue % radix);
- if (ch > 9)
- ch -= (10 - (int) 'a');
- else
- ch += (int) '0';
- buffer [--i] = (byte) ch;
- } while ((longValue /= radix) != 0);
- if (negative) buffer [0] = (byte)'-';
-
- return count;
-
- }
-
- /**
- * sprintf(char *str, char *format, char* value)
- *
- * @param str The destination 'string' (memory in C space)
- * @param format The format 'string' (memory in C space)
- * @param value The value 'string' (memory in C space)
- * @return The number of characters printed (as returned by C's sprintf
- */
- public abstract int sprintf(Address str, Address format, Address value);
-
- /**
- * Create an array of a particular type.
- * The easiest way to use this is:
- * Foo[] x = (Foo [])Stream.createDataArray(new Foo[0], numElements);
- * @param templ a data array to use as a template
- * @param numElements number of elements in new array
- * @return the new array
- */
- @Interruptible
- public abstract Object createDataArray(Object templ, int numElements);
-}
-
diff --git a/vmkit/mmtk/java/src/org/vmmagic/Intrinsic.java b/vmkit/mmtk/java/src/org/vmmagic/Intrinsic.java
deleted file mode 100644
index 8b63e5e..0000000
--- a/vmkit/mmtk/java/src/org/vmmagic/Intrinsic.java
+++ /dev/null
@@ -1,40 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Common Public License (CPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/cpl1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.vmmagic;
-
-import java.lang.annotation.Retention;
-import java.lang.annotation.RetentionPolicy;
-import java.lang.annotation.Target;
-import java.lang.annotation.ElementType;
-import java.lang.annotation.Inherited;
-
-/**
- * An intrinsic method is a method that is built in (that is, intrinsic) to the compiler
- * rather than part of a class library. Intrinsic methods are an escape hatch to provide
- * "magic" that is inexpressible int the Java programming language. A compiler intrinsic
- * will usually generate a specific code sequence that is inlined and optimized as part
- * by the compiler. Unless an intrinsic method is expected to be executed in a non-intrinsic
- * aware compiler, the body of the method should be empty.
- *
- * <p>If the Intrinsic annotation is applied to a method then then the method is a compiler
- * intrinsic. If the Intrinsic annotation is applied to a class then all the methods of
- * the class AND all subclasses are intrinsic.</p>
- *
- * <p>NOTE: At the current time the Intrinsic annotation is only used for documentation
- * purposes but in the near future it is expected that the semantics of the annotation will
- * be enforced by the compiler.</p>
- */
-@Retention(RetentionPolicy.RUNTIME)
-@Target({ElementType.TYPE,ElementType.METHOD})
-@Inherited
-public @interface Intrinsic { }
diff --git a/vmkit/mmtk/java/src/org/vmmagic/Pragma.java b/vmkit/mmtk/java/src/org/vmmagic/Pragma.java
deleted file mode 100644
index 6774b97..0000000
--- a/vmkit/mmtk/java/src/org/vmmagic/Pragma.java
+++ /dev/null
@@ -1,38 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Common Public License (CPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/cpl1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.vmmagic;
-
-import java.lang.annotation.Retention;
-import java.lang.annotation.RetentionPolicy;
-import java.lang.annotation.Target;
-import java.lang.annotation.ElementType;
-import java.lang.annotation.Inherited;
-
-/**
- * A Pragma is a mechanism for supplying information to the compiler to alter the code it
- * generates for a method. A Pragma is similar to an {@link org.vmmagic.Intrinsic}
- * but it does not provide any behaviour but provides information to the compiler that modifies
- * optimizations, calling conventions and activation frame layout.
- *
- * <p>If the Pragma annotation is applied to a method then then the method is a handled specially
- * by the compiler. If the Pragma annotation is applied to a class then then all the methods in that
- * class are handled specially by the compiler.</p>
- *
- * <p>NOTE: At the current time the Pragma annotation is only used for documentation
- * purposes but in the near future it is expected that the semantics of the annotation will
- * be enforced by the compiler.</p>
- */
-@Retention(RetentionPolicy.RUNTIME)
-@Target({ElementType.TYPE,ElementType.METHOD})
-@Inherited
-public @interface Pragma { }
diff --git a/vmkit/mmtk/java/src/org/vmmagic/Unboxed.java b/vmkit/mmtk/java/src/org/vmmagic/Unboxed.java
deleted file mode 100644
index d53e3cf..0000000
--- a/vmkit/mmtk/java/src/org/vmmagic/Unboxed.java
+++ /dev/null
@@ -1,44 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Common Public License (CPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/cpl1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.vmmagic;
-
-import java.lang.annotation.Retention;
-import java.lang.annotation.RetentionPolicy;
-import java.lang.annotation.Target;
-import java.lang.annotation.ElementType;
-import java.lang.annotation.Inherited;
-
-/**
- * The Unboxed annotation marks a type as unboxed. Besides the primitive types, all Java values
- * are boxed types. Conceptually, they are represented by a pointer to a heap object. However,
- * an unboxed type is represented by the value itself. All methods on an unboxed type are
- * {@link Intrinsic}s.
- *
- * <p>As an unboxed type is not a regular java object there are a few constraints on the way unboxed
- * types are handled;</p>
- * <ul>
- * <li>All methods are {@link Intrinsic} and thus there can be no virtual methods.</li>
- * <li>An unboxed type can not be synchronized on.</li>
- * <li>An unboxed type has no hashcode.</li>
- * <li>An unboxed type MUST NOT be passed where an object is expected or when two overloaded methods
- * can only be distinguished by by Object vs unboxed parameter type.</li>
- * </ul>
- *
- * <p>NOTE: At the current time the Unboxed annotation is only used for documentation
- * purposes but in the near future it is expected that the semantics of the annotation will
- * be enforced by the compiler.</p>
- */
-@Retention(RetentionPolicy.RUNTIME)
-@Target(ElementType.TYPE)
-@Inherited
-public @interface Unboxed { }
diff --git a/vmkit/mmtk/java/src/org/vmmagic/pragma/BaselineNoRegisters.java b/vmkit/mmtk/java/src/org/vmmagic/pragma/BaselineNoRegisters.java
deleted file mode 100644
index fcba65b..0000000
--- a/vmkit/mmtk/java/src/org/vmmagic/pragma/BaselineNoRegisters.java
+++ /dev/null
@@ -1,28 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Common Public License (CPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/cpl1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.vmmagic.pragma;
-
-import java.lang.annotation.Retention;
-import java.lang.annotation.Target;
-import java.lang.annotation.RetentionPolicy;
-import java.lang.annotation.ElementType;
-import org.vmmagic.Pragma;
-
-/**
- * Some methods shouldn't use registers for locals and stack values.
- * E.g. CollectorThread can't relocate refs in registers of its own.
- */
-@Retention(RetentionPolicy.RUNTIME)
-@Target(ElementType.METHOD)
-@Pragma
-public @interface BaselineNoRegisters { }
diff --git a/vmkit/mmtk/java/src/org/vmmagic/pragma/BaselineSaveLSRegisters.java b/vmkit/mmtk/java/src/org/vmmagic/pragma/BaselineSaveLSRegisters.java
deleted file mode 100644
index 61464c7..0000000
--- a/vmkit/mmtk/java/src/org/vmmagic/pragma/BaselineSaveLSRegisters.java
+++ /dev/null
@@ -1,28 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Common Public License (CPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/cpl1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.vmmagic.pragma;
-
-import java.lang.annotation.Retention;
-import java.lang.annotation.Target;
-import java.lang.annotation.RetentionPolicy;
-import java.lang.annotation.ElementType;
-import org.vmmagic.Pragma;
-
-/**
- * Methods with this pragma that are BaselineCompiled should save in its prologue, ALL registers that
- * can be used to store local and stack registers in any BaselineCompiled method. Used by OSR.
- */
-@Retention(RetentionPolicy.RUNTIME)
-@Target(ElementType.METHOD)
-@Pragma
-public @interface BaselineSaveLSRegisters { }
diff --git a/vmkit/mmtk/java/src/org/vmmagic/pragma/DynamicBridge.java b/vmkit/mmtk/java/src/org/vmmagic/pragma/DynamicBridge.java
deleted file mode 100644
index 9e03545..0000000
--- a/vmkit/mmtk/java/src/org/vmmagic/pragma/DynamicBridge.java
+++ /dev/null
@@ -1,37 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Common Public License (CPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/cpl1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.vmmagic.pragma;
-
-import java.lang.annotation.Retention;
-import java.lang.annotation.RetentionPolicy;
-import java.lang.annotation.Target;
-import java.lang.annotation.ElementType;
-import org.vmmagic.Pragma;
-
-/**
- * Methods of a class that implements this interface are treated specially
- * by the compilers.
- *
- * <p>Instead of saving just the non-volatile registers used by the method into
- * the register save area of the method's stackframe, the compiler generates
- * code to save *all* GPR and FPR registers except GPR0, FPR0, JTOC, and FP.
- *
- * <p>Methods of a class that implement this interface may not return.
- * (it is assumed that execution is resumed via a call to Magic.dynamicBridgeTo)
- *
- * @see org.jikesrvm.runtime.Magic#dynamicBridgeTo(org.jikesrvm.ArchitectureSpecific.CodeArray)
- */
-@Retention(RetentionPolicy.RUNTIME)
-@Target(ElementType.TYPE)
-@Pragma
-public @interface DynamicBridge { }
diff --git a/vmkit/mmtk/java/src/org/vmmagic/pragma/Entrypoint.java b/vmkit/mmtk/java/src/org/vmmagic/pragma/Entrypoint.java
deleted file mode 100644
index d755024..0000000
--- a/vmkit/mmtk/java/src/org/vmmagic/pragma/Entrypoint.java
+++ /dev/null
@@ -1,29 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Common Public License (CPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/cpl1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.vmmagic.pragma;
-
-import java.lang.annotation.Retention;
-import java.lang.annotation.RetentionPolicy;
-import java.lang.annotation.Target;
-import java.lang.annotation.ElementType;
-import org.vmmagic.Pragma;
-
-/**
- * The entrypoint annotation indicates that the method or field is
- * directly accessed by the compiler. We cache resolved values for
- * these elements in Entrypoints.
- */
-@Retention(RetentionPolicy.RUNTIME)
-@Target({ElementType.METHOD, ElementType.FIELD})
-@Pragma
-public @interface Entrypoint { }
diff --git a/vmkit/mmtk/java/src/org/vmmagic/pragma/Inline.java b/vmkit/mmtk/java/src/org/vmmagic/pragma/Inline.java
deleted file mode 100644
index dc2b627..0000000
--- a/vmkit/mmtk/java/src/org/vmmagic/pragma/Inline.java
+++ /dev/null
@@ -1,63 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Common Public License (CPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/cpl1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.vmmagic.pragma;
-
-import java.lang.annotation.Retention;
-import java.lang.annotation.Target;
-import java.lang.annotation.RetentionPolicy;
-import java.lang.annotation.ElementType;
-import org.vmmagic.Pragma;
-
-/**
- * This pragma indicates that a particular method should always be inlined
- * by the optimizing compiler.
- */
-@Retention(RetentionPolicy.RUNTIME)
-@Target(ElementType.METHOD)
-@Pragma
-public @interface Inline {
- /**
- * Enumeration defining when to inline
- */
- public enum When {
- /**
- * Always inline, regardless of arguments
- */
- Always,
- /**
- * Inline when all the arguments are constants
- */
- AllArgumentsAreConstant,
- /**
- * Inline when the specified arguments are constants
- */
- ArgumentsAreConstant,
- /**
- * Inline when the VM is built without Assertions (VM.VerifyAssertions == false).
- * Note: It would be nicer to have the more general ExpressionIsTrue annotation,
- * but the argument expression to the annotation is restricted to be a fairly
- * trivial constant, and that isn't enough to handle how VM.VERIFY_ASSERTIONS
- * is defined in MMTk.
- */
- AssertionsDisabled
- }
- /**
- * When to inline, default When.Always
- */
- When value() default When.Always;
- /**
- * Arguments that must be constant to cause inlining. NB for static methods 0
- * is the first argument whilst for virtual methods 0 is this
- */
- int[] arguments() default {};
-}
diff --git a/vmkit/mmtk/java/src/org/vmmagic/pragma/Interruptible.java b/vmkit/mmtk/java/src/org/vmmagic/pragma/Interruptible.java
deleted file mode 100644
index 71650e0..0000000
--- a/vmkit/mmtk/java/src/org/vmmagic/pragma/Interruptible.java
+++ /dev/null
@@ -1,48 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Common Public License (CPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/cpl1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.vmmagic.pragma;
-
-import java.lang.annotation.Retention;
-import java.lang.annotation.Target;
-import java.lang.annotation.RetentionPolicy;
-import java.lang.annotation.ElementType;
-import org.vmmagic.Pragma;
-
-/**
- * By default all Java code is interruptible, that is scheduling or garbage
- * collection may occur at points within the code. Code can be marked as
- * {@link Unpreemptible} or {@link Uninterruptible}, that instructs the JVM to
- * avoid garbage collection and thread scheduling. The {@link Uninterruptible}
- * annotation disallows any operation that may cause garbage collection or
- * thread scheduling, for example memory allocation. The {@link Unpreemptible}
- * annotation doesn't disallow operations that can cause garbage collection or
- * scheduling, but instructs the JVM to avoid inserting such operations during a
- * block of code.
- *
- * In the internals of a VM most code wants to be {@link Uninterruptible}.
- * However, code involved in scheduling and locking will cause context switches,
- * and creating exception objects may trigger garbage collection, this code is
- * therefore {@link Unpreemptible}.
- *
- * This pragma is used to declare that a particular method is interruptible. It
- * is used to override the class-wide pragma {@link Uninterruptible}.
- */
-@Retention(RetentionPolicy.RUNTIME)
-@Target(ElementType.METHOD)
-@Pragma
-public @interface Interruptible {
- /**
- * @return Explanation of why code needs to be interruptible
- */
- String value() default "";
-}
diff --git a/vmkit/mmtk/java/src/org/vmmagic/pragma/LogicallyUninterruptible.java b/vmkit/mmtk/java/src/org/vmmagic/pragma/LogicallyUninterruptible.java
deleted file mode 100644
index 0d10bf4..0000000
--- a/vmkit/mmtk/java/src/org/vmmagic/pragma/LogicallyUninterruptible.java
+++ /dev/null
@@ -1,51 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Common Public License (CPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/cpl1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.vmmagic.pragma;
-
-import java.lang.annotation.Retention;
-import java.lang.annotation.Target;
-import java.lang.annotation.RetentionPolicy;
-import java.lang.annotation.ElementType;
-import org.vmmagic.Pragma;
-
-/**
- * A pragma that can be used to declare that a particular method is logically
- * uninterruptible even though it contains bytecodes that are actually
- * interruptible.
- *
- * The effect of this pragma is to suppress warning messages about violations of
- * uninterruptiblity when compiling a method that throws this exception. There
- * are two cases in which using the pragma is justified.
- * <ul>
- * <li> Uninterruptibility is ensured via some other mechanism. For example, the
- * method explicitly disables threadswitching around the interruptible regions
- * (VM.sysWrite on String). Or the interruptible regions are not reachable when
- * the VM is running (various VM.sysWrite that check VM.runningVM).
- * <li> The interruptible regions represent an 'error' condition that will never
- * be executed unless the VM is already in the process of reporting an error,
- * for example RuntimeEntrypoints.raiseClassCastException.
- * <ul>
- * Extreme care must be exercised when using this pragma since it suppresses the
- * checking of uninterruptibility.
- * <p>
- * Use of this pragma is being phased out since it lumps together two possible
- * special cases. Use either {@link Unpreemptible} or
- * {@link UninterruptibleNoWarn} instead.
- * {@link <a href="http://jira.codehaus.org/browse/RVM-115">RVM-115</a>} for more
- * context.
- * @deprecated
- */
-@Retention(RetentionPolicy.RUNTIME)
-@Target(ElementType.METHOD)
-@Pragma
-public @interface LogicallyUninterruptible { }
diff --git a/vmkit/mmtk/java/src/org/vmmagic/pragma/NativeBridge.java b/vmkit/mmtk/java/src/org/vmmagic/pragma/NativeBridge.java
deleted file mode 100644
index 258873e..0000000
--- a/vmkit/mmtk/java/src/org/vmmagic/pragma/NativeBridge.java
+++ /dev/null
@@ -1,32 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Common Public License (CPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/cpl1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.vmmagic.pragma;
-
-import java.lang.annotation.Retention;
-import java.lang.annotation.RetentionPolicy;
-import java.lang.annotation.Target;
-import java.lang.annotation.ElementType;
-import org.vmmagic.Pragma;
-
-/**
- * Methods of a class that implements this interface are treated specially
- * by the compilers:
- * -They are only called from C or C++ program
- * -The compiler will generate the necessary prolog to insert a glue stack
- * frame to map from the native stack/register convention to RVM's convention
- * -It is an error to call these methods from Java
- */
-@Retention(RetentionPolicy.RUNTIME)
-@Target(ElementType.TYPE)
-@Pragma
-public @interface NativeBridge { }
diff --git a/vmkit/mmtk/java/src/org/vmmagic/pragma/NoBoundsCheck.java b/vmkit/mmtk/java/src/org/vmmagic/pragma/NoBoundsCheck.java
deleted file mode 100644
index af72a40..0000000
--- a/vmkit/mmtk/java/src/org/vmmagic/pragma/NoBoundsCheck.java
+++ /dev/null
@@ -1,28 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Common Public License (CPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/cpl1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.vmmagic.pragma;
-
-import java.lang.annotation.Retention;
-import java.lang.annotation.Target;
-import java.lang.annotation.RetentionPolicy;
-import java.lang.annotation.ElementType;
-import org.vmmagic.Pragma;
-
-/**
- * This pragma indicates that a particular method should never have bounds
- * checks generated.
- */
-@Retention(RetentionPolicy.RUNTIME)
-@Target(ElementType.METHOD)
-@Pragma
-public @interface NoBoundsCheck { }
diff --git a/vmkit/mmtk/java/src/org/vmmagic/pragma/NoEscapes.java b/vmkit/mmtk/java/src/org/vmmagic/pragma/NoEscapes.java
deleted file mode 100644
index 956e73c..0000000
--- a/vmkit/mmtk/java/src/org/vmmagic/pragma/NoEscapes.java
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Common Public License (CPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/cpl1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.vmmagic.pragma;
-
-import java.lang.annotation.Retention;
-import java.lang.annotation.Target;
-import java.lang.annotation.RetentionPolicy;
-import java.lang.annotation.ElementType;
-
-/**
- * Use this annotation to mark methods that won't cause their reference arguments
- * to escape. If we can convert the object referenced in to registers then the
- * method marked with this annotation will be removed.
- */
-@Retention(RetentionPolicy.RUNTIME)
-@Target({ElementType.METHOD, ElementType.CONSTRUCTOR})
-public @interface NoEscapes { }
diff --git a/vmkit/mmtk/java/src/org/vmmagic/pragma/NoInline.java b/vmkit/mmtk/java/src/org/vmmagic/pragma/NoInline.java
deleted file mode 100644
index 6e4f835..0000000
--- a/vmkit/mmtk/java/src/org/vmmagic/pragma/NoInline.java
+++ /dev/null
@@ -1,28 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Common Public License (CPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/cpl1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.vmmagic.pragma;
-
-import java.lang.annotation.Retention;
-import java.lang.annotation.Target;
-import java.lang.annotation.RetentionPolicy;
-import java.lang.annotation.ElementType;
-import org.vmmagic.Pragma;
-
-/**
- * This pragma indicates that a particular method should never be inlined
- * by the optimizing compiler.
- */
-@Retention(RetentionPolicy.RUNTIME)
-@Target(ElementType.METHOD)
-@Pragma
-public @interface NoInline { }
diff --git a/vmkit/mmtk/java/src/org/vmmagic/pragma/NoNullCheck.java b/vmkit/mmtk/java/src/org/vmmagic/pragma/NoNullCheck.java
deleted file mode 100644
index 07d9a10..0000000
--- a/vmkit/mmtk/java/src/org/vmmagic/pragma/NoNullCheck.java
+++ /dev/null
@@ -1,28 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Common Public License (CPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/cpl1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.vmmagic.pragma;
-
-import java.lang.annotation.Retention;
-import java.lang.annotation.Target;
-import java.lang.annotation.RetentionPolicy;
-import java.lang.annotation.ElementType;
-import org.vmmagic.Pragma;
-
-/**
- * This pragma indicates that a particular method should never have null checks
- * generated.
- */
-@Retention(RetentionPolicy.RUNTIME)
-@Target(ElementType.METHOD)
-@Pragma
-public @interface NoNullCheck { }
diff --git a/vmkit/mmtk/java/src/org/vmmagic/pragma/NoOptCompile.java b/vmkit/mmtk/java/src/org/vmmagic/pragma/NoOptCompile.java
deleted file mode 100644
index d3d002e..0000000
--- a/vmkit/mmtk/java/src/org/vmmagic/pragma/NoOptCompile.java
+++ /dev/null
@@ -1,29 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Common Public License (CPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/cpl1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.vmmagic.pragma;
-
-import java.lang.annotation.Retention;
-import java.lang.annotation.Target;
-import java.lang.annotation.RetentionPolicy;
-import java.lang.annotation.ElementType;
-import org.vmmagic.Pragma;
-
-/**
- * This pragma indicates that a particular method should never be
- * compiled by the optimizing compiler. It also implies that the
- * method will never be inlined by the optimizing compiler.
- */
-@Retention(RetentionPolicy.RUNTIME)
-@Target({ElementType.TYPE, ElementType.METHOD})
-@Pragma
-public @interface NoOptCompile { }
diff --git a/vmkit/mmtk/java/src/org/vmmagic/pragma/NonMoving.java b/vmkit/mmtk/java/src/org/vmmagic/pragma/NonMoving.java
deleted file mode 100644
index 7d4a334..0000000
--- a/vmkit/mmtk/java/src/org/vmmagic/pragma/NonMoving.java
+++ /dev/null
@@ -1,28 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Common Public License (CPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/cpl1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.vmmagic.pragma;
-
-import java.lang.annotation.Retention;
-import java.lang.annotation.Target;
-import java.lang.annotation.RetentionPolicy;
-import java.lang.annotation.ElementType;
-
-/**
- * Use this annotation to mark types that must never move. This is intended for
- * a very small set of VM internal types that are accessed without knowledge of the
- * memory manager. This includes code, that is CALLed and fields that are loaded
- * directly (such as Untraced fields).
- */
-@Retention(RetentionPolicy.RUNTIME)
-@Target(ElementType.TYPE)
-public @interface NonMoving { }
diff --git a/vmkit/mmtk/java/src/org/vmmagic/pragma/NonMovingAllocation.java b/vmkit/mmtk/java/src/org/vmmagic/pragma/NonMovingAllocation.java
deleted file mode 100644
index c3b45c9..0000000
--- a/vmkit/mmtk/java/src/org/vmmagic/pragma/NonMovingAllocation.java
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Common Public License (CPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/cpl1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.vmmagic.pragma;
-
-import java.lang.annotation.Retention;
-import java.lang.annotation.Target;
-import java.lang.annotation.RetentionPolicy;
-import java.lang.annotation.ElementType;
-
-/**
- * Use this annotation to mark methods for which all allocation must never
- * move. This is intended for a very small set of VM internal methods that
- * specifically require these semantics.
- */
-@Retention(RetentionPolicy.RUNTIME)
-@Target(ElementType.METHOD)
-public @interface NonMovingAllocation { }
diff --git a/vmkit/mmtk/java/src/org/vmmagic/pragma/Preemptible.java b/vmkit/mmtk/java/src/org/vmmagic/pragma/Preemptible.java
deleted file mode 100644
index 2fded57..0000000
--- a/vmkit/mmtk/java/src/org/vmmagic/pragma/Preemptible.java
+++ /dev/null
@@ -1,48 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Common Public License (CPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/cpl1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.vmmagic.pragma;
-
-import java.lang.annotation.Retention;
-import java.lang.annotation.Target;
-import java.lang.annotation.RetentionPolicy;
-import java.lang.annotation.ElementType;
-import org.vmmagic.Pragma;
-
-/**
- * By default all Java code is interruptible, that is scheduling or garbage
- * collection may occur at points within the code. Code can be marked as
- * {@link Unpreemptible} or {@link Uninterruptible}, that instructs the JVM to
- * avoid garbage collection and thread scheduling. The {@link Uninterruptible}
- * annotation disallows any operation that may cause garbage collection or
- * thread scheduling, for example memory allocation. The {@link Unpreemptible}
- * annotation doesn't disallow operations that can cause garbage collection or
- * scheduling, but instructs the JVM to avoid inserting such operations during a
- * block of code.
- *
- * In the internals of a VM most code wants to be {@link Uninterruptible}.
- * However, code involved in scheduling and locking will cause context switches,
- * and creating exception objects may trigger garbage collection, this code is
- * therefore {@link Unpreemptible}.
- *
- * This pragma is used to declare that a particular method is preemptible. It
- * is used to override the class-wide pragma {@link Unpreemptible}.
- */
-@Retention(RetentionPolicy.RUNTIME)
-@Target({ElementType.TYPE, ElementType.METHOD})
-@Pragma
-public @interface Preemptible {
- /**
- * @return Explanation of why code needs to be preemptible
- */
- String value() default "";
-}
diff --git a/vmkit/mmtk/java/src/org/vmmagic/pragma/Pure.java b/vmkit/mmtk/java/src/org/vmmagic/pragma/Pure.java
deleted file mode 100644
index e70276d..0000000
--- a/vmkit/mmtk/java/src/org/vmmagic/pragma/Pure.java
+++ /dev/null
@@ -1,31 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Common Public License (CPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/cpl1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.vmmagic.pragma;
-
-import java.lang.annotation.Retention;
-import java.lang.annotation.Target;
-import java.lang.annotation.RetentionPolicy;
-import java.lang.annotation.ElementType;
-import org.vmmagic.Pragma;
-
-/**
- * This pragma is used to indicate a method has no side effects. Use this pragma
- * with care as it can cause compile time invocation of the method it is placed
- * on. This pragma is used to imply weak purity of a method, and as such cannot
- * remove calls to pure methods - as they may throw exceptions.
- * {@link <a href="http://jira.codehaus.org/browse/RVM-503">RVM-503</a>}.
- */
-@Retention(RetentionPolicy.RUNTIME)
-@Target({ElementType.METHOD})
-@Pragma
-public @interface Pure { /* annotation has no value */ }
diff --git a/vmkit/mmtk/java/src/org/vmmagic/pragma/RawStorage.java b/vmkit/mmtk/java/src/org/vmmagic/pragma/RawStorage.java
deleted file mode 100644
index c71bc27..0000000
--- a/vmkit/mmtk/java/src/org/vmmagic/pragma/RawStorage.java
+++ /dev/null
@@ -1,36 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Common Public License (CPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/cpl1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.vmmagic.pragma;
-
-import java.lang.annotation.Retention;
-import java.lang.annotation.Target;
-import java.lang.annotation.RetentionPolicy;
-import java.lang.annotation.ElementType;
-import org.vmmagic.Pragma;
-
-/**
- * When applied to class this annotation indicates that the data component
- * of this field consists of an intrisically managed chunk of raw memory of
- * the specified size. This is used as the basic building block for native
- * width types.
- *
- * To construct types larger than those possible with RawStorage, simply
- * construct an type with multiple (Unboxed) fields.
- */
-@Retention(RetentionPolicy.RUNTIME)
-@Target({ElementType.TYPE})
-@Pragma
-public @interface RawStorage {
- boolean lengthInWords();
- int length();
-}
diff --git a/vmkit/mmtk/java/src/org/vmmagic/pragma/RuntimeFinal.java b/vmkit/mmtk/java/src/org/vmmagic/pragma/RuntimeFinal.java
deleted file mode 100644
index 2e94db2..0000000
--- a/vmkit/mmtk/java/src/org/vmmagic/pragma/RuntimeFinal.java
+++ /dev/null
@@ -1,32 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Common Public License (CPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/cpl1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.vmmagic.pragma;
-
-import java.lang.annotation.Retention;
-import java.lang.annotation.Target;
-import java.lang.annotation.RetentionPolicy;
-import java.lang.annotation.ElementType;
-import org.vmmagic.Pragma;
-
-/**
- * This pragma is used to indicate a field will be final in the running VM. We
- * can't indicate all fields are final as some are used in the boot strap
- * process.
- */
-@Retention(RetentionPolicy.RUNTIME)
-@Target({ElementType.FIELD})
-@Pragma
-public @interface RuntimeFinal {
- /** The value of the field. Currently only boolean values can be RuntimeFinal. */
- boolean value();
-}
diff --git a/vmkit/mmtk/java/src/org/vmmagic/pragma/RuntimePure.java b/vmkit/mmtk/java/src/org/vmmagic/pragma/RuntimePure.java
deleted file mode 100644
index c8569cf..0000000
--- a/vmkit/mmtk/java/src/org/vmmagic/pragma/RuntimePure.java
+++ /dev/null
@@ -1,36 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Common Public License (CPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/cpl1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.vmmagic.pragma;
-
-import java.lang.annotation.Retention;
-import java.lang.annotation.Target;
-import java.lang.annotation.RetentionPolicy;
-import java.lang.annotation.ElementType;
-import org.vmmagic.Pragma;
-
-/**
- * This pragma is a variant of Pure that is used to mark methods that have a
- * special behaviour at boot image writing time and are Pure at runtime
- */
-@Retention(RetentionPolicy.RUNTIME)
-@Target({ElementType.METHOD})
-@Pragma
-public @interface RuntimePure {
- /** Enumeration of the special boot image return values */
- public enum ReturnValue {
- /** the return value is unavailable until runtime*/
- Unavailable
- }
- /** What value should be returned */
- ReturnValue value() default ReturnValue.Unavailable;
-}
diff --git a/vmkit/mmtk/java/src/org/vmmagic/pragma/SaveVolatile.java b/vmkit/mmtk/java/src/org/vmmagic/pragma/SaveVolatile.java
deleted file mode 100644
index cbd884d..0000000
--- a/vmkit/mmtk/java/src/org/vmmagic/pragma/SaveVolatile.java
+++ /dev/null
@@ -1,30 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Common Public License (CPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/cpl1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.vmmagic.pragma;
-
-import java.lang.annotation.Retention;
-import java.lang.annotation.RetentionPolicy;
-import java.lang.annotation.Target;
-import java.lang.annotation.ElementType;
-import org.vmmagic.Pragma;
-
-/**
- * Methods of a class that implements this interface
- * are treated specially by the machine code compiler:
- * the method prologue saves all the volatile registers
- * and the method epilogue restores all the volatile registers
- */
-@Retention(RetentionPolicy.RUNTIME)
-@Target(ElementType.TYPE)
-@Pragma
-public @interface SaveVolatile { }
diff --git a/vmkit/mmtk/java/src/org/vmmagic/pragma/SpecializedMethodInvoke.java b/vmkit/mmtk/java/src/org/vmmagic/pragma/SpecializedMethodInvoke.java
deleted file mode 100644
index f50da98..0000000
--- a/vmkit/mmtk/java/src/org/vmmagic/pragma/SpecializedMethodInvoke.java
+++ /dev/null
@@ -1,30 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Common Public License (CPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/cpl1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.vmmagic.pragma;
-
-import java.lang.annotation.Retention;
-import java.lang.annotation.Target;
-import java.lang.annotation.RetentionPolicy;
-import java.lang.annotation.ElementType;
-import org.vmmagic.Pragma;
-
-/**
- * This pragma indicates that a particular method is a specialized
- * method invocation point, and could be optimized as such.
- *
- * All such methods must be static.
- */
-@Retention(RetentionPolicy.RUNTIME)
-@Target(ElementType.METHOD)
-@Pragma
-public @interface SpecializedMethodInvoke { }
diff --git a/vmkit/mmtk/java/src/org/vmmagic/pragma/SynchronizedObject.java b/vmkit/mmtk/java/src/org/vmmagic/pragma/SynchronizedObject.java
deleted file mode 100644
index 360850f..0000000
--- a/vmkit/mmtk/java/src/org/vmmagic/pragma/SynchronizedObject.java
+++ /dev/null
@@ -1,29 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Common Public License (CPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/cpl1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.vmmagic.pragma;
-
-import java.lang.annotation.ElementType;
-import java.lang.annotation.Retention;
-import java.lang.annotation.RetentionPolicy;
-import java.lang.annotation.Target;
-import org.vmmagic.Pragma;
-
-/**
- * This interface designates an object which should always be allocated a
- * thin lock, since it is likely to be synchronized.
- */
-@Retention(RetentionPolicy.RUNTIME)
-@Target(ElementType.TYPE)
-@Pragma
-public @interface SynchronizedObject {
-}
diff --git a/vmkit/mmtk/java/src/org/vmmagic/pragma/SysCallNative.java b/vmkit/mmtk/java/src/org/vmmagic/pragma/SysCallNative.java
deleted file mode 100644
index 3910a81..0000000
--- a/vmkit/mmtk/java/src/org/vmmagic/pragma/SysCallNative.java
+++ /dev/null
@@ -1,32 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Common Public License (CPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/cpl1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.vmmagic.pragma;
-
-import java.lang.annotation.Retention;
-import java.lang.annotation.Target;
-import java.lang.annotation.RetentionPolicy;
-import java.lang.annotation.ElementType;
-import org.vmmagic.Pragma;
-
-/**
- * An annotation for static native methods to show that they should be
- * compiled as system calls. A system call is a lightweight call to a
- * C function that doesn't set up the JNI environment and is therefore
- * cheaper than JNI. The first argument to the function is the address
- * of the C function to run.
- */
-@Retention(RetentionPolicy.RUNTIME)
-@Target({ElementType.METHOD})
-@Pragma
-public @interface SysCallNative {
-}
diff --git a/vmkit/mmtk/java/src/org/vmmagic/pragma/Uninterruptible.java b/vmkit/mmtk/java/src/org/vmmagic/pragma/Uninterruptible.java
deleted file mode 100644
index 9a6625f..0000000
--- a/vmkit/mmtk/java/src/org/vmmagic/pragma/Uninterruptible.java
+++ /dev/null
@@ -1,64 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Common Public License (CPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/cpl1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.vmmagic.pragma;
-
-import java.lang.annotation.Retention;
-import java.lang.annotation.Target;
-import java.lang.annotation.RetentionPolicy;
-import java.lang.annotation.ElementType;
-import org.vmmagic.Pragma;
-
-/**
- * By default all Java code is interruptible, that is scheduling or garbage
- * collection may occur at points within the code. Code can be marked as
- * {@link Unpreemptible} or {@link Uninterruptible}, that instructs the JVM to
- * avoid garbage collection and thread scheduling. The {@link Uninterruptible}
- * annotation disallows any operation that may cause garbage collection or
- * thread scheduling, for example memory allocation. The {@link Unpreemptible}
- * annotation doesn't disallow operations that can cause garbage collection or
- * scheduling, but instructs the JVM to avoid inserting such operations during a
- * block of code.
- *
- * In the internals of a VM most code wants to be {@link Uninterruptible}.
- * However, code involved in scheduling and locking will cause context switches,
- * and creating exception objects may trigger garbage collection, this code is
- * therefore {@link Unpreemptible}.
- *
- * Any method that is marked as uninterruptible is treated specially by the
- * machine code compiler:
- *
- * (1) the normal thread switch test that would be emitted in the method
- * prologue is omitted.
- *
- * (2) the stack overflow test that would be emitted in the method prologue is
- * omitted.
- *
- * (3) calls to preemptible code causes warnings.
- *
- * (4) bytecodes that can cause interruption cause warnings.
- *
- * (5) uninterruptible code will be generated assuming no RuntimeExceptions are
- * raised and without any GC maps (since by definition there can be noGC if
- * control is not lost).
- *
- * This is the inverse of {@link Interruptible}.
- */
-@Retention(RetentionPolicy.RUNTIME)
-@Target({ElementType.TYPE, ElementType.METHOD})
-@Pragma
-public @interface Uninterruptible {
- /**
- * @return Explanation of why code needs to be uninterruptible
- */
- String value() default "";
-}
diff --git a/vmkit/mmtk/java/src/org/vmmagic/pragma/UninterruptibleNoWarn.java b/vmkit/mmtk/java/src/org/vmmagic/pragma/UninterruptibleNoWarn.java
deleted file mode 100644
index 38fb680..0000000
--- a/vmkit/mmtk/java/src/org/vmmagic/pragma/UninterruptibleNoWarn.java
+++ /dev/null
@@ -1,35 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Common Public License (CPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/cpl1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.vmmagic.pragma;
-
-import java.lang.annotation.Retention;
-import java.lang.annotation.Target;
-import java.lang.annotation.RetentionPolicy;
-import java.lang.annotation.ElementType;
-import org.vmmagic.Pragma;
-
-/**
- * A pragma that has the same direct effect as {@link Uninterruptible}
- * but also suppresses checking of uninterruptibility violations for
- * the method. This should be used with care and is only justified
- * for code only executed when creating the boot image.
- */
-@Retention(RetentionPolicy.RUNTIME)
-@Target({ElementType.TYPE, ElementType.METHOD})
-@Pragma
-public @interface UninterruptibleNoWarn {
- /**
- * @return Explanation of why uninterruptible warnings are disabled
- */
- String value() default "";
-}
diff --git a/vmkit/mmtk/java/src/org/vmmagic/pragma/Unpreemptible.java b/vmkit/mmtk/java/src/org/vmmagic/pragma/Unpreemptible.java
deleted file mode 100644
index 093da9f..0000000
--- a/vmkit/mmtk/java/src/org/vmmagic/pragma/Unpreemptible.java
+++ /dev/null
@@ -1,58 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Common Public License (CPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/cpl1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.vmmagic.pragma;
-
-import java.lang.annotation.Retention;
-import java.lang.annotation.Target;
-import java.lang.annotation.RetentionPolicy;
-import java.lang.annotation.ElementType;
-import org.vmmagic.Pragma;
-
-/**
- * By default all Java code is interruptible, that is scheduling or garbage
- * collection may occur at points within the code. Code can be marked as
- * {@link Unpreemptible} or {@link Uninterruptible}, that instructs the JVM to
- * avoid garbage collection and thread scheduling. The {@link Uninterruptible}
- * annotation disallows any operation that may cause garbage collection or
- * thread scheduling, for example memory allocation. The {@link Unpreemptible}
- * annotation doesn't disallow operations that can cause garbage collection or
- * scheduling, but instructs the JVM to avoid inserting such operations during a
- * block of code.
- *
- * In the internals of a VM most code wants to be {@link Uninterruptible}.
- * However, code involved in scheduling and locking will cause context switches,
- * and creating exception objects may trigger garbage collection, this code is
- * therefore {@link Unpreemptible}.
- *
- * Any method that is marked as unpreemptible is treated specially by the
- * machine code compiler:
- *
- * (1) the normal thread switch test that would be emitted in the method
- * prologue is omitted.
- *
- * (2) the stack overflow test that would be emitted in the method prologue is
- * omitted.
- *
- * (3) calls to preemptible code causes warnings.
- *
- * This is the inverse of {@link Preemptible}.
- */
-@Retention(RetentionPolicy.RUNTIME)
-@Target({ElementType.TYPE, ElementType.METHOD})
-@Pragma
-public @interface Unpreemptible {
- /**
- * @return Explanation of why code needs to be unpreemptible
- */
- String value() default "";
-}
diff --git a/vmkit/mmtk/java/src/org/vmmagic/pragma/UnpreemptibleNoWarn.java b/vmkit/mmtk/java/src/org/vmmagic/pragma/UnpreemptibleNoWarn.java
deleted file mode 100644
index b81b214..0000000
--- a/vmkit/mmtk/java/src/org/vmmagic/pragma/UnpreemptibleNoWarn.java
+++ /dev/null
@@ -1,33 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Common Public License (CPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/cpl1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.vmmagic.pragma;
-
-import java.lang.annotation.Retention;
-import java.lang.annotation.Target;
-import java.lang.annotation.RetentionPolicy;
-import java.lang.annotation.ElementType;
-import org.vmmagic.Pragma;
-
-/**
- * A special case of {@link Unpreemptible} where the code may call out to other
- * interruptible routines.
- */
-@Retention(RetentionPolicy.RUNTIME)
-@Target({ElementType.TYPE, ElementType.METHOD})
-@Pragma
-public @interface UnpreemptibleNoWarn {
- /**
- * @return Explanation of why code needs to be unpreemptible
- */
- String value() default "";
-}
diff --git a/vmkit/mmtk/java/src/org/vmmagic/pragma/Untraced.java b/vmkit/mmtk/java/src/org/vmmagic/pragma/Untraced.java
deleted file mode 100644
index a672aef..0000000
--- a/vmkit/mmtk/java/src/org/vmmagic/pragma/Untraced.java
+++ /dev/null
@@ -1,31 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Common Public License (CPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/cpl1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.vmmagic.pragma;
-
-import java.lang.annotation.Retention;
-import java.lang.annotation.Target;
-import java.lang.annotation.RetentionPolicy;
-import java.lang.annotation.ElementType;
-
-/**
- * Use this annotation to mark fields that are read without the knowledge of the
- * memory management system. This means that barriers are not triggered and
- * the reference is also not traced by the garbage collector.
- *
- * As annotations are loaded at class resolution time, fields marked with this
- * annotation must be private so that no unresolved accesses are compiled to them with
- * barriers.
- */
-@Retention(RetentionPolicy.RUNTIME)
-@Target(ElementType.FIELD)
-public @interface Untraced { }
diff --git a/vmkit/mmtk/java/src/org/vmmagic/unboxed/Address.java b/vmkit/mmtk/java/src/org/vmmagic/unboxed/Address.java
deleted file mode 100644
index f9e8023..0000000
--- a/vmkit/mmtk/java/src/org/vmmagic/unboxed/Address.java
+++ /dev/null
@@ -1,952 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Common Public License (CPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/cpl1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.vmmagic.unboxed;
-
-import org.vmmagic.Unboxed;
-import org.vmmagic.pragma.RawStorage;
-
-/**
- * <b>Stub</b> implementation of an Address type, intended only to
- * allow the core of MMTk to be compiled. This <b>must</b> be
- * replaced with a concrete implementation appropriate to a specific
- * VM.
- *
- * The address type is used by the runtime system and collector to
- * denote machine addresses. We use a separate type instead of the
- * Java int type for coding clarity, machine-portability (it can map
- * to 32 bit and 64 bit integral types), and access to unsigned
- * operations (Java does not have unsigned int types).
- */
-@Unboxed
-@RawStorage(lengthInWords = true, length = 1)
-public final class Address {
-
- /****************************************************************************
- *
- * Special values
- */
-
- /**
- * Return an <code>Address</code> instance that reflects the value
- * zero.
- *
- * @return An address instance that reflects the value zero.
- */
- public static Address zero() {
- return null;
- }
-
- /**
- * Return <code>true</code> if this instance is zero.
- *
- * @return <code>true</code> if this instance is zero.
- */
- public boolean isZero() {
- return false;
- }
-
- /**
- * Return an <code>Address</code> instance that reflects the maximum
- * allowable <code>Address</code> value.
- *
- * @return An <code>Address</code> instance that reflects the
- * maximum allowable <code>Address</code> value.
- */
- public static Address max() {
- return null;
- }
-
- /**
- * Return <code>true</code> if this instance is the maximum
- * allowable <code>Address</code> value.
- *
- * @return <code>true</code> if this instance is the maximum
- * allowable <code>Address</code> valu.
- */
- public boolean isMax() {
- return false;
- }
-
- /****************************************************************************
- *
- * Conversions
- */
-
- /**
- * Fabricate an <code>Address</code> instance from an integer, after
- * sign extending the integer.
- *
- * @param address the integer from which to create an <code>Address</code>
- * instance
- * @return An address instance
- */
- public static Address fromIntSignExtend(int address) {
- return null;
- }
-
- /**
- * Fabricate an <code>Address</code> instance from an integer, after
- * zero extending the integer.
- *
- * @param address the integer from which to create an <code>Address</code>
- * instance
- * @return An address instance
- */
- public static Address fromIntZeroExtend(int address) {
- return null;
- }
-
- /**
- * Fabricate an <code>Address</code> instance from an integer
- *
- * @param address the integer from which to create an <code>Address</code>
- * instance
- * @return An address instance
- */
- public static Address fromLong(long address) {
- return null;
- }
-
- /**
- * Fabricate an <code>ObjectReference</code> instance from an
- * <code>Address</code> instance. It is the user's responsibility
- * to ensure that the <code>Address</code> is suitable (i.e. it
- * points to the object header, or satisfies any other VM-specific
- * requirement for such a conversion).
- *
- * @return An <code>ObjectReference</code> instance.
- */
- public ObjectReference toObjectReference() {
- return null;
- }
-
- /**
- * Return an integer that reflects the value of this
- * <code>Address</code> instance.
- *
- * @return An integer that reflects the value of this
- * <code>Address</code> instance.
- */
- public int toInt() {
- return 0;
- }
-
- /**
- * Return an long that reflects the value of this
- * <code>Address</code> instance.
- *
- * @return An long that reflects the value of this
- * <code>Address</code> instance.
- */
- public long toLong() {
- return 0;
- }
-
- /**
- * Return a <code>Word</code> instance that reflects the value of
- * this <code>Address</code> instance.
- *
- * @return A <code>Word</code> instance that reflects the value of
- * this <code>Address</code> instance.
- */
- public Word toWord() {
- return null;
- }
-
- /****************************************************************************
- *
- * Arithemtic operators
- */
-
- /**
- * Add an integer to this <code>Address</code>, and return the sum.
- *
- * @param v the value to be added to this <code>Address</code>
- * @return An <code>Address</code> instance that reflects the result
- * of the addition.
- */
- public Address plus(int v) {
- return null;
- }
-
- /**
- * Add an <code>Offset</code> to this <code>Address</code>, and
- * return the sum.
- *
- * @param offset the <code>Offset</code> to be added to the address
- * @return An <code>Address</code> instance that reflects the result
- * of the addition.
- */
- public Address plus(Offset offset) {
- return null;
- }
-
- /**
- * Add an <code>Extent</code> to this <code>Address</code>, and
- * return the sum.
- *
- * @param extent the <code>Extent</code> to be added to this
- * <code>Address</code>
- * @return An <code>Address</code> instance that reflects the result
- * of the addition.
- */
- public Address plus(Extent extent) {
- return null;
- }
-
- /**
- * Subtract an integer from this <code>Address</code>, and return
- * the result.
- *
- * @param v the integer to be subtracted from this
- * <code>Address</code>.
- * @return An <code>Address</code> instance that reflects the result
- * of the subtraction.
- */
- public Address minus(int v) {
- return null;
- }
-
- /**
- * Subtract an <code>Offset</code> from this <code>Address</code>, and
- * return the result.
- *
- * @param offset the <code>Offset</code> to be subtracted from this
- * <code>Address</code>.
- * @return An <code>Address</code> instance that reflects the result
- * of the subtraction.
- */
- public Address minus(Offset offset) {
- return null;
- }
-
- /**
- * Subtract an <code>Extent</code> from this <code>Address</code>, and
- * return the result.
- *
- * @param extent the <code>Extent</code> to be subtracted from this
- * <code>Address</code>.
- * @return An <code>Address</code> instance that reflects the result
- * of the subtraction.
- */
- public Address minus(Extent extent) {
- return null;
- }
-
- /**
- * Compute the difference between two <code>Address</code>es and
- * return the result.
- *
- * @param addr2 the <code>Address</code> to be subtracted from this
- * <code>Address</code>.
- * @return An <code>Offset</code> instance that reflects the result
- * of the subtraction.
- */
- public Offset diff(Address addr2) {
- return null;
- }
-
- /****************************************************************************
- *
- * Boolean operators
- */
-
- /**
- * Return true if this <code>Address</code> instance is <i>less
- * than</i> <code>addr2</code>.
- *
- * @param addr2 the <code>Address</code> to be compared to this
- * <code>Address</code>.
- * @return true if this <code>Address</code> instance is <i>less
- * than</i> <code>addr2</code>.
- */
- public boolean LT(Address addr2) {
- return false;
- }
-
- /**
- * Return true if this <code>Address</code> instance is <i>less
- * than or equal to</i> <code>addr2</code>.
- *
- * @param addr2 the <code>Address</code> to be compared to this
- * <code>Address</code>.
- * @return true if this <code>Address</code> instance is <i>less
- * than or equal to</i> <code>addr2</code>.
- */
- public boolean LE(Address addr2) {
- return false;
- }
-
- /**
- * Return true if this <code>Address</code> instance is <i>greater
- * than</i> <code>addr2</code>.
- *
- * @param addr2 the <code>Address</code> to be compared to this
- * <code>Address</code>.
- * @return true if this <code>Address</code> instance is <i>greater
- * than</i> <code>addr2</code>.
- */
- public boolean GT(Address addr2) {
- return false;
- }
-
- /**
- * Return true if this <code>Address</code> instance is <i>greater
- * than or equal to</i> <code>addr2</code>.
- *
- * @param addr2 the <code>Address</code> to be compared to this
- * <code>Address</code>.
- * @return true if this <code>Address</code> instance is <i>greater
- * than or equal to</i> <code>addr2</code>.
- */
- public boolean GE(Address addr2) {
- return false;
- }
-
- /**
- * Return true if this <code>Address</code> instance is <i>equal
- * to</i> <code>addr2</code>.
- *
- * @param addr2 the <code>Address</code> to be compared to this
- * <code>Address</code>.
- * @return true if this <code>Address</code> instance is <i>equal
- * to</i> <code>addr2</code>.
- */
- public boolean EQ(Address addr2) {
- return false;
- }
-
- /**
- * Return true if this <code>Address</code> instance is <i>not equal
- * to</i> <code>addr2</code>.
- *
- * @param addr2 the <code>Address</code> to be compared to this
- * <code>Address</code>.
- * @return true if this <code>Address</code> instance is <i>not
- * equal to</i> <code>addr2</code>.
- */
- public boolean NE(Address addr2) {
- return false;
- }
-
- /****************************************************************************
- *
- * Software prefetch operators etc
- */
-
- /**
- * Prefetch a cache-line, architecture-independent
- */
- public void prefetch() {
- }
-
- /****************************************************************************
- *
- * Memory access operators
- */
-
- /**
- * Loads a reference from the memory location pointed to by the
- * current instance.
- *
- * @return the read value
- */
- public ObjectReference loadObjectReference() {
- return null;
- }
-
- /**
- * Loads a reference from the memory location pointed to by the
- * current instance.
- *
- * @param offset the offset to the value.
- * @return the read value
- */
- public ObjectReference loadObjectReference(Offset offset) {
- return null;
- }
-
- /**
- * Loads a byte from the memory location pointed to by the
- * current instance.
- *
- * @return the read value
- */
- public byte loadByte() {
- return (byte) 0;
- }
-
- /**
- * Loads a byte from the memory location pointed to by the
- * current instance.
- *
- * @param offset the offset to the value.
- * @return the read value
- */
- public byte loadByte(Offset offset) {
- return (byte) 0;
- }
-
- /**
- * Loads a char from the memory location pointed to by the
- * current instance.
- *
- * @return the read value
- */
- public char loadChar() {
- return (char) 0;
- }
-
- /**
- * Loads a char from the memory location pointed to by the
- * current instance.
- *
- * @param offset the offset to the value.
- * @return the read value
- */
- public char loadChar(Offset offset) {
- return (char) 0;
- }
-
- /**
- * Loads a short from the memory location pointed to by the
- * current instance.
- *
- * @return the read value
- */
- public short loadShort() {
- return (short) 0;
- }
-
- /**
- * Loads a short from the memory location pointed to by the
- * current instance.
- *
- * @param offset the offset to the value.
- * @return the read value
- */
- public short loadShort(Offset offset) {
- return (short) 0;
- }
-
- /**
- * Loads a float from the memory location pointed to by the
- * current instance.
- *
- * @return the read value
- */
- public float loadFloat() {
- return (float) 0;
- }
-
- /**
- * Loads a float from the memory location pointed to by the
- * current instance.
- *
- * @param offset the offset to the value.
- * @return the read value
- */
- public float loadFloat(Offset offset) {
- return (float) 0;
- }
-
- /**
- * Loads an int from the memory location pointed to by the
- * current instance.
- *
- * @return the read value
- */
- public int loadInt() {
- return 0;
- }
-
- /**
- * Loads an int from the memory location pointed to by the
- * current instance.
- *
- * @param offset the offset to the value.
- * @return the read value
- */
- public int loadInt(Offset offset) {
- return 0;
- }
-
-
- /**
- * Loads a long from the memory location pointed to by the
- * current instance.
- *
- * @return the read value
- */
- public long loadLong() {
- return 0L;
- }
-
- /**
- * Loads a long from the memory location pointed to by the
- * current instance.
- *
- * @param offset the offset to the value.
- * @return the read value
- */
- public long loadLong(Offset offset) {
- return 0L;
- }
-
- /**
- * Loads a double from the memory location pointed to by the
- * current instance.
- *
- * @return the read value
- */
- public double loadDouble() {
- return 0;
- }
-
- /**
- * Loads a double from the memory location pointed to by the
- * current instance.
- *
- * @param offset the offset to the value.
- * @return the read value
- */
- public double loadDouble(Offset offset) {
- return 0;
- }
-
-
- /**
- * Loads an address value from the memory location pointed to by the
- * current instance.
- *
- * @return the read address value.
- */
- public Address loadAddress() {
- return null;
- }
-
- /**
- * Loads an address value from the memory location pointed to by the
- * current instance.
- *
- * @param offset the offset to the value.
- * @return the read address value.
- */
- public Address loadAddress(Offset offset) {
- return null;
- }
-
- /**
- * Loads a word value from the memory location pointed to by the
- * current instance.
- *
- * @return the read word value.
- */
- public Word loadWord() {
- return null;
- }
-
- /**
- * Loads a word value from the memory location pointed to by the
- * current instance.
- *
- * @param offset the offset to the value.
- * @return the read word value.
- */
- public Word loadWord(Offset offset) {
- return null;
- }
-
- /**
- * Stores the address value in the memory location pointed to by the
- * current instance.
- *
- * @param value The address value to store.
- */
- public void store(ObjectReference value) {
- }
-
- /**
- * Stores the object reference value in the memory location pointed
- * to by the current instance.
- *
- * @param value The object reference value to store.
- * @param offset the offset to the value.
- */
- public void store(ObjectReference value, Offset offset) {
- }
-
- /**
- * Stores the address value in the memory location pointed to by the
- * current instance.
- *
- * @param value The address value to store.
- */
- public void store(Address value) {
- }
-
- /**
- * Stores the address value in the memory location pointed to by the
- * current instance.
- *
- * @param value The address value to store.
- * @param offset the offset to the value.
- */
- public void store(Address value, Offset offset) {
- }
-
- /**
- * Stores the float value in the memory location pointed to by the
- * current instance.
- *
- * @param value The float value to store.
- */
- public void store(float value) {
- }
-
- /**
- * Stores the float value in the memory location pointed to by the
- * current instance.
- *
- * @param value The float value to store.
- * @param offset the offset to the value.
- */
- public void store(float value, Offset offset) {
- }
-
- /**
- * Stores the word value in the memory location pointed to by the
- * current instance.
- *
- * @param value The word value to store.
- */
- public void store(Word value) {
- }
-
- /**
- * Stores the word value in the memory location pointed to by the
- * current instance.
- *
- * @param value The word value to store.
- * @param offset the offset to the value.
- */
- public void store(Word value, Offset offset) {
- }
-
- /**
- * Stores the byte value in the memory location pointed to by the
- * current instance.
- *
- * @param value The byte value to store.
- */
- public void store(byte value) {
- }
-
- /**
- * Stores the byte value in the memory location pointed to by the
- * current instance.
- *
- * @param value The byte value to store.
- * @param offset the offset to the value.
- */
- public void store(byte value, Offset offset) {
- }
-
-
- /**
- * Stores an int value in memory location pointed to by the
- * current instance.
- *
- * @param value The int value to store.
- */
- public void store(int value) {
- }
-
- /**
- * Stores an int value in memory location pointed to by the
- * current instance.
- *
- * @param value The int value to store.
- * @param offset the offset to the value.
- */
- public void store(int value, Offset offset) {
- }
-
- /**
- * Stores a double value in memory location pointed to by the
- * current instance.
- *
- * @param value The double value to store.
- */
- public void store(double value) {
- }
-
- /**
- * Stores a double value in memory location pointed to by the
- * current instance.
- *
- * @param value The double value to store.
- * @param offset the offset to the value.
- */
- public void store(double value, Offset offset) {
- }
-
-
- /**
- * Stores a double value in memory location pointed to by the
- * current instance.
- *
- * @param value The double value to store.
- */
- public void store(long value) {
- }
-
- /**
- * Stores a double value in memory location pointed to by the
- * current instance.
- *
- * @param value The double value to store.
- * @param offset the offset to the value.
- */
- public void store(long value, Offset offset) {
- }
-
- /**
- * Stores a char value in the memory location pointed to by the
- * current instance.
- *
- * @param value the char value to store.
- */
- public void store(char value) {
- }
-
- /**
- * Stores a char value in the memory location pointed to by the
- * current instance.
- *
- * @param value the char value to store.
- * @param offset the offset to the value.
- */
- public void store(char value, Offset offset) {
- }
-
- /**
- * Stores a short value in the memory location pointed to by the
- * current instance.
- *
- * @param value the short value to store.
- */
- public void store(short value) {
- }
-
- /**
- * Stores a short value in the memory location pointed to by the
- * current instance.
- *
- * @param value the short value to store.
- * @param offset the offset to the value.
- */
- public void store(short value, Offset offset) {
- }
-
- /****************************************************************************
- *
- * Atomic memory access operators (compare and swap)
- */
-
- /**
- * Prepare for an atomic store operation. This must be associated with
- * a related call to attempt.
- *
- * @return the old value to be passed to an attempt call.
- */
- public Word prepareWord() {
- return null;
- }
-
- /**
- * Prepare for an atomic store operation. This must be associated with
- * a related call to attempt.
- *
- * @param offset the offset to the value.
- * @return the old value to be passed to an attempt call.
- */
- public Word prepareWord(Offset offset) {
- return null;
- }
-
- /**
- * Prepare for an atomic store operation. This must be associated with
- * a related call to attempt.
- *
- * @return the old value to be passed to an attempt call.
- */
- public ObjectReference prepareObjectReference() {
- return null;
- }
-
- /**
- * Prepare for an atomic store operation. This must be associated with
- * a related call to attempt.
- *
- * @param offset the offset to the value.
- * @return the old value to be passed to an attempt call.
- */
- public ObjectReference prepareObjectReference(Offset offset) {
- return null;
- }
-
- /**
- * Prepare for an atomic store operation. This must be associated with
- * a related call to attempt.
- *
- * @return the old value to be passed to an attempt call.
- */
- public Address prepareAddress() {
- return null;
- }
-
- /**
- * Prepare for an atomic store operation. This must be associated with
- * a related call to attempt.
- *
- * @param offset the offset to the value.
- * @return the old value to be passed to an attempt call.
- */
- public Address prepareAddress(Offset offset) {
- return null;
- }
-
- /**
- * Prepare for an atomic store operation. This must be associated with
- * a related call to attempt.
- *
- * @return the old value to be passed to an attempt call.
- */
- public int prepareInt() {
- return 0;
- }
-
- /**
- * Prepare for an atomic store operation. This must be associated with
- * a related call to attempt.
- *
- * @param offset the offset to the value.
- * @return the old value to be passed to an attempt call.
- */
- public int prepareInt(Offset offset) {
- return 0;
- }
-
- /**
- * Attempt an atomic store operation. This must be associated with a
- * related call to prepare.
- *
- * @param old the old value.
- * @param value the new value.
- * @return true if the attempt was successful.
- */
- public boolean attempt(int old, int value) {
- return false;
- }
-
- /**
- * Attempt an atomic store operation. This must be associated with a
- * related call to prepare.
- *
- * @param old the old value.
- * @param value the new value.
- * @param offset the offset to the value.
- * @return true if the attempt was successful.
- */
- public boolean attempt(int old, int value, Offset offset) {
- return false;
- }
-
- /**
- * Attempt an atomic store operation. This must be associated with a
- * related call to prepare.
- *
- * @param old the old value.
- * @param value the new value.
- * @return true if the attempt was successful.
- */
- public boolean attempt(Word old, Word value) {
- return false;
- }
-
- /**
- * Attempt an atomic store operation. This must be associated with a
- * related call to prepare.
- *
- * @param old the old value.
- * @param value the new value.
- * @param offset the offset to the value.
- * @return true if the attempt was successful.
- */
- public boolean attempt(Word old, Word value, Offset offset) {
- return false;
- }
-
- /**
- * Attempt an atomic store operation. This must be associated with a
- * related call to prepare.
- *
- * @param old the old value.
- * @param value the new value.
- * @return true if the attempt was successful.
- */
- public boolean attempt(ObjectReference old, ObjectReference value) {
- return false;
- }
-
- /**
- * Attempt an atomic store operation. This must be associated with a
- * related call to prepare.
- *
- * @param old the old value.
- * @param value the new value.
- * @param offset the offset to the value.
- * @return true if the attempt was successful.
- */
- public boolean attempt(ObjectReference old, ObjectReference value,
- Offset offset) {
- return false;
- }
-
- /**
- * Attempt an atomic store operation. This must be associated with a
- * related call to prepare.
- *
- * @param old the old value.
- * @param value the new value.
- * @return true if the attempt was successful.
- */
- public boolean attempt(Address old, Address value) {
- return false;
- }
-
- /**
- * Attempt an atomic store operation. This must be associated with a
- * related call to prepare.
- *
- * @param old the old value.
- * @param value the new value.
- * @param offset the offset to the value.
- * @return true if the attempt was successful.
- */
- public boolean attempt(Address old, Address value, Offset offset) {
- return false;
- }
-
-}
diff --git a/vmkit/mmtk/java/src/org/vmmagic/unboxed/AddressArray.java b/vmkit/mmtk/java/src/org/vmmagic/unboxed/AddressArray.java
deleted file mode 100644
index 22c353d..0000000
--- a/vmkit/mmtk/java/src/org/vmmagic/unboxed/AddressArray.java
+++ /dev/null
@@ -1,42 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Common Public License (CPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/cpl1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.vmmagic.unboxed;
-
-public final class AddressArray {
-
- private final Address[] data;
-
- private AddressArray(int size) {
- data = new Address[size];
- Address zero = Address.zero();
- for(int i=0; i<size;i++) {
- data[i] = zero;
- }
- }
-
- public static AddressArray create(int size) {
- return new AddressArray(size);
- }
-
- public Address get(int index) {
- return data[index];
- }
-
- public void set(int index, Address v) {
- data[index] = v;
- }
-
- public int length() {
- return data.length;
- }
-}
diff --git a/vmkit/mmtk/java/src/org/vmmagic/unboxed/Extent.java b/vmkit/mmtk/java/src/org/vmmagic/unboxed/Extent.java
deleted file mode 100644
index a45796f..0000000
--- a/vmkit/mmtk/java/src/org/vmmagic/unboxed/Extent.java
+++ /dev/null
@@ -1,93 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Common Public License (CPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/cpl1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.vmmagic.unboxed;
-
-import org.vmmagic.Unboxed;
-import org.vmmagic.pragma.RawStorage;
-
-@Unboxed
-@RawStorage(lengthInWords = true, length = 1)
-public final class Extent {
- public static Extent fromIntSignExtend(int address) {
- return null;
- }
-
- public static Extent fromIntZeroExtend(int address) {
- return null;
- }
-
- public static Extent zero() {
- return null;
- }
-
- public static Extent one() {
- return null;
- }
-
- public static Extent max() {
- return null;
- }
-
- public int toInt() {
- return 0;
- }
-
- public long toLong() {
- return 0L;
- }
-
- public Word toWord() {
- return null;
- }
-
- public Extent plus(int byteSize) {
- return null;
- }
-
- public Extent plus(Extent byteSize) {
- return null;
- }
-
- public Extent minus(int byteSize) {
- return null;
- }
-
- public Extent minus(Extent byteSize) {
- return null;
- }
-
- public boolean LT(Extent extent2) {
- return false;
- }
-
- public boolean LE(Extent extent2) {
- return false;
- }
-
- public boolean GT(Extent extent2) {
- return false;
- }
-
- public boolean GE(Extent extent2) {
- return false;
- }
-
- public boolean EQ(Extent extent2) {
- return false;
- }
-
- public boolean NE(Extent extent2) {
- return false;
- }
-}
-
diff --git a/vmkit/mmtk/java/src/org/vmmagic/unboxed/ExtentArray.java b/vmkit/mmtk/java/src/org/vmmagic/unboxed/ExtentArray.java
deleted file mode 100644
index 81c663a..0000000
--- a/vmkit/mmtk/java/src/org/vmmagic/unboxed/ExtentArray.java
+++ /dev/null
@@ -1,42 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Common Public License (CPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/cpl1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.vmmagic.unboxed;
-
-public final class ExtentArray {
-
- private final Extent[] data;
-
- private ExtentArray(int size) {
- data = new Extent[size];
- Extent zero = Extent.zero();
- for(int i=0; i<size;i++) {
- data[i] = zero;
- }
- }
-
- public static ExtentArray create(int size) {
- return new ExtentArray(size);
- }
-
- public Extent get(int index) {
- return data[index];
- }
-
- public void set(int index, Extent v) {
- data[index] = v;
- }
-
- public int length() {
- return data.length;
- }
-}
diff --git a/vmkit/mmtk/java/src/org/vmmagic/unboxed/ObjectReference.java b/vmkit/mmtk/java/src/org/vmmagic/unboxed/ObjectReference.java
deleted file mode 100644
index 9d0072e..0000000
--- a/vmkit/mmtk/java/src/org/vmmagic/unboxed/ObjectReference.java
+++ /dev/null
@@ -1,72 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Common Public License (CPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/cpl1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.vmmagic.unboxed;
-
-import org.vmmagic.Unboxed;
-
-/**
- * The object reference type is used by the runtime system and collector to
- * represent a type that holds a reference to a single object.
- * We use a separate type instead of the Java Object type for coding clarity,
- * to make a clear distinction between objects the VM is written in, and
- * objects that the VM is managing. No operations that can not be completed in
- * pure Java should be allowed on Object.
- */
-@Unboxed
-public final class ObjectReference {
-
- /**
- * The object field.
- */
- @SuppressWarnings("unused")
- private Object data;
-
- /**
- * Convert from an object to a reference.
- * @param obj The object
- * @return The corresponding reference
- */
- public static ObjectReference fromObject(Object obj) {
- return null;
- }
-
- /**
- * Return a null reference
- */
- public static ObjectReference nullReference() {
- return null;
- }
-
- /**
- * Convert from an reference to an object. Note: this is a JikesRVM
- * specific extension to vmmagic.
- * @return The object
- */
- public Object toObject() {
- return null;
- }
-
- /**
- * Get a heap address for the object.
- */
- public Address toAddress() {
- return null;
- }
-
- /**
- * Is this a null reference?
- */
- public boolean isNull() {
- return false;
- }
-}
diff --git a/vmkit/mmtk/java/src/org/vmmagic/unboxed/ObjectReferenceArray.java b/vmkit/mmtk/java/src/org/vmmagic/unboxed/ObjectReferenceArray.java
deleted file mode 100644
index 1844fb2..0000000
--- a/vmkit/mmtk/java/src/org/vmmagic/unboxed/ObjectReferenceArray.java
+++ /dev/null
@@ -1,42 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Common Public License (CPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/cpl1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.vmmagic.unboxed;
-
-public final class ObjectReferenceArray {
-
- private final ObjectReference[] data;
-
- private ObjectReferenceArray(int size) {
- data = new ObjectReference[size];
- ObjectReference nullRef = ObjectReference.nullReference();
- for(int i=0; i<size;i++) {
- data[i] = nullRef;
- }
- }
-
- public static ObjectReferenceArray create(int size) {
- return new ObjectReferenceArray(size);
- }
-
- public ObjectReference get(int index) {
- return data[index];
- }
-
- public void set(int index, ObjectReference v) {
- data[index] = v;
- }
-
- public int length() {
- return data.length;
- }
-}
diff --git a/vmkit/mmtk/java/src/org/vmmagic/unboxed/Offset.java b/vmkit/mmtk/java/src/org/vmmagic/unboxed/Offset.java
deleted file mode 100644
index b52c47a..0000000
--- a/vmkit/mmtk/java/src/org/vmmagic/unboxed/Offset.java
+++ /dev/null
@@ -1,97 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Common Public License (CPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/cpl1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.vmmagic.unboxed;
-
-import org.vmmagic.Unboxed;
-import org.vmmagic.pragma.RawStorage;
-
-/**
- * To be commented
- */
-@Unboxed
-@RawStorage(lengthInWords = true, length = 1)
-public final class Offset {
-
- public static Offset fromIntSignExtend(int address) {
- return null;
- }
-
- public static Offset fromIntZeroExtend(int address) {
- return null;
- }
-
- public static Offset zero() {
- return null;
- }
-
- public static Offset max() {
- return null;
- }
-
- public int toInt() {
- return 0;
- }
-
- public long toLong() {
- return 0L;
- }
-
- public Word toWord() {
- return null;
- }
-
- public Offset plus(int byteSize) {
- return null;
- }
-
- public Offset minus(int byteSize) {
- return null;
- }
-
- public Offset minus(Offset off2) {
- return null;
- }
-
- public boolean EQ(Offset off2) {
- return false;
- }
-
- public boolean NE(Offset off2) {
- return false;
- }
-
- public boolean sLT(Offset off2) {
- return false;
- }
-
- public boolean sLE(Offset off2) {
- return false;
- }
-
- public boolean sGT(Offset off2) {
- return false;
- }
-
- public boolean sGE(Offset off2) {
- return false;
- }
-
- public boolean isZero() {
- return false;
- }
-
- public boolean isMax() {
- return false;
- }
-}
-
diff --git a/vmkit/mmtk/java/src/org/vmmagic/unboxed/OffsetArray.java b/vmkit/mmtk/java/src/org/vmmagic/unboxed/OffsetArray.java
deleted file mode 100644
index ccaa51b..0000000
--- a/vmkit/mmtk/java/src/org/vmmagic/unboxed/OffsetArray.java
+++ /dev/null
@@ -1,42 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Common Public License (CPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/cpl1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.vmmagic.unboxed;
-
-public final class OffsetArray {
-
- private final Offset[] data;
-
- private OffsetArray(int size) {
- data = new Offset[size];
- Offset zero = Offset.zero();
- for(int i=0; i<size;i++) {
- data[i] = zero;
- }
- }
-
- public static OffsetArray create(int size) {
- return new OffsetArray(size);
- }
-
- public Offset get(int index) {
- return data[index];
- }
-
- public void set(int index, Offset v) {
- data[index] = v;
- }
-
- public int length() {
- return data.length;
- }
-}
diff --git a/vmkit/mmtk/java/src/org/vmmagic/unboxed/Word.java b/vmkit/mmtk/java/src/org/vmmagic/unboxed/Word.java
deleted file mode 100644
index 03f0cef..0000000
--- a/vmkit/mmtk/java/src/org/vmmagic/unboxed/Word.java
+++ /dev/null
@@ -1,319 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Common Public License (CPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/cpl1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.vmmagic.unboxed;
-
-import org.vmmagic.Unboxed;
-import org.vmmagic.pragma.RawStorage;
-
-/**
- * (Mistakes in) comments by Robin Garner
- * @see Address
- */
-@Unboxed
-@RawStorage(lengthInWords = true, length = 1)
-public final class Word {
-
- /**
- * Convert an into to a word. On 64-bit machines, sign-extend the
- * high order bit.
- *
- * @param val
- * @return A word instance whose value is val, sign-extended on 64 bit machines
- */
- public static Word fromIntSignExtend(int val) {
- return null;
- }
-
- /**
- * Convert an int to a word. On 64-bit machines, zero-extend the
- * high order bit.
- *
- * @param val
- * @return A word instance whose value is val, zero-extended on 64 bit machines
- */
- public static Word fromIntZeroExtend(int val) {
- return null;
- }
-
- /**
- * Convert a long to a word. On 64-bit this is a no-op.
- * TODO document behaviour on 32-bit. Truncate ?
- *
- * @param val
- * @return A word instance whose value is val on 32 bit machine this truncates the upper 32 bits.
- */
- public static Word fromLong(long val) {
- return null;
- }
-
- /**
- * The Word constant 0.
- * Equivalent to Word.fromIntSignExtend(0), but more readable.
- *
- * @return the Word constant 0.
- */
- public static Word zero() {
- return null;
- }
-
- /**
- * The Word constant 1.
- * Equivalent to Word.fromIntSignExtend(1), but more readable.
- *
- * @return the Word constant 1.
- */
- public static Word one() {
- return null;
- }
-
- /**
- * The maximum representable Word value. Words are unsigned, so this is
- * a word full of 1s, 32/64-bit safe.
- *
- * @return the maximum representable Word value
- */
- public static Word max() {
- return null;
- }
-
- /**
- * Type-cast to an int, truncating on 64-bit platforms.
- *
- * @return an int, with the same value as the word on 32 bit platforms; truncates on 64 bit platforms.
- */
- public int toInt() {
- return 0;
- }
-
- /**
- * Type-cast to a long, zero-extending on a 32-bit platform.
- * @return a long, with the same value as the word (zero extends on 32 bit platforms).
- */
- public long toLong() {
- return 0L;
- }
-
- /** Type-cast to an address. */
- public Address toAddress() {
- return null;
- }
-
- /** Type-cast to an offset */
- public Offset toOffset() {
- return null;
- }
-
- /** Type-cast to an extent */
- public Extent toExtent() {
- return null;
- }
-
- /**
- * Add two words
- *
- * @param w2
- * @return The word whose value is this+w2
- */
- public Word plus(Word w2) {
- return null;
- }
-
- /**
- * Add an offset to a word
- * @param w2
- * @return The word whose value is this+w2
- */
- public Word plus(Offset w2) {
- return null;
- }
-
- /**
- * Add an extent to a word
- * @param w2
- * @return The word whose value is this+w2
- */
- public Word plus(Extent w2) {
- return null;
- }
-
- /**
- * Subtract two words
- * @param w2
- * @return The word whose value is this-w2
- */
- public Word minus(Word w2) {
- return null;
- }
-
- /**
- * Subtract an offset from a word
- * @param w2
- * @return The word whose value is this-w2
- */
- public Word minus(Offset w2) {
- return null;
- }
-
- /**
- * Subtract an extent from a word.
- * @param w2
- * @return The word whose value is this-w2
- */
- public Word minus(Extent w2) {
- return null;
- }
-
- /**
- * Test for zero. Equivalent to .EQ(Word.zero())
- * @return return true if this is equal to Word.zero(), false otherwise
- */
- public boolean isZero() {
- return false;
- }
-
- /**
- * Test for zero. Equivalent to .EQ(Word.max())
- * @return true if this is equal to Word.max(), false otherwise
- */
- public boolean isMax() {
- return false;
- }
-
- /**
- * Less-than comparison
- * @param addr2
- * @return true if this <code>Word</code> instance is <i>less than</i> <code>addr2</code>
- */
- public boolean LT(Word addr2) {
- return false;
- }
-
- /**
- * Less-than or equal comparison
- * @param w2
- * @return true if this <code>Word</code> instance is <i>less than or equal to</i> <code>w2</code>
- */
- public boolean LE(Word w2) {
- return false;
- }
-
- /**
- * Greater-than comparison
- * @param w2
- * @return true if this <code>Word</code> instance is <i>greater than</i> <code>w2</code>
- */
- public boolean GT(Word w2) {
- return false;
- }
-
- /**
- * Greater-than or equal comparison
- * @param w2
- * @return true if this <code>Word</code> instance is <i>greater than or equal to</i> <code>w2</code>
- */
- public boolean GE(Word w2) {
- return false;
- }
-
- /**
- * Equality comparison
- * @param w2
- * @return true if this <code>Word</code> instance is <i>equal to</i> <code>w2</code>
- */
- public boolean EQ(Word w2) {
- return false;
- }
-
- /**
- * Not-equal comparison
- * @param w2
- * @return true if this <code>Word</code> instance is <i>not equal to</i> <code>w2</code>
- */
- public boolean NE(Word w2) {
- return false;
- }
-
- /**
- * Bit-wise and of two words.
- * @param w2
- * @return The word whose value is the bitwise and of this and w2
- */
- public Word and(Word w2) {
- return null;
- }
-
- /**
- * Bit-wise or of two words.
- * @param w2
- * @return The word whose value is the bitwise not of this and w2
- */
- public Word or(Word w2) {
- return null;
- }
-
- /**
- * Bit-wise complement of a word.
- * @return the bitwise complement of this
- */
- public Word not() {
- return null;
- }
-
- /**
- * Bit-wise exclusive or of two words.
- * @param w2
- * @return The word whose value is the bitwise xor of this and w2
- */
- public Word xor(Word w2) {
- return null;
- }
-
- /**
- * Left-shift a word. Shifts of a size greater than the Word are undefined and
- * have an architecture and compiler specific behaviour. On Intel the shift
- * amount ignores the most significant bits, for example for a 32bit Word 1
- * << 32 == 1, the result will be 0 on PowerPC. Shifts may or may not be
- * combined by the compiler, this yields differing behaviour, for example for a
- * 32bit Word 1 <<32 may or may not equal 1 << 16 << 16.
- *
- * @param amt the amount to shift by
- * @return new Word shifted by the given amount
- */
- public Word lsh(int amt) {
- return null;
- }
-
- /**
- * Logical right-shift a word. Shifts of a size greater than the Word are undefined and
- * have an architecture and compiler specific behaviour see also {@link #lsh(int)}.
- *
- * @param amt the amount to shift by
- * @return new Word shifted by the given amount
- */
- public Word rshl(int amt) {
- return null;
- }
-
- /**
- * Arithmetic right-shift a word. Shifts of a size greater than the Word are undefined and
- * have an architecture and compiler specific behaviour see also {@link #lsh(int)}.
- * Arithmetic right-shift a word. Equivalent to the integer <code>>></code> operator
- *
- * @param amt the amount to shift by
- * @return new Word shifted by the given amount
- */
- public Word rsha(int amt) {
- return null;
- }
-}
-
diff --git a/vmkit/mmtk/java/src/org/vmmagic/unboxed/WordArray.java b/vmkit/mmtk/java/src/org/vmmagic/unboxed/WordArray.java
deleted file mode 100644
index fae1566..0000000
--- a/vmkit/mmtk/java/src/org/vmmagic/unboxed/WordArray.java
+++ /dev/null
@@ -1,42 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Common Public License (CPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/cpl1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.vmmagic.unboxed;
-
-public final class WordArray {
-
- private final Word[] data;
-
- private WordArray(int size) {
- data = new Word[size];
- Word zero = Word.zero();
- for(int i=0; i<size;i++) {
- data[i] = zero;
- }
- }
-
- public static WordArray create(int size) {
- return new WordArray(size);
- }
-
- public Word get(int index) {
- return data[index];
- }
-
- public void set(int index, Word v) {
- data[index] = v;
- }
-
- public int length() {
- return data.length;
- }
-}
diff --git a/vmkit/mmtk/java/src/org/vmutil/options/AddressOption.java b/vmkit/mmtk/java/src/org/vmutil/options/AddressOption.java
deleted file mode 100644
index a3329f6..0000000
--- a/vmkit/mmtk/java/src/org/vmutil/options/AddressOption.java
+++ /dev/null
@@ -1,80 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Common Public License (CPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/cpl1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.vmutil.options;
-
-import org.vmmagic.pragma.Uninterruptible;
-import org.vmmagic.unboxed.Address;
-
-/**
- * An option with a simple integer value.
- */
-public class AddressOption extends Option {
- // values
- protected Address defaultValue;
- protected Address value;
-
- /**
- * Create a new int option.
- *
- * @param set The option set this option belongs to.
- * @param name The space separated name for the option.
- * @param desc The purpose of the option
- * @param defaultValue The default value of the option.
- */
- protected AddressOption(OptionSet set, String name, String desc, Address defaultValue) {
- super(set, ADDRESS_OPTION, name, desc);
- this.value = this.defaultValue = defaultValue;
- }
-
- /**
- * Read the current value of the option.
- *
- * @return The option value.
- */
- @Uninterruptible
- public Address getValue() {
- return this.value;
- }
-
- /**
- * Read the default value of the option.
- *
- * @return The default value.
- */
- @Uninterruptible
- public Address getDefaultValue() {
- return this.defaultValue;
- }
-
- /**
- * Update the value of the option, echoing the change if the echoOptions
- * option is set. This method also calls the validate method to allow
- * subclasses to perform any required validation.
- *
- * @param value The new value for the option.
- */
- public void setValue(int value) {
- this.value = Address.fromIntZeroExtend(value);
- validate();
- set.logChange(this);
- }
-
- /**
- * Modify the default value of the option.
- *
- * @param value The new default value for the option.
- */
- public void setDefaultValue(Address value) {
- this.value = this.defaultValue = value;
- }
-}
diff --git a/vmkit/mmtk/java/src/org/vmutil/options/BooleanOption.java b/vmkit/mmtk/java/src/org/vmutil/options/BooleanOption.java
deleted file mode 100644
index a9b4dde..0000000
--- a/vmkit/mmtk/java/src/org/vmutil/options/BooleanOption.java
+++ /dev/null
@@ -1,79 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Common Public License (CPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/cpl1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.vmutil.options;
-
-import org.vmmagic.pragma.Uninterruptible;
-
-/**
- * Base class for boolean options.
- */
-public class BooleanOption extends Option {
- // values
- protected boolean defaultValue;
- protected boolean value;
-
- /**
- * Create a new boolean option.
- *
- * @param set The option set this option belongs to.
- * @param name The space separated name for the option.
- * @param desc The purpose of the option
- * @param defaultValue The default value of the option.
- */
- protected BooleanOption(OptionSet set, String name, String desc, boolean defaultValue) {
- super(set, BOOLEAN_OPTION, name, desc);
- this.value = this.defaultValue = defaultValue;
- }
-
- /**
- * Read the current value of the option.
- *
- * @return The option value.
- */
- @Uninterruptible
- public boolean getValue() {
- return this.value;
- }
-
- /**
- * Read the default value of the option.
- *
- * @return The default value.
- */
- @Uninterruptible
- public boolean getDefaultValue() {
- return this.defaultValue;
- }
-
- /**
- * Update the value of the option, echoing the change if the echoOptions
- * option is set. This method also calls the validate method to allow
- * subclasses to perform any required validation.
- *
- * @param value The new value for the option.
- */
- public void setValue(boolean value) {
- this.value = value;
- validate();
- set.logChange(this);
- }
-
- /**
- * Modify the default value of the option.
- *
- * @param value The new default value for the option.
- */
- public void setDefaultValue(boolean value) {
- this.value = this.defaultValue = value;
- }
-}
diff --git a/vmkit/mmtk/java/src/org/vmutil/options/EnumOption.java b/vmkit/mmtk/java/src/org/vmutil/options/EnumOption.java
deleted file mode 100644
index 2a06b18..0000000
--- a/vmkit/mmtk/java/src/org/vmutil/options/EnumOption.java
+++ /dev/null
@@ -1,142 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Common Public License (CPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/cpl1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.vmutil.options;
-
-import org.vmmagic.pragma.Uninterruptible;
-
-/**
- * An option that is a selection of several strings. The mapping
- * between strings and integers is determined using indexes into
- * a string array.
- *
- * Enumerations are case sensitive.
- */
-public class EnumOption extends Option {
- // values
- protected int defaultValue;
- protected int value;
- protected String[] values;
-
- /**
- * Create a new enumeration option.
- *
- * @param set The option set this option belongs to.
- * @param name The space separated name for the option.
- * @param description The purpose of the option.
- * @param values A mapping of int to string for the enum.
- * @param defaultValue The default value of the option.
- */
- protected EnumOption(OptionSet set, String name, String description, String[] values, String defaultValue) {
- super(set, ENUM_OPTION, name, description);
- this.values = values;
- this.value = this.defaultValue = findValue(defaultValue);
- }
-
- /**
- * Search for a string in the enumeration.
- *
- * @return The index of the passed string.
- */
- private int findValue(String string) {
- for (int i = 0; i < values.length; i++) {
- if (values[i].equals(string)) {
- return i;
- }
- }
- fail("Invalid Enumeration Value");
- return -1;
- }
-
- /**
- * Read the current value of the option.
- *
- * @return The option value.
- */
- @Uninterruptible
- public int getValue() {
- return this.value;
- }
-
- /**
- * Read the string for the current value of the option.
- *
- * @return The option value.
- */
- @Uninterruptible
- public String getValueString() {
- return this.values[this.value];
- }
-
- /**
- * Read the default value of the option.
- *
- * @return The default value.
- */
- @Uninterruptible
- public int getDefaultValue() {
- return this.defaultValue;
- }
-
- /**
- * Read the string for the default value of the option.
- *
- * @return The default value.
- */
- @Uninterruptible
- public String getDefaultValueString() {
- return this.values[this.defaultValue];
- }
-
- /**
- * Update the value of the option, echoing the change if the echoOptions
- * option is set. This method also calls the validate method to allow
- * subclasses to perform any required validation.
- *
- * @param value The new value for the option.
- */
- public void setValue(int value) {
- this.value = value;
- validate();
- set.logChange(this);
- }
-
- /**
- * Look up the value for a string and update the value of the option
- * accordingly, echoing the change if the echoOptions option is set.
- * This method also calls the validate method to allow subclasses to
- * perform any required validation.
- *
- * @param value The new value for the option.
- */
- public void setValue(String value) {
- setValue(findValue(value));
- }
-
- /**
- * Modify the default value of the option.
- *
- * @param value The new default value for the option.
- */
- public void setDefaultValue(String value) {
- this.value = this.defaultValue = findValue(value);
- }
-
- /**
- * Return the array of allowed enumeration values.
- *
- * @return The values array.
- */
- public String[] getValues() {
- return this.values;
- }
-}
diff --git a/vmkit/mmtk/java/src/org/vmutil/options/FloatOption.java b/vmkit/mmtk/java/src/org/vmutil/options/FloatOption.java
deleted file mode 100644
index 0a52154..0000000
--- a/vmkit/mmtk/java/src/org/vmutil/options/FloatOption.java
+++ /dev/null
@@ -1,79 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Common Public License (CPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/cpl1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.vmutil.options;
-
-import org.vmmagic.pragma.Uninterruptible;
-
-/**
- * An option that has a simple single precision floating point value.
- */
-public class FloatOption extends Option {
- // values
- protected float defaultValue;
- protected float value;
-
- /**
- * Create a new float option.
- *
- * @param set The option set this option belongs to.
- * @param name The space separated name for the option.
- * @param desc The purpose of the option
- * @param defaultValue The default value of the option.
- */
- protected FloatOption(OptionSet set, String name, String desc, float defaultValue) {
- super(set, FLOAT_OPTION, name, desc);
- this.value = this.defaultValue = defaultValue;
- }
-
- /**
- * Read the current value of the option.
- *
- * @return The option value.
- */
- @Uninterruptible
- public float getValue() {
- return this.value;
- }
-
- /**
- * Read the default value of the option
- *
- * @return The default value.
- */
- @Uninterruptible
- public float getDefaultValue() {
- return this.defaultValue;
- }
-
- /**
- * Update the value of the option, echoing the change if the echoOptions
- * option is set. This method also calls the validate method to allow
- * subclasses to perform any required validation.
- *
- * @param value The new value for the option.
- */
- public void setValue(float value) {
- this.value = value;
- validate();
- set.logChange(this);
- }
-
- /**
- * Modify the default value of the option.
- *
- * @param value The new default value for the option.
- */
- public void setDefaultValue(float value) {
- this.value = this.defaultValue = value;
- }
-}
diff --git a/vmkit/mmtk/java/src/org/vmutil/options/IntOption.java b/vmkit/mmtk/java/src/org/vmutil/options/IntOption.java
deleted file mode 100644
index 7f02042..0000000
--- a/vmkit/mmtk/java/src/org/vmutil/options/IntOption.java
+++ /dev/null
@@ -1,79 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Common Public License (CPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/cpl1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.vmutil.options;
-
-import org.vmmagic.pragma.Uninterruptible;
-
-/**
- * An option with a simple integer value.
- */
-public class IntOption extends Option {
- // values
- protected int defaultValue;
- protected int value;
-
- /**
- * Create a new int option.
- *
- * @param set The option set this option belongs to.
- * @param name The space separated name for the option.
- * @param desc The purpose of the option
- * @param defaultValue The default value of the option.
- */
- protected IntOption(OptionSet set, String name, String desc, int defaultValue) {
- super(set, INT_OPTION, name, desc);
- this.value = this.defaultValue = defaultValue;
- }
-
- /**
- * Read the current value of the option.
- *
- * @return The option value.
- */
- @Uninterruptible
- public int getValue() {
- return this.value;
- }
-
- /**
- * Read the default value of the option.
- *
- * @return The default value.
- */
- @Uninterruptible
- public int getDefaultValue() {
- return this.defaultValue;
- }
-
- /**
- * Update the value of the option, echoing the change if the echoOptions
- * option is set. This method also calls the validate method to allow
- * subclasses to perform any required validation.
- *
- * @param value The new value for the option.
- */
- public void setValue(int value) {
- this.value = value;
- validate();
- set.logChange(this);
- }
-
- /**
- * Modify the default value of the option.
- *
- * @param value The new default value for the option.
- */
- public void setDefaultValue(int value) {
- this.value = this.defaultValue = value;
- }
-}
diff --git a/vmkit/mmtk/java/src/org/vmutil/options/MicrosecondsOption.java b/vmkit/mmtk/java/src/org/vmutil/options/MicrosecondsOption.java
deleted file mode 100644
index 2413db2..0000000
--- a/vmkit/mmtk/java/src/org/vmutil/options/MicrosecondsOption.java
+++ /dev/null
@@ -1,101 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Common Public License (CPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/cpl1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.vmutil.options;
-
-import org.vmmagic.pragma.Uninterruptible;
-
-/**
- * A time option that stores values at a microsecond granularity.
- */
-public class MicrosecondsOption extends Option {
- // values
- protected int defaultValue;
- protected int value;
-
- /**
- * Create a new microsecond option.
- *
- * @param set The option set this option belongs to.
- * @param name The space separated name for the option.
- * @param desc The purpose of the option
- * @param defaultUs The default value of the option (usec).
- */
- protected MicrosecondsOption(OptionSet set, String name, String desc, int defaultUs) {
- super(set, MICROSECONDS_OPTION, name, desc);
- this.value = this.defaultValue = defaultUs;
- }
-
- /**
- * Read the current value of the option in microseconds.
- *
- * @return The option value.
- */
- @Uninterruptible
- public int getMicroseconds() {
- return this.value;
- }
-
- /**
- * Read the current value of the option in milliseconds.
- *
- * @return The option value.
- */
- @Uninterruptible
- public int getMilliseconds() {
- return this.value / 1000;
- }
-
- /**
- * Read the default value of the option in microseconds.
- *
- * @return The default value.
- */
- @Uninterruptible
- public int getDefaultMicroseconds() {
- return this.defaultValue;
- }
-
- /**
- * Read the default value of the option in milliseconds.
- *
- * @return The default value.
- */
- @Uninterruptible
- public int getDefaultMilliseconds() {
- return this.defaultValue / 1000;
- }
-
- /**
- * Update the value of the option, echoing the change if the echoOptions
- * option is set. An error occurs if the value is negative, and then the
- * validate method is called to allow subclasses to perform any additional
- * validation.
- *
- * @param value The new value for the option.
- */
- public void setMicroseconds(int value) {
- failIf(value < 0, "Unreasonable " + this.getName() + " value");
- this.value = value;
- validate();
- set.logChange(this);
- }
-
- /**
- * Modify the default value of the option.
- *
- * @param value The new default value for the option.
- */
- public void setDefaultMicrosends(int value) {
- this.value = this.defaultValue = value;
- }
-}
diff --git a/vmkit/mmtk/java/src/org/vmutil/options/Option.java b/vmkit/mmtk/java/src/org/vmutil/options/Option.java
deleted file mode 100644
index 50339ce..0000000
--- a/vmkit/mmtk/java/src/org/vmutil/options/Option.java
+++ /dev/null
@@ -1,176 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Common Public License (CPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/cpl1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.vmutil.options;
-
-/**
- * The abstract base class for all options. This class also has
- * the static interfaces to access the options system to set
- * option values.
- *
- * All options within the system should have a unique name. No
- * two options shall have a name that is the same when a case
- * insensitive comparison between the names with spaces removed
- * is performed. Only basic alphanumeric characters and spaces
- * are allowed.
- *
- * The VM is required to provide a one way mapping function that
- * takes the name and creates a VM style name, such as mapping
- * "No Finalizer" to noFinalizer. The VM may not remove any letters
- * when performing this mapping but may remove spaces and change
- * the case of any character.
- */
-public abstract class Option {
- // Option types
- public static final int BOOLEAN_OPTION = 1;
- public static final int STRING_OPTION = 2;
- public static final int ENUM_OPTION = 3;
- public static final int INT_OPTION = 4;
- public static final int PAGES_OPTION = 6;
- public static final int MICROSECONDS_OPTION = 7;
- public static final int FLOAT_OPTION = 8;
- public static final int ADDRESS_OPTION = 9;
-
- /**
- * The possible output formats
- */
- public static final int READABLE = 0;
- public static final int RAW = 1;
- public static final int XML = 2;
-
- // Per option values
- private int type;
- private String name;
- private String description;
- private String key;
- private Option next;
-
- protected OptionSet set;
-
- /**
- * Construct a new option. This also calls the VM to map the option's
- * name into a unique option key and links it onto the option list.
- *
- * @param set The option set this option belongs to.
- * @param type The option type as defined in this class.
- * @param name The unique name of the option.
- * @param description A short description of the option and purpose.
- */
- protected Option(OptionSet set, int type, String name, String description) {
- this.type = type;
- this.name = name;
- this.description = description;
- this.set = set;
- this.key = set.register(this, name);
- }
-
- /**
- * Return the VM determined key for an option
- *
- * @return The key.
- */
- public String getKey() {
- return this.key;
- }
-
- /**
- * Update the next pointer in the Option chain.
- */
- void setNext(Option o) {
- next = o;
- }
-
- /**
- * Return the next option in the linked list.
- *
- * @return The next option or null if this is the last option.
- */
- public Option getNext() {
- return this.next;
- }
-
- /**
- * Return the name for the option.
- *
- * @return The option name.
- */
- public String getName() {
- return this.name;
- }
-
- /**
- * Return the option description.
- *
- * @return The option description.
- */
- public String getDescription() {
- return this.description;
- }
-
- /**
- * Return the type of the option.
- *
- * @return The option type.
- */
- public int getType() {
- return this.type;
- }
-
- /**
- * This is a validation method that can be implemented by leaf option
- * classes to provide additional validation. This should not be implemented
- * at other levels within the heirarchy to avoid confusion. The validate
- * method works against the current value of the option (post-set).
- */
- protected void validate() {}
-
- /**
- * A fatal error occurred during the setting of an option. This method
- * calls into the VM and is required to cause the system to stop.
- *
- * @param message The error message associated with the failure.
- */
- protected void fail(String message) {
- set.fail(this, message);
- }
-
- /**
- * Fail if a specified condition is met.
- *
- * @param condition The condition that indicates failure.
- * @param message The error message associated with the failure.
- */
- protected void failIf(boolean condition, String message) {
- if (condition) set.fail(this, message);
- }
-
- /**
- * A non-fatal error occurred during the setting of an option. This method
- * calls into the VM and shall not cause the system to stop.
- *
- * @param message The message associated with the warning.
- */
- protected void warn(String message) {
- set.warn(this, message);
- }
-
- /**
- * Warn if a specified condition is met.
- *
- * @param condition The condition that indicates warning.
- * @param message The message associated with the warning.
- */
- protected void warnIf(boolean condition, String message) {
- if (condition) set.warn(this, message);
- }
-}
-
diff --git a/vmkit/mmtk/java/src/org/vmutil/options/OptionSet.java b/vmkit/mmtk/java/src/org/vmutil/options/OptionSet.java
deleted file mode 100644
index 56218c6..0000000
--- a/vmkit/mmtk/java/src/org/vmutil/options/OptionSet.java
+++ /dev/null
@@ -1,203 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Common Public License (CPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/cpl1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.vmutil.options;
-
-import org.vmmagic.pragma.Uninterruptible;
-import org.vmmagic.unboxed.*;
-
-/**
- * The abstract base class for all option sets.
- *
- * Concrete instantiations of this class include logic
- *
- * All options within the system should have a unique name. No
- * two options shall have a name that is the same when a case
- * insensitive comparison between the names with spaces removed
- * is performed. Only basic alphanumeric characters and spaces
- * are allowed.
- *
- * The VM is required to provide a one way mapping function that
- * takes the name and creates a VM style name, such as mapping
- * "No Finalizer" to noFinalizer. The VM may not remove any letters
- * when performing this mapping but may remove spaces and change
- * the case of any character.
- */
-public abstract class OptionSet {
- private Option head;
- private Option tail;
- private boolean loggingChanges;
-
- /**
- * Initialize the option set so that options can be created.
- */
- protected OptionSet() {
- head = null;
- tail = null;
- loggingChanges = false;
- }
-
- /**
- * Register the option to this set, computing its key in the process.
- *
- * @param o The option to register.
- */
- final String register(Option o, String name) {
- if (tail == null) {
- tail = head = o;
- } else {
- tail.setNext(o);
- tail = o;
- }
- return computeKey(name);
- }
-
- /**
- * Using the VM determined key, look up the corresponding option,
- * or return null if an option can not be found.
- *
- * @param key The (unique) option key.
- * @return The option, or null.
- */
- public final Option getOption(String key) {
- Option o = getFirst();
- while (o != null) {
- if (o.getKey().equals(key)) {
- return o;
- }
- o = o.getNext();
- }
- return null;
- }
-
- /**
- * Return the first option. This can be used with the getNext method to
- * iterate through the options.
- *
- * @return The first option, or null if no options exist.
- */
- public final Option getFirst() {
- return head;
- }
-
- public void logChange(Option o) {
- if (loggingChanges) {
- logString("Option Update: ");
- log(o);
- }
- }
-
- /**
- * Log the option value in plain text.
- *
- * @param o The option to log.
- */
- public void log(Option o) {
- logString("Option '");
- logString(o.getKey());
- logString("' = ");
- logValue(o, false);
- logNewLine();
- }
-
- /**
- * Log the option value in Xml.
- *
- * @param o The option to log.
- */
- public void logXml(Option o) {
- logString("<option name=\"");
- logString(o.getKey());
- logString("\" value=\"");
- logValue(o, true);
- logString("\"/>");
- logNewLine();
- }
-
- /**
- * Log the option values in Xml.
- */
- public void logXml() {
- logString("<options>");
- logNewLine();
-
- for(Option o = getFirst(); o != null; o = o.getNext()) {
- logXml(o);
- }
-
- logString("</options>");
- logNewLine();
- }
-
- /**
- * Format and log an option value.
- *
- * @param o The option.
- * @param forXml Is this part of xml output?
- */
- protected abstract void logValue(Option o, boolean forXml);
-
- /**
- * Log a string.
- */
- protected abstract void logString(String s);
-
- /**
- * Print a new line.
- */
- protected abstract void logNewLine();
-
- /**
- * Determine the VM specific key for a given option name. Option names are
- * space delimited with capitalised words (e.g. "GC Verbosity Level").
- *
- * @param name The option name.
- * @return The VM specific key.
- */
- protected abstract String computeKey(String name);
-
- /**
- * A non-fatal error occurred during the setting of an option. This method
- * calls into the VM and shall not cause the system to stop.
- *
- * @param o The responsible option.
- * @param message The message associated with the warning.
- */
- protected abstract void warn(Option o, String message);
-
- /**
- * A fatal error occurred during the setting of an option. This method
- * calls into the VM and is required to cause the system to stop.
- *
- * @param o The responsible option.
- * @param message The error message associated with the failure.
- */
- protected abstract void fail(Option o, String message);
-
- /**
- * Convert bytes into pages, rounding up if necessary.
- *
- * @param bytes The number of bytes.
- * @return The corresponding number of pages.
- */
- @Uninterruptible
- protected abstract int bytesToPages(Extent bytes);
-
- /**
- * Convert from pages into bytes.
- * @param pages the number of pages.
- * @return The corresponding number of bytes.
- */
- @Uninterruptible
- protected abstract Extent pagesToBytes(int pages);
-}
-
diff --git a/vmkit/mmtk/java/src/org/vmutil/options/PagesOption.java b/vmkit/mmtk/java/src/org/vmutil/options/PagesOption.java
deleted file mode 100644
index 4d790b5..0000000
--- a/vmkit/mmtk/java/src/org/vmutil/options/PagesOption.java
+++ /dev/null
@@ -1,114 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Common Public License (CPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/cpl1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.vmutil.options;
-
-import org.vmmagic.pragma.Uninterruptible;
-import org.vmmagic.unboxed.Extent;
-
-/**
- * A memory option that stores values as a whole number of pages.
- */
-public class PagesOption extends Option {
- // values
- protected int defaultValue;
- protected int value;
-
- /**
- * Create a new pages option.
- *
- * @param set The option set this option belongs to.
- * @param name The space separated name for the option.
- * @param desc The purpose of the option
- * @param defaultPages The default value of the option.
- */
- protected PagesOption(OptionSet set, String name, String desc, int defaultPages) {
- super(set, PAGES_OPTION, name, desc);
- this.value = this.defaultValue = defaultPages;
- }
-
- /**
- * Read the current value of the option in pages.
- *
- * @return The option value.
- */
- @Uninterruptible
- public int getPages() {
- return this.value;
- }
-
- /**
- * Read the current value of the option in bytes.
- *
- * @return The option value.
- */
- @Uninterruptible
- public Extent getBytes() {
- return set.pagesToBytes(this.value);
- }
-
- /**
- * Read the default value of the option in bytes.
- *
- * @return The default value.
- */
- @Uninterruptible
- public Extent getDefaultBytes() {
- return set.pagesToBytes(this.defaultValue);
- }
-
- /**
- * Read the default value of the option in pages.
- *
- * @return The default value.
- */
- @Uninterruptible
- public int getDefaultPages() {
- return this.defaultValue;
- }
-
- /**
- * Update the value of the option, echoing the change if logChanges is set.
- * A warning is raised if the value is not a whole multiple of pages, and
- * then the validate method is called to allow subclasses to perform any
- * additional validation.
- *
- * @param value The new value for the option.
- */
- public void setBytes(Extent value) {
- int pages = set.bytesToPages(value);
- warnIf(value.NE(set.pagesToBytes(pages)), "Value rounded up to a whole number of pages");
- setPages(pages);
- }
-
- /**
- * Update the value of the option, echoing the change if logChanges is set.
- * The validate method is called to allow subclasses to perform any additional
- * validation.
- *
- * @param pages The new value for the option.
- */
- public void setPages(int pages) {
- this.value = pages;
- validate();
- set.logChange(this);
- }
-
- /**
- * Modify the default value of the option.
- *
- * @param value The new default value for the option.
- */
- public void setDefaultPages(int value) {
- this.value = this.defaultValue = value;
- }
-}
diff --git a/vmkit/mmtk/java/src/org/vmutil/options/StringOption.java b/vmkit/mmtk/java/src/org/vmutil/options/StringOption.java
deleted file mode 100644
index 6b58aee..0000000
--- a/vmkit/mmtk/java/src/org/vmutil/options/StringOption.java
+++ /dev/null
@@ -1,79 +0,0 @@
-/*
- * This file is part of the Jikes RVM project (http://jikesrvm.org).
- *
- * This file is licensed to You under the Common Public License (CPL);
- * You may not use this file except in compliance with the License. You
- * may obtain a copy of the License at
- *
- * http://www.opensource.org/licenses/cpl1.0.php
- *
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.
- */
-package org.vmutil.options;
-
-import org.vmmagic.pragma.Uninterruptible;
-
-/**
- * An option that has a simple string value.
- */
-public class StringOption extends Option {
- // values
- protected String defaultValue;
- protected String value;
-
- /**
- * Create a new string option.
- *
- * @param set The option set this option belongs to.
- * @param name The space separated name for the option.
- * @param desc The purpose of the option
- * @param defaultValue The default value of the option.
- */
- protected StringOption(OptionSet set, String name, String desc, String defaultValue) {
- super(set, STRING_OPTION, name, desc);
- this.value = this.defaultValue = defaultValue;
- }
-
- /**
- * Read the current value of the option.
- *
- * @return The option value.
- */
- @Uninterruptible
- public String getValue() {
- return this.value;
- }
-
- /**
- * Read the default value of the option
- *
- * @return The default value.
- */
- @Uninterruptible
- public String getDefaultValue() {
- return this.defaultValue;
- }
-
- /**
- * Update the value of the option, echoing the change if the echoOptions
- * option is set. This method also calls the validate method to allow
- * subclasses to perform any required validation.
- *
- * @param value The new value for the option.
- */
- public void setValue(String value) {
- this.value = value;
- validate();
- set.logChange(this);
- }
-
- /**
- * Modify the default value of the option.
- *
- * @param value The new default value for the option.
- */
- public void setDefaultValue(String value) {
- this.value = this.defaultValue = value;
- }
-}
diff --git a/vmkit/mmtk/java/vmkit.properties b/vmkit/mmtk/java/vmkit.properties
deleted file mode 100644
index d1021a1..0000000
--- a/vmkit/mmtk/java/vmkit.properties
+++ /dev/null
@@ -1,10 +0,0 @@
-# This file is licensed to You under the Eclipse Public License (EPL);
-# You may not use this file except in compliance with the License. You
-# may obtain a copy of the License at
-#
-# http://www.opensource.org/licenses/eclipse-1.0.php
-#
-# See the COPYRIGHT.txt file distributed with this work for information
-# regarding copyright ownership.
-#
-mmtk.headerMarkBit = true
diff --git a/vmkit/mmtk/magic/LowerJavaRT.cpp b/vmkit/mmtk/magic/LowerJavaRT.cpp
deleted file mode 100644
index ee24d5f..0000000
--- a/vmkit/mmtk/magic/LowerJavaRT.cpp
+++ /dev/null
@@ -1,100 +0,0 @@
-//===-- LowerJavaRT.cpp - Remove references to RT classes and functions --===//
-//
-// The VMKit project
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#include "llvm/Constants.h"
-#include "llvm/Function.h"
-#include "llvm/Instructions.h"
-#include "llvm/LLVMContext.h"
-#include "llvm/Module.h"
-#include "llvm/Pass.h"
-#include "llvm/Support/CallSite.h"
-#include "llvm/Support/Compiler.h"
-#include "llvm/Support/Debug.h"
-#include "llvm/Support/raw_ostream.h"
-
-using namespace llvm;
-
-namespace {
-
- class LowerJavaRT : public ModulePass {
- public:
- static char ID;
- LowerJavaRT() : ModulePass(ID) { }
-
- virtual bool runOnModule(Module &M);
- private:
- };
- char LowerJavaRT::ID = 0;
- static RegisterPass<LowerJavaRT> X("LowerJavaRT",
- "Remove references to RT");
-
-bool LowerJavaRT::runOnModule(Module& M) {
- bool Changed = true;
-
- for (Module::iterator I = M.begin(), E = M.end(); I != E;) {
- Function& GV = *I;
- ++I;
- if (!strncmp(GV.getName().data(), "JnJVM_java", 10) ||
- !strncmp(GV.getName().data(), "java", 4)) {
- if (!strcmp(GV.getName().data(), "JnJVM_java_lang_String_charAt__I")) {
- Function* F = M.getFunction("MMTkCharAt");
- if (!F)
- F = Function::Create(GV.getFunctionType(),
- GlobalValue::ExternalLinkage, "MMTkCharAt", &M);
-
- GV.replaceAllUsesWith(F);
- } else if (!strcmp(GV.getName().data(), "JnJVM_java_lang_Object_getClass__")) {
- Function* F = M.getFunction("MMTkGetClass");
- if (!F)
- F = Function::Create(GV.getFunctionType(),
- GlobalValue::ExternalLinkage, "MMTkGetClass", &M);
- GV.replaceAllUsesWith(F);
- } else {
- GV.replaceAllUsesWith(Constant::getNullValue(GV.getType()));
- }
- GV.eraseFromParent();
- }
- }
-
- for (Module::global_iterator I = M.global_begin(), E = M.global_end();
- I != E;) {
- GlobalValue& GV = *I;
- ++I;
- if (!strncmp(GV.getName().data(), "JnJVM_java", 10) ||
- !strncmp(GV.getName().data(), "java", 4) ||
- !strncmp(GV.getName().data(), "JnJVM_gnu", 9) ||
- !strncmp(GV.getName().data(), "gnu", 3)) {
- GV.replaceAllUsesWith(Constant::getNullValue(GV.getType()));
- GV.eraseFromParent();
- }
- }
-
- // Replace gcmalloc with the allocator of MMTk objects in VMKit
- Function* F = M.getFunction("gcmalloc");
- Function* Ma = M.getFunction("AllocateMagicArray");
-
- Function* NewFunction =
- Function::Create(F->getFunctionType(), GlobalValue::ExternalLinkage,
- "MMTkMutatorAllocate", &M);
-
- F->replaceAllUsesWith(NewFunction);
- F->eraseFromParent();
-
- Ma->replaceAllUsesWith(NewFunction);
- Ma->eraseFromParent();
-
- return Changed;
-}
-
-
-ModulePass* createLowerJavaRT() {
- return new LowerJavaRT();
-}
-
-}
diff --git a/vmkit/mmtk/magic/LowerMagic.cpp b/vmkit/mmtk/magic/LowerMagic.cpp
deleted file mode 100644
index e62baab..0000000
--- a/vmkit/mmtk/magic/LowerMagic.cpp
+++ /dev/null
@@ -1,1267 +0,0 @@
-//===----- LowerConstantCalls.cpp - Changes arrayLength calls --------------===//
-//
-// JnJVM
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#include "llvm/Constants.h"
-#include "llvm/Function.h"
-#include "llvm/Instructions.h"
-#include "llvm/LLVMContext.h"
-#include "llvm/Module.h"
-#include "llvm/Pass.h"
-#include "llvm/Support/CallSite.h"
-#include "llvm/Support/Compiler.h"
-#include "llvm/Support/Debug.h"
-#include "llvm/Support/raw_ostream.h"
-
-#include <cstdio>
-
-using namespace llvm;
-
-namespace vmmagic {
-
- class LowerMagic : public FunctionPass {
- public:
- static char ID;
- LowerMagic() : FunctionPass(ID) { }
-
- virtual bool runOnFunction(Function &F);
- private:
- };
- char LowerMagic::ID = 0;
- static RegisterPass<LowerMagic> X("LowerMagic",
- "Lower magic calls");
-
-static const char* AddressClass = "JnJVM_org_vmmagic_unboxed_Address_";
-static const char* AddressZeroMethod = 0;
-static const char* AddressIsZeroMethod;
-static const char* AddressMaxMethod;
-static const char* AddressIsMaxMethod;
-static const char* AddressFromIntSignExtendMethod;
-static const char* AddressFromIntZeroExtendMethod;
-static const char* AddressFromLongMethod;
-static const char* AddressToObjectReferenceMethod;
-static const char* AddressToIntMethod;
-static const char* AddressToLongMethod;
-static const char* AddressToWordMethod;
-static const char* AddressPlusIntMethod;
-static const char* AddressPlusOffsetMethod;
-static const char* AddressPlusExtentMethod;
-static const char* AddressMinusIntMethod;
-static const char* AddressMinusOffsetMethod;
-static const char* AddressMinusExtentMethod;
-static const char* AddressDiffMethod;
-static const char* AddressLTMethod;
-static const char* AddressLEMethod;
-static const char* AddressGTMethod;
-static const char* AddressGEMethod;
-static const char* AddressEQMethod;
-static const char* AddressNEMethod;
-static const char* AddressPrefetchMethod;
-static const char* AddressLoadObjectReferenceMethod;
-static const char* AddressLoadObjectReferenceAtOffsetMethod;
-static const char* AddressLoadByteMethod;
-static const char* AddressLoadByteAtOffsetMethod;
-static const char* AddressLoadCharMethod;
-static const char* AddressLoadCharAtOffsetMethod;
-static const char* AddressLoadShortMethod;
-static const char* AddressLoadShortAtOffsetMethod;
-static const char* AddressLoadFloatMethod;
-static const char* AddressLoadFloatAtOffsetMethod;
-static const char* AddressLoadIntMethod;
-static const char* AddressLoadIntAtOffsetMethod;
-static const char* AddressLoadLongMethod;
-static const char* AddressLoadLongAtOffsetMethod;
-static const char* AddressLoadDoubleMethod;
-static const char* AddressLoadDoubleAtOffsetMethod;
-static const char* AddressLoadAddressMethod;
-static const char* AddressLoadAddressAtOffsetMethod;
-static const char* AddressLoadWordMethod;
-static const char* AddressLoadWordAtOffsetMethod;
-static const char* AddressStoreObjectReferenceMethod;
-static const char* AddressStoreObjectReferenceAtOffsetMethod;
-static const char* AddressStoreAddressMethod;
-static const char* AddressStoreAddressAtOffsetMethod;
-static const char* AddressStoreFloatMethod;
-static const char* AddressStoreFloatAtOffsetMethod;
-static const char* AddressStoreWordMethod;
-static const char* AddressStoreWordAtOffsetMethod;
-static const char* AddressStoreByteMethod;
-static const char* AddressStoreByteAtOffsetMethod;
-static const char* AddressStoreIntMethod;
-static const char* AddressStoreIntAtOffsetMethod;
-static const char* AddressStoreDoubleMethod;
-static const char* AddressStoreDoubleAtOffsetMethod;
-static const char* AddressStoreLongMethod;
-static const char* AddressStoreLongAtOffsetMethod;
-static const char* AddressStoreCharMethod;
-static const char* AddressStoreCharAtOffsetMethod;
-static const char* AddressStoreShortMethod;
-static const char* AddressStoreShortAtOffsetMethod;
-static const char* AddressPrepareWordMethod;
-static const char* AddressPrepareWordAtOffsetMethod;
-static const char* AddressPrepareObjectReferenceMethod;
-static const char* AddressPrepareObjectReferenceAtOffsetMethod;
-static const char* AddressPrepareAddressMethod;
-static const char* AddressPrepareAddressAtOffsetMethod;
-static const char* AddressPrepareIntMethod;
-static const char* AddressPrepareIntAtOffsetMethod;
-static const char* AddressAttemptIntMethod;
-static const char* AddressAttemptIntAtOffsetMethod;
-static const char* AddressAttemptWordMethod;
-static const char* AddressAttemptWordAtOffsetMethod;
-static const char* AddressAttemptObjectReferenceMethod;
-static const char* AddressAttemptObjectReferenceAtOffsetMethod;
-static const char* AddressAttemptAddressMethod;
-static const char* AddressAttemptAddressAtOffsetMethod;
-
-static const char* ExtentClass = "JnJVM_org_vmmagic_unboxed_Extent_";
-static const char* ExtentToWordMethod = 0;
-static const char* ExtentFromIntSignExtendMethod;
-static const char* ExtentFromIntZeroExtendMethod;
-static const char* ExtentZeroMethod;
-static const char* ExtentOneMethod;
-static const char* ExtentMaxMethod;
-static const char* ExtentToIntMethod;
-static const char* ExtentToLongMethod;
-static const char* ExtentPlusIntMethod;
-static const char* ExtentPlusExtentMethod;
-static const char* ExtentMinusIntMethod;
-static const char* ExtentMinusExtentMethod;
-static const char* ExtentLTMethod;
-static const char* ExtentLEMethod;
-static const char* ExtentGTMethod;
-static const char* ExtentGEMethod;
-static const char* ExtentEQMethod;
-static const char* ExtentNEMethod;
-
-static const char* ObjectReferenceClass =
- "JnJVM_org_vmmagic_unboxed_ObjectReference_";
-static const char* ObjectReferenceFromObjectMethod = 0;
-static const char* ObjectReferenceNullReferenceMethod;
-static const char* ObjectReferenceToObjectMethod;
-static const char* ObjectReferenceToAddressMethod;
-static const char* ObjectReferenceIsNullMethod;
-
-static const char* OffsetClass = "JnJVM_org_vmmagic_unboxed_Offset_";
-static const char* OffsetFromIntSignExtendMethod = 0;
-static const char* OffsetFromIntZeroExtendMethod;
-static const char* OffsetZeroMethod;
-static const char* OffsetMaxMethod;
-static const char* OffsetToIntMethod;
-static const char* OffsetToLongMethod;
-static const char* OffsetToWordMethod;
-static const char* OffsetPlusIntMethod;
-static const char* OffsetMinusIntMethod;
-static const char* OffsetMinusOffsetMethod;
-static const char* OffsetEQMethod;
-static const char* OffsetNEMethod;
-static const char* OffsetSLTMethod;
-static const char* OffsetSLEMethod;
-static const char* OffsetSGTMethod;
-static const char* OffsetSGEMethod;
-static const char* OffsetIsZeroMethod;
-static const char* OffsetIsMaxMethod;
-
-static const char* WordClass = "JnJVM_org_vmmagic_unboxed_Word_";
-static const char* WordFromIntSignExtendMethod = 0;
-static const char* WordFromIntZeroExtendMethod;
-static const char* WordFromLongMethod;
-static const char* WordZeroMethod;
-static const char* WordOneMethod;
-static const char* WordMaxMethod;
-static const char* WordToIntMethod;
-static const char* WordToLongMethod;
-static const char* WordToAddressMethod;
-static const char* WordToOffsetMethod;
-static const char* WordToExtentMethod;
-static const char* WordPlusWordMethod;
-static const char* WordPlusOffsetMethod;
-static const char* WordPlusExtentMethod;
-static const char* WordMinusWordMethod;
-static const char* WordMinusOffsetMethod;
-static const char* WordMinusExtentMethod;
-static const char* WordIsZeroMethod;
-static const char* WordIsMaxMethod;
-static const char* WordLTMethod;
-static const char* WordLEMethod;
-static const char* WordGTMethod;
-static const char* WordGEMethod;
-static const char* WordEQMethod;
-static const char* WordNEMethod;
-static const char* WordAndMethod;
-static const char* WordOrMethod;
-static const char* WordNotMethod;
-static const char* WordXorMethod;
-static const char* WordLshMethod;
-static const char* WordRshlMethod;
-static const char* WordRshaMethod;
-
-static Function* CASPtr;
-static Function* CASInt;
-
-static const char* AddressArrayClass = "JnJVM_org_vmmagic_unboxed_AddressArray_";
-static const char* ExtentArrayClass = "JnJVM_org_vmmagic_unboxed_ExtentArray_";
-static const char* ObjectReferenceArrayClass = "JnJVM_org_vmmagic_unboxed_ObjectReferenceArray_";
-static const char* OffsetArrayClass = "JnJVM_org_vmmagic_unboxed_OffsetArray_";
-static const char* WordArrayClass = "JnJVM_org_vmmagic_unboxed_WordArray_";
-
-static const char* AddressArrayCreateMethod = "JnJVM_org_vmmagic_unboxed_AddressArray_create__I";
-static const char* ExtentArrayCreateMethod = "JnJVM_org_vmmagic_unboxed_ExtentArray_create__I";
-static const char* ObjectReferenceArrayCreateMethod = "JnJVM_org_vmmagic_unboxed_ObjectReferenceArray_create__I";
-static const char* OffsetArrayCreateMethod = "JnJVM_org_vmmagic_unboxed_OffsetArray_create__I";
-static const char* WordArrayCreateMethod = "JnJVM_org_vmmagic_unboxed_WordArray_create__I";
-
-static const char* AddressArrayGetMethod = "JnJVM_org_vmmagic_unboxed_AddressArray_get__I";
-static const char* ExtentArrayGetMethod = "JnJVM_org_vmmagic_unboxed_ExtentArray_get__I";
-static const char* ObjectReferenceArrayGetMethod = "JnJVM_org_vmmagic_unboxed_ObjectReferenceArray_get__I";
-static const char* OffsetArrayGetMethod = "JnJVM_org_vmmagic_unboxed_OffsetArray_get__I";
-static const char* WordArrayGetMethod = "JnJVM_org_vmmagic_unboxed_WordArray_get__I";
-
-static const char* AddressArraySetMethod = "JnJVM_org_vmmagic_unboxed_AddressArray_set__ILorg_vmmagic_unboxed_Address_2";
-static const char* ExtentArraySetMethod = "JnJVM_org_vmmagic_unboxed_ExtentArray_set__ILorg_vmmagic_unboxed_Extent_2";
-static const char* ObjectReferenceArraySetMethod = "JnJVM_org_vmmagic_unboxed_ObjectReferenceArray_set__ILorg_vmmagic_unboxed_ObjectReference_2";
-static const char* OffsetArraySetMethod = "JnJVM_org_vmmagic_unboxed_OffsetArray_set__ILorg_vmmagic_unboxed_Offset_2";
-static const char* WordArraySetMethod = "JnJVM_org_vmmagic_unboxed_WordArray_set__ILorg_vmmagic_unboxed_Word_2";
-
-static const char* AddressArrayLengthMethod = "JnJVM_org_vmmagic_unboxed_AddressArray_lenght__";
-static const char* ExtentArrayLengthMethod = "JnJVM_org_vmmagic_unboxed_ExtentArray_length__";
-static const char* ObjectReferenceArrayLengthMethod = "JnJVM_org_vmmagic_unboxed_ObjectReferenceArray_length__";
-static const char* OffsetArrayLengthMethod = "JnJVM_org_vmmagic_unboxed_OffsetArray_length__";
-static const char* WordArrayLengthMethod = "JnJVM_org_vmmagic_unboxed_WordArray_length__";
-
-
-
-static void initialiseFunctions(Module* M) {
- if (!AddressZeroMethod) {
- AddressZeroMethod = "JnJVM_org_vmmagic_unboxed_Address_zero__";
- AddressMaxMethod = "JnJVM_org_vmmagic_unboxed_Address_max__";
- AddressStoreObjectReferenceMethod = "JnJVM_org_vmmagic_unboxed_Address_store__Lorg_vmmagic_unboxed_ObjectReference_2";
- AddressLoadObjectReferenceMethod = "JnJVM_org_vmmagic_unboxed_Address_loadObjectReference__";
- AddressLoadAddressMethod = "JnJVM_org_vmmagic_unboxed_Address_loadAddress__";
- AddressLoadWordMethod = "JnJVM_org_vmmagic_unboxed_Address_loadWord__";
- AddressDiffMethod = "JnJVM_org_vmmagic_unboxed_Address_diff__Lorg_vmmagic_unboxed_Address_2";
- AddressPlusOffsetMethod = "JnJVM_org_vmmagic_unboxed_Address_plus__Lorg_vmmagic_unboxed_Offset_2";
- AddressStoreAddressMethod = "JnJVM_org_vmmagic_unboxed_Address_store__Lorg_vmmagic_unboxed_Address_2";
- AddressPlusIntMethod = "JnJVM_org_vmmagic_unboxed_Address_plus__I";
- AddressLTMethod = "JnJVM_org_vmmagic_unboxed_Address_LT__Lorg_vmmagic_unboxed_Address_2";
- AddressGEMethod = "JnJVM_org_vmmagic_unboxed_Address_GE__Lorg_vmmagic_unboxed_Address_2";
- AddressStoreWordMethod = "JnJVM_org_vmmagic_unboxed_Address_store__Lorg_vmmagic_unboxed_Word_2";
- AddressToObjectReferenceMethod = "JnJVM_org_vmmagic_unboxed_Address_toObjectReference__";
- AddressToWordMethod = "JnJVM_org_vmmagic_unboxed_Address_toWord__";
- AddressPrepareWordMethod = "JnJVM_org_vmmagic_unboxed_Address_prepareWord__";
- AddressAttemptWordAtOffsetMethod = "JnJVM_org_vmmagic_unboxed_Address_attempt__Lorg_vmmagic_unboxed_Word_2Lorg_vmmagic_unboxed_Word_2Lorg_vmmagic_unboxed_Offset_2";
- AddressPrepareWordAtOffsetMethod = "JnJVM_org_vmmagic_unboxed_Address_prepareWord__Lorg_vmmagic_unboxed_Offset_2";
- AddressLoadWordAtOffsetMethod = "JnJVM_org_vmmagic_unboxed_Address_loadWord__Lorg_vmmagic_unboxed_Offset_2";
- AddressStoreWordAtOffsetMethod = "JnJVM_org_vmmagic_unboxed_Address_store__Lorg_vmmagic_unboxed_Word_2Lorg_vmmagic_unboxed_Offset_2";
- AddressPlusExtentMethod = "JnJVM_org_vmmagic_unboxed_Address_plus__Lorg_vmmagic_unboxed_Extent_2";
- AddressIsZeroMethod = "JnJVM_org_vmmagic_unboxed_Address_isZero__";
- AddressStoreAddressAtOffsetMethod = "JnJVM_org_vmmagic_unboxed_Address_store__Lorg_vmmagic_unboxed_Address_2Lorg_vmmagic_unboxed_Offset_2";
- AddressGTMethod = "JnJVM_org_vmmagic_unboxed_Address_GT__Lorg_vmmagic_unboxed_Address_2";
- AddressLoadAddressAtOffsetMethod = "JnJVM_org_vmmagic_unboxed_Address_loadAddress__Lorg_vmmagic_unboxed_Offset_2";
- AddressEQMethod = "JnJVM_org_vmmagic_unboxed_Address_EQ__Lorg_vmmagic_unboxed_Address_2";
- AddressLoadObjectReferenceAtOffsetMethod = "JnJVM_org_vmmagic_unboxed_Address_loadObjectReference__Lorg_vmmagic_unboxed_Offset_2";
- AddressLEMethod = "JnJVM_org_vmmagic_unboxed_Address_LE__Lorg_vmmagic_unboxed_Address_2";
- AddressAttemptWordMethod = "JnJVM_org_vmmagic_unboxed_Address_attempt__Lorg_vmmagic_unboxed_Word_2Lorg_vmmagic_unboxed_Word_2";
- AddressNEMethod = "JnJVM_org_vmmagic_unboxed_Address_NE__Lorg_vmmagic_unboxed_Address_2";
- AddressToLongMethod = "JnJVM_org_vmmagic_unboxed_Address_toLong__";
- AddressMinusExtentMethod = "JnJVM_org_vmmagic_unboxed_Address_minus__Lorg_vmmagic_unboxed_Extent_2";
- AddressLoadShortAtOffsetMethod = "JnJVM_org_vmmagic_unboxed_Address_loadShort__Lorg_vmmagic_unboxed_Offset_2";
- AddressStoreShortAtOffsetMethod = "JnJVM_org_vmmagic_unboxed_Address_store__SLorg_vmmagic_unboxed_Offset_2";
- AddressLoadShortMethod = "JnJVM_org_vmmagic_unboxed_Address_loadShort__";
- AddressStoreShortMethod = "JnJVM_org_vmmagic_unboxed_Address_store__S";
- AddressLoadByteMethod = "JnJVM_org_vmmagic_unboxed_Address_loadByte__";
- AddressLoadIntMethod = "JnJVM_org_vmmagic_unboxed_Address_loadInt__";
- AddressStoreIntMethod = "JnJVM_org_vmmagic_unboxed_Address_store__I";
- AddressStoreByteMethod = "JnJVM_org_vmmagic_unboxed_Address_store__B";
- AddressLoadByteAtOffsetMethod = "JnJVM_org_vmmagic_unboxed_Address_loadByte__Lorg_vmmagic_unboxed_Offset_2";
- AddressMinusIntMethod = "JnJVM_org_vmmagic_unboxed_Address_minus__I";
- AddressLoadIntAtOffsetMethod = "JnJVM_org_vmmagic_unboxed_Address_loadInt__Lorg_vmmagic_unboxed_Offset_2";
- AddressStoreByteAtOffsetMethod = "JnJVM_org_vmmagic_unboxed_Address_store__BLorg_vmmagic_unboxed_Offset_2";
- AddressFromIntZeroExtendMethod = "JnJVM_org_vmmagic_unboxed_Address_fromIntZeroExtend__I";
- AddressToIntMethod = "JnJVM_org_vmmagic_unboxed_Address_toInt__";
-
- ExtentToWordMethod = "JnJVM_org_vmmagic_unboxed_Extent_toWord__";
- ExtentMinusExtentMethod = "JnJVM_org_vmmagic_unboxed_Extent_minus__Lorg_vmmagic_unboxed_Extent_2";
- ExtentPlusExtentMethod = "JnJVM_org_vmmagic_unboxed_Extent_plus__Lorg_vmmagic_unboxed_Extent_2";
- ExtentPlusIntMethod = "JnJVM_org_vmmagic_unboxed_Extent_plus__I";
- ExtentMinusIntMethod = "JnJVM_org_vmmagic_unboxed_Extent_minus__I";
- ExtentFromIntZeroExtendMethod = "JnJVM_org_vmmagic_unboxed_Extent_fromIntZeroExtend__I";
- ExtentFromIntSignExtendMethod = "JnJVM_org_vmmagic_unboxed_Extent_fromIntSignExtend__I";
- ExtentOneMethod = "JnJVM_org_vmmagic_unboxed_Extent_one__";
- ExtentNEMethod = "JnJVM_org_vmmagic_unboxed_Extent_NE__Lorg_vmmagic_unboxed_Extent_2";
- ExtentZeroMethod = "JnJVM_org_vmmagic_unboxed_Extent_zero__";
- ExtentToLongMethod = "JnJVM_org_vmmagic_unboxed_Extent_toLong__";
- ExtentToIntMethod = "JnJVM_org_vmmagic_unboxed_Extent_toInt__";
- ExtentEQMethod = "JnJVM_org_vmmagic_unboxed_Extent_EQ__Lorg_vmmagic_unboxed_Extent_2";
- ExtentGTMethod = "JnJVM_org_vmmagic_unboxed_Extent_GT__Lorg_vmmagic_unboxed_Extent_2";
- ExtentLTMethod = "JnJVM_org_vmmagic_unboxed_Extent_LT__Lorg_vmmagic_unboxed_Extent_2";
- ExtentMaxMethod = "JnJVM_org_vmmagic_unboxed_Extent_max__";
-
- ObjectReferenceFromObjectMethod = "JnJVM_org_vmmagic_unboxed_ObjectReference_fromObject__Ljava_lang_Object_2";
- ObjectReferenceToObjectMethod = "JnJVM_org_vmmagic_unboxed_ObjectReference_toObject__";
- ObjectReferenceNullReferenceMethod = "JnJVM_org_vmmagic_unboxed_ObjectReference_nullReference__";
- ObjectReferenceToAddressMethod = "JnJVM_org_vmmagic_unboxed_ObjectReference_toAddress__";
- ObjectReferenceIsNullMethod = "JnJVM_org_vmmagic_unboxed_ObjectReference_isNull__";
-
- WordOrMethod = "JnJVM_org_vmmagic_unboxed_Word_or__Lorg_vmmagic_unboxed_Word_2";
- WordRshlMethod = "JnJVM_org_vmmagic_unboxed_Word_rshl__I";
- WordToIntMethod = "JnJVM_org_vmmagic_unboxed_Word_toInt__";
- WordNotMethod = "JnJVM_org_vmmagic_unboxed_Word_not__";
- WordZeroMethod = "JnJVM_org_vmmagic_unboxed_Word_zero__";
- WordOneMethod = "JnJVM_org_vmmagic_unboxed_Word_one__";
- WordAndMethod = "JnJVM_org_vmmagic_unboxed_Word_and__Lorg_vmmagic_unboxed_Word_2";
- WordToAddressMethod = "JnJVM_org_vmmagic_unboxed_Word_toAddress__";
- WordLshMethod = "JnJVM_org_vmmagic_unboxed_Word_lsh__I";
- WordMinusWordMethod = "JnJVM_org_vmmagic_unboxed_Word_minus__Lorg_vmmagic_unboxed_Word_2";
- WordLTMethod = "JnJVM_org_vmmagic_unboxed_Word_LT__Lorg_vmmagic_unboxed_Word_2";
- WordPlusWordMethod = "JnJVM_org_vmmagic_unboxed_Word_plus__Lorg_vmmagic_unboxed_Word_2";
- WordLEMethod = "JnJVM_org_vmmagic_unboxed_Word_LE__Lorg_vmmagic_unboxed_Word_2";
- WordGEMethod = "JnJVM_org_vmmagic_unboxed_Word_GE__Lorg_vmmagic_unboxed_Word_2";
- WordEQMethod = "JnJVM_org_vmmagic_unboxed_Word_EQ__Lorg_vmmagic_unboxed_Word_2";
- WordNEMethod = "JnJVM_org_vmmagic_unboxed_Word_NE__Lorg_vmmagic_unboxed_Word_2";
- WordFromIntSignExtendMethod = "JnJVM_org_vmmagic_unboxed_Word_fromIntSignExtend__I";
- WordIsZeroMethod = "JnJVM_org_vmmagic_unboxed_Word_isZero__";
- WordXorMethod = "JnJVM_org_vmmagic_unboxed_Word_xor__Lorg_vmmagic_unboxed_Word_2";
- WordFromIntZeroExtendMethod = "JnJVM_org_vmmagic_unboxed_Word_fromIntZeroExtend__I";
- WordToExtentMethod = "JnJVM_org_vmmagic_unboxed_Word_toExtent__";
- WordMinusExtentMethod = "JnJVM_org_vmmagic_unboxed_Word_minus__Lorg_vmmagic_unboxed_Extent_2";
- WordToLongMethod = "JnJVM_org_vmmagic_unboxed_Word_toLong__";
- WordMaxMethod = "JnJVM_org_vmmagic_unboxed_Word_max__";
- WordToOffsetMethod = "JnJVM_org_vmmagic_unboxed_Word_toOffset__";
- WordGTMethod = "JnJVM_org_vmmagic_unboxed_Word_GT__Lorg_vmmagic_unboxed_Word_2";
-
-
- OffsetSLTMethod = "JnJVM_org_vmmagic_unboxed_Offset_sLT__Lorg_vmmagic_unboxed_Offset_2";
- OffsetFromIntSignExtendMethod = "JnJVM_org_vmmagic_unboxed_Offset_fromIntSignExtend__I";
- OffsetSGTMethod = "JnJVM_org_vmmagic_unboxed_Offset_sGT__Lorg_vmmagic_unboxed_Offset_2";
- OffsetPlusIntMethod = "JnJVM_org_vmmagic_unboxed_Offset_plus__I";
- OffsetZeroMethod = "JnJVM_org_vmmagic_unboxed_Offset_zero__";
- OffsetToWordMethod = "JnJVM_org_vmmagic_unboxed_Offset_toWord__";
- OffsetFromIntZeroExtendMethod = "JnJVM_org_vmmagic_unboxed_Offset_fromIntZeroExtend__I";
- OffsetSGEMethod = "JnJVM_org_vmmagic_unboxed_Offset_sGE__Lorg_vmmagic_unboxed_Offset_2";
- OffsetToIntMethod = "JnJVM_org_vmmagic_unboxed_Offset_toInt__";
- OffsetToLongMethod = "JnJVM_org_vmmagic_unboxed_Offset_toLong__";
- OffsetIsZeroMethod = "JnJVM_org_vmmagic_unboxed_Offset_isZero__";
- OffsetMinusIntMethod = "JnJVM_org_vmmagic_unboxed_Offset_minus__I";
- OffsetSLEMethod = "JnJVM_org_vmmagic_unboxed_Offset_sLE__Lorg_vmmagic_unboxed_Offset_2";
- OffsetEQMethod = "JnJVM_org_vmmagic_unboxed_Offset_EQ__Lorg_vmmagic_unboxed_Offset_2";
- OffsetMinusOffsetMethod = "JnJVM_org_vmmagic_unboxed_Offset_minus__Lorg_vmmagic_unboxed_Offset_2";
- }
-}
-
-
-static bool removePotentialNullCheck(BasicBlock* Cur, Value* Obj) {
- BasicBlock* BB = Cur->getUniquePredecessor();
- LLVMContext& Context = Cur->getParent()->getContext();
- if (BB) {
- Instruction* T = BB->getTerminator();
- if (dyn_cast<BranchInst>(T) && T != BB->begin()) {
- BasicBlock::iterator BIE = BB->end();
- --BIE; // Terminator
- --BIE; // Null test
- if (ICmpInst* IE = dyn_cast<ICmpInst>(BIE)) {
- if (IE->getPredicate() == ICmpInst::ICMP_EQ &&
- IE->getOperand(0) == Obj &&
- IE->getOperand(1) == Constant::getNullValue(Obj->getType())) {
- BIE->replaceAllUsesWith(ConstantInt::getFalse(Context));
- BIE->eraseFromParent();
- return true;
- }
- }
- }
- }
- return false;
-}
-
-bool LowerMagic::runOnFunction(Function& F) {
- Module* globalModule = F.getParent();
- LLVMContext& Context = globalModule->getContext();
- bool Changed = false;
- const llvm::Type* pointerSizeType =
- globalModule->getPointerSize() == llvm::Module::Pointer32 ?
- Type::getInt32Ty(Context) : Type::getInt64Ty(Context);
-
- Constant* constantPtrLogSize =
- ConstantInt::get(Type::getInt32Ty(Context), sizeof(void*) == 8 ? 3 : 2);
-
- const llvm::Type* ptrType = PointerType::getUnqual(Type::getInt8Ty(Context));
- const llvm::Type* ptrSizeType = PointerType::getUnqual(pointerSizeType);
-
-
- initialiseFunctions(globalModule);
-
- Function* MMalloc = globalModule->getFunction("AllocateMagicArray");
- if (!MMalloc) {
- std::vector<const Type*>FuncTyArgs;
- FuncTyArgs.push_back(Type::getInt32Ty(Context));
- FuncTyArgs.push_back(ptrType);
- FunctionType* FuncTy = FunctionType::get(ptrType, FuncTyArgs, false);
-
-
- MMalloc = Function::Create(FuncTy, GlobalValue::ExternalLinkage, "AllocateMagicArray",
- globalModule);
- }
-
-
- if (!CASPtr || CASPtr->getParent() != globalModule) {
- if (pointerSizeType == Type::getInt32Ty(Context)) {
- CASPtr = globalModule->getFunction("llvm.atomic.cmp.swap.i32.p0i32");
- } else {
- CASPtr = globalModule->getFunction("llvm.atomic.cmp.swap.i64.p0i64");
- }
- CASInt = globalModule->getFunction("llvm.atomic.cmp.swap.i32.p0i32");
- }
-
- for (Function::iterator BI = F.begin(), BE = F.end(); BI != BE; BI++) {
- BasicBlock *Cur = BI;
- for (BasicBlock::iterator II = Cur->begin(), IE = Cur->end(); II != IE;) {
- Instruction *I = II;
- II++;
- if (I->getOpcode() != Instruction::Call &&
- I->getOpcode() != Instruction::Invoke) {
- continue;
- }
-
- CallSite Call(I);
- Instruction* CI = I;
- Value* V = Call.getCalledValue();
- if (Function* FCur = dyn_cast<Function>(V)) {
- const char* name = FCur->getName().data();
- unsigned len = FCur->getName().size();
- if (len > strlen(AddressClass) &&
- !memcmp(AddressClass, name, strlen(AddressClass))) {
-
- Changed = true;
- // Remove the null check
- if (Call.arg_begin() != Call.arg_end()) {
- removePotentialNullCheck(Cur, Call.getArgument(0));
- }
-
- if (!strcmp(FCur->getName().data(), AddressZeroMethod)) {
- Constant* N = Constant::getNullValue(FCur->getReturnType());
- CI->replaceAllUsesWith(N);
- CI->eraseFromParent();
- } else if (!strcmp(FCur->getName().data(), AddressMaxMethod)) {
- ConstantInt* M = ConstantInt::get(Type::getInt64Ty(Context), (uint64_t)-1);
- Constant* N = ConstantExpr::getIntToPtr(M, FCur->getReturnType());
- CI->replaceAllUsesWith(N);
- CI->eraseFromParent();
- } else if (!strcmp(FCur->getName().data(), AddressStoreObjectReferenceMethod) ||
- !strcmp(FCur->getName().data(), AddressStoreAddressMethod) ||
- !strcmp(FCur->getName().data(), AddressStoreShortMethod) ||
- !strcmp(FCur->getName().data(), AddressStoreByteMethod) ||
- !strcmp(FCur->getName().data(), AddressStoreIntMethod) ||
- !strcmp(FCur->getName().data(), AddressStoreWordMethod)) {
- Value* Addr = Call.getArgument(0);
- Value* Obj = Call.getArgument(1);
- const llvm::Type* Ty = PointerType::getUnqual(Obj->getType());
- Addr = new BitCastInst(Addr, Ty, "", CI);
- new StoreInst(Obj, Addr, CI);
- CI->eraseFromParent();
- } else if (!strcmp(FCur->getName().data(), AddressLoadObjectReferenceMethod) ||
- !strcmp(FCur->getName().data(), AddressLoadAddressMethod) ||
- !strcmp(FCur->getName().data(), AddressLoadWordMethod) ||
- !strcmp(FCur->getName().data(), AddressLoadShortMethod) ||
- !strcmp(FCur->getName().data(), AddressLoadByteMethod) ||
- !strcmp(FCur->getName().data(), AddressLoadIntMethod) ||
- !strcmp(FCur->getName().data(), AddressPrepareWordMethod)) {
- Value* Addr = Call.getArgument(0);
- const Type* Ty = PointerType::getUnqual(FCur->getReturnType());
- Addr = new BitCastInst(Addr, Ty, "", CI);
- Value* LD = new LoadInst(Addr, "", CI);
- CI->replaceAllUsesWith(LD);
- CI->eraseFromParent();
- } else if (!strcmp(FCur->getName().data(), AddressDiffMethod) ||
- !strcmp(FCur->getName().data(), AddressMinusExtentMethod)) {
- Value* Val1 = Call.getArgument(0);
- Value* Val2 = Call.getArgument(1);
- Val1 = new PtrToIntInst(Val1, pointerSizeType, "", CI);
- Val2 = new PtrToIntInst(Val2, pointerSizeType, "", CI);
- Value* res = BinaryOperator::CreateSub(Val1, Val2, "", CI);
- res = new IntToPtrInst(res, FCur->getReturnType(), "", CI);
- CI->replaceAllUsesWith(res);
- CI->eraseFromParent();
- } else if (!strcmp(FCur->getName().data(), AddressPlusOffsetMethod)) {
- Value* Val1 = Call.getArgument(0);
- Value* Val2 = Call.getArgument(1);
- Val1 = new PtrToIntInst(Val1, pointerSizeType, "", CI);
- Val2 = new PtrToIntInst(Val2, pointerSizeType, "", CI);
- Value* res = BinaryOperator::CreateAdd(Val1, Val2, "", CI);
- res = new IntToPtrInst(res, FCur->getReturnType(), "", CI);
- CI->replaceAllUsesWith(res);
- CI->eraseFromParent();
- } else if (!strcmp(FCur->getName().data(), AddressPlusIntMethod)) {
- Value* Val1 = Call.getArgument(0);
- Value* Val2 = Call.getArgument(1);
- Val1 = new PtrToIntInst(Val1, pointerSizeType, "", CI);
- if (Val2->getType() != pointerSizeType)
- Val2 = new ZExtInst(Val2, pointerSizeType, "", CI);
- Value* res = BinaryOperator::CreateAdd(Val1, Val2, "", CI);
- res = new IntToPtrInst(res, FCur->getReturnType(), "", CI);
- CI->replaceAllUsesWith(res);
- CI->eraseFromParent();
- } else if (!strcmp(FCur->getName().data(), AddressMinusIntMethod)) {
- Value* Val1 = Call.getArgument(0);
- Value* Val2 = Call.getArgument(1);
- Val1 = new PtrToIntInst(Val1, pointerSizeType, "", CI);
- if (Val2->getType() != pointerSizeType)
- Val2 = new ZExtInst(Val2, pointerSizeType, "", CI);
- Value* res = BinaryOperator::CreateSub(Val1, Val2, "", CI);
- res = new IntToPtrInst(res, FCur->getReturnType(), "", CI);
- CI->replaceAllUsesWith(res);
- CI->eraseFromParent();
- } else if (!strcmp(FCur->getName().data(), AddressLTMethod)) {
- Value* Val1 = Call.getArgument(0);
- Value* Val2 = Call.getArgument(1);
- Val1 = new PtrToIntInst(Val1, pointerSizeType, "", CI);
- Val2 = new PtrToIntInst(Val2, pointerSizeType, "", CI);
- Value* res = new ICmpInst(CI, ICmpInst::ICMP_ULT, Val1, Val2, "");
- res = new ZExtInst(res, FCur->getReturnType(), "", CI);
- CI->replaceAllUsesWith(res);
- CI->eraseFromParent();
- } else if (!strcmp(FCur->getName().data(), AddressGTMethod)) {
- Value* Val1 = Call.getArgument(0);
- Value* Val2 = Call.getArgument(1);
- Val1 = new PtrToIntInst(Val1, pointerSizeType, "", CI);
- Val2 = new PtrToIntInst(Val2, pointerSizeType, "", CI);
- Value* res = new ICmpInst(CI, ICmpInst::ICMP_UGT, Val1, Val2, "");
- res = new ZExtInst(res, FCur->getReturnType(), "", CI);
- CI->replaceAllUsesWith(res);
- CI->eraseFromParent();
- } else if (!strcmp(FCur->getName().data(), AddressEQMethod)) {
- Value* Val1 = Call.getArgument(0);
- Value* Val2 = Call.getArgument(1);
- Val1 = new PtrToIntInst(Val1, pointerSizeType, "", CI);
- Val2 = new PtrToIntInst(Val2, pointerSizeType, "", CI);
- Value* res = new ICmpInst(CI, ICmpInst::ICMP_EQ, Val1, Val2, "");
- res = new ZExtInst(res, FCur->getReturnType(), "", CI);
- CI->replaceAllUsesWith(res);
- CI->eraseFromParent();
- } else if (!strcmp(FCur->getName().data(), AddressNEMethod)) {
- Value* Val1 = Call.getArgument(0);
- Value* Val2 = Call.getArgument(1);
- Val1 = new PtrToIntInst(Val1, pointerSizeType, "", CI);
- Val2 = new PtrToIntInst(Val2, pointerSizeType, "", CI);
- Value* res = new ICmpInst(CI, ICmpInst::ICMP_NE, Val1, Val2, "");
- res = new ZExtInst(res, FCur->getReturnType(), "", CI);
- CI->replaceAllUsesWith(res);
- CI->eraseFromParent();
- } else if (!strcmp(FCur->getName().data(), AddressLEMethod)) {
- Value* Val1 = Call.getArgument(0);
- Value* Val2 = Call.getArgument(1);
- Val1 = new PtrToIntInst(Val1, pointerSizeType, "", CI);
- Val2 = new PtrToIntInst(Val2, pointerSizeType, "", CI);
- Value* res = new ICmpInst(CI, ICmpInst::ICMP_ULE, Val1, Val2, "");
- res = new ZExtInst(res, FCur->getReturnType(), "", CI);
- CI->replaceAllUsesWith(res);
- CI->eraseFromParent();
- } else if (!strcmp(FCur->getName().data(), AddressGEMethod)) {
- Value* Val1 = Call.getArgument(0);
- Value* Val2 = Call.getArgument(1);
- Val1 = new PtrToIntInst(Val1, pointerSizeType, "", CI);
- Val2 = new PtrToIntInst(Val2, pointerSizeType, "", CI);
- Value* res = new ICmpInst(CI, ICmpInst::ICMP_UGE, Val1, Val2, "");
- res = new ZExtInst(res, FCur->getReturnType(), "", CI);
- CI->replaceAllUsesWith(res);
- CI->eraseFromParent();
- } else if (!strcmp(FCur->getName().data(), AddressToObjectReferenceMethod) ||
- !strcmp(FCur->getName().data(), AddressToWordMethod)) {
- Value* Val = Call.getArgument(0);
- Val = new BitCastInst(Val, FCur->getReturnType(), "", CI);
- CI->replaceAllUsesWith(Val);
- CI->eraseFromParent();
- } else if (!strcmp(FCur->getName().data(), AddressAttemptWordAtOffsetMethod)) {
- Value* Ptr = Call.getArgument(0);
- Value* Old = Call.getArgument(1);
- Value* Val = Call.getArgument(2);
- Value* Offset = Call.getArgument(3);
-
- Ptr = new PtrToIntInst(Ptr, pointerSizeType, "", CI);
- Offset = new PtrToIntInst(Offset, pointerSizeType, "", CI);
- Ptr = BinaryOperator::CreateAdd(Ptr, Offset, "", CI);
- const Type* Ty = PointerType::getUnqual(pointerSizeType);
- Ptr = new IntToPtrInst(Ptr, Ty, "", CI);
- Old = new PtrToIntInst(Old, pointerSizeType, "", CI);
- Val = new PtrToIntInst(Val, pointerSizeType, "", CI);
-
- Value* Args[3] = { Ptr, Old, Val };
- Value* res = CallInst::Create(CASPtr, Args, Args + 3, "", CI);
- res = new ICmpInst(CI, ICmpInst::ICMP_EQ, res, Old, "");
- res = new ZExtInst(res, FCur->getReturnType(), "", CI);
-
- CI->replaceAllUsesWith(res);
- CI->eraseFromParent();
- } else if (!strcmp(FCur->getName().data(), AddressAttemptWordMethod)) {
- Value* Ptr = Call.getArgument(0);
- Value* Old = Call.getArgument(1);
- Value* Val = Call.getArgument(2);
-
- const Type* Ty = PointerType::getUnqual(pointerSizeType);
- Ptr = new BitCastInst(Ptr, Ty, "", CI);
- Old = new PtrToIntInst(Old, pointerSizeType, "", CI);
- Val = new PtrToIntInst(Val, pointerSizeType, "", CI);
-
- Value* Args[3] = { Ptr, Old, Val };
- Value* res = CallInst::Create(CASPtr, Args, Args + 3, "", CI);
- res = new ICmpInst(CI, ICmpInst::ICMP_EQ, res, Old, "");
- res = new ZExtInst(res, FCur->getReturnType(), "", CI);
-
- CI->replaceAllUsesWith(res);
- CI->eraseFromParent();
- } else if (!strcmp(FCur->getName().data(), AddressPrepareWordAtOffsetMethod) ||
- !strcmp(FCur->getName().data(), AddressLoadWordAtOffsetMethod) ||
- !strcmp(FCur->getName().data(), AddressLoadAddressAtOffsetMethod) ||
- !strcmp(FCur->getName().data(), AddressLoadObjectReferenceAtOffsetMethod) ||
- !strcmp(FCur->getName().data(), AddressLoadByteAtOffsetMethod) ||
- !strcmp(FCur->getName().data(), AddressLoadIntAtOffsetMethod) ||
- !strcmp(FCur->getName().data(), AddressLoadShortAtOffsetMethod)) {
- Value* Ptr = Call.getArgument(0);
- Value* Offset = Call.getArgument(1);
-
- Ptr = new PtrToIntInst(Ptr, pointerSizeType, "", CI);
- Offset = new PtrToIntInst(Offset, pointerSizeType, "", CI);
- Ptr = BinaryOperator::CreateAdd(Ptr, Offset, "", CI);
- const Type* Ty = PointerType::getUnqual(FCur->getReturnType());
- Ptr = new IntToPtrInst(Ptr, Ty, "", CI);
- Value* res = new LoadInst(Ptr, "", CI);
-
- CI->replaceAllUsesWith(res);
- CI->eraseFromParent();
- } else if (!strcmp(FCur->getName().data(), AddressStoreWordAtOffsetMethod) ||
- !strcmp(FCur->getName().data(), AddressStoreAddressAtOffsetMethod) ||
- !strcmp(FCur->getName().data(), AddressStoreByteAtOffsetMethod) ||
- !strcmp(FCur->getName().data(), AddressStoreShortAtOffsetMethod)) {
- Value* Ptr = Call.getArgument(0);
- Value* Val = Call.getArgument(1);
- Value* Offset = Call.getArgument(2);
-
- Ptr = new PtrToIntInst(Ptr, pointerSizeType, "", CI);
- Offset = new PtrToIntInst(Offset, pointerSizeType, "", CI);
- Ptr = BinaryOperator::CreateAdd(Ptr, Offset, "", CI);
- const Type* Ty = PointerType::getUnqual(Val->getType());
- Ptr = new IntToPtrInst(Ptr, Ty, "", CI);
- new StoreInst(Val, Ptr, CI);
-
- CI->eraseFromParent();
- } else if (!strcmp(FCur->getName().data(), AddressPlusExtentMethod)) {
- Value* Val1 = Call.getArgument(0);
- Value* Val2 = Call.getArgument(1);
- Val1 = new PtrToIntInst(Val1, pointerSizeType, "", CI);
- Val2 = new PtrToIntInst(Val2, pointerSizeType, "", CI);
- Value* res = BinaryOperator::CreateAdd(Val1, Val2, "", CI);
- res = new IntToPtrInst(res, FCur->getReturnType(), "", CI);
- CI->replaceAllUsesWith(res);
- CI->eraseFromParent();
- } else if (!strcmp(FCur->getName().data(), AddressIsZeroMethod)) {
- Value* Val = Call.getArgument(0);
- Constant* N = Constant::getNullValue(Val->getType());
- Value* Res = new ICmpInst(CI, ICmpInst::ICMP_EQ, Val, N, "");
- Res = new ZExtInst(Res, FCur->getReturnType(), "", CI);
- CI->replaceAllUsesWith(Res);
- CI->eraseFromParent();
- } else if (!strcmp(FCur->getName().data(), AddressToLongMethod)) {
- Value* Val = Call.getArgument(0);
- Val = new PtrToIntInst(Val, Type::getInt64Ty(Context), "", CI);
- CI->replaceAllUsesWith(Val);
- CI->eraseFromParent();
- } else if (!strcmp(FCur->getName().data(), AddressFromIntZeroExtendMethod)) {
- Value* Val = Call.getArgument(0);
- if (pointerSizeType != Type::getInt32Ty(Context))
- Val = new ZExtInst(Val, pointerSizeType, "", CI);
- Val = new IntToPtrInst(Val, FCur->getReturnType(), "", CI);
- CI->replaceAllUsesWith(Val);
- CI->eraseFromParent();
- } else if (!strcmp(FCur->getName().data(), AddressToIntMethod)) {
- Value* Val = Call.getArgument(0);
- Val = new PtrToIntInst(Val, Type::getInt32Ty(Context), "", CI);
- CI->replaceAllUsesWith(Val);
- CI->eraseFromParent();
- } else {
- fprintf(stderr, "Implement me %s\n", name);
- abort();
- }
-
- } else if (len > strlen(ExtentClass) &&
- !memcmp(ExtentClass, name, strlen(ExtentClass))) {
-
- Changed = true;
- // Remove the null check
- if (Call.arg_begin() != Call.arg_end()) {
- removePotentialNullCheck(Cur, Call.getArgument(0));
- }
-
- if (!strcmp(FCur->getName().data(), ExtentToWordMethod)) {
- CI->replaceAllUsesWith(Call.getArgument(0));
- CI->eraseFromParent();
- } else if (!strcmp(FCur->getName().data(), ExtentMinusExtentMethod)) {
- Value* Val1 = Call.getArgument(0);
- Value* Val2 = Call.getArgument(1);
- Val1 = new PtrToIntInst(Val1, pointerSizeType, "", CI);
- Val2 = new PtrToIntInst(Val2, pointerSizeType, "", CI);
- Value* res = BinaryOperator::CreateSub(Val1, Val2, "", CI);
- res = new IntToPtrInst(res, FCur->getReturnType(), "", CI);
- CI->replaceAllUsesWith(res);
- CI->eraseFromParent();
- } else if (!strcmp(FCur->getName().data(), ExtentPlusExtentMethod)) {
- Value* Val1 = Call.getArgument(0);
- Value* Val2 = Call.getArgument(1);
- Val1 = new PtrToIntInst(Val1, pointerSizeType, "", CI);
- Val2 = new PtrToIntInst(Val2, pointerSizeType, "", CI);
- Value* res = BinaryOperator::CreateAdd(Val1, Val2, "", CI);
- res = new IntToPtrInst(res, FCur->getReturnType(), "", CI);
- CI->replaceAllUsesWith(res);
- CI->eraseFromParent();
- } else if (!strcmp(FCur->getName().data(), ExtentPlusIntMethod)) {
- Value* Val1 = Call.getArgument(0);
- Value* Val2 = Call.getArgument(1);
- Val1 = new PtrToIntInst(Val1, pointerSizeType, "", CI);
- if (Val2->getType() != pointerSizeType)
- Val2 = new ZExtInst(Val2, pointerSizeType, "", CI);
- Value* res = BinaryOperator::CreateAdd(Val1, Val2, "", CI);
- res = new IntToPtrInst(res, FCur->getReturnType(), "", CI);
- CI->replaceAllUsesWith(res);
- CI->eraseFromParent();
- } else if (!strcmp(FCur->getName().data(), ExtentMinusIntMethod)) {
- Value* Val1 = Call.getArgument(0);
- Value* Val2 = Call.getArgument(1);
- Val1 = new PtrToIntInst(Val1, pointerSizeType, "", CI);
- if (Val2->getType() != pointerSizeType)
- Val2 = new ZExtInst(Val2, pointerSizeType, "", CI);
- Value* res = BinaryOperator::CreateSub(Val1, Val2, "", CI);
- res = new IntToPtrInst(res, FCur->getReturnType(), "", CI);
- CI->replaceAllUsesWith(res);
- CI->eraseFromParent();
- } else if (!strcmp(FCur->getName().data(), ExtentFromIntZeroExtendMethod)) {
- Value* Val = Call.getArgument(0);
- if (pointerSizeType != Type::getInt32Ty(Context))
- Val = new ZExtInst(Val, pointerSizeType, "", CI);
- Val = new IntToPtrInst(Val, FCur->getReturnType(), "", CI);
- CI->replaceAllUsesWith(Val);
- CI->eraseFromParent();
- } else if (!strcmp(FCur->getName().data(), ExtentFromIntSignExtendMethod)) {
- Value* Val = Call.getArgument(0);
- if (pointerSizeType != Type::getInt32Ty(Context))
- Val = new SExtInst(Val, pointerSizeType, "", CI);
- Val = new IntToPtrInst(Val, FCur->getReturnType(), "", CI);
- CI->replaceAllUsesWith(Val);
- CI->eraseFromParent();
- } else if (!strcmp(FCur->getName().data(), ExtentOneMethod)) {
- Constant* N = ConstantInt::get(pointerSizeType, 1);
- N = ConstantExpr::getIntToPtr(N, FCur->getReturnType());
- CI->replaceAllUsesWith(N);
- CI->eraseFromParent();
- } else if (!strcmp(FCur->getName().data(), ExtentNEMethod)) {
- Value* Val1 = Call.getArgument(0);
- Value* Val2 = Call.getArgument(1);
- Val1 = new PtrToIntInst(Val1, pointerSizeType, "", CI);
- Val2 = new PtrToIntInst(Val2, pointerSizeType, "", CI);
- Value* res = new ICmpInst(CI, ICmpInst::ICMP_NE, Val1, Val2, "");
- res = new ZExtInst(res, FCur->getReturnType(), "", CI);
- CI->replaceAllUsesWith(res);
- CI->eraseFromParent();
- } else if (!strcmp(FCur->getName().data(), ExtentEQMethod)) {
- Value* Val1 = Call.getArgument(0);
- Value* Val2 = Call.getArgument(1);
- Val1 = new PtrToIntInst(Val1, pointerSizeType, "", CI);
- Val2 = new PtrToIntInst(Val2, pointerSizeType, "", CI);
- Value* res = new ICmpInst(CI, ICmpInst::ICMP_EQ, Val1, Val2, "");
- res = new ZExtInst(res, FCur->getReturnType(), "", CI);
- CI->replaceAllUsesWith(res);
- CI->eraseFromParent();
- } else if (!strcmp(FCur->getName().data(), ExtentGTMethod)) {
- Value* Val1 = Call.getArgument(0);
- Value* Val2 = Call.getArgument(1);
- Val1 = new PtrToIntInst(Val1, pointerSizeType, "", CI);
- Val2 = new PtrToIntInst(Val2, pointerSizeType, "", CI);
- Value* res = new ICmpInst(CI, ICmpInst::ICMP_UGT, Val1, Val2, "");
- res = new ZExtInst(res, FCur->getReturnType(), "", CI);
- CI->replaceAllUsesWith(res);
- CI->eraseFromParent();
- } else if (!strcmp(FCur->getName().data(), ExtentLTMethod)) {
- Value* Val1 = Call.getArgument(0);
- Value* Val2 = Call.getArgument(1);
- Val1 = new PtrToIntInst(Val1, pointerSizeType, "", CI);
- Val2 = new PtrToIntInst(Val2, pointerSizeType, "", CI);
- Value* res = new ICmpInst(CI, ICmpInst::ICMP_ULT, Val1, Val2, "");
- res = new ZExtInst(res, FCur->getReturnType(), "", CI);
- CI->replaceAllUsesWith(res);
- CI->eraseFromParent();
- } else if (!strcmp(FCur->getName().data(), ExtentZeroMethod)) {
- Constant* N = Constant::getNullValue(FCur->getReturnType());
- CI->replaceAllUsesWith(N);
- CI->eraseFromParent();
- } else if (!strcmp(FCur->getName().data(), ExtentToLongMethod)) {
- Value* Val = Call.getArgument(0);
- Val = new PtrToIntInst(Val, Type::getInt64Ty(Context), "", CI);
- CI->replaceAllUsesWith(Val);
- CI->eraseFromParent();
- } else if (!strcmp(FCur->getName().data(), ExtentToIntMethod)) {
- Value* Val = Call.getArgument(0);
- Val = new PtrToIntInst(Val, Type::getInt32Ty(Context), "", CI);
- CI->replaceAllUsesWith(Val);
- CI->eraseFromParent();
- } else if (!strcmp(FCur->getName().data(), ExtentMaxMethod)) {
- ConstantInt* M = ConstantInt::get(Type::getInt64Ty(Context), (uint64_t)-1);
- Constant* N = ConstantExpr::getIntToPtr(M, FCur->getReturnType());
- CI->replaceAllUsesWith(N);
- CI->eraseFromParent();
- } else {
- fprintf(stderr, "Implement me %s\n", name);
- abort();
- }
- } else if (len > strlen(OffsetClass) &&
- !memcmp(OffsetClass, name, strlen(OffsetClass))) {
-
- Changed = true;
- // Remove the null check
- if (Call.arg_begin() != Call.arg_end()) {
- removePotentialNullCheck(Cur, Call.getArgument(0));
- }
-
- if (!strcmp(FCur->getName().data(), OffsetSLTMethod)) {
- Value* Val1 = Call.getArgument(0);
- Value* Val2 = Call.getArgument(1);
- Val1 = new PtrToIntInst(Val1, pointerSizeType, "", CI);
- Val2 = new PtrToIntInst(Val2, pointerSizeType, "", CI);
- Value* res = new ICmpInst(CI, ICmpInst::ICMP_SLT, Val1, Val2, "");
- res = new ZExtInst(res, FCur->getReturnType(), "", CI);
- CI->replaceAllUsesWith(res);
- CI->eraseFromParent();
- } else if (!strcmp(FCur->getName().data(), OffsetToWordMethod)) {
- Value* Val = Call.getArgument(0);
- Val = new BitCastInst(Val, FCur->getReturnType(), "", CI);
- CI->replaceAllUsesWith(Val);
- CI->eraseFromParent();
- } else if (!strcmp(FCur->getName().data(), OffsetZeroMethod)) {
- Constant* N = Constant::getNullValue(FCur->getReturnType());
- CI->replaceAllUsesWith(N);
- CI->eraseFromParent();
- } else if (!strcmp(FCur->getName().data(), OffsetSGTMethod)) {
- Value* Val1 = Call.getArgument(0);
- Value* Val2 = Call.getArgument(1);
- Val1 = new PtrToIntInst(Val1, pointerSizeType, "", CI);
- Val2 = new PtrToIntInst(Val2, pointerSizeType, "", CI);
- Value* res = new ICmpInst(CI, ICmpInst::ICMP_SGT, Val1, Val2, "");
- res = new ZExtInst(res, FCur->getReturnType(), "", CI);
- CI->replaceAllUsesWith(res);
- CI->eraseFromParent();
- } else if (!strcmp(FCur->getName().data(), OffsetSGEMethod)) {
- Value* Val1 = Call.getArgument(0);
- Value* Val2 = Call.getArgument(1);
- Val1 = new PtrToIntInst(Val1, pointerSizeType, "", CI);
- Val2 = new PtrToIntInst(Val2, pointerSizeType, "", CI);
- Value* res = new ICmpInst(CI, ICmpInst::ICMP_SGE, Val1, Val2, "");
- res = new ZExtInst(res, FCur->getReturnType(), "", CI);
- CI->replaceAllUsesWith(res);
- CI->eraseFromParent();
- } else if (!strcmp(FCur->getName().data(), OffsetSLEMethod)) {
- Value* Val1 = Call.getArgument(0);
- Value* Val2 = Call.getArgument(1);
- Val1 = new PtrToIntInst(Val1, pointerSizeType, "", CI);
- Val2 = new PtrToIntInst(Val2, pointerSizeType, "", CI);
- Value* res = new ICmpInst(CI, ICmpInst::ICMP_SLE, Val1, Val2, "");
- res = new ZExtInst(res, FCur->getReturnType(), "", CI);
- CI->replaceAllUsesWith(res);
- CI->eraseFromParent();
- } else if (!strcmp(FCur->getName().data(), OffsetEQMethod)) {
- Value* Val1 = Call.getArgument(0);
- Value* Val2 = Call.getArgument(1);
- Val1 = new PtrToIntInst(Val1, pointerSizeType, "", CI);
- Val2 = new PtrToIntInst(Val2, pointerSizeType, "", CI);
- Value* res = new ICmpInst(CI, ICmpInst::ICMP_EQ, Val1, Val2, "");
- res = new ZExtInst(res, FCur->getReturnType(), "", CI);
- CI->replaceAllUsesWith(res);
- CI->eraseFromParent();
- } else if (!strcmp(FCur->getName().data(), OffsetFromIntSignExtendMethod)) {
- Value* Val = Call.getArgument(0);
- if (pointerSizeType != Type::getInt32Ty(Context))
- Val = new SExtInst(Val, pointerSizeType, "", CI);
- Val = new IntToPtrInst(Val, FCur->getReturnType(), "", CI);
- CI->replaceAllUsesWith(Val);
- CI->eraseFromParent();
- } else if (!strcmp(FCur->getName().data(), OffsetFromIntZeroExtendMethod)) {
- Value* Val = Call.getArgument(0);
- if (pointerSizeType != Type::getInt32Ty(Context))
- Val = new ZExtInst(Val, pointerSizeType, "", CI);
- Val = new IntToPtrInst(Val, FCur->getReturnType(), "", CI);
- CI->replaceAllUsesWith(Val);
- CI->eraseFromParent();
- } else if (!strcmp(FCur->getName().data(), OffsetPlusIntMethod)) {
- Value* Val1 = Call.getArgument(0);
- Value* Val2 = Call.getArgument(1);
- Val1 = new PtrToIntInst(Val1, pointerSizeType, "", CI);
- if (Val2->getType() != pointerSizeType)
- Val2 = new ZExtInst(Val2, pointerSizeType, "", CI);
- Value* res = BinaryOperator::CreateAdd(Val1, Val2, "", CI);
- res = new IntToPtrInst(res, FCur->getReturnType(), "", CI);
- CI->replaceAllUsesWith(res);
- CI->eraseFromParent();
- } else if (!strcmp(FCur->getName().data(), OffsetToIntMethod)) {
- Value* Val = Call.getArgument(0);
- Val = new PtrToIntInst(Val, Type::getInt32Ty(Context), "", CI);
- CI->replaceAllUsesWith(Val);
- CI->eraseFromParent();
- } else if (!strcmp(FCur->getName().data(), OffsetToLongMethod)) {
- Value* Val = Call.getArgument(0);
- Val = new PtrToIntInst(Val, Type::getInt64Ty(Context), "", CI);
- CI->replaceAllUsesWith(Val);
- CI->eraseFromParent();
- } else if (!strcmp(FCur->getName().data(), OffsetIsZeroMethod)) {
- Value* Val = Call.getArgument(0);
- Constant* N = Constant::getNullValue(Val->getType());
- Value* Res = new ICmpInst(CI, ICmpInst::ICMP_EQ, Val, N, "");
- Res = new ZExtInst(Res, FCur->getReturnType(), "", CI);
- CI->replaceAllUsesWith(Res);
- CI->eraseFromParent();
- } else if (!strcmp(FCur->getName().data(), OffsetMinusIntMethod)) {
- Value* Val1 = Call.getArgument(0);
- Value* Val2 = Call.getArgument(1);
- Val1 = new PtrToIntInst(Val1, pointerSizeType, "", CI);
- if (Val2->getType() != pointerSizeType)
- Val2 = new ZExtInst(Val2, pointerSizeType, "", CI);
- Value* res = BinaryOperator::CreateSub(Val1, Val2, "", CI);
- res = new IntToPtrInst(res, FCur->getReturnType(), "", CI);
- CI->replaceAllUsesWith(res);
- CI->eraseFromParent();
- } else if (!strcmp(FCur->getName().data(), OffsetMinusOffsetMethod)) {
- Value* Val1 = Call.getArgument(0);
- Value* Val2 = Call.getArgument(1);
- Val1 = new PtrToIntInst(Val1, pointerSizeType, "", CI);
- Val2 = new PtrToIntInst(Val2, pointerSizeType, "", CI);
- Value* res = BinaryOperator::CreateSub(Val1, Val2, "", CI);
- res = new IntToPtrInst(res, FCur->getReturnType(), "", CI);
- CI->replaceAllUsesWith(res);
- CI->eraseFromParent();
- } else {
- fprintf(stderr, "Implement me %s\n", name);
- abort();
- }
- } else if (len > strlen(ObjectReferenceClass) &&
- !memcmp(ObjectReferenceClass, name, strlen(ObjectReferenceClass))) {
-
- Changed = true;
- // Remove the null check
- if (Call.arg_begin() != Call.arg_end()) {
- removePotentialNullCheck(Cur, Call.getArgument(0));
- }
-
- if (!strcmp(FCur->getName().data(), ObjectReferenceNullReferenceMethod)) {
- Constant* N = Constant::getNullValue(FCur->getReturnType());
- CI->replaceAllUsesWith(N);
- CI->eraseFromParent();
- } else if (!strcmp(FCur->getName().data(), ObjectReferenceFromObjectMethod)) {
- Value* Val = Call.getArgument(0);
- Val = new BitCastInst(Val, FCur->getReturnType(), "", CI);
- CI->replaceAllUsesWith(Val);
- CI->eraseFromParent();
- } else if (!strcmp(FCur->getName().data(), ObjectReferenceToAddressMethod)) {
- Value* Val = Call.getArgument(0);
- Val = new BitCastInst(Val, FCur->getReturnType(), "", CI);
- CI->replaceAllUsesWith(Val);
- CI->eraseFromParent();
- } else if (!strcmp(FCur->getName().data(), ObjectReferenceToObjectMethod)) {
- Value* Val = Call.getArgument(0);
- Val = new BitCastInst(Val, FCur->getReturnType(), "", CI);
- CI->replaceAllUsesWith(Val);
- CI->eraseFromParent();
- } else if (!strcmp(FCur->getName().data(), ObjectReferenceIsNullMethod)) {
- Value* Val = Call.getArgument(0);
- Constant* N = Constant::getNullValue(Val->getType());
- Value* Res = new ICmpInst(CI, ICmpInst::ICMP_EQ, Val, N, "");
- Res = new ZExtInst(Res, FCur->getReturnType(), "", CI);
- CI->replaceAllUsesWith(Res);
- CI->eraseFromParent();
- } else {
- fprintf(stderr, "Implement me %s\n", name);
- abort();
- }
- } else if (len > strlen(WordClass) &&
- !memcmp(WordClass, name, strlen(WordClass))) {
-
- Changed = true;
- // Remove the null check
- if (Call.arg_begin() != Call.arg_end()) {
- removePotentialNullCheck(Cur, Call.getArgument(0));
- }
-
- if (!strcmp(FCur->getName().data(), WordOrMethod)) {
- Value* Val1 = Call.getArgument(0);
- Value* Val2 = Call.getArgument(1);
- Val1 = new PtrToIntInst(Val1, pointerSizeType, "", CI);
- Val2 = new PtrToIntInst(Val2, pointerSizeType, "", CI);
- Value* Res = BinaryOperator::CreateOr(Val1, Val2, "", CI);
- Res = new IntToPtrInst(Res, FCur->getReturnType(), "", CI);
- CI->replaceAllUsesWith(Res);
- CI->eraseFromParent();
- } else if (!strcmp(FCur->getName().data(), WordAndMethod)) {
- Value* Val1 = Call.getArgument(0);
- Value* Val2 = Call.getArgument(1);
- Val1 = new PtrToIntInst(Val1, pointerSizeType, "", CI);
- Val2 = new PtrToIntInst(Val2, pointerSizeType, "", CI);
- Value* Res = BinaryOperator::CreateAnd(Val1, Val2, "", CI);
- Res = new IntToPtrInst(Res, FCur->getReturnType(), "", CI);
- CI->replaceAllUsesWith(Res);
- CI->eraseFromParent();
- } else if (!strcmp(FCur->getName().data(), WordXorMethod)) {
- Value* Val1 = Call.getArgument(0);
- Value* Val2 = Call.getArgument(1);
- Val1 = new PtrToIntInst(Val1, pointerSizeType, "", CI);
- Val2 = new PtrToIntInst(Val2, pointerSizeType, "", CI);
- Value* Res = BinaryOperator::CreateXor(Val1, Val2, "", CI);
- Res = new IntToPtrInst(Res, FCur->getReturnType(), "", CI);
- CI->replaceAllUsesWith(Res);
- CI->eraseFromParent();
- } else if (!strcmp(FCur->getName().data(), WordRshlMethod)) {
- Value* Val1 = Call.getArgument(0);
- Value* Val2 = Call.getArgument(1);
- Val1 = new PtrToIntInst(Val1, pointerSizeType, "", CI);
- if (Val2->getType() != pointerSizeType)
- Val2 = new ZExtInst(Val2, pointerSizeType, "", CI);
- Value* Res = BinaryOperator::CreateLShr(Val1, Val2, "", CI);
- Res = new IntToPtrInst(Res, FCur->getReturnType(), "", CI);
- CI->replaceAllUsesWith(Res);
- CI->eraseFromParent();
- } else if (!strcmp(FCur->getName().data(), WordLshMethod)) {
- Value* Val1 = Call.getArgument(0);
- Value* Val2 = Call.getArgument(1);
- Val1 = new PtrToIntInst(Val1, pointerSizeType, "", CI);
- if (Val2->getType() != pointerSizeType)
- Val2 = new ZExtInst(Val2, pointerSizeType, "", CI);
- Value* Res = BinaryOperator::CreateShl(Val1, Val2, "", CI);
- Res = new IntToPtrInst(Res, FCur->getReturnType(), "", CI);
- CI->replaceAllUsesWith(Res);
- CI->eraseFromParent();
- } else if (!strcmp(FCur->getName().data(), WordToIntMethod)) {
- Value* Val = Call.getArgument(0);
- Val = new PtrToIntInst(Val, Type::getInt32Ty(Context), "", CI);
- CI->replaceAllUsesWith(Val);
- CI->eraseFromParent();
- } else if (!strcmp(FCur->getName().data(), WordNotMethod)) {
- Value* Val = Call.getArgument(0);
- Val = new PtrToIntInst(Val, pointerSizeType, "", CI);
- Constant* M1 = ConstantInt::get(pointerSizeType, -1);
- Value* Res = BinaryOperator::CreateXor(Val, M1, "", CI);
- Res = new IntToPtrInst(Res, FCur->getReturnType(), "", CI);
- CI->replaceAllUsesWith(Res);
- CI->eraseFromParent();
- } else if (!strcmp(FCur->getName().data(), WordZeroMethod)) {
- Constant* N = Constant::getNullValue(FCur->getReturnType());
- CI->replaceAllUsesWith(N);
- CI->eraseFromParent();
- } else if (!strcmp(FCur->getName().data(), WordOneMethod)) {
- Constant* N = ConstantInt::get(pointerSizeType, 1);
- N = ConstantExpr::getIntToPtr(N, FCur->getReturnType());
- CI->replaceAllUsesWith(N);
- CI->eraseFromParent();
- } else if (!strcmp(FCur->getName().data(), WordToAddressMethod) ||
- !strcmp(FCur->getName().data(), WordToOffsetMethod) ||
- !strcmp(FCur->getName().data(), WordToExtentMethod)) {
- Value* Val = Call.getArgument(0);
- Val = new BitCastInst(Val, FCur->getReturnType(), "", CI);
- CI->replaceAllUsesWith(Val);
- CI->eraseFromParent();
- } else if (!strcmp(FCur->getName().data(), WordMinusWordMethod) ||
- !strcmp(FCur->getName().data(), WordMinusExtentMethod)) {
- Value* Val1 = Call.getArgument(0);
- Value* Val2 = Call.getArgument(1);
- Val1 = new PtrToIntInst(Val1, pointerSizeType, "", CI);
- Val2 = new PtrToIntInst(Val2, pointerSizeType, "", CI);
- Value* res = BinaryOperator::CreateSub(Val1, Val2, "", CI);
- res = new IntToPtrInst(res, FCur->getReturnType(), "", CI);
- CI->replaceAllUsesWith(res);
- CI->eraseFromParent();
- } else if (!strcmp(FCur->getName().data(), WordPlusWordMethod)) {
- Value* Val1 = Call.getArgument(0);
- Value* Val2 = Call.getArgument(1);
- Val1 = new PtrToIntInst(Val1, pointerSizeType, "", CI);
- Val2 = new PtrToIntInst(Val2, pointerSizeType, "", CI);
- Value* res = BinaryOperator::CreateAdd(Val1, Val2, "", CI);
- res = new IntToPtrInst(res, FCur->getReturnType(), "", CI);
- CI->replaceAllUsesWith(res);
- CI->eraseFromParent();
- } else if (!strcmp(FCur->getName().data(), WordLTMethod)) {
- Value* Val1 = Call.getArgument(0);
- Value* Val2 = Call.getArgument(1);
- Val1 = new PtrToIntInst(Val1, pointerSizeType, "", CI);
- Val2 = new PtrToIntInst(Val2, pointerSizeType, "", CI);
- Value* res = new ICmpInst(CI, ICmpInst::ICMP_ULT, Val1, Val2, "");
- res = new ZExtInst(res, FCur->getReturnType(), "", CI);
- CI->replaceAllUsesWith(res);
- CI->eraseFromParent();
- } else if (!strcmp(FCur->getName().data(), WordLEMethod)) {
- Value* Val1 = Call.getArgument(0);
- Value* Val2 = Call.getArgument(1);
- Val1 = new PtrToIntInst(Val1, pointerSizeType, "", CI);
- Val2 = new PtrToIntInst(Val2, pointerSizeType, "", CI);
- Value* res = new ICmpInst(CI, ICmpInst::ICMP_ULE, Val1, Val2, "");
- res = new ZExtInst(res, FCur->getReturnType(), "", CI);
- CI->replaceAllUsesWith(res);
- CI->eraseFromParent();
- } else if (!strcmp(FCur->getName().data(), WordGEMethod)) {
- Value* Val1 = Call.getArgument(0);
- Value* Val2 = Call.getArgument(1);
- Val1 = new PtrToIntInst(Val1, pointerSizeType, "", CI);
- Val2 = new PtrToIntInst(Val2, pointerSizeType, "", CI);
- Value* res = new ICmpInst(CI, ICmpInst::ICMP_UGE, Val1, Val2, "");
- res = new ZExtInst(res, FCur->getReturnType(), "", CI);
- CI->replaceAllUsesWith(res);
- CI->eraseFromParent();
- } else if (!strcmp(FCur->getName().data(), WordEQMethod)) {
- Value* Val1 = Call.getArgument(0);
- Value* Val2 = Call.getArgument(1);
- Val1 = new PtrToIntInst(Val1, pointerSizeType, "", CI);
- Val2 = new PtrToIntInst(Val2, pointerSizeType, "", CI);
- Value* res = new ICmpInst(CI, ICmpInst::ICMP_EQ, Val1, Val2, "");
- res = new ZExtInst(res, FCur->getReturnType(), "", CI);
- CI->replaceAllUsesWith(res);
- CI->eraseFromParent();
- } else if (!strcmp(FCur->getName().data(), WordGTMethod)) {
- Value* Val1 = Call.getArgument(0);
- Value* Val2 = Call.getArgument(1);
- Val1 = new PtrToIntInst(Val1, pointerSizeType, "", CI);
- Val2 = new PtrToIntInst(Val2, pointerSizeType, "", CI);
- Value* res = new ICmpInst(CI, ICmpInst::ICMP_UGT, Val1, Val2, "");
- res = new ZExtInst(res, FCur->getReturnType(), "", CI);
- CI->replaceAllUsesWith(res);
- CI->eraseFromParent();
- } else if (!strcmp(FCur->getName().data(), WordNEMethod)) {
- Value* Val1 = Call.getArgument(0);
- Value* Val2 = Call.getArgument(1);
- Val1 = new PtrToIntInst(Val1, pointerSizeType, "", CI);
- Val2 = new PtrToIntInst(Val2, pointerSizeType, "", CI);
- Value* res = new ICmpInst(CI, ICmpInst::ICMP_NE, Val1, Val2, "");
- res = new ZExtInst(res, FCur->getReturnType(), "", CI);
- CI->replaceAllUsesWith(res);
- CI->eraseFromParent();
- } else if (!strcmp(FCur->getName().data(), WordFromIntSignExtendMethod)) {
- Value* Val = Call.getArgument(0);
- if (pointerSizeType != Type::getInt32Ty(Context))
- Val = new SExtInst(Val, pointerSizeType, "", CI);
- Val = new IntToPtrInst(Val, FCur->getReturnType(), "", CI);
- CI->replaceAllUsesWith(Val);
- CI->eraseFromParent();
- } else if (!strcmp(FCur->getName().data(), WordFromIntZeroExtendMethod)) {
- Value* Val = Call.getArgument(0);
- if (pointerSizeType != Type::getInt32Ty(Context))
- Val = new ZExtInst(Val, pointerSizeType, "", CI);
- Val = new IntToPtrInst(Val, FCur->getReturnType(), "", CI);
- CI->replaceAllUsesWith(Val);
- CI->eraseFromParent();
- } else if (!strcmp(FCur->getName().data(), WordIsZeroMethod)) {
- Value* Val = Call.getArgument(0);
- Constant* N = Constant::getNullValue(Val->getType());
- Value* Res = new ICmpInst(CI, ICmpInst::ICMP_EQ, Val, N, "");
- Res = new ZExtInst(Res, FCur->getReturnType(), "", CI);
- CI->replaceAllUsesWith(Res);
- CI->eraseFromParent();
- } else if (!strcmp(FCur->getName().data(), WordToLongMethod)) {
- Value* Val = Call.getArgument(0);
- Val = new PtrToIntInst(Val, Type::getInt64Ty(Context), "", CI);
- CI->replaceAllUsesWith(Val);
- CI->eraseFromParent();
- } else if (!strcmp(FCur->getName().data(), WordMaxMethod)) {
- ConstantInt* M = ConstantInt::get(Type::getInt64Ty(Context), (uint64_t)-1);
- Constant* N = ConstantExpr::getIntToPtr(M, FCur->getReturnType());
- CI->replaceAllUsesWith(N);
- CI->eraseFromParent();
- } else {
- fprintf(stderr, "Implement me %s\n", name);
- abort();
- }
- } else if (
- (len > strlen(AddressArrayClass) &&
- !memcmp(AddressArrayClass, name, strlen(AddressArrayClass))) ||
- (len > strlen(OffsetArrayClass) &&
- !memcmp(OffsetArrayClass, name, strlen(OffsetArrayClass))) ||
- (len > strlen(WordArrayClass) &&
- !memcmp(WordArrayClass, name, strlen(WordArrayClass))) ||
- (len > strlen(ObjectReferenceArrayClass) &&
- !memcmp(ObjectReferenceArrayClass, name, strlen(ObjectReferenceArrayClass))) ||
- (len > strlen(ExtentArrayClass) &&
- !memcmp(ExtentArrayClass, name, strlen(ExtentArrayClass)))) {
- Changed = true;
-
- if (!strcmp(FCur->getName().data(), AddressArrayCreateMethod) ||
- !strcmp(FCur->getName().data(), OffsetArrayCreateMethod) ||
- !strcmp(FCur->getName().data(), WordArrayCreateMethod) ||
- !strcmp(FCur->getName().data(), ExtentArrayCreateMethod) ||
- !strcmp(FCur->getName().data(), ObjectReferenceArrayCreateMethod)) {
- Value* Val = Call.getArgument(0);
- ConstantInt* One = ConstantInt::get(Type::getInt32Ty(Context), (uint64_t)1);
- Value* Length = BinaryOperator::CreateAdd(Val, One, "", CI);
- Length = BinaryOperator::CreateShl(Length, constantPtrLogSize, "", CI);
- Val = new IntToPtrInst(Val, ptrType, "", CI);
- Value* args[2] = { Length, Val };
- Value* res = CallInst::Create(MMalloc, args, args + 2, "", CI);
- res = new BitCastInst(res, FCur->getReturnType(), "", CI);
- CI->replaceAllUsesWith(res);
- CI->eraseFromParent();
-
- } else if (!strcmp(FCur->getName().data(), AddressArrayGetMethod) ||
- !strcmp(FCur->getName().data(), OffsetArrayGetMethod) ||
- !strcmp(FCur->getName().data(), WordArrayGetMethod) ||
- !strcmp(FCur->getName().data(), ExtentArrayGetMethod) ||
- !strcmp(FCur->getName().data(), ObjectReferenceArrayGetMethod)) {
-
- Value* Array = Call.getArgument(0);
- Value* Index = Call.getArgument(1);
- ConstantInt* One = ConstantInt::get(Type::getInt32Ty(Context), (uint64_t)1);
- Index = BinaryOperator::CreateAdd(Index, One, "", CI);
- Array = new BitCastInst(Array, ptrSizeType, "", CI);
- Value* res = GetElementPtrInst::Create(Array, Index, "", CI);
- res = new LoadInst(res, "", CI);
- res = new IntToPtrInst(res, FCur->getReturnType(), "", CI);
- CI->replaceAllUsesWith(res);
- CI->eraseFromParent();
-
- } else if (!strcmp(FCur->getName().data(), AddressArraySetMethod) ||
- !strcmp(FCur->getName().data(), OffsetArraySetMethod) ||
- !strcmp(FCur->getName().data(), WordArraySetMethod) ||
- !strcmp(FCur->getName().data(), ExtentArraySetMethod) ||
- !strcmp(FCur->getName().data(), ObjectReferenceArraySetMethod)) {
-
- Value* Array = Call.getArgument(0);
- Value* Index = Call.getArgument(1);
- Value* Element = Call.getArgument(2);
- ConstantInt* One = ConstantInt::get(Type::getInt32Ty(Context), (uint64_t)1);
-
- Index = BinaryOperator::CreateAdd(Index, One, "", CI);
- Array = new BitCastInst(Array, ptrSizeType, "", CI);
- Value* ptr = GetElementPtrInst::Create(Array, Index, "", CI);
- Element = new PtrToIntInst(Element, pointerSizeType, "", CI);
- new StoreInst(Element, ptr, CI);
- CI->eraseFromParent();
-
- } else if (!strcmp(FCur->getName().data(), AddressArrayLengthMethod) ||
- !strcmp(FCur->getName().data(), OffsetArrayLengthMethod) ||
- !strcmp(FCur->getName().data(), WordArrayLengthMethod) ||
- !strcmp(FCur->getName().data(), ExtentArrayLengthMethod) ||
- !strcmp(FCur->getName().data(), ObjectReferenceArrayLengthMethod)) {
-
- Value* Array = Call.getArgument(0);
- Array = new BitCastInst(Array, ptrSizeType, "", CI);
- Value* Length = new LoadInst(Array, "", CI);
- if (Length->getType() != Type::getInt32Ty(Context)) {
- Length = new TruncInst(Length, Type::getInt32Ty(Context), "", CI);
- }
- CI->replaceAllUsesWith(Length);
- CI->eraseFromParent();
- }
- }
- }
- }
- }
- return Changed;
-}
-
-
-FunctionPass* createLowerMagicPass() {
- return new LowerMagic();
-}
-
-}
diff --git a/vmkit/mmtk/magic/Makefile b/vmkit/mmtk/magic/Makefile
deleted file mode 100644
index 863075f..0000000
--- a/vmkit/mmtk/magic/Makefile
+++ /dev/null
@@ -1,16 +0,0 @@
-##===- mmtk/magic/Makefile ---------------------------------*- Makefile -*-===##
-#
-# The LLVM Compiler Infrastructure
-#
-# This file is distributed under the University of Illinois Open Source
-# License. See LICENSE.TXT for details.
-#
-##===----------------------------------------------------------------------===##
-
-LEVEL = ../..
-LIBRARYNAME = MMTKMagic
-LOADABLE_MODULE = 1
-USEDLIBS =
-
-include $(LEVEL)/Makefile.common
-
diff --git a/vmkit/mmtk/mmtk-alloc/Makefile b/vmkit/mmtk/mmtk-alloc/Makefile
deleted file mode 100644
index 97e7a84..0000000
--- a/vmkit/mmtk/mmtk-alloc/Makefile
+++ /dev/null
@@ -1,26 +0,0 @@
-##===- mmtk/mmtk-j3/Makefile -------------------------------*- Makefile -*-===##
-#
-# The vmkit project
-#
-# This file is distributed under the University of Illinois Open Source
-# License. See LICENSE.TXT for details.
-#
-##===----------------------------------------------------------------------===##
-
-LEVEL = ../..
-
-include $(LEVEL)/Makefile.config
-
-ifeq ($(WITH_LLVM_GCC), 1)
- MODULE_NAME = MMTKAlloc
-else
- LIBRARYNAME = MMTKAlloc
-endif
-
-LOADABLE_MODULE = 1
-USEDLIBS =
-
-CXX.Flags += -I$(PROJ_SRC_DIR)/../../lib/J3/VMCore
-
-include $(LEVEL)/Makefile.common
-
diff --git a/vmkit/mmtk/mmtk-alloc/Selected.cpp b/vmkit/mmtk/mmtk-alloc/Selected.cpp
deleted file mode 100644
index f050bde..0000000
--- a/vmkit/mmtk/mmtk-alloc/Selected.cpp
+++ /dev/null
@@ -1,163 +0,0 @@
-//===-------- Selected.cpp - Implementation of the Selected class --------===//
-//
-// The VMKit project
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#include "MutatorThread.h"
-#include "mvm/GC.h"
-
-#include "mvm/VirtualMachine.h"
-#include "mvm/VMKit.h"
-
-#include <sys/mman.h>
-#include <set>
-
-#include "debug.h"
-
-using namespace mvm;
-
-int Collector::verbose = 0;
-extern "C" void Java_org_j3_mmtk_Collection_triggerCollection__I(uintptr_t, int32_t) ALWAYS_INLINE;
-
-extern "C" intptr_t JnJVM_org_j3_bindings_Bindings_allocateMutator__I(int32_t) ALWAYS_INLINE;
-extern "C" void JnJVM_org_j3_bindings_Bindings_freeMutator__Lorg_mmtk_plan_MutatorContext_2(intptr_t) ALWAYS_INLINE;
-extern "C" void JnJVM_org_j3_bindings_Bindings_boot__Lorg_vmmagic_unboxed_Extent_2Lorg_vmmagic_unboxed_Extent_2(intptr_t, intptr_t) ALWAYS_INLINE;
-
-extern "C" void JnJVM_org_j3_bindings_Bindings_processEdge__Lorg_mmtk_plan_TransitiveClosure_2Lorg_vmmagic_unboxed_ObjectReference_2Lorg_vmmagic_unboxed_Address_2(
- uintptr_t closure, void* source, void* slot) ALWAYS_INLINE;
-
-extern "C" void JnJVM_org_j3_bindings_Bindings_reportDelayedRootEdge__Lorg_mmtk_plan_TraceLocal_2Lorg_vmmagic_unboxed_Address_2(
- uintptr_t TraceLocal, void** slot) ALWAYS_INLINE;
-extern "C" void JnJVM_org_j3_bindings_Bindings_processRootEdge__Lorg_mmtk_plan_TraceLocal_2Lorg_vmmagic_unboxed_Address_2Z(
- uintptr_t TraceLocal, void* slot, uint8_t untraced) ALWAYS_INLINE;
-extern "C" gc* JnJVM_org_j3_bindings_Bindings_retainForFinalize__Lorg_mmtk_plan_TraceLocal_2Lorg_vmmagic_unboxed_ObjectReference_2(
- uintptr_t TraceLocal, void* obj) ALWAYS_INLINE;
-extern "C" gc* JnJVM_org_j3_bindings_Bindings_retainReferent__Lorg_mmtk_plan_TraceLocal_2Lorg_vmmagic_unboxed_ObjectReference_2(
- uintptr_t TraceLocal, void* obj) ALWAYS_INLINE;
-extern "C" gc* JnJVM_org_j3_bindings_Bindings_getForwardedReference__Lorg_mmtk_plan_TraceLocal_2Lorg_vmmagic_unboxed_ObjectReference_2(
- uintptr_t TraceLocal, void* obj) ALWAYS_INLINE;
-extern "C" gc* JnJVM_org_j3_bindings_Bindings_getForwardedReferent__Lorg_mmtk_plan_TraceLocal_2Lorg_vmmagic_unboxed_ObjectReference_2(
- uintptr_t TraceLocal, void* obj) ALWAYS_INLINE;
-extern "C" gc* JnJVM_org_j3_bindings_Bindings_getForwardedFinalizable__Lorg_mmtk_plan_TraceLocal_2Lorg_vmmagic_unboxed_ObjectReference_2(
- uintptr_t TraceLocal, void* obj) ALWAYS_INLINE;
-extern "C" uint8_t JnJVM_org_j3_bindings_Bindings_isLive__Lorg_mmtk_plan_TraceLocal_2Lorg_vmmagic_unboxed_ObjectReference_2(
- uintptr_t TraceLocal, void* obj) ALWAYS_INLINE;
-
-extern "C" void* JnJVM_org_j3_bindings_Bindings_gcmalloc__ILorg_vmmagic_unboxed_ObjectReference_2(
- int sz, void* VT) ALWAYS_INLINE;
-
-extern "C" void* gcmalloc(uint32_t sz, void* VT) {
- sz = llvm::RoundUpToAlignment(sz, sizeof(void*));
- return (gc*)JnJVM_org_j3_bindings_Bindings_gcmalloc__ILorg_vmmagic_unboxed_ObjectReference_2(sz, VT);
-}
-
-extern "C" void addFinalizationCandidate(void* obj) __attribute__((always_inline));
-
-extern "C" void addFinalizationCandidate(void* obj) {
- llvm_gcroot(obj, 0);
- mvm::Thread::get()->vmkit->addFinalizationCandidate((gc*)obj);
-}
-
-extern "C" void* gcmallocUnresolved(uint32_t sz, VirtualTable* VT) {
- gc* res = 0;
- llvm_gcroot(res, 0);
- res = (gc*)gcmalloc(sz, VT);
- if (VT->destructor) addFinalizationCandidate(res);
- return res;
-}
-
-void MutatorThread::init(Thread* _th) {
- MutatorThread* th = (MutatorThread*)_th;
- th->MutatorContext =
- JnJVM_org_j3_bindings_Bindings_allocateMutator__I((int32_t)_th->getThreadID());
- th->realRoutine(_th);
- uintptr_t context = th->MutatorContext;
- th->MutatorContext = 0;
- JnJVM_org_j3_bindings_Bindings_freeMutator__Lorg_mmtk_plan_MutatorContext_2(context);
-}
-
-bool Collector::isLive(gc* ptr, uintptr_t closure) {
- return JnJVM_org_j3_bindings_Bindings_isLive__Lorg_mmtk_plan_TraceLocal_2Lorg_vmmagic_unboxed_ObjectReference_2(closure, ptr);
-}
-
-void Collector::scanObject(void** ptr, uintptr_t closure) {
- if ((*ptr) != NULL) {
- assert(((gc*)(*ptr))->getVirtualTable());
- }
- JnJVM_org_j3_bindings_Bindings_reportDelayedRootEdge__Lorg_mmtk_plan_TraceLocal_2Lorg_vmmagic_unboxed_Address_2(closure, ptr);
-}
-
-void Collector::markAndTrace(void* source, void* ptr, uintptr_t closure) {
- void** ptr_ = (void**)ptr;
- if ((*ptr_) != NULL) {
- assert(((gc*)(*ptr_))->getVirtualTable());
- }
- if ((*(void**)ptr) != NULL) assert(((gc*)(*(void**)ptr))->getVirtualTable());
- JnJVM_org_j3_bindings_Bindings_processEdge__Lorg_mmtk_plan_TransitiveClosure_2Lorg_vmmagic_unboxed_ObjectReference_2Lorg_vmmagic_unboxed_Address_2(closure, source, ptr);
-}
-
-void Collector::markAndTraceRoot(void* ptr, uintptr_t closure) {
- void** ptr_ = (void**)ptr;
- if ((*ptr_) != NULL) {
- assert(((gc*)(*ptr_))->getVirtualTable());
- }
- JnJVM_org_j3_bindings_Bindings_processRootEdge__Lorg_mmtk_plan_TraceLocal_2Lorg_vmmagic_unboxed_Address_2Z(closure, ptr, true);
-}
-
-gc* Collector::retainForFinalize(gc* val, uintptr_t closure) {
- return JnJVM_org_j3_bindings_Bindings_retainForFinalize__Lorg_mmtk_plan_TraceLocal_2Lorg_vmmagic_unboxed_ObjectReference_2(closure, val);
-}
-
-gc* Collector::retainReferent(gc* val, uintptr_t closure) {
- return JnJVM_org_j3_bindings_Bindings_retainReferent__Lorg_mmtk_plan_TraceLocal_2Lorg_vmmagic_unboxed_ObjectReference_2(closure, val);
-}
-
-gc* Collector::getForwardedFinalizable(gc* val, uintptr_t closure) {
- return JnJVM_org_j3_bindings_Bindings_getForwardedFinalizable__Lorg_mmtk_plan_TraceLocal_2Lorg_vmmagic_unboxed_ObjectReference_2(closure, val);
-}
-
-gc* Collector::getForwardedReference(gc* val, uintptr_t closure) {
- return JnJVM_org_j3_bindings_Bindings_getForwardedReference__Lorg_mmtk_plan_TraceLocal_2Lorg_vmmagic_unboxed_ObjectReference_2(closure, val);
-}
-
-gc* Collector::getForwardedReferent(gc* val, uintptr_t closure) {
- return JnJVM_org_j3_bindings_Bindings_getForwardedReferent__Lorg_mmtk_plan_TraceLocal_2Lorg_vmmagic_unboxed_ObjectReference_2(closure, val);
-}
-
-void Collector::collect() {
- Java_org_j3_mmtk_Collection_triggerCollection__I(NULL, 2);
-}
-
-void Collector::initialise() {
- // Allocate the memory for MMTk right now, to avoid conflicts with
- // other allocators.
-#if defined (__MACH__)
- uint32 flags = MAP_PRIVATE | MAP_ANON | MAP_FIXED;
-#else
- uint32 flags = MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED;
-#endif
- void* baseAddr = mmap((void*)0x30000000, 0x30000000, PROT_READ | PROT_WRITE,
- flags, -1, 0);
- if (baseAddr == MAP_FAILED) {
- perror("mmap");
- abort();
- }
-
- JnJVM_org_j3_bindings_Bindings_boot__Lorg_vmmagic_unboxed_Extent_2Lorg_vmmagic_unboxed_Extent_2(128 * 1024 * 1024, 1024 * 1024 * 1024);
-}
-
-extern "C" void* MMTkMutatorAllocate(uint32_t size, VirtualTable* VT) {
- void* val = MutatorThread::get()->Allocator.Allocate(size);
- ((void**)val)[0] = VT;
- return val;
-}
-
-//TODO: Remove these.
-std::set<gc*> __InternalSet__;
-void* Collector::begOf(gc* obj) {
- abort();
-}
diff --git a/vmkit/mmtk/mmtk-j3/ActivePlan.cpp b/vmkit/mmtk/mmtk-j3/ActivePlan.cpp
deleted file mode 100644
index b0765ee..0000000
--- a/vmkit/mmtk/mmtk-j3/ActivePlan.cpp
+++ /dev/null
@@ -1,49 +0,0 @@
-//===------ ActivePlan.cpp - Implementation of the ActivePlan class ------===//
-//
-// The VMKit project
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#include "debug.h"
-#include "mvm/VirtualMachine.h"
-#include "mvm/VMKit.h"
-#include "MMTkObject.h"
-#include "MutatorThread.h"
-
-namespace mmtk {
-
-extern "C" MMTkObject* Java_org_j3_mmtk_ActivePlan_getNextMutator__(MMTkActivePlan* A) {
- assert(A && "No active plan");
-
- mvm::CircularBase<mvm::Thread>* mut = A->current;
-
- if(!mut)
- mut = &mvm::Thread::get()->vmkit->runningThreads;
-
- mut = mut->next();
-
- if(mut == &mvm::Thread::get()->vmkit->runningThreads) {
- A->current = NULL;
- return NULL;
- }
-
- A->current = (mvm::MutatorThread*)mut;
-
- if (A->current->MutatorContext == 0) {
- return Java_org_j3_mmtk_ActivePlan_getNextMutator__(A);
- }
- return (MMTkObject*)A->current->MutatorContext;
-}
-
-extern "C" void Java_org_j3_mmtk_ActivePlan_resetMutatorIterator__(MMTkActivePlan* A) {
- A->current = NULL;
-}
-
-extern "C" void Java_org_j3_mmtk_ActivePlan_collectorCount__ (MMTkActivePlan* A) {
- UNIMPLEMENTED();
-}
-
-}
diff --git a/vmkit/mmtk/mmtk-j3/Assert.cpp b/vmkit/mmtk/mmtk-j3/Assert.cpp
deleted file mode 100644
index a42c1c9..0000000
--- a/vmkit/mmtk/mmtk-j3/Assert.cpp
+++ /dev/null
@@ -1,17 +0,0 @@
-//===----------- Assert.cpp - Implementation of the Assert class ---------===//
-//
-// The VMKit project
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#include "debug.h"
-#include "MMTkObject.h"
-
-namespace mmtk {
-
-extern "C" void Java_org_j3_mmtk_Assert_dumpStack__ (MMTkObject* self) { UNIMPLEMENTED(); }
-
-}
diff --git a/vmkit/mmtk/mmtk-j3/Collection.cpp b/vmkit/mmtk/mmtk-j3/Collection.cpp
deleted file mode 100644
index 0cc5df8..0000000
--- a/vmkit/mmtk/mmtk-j3/Collection.cpp
+++ /dev/null
@@ -1,102 +0,0 @@
-//===------- Collection.cpp - Implementation of the Collection class -----===//
-//
-// The VMKit project
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#include "debug.h"
-#include "mvm/VirtualMachine.h"
-#include "mvm/VMKit.h"
-#include "MMTkObject.h"
-#include "mvm/GC.h"
-
-namespace mmtk {
-
-extern "C" void JnJVM_org_mmtk_plan_Plan_setCollectionTriggered__();
-extern "C" void JnJVM_org_j3_config_Selected_00024Collector_staticCollect__();
-extern "C" void JnJVM_org_mmtk_plan_Plan_collectionComplete__();
-extern "C" uint8_t JnJVM_org_mmtk_utility_heap_HeapGrowthManager_considerHeapSize__();
-extern "C" void JnJVM_org_mmtk_utility_heap_HeapGrowthManager_reset__();
-extern "C" int64_t Java_org_j3_mmtk_Statistics_nanoTime__ ();
-extern "C" void JnJVM_org_mmtk_utility_heap_HeapGrowthManager_recordGCTime__D(double);
-
-extern "C" bool Java_org_j3_mmtk_Collection_isEmergencyAllocation__ (MMTkObject* C) {
- // TODO: emergency when OOM.
- return false;
-}
-
-extern "C" void Java_org_j3_mmtk_Collection_reportAllocationSuccess__ (MMTkObject* C) {
- // TODO: clear internal data.
-}
-
-extern "C" void Java_org_j3_mmtk_Collection_triggerCollection__I (MMTkObject* C, int why) {
- mvm::Thread* th = mvm::Thread::get();
-
- if (th->vmkit->startCollection()) {
-
- JnJVM_org_mmtk_plan_Plan_setCollectionTriggered__();
-
- // Record the starting time
- int64_t startTime = Java_org_j3_mmtk_Statistics_nanoTime__();
-
- // Collect!
- JnJVM_org_j3_config_Selected_00024Collector_staticCollect__();
-
- // Record the time to GC.
- int64_t elapsedTime = Java_org_j3_mmtk_Statistics_nanoTime__() - startTime;
-
- JnJVM_org_mmtk_utility_heap_HeapGrowthManager_recordGCTime__D(((double)elapsedTime) / 1000000);
-
- // 2 means called by System.gc();
- if (why != 2)
- JnJVM_org_mmtk_utility_heap_HeapGrowthManager_considerHeapSize__();
-
- JnJVM_org_mmtk_utility_heap_HeapGrowthManager_reset__();
-
- JnJVM_org_mmtk_plan_Plan_collectionComplete__();
-
- if (mvm::Collector::verbose > 0) {
- static int collectionNum = 1;
- if (why == 2) fprintf(stderr, "[Forced] ");
- fprintf(stderr, "Collection %d finished in %lld ms.\n", collectionNum++,
- elapsedTime / 1000000);
- }
-
- th->vmkit->endCollection();
- }
-
-}
-
-extern "C" void Java_org_j3_mmtk_Collection_joinCollection__ (MMTkObject* C) {
- mvm::Thread* th = mvm::Thread::get();
- assert(th->inRV && "Joining collection without a rendezvous");
- th->vmkit->rendezvous.join();
-}
-
-extern "C" int Java_org_j3_mmtk_Collection_rendezvous__I (MMTkObject* C, int where) {
- return 1;
-}
-
-extern "C" int Java_org_j3_mmtk_Collection_maximumCollectionAttempt__ (MMTkObject* C) {
- return 0;
-}
-
-extern "C" void Java_org_j3_mmtk_Collection_prepareCollector__Lorg_mmtk_plan_CollectorContext_2 (MMTkObject* C, MMTkObject* CC) {
- // Nothing to do.
-}
-
-extern "C" void Java_org_j3_mmtk_Collection_prepareMutator__Lorg_mmtk_plan_MutatorContext_2 (MMTkObject* C, MMTkObject* MC) {
-}
-
-
-extern "C" void Java_org_j3_mmtk_Collection_reportPhysicalAllocationFailed__ (MMTkObject* C) { UNIMPLEMENTED(); }
-extern "C" void Java_org_j3_mmtk_Collection_triggerAsyncCollection__I (MMTkObject* C, sint32 val) { UNIMPLEMENTED(); }
-extern "C" void Java_org_j3_mmtk_Collection_noThreadsInGC__ (MMTkObject* C) { UNIMPLEMENTED(); }
-extern "C" void Java_org_j3_mmtk_Collection_activeGCThreads__ (MMTkObject* C) { UNIMPLEMENTED(); }
-extern "C" void Java_org_j3_mmtk_Collection_activeGCThreadOrdinal__ (MMTkObject* C) { UNIMPLEMENTED(); }
-extern "C" void Java_org_j3_mmtk_Collection_requestMutatorFlush__ (MMTkObject* C) { UNIMPLEMENTED(); }
-
-} // namespace mmtk
diff --git a/vmkit/mmtk/mmtk-j3/FinalizableProcessor.cpp b/vmkit/mmtk/mmtk-j3/FinalizableProcessor.cpp
deleted file mode 100644
index a997f10..0000000
--- a/vmkit/mmtk/mmtk-j3/FinalizableProcessor.cpp
+++ /dev/null
@@ -1,33 +0,0 @@
-//===- FinalizableProcessor.cpp -------------------------------------------===//
-//===- Implementation of the FinalizableProcessor class ------------------===//
-//
-// The VMKit project
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#include "debug.h"
-#include "mvm/VirtualMachine.h"
-#include "mvm/VMKit.h"
-#include "MMTkObject.h"
-
-namespace mmtk {
-
-extern "C" void Java_org_j3_mmtk_FinalizableProcessor_clear__ (MMTkObject* P) {
- UNIMPLEMENTED();
-}
-
-extern "C" void
-Java_org_j3_mmtk_FinalizableProcessor_forward__Lorg_mmtk_plan_TraceLocal_2Z (MMTkObject* P, uintptr_t TL, uint8_t nursery) {
- UNIMPLEMENTED();
-}
-
-extern "C" void
-Java_org_j3_mmtk_FinalizableProcessor_scan__Lorg_mmtk_plan_TraceLocal_2Z (MMTkObject* FP, MMTkObject* TL, uint8_t nursery) {
- mvm::Thread* th = mvm::Thread::get();
- th->vmkit->scanFinalizationQueue(reinterpret_cast<uintptr_t>(TL));
-}
-
-}
diff --git a/vmkit/mmtk/mmtk-j3/Lock.cpp b/vmkit/mmtk/mmtk-j3/Lock.cpp
deleted file mode 100644
index 3bd1697..0000000
--- a/vmkit/mmtk/mmtk-j3/Lock.cpp
+++ /dev/null
@@ -1,36 +0,0 @@
-//===----------- Lock.cpp - Implementation of the Lock class -------------===//
-//
-// The VMKit project
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#include "debug.h"
-
-#include "MMTkObject.h"
-
-namespace mmtk {
-
-extern "C" void Java_org_j3_mmtk_Lock_acquire__(MMTkLock* l) {
- for (uint32 count = 0; count < 1000; ++count) {
- uint32 res = __sync_val_compare_and_swap(&(l->state), 0, 1);
- if (!res) return;
- }
-
- while (__sync_val_compare_and_swap(&(l->state), 0, 1)) {
- sched_yield();
- }
-}
-
-extern "C" void Java_org_j3_mmtk_Lock_release__(MMTkLock* l) {
- l->state = 0;
-}
-
-
-extern "C" void Java_org_j3_mmtk_Lock_check__I (MMTkLock* l, int i) {
- UNIMPLEMENTED();
-}
-
-}
diff --git a/vmkit/mmtk/mmtk-j3/MMTkObject.h b/vmkit/mmtk/mmtk-j3/MMTkObject.h
deleted file mode 100644
index b1cba5d..0000000
--- a/vmkit/mmtk/mmtk-j3/MMTkObject.h
+++ /dev/null
@@ -1,62 +0,0 @@
-//===----------- MMTkObject.h - Internal object type for MMTk ------------===//
-//
-// The VMKit project
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#ifndef MMTK_OBJECT_H
-#define MMTK_OBJECT_H
-
-#include <stdint.h>
-#include "MutatorThread.h"
-#include "mvm/GC.h"
-
-namespace mmtk {
-
-class MMTkObject;
-
-struct MMTkClass {
- MMTkObject* delegatee;
-};
-
-struct MMTkVirtualTable : public mvm::VirtualTable {
- MMTkClass* cl;
-};
-
-struct MMTkObject {
- MMTkVirtualTable* virtualTable;
- uintptr_t header;
-};
-
-struct MMTkArray : public MMTkObject {
- uintptr_t size;
- uint16_t elements[1];
-};
-
-struct MMTkString : public MMTkObject {
- MMTkArray* value;
- int32_t count;
- int32_t cachedHashCode;
- int32_t offset;
-};
-
-struct MMTkLock : public MMTkObject {
- uint32_t state;
- MMTkString* name;
-};
-
-struct MMTkActivePlan : public MMTkObject {
- mvm::MutatorThread* current;
-};
-
-struct MMTkReferenceProcessor : public MMTkObject {
- MMTkObject* semantics;
- int32_t ordinal;
-};
-
-} // namespace mmtk
-
-#endif // MMTK_OBJECT_H
diff --git a/vmkit/mmtk/mmtk-j3/MMTk_Events.cpp b/vmkit/mmtk/mmtk-j3/MMTk_Events.cpp
deleted file mode 100644
index eb472de..0000000
--- a/vmkit/mmtk/mmtk-j3/MMTk_Events.cpp
+++ /dev/null
@@ -1,35 +0,0 @@
-//===----- MMTk_Events.cpp - Implementation of the MMTk_Events class -----===//
-//
-// The VMKit project
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#include "MMTkObject.h"
-
-namespace mmtk {
-
-extern "C" void Java_org_j3_mmtk_MMTk_1Events_tracePageAcquired__Lorg_mmtk_policy_Space_2Lorg_vmmagic_unboxed_Address_2I(
- MMTkObject* event, MMTkObject* space, uintptr_t address, int numPages) {
-#if 0
- fprintf(stderr, "Pages acquired by thread %p from space %p at %x (%d)\n", (void*)mvm::Thread::get(), (void*)space, address, numPages);
-#endif
-}
-
-extern "C" void Java_org_j3_mmtk_MMTk_1Events_tracePageReleased__Lorg_mmtk_policy_Space_2Lorg_vmmagic_unboxed_Address_2I(
- MMTkObject* event, MMTkObject* space, uintptr_t address, int numPages) {
-#if 0
- fprintf(stderr, "Pages released by thread %p from space %p at %x (%d)\n", (void*)mvm::Thread::get(), (void*)space, address, numPages);
-#endif
-}
-
-extern "C" void Java_org_j3_mmtk_MMTk_1Events_heapSizeChanged__Lorg_vmmagic_unboxed_Extent_2(
- MMTkObject* event, uintptr_t heapSize) {
-#if 0
- fprintf(stderr, "New heap size : %d\n", (int)heapSize);
-#endif
-}
-
-}
diff --git a/vmkit/mmtk/mmtk-j3/Makefile b/vmkit/mmtk/mmtk-j3/Makefile
deleted file mode 100644
index 03b7ea8..0000000
--- a/vmkit/mmtk/mmtk-j3/Makefile
+++ /dev/null
@@ -1,26 +0,0 @@
-##===- mmtk/mmtk-j3/Makefile -------------------------------*- Makefile -*-===##
-#
-# The vmkit project
-#
-# This file is distributed under the University of Illinois Open Source
-# License. See LICENSE.TXT for details.
-#
-##===----------------------------------------------------------------------===##
-
-LEVEL = ../..
-
-include $(LEVEL)/Makefile.config
-
-ifeq ($(WITH_LLVM_GCC), 1)
- MODULE_NAME = MMTKRuntime
-else
- LIBRARYNAME = MMTKRuntime
-endif
-
-LOADABLE_MODULE = 1
-USEDLIBS =
-
-CXX.Flags += -I$(PROJ_SRC_DIR)/../../lib/J3/VMCore
-
-include $(LEVEL)/Makefile.common
-
diff --git a/vmkit/mmtk/mmtk-j3/Memory.cpp b/vmkit/mmtk/mmtk-j3/Memory.cpp
deleted file mode 100644
index a7eb88d..0000000
--- a/vmkit/mmtk/mmtk-j3/Memory.cpp
+++ /dev/null
@@ -1,71 +0,0 @@
-//===------------ Memory.cpp - Implementation of the Memory class --------===//
-//
-// The VMKit project
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#include "debug.h"
-#include "mvm/VirtualMachine.h"
-#include "MMTkObject.h"
-
-#include <sys/mman.h>
-
-namespace mmtk {
-
-extern "C" uintptr_t Java_org_j3_mmtk_Memory_getHeapStartConstant__ (MMTkObject* M) {
- return (uintptr_t)0x30000000;
-}
-
-extern "C" uintptr_t Java_org_j3_mmtk_Memory_getHeapEndConstant__ (MMTkObject* M) {
- return (uintptr_t)0x60000000;
-}
-
-extern "C" uintptr_t Java_org_j3_mmtk_Memory_getAvailableStartConstant__ (MMTkObject* M) {
- return (uintptr_t)0x30000000;
-}
-
-extern "C" uintptr_t Java_org_j3_mmtk_Memory_getAvailableEndConstant__ (MMTkObject* M) {
- return (uintptr_t)0x60000000;
-}
-
-extern "C" sint32
-Java_org_j3_mmtk_Memory_dzmmap__Lorg_vmmagic_unboxed_Address_2I(MMTkObject* M,
- void* start,
- sint32 size) {
- // Already mmapped during initialization.
- return 0;
-}
-
-extern "C" uint8_t
-Java_org_j3_mmtk_Memory_mprotect__Lorg_vmmagic_unboxed_Address_2I (MMTkObject* M, uintptr_t address, sint32 size) {
- int val = mprotect((void*)address, size, PROT_NONE);
- return (val == 0);
-}
-
-extern "C" uint8_t
-Java_org_j3_mmtk_Memory_munprotect__Lorg_vmmagic_unboxed_Address_2I (MMTkObject* M, uintptr_t address, sint32 size) {
- int val = mprotect((void*)address, size, PROT_READ | PROT_WRITE);
- return (val == 0);
-}
-
-extern "C" void
-Java_org_j3_mmtk_Memory_zero__Lorg_vmmagic_unboxed_Address_2Lorg_vmmagic_unboxed_Extent_2(MMTkObject* M,
- void* addr,
- uintptr_t len) {
- memset(addr, 0, len);
-}
-
-extern "C" void
-Java_org_j3_mmtk_Memory_zeroPages__Lorg_vmmagic_unboxed_Address_2I (MMTkObject* M, uintptr_t address, sint32 size) {
- UNIMPLEMENTED();
-}
-
-extern "C" void
-Java_org_j3_mmtk_Memory_dumpMemory__Lorg_vmmagic_unboxed_Address_2II (MMTkObject* M, uintptr_t address, sint32 before, sint32 after) {
- UNIMPLEMENTED();
-}
-
-}
diff --git a/vmkit/mmtk/mmtk-j3/ObjectModel.cpp b/vmkit/mmtk/mmtk-j3/ObjectModel.cpp
deleted file mode 100644
index 79e5c67..0000000
--- a/vmkit/mmtk/mmtk-j3/ObjectModel.cpp
+++ /dev/null
@@ -1,161 +0,0 @@
-//===---- ObjectModel.cpp - Implementation of the ObjectModel class ------===//
-//
-// The VMKit project
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#include "mvm/VirtualMachine.h"
-#include "MMTkObject.h"
-#include "debug.h"
-
-namespace mmtk {
-
-extern "C" intptr_t Java_org_j3_mmtk_ObjectModel_getArrayBaseOffset__ (MMTkObject* OM) {
- return sizeof(MMTkObject) + sizeof(ssize_t);
-}
-
-extern "C" intptr_t Java_org_j3_mmtk_ObjectModel_GC_1HEADER_1OFFSET__ (MMTkObject* OM) {
- return sizeof(void*);
-}
-
-extern "C" uintptr_t Java_org_j3_mmtk_ObjectModel_readAvailableBitsWord__Lorg_vmmagic_unboxed_ObjectReference_2 (MMTkObject* OM, mvm::gc* obj) {
- return obj->header;
-}
-
-extern "C" void Java_org_j3_mmtk_ObjectModel_writeAvailableBitsWord__Lorg_vmmagic_unboxed_ObjectReference_2Lorg_vmmagic_unboxed_Word_2 (
- MMTkObject* OM, mvm::gc* obj, uintptr_t val) {
- obj->header = val;
-}
-
-extern "C" mvm::gc* Java_org_j3_mmtk_ObjectModel_objectStartRef__Lorg_vmmagic_unboxed_ObjectReference_2 (MMTkObject* OM, mvm::gc* obj) {
- return obj;
-}
-
-extern "C" mvm::gc* Java_org_j3_mmtk_ObjectModel_refToAddress__Lorg_vmmagic_unboxed_ObjectReference_2 (MMTkObject* OM, mvm::gc* obj) {
- return obj;
-}
-
-extern "C" uint8_t Java_org_j3_mmtk_ObjectModel_readAvailableByte__Lorg_vmmagic_unboxed_ObjectReference_2 (MMTkObject* OM, mvm::gc* obj) {
-#if defined(__PPC__)
- return ((uint8_t*)obj)[7];
-#else
- return ((uint8_t*)obj)[4];
-#endif
-}
-
-extern "C" void Java_org_j3_mmtk_ObjectModel_writeAvailableByte__Lorg_vmmagic_unboxed_ObjectReference_2B (MMTkObject* OM, mvm::gc* obj, uint8_t val) {
-#if defined(__PPC__)
- ((uint8_t*)obj)[7] = val;
-#else
- ((uint8_t*)obj)[4] = val;
-#endif
-}
-
-extern "C" mvm::gc* Java_org_j3_mmtk_ObjectModel_getObjectFromStartAddress__Lorg_vmmagic_unboxed_Address_2 (MMTkObject* OM, mvm::gc* obj) {
- return obj;
-}
-
-extern "C" uintptr_t Java_org_j3_mmtk_ObjectModel_prepareAvailableBits__Lorg_vmmagic_unboxed_ObjectReference_2 (MMTkObject* OM, mvm::gc* obj) {
- return obj->header;
-}
-
-extern "C" uint8_t
-Java_org_j3_mmtk_ObjectModel_attemptAvailableBits__Lorg_vmmagic_unboxed_ObjectReference_2Lorg_vmmagic_unboxed_Word_2Lorg_vmmagic_unboxed_Word_2(
- MMTkObject* OM, mvm::gc* obj, intptr_t oldValue, intptr_t newValue) {
- intptr_t val = __sync_val_compare_and_swap(&(obj->header), oldValue, newValue);
- return (val == oldValue);
-}
-
-extern "C" void Java_org_j3_bindings_Bindings_memcpy__Lorg_vmmagic_unboxed_ObjectReference_2Lorg_vmmagic_unboxed_ObjectReference_2I(
- void* res, void* src, int size) ALWAYS_INLINE;
-
-extern "C" void Java_org_j3_bindings_Bindings_memcpy__Lorg_vmmagic_unboxed_ObjectReference_2Lorg_vmmagic_unboxed_ObjectReference_2I(
- void* res, void* src, int size) {
- memcpy(res, src, size);
-}
-
-extern "C" uintptr_t JnJVM_org_j3_bindings_Bindings_copy__Lorg_vmmagic_unboxed_ObjectReference_2Lorg_vmmagic_unboxed_ObjectReference_2II(
- mvm::gc* obj, mvm::VirtualTable* VT, int size, int allocator) ALWAYS_INLINE;
-
-extern "C" uintptr_t Java_org_j3_mmtk_ObjectModel_copy__Lorg_vmmagic_unboxed_ObjectReference_2I (
- MMTkObject* OM, mvm::gc* src, int allocator) ALWAYS_INLINE;
-
-extern "C" uintptr_t Java_org_j3_mmtk_ObjectModel_copy__Lorg_vmmagic_unboxed_ObjectReference_2I (
- MMTkObject* OM, mvm::gc* src, int allocator) {
- size_t size = src->getVirtualTable()->vm->getObjectSize(src);
- size = llvm::RoundUpToAlignment(size, sizeof(void*));
- uintptr_t res = JnJVM_org_j3_bindings_Bindings_copy__Lorg_vmmagic_unboxed_ObjectReference_2Lorg_vmmagic_unboxed_ObjectReference_2II(
- src, src->getVirtualTable(), size, allocator);
- assert((((uintptr_t*)res)[1] & ~mvm::GCBitMask) == (((uintptr_t*)src)[1] & ~mvm::GCBitMask));
- return res;
-}
-
-extern "C" void Java_org_j3_mmtk_ObjectModel_copyTo__Lorg_vmmagic_unboxed_ObjectReference_2Lorg_vmmagic_unboxed_ObjectReference_2Lorg_vmmagic_unboxed_Address_2 (
- MMTkObject* OM, uintptr_t from, uintptr_t to, uintptr_t region) { UNIMPLEMENTED(); }
-
-extern "C" void Java_org_j3_mmtk_ObjectModel_getReferenceWhenCopiedTo__Lorg_vmmagic_unboxed_ObjectReference_2Lorg_vmmagic_unboxed_Address_2 (
- MMTkObject* OM, uintptr_t from, uintptr_t to) { UNIMPLEMENTED(); }
-
-extern "C" void Java_org_j3_mmtk_ObjectModel_getObjectEndAddress__Lorg_vmmagic_unboxed_ObjectReference_2 (
- MMTkObject* OM, uintptr_t object) { UNIMPLEMENTED(); }
-
-extern "C" void Java_org_j3_mmtk_ObjectModel_getSizeWhenCopied__Lorg_vmmagic_unboxed_ObjectReference_2 (
- MMTkObject* OM, uintptr_t object) { UNIMPLEMENTED(); }
-
-extern "C" void Java_org_j3_mmtk_ObjectModel_getAlignWhenCopied__Lorg_vmmagic_unboxed_ObjectReference_2 (
- MMTkObject* OM, uintptr_t object) { UNIMPLEMENTED(); }
-
-extern "C" void Java_org_j3_mmtk_ObjectModel_getAlignOffsetWhenCopied__Lorg_vmmagic_unboxed_ObjectReference_2 (
- MMTkObject* OM, uintptr_t object) { UNIMPLEMENTED(); }
-
-extern "C" void Java_org_j3_mmtk_ObjectModel_getCurrentSize__Lorg_vmmagic_unboxed_ObjectReference_2 (
- MMTkObject* OM, uintptr_t object) { UNIMPLEMENTED(); }
-
-extern "C" void Java_org_j3_mmtk_ObjectModel_getNextObject__Lorg_vmmagic_unboxed_ObjectReference_2 (
- MMTkObject* OM, uintptr_t object) { UNIMPLEMENTED(); }
-
-
-class FakeByteArray : public MMTkObject {
- public:
- void* operator new(size_t size, int length) {
- return new char[size + length];
- }
-
- FakeByteArray(const char* name) {
- length = strlen(name);
- for (uint32 i = 0; i < length; i++) {
- elements[i] = name[i];
- }
- }
- private:
- size_t length;
- uint8_t elements[1];
-};
-
-extern "C" FakeByteArray* Java_org_j3_mmtk_ObjectModel_getTypeDescriptor__Lorg_vmmagic_unboxed_ObjectReference_2 (
- MMTkObject* OM, mvm::gc* src) {
- const char* name = src->getVirtualTable()->vm->getObjectTypeName(src);
- // This code is only used for debugging on a fatal error. It is fine to
- // allocate in the C++ heap.
- return new (strlen(name)) FakeByteArray(name);
-}
-
-extern "C" void Java_org_j3_mmtk_ObjectModel_getArrayLength__Lorg_vmmagic_unboxed_ObjectReference_2 (
- MMTkObject* OM, uintptr_t object) { UNIMPLEMENTED(); }
-
-extern "C" void Java_org_j3_mmtk_ObjectModel_isArray__Lorg_vmmagic_unboxed_ObjectReference_2 (
- MMTkObject* OM, uintptr_t object) { UNIMPLEMENTED(); }
-
-extern "C" void Java_org_j3_mmtk_ObjectModel_isPrimitiveArray__Lorg_vmmagic_unboxed_ObjectReference_2 (
- MMTkObject* OM, uintptr_t object) { UNIMPLEMENTED(); }
-
-extern "C" void Java_org_j3_mmtk_ObjectModel_isAcyclic__Lorg_vmmagic_unboxed_ObjectReference_2 (
- MMTkObject* OM, uintptr_t object) { UNIMPLEMENTED(); }
-
-extern "C" void Java_org_j3_mmtk_ObjectModel_dumpObject__Lorg_vmmagic_unboxed_ObjectReference_2 (
- MMTkObject* OM, uintptr_t object) { UNIMPLEMENTED(); }
-
-}
diff --git a/vmkit/mmtk/mmtk-j3/ReferenceProcessor.cpp b/vmkit/mmtk/mmtk-j3/ReferenceProcessor.cpp
deleted file mode 100644
index c06bc30..0000000
--- a/vmkit/mmtk/mmtk-j3/ReferenceProcessor.cpp
+++ /dev/null
@@ -1,37 +0,0 @@
-//===-------- ReferenceProcessor.cpp --------------------------------------===//
-//===-------- Implementation of the Selected class -----------------------===//
-//
-// The VMKit project
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#include "debug.h"
-#include "mvm/VirtualMachine.h"
-#include "mvm/VMKit.h"
-#include "mvm/SystemThreads.h"
-#include "MMTkObject.h"
-
-namespace mmtk {
-
-extern "C" void Java_org_j3_mmtk_ReferenceProcessor_scan__Lorg_mmtk_plan_TraceLocal_2Z (MMTkReferenceProcessor* RP, uintptr_t TL, uint8_t nursery) {
- mvm::Thread* th = mvm::Thread::get();
- uint32_t val = RP->ordinal;
-
- if (val == 0) {
- th->vmkit->scanSoftReferencesQueue(TL);
- } else if (val == 1) {
- th->vmkit->scanWeakReferencesQueue(TL);
- } else {
- assert(val == 2);
- th->vmkit->scanPhantomReferencesQueue(TL);
- }
-}
-
-extern "C" void Java_org_j3_mmtk_ReferenceProcessor_forward__Lorg_mmtk_plan_TraceLocal_2Z (MMTkReferenceProcessor* RP, uintptr_t TL, uint8_t nursery) { UNIMPLEMENTED(); }
-extern "C" void Java_org_j3_mmtk_ReferenceProcessor_clear__ (MMTkReferenceProcessor* RP) { UNIMPLEMENTED(); }
-extern "C" void Java_org_j3_mmtk_ReferenceProcessor_countWaitingReferences__ (MMTkReferenceProcessor* RP) { UNIMPLEMENTED(); }
-
-}
diff --git a/vmkit/mmtk/mmtk-j3/RuntimeHelpers.cpp b/vmkit/mmtk/mmtk-j3/RuntimeHelpers.cpp
deleted file mode 100644
index f9cf6c5..0000000
--- a/vmkit/mmtk/mmtk-j3/RuntimeHelpers.cpp
+++ /dev/null
@@ -1,22 +0,0 @@
-//===-- RuntimeHelpers.cpp - Implement rt.jar functions needed by MMTk --===//
-//
-// The VMKit project
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#include "MMTkObject.h"
-
-namespace mmtk {
-
-extern "C" uint16_t MMTkCharAt(MMTkString* str, uint32_t index) {
- return str->value->elements[index];
-}
-
-extern "C" MMTkObject* MMTkGetClass(MMTkObject* obj) {
- return obj->virtualTable->cl->delegatee;
-}
-
-}
diff --git a/vmkit/mmtk/mmtk-j3/Scanning.cpp b/vmkit/mmtk/mmtk-j3/Scanning.cpp
deleted file mode 100644
index 6e04f65..0000000
--- a/vmkit/mmtk/mmtk-j3/Scanning.cpp
+++ /dev/null
@@ -1,72 +0,0 @@
-//===-------- Scanning.cpp - Implementation of the Scanning class --------===//
-//
-// The VMKit project
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#include "debug.h"
-#include "mvm/VirtualMachine.h"
-#include "MMTkObject.h"
-#include "mvm/GC.h"
-#include "mvm/VMKit.h"
-
-namespace mmtk {
-
-extern "C" void Java_org_j3_mmtk_Scanning_computeThreadRoots__Lorg_mmtk_plan_TraceLocal_2 (MMTkObject* Scanning, MMTkObject* TL) {
- // When entering this function, all threads are waiting on the rendezvous to
- // finish.
- mvm::VMKit* vmkit = mvm::Thread::get()->vmkit;
- mvm::Thread* tcur;
-
- for(tcur=vmkit->runningThreads.next(); tcur!=&vmkit->runningThreads; tcur=tcur->next()) {
- tcur->scanStack(reinterpret_cast<uintptr_t>(TL));
- }
-}
-
-extern "C" void Java_org_j3_mmtk_Scanning_computeGlobalRoots__Lorg_mmtk_plan_TraceLocal_2 (MMTkObject* Scanning, MMTkObject* TL) {
- mvm::Thread::get()->vmkit->tracer(reinterpret_cast<uintptr_t>(TL));
-
- mvm::VMKit* vmkit = mvm::Thread::get()->vmkit;
- mvm::Thread* tcur;
-
- for(tcur=vmkit->runningThreads.next(); tcur!=&vmkit->runningThreads; tcur=tcur->next()) {
- tcur->tracer(reinterpret_cast<uintptr_t>(TL));
- }
-}
-
-extern "C" void Java_org_j3_mmtk_Scanning_computeStaticRoots__Lorg_mmtk_plan_TraceLocal_2 (MMTkObject* Scanning, MMTkObject* TL) {
- // Nothing to do.
-}
-
-extern "C" void Java_org_j3_mmtk_Scanning_resetThreadCounter__ (MMTkObject* Scanning) {
- // Nothing to do.
-}
-
-extern "C" void Java_org_j3_mmtk_Scanning_specializedScanObject__ILorg_mmtk_plan_TransitiveClosure_2Lorg_vmmagic_unboxed_ObjectReference_2 (MMTkObject* Scanning, uint32_t id, MMTkObject* TC, mvm::gc* obj) ALWAYS_INLINE;
-
-extern "C" void Java_org_j3_mmtk_Scanning_specializedScanObject__ILorg_mmtk_plan_TransitiveClosure_2Lorg_vmmagic_unboxed_ObjectReference_2 (MMTkObject* Scanning, uint32_t id, MMTkObject* TC, mvm::gc* obj) {
- assert(obj && "No object to trace");
- assert(obj->getVirtualTable() && "No virtual table");
- assert(obj->getVirtualTable()->tracer && "No tracer in VT");
- obj->tracer(reinterpret_cast<uintptr_t>(TC));
-}
-
-extern "C" void Java_org_j3_mmtk_Scanning_preCopyGCInstances__Lorg_mmtk_plan_TraceLocal_2 (MMTkObject* Scanning, MMTkObject* TL) {
- // Nothing to do, there are no GC objects on which the GC depends.
-}
-
-extern "C" void Java_org_j3_mmtk_Scanning_scanObject__Lorg_mmtk_plan_TransitiveClosure_2Lorg_vmmagic_unboxed_ObjectReference_2 (
- MMTkObject* Scanning, uintptr_t TC, mvm::gc* obj) {
- assert(obj && "No object to trace");
- assert(obj->getVirtualTable() && "No virtual table");
- assert(obj->getVirtualTable()->tracer && "No tracer in VT");
- obj->tracer(TC);
-}
-
-extern "C" void Java_org_j3_mmtk_Scanning_precopyChildren__Lorg_mmtk_plan_TraceLocal_2Lorg_vmmagic_unboxed_ObjectReference_2 (
- MMTkObject* Scanning, MMTkObject TL, uintptr_t ref) { UNIMPLEMENTED(); }
-
-}
diff --git a/vmkit/mmtk/mmtk-j3/Selected.cpp b/vmkit/mmtk/mmtk-j3/Selected.cpp
deleted file mode 100644
index 0b57e10..0000000
--- a/vmkit/mmtk/mmtk-j3/Selected.cpp
+++ /dev/null
@@ -1,19 +0,0 @@
-//===-------- Selected.cpp - Implementation of the Selected class --------===//
-//
-// The VMKit project
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#include "MutatorThread.h"
-#include "MMTkObject.h"
-
-namespace mmtk {
-
-extern "C" MMTkObject* Java_org_j3_config_Selected_00024Mutator_get__() {
- return (MMTkObject*)mvm::MutatorThread::get()->MutatorContext;
-}
-
-}
diff --git a/vmkit/mmtk/mmtk-j3/Statistics.cpp b/vmkit/mmtk/mmtk-j3/Statistics.cpp
deleted file mode 100644
index 7a6d699..0000000
--- a/vmkit/mmtk/mmtk-j3/Statistics.cpp
+++ /dev/null
@@ -1,47 +0,0 @@
-//===----- Statistics.cpp - Implementation of the Statistics class -------===//
-//
-// The VMKit project
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#include "MMTkObject.h"
-
-#include <sys/time.h>
-#include <ctime>
-
-namespace mmtk {
-
-extern "C" int64_t Java_org_j3_mmtk_Statistics_cycles__ (MMTkObject* S) {
- return 0;
-}
-
-extern "C" int64_t Java_org_j3_mmtk_Statistics_nanoTime__ (MMTkObject* S) {
- int64_t result;
- struct timeval tp;
-
- int res = gettimeofday (&tp, NULL);
- assert(res != -1 && "failed gettimeofday.");
-
- result = (int64_t) tp.tv_sec;
- result *= (int64_t)1000000L;
- result += (int64_t)tp.tv_usec;
- result *= (int64_t)1000;
-
- return result;
-}
-
-
-extern "C" int32_t Java_org_j3_mmtk_Statistics_getCollectionCount__ (MMTkObject* S) {
- return 0;
-}
-
-extern "C" void Java_org_j3_mmtk_Statistics_perfEventInit__Ljava_lang_String_2(MMTkObject* S, MMTkObject* Str) {
-}
-
-extern "C" void Java_org_j3_mmtk_Statistics_perfEventRead__I_3J(MMTkObject* S, int id, int64_t* values) {
-}
-
-} // namespace mmtk
diff --git a/vmkit/mmtk/mmtk-j3/Strings.cpp b/vmkit/mmtk/mmtk-j3/Strings.cpp
deleted file mode 100644
index 991ebff..0000000
--- a/vmkit/mmtk/mmtk-j3/Strings.cpp
+++ /dev/null
@@ -1,51 +0,0 @@
-//===--------- Strings.cpp - Implementation of the Strings class ---------===//
-//
-// The VMKit project
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#include "mvm/Threads/Thread.h"
-
-#include "MMTkObject.h"
-
-namespace mmtk {
-
-extern "C" void Java_org_j3_mmtk_Strings_write___3CI(MMTkObject* str,
- MMTkArray* msg,
- sint32 len) {
- for (sint32 i = 0; i < len; ++i) {
- fprintf(stderr, "%c", msg->elements[i]);
- }
-}
-
-extern "C" void Java_org_j3_mmtk_Strings_writeThreadId___3CI(MMTkObject* str,
- MMTkArray* msg,
- sint32 len) {
- fprintf(stderr, "[%p] ", (void*)mvm::Thread::get());
-
- for (sint32 i = 0; i < len; ++i) {
- fprintf(stderr, "%c", msg->elements[i]);
- }
-}
-
-
-extern "C" sint32
-Java_org_j3_mmtk_Strings_copyStringToChars__Ljava_lang_String_2_3CII(
- MMTkObject* obj, MMTkString* str, MMTkArray* dst, uint32 dstBegin,
- uint32 dstEnd) {
-
- sint32 len = str->count;
- sint32 n = (dstBegin + len <= dstEnd) ? len : (dstEnd - dstBegin);
-
- for (sint32 i = 0; i < n; i++) {
- dst->elements[dstBegin + i] = str->value->elements[str->offset + i];
- }
-
- return n;
-
-}
-
-} // end namespace mmtk
diff --git a/vmkit/mmtk/mmtk-j3/SynchronizedCounter.cpp b/vmkit/mmtk/mmtk-j3/SynchronizedCounter.cpp
deleted file mode 100644
index 20986bd..0000000
--- a/vmkit/mmtk/mmtk-j3/SynchronizedCounter.cpp
+++ /dev/null
@@ -1,19 +0,0 @@
-//===-------- SynchronizedCounter.cpp -------------------------------------===//
-//===-------- Implementation of the SynchronizedCounter class ------------===//
-//
-// The VMKit project
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#include "MMTkObject.h"
-#include "debug.h"
-
-namespace mmtk {
-
-extern "C" void Java_org_j3_mmtk_SynchronizedCounter_reset__ (MMTkObject* self) { UNIMPLEMENTED(); }
-extern "C" void Java_org_j3_mmtk_SynchronizedCounter_increment__ (MMTkObject* self) { UNIMPLEMENTED(); }
-
-} // end namespace mmtk
diff --git a/vmkit/mmtk/mmtk-j3/TraceInterface.cpp b/vmkit/mmtk/mmtk-j3/TraceInterface.cpp
deleted file mode 100644
index a86db76..0000000
--- a/vmkit/mmtk/mmtk-j3/TraceInterface.cpp
+++ /dev/null
@@ -1,56 +0,0 @@
-//===-- TraceInterface.cpp - Implementation of the TraceInterface class --===//
-//
-// The VMKit project
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#include "debug.h"
-#include "MMTkObject.h"
-
-namespace mmtk {
-
-extern "C" bool Java_org_j3_mmtk_TraceInterface_gcEnabled__ (MMTkObject* TI) { UNIMPLEMENTED(); }
-
-extern "C" void Java_org_j3_mmtk_TraceInterface_adjustSlotOffset__ZLorg_vmmagic_unboxed_ObjectReference_2Lorg_vmmagic_unboxed_Address_2 (
- MMTkObject* TI, bool scalar, uintptr_t src, uintptr_t slot) { UNIMPLEMENTED(); }
-
-extern "C" void Java_org_j3_mmtk_TraceInterface_skipOwnFramesAndDump__Lorg_vmmagic_unboxed_ObjectReference_2 (
- MMTkObject* TI, uintptr_t typeRef) { UNIMPLEMENTED(); }
-
-extern "C" void Java_org_j3_mmtk_TraceInterface_updateDeathTime__Lorg_vmmagic_unboxed_ObjectReference_2 (
- MMTkObject* TI, uintptr_t obj) { UNIMPLEMENTED(); }
-
-extern "C" void Java_org_j3_mmtk_TraceInterface_setDeathTime__Lorg_vmmagic_unboxed_ObjectReference_2Lorg_vmmagic_unboxed_Word_2 (
- MMTkObject* TI, uintptr_t ref, uintptr_t time) { UNIMPLEMENTED(); }
-
-extern "C" void Java_org_j3_mmtk_TraceInterface_setLink__Lorg_vmmagic_unboxed_ObjectReference_2Lorg_vmmagic_unboxed_ObjectReference_2 (
- MMTkObject* TI, uintptr_t ref, uintptr_t link) { UNIMPLEMENTED(); }
-
-extern "C" void Java_org_j3_mmtk_TraceInterface_updateTime__Lorg_vmmagic_unboxed_Word_2 (
- MMTkObject* TI, uintptr_t obj) { UNIMPLEMENTED(); }
-
-extern "C" void Java_org_j3_mmtk_TraceInterface_getOID__Lorg_vmmagic_unboxed_ObjectReference_2 (
- MMTkObject* TI, uintptr_t ref) { UNIMPLEMENTED(); }
-
-extern "C" uintptr_t Java_org_j3_mmtk_TraceInterface_getDeathTime__Lorg_vmmagic_unboxed_ObjectReference_2 (
- MMTkObject* TI, uintptr_t ref) { UNIMPLEMENTED(); }
-
-extern "C" uintptr_t Java_org_j3_mmtk_TraceInterface_getLink__Lorg_vmmagic_unboxed_ObjectReference_2 (
- MMTkObject* TI, uintptr_t ref) { UNIMPLEMENTED(); }
-
-extern "C" uintptr_t Java_org_j3_mmtk_TraceInterface_getBootImageLink__ (
- MMTkObject* TI) { UNIMPLEMENTED(); }
-
-extern "C" uintptr_t Java_org_j3_mmtk_TraceInterface_getOID__ (
- MMTkObject* TI) { UNIMPLEMENTED(); }
-
-extern "C" void Java_org_j3_mmtk_TraceInterface_setOID__Lorg_vmmagic_unboxed_Word_2 (
- MMTkObject* TI, uintptr_t oid) { UNIMPLEMENTED(); }
-
-extern "C" sint32 Java_org_j3_mmtk_TraceInterface_getHeaderSize__ (MMTkObject* TI) { UNIMPLEMENTED(); }
-extern "C" sint32 Java_org_j3_mmtk_TraceInterface_getHeaderEndOffset__ (MMTkObject* TI) { UNIMPLEMENTED(); }
-
-} // namespace mmtk
diff --git a/vmkit/mmtk/mmtk-j3/VM.cpp b/vmkit/mmtk/mmtk-j3/VM.cpp
deleted file mode 100644
index b10b7a2..0000000
--- a/vmkit/mmtk/mmtk-j3/VM.cpp
+++ /dev/null
@@ -1,68 +0,0 @@
-//===-------------- VM.cpp - Implementation of the VM class --------------===//
-//
-// The VMKit project
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#include "debug.h"
-#include "MMTkObject.h"
-
-namespace mmtk {
-
-extern "C" void Java_org_j3_runtime_VM_sysWrite__Lorg_vmmagic_unboxed_Extent_2 (uintptr_t e) { UNIMPLEMENTED(); }
-extern "C" void Java_org_j3_runtime_VM_sysWrite__Lorg_vmmagic_unboxed_Address_2 (uintptr_t a) { UNIMPLEMENTED(); }
-extern "C" void Java_org_j3_runtime_VM_sysWrite__F (float f) { UNIMPLEMENTED(); }
-extern "C" void Java_org_j3_runtime_VM_sysWrite__I (int i) { UNIMPLEMENTED(); }
-extern "C" void Java_org_j3_runtime_VM_sysWrite__Ljava_lang_String_2 (MMTkString* msg) { UNIMPLEMENTED(); }
-extern "C" void Java_org_j3_runtime_VM_sysWriteln__ () { UNIMPLEMENTED(); }
-extern "C" void Java_org_j3_runtime_VM_sysWriteln__Ljava_lang_String_2 (MMTkString* msg) { UNIMPLEMENTED(); }
-
-extern "C" void Java_org_j3_runtime_VM__1assert__ZLjava_lang_String_2 (bool cond, MMTkString* msg) {
- ABORT();
-}
-
-extern "C" void Java_org_j3_runtime_VM_sysExit__I (int i) {
- ABORT();
-}
-
-extern "C" void Java_org_j3_runtime_VM_sysFail__Ljava_lang_String_2 (MMTkString* msg) {
- // Just call abort because gcmalloc calls this function. If it were to
- // call printf, MMTkInline.inc could not be JIT-compiled.
- abort();
-}
-
-extern "C" void Java_org_j3_runtime_VM__1assert__Z (uint8_t cond) {
- ASSERT(cond);
-}
-
-extern "C" bool Java_org_j3_runtime_VM_buildFor64Addr__ () {
-#if (__WORDSIZE==64)
- return true;
-#else
- return false;
-#endif
-}
-
-extern "C" bool Java_org_j3_runtime_VM_buildForIA32__ () {
-#if defined(__i386__) || defined(i386) || defined(_M_IX86)
- return true;
-#else
- return false;
-#endif
-}
-
-extern "C" bool Java_org_j3_runtime_VM_verifyAssertions__ () {
- // Note that DEBUG is defined in make ENABLE_OPTIMIZED=1.
- // You must provide DISABLE_ASSERTIONS=1 to not have DEBUG defined.
- // To generate MMTkInline.inc, this function returns false.
-#if 0
- return true;
-#else
- return false;
-#endif
-}
-
-} // namespace mmtk
diff --git a/vmkit/patches/vmkit-llvm-ppc.patch b/vmkit/patches/vmkit-llvm-ppc.patch
deleted file mode 100644
index a5f0cad..0000000
--- a/vmkit/patches/vmkit-llvm-ppc.patch
+++ /dev/null
@@ -1,339 +0,0 @@
-Index: PPCInstrInfo.td
-===================================================================
---- PPCInstrInfo.td (revision 50006)
-+++ PPCInstrInfo.td (working copy)
-@@ -1212,6 +1212,8 @@
- (BL_ELF texternalsym:$dst)>;
-
- // Hi and Lo for Darwin Global Addresses.
-+def : Pat<(PPChi texternalsym:$in, 0), (LIS texternalsym:$in)>;
-+def : Pat<(PPClo texternalsym:$in, 0), (LI texternalsym:$in)>;
- def : Pat<(PPChi tglobaladdr:$in, 0), (LIS tglobaladdr:$in)>;
- def : Pat<(PPClo tglobaladdr:$in, 0), (LI tglobaladdr:$in)>;
- def : Pat<(PPChi tconstpool:$in, 0), (LIS tconstpool:$in)>;
-Index: PPCJITInfo.cpp
-===================================================================
---- PPCJITInfo.cpp (revision 50006)
-+++ PPCJITInfo.cpp (working copy)
-@@ -13,12 +13,16 @@
-
- #define DEBUG_TYPE "jit"
- #include "PPCJITInfo.h"
-+#include "PPCRegisterInfo.h"
- #include "PPCRelocations.h"
- #include "PPCTargetMachine.h"
- #include "llvm/Function.h"
- #include "llvm/CodeGen/MachineCodeEmitter.h"
- #include "llvm/Config/alloca.h"
-+#include "llvm/ExecutionEngine/ExecutionEngine.h"
- #include "llvm/Support/Debug.h"
-+#include "llvm/Support/Dwarf.h"
-+#include "llvm/Target/TargetOptions.h"
- #include <set>
- using namespace llvm;
-
-@@ -53,24 +57,27 @@
- if (Offset >= -(1 << 23) && Offset < (1 << 23)) { // In range?
- AtI[0] = BUILD_B(Offset, isCall); // b/bl target
- } else if (!is64Bit) {
-- AtI[0] = BUILD_LIS(12, To >> 16); // lis r12, hi16(address)
-+ AtI[0] = BUILD_B(0, false); // thread safety
- AtI[1] = BUILD_ORI(12, 12, To); // ori r12, r12, lo16(address)
- AtI[2] = BUILD_MTCTR(12); // mtctr r12
- AtI[3] = BUILD_BCTR(isCall); // bctr/bctrl
-+ AtI[0] = BUILD_LIS(12, To >> 16); // lis r12, hi16(address)
- } else {
-- AtI[0] = BUILD_LIS(12, To >> 48); // lis r12, hi16(address)
-+ AtI[0] = BUILD_B(0, false); // thread safety
- AtI[1] = BUILD_ORI(12, 12, To >> 32); // ori r12, r12, lo16(address)
- AtI[2] = BUILD_SLDI(12, 12, 32); // sldi r12, r12, 32
- AtI[3] = BUILD_ORIS(12, 12, To >> 16); // oris r12, r12, hi16(address)
- AtI[4] = BUILD_ORI(12, 12, To); // ori r12, r12, lo16(address)
- AtI[5] = BUILD_MTCTR(12); // mtctr r12
- AtI[6] = BUILD_BCTR(isCall); // bctr/bctrl
-+ AtI[0] = BUILD_LIS(12, To >> 48); // lis r12, hi16(address)
- }
- }
-
- extern "C" void PPC32CompilationCallback();
- extern "C" void PPC64CompilationCallback();
-
-+
- #if (defined(__POWERPC__) || defined (__ppc__) || defined(_POWER)) && \
- !defined(__ppc64__)
- // CompilationCallback stub - We can't use a C function with inline assembly in
-@@ -144,6 +151,9 @@
- // it, because we the prolog/epilog inserted by GCC won't work for us. Instead,
- // write our own wrapper, which does things our way, so we have complete control
- // over register saving and restoring.
-+
-+# define CFI(x) x
-+
- asm(
- ".text\n"
- ".align 2\n"
-@@ -156,19 +166,29 @@
- // FIXME Layout
- // 8 double registers - 64 bytes
- // 8 int registers - 32 bytes
-+ CFI(".cfi_startproc\n")
-+ "stwu 1, -104(1)\n"
-+ CFI(".cfi_adjust_cfa_offset 104\n")
- "mflr 0\n"
-- "stw 0, 4(1)\n"
-- "stwu 1, -104(1)\n"
-+ "stw 0, 108(1)\n"
-+ CFI(".cfi_offset lr, 4\n")
- // Save all int arg registers
-- "stw 10, 100(1)\n" "stw 9, 96(1)\n"
-- "stw 8, 92(1)\n" "stw 7, 88(1)\n"
-- "stw 6, 84(1)\n" "stw 5, 80(1)\n"
-- "stw 4, 76(1)\n" "stw 3, 72(1)\n"
-+ "stw 10, 100(1)\n"
-+ "stw 9, 96(1)\n"
-+ "stw 8, 92(1)\n"
-+ "stw 7, 88(1)\n"
-+ "stw 6, 84(1)\n"
-+ "stw 5, 80(1)\n"
-+ "stw 4, 76(1)\n"
-+ "stw 3, 72(1)\n"
- // Save all call-clobbered FP regs.
- "stfd 8, 64(1)\n"
-- "stfd 7, 56(1)\n" "stfd 6, 48(1)\n"
-- "stfd 5, 40(1)\n" "stfd 4, 32(1)\n"
-- "stfd 3, 24(1)\n" "stfd 2, 16(1)\n"
-+ "stfd 7, 56(1)\n"
-+ "stfd 6, 48(1)\n"
-+ "stfd 5, 40(1)\n"
-+ "stfd 4, 32(1)\n"
-+ "stfd 3, 24(1)\n"
-+ "stfd 2, 16(1)\n"
- "stfd 1, 8(1)\n"
- // Arguments to Compilation Callback:
- // r3 - our lr (address of the call instruction in stub plus 4)
-@@ -181,21 +201,29 @@
- "bl PPCCompilationCallbackC\n"
- "mtctr 3\n"
- // Restore all int arg registers
-- "lwz 10, 100(1)\n" "lwz 9, 96(1)\n"
-- "lwz 8, 92(1)\n" "lwz 7, 88(1)\n"
-- "lwz 6, 84(1)\n" "lwz 5, 80(1)\n"
-- "lwz 4, 76(1)\n" "lwz 3, 72(1)\n"
-+ "lwz 10, 100(1)\n"
-+ "lwz 9, 96(1)\n"
-+ "lwz 8, 92(1)\n"
-+ "lwz 7, 88(1)\n"
-+ "lwz 6, 84(1)\n"
-+ "lwz 5, 80(1)\n"
-+ "lwz 4, 76(1)\n"
-+ "lwz 3, 72(1)\n"
- // Restore all FP arg registers
- "lfd 8, 64(1)\n"
-- "lfd 7, 56(1)\n" "lfd 6, 48(1)\n"
-- "lfd 5, 40(1)\n" "lfd 4, 32(1)\n"
-- "lfd 3, 24(1)\n" "lfd 2, 16(1)\n"
-+ "lfd 7, 56(1)\n"
-+ "lfd 6, 48(1)\n"
-+ "lfd 5, 40(1)\n"
-+ "lfd 4, 32(1)\n"
-+ "lfd 3, 24(1)\n"
-+ "lfd 2, 16(1)\n"
- "lfd 1, 8(1)\n"
- // Pop 3 frames off the stack and branch to target
- "lwz 1, 104(1)\n"
- "lwz 0, 4(1)\n"
- "mtlr 0\n"
- "bctr\n"
-+ CFI(".cfi_endproc\n")
- );
- #else
- void PPC32CompilationCallback() {
-@@ -325,6 +353,31 @@
- return is64Bit ? PPC64CompilationCallback : PPC32CompilationCallback;
- }
-
-+static const char* GetCommonFrame32() {
-+ /*
-+ // Size of common frame
-+ MCE.emitWordBE(16);
-+ // Common frame
-+ MCE.emitWordBE(0);
-+ MCE.emitByte(1);
-+ MCE.emitByte('z');
-+ MCE.emitByte('R');
-+ MCE.emitByte(0);
-+ MCE.emitByte(1);
-+ MCE.emitByte(-4 & 0x7f);
-+ MCE.emitByte(0x41);
-+ MCE.emitByte(1);
-+ MCE.emitByte(16);
-+ MCE.emitByte(0xc);
-+ MCE.emitByte(1);
-+ MCE.emitByte(0);*/
-+ static const char CF[] = {
-+ 0, 0, 0, 16, 0, 0, 0, 0, 1, 'z', 'R', 0, 1, -4 & 0x7f,
-+ 0x41, 1, 16, 0xc, 1, 0
-+ };
-+ return CF;
-+}
-+
- #if (defined(__POWERPC__) || defined (__ppc__) || defined(_POWER)) && \
- defined(__APPLE__)
- extern "C" void sys_icache_invalidate(const void *Addr, size_t len);
-@@ -358,21 +411,26 @@
- SyncICache((void*)Addr, 7*4);
- return MCE.finishFunctionStub(F);
- }
--
-- MCE.startFunctionStub(F, 10*4);
-+
-+ if (ExceptionHandling && !is64Bit) {
-+ MCE.startFunctionStub(F, 10*4 + 44);
-+ } else {
-+ MCE.startFunctionStub(F, 10*4);
-+ }
-+
- intptr_t Addr = (intptr_t)MCE.getCurrentPCValue();
- if (is64Bit) {
-+ MCE.emitWordBE(0x7d6802a6); // mflr r11
-+ MCE.emitWordBE(0xf9610010); // std r11, 16(r1)
- MCE.emitWordBE(0xf821ffb1); // stdu r1,-80(r1)
-+ } else if (TM.getSubtargetImpl()->isMachoABI()){
- MCE.emitWordBE(0x7d6802a6); // mflr r11
-- MCE.emitWordBE(0xf9610060); // std r11, 96(r1)
-- } else if (TM.getSubtargetImpl()->isMachoABI()){
-+ MCE.emitWordBE(0x91610008); // stw r11, 8(r1)
- MCE.emitWordBE(0x9421ffe0); // stwu r1,-32(r1)
-+ } else {
- MCE.emitWordBE(0x7d6802a6); // mflr r11
-- MCE.emitWordBE(0x91610028); // stw r11, 40(r1)
-- } else {
-+ MCE.emitWordBE(0x91610004); // stw r11, 4(r1)
- MCE.emitWordBE(0x9421ffe0); // stwu r1,-32(r1)
-- MCE.emitWordBE(0x7d6802a6); // mflr r11
-- MCE.emitWordBE(0x91610024); // stw r11, 36(r1)
- }
- intptr_t BranchAddr = (intptr_t)MCE.getCurrentPCValue();
- MCE.emitWordBE(0);
-@@ -384,6 +442,42 @@
- MCE.emitWordBE(0);
- EmitBranchToAt(BranchAddr, (intptr_t)Fn, true, is64Bit);
- SyncICache((void*)Addr, 10*4);
-+ intptr_t EndAddr = (intptr_t)MCE.getCurrentPCValue();
-+
-+ if (ExceptionHandling && !is64Bit) {
-+ // Size of Eh section
-+ MCE.emitWordBE(32);
-+ // Eh section
-+ MCE.emitWordBE(MCE.getCurrentPCValue() - (intptr_t)GetCommonFrame32());
-+ MCE.emitWordBE(Addr - MCE.getCurrentPCValue());
-+ MCE.emitWordBE(EndAddr - Addr);
-+ MCE.emitByte(0);
-+ MCE.emitByte(dwarf::DW_CFA_advance_loc4);
-+ MCE.emitWordBE(8);
-+ MCE.emitByte(dwarf::DW_CFA_def_cfa_offset);
-+ MCE.emitByte(32);
-+ MCE.emitByte(dwarf::DW_CFA_offset_extended_sf);
-+ MCE.emitByte(TM.getRegisterInfo()->getDwarfRegNum(PPC::LR, true));
-+ if (TM.getSubtargetImpl()->isMachoABI()){
-+ MCE.emitByte(-2 & 0x7f);
-+ } else {
-+ MCE.emitByte(-1 & 0x7f);
-+ }
-+ MCE.emitByte(dwarf::DW_CFA_advance_loc4);
-+ MCE.emitWordBE(4);
-+ MCE.emitByte(dwarf::DW_CFA_def_cfa_register);
-+ MCE.emitByte(1);
-+ // Alignment
-+ MCE.emitByte(0);
-+ MCE.emitByte(0);
-+
-+ // Two zero for the unwind runtime
-+ MCE.emitWordBE(0);
-+ MCE.emitWordBE(0);
-+
-+ SyncICache((void*)EndAddr, 44);
-+ ExecutionEngine::RegisterTable((void*)EndAddr);
-+ }
- return MCE.finishFunctionStub(F);
- }
-
-Index: PPCISelLowering.cpp
-===================================================================
---- PPCISelLowering.cpp (revision 50006)
-+++ PPCISelLowering.cpp (working copy)
-@@ -175,10 +175,12 @@
- // We want to legalize GlobalAddress and ConstantPool nodes into the
- // appropriate instructions to materialize the address.
- setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
-+ setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
- setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
- setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
- setOperationAction(ISD::JumpTable, MVT::i32, Custom);
- setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
-+ setOperationAction(ISD::ExternalSymbol , MVT::i64 , Custom);
- setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
- setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
- setOperationAction(ISD::JumpTable, MVT::i64, Custom);
-@@ -745,6 +747,36 @@
- return isIntS16Immediate(Op.Val, Imm);
- }
-
-+ static SDOperand LowerExternalSymbol(SDOperand Op, SelectionDAG &DAG) {
-+ MVT::ValueType PtrVT = Op.getValueType();
-+ ExternalSymbolSDNode *GSDB = dyn_cast<ExternalSymbolSDNode>(Op);
-+ SDOperand GA = DAG.getTargetExternalSymbol(GSDB->getSymbol(), PtrVT);
-+ SDOperand Zero = DAG.getConstant(0, PtrVT);
-+
-+ const TargetMachine &TM = DAG.getTarget();
-+
-+ SDOperand Hi = DAG.getNode(PPCISD::Hi, PtrVT, GA, Zero);
-+ SDOperand Lo = DAG.getNode(PPCISD::Lo, PtrVT, GA, Zero);
-+
-+ // If this is a non-darwin platform, we don't support non-static relo models
-+ // yet.
-+ if (TM.getRelocationModel() == Reloc::Static ||
-+ !TM.getSubtarget<PPCSubtarget>().isDarwin()) {
-+ // Generate non-pic code that has direct accesses to globals.
-+ // The address of the global is just (hi(&g)+lo(&g)).
-+ return DAG.getNode(ISD::ADD, PtrVT, Hi, Lo);
-+ }
-+
-+ if (TM.getRelocationModel() == Reloc::PIC_) {
-+ // With PIC, the first instruction is actually "GR+hi(&G)".
-+ Hi = DAG.getNode(ISD::ADD, PtrVT,
-+ DAG.getNode(PPCISD::GlobalBaseReg, PtrVT), Hi);
-+ }
-+
-+ Lo = DAG.getNode(ISD::ADD, PtrVT, Hi, Lo);
-+
-+ return Lo;
-+ }
-
- /// SelectAddressRegReg - Given the specified addressed, check to see if it
- /// can be represented as an indexed [r+r] operation. Returns false if it
-@@ -2130,11 +2162,11 @@
- // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
- // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
- // node so that legalize doesn't hack it.
-- if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
-- Callee = DAG.getTargetGlobalAddress(G->getGlobal(), Callee.getValueType());
-- else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee))
-- Callee = DAG.getTargetExternalSymbol(S->getSymbol(), Callee.getValueType());
-- else if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG))
-+ //if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
-+ // Callee = DAG.getTargetGlobalAddress(G->getGlobal(), Callee.getValueType());
-+ //if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee))
-+ // Callee = DAG.getTargetExternalSymbol(S->getSymbol(), Callee.getValueType());
-+ if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG))
- // If this is an absolute destination address, use the munged value.
- Callee = SDOperand(Dest, 0);
- else {
-@@ -3506,6 +3538,7 @@
- default: assert(0 && "Wasn't expecting to be able to lower this!");
- case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
- case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
-+ case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
- case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
- case ISD::JumpTable: return LowerJumpTable(Op, DAG);
- case ISD::SETCC: return LowerSETCC(Op, DAG);
diff --git a/vmkit/patches/vmkit-llvm-x86.patch b/vmkit/patches/vmkit-llvm-x86.patch
deleted file mode 100644
index ea513c3..0000000
--- a/vmkit/patches/vmkit-llvm-x86.patch
+++ /dev/null
@@ -1,37 +0,0 @@
-Index: X86Subtarget.cpp
-===================================================================
---- X86Subtarget.cpp (revision 50008)
-+++ X86Subtarget.cpp (working copy)
-@@ -127,7 +127,7 @@
- return;
-
- X86::GetCpuIDAndInfo(0x1, &EAX, &EBX, &ECX, &EDX);
--
-+#if 0
- if ((EDX >> 23) & 0x1) X86SSELevel = MMX;
- if ((EDX >> 25) & 0x1) X86SSELevel = SSE1;
- if ((EDX >> 26) & 0x1) X86SSELevel = SSE2;
-@@ -135,7 +135,9 @@
- if ((ECX >> 9) & 0x1) X86SSELevel = SSSE3;
- if ((ECX >> 19) & 0x1) X86SSELevel = SSE41;
- if ((ECX >> 20) & 0x1) X86SSELevel = SSE42;
--
-+#else
-+ X86SSELevel = MMX;
-+#endif
- if (memcmp(text.c, "GenuineIntel", 12) == 0 ||
- memcmp(text.c, "AuthenticAMD", 12) == 0) {
- X86::GetCpuIDAndInfo(0x80000001, &EAX, &EBX, &ECX, &EDX);
-Index: X86JITInfo.cpp
-===================================================================
---- X86JITInfo.cpp (revision 50008)
-+++ X86JITInfo.cpp (working copy)
-@@ -60,7 +60,7 @@
- // FIXME: Disable this until we really want to use it. Also, we will
- // need to add some workarounds for compilers, which support
- // only subset of these directives.
--# define CFI(x)
-+# define CFI(x) x
- #endif
-
- // Provide a wrapper for X86CompilationCallback2 that saves non-traditional
diff --git a/vmkit/tools/Makefile b/vmkit/tools/Makefile
deleted file mode 100755
index f735557..0000000
--- a/vmkit/tools/Makefile
+++ /dev/null
@@ -1,30 +0,0 @@
-##===- tools/Makefile --------------------------------------*- Makefile -*-===##
-#
-# The vmkit project
-#
-# This file is distributed under the University of Illinois Open Source
-# License. See LICENSE.TXT for details.
-#
-##===----------------------------------------------------------------------===##
-LEVEL = ..
-
-PARALLEL_DIRS += vmkit
-
-include $(LEVEL)/Makefile.config
-
-ifeq ($(WITH_J3), 1)
- PARALLEL_DIRS += j3
- PARALLEL_DIRS += vmjc
- PARALLEL_DIRS += llcj
-endif
-
-ifeq ($(WITH_N3_MONO), 1)
- PARALLEL_DIRS += n3-mono
-endif
-
-ifeq ($(WITH_N3_PNETLIB), 1)
- PARALLEL_DIRS += n3-pnetlib
-endif
-
-include $(LEVEL)/Makefile.common
-
diff --git a/vmkit/tools/j3/Main.cpp b/vmkit/tools/j3/Main.cpp
deleted file mode 100644
index 2e699e1..0000000
--- a/vmkit/tools/j3/Main.cpp
+++ /dev/null
@@ -1,52 +0,0 @@
-//===------------- Main.cpp - Simple execution of J3 ----------------------===//
-//
-// The VMKit project
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#include "mvm/GC.h"
-#include "mvm/JIT.h"
-#include "mvm/VMKit.h"
-#include "mvm/VirtualMachine.h"
-#include "mvm/Threads/Thread.h"
-
-#include "j3/JavaJITCompiler.h"
-#include "../../lib/J3/VMCore/JnjvmClassLoader.h"
-#include "../../lib/J3/VMCore/Jnjvm.h"
-
-#include "llvm/Support/CommandLine.h"
-#include "llvm/Support/ManagedStatic.h"
-
-extern llvm::cl::opt<bool> StandardCompileOpts;
-
-using namespace j3;
-using namespace mvm;
-
-int main(int argc, char **argv, char **envp) {
- llvm::llvm_shutdown_obj X;
-
- // Initialize base components.
- mvm::BumpPtrAllocator Allocator;
- mvm::VMKit* vmkit = new(Allocator, "VMKit") mvm::VMKit(Allocator);
-
- // Tell the compiler to run all optimizations.
- StandardCompileOpts = true;
-
- // Create the allocator that will allocate the bootstrap loader and the JVM.
- JavaJITCompiler* Comp = JavaJITCompiler::CreateCompiler("JITModule");
- Jnjvm* vm = new(Allocator, "VM") Jnjvm(Allocator, vmkit, Comp, true);
-
- // Run the application.
- vm->runApplication(argc, argv);
- vmkit->waitNonDaemonThreads();
- exit(0);
-
- // Destroy everyone.
- // vm->~Jnjvm();
- // loader->~JnjvmBootstrapLoader();
-
- return 0;
-}
diff --git a/vmkit/tools/j3/Makefile b/vmkit/tools/j3/Makefile
deleted file mode 100755
index 8a8687b..0000000
--- a/vmkit/tools/j3/Makefile
+++ /dev/null
@@ -1,40 +0,0 @@
-##===- tools/jnjvm/Makefile --------------------------------*- Makefile -*-===##
-#
-# The vmkit project
-#
-# This file is distributed under the University of Illinois Open Source
-# License. See LICENSE.TXT for details.
-#
-##===----------------------------------------------------------------------===##
-LEVEL = ../..
-
-include $(LEVEL)/Makefile.config
-
-TOOLNAME = j3
-
-ifeq ($(WITH_LLVM_GCC), 1)
-
- MODULESNAME = j3
- USEDMODULES = J3.bc Classpath.bc J3Compiler.bc Allocator.bc CommonThread.bc \
- Mvm.bc MvmCompiler.bc
-
- ifeq ($(GC_MMTK), 1)
- USEDMODULES += FinalMMTk.bc InlineMMTk.bc
- else
- USEDMODULES += $(GCLIB).bc
- endif
-
- BUILT_SOURCES = j3.s
- SOURCES = j3.s $(notdir $(wildcard $(PROJ_SRC_DIR)/*.cpp))
-
-else
-
-USEDLIBS = J3.a Classpath.a J3.a J3Compiler.a Allocator.a \
- Mvm.a MvmCompiler.a $(GCLIB).a Allocator.a CommonThread.a
-
-endif
-
-LINK_COMPONENTS = jit nativecodegen scalaropts instrumentation ipa ipo bitreader asmparser linker
-
-
-include $(LEVEL)/Makefile.common
diff --git a/vmkit/tools/llcj/LinkPaths.h.in b/vmkit/tools/llcj/LinkPaths.h.in
deleted file mode 100644
index 4b67107..0000000
--- a/vmkit/tools/llcj/LinkPaths.h.in
+++ /dev/null
@@ -1,14 +0,0 @@
-//===---- LinkPaths.h - Library paths for generating executables ----------===//
-//
-// VMKit
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-
-#define LLVMLibs "-L@LLVM_OBJ@/Release/lib"
-#define VMKITLibs1 "-L@abs_top_objdir@/Release/lib"
-#define VMKITLibs2 "-L@abs_top_srcdir@/Release/lib"
-#define VMKITLibs3 "-L@PROJ_INSTALL_ROOT@/lib"
diff --git a/vmkit/tools/llcj/Makefile b/vmkit/tools/llcj/Makefile
deleted file mode 100755
index 8b5d9ca..0000000
--- a/vmkit/tools/llcj/Makefile
+++ /dev/null
@@ -1,16 +0,0 @@
-##===- tools/llcj/Makefile ---------------------------------*- Makefile -*-===##
-#
-# The vmkit project
-#
-# This file is distributed under the University of Illinois Open Source
-# License. See LICENSE.TXT for details.
-#
-##===----------------------------------------------------------------------===##
-LEVEL = ../..
-
-include $(LEVEL)/Makefile.config
-
-TOOLNAME = llcj
-LINK_COMPONENTS = support
-
-include $(LEVEL)/Makefile.common
diff --git a/vmkit/tools/llcj/llcj.cpp b/vmkit/tools/llcj/llcj.cpp
deleted file mode 100644
index aa61f67..0000000
--- a/vmkit/tools/llcj/llcj.cpp
+++ /dev/null
@@ -1,258 +0,0 @@
-//===------------- llcj.cpp - Java ahead of time compiler -----------------===//
-//
-// The VMKit project
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#include "llvm/Support/ManagedStatic.h"
-#include "llvm/Support/Path.h"
-#include "llvm/Support/Program.h"
-#include "llvm/Support/Signals.h"
-
-#include "LinkPaths.h"
-
-#include <cstdio>
-#include <cstdlib>
-#include <cstring>
-
-using namespace llvm;
-
-int main(int argc, char **argv) {
- llvm_shutdown_obj X; // Call llvm_shutdown() on exit.
-
- bool SaveTemps = false;
- char* opt = 0;
-
- const char** vmjcArgv = new const char*[argc + 5];
- int vmjcArgc = 1;
- const char** gccArgv = new const char*[argc + 32];
- int gccArgc = 1;
-
- bool runGCC = true;
- char* className = 0;
- bool shared = false;
- bool withJIT = false;
-
- for (int i = 1; i < argc; ++i) {
- if (!strcmp(argv[i], "-shared")) {
- gccArgv[gccArgc++] = argv[i];
- shared = true;
- } else if (!strcmp(argv[i], "-with-jit") ||
- !strcmp(argv[i], "--with-jit")) {
- withJIT = true;
- vmjcArgv[vmjcArgc++] = argv[i];
- } else if (!strcmp(argv[i], "-O1") || !strcmp(argv[i], "-O2") ||
- !strcmp(argv[i], "-O3")) {
- opt = argv[i];
- vmjcArgv[vmjcArgc++] = (const char*)"-std-compile-opts";
- } else if (argv[i][0] == '-' && argv[i][1] == 'S') {
- runGCC = false;
- } else if (argv[i][0] == '-' && argv[i][1] == 'c') {
- gccArgv[gccArgc++] = argv[i];
- } else if (argv[i][0] == '-' && argv[i][1] == 'l') {
- gccArgv[gccArgc++] = argv[i];
- } else if (argv[i][0] == '-' && argv[i][1] == 'L') {
- gccArgv[gccArgc++] = argv[i];
- } else if (argv[i][0] == '-' && argv[i][1] == 'W') {
- gccArgv[gccArgc++] = argv[i];
- } else if (argv[i][0] == '-' && argv[i][1] == 'g') {
- gccArgv[gccArgc++] = argv[i];
- } else if (argv[i][0] == '-' && argv[i][1] == 'p' && argv[i][2] == 'g') {
- gccArgv[gccArgc++] = argv[i];
- } else if (argv[i][0] == '-' && argv[i][1] == 'o') {
- gccArgv[gccArgc++] = argv[i++];
- gccArgv[gccArgc++] = argv[i];
- } else if (argv[i][0] != '-') {
- char* name = argv[i];
- int len = strlen(name);
- if (len > 4 && (!strcmp(&name[len - 4], ".jar") ||
- !strcmp(&name[len - 4], ".zip"))) {
- vmjcArgv[vmjcArgc++] = name;
- char* slash = strrchr(name, '/');
- if (slash) {
- name = slash;
- len = strlen(name);
- }
- className = strdup(name);
- className[len - 4] = 0;
- } else if (len > 6 && !strcmp(&name[len - 6], ".class")) {
- vmjcArgv[vmjcArgc++] = name;
- char* slash = strrchr(name, '/');
- if (slash) {
- name = slash;
- len = strlen(name);
- }
- className = strdup(name);
- className[len - 6] = 0;
- } else {
- gccArgv[gccArgc++] = name;
- }
- } else if (!strcmp(argv[i], "--help")) {
- fprintf(stderr, "Usage: llcj [options] file ...\n"
- "The Java to native compiler. Run vmjc --help for more "
- "information on the real AOT compiler.\n");
- delete gccArgv;
- delete vmjcArgv;
- if (className) free(className);
- return 0;
- } else {
- vmjcArgv[vmjcArgc++] = argv[i];
- }
- }
-
- vmjcArgv[vmjcArgc] = 0;
- gccArgv[gccArgc] = 0;
-
- std::string errMsg;
-
- const sys::Path& tempDir = SaveTemps
- ? sys::Path(sys::Path::GetCurrentDirectory())
- : sys::Path(sys::Path::GetTemporaryDirectory());
-
- sys::Path Out = tempDir;
- int res = 0;
- sys::Path Prog;
-
- if (!className) {
- fprintf(stderr, "No Java file specified.... Abort\n");
- goto cleanup;
- }
-
- Prog = sys::Program::FindProgramByName("vmjc");
-
- if (Prog.isEmpty()) {
- fprintf(stderr, "Can't find vmjc.... Abort\n");
- goto cleanup;
- }
-
- Out.appendComponent(className);
- Out.appendSuffix("bc");
-
- vmjcArgv[0] = Prog.c_str();
- vmjcArgv[vmjcArgc++] = "-f";
- vmjcArgv[vmjcArgc++] = "-o";
- vmjcArgv[vmjcArgc++] = Out.c_str();
-
- res = sys::Program::ExecuteAndWait(Prog, vmjcArgv);
-
- if (!res && opt) {
- sys::Path OptOut = tempDir;
- OptOut.appendComponent("llvmopt");
- OptOut.appendSuffix("bc");
-
- sys::Path Prog = sys::Program::FindProgramByName("opt");
-
- if (Prog.isEmpty()) {
- fprintf(stderr, "Can't find opt.... Abort\n");
- goto cleanup;
- }
-
- const char* optArgv[7];
- optArgv[0] = Prog.c_str();
- optArgv[1] = Out.c_str();
- optArgv[2] = "-f";
- optArgv[3] = "-o";
- optArgv[4] = OptOut.c_str();
- if (opt) {
- optArgv[5] = opt;
- optArgv[6] = 0;
- } else {
- optArgv[5] = 0;
- }
-
- res = sys::Program::ExecuteAndWait(Prog, optArgv);
- Out = OptOut;
- }
-
- if (!res) {
- sys::Path LlcOut;
-
- if (runGCC)
- LlcOut= tempDir;
- else
- LlcOut = sys::Path(sys::Path::GetCurrentDirectory());
-
- LlcOut.appendComponent(className);
- LlcOut.appendSuffix("s");
-
- sys::Path Prog = sys::Program::FindProgramByName("llc");
-
- if (Prog.isEmpty()) {
- fprintf(stderr, "Can't find llc.... Abort\n");
- goto cleanup;
- }
-
- const char* llcArgv[8];
- int i = 0;
- llcArgv[i++] = Prog.c_str();
- llcArgv[i++] = Out.c_str();
- if (shared) llcArgv[i++] = "-relocation-model=pic";
- llcArgv[i++] = "-disable-fp-elim";
- llcArgv[i++] = "-f";
- llcArgv[i++] = "-o";
- llcArgv[i++] = LlcOut.c_str();
- llcArgv[i++] = 0;
-
- res = sys::Program::ExecuteAndWait(Prog, llcArgv);
- Out = LlcOut;
- }
-
- if (!res && runGCC) {
- sys::Path Prog = sys::Program::FindProgramByName("g++");
-
- if (Prog.isEmpty()) {
- fprintf(stderr, "Can't find gcc.... Abort\n");
- goto cleanup;
- }
-
- gccArgv[0] = Prog.c_str();
- gccArgv[gccArgc++] = Out.c_str();
- gccArgv[gccArgc++] = LLVMLibs;
- gccArgv[gccArgc++] = VMKITLibs1;
- gccArgv[gccArgc++] = VMKITLibs2;
- gccArgv[gccArgc++] = VMKITLibs3;
- gccArgv[gccArgc++] = "-pthread";
-#ifdef USE_GC_BOEHM
- gccArgv[gccArgc++] = "-lgc";
-#endif
- gccArgv[gccArgc++] = "-lm";
- gccArgv[gccArgc++] = "-ldl";
- gccArgv[gccArgc++] = "-lz";
- gccArgv[gccArgc++] = "-lJ3";
- gccArgv[gccArgc++] = "-lClasspath";
- gccArgv[gccArgc++] = "-lJ3";
- gccArgv[gccArgc++] = "-lClasspath";
- if (withJIT) {
- gccArgv[gccArgc++] = "-lJ3Compiler";
- }
- gccArgv[gccArgc++] = "-lAllocator";
- gccArgv[gccArgc++] = "-lCommonThread";
- gccArgv[gccArgc++] = "-lMvm";
- gccArgv[gccArgc++] = "-lMvmCompiler";
- gccArgv[gccArgc++] = "-lGCMmap2";
- gccArgv[gccArgc++] = "-lvmjc";
- gccArgv[gccArgc++] = "-lLLVMSupport";
- gccArgv[gccArgc++] = "-lLLVMSystem";
-#if !defined(__MACH__)
- gccArgv[gccArgc++] = "-rdynamic";
-#endif
- gccArgv[gccArgc++] = 0;
-
- res = sys::Program::ExecuteAndWait(Prog, gccArgv);
-
- }
-
-cleanup:
- if (!SaveTemps)
- tempDir.eraseFromDisk(true);
-
- delete gccArgv;
- delete vmjcArgv;
- free(className);
-
- return 0;
-}
-
diff --git a/vmkit/tools/n3-mono/Main.cpp b/vmkit/tools/n3-mono/Main.cpp
deleted file mode 100644
index b2dd4a4..0000000
--- a/vmkit/tools/n3-mono/Main.cpp
+++ /dev/null
@@ -1,32 +0,0 @@
-//===--------- Main.cpp - Simple execution of JnJVM -----------------------===//
-//
-// JnJVM
-//
-// This file is distributed under the University of Pierre et Marie Curie
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#include "mvm/GC.h"
-#include "mvm/JIT.h"
-#include "mvm/Object.h"
-#include "mvm/VirtualMachine.h"
-#include "mvm/Threads/Thread.h"
-
-#include "llvm/Support/ManagedStatic.h"
-
-using namespace mvm;
-
-int main(int argc, char **argv, char **envp) {
- llvm::llvm_shutdown_obj X;
-
- MvmModule::initialise();
- Collector::initialise();
-
- VirtualMachine::initialiseCLIVM();
- VirtualMachine* vm = VirtualMachine::createCLIVM();
- vm->runApplication(argc, argv);
- vm->waitForExit();
-
- return 0;
-}
diff --git a/vmkit/tools/n3-mono/Makefile b/vmkit/tools/n3-mono/Makefile
deleted file mode 100755
index 5ff7f14..0000000
--- a/vmkit/tools/n3-mono/Makefile
+++ /dev/null
@@ -1,35 +0,0 @@
-##===- tools/n3/Mono/Makefile ------------------------------*- Makefile -*-===##
-#
-# The vmkit project
-#
-# This file is distributed under the University of Illinois Open Source
-# License. See LICENSE.TXT for details.
-#
-##===----------------------------------------------------------------------===##
-LEVEL = ../..
-
-include $(LEVEL)/Makefile.config
-
-TOOLNAME = n3-mono
-LINK_COMPONENTS = jit nativecodegen scalaropts instrumentation ipa ipo bitreader asmparser linker
-
-
-ifeq ($(WITH_LLVM_GCC), 1)
- MODULESNAME = vmkit
- USEDMODULES = Mono.bc Allocator.bc CommonThread.bc Mvm.bc \
- MvmCompiler.bc N3.bc $(GCLIB).bc
- BUILT_SOURCES = vmkit.s
- SOURCES = vmkit.s $(notdir $(wildcard $(PROJ_SRC_DIR)/*.cpp))
-else
-
- USEDLIBS = N3.a Mono.a Allocator.a Mvm.a MvmCompiler.a \
- $(GCLIB).a CommonThread.a
-endif
-
-include $(LEVEL)/Makefile.common
-
-CXX.Flags += `pkg-config --cflags glib-2.0 gthread-2.0`
-LIBS += `pkg-config --libs glib-2.0 gthread-2.0`
-CXX.Flags += `pkg-config --cflags gmodule-2.0`
-LIBS += `pkg-config --libs gmodule-2.0`
-
diff --git a/vmkit/tools/n3-pnetlib/Main.cpp b/vmkit/tools/n3-pnetlib/Main.cpp
deleted file mode 100644
index b2dd4a4..0000000
--- a/vmkit/tools/n3-pnetlib/Main.cpp
+++ /dev/null
@@ -1,32 +0,0 @@
-//===--------- Main.cpp - Simple execution of JnJVM -----------------------===//
-//
-// JnJVM
-//
-// This file is distributed under the University of Pierre et Marie Curie
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#include "mvm/GC.h"
-#include "mvm/JIT.h"
-#include "mvm/Object.h"
-#include "mvm/VirtualMachine.h"
-#include "mvm/Threads/Thread.h"
-
-#include "llvm/Support/ManagedStatic.h"
-
-using namespace mvm;
-
-int main(int argc, char **argv, char **envp) {
- llvm::llvm_shutdown_obj X;
-
- MvmModule::initialise();
- Collector::initialise();
-
- VirtualMachine::initialiseCLIVM();
- VirtualMachine* vm = VirtualMachine::createCLIVM();
- vm->runApplication(argc, argv);
- vm->waitForExit();
-
- return 0;
-}
diff --git a/vmkit/tools/n3-pnetlib/Makefile b/vmkit/tools/n3-pnetlib/Makefile
deleted file mode 100755
index 69e4457..0000000
--- a/vmkit/tools/n3-pnetlib/Makefile
+++ /dev/null
@@ -1,32 +0,0 @@
-##===- tools/n3/Makefile -----------------------------------*- Makefile -*-===##
-#
-# The vmkit project
-#
-# This file is distributed under the University of Illinois Open Source
-# License. See LICENSE.TXT for details.
-#
-##===----------------------------------------------------------------------===##
-LEVEL = ../..
-
-include $(LEVEL)/Makefile.config
-
-TOOLNAME = n3-pnetlib
-LINK_COMPONENTS = jit nativecodegen scalaropts instrumentation ipa ipo bitreader asmparser linker
-
-ifeq ($(WITH_LLVM_GCC), 1)
- MODULESNAME = vmkit
- USEDMODULES = N3.bc PNetLib.bc Allocator.bc CommonThread.bc Mvm.bc \
- MvmCompiler.bc $(GCLIB).bc
- BUILT_SOURCES = vmkit.s
- SOURCES = vmkit.s $(notdir $(wildcard $(PROJ_SRC_DIR)/*.cpp))
-else
- USEDLIBS = N3.a PNetLib.a Allocator.a Mvm.a MvmCompiler.a \
- $(GCLIB).a CommonThread.a
-endif
-
-include $(LEVEL)/Makefile.common
-
-
-LIBS += $(PNETLIB)/engine/libILEngine.a $(PNETLIB)/image/libILImage.a $(PNETLIB)/support/libILSupport.a \
- $(PNETLIB)/libffi/.libs/libffi.a $(PNETLIB)//dumpasm/libILDumpAsm.a
-
diff --git a/vmkit/tools/testAllocator/Main.cpp b/vmkit/tools/testAllocator/Main.cpp
deleted file mode 100644
index f396480..0000000
--- a/vmkit/tools/testAllocator/Main.cpp
+++ /dev/null
@@ -1,147 +0,0 @@
-//===------------------ main.cc - Mvm allocator ---------------------------===//
-//
-// Mvm
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#include "gcalloc.h"
-#include <stdio.h>
-#include <time.h>
-#include <stdlib.h>
-#include <math.h>
-#include <sys/time.h>
-
-#include <sys/resource.h>
-void set_stack_size(uint Mbs)
-{
- const rlim_t kStackSize = Mbs * 1024 * 1024;
- struct rlimit rl;
- int result;
-
- result = getrlimit(RLIMIT_STACK, &rl);
- if (result == 0)
- {
- if (rl.rlim_cur < kStackSize)
- {
- rl.rlim_cur = kStackSize;
- result = setrlimit(RLIMIT_STACK, &rl);
- if (result != 0)
- fprintf(stderr, "setrlimit returned result = %d\n", result);
- else
- fprintf(stderr, "setrlimit OK\n");
- }
- }
-}
-
-unsigned int rand(unsigned int min, unsigned int max) {
- return (unsigned int)nearbyint((((double)(max - min))*::rand())/(RAND_MAX + 1.0)) + min;
-}
-
-void tire(size_t n, size_t *vals, size_t *reallocs, size_t *frees) {
- for(size_t i=0; i<n; i++) {
- if(rand(0, 20))
- vals[i] = rand(1, 256);
- else
- vals[i] = rand(256, 65536);
- if(!rand(0, 10)) /* un chance sur 10 de réallouer */
- if(rand(0, 20))
- reallocs[i] = rand(1, 256);
- else
- reallocs[i] = rand(256, 65536);
- else
- reallocs[i] = 0;
- if(rand(0, 10)) /* un chance sur 10 de ne pas libérer */
- frees[i] = 1;
- else
- frees[i] = 0;
- }
-}
-
-void printMesure(size_t n, size_t *vals, size_t *reallocs, size_t *frees, struct timeval *start, struct timeval *end) {
- size_t totAllocated = 0;
- size_t curAllocated = 0;
- size_t na = 0;
- size_t nr = 0;
- size_t nf = 0;
- size_t no = 0;
-
- for(size_t i=0; i<n; i++) {
- size_t here = vals[i] + reallocs[i];
- if(reallocs[i]) {
- na++;
- nr++;
- }
- na++;
- totAllocated += here;
- if(!frees[i]) {
- curAllocated += here;
- no++;
- } else
- nf++;
- }
-
- printf("; %lu allocations (%lu reallocations, %lu free, %lu chunks)\n", na, nr, nf, no);
- printf("; Allocated: %lu bytes, current %lu bytes\n", totAllocated, curAllocated);
-
- struct timeval diff;
- timersub(end, start, &diff);
- double f = (double)diff.tv_sec + ((double)diff.tv_usec / 1000000.0);
- printf("; time consumed: %fs\n", f);
-}
-
-void mesureAllocateur() {
- size_t n = 512*1024; //512K 4bytes==2Mb, times3=6Mb; for x86_64:12Mb
- size_t* vals = (size_t*)alloca(sizeof(size_t) * n);
- size_t* reallocs = (size_t*)alloca(sizeof(size_t) * n);
- size_t* frees = (size_t*)alloca(sizeof(size_t) * n);
-
- printf("Tire une sequence d'allocations alléatoire\n");
- tire(n, vals, reallocs, frees);
-
- printf("test\n");
- struct timeval start;
- struct timeval end;
- GCAllocator *a = new GCAllocator();
-
- gettimeofday(&start, 0);
- for(size_t i=0; i<n; i++) {
- void *p = a->alloc(vals[i]);
- if(reallocs[i])
- p = a->realloc(p, reallocs[i]);
- if(frees[i])
- a->free(p);
- }
- gettimeofday(&end, 0);
- delete a;
-
- printMesure(n, vals, reallocs, frees, &start, &end);
- printf("Press a key...\n");
- getchar();
-
- gettimeofday(&start, 0);
- for(size_t i=0; i<n; i++) {
- void *p = malloc(vals[i]);
- ((char *)p)[0] = 1;
- if(reallocs[i])
- p = realloc(p, reallocs[i]);
- if(frees[i])
- free(p);
- }
- gettimeofday(&end, 0);
- printMesure(n, vals, reallocs, frees, &start, &end);
- printf("Press a key...\n");
- getchar();
-
-}
-
-int main(int argc, char **argv) {
- if( sizeof(size_t) > 4) //bogus check for 64bits
- set_stack_size(16); //update min stack size to 16 MB for mesureAllocateur()
- mesureAllocateur();
-
- GCHash::destroy();
- return 0;
-}
diff --git a/vmkit/tools/testAllocator/Makefile b/vmkit/tools/testAllocator/Makefile
deleted file mode 100644
index 29eb7be..0000000
--- a/vmkit/tools/testAllocator/Makefile
+++ /dev/null
@@ -1,16 +0,0 @@
-##===- tools/testAllocator/Makefile ------------------------*- Makefile -*-===##
-#
-# The vmkit project
-#
-# This file is distributed under the University of Illinois Open Source
-# License. See LICENSE.TXT for details.
-#
-##===----------------------------------------------------------------------===##
-LEVEL = ../..
-
-TOOLNAME = testAllocator
-USEDLIBS = Allocator.a
-
-include $(LEVEL)/Makefile.common
-
-CXX.Flags += -I$(LEVEL)/lib/Mvm/Allocator
diff --git a/vmkit/tools/testCollector/Main.cpp b/vmkit/tools/testCollector/Main.cpp
deleted file mode 100644
index 058878a..0000000
--- a/vmkit/tools/testCollector/Main.cpp
+++ /dev/null
@@ -1,35 +0,0 @@
-//===---------------- main.cc - Mvm Garbage Collector ---------------------===//
-//
-// Mvm
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#include "mvm/GC.h"
-#include "mvm/Threads/Thread.h"
-#include <stdio.h>
-
-void destr(gc *me, size_t sz) {
- printf("Destroy %p\n", (void*)me);
-}
-
-void trace(gc *me, size_t sz) {
- // printf("Trace %p\n", (void*)me);
-}
-
-void marker(void*) {
- // printf("Marker...\n");
-}
-
-int main(int argc, char **argv) {
- mvm::Collector::initialise();
-#ifdef MULTIPLE_GC
- mvm::Thread::get()->GC->destroy();
-#else
- mvm::Collector::destroy();
-#endif
- return 0;
-}
-
diff --git a/vmkit/tools/testCollector/Makefile b/vmkit/tools/testCollector/Makefile
deleted file mode 100755
index 36394f6..0000000
--- a/vmkit/tools/testCollector/Makefile
+++ /dev/null
@@ -1,18 +0,0 @@
-##===- tools/testCollector/Makefile ------------------------*- Makefile -*-===##
-#
-# The vmkit project
-#
-# This file is distributed under the University of Illinois Open Source
-# License. See LICENSE.TXT for details.
-#
-##===----------------------------------------------------------------------===##
-LEVEL = ../..
-
-TOOLNAME = testCollector
-USEDLIBS=GCMmap2.a CommonThread.a Allocator.a GCMmap2.a Mvm.a GCMmap2.a
-
-LINK_COMPONENTS = support
-
-include $(LEVEL)/Makefile.common
-
-CXX.Flags += -I$(LEVEL)/lib/Mvm/Allocator -I$(LEVEL)/lib/Mvm/GCMmap2
diff --git a/vmkit/tools/vmjc/Makefile b/vmkit/tools/vmjc/Makefile
deleted file mode 100755
index be35651..0000000
--- a/vmkit/tools/vmjc/Makefile
+++ /dev/null
@@ -1,34 +0,0 @@
-##===- tools/vmjc/Makefile --------------------------------*- Makefile -*-===##
-#
-# The VMKit project
-#
-# This file is distributed under the University of Illinois Open Source
-# License. See LICENSE.TXT for details.
-#
-##===----------------------------------------------------------------------===##
-LEVEL = ../..
-
-include $(LEVEL)/Makefile.config
-
-EXTRA_DIST = libvmjc
-
-TOOLNAME = vmjc
-
-
-ifeq ($(WITH_LLVM_GCC), 1)
- MODULESNAME = vmkit
- USEDMODULES = J3.bc Classpath.bc J3Compiler.bc Allocator.bc \
- CommonThread.bc Mvm.bc MvmCompiler.bc $(GCLIB).bc
-
- BUILT_SOURCES = vmkit.s
- SOURCES = vmkit.s $(notdir $(wildcard $(PROJ_SRC_DIR)/*.cpp))
-
-else
-
- USEDLIBS = J3.a Classpath.a J3.a J3Compiler.a Allocator.a \
- Mvm.a MvmCompiler.a $(GCLIB).a Allocator.a CommonThread.a
-endif
-
-LINK_COMPONENTS = jit nativecodegen scalaropts instrumentation ipa ipo bitwriter bitreader asmparser linker
-
-include $(LEVEL)/Makefile.common
diff --git a/vmkit/tools/vmjc/libvmjc/Makefile b/vmkit/tools/vmjc/libvmjc/Makefile
deleted file mode 100755
index 9e516b9..0000000
--- a/vmkit/tools/vmjc/libvmjc/Makefile
+++ /dev/null
@@ -1,20 +0,0 @@
-##===- tools/vmjc/libvmjc/Makefile -------------------------*- Makefile -*-===##
-#
-# The VMKit project
-#
-# This file is distributed under the University of Illinois Open Source
-# License. See LICENSE.TXT for details.
-#
-##===----------------------------------------------------------------------===##
-LEVEL = ../../..
-
-include $(LEVEL)/Makefile.config
-
-LIBRARYNAME = libvmjc
-LOADABLE_MODULE = 1
-VMJC_ASSEMBLY = 1
-BUILT_SOURCES = glibj.zip.s
-
-SOURCES = glibj.zip.s
-
-include $(LEVEL)/Makefile.common
diff --git a/vmkit/tools/vmjc/vmjc.cpp b/vmkit/tools/vmjc/vmjc.cpp
deleted file mode 100644
index 884fc02..0000000
--- a/vmkit/tools/vmjc/vmjc.cpp
+++ /dev/null
@@ -1,249 +0,0 @@
-//===----------------- vmjc.cpp - Java static compiler --------------------===//
-//
-// The VMKit project
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-//
-// This utility may be invoked in the following manner:
-// vmjc [options] x - Read Java bytecode from the x.class file, write llvm
-// bytecode to the x.bc file.
-// Options:
-// --help - Output information about command line switches
-//
-//===----------------------------------------------------------------------===//
-
-#include "llvm/LinkAllPasses.h"
-#include "llvm/LinkAllVMCore.h"
-#include "llvm/Module.h"
-#include "llvm/PassManager.h"
-#include "llvm/Assembly/PrintModulePass.h"
-#include "llvm/CodeGen/LinkAllCodegenComponents.h"
-#include "llvm/Bitcode/ReaderWriter.h"
-#include "llvm/ExecutionEngine/ExecutionEngine.h"
-#include "llvm/Support/CommandLine.h"
-#include "llvm/Support/ManagedStatic.h"
-#include "llvm/Support/MemoryBuffer.h"
-#include "llvm/Support/PassNameParser.h"
-#include "llvm/Support/PluginLoader.h"
-#include "llvm/Support/RegistryParser.h"
-#include "llvm/Support/SystemUtils.h"
-#include "llvm/Support/raw_ostream.h"
-#include "llvm/Support/Signals.h"
-#include "llvm/Target/TargetData.h"
-#include "llvm/Target/TargetMachine.h"
-
-
-#include "mvm/GC.h"
-#include "mvm/JIT.h"
-#include "mvm/VMKit.h"
-#include "mvm/VirtualMachine.h"
-#include "mvm/Threads/Thread.h"
-
-#include "j3/JavaAOTCompiler.h"
-
-#include "../../lib/J3/VMCore/JnjvmClassLoader.h"
-#include "../../lib/J3/VMCore/Jnjvm.h"
-
-#include <iostream>
-#include <fstream>
-#include <memory>
-#include <string>
-
-using namespace j3;
-using namespace llvm;
-
-static cl::opt<std::string>
-InputFilename(cl::Positional, cl::desc("<input Java bytecode>"), cl::init("-"));
-
-static cl::opt<std::string>
-OutputFilename("o", cl::desc("Override output filename"),
- cl::value_desc("filename"));
-
-static cl::opt<bool>
-Force("f", cl::desc("Overwrite output files"));
-
-static cl::opt<std::string>
-MainClass("main", cl::desc("Specify main class"));
-
-static cl::opt<bool>
-WithJIT("with-jit", cl::desc("Generate main function with JIT support"));
-
-static cl::opt<bool>
-DisableOutput("disable-output", cl::desc("Disable output"), cl::init(false));
-
-static cl::opt<std::string>
-TargetTriple("mtriple", cl::desc("Override target triple for module"));
-
-static cl::opt<bool>
-DisableExceptions("disable-exceptions",
- cl::desc("Disable Java exceptions"));
-
-static cl::opt<bool>
-DisableCooperativeGC("disable-cooperativegc",
- cl::desc("Disable cooperative garbage collection"));
-
-
-static cl::opt<bool>
-DisableStubs("disable-stubs",
- cl::desc("Disable Java stubs"));
-
-static cl::opt<bool>
-AssumeCompiled("assume-compiled",
- cl::desc("Assume external Java classes are compiled"));
-
-static cl::opt<bool>
-PrintStats("print-aot-stats",
- cl::desc("Print stats by the AOT compiler"));
-
-
-static cl::list<std::string>
-Properties("D", cl::desc("Set a property"), cl::Prefix, cl::ZeroOrMore);
-
-static cl::list<std::string>
-WithClinit("with-clinit", cl::desc("Classes to clinit"), cl::ZeroOrMore,
- cl::CommaSeparated);
-
-int main(int argc, char **argv) {
- llvm_shutdown_obj X; // Call llvm_shutdown() on exit.
- cl::ParseCommandLineOptions(argc, argv, "vmkit .class -> .ll compiler\n");
- sys::PrintStackTraceOnErrorSignal();
-
- std::string ErrorMessage;
-
-
- if (InputFilename == "-") {
- cl::PrintHelpMessage();
- return 0;
- }
-
- // Disable cross-compiling for now.
- if (false) {
- Module* TheModule = new Module("bootstrap module",
- *(new llvm::LLVMContext()));
- if (!TargetTriple.empty())
- TheModule->setTargetTriple(TargetTriple);
- else
- TheModule->setTargetTriple(mvm::MvmModule::getHostTriple());
-
-#if 0
- // explicitly specified an architecture to compile for.
- const Target *TheTarget = 0;
- if (!MArch.empty()) {
- for (TargetRegistry::iterator it = TargetRegistry::begin(),
- ie = TargetRegistry::end(); it != ie; ++it) {
- if (MArch == it->getName()) {
- TheTarget = &*it;
- break;
- }
- }
-
- if (!TheTarget) {
- errs() << argv[0] << ": error: invalid target '" << MArch << "'.\n";
- return 1;
- }
- } else {
- std::string Err;
- TheTarget =
- TargetRegistry::getClosestStaticTargetForModule(*TheModule, Err);
- if (TheTarget == 0) {
- errs() << argv[0] << ": error auto-selecting target for module '"
- << Err << "'. Please use the -march option to explicitly "
- << "pick a target.\n";
- return 1;
- }
- }
-
- std::string FeaturesStr;
- std::auto_ptr<TargetMachine>
- target(TheTarget->createTargetMachine(*TheModule, FeaturesStr));
- assert(target.get() && "Could not allocate target machine!");
- TargetMachine &Target = *target.get();
-
- // Install information about target datalayout stuff into the module for
- // optimizer use.
- TheModule->setDataLayout(Target.getTargetData()->
- getStringRepresentation());
-
-
- mvm::VMKit::initialise(CodeGenOpt::Default, TheModule, &Target);
-#endif
- }
-
- mvm::BumpPtrAllocator allocator;
- mvm::VMKit* vmkit = new(allocator, "VMKit") mvm::VMKit(allocator);
-
- JavaAOTCompiler* Comp = new JavaAOTCompiler("AOT");
-
- if (DisableExceptions) Comp->disableExceptions();
- if (DisableStubs) Comp->generateStubs = false;
- if (AssumeCompiled) Comp->assumeCompiled = true;
- if (DisableCooperativeGC) Comp->disableCooperativeGC();
-
- Jnjvm* vm = new(allocator, "Bootstrap loader") Jnjvm(allocator, vmkit, Comp, false);
-
- for (std::vector<std::string>::iterator i = Properties.begin(),
- e = Properties.end(); i != e; ++i) {
-
- char* key = new char [(*i).size()+1];
- strcpy(key, (*i).c_str());
- char* value = strchr(key, '=');
- if (!value) {
- delete[] key;
- } else {
- value[0] = 0;
- vm->addProperty(key, &value[1]);
- }
- }
-
- Comp->clinits = &WithClinit;
- Comp->compileFile(vm, InputFilename.c_str());
-
- if (!MainClass.empty()) {
- Comp->generateMain(MainClass.c_str(), WithJIT);
- }
-
- if (PrintStats)
- Comp->printStats();
-
- // Infer the output filename if needed.
- if (OutputFilename.empty()) {
- if (InputFilename == "-") {
- OutputFilename = "-";
- } else {
- std::string IFN = InputFilename;
- int Len = IFN.length();
- if (IFN[Len-3] == '.' && IFN[Len-2] == 'l' && IFN[Len-1] == 'l') {
- // Source ends in .ll
- OutputFilename = std::string(IFN.begin(), IFN.end()-3);
- } else {
- OutputFilename = IFN; // Append a .bc to it
- }
- OutputFilename += ".bc";
- }
- }
-
- std::string ErrorInfo;
- std::auto_ptr<raw_ostream> Out
- (new raw_fd_ostream(OutputFilename.c_str(), ErrorInfo,
- raw_fd_ostream::F_Binary));
- if (!ErrorInfo.empty()) {
- errs() << ErrorInfo << '\n';
- return 1;
- }
-
-
- // Make sure that the Out file gets unlinked from the disk if we get a
- // SIGINT.
- if (OutputFilename != "-")
- sys::RemoveFileOnSignal(sys::Path(OutputFilename));
-
- if (!DisableOutput)
- if (Force || !CheckBitcodeOutputToConsole(*Out, true))
- WriteBitcodeToFile(Comp->getLLVMModule(), *Out);
-
- return 0;
-}
-
diff --git a/vmkit/tools/vmkit/CommandLine.cpp b/vmkit/tools/vmkit/CommandLine.cpp
deleted file mode 100644
index e3fc4d1..0000000
--- a/vmkit/tools/vmkit/CommandLine.cpp
+++ /dev/null
@@ -1,176 +0,0 @@
-//===------- CommandLine.cpp - Parses the command line --------------------===//
-//
-// The VMKit project
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-#if 0
-
-#include <assert.h>
-#include <dlfcn.h>
-#include <stdio.h>
-#include <stdlib.h>
-
-#include "CommandLine.h"
-#include "mvm/GC.h"
-#include "mvm/Threads/Thread.h"
-
-using namespace mvm;
-
-typedef struct thread_arg_t {
- int argc;
- char** argv;
- create_vm_t func;
-} thread_arg_t;
-
-
-
-CommandLine::CommandLine() {
- resetString();
- resetArgv();
-}
-
-void CommandLine::appendChar(char c) {
- assert(_yytext);
- _yytext[_yylen++]= c;
- if (_yylen == _yylenMax) {
- _yylenMax *= 2;
- _yytext= (char *)realloc(_yytext, _yylenMax);
- }
-}
-
-void CommandLine::appendString(char* str) {
- assert(argv);
- appendChar(0);
- argv[argc++] = str;
- if (argc == argcMax) {
- argcMax *= 2;
- argv = (char **)realloc(argv, argcMax * sizeof(char*));
- }
-}
-
-void CommandLine::resetString() {
- _yytext = (char *)malloc(_yylenMax= 32);
- _yylen = 0;
-}
-
-void CommandLine::resetArgv() {
- argv = (char **)malloc(sizeof(char*) * (argcMax= 10));
- argc = 0;
-}
-
-
-void CommandLine::start() {
- printf("> ");
- _yyChar = getc(stdin);
-
- while (true) {
- switch(_yyChar) {
- case ' ' :
- do { _yyChar = getc(stdin); } while (_yyChar == ' ');
- if (_yylen != 0) {
- appendString(_yytext);
- resetString();
- }
- break;
-
- case '\n' :
- if (_yylen != 0) {
- appendString(_yytext);
- resetString();
- }
- if (argc > 1) {
- executeInstr();
- resetArgv();
- printf("> ");
- }
- _yyChar = getc(stdin);
- break;
-
- case EOF :
- printf("\n");
- return;
-
- default :
- appendChar(_yyChar);
- _yyChar = getc(stdin);
- }
- }
-}
-
-#if 0
-extern "C" int startApp(thread_arg_t* arg) {
- int argc = arg->argc;
- char** argv = arg->argv;
- create_vm_t func = arg->func;
- free(arg);
-#ifndef MULTIPLE_GC
- Collector::inject_my_thread(&argc);
- VirtualMachine* VM = func();
- VM->runApplication(argc, argv);
- Collector::remove_my_thread();
- Collector::collect();
-#else
- Collector* GC = Collector::allocate();
- GC->inject_my_thread(&argc);
- func(argc, argv);
- GC->remove_my_thread();
- GC->collect();
-#endif
- return 0;
-}
-#endif
-
-void CommandLine::executeInstr() {
- if (!strcmp(argv[0], "load")) {
-#if defined(__APPLE__)
- char* buf = (char*)alloca(sizeof(argv[1]) + 7);
- sprintf(buf, "%s.dylib", argv[1]);
-#else
- char* buf = (char*)alloca(sizeof(argv[1]) + 4);
- sprintf(buf, "%s.so", argv[1]);
-#endif
- void* handle = dlopen(buf, RTLD_LAZY | RTLD_GLOBAL);
- if (handle == 0) {
- fprintf(stderr, "\t Unable to load %s\n", argv[1]);
- printf("\t error = %s\n", dlerror());
- return;
- }
-
- boot_t func = (boot_t)(intptr_t)dlsym(handle, "initialiseVirtualMachine");
-
- if (func == 0) {
- fprintf(stderr, "\t Unable to find %s boot method\n", argv[1]);
- dlclose(handle);
- return;
- }
- func();
-
- create_vm_t vmlet = (create_vm_t)(intptr_t)dlsym(handle, "createVirtualMachine");
-
- vmlets[argv[1]] = vmlet;
-
- } else {
- create_vm_t func = vmlets[argv[0]];
- mvm::Object* CU = compilers[argv[0]];
- if (!func) {
- fprintf(stderr, "\t Unknown vm %s\n", argv[0]);
- } else {
-#if 0
- thread_arg_t* thread_arg = (thread_arg_t*)malloc(sizeof (thread_arg_t));
- thread_arg->argc = argc;
- thread_arg->argv = argv;
- thread_arg->func = func;
- int tid = 0;
- Thread::start(&tid, (int (*)(void *))startApp, thread_arg);
-#else
- VirtualMachine* VM = func(CU);
- VM->runApplication(argc, argv);
-#endif
- }
- }
-}
-
-#endif
diff --git a/vmkit/tools/vmkit/CommandLine.h b/vmkit/tools/vmkit/CommandLine.h
deleted file mode 100644
index 4ec56a8..0000000
--- a/vmkit/tools/vmkit/CommandLine.h
+++ /dev/null
@@ -1,75 +0,0 @@
-//===--------- CommandLine.h - Parses the command line --------------------===//
-//
-// The VMKit project
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#ifndef COMMAND_LINE_H
-#define COMMAND_LINE_H
-
-#include <map>
-
-#include <string.h>
-
-#include "mvm/Object.h"
-#include "mvm/VirtualMachine.h"
-
-#if defined(__APPLE__)
-#define JNJVM_LIB "Jnjvm.dylib"
-#define CLASSPATH_LIB "Classpath.dylib"
-#define N3_LIB "N3.dylib"
-#define PNET_LIB "Pnetlib.dylib"
-#else
-#define JNJVM_LIB "Jnjvm.so"
-#define CLASSPATH_LIB "Classpath.so"
-#define N3_LIB "N3.so"
-#define PNET_LIB "Pnetlib.so"
-#endif
-
-typedef int (*boot_t)();
-typedef mvm::VirtualMachine* (*create_vm_t)(mvm::Object*);
-
-namespace mvm {
-
-
-struct ltstr
-{
- bool operator()(const char* s1, const char* s2) const
- {
- return strcmp(s1, s2) < 0;
- }
-};
-
-class CommandLine {
-public:
- char** argv;
- unsigned argc;
- unsigned argcMax;
-
- char* _yytext;
- unsigned _yylen;
- unsigned _yylenMax;
- char _yyChar;
-
- std::map<const char*, create_vm_t, ltstr> vmlets;
- std::map<const char*, mvm::Object*, ltstr> compilers;
-
- CommandLine();
-
- void appendChar(char c);
- void appendString(char* str);
-
- void start();
- void executeInstr();
-
- void resetArgv();
- void resetString();
-
-};
-
-} // end namespace mvm
-
-#endif // COMMAND_LINE_H
diff --git a/vmkit/tools/vmkit/Launcher.cpp b/vmkit/tools/vmkit/Launcher.cpp
deleted file mode 100644
index 52f6d32..0000000
--- a/vmkit/tools/vmkit/Launcher.cpp
+++ /dev/null
@@ -1,83 +0,0 @@
-//===--------- Launcher.cpp - Launch command line -------------------------===//
-//
-// The VMKit project
-//
-// This file is distributed under the University of Pierre et Marie Curie
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#include "llvm/LinkAllPasses.h"
-#include "llvm/LinkAllVMCore.h"
-#include "llvm/PassManager.h"
-#include "llvm/CodeGen/LinkAllCodegenComponents.h"
-//#include "llvm/Support/CommandLine.h"
-#include "llvm/Support/ManagedStatic.h"
-#include "llvm/Support/PassNameParser.h"
-#include "llvm/Support/PluginLoader.h"
-#include "llvm/Target/TargetData.h"
-
-
-#include "mvm/GC.h"
-#include "mvm/Config/config.h"
-#include "mvm/JIT.h"
-#include "mvm/VMKit.h"
-#include "mvm/VirtualMachine.h"
-#include "mvm/Threads/Thread.h"
-
-#include "j3/JavaJITCompiler.h"
-#include "../../lib/J3/VMCore/JnjvmClassLoader.h"
-#include "../../lib/J3/VMCore/Jnjvm.h"
-
-//#include "CommandLine.h"
-
-using namespace j3;
-using namespace llvm;
-
-enum VMType {
- RunJava
-};
-
-static llvm::cl::opt<VMType> VMToRun(llvm::cl::desc("Choose VM to run:"),
- llvm::cl::values(
- clEnumValN(RunJava , "java", "Run the JVM"),
- clEnumValEnd));
-
-static llvm::cl::opt<bool> Fast("fast",
- cl::desc("Generate code quickly, "
- "potentially sacrificing code quality"),
- cl::init(false));
-
-int found(char** argv, int argc, const char* name) {
- int i = 1;
- for (; i < argc; i++) {
- if (!(strcmp(name, argv[i]))) return i + 1;
- }
- return 0;
-}
-
-int main(int argc, char** argv) {
- llvm::llvm_shutdown_obj X;
- int pos = found(argv, argc, "-java");
- if (pos) {
- llvm::cl::ParseCommandLineOptions(pos, argv);
- } else {
- fprintf(stderr, "Only -java is supported\n");
- return 0;
- }
-
- mvm::BumpPtrAllocator Allocator;
-
- mvm::VMKit::initialise(Fast ? CodeGenOpt::None : CodeGenOpt::Aggressive);
- mvm::VMKit* vmkit = new(Allocator, "VMKit") mvm::VMKit(Allocator);
-
- if (VMToRun == RunJava) {
- JavaJITCompiler* Comp = JavaJITCompiler::CreateCompiler("JITModule");
- Jnjvm* vm = new(Allocator, "VM") Jnjvm(Allocator, vmkit, Comp, true);
- vm->runApplication(argc, argv);
- }
-
- vmkit->waitNonDaemonThreads();
-
- return 0;
-}
diff --git a/vmkit/tools/vmkit/Makefile b/vmkit/tools/vmkit/Makefile
deleted file mode 100755
index d693db0..0000000
--- a/vmkit/tools/vmkit/Makefile
+++ /dev/null
@@ -1,65 +0,0 @@
-##===- tools/vmkit/Makefile --------------------------------*- Makefile -*-===##
-#
-# The VMKit project
-#
-# This file is distributed under the University of Illinois Open Source
-# License. See LICENSE.TXT for details.
-#
-##===----------------------------------------------------------------------===##
-LEVEL = ../..
-
-include $(LEVEL)/Makefile.config
-
-TOOLNAME = vmkit
-
-
-ifeq ($(WITH_LLVM_GCC), 1)
-
- MODULESNAME = vmkit
-
- ifeq ($(WITH_J3), 1)
- USEDMODULES += J3.bc Classpath.bc J3Compiler.bc
- endif
-
- ifeq ($(WITH_N3_PNETLIB), 1)
- USEDMODULES += N3.bc PNetLib.bc
- endif
-
- USEDMODULES += Allocator.bc CommonThread.bc Mvm.bc MvmCompiler.bc
-
- ifeq ($(GC_MMTK), 1)
- USEDMODULES += FinalMMTk.bc InlineMMTk.bc
- else
- USEDMODULES += $(GCLIB).bc
- endif
-
- BUILT_SOURCES = vmkit.s
- SOURCES = vmkit.s $(notdir $(wildcard $(PROJ_SRC_DIR)/*.cpp))
-
-
-else
-
- USEDLIBS += Allocator.a Mvm.a MvmCompiler.a $(GCLIB).a CommonThread.a
-
- ifeq ($(WITH_J3), 1)
- USEDLIBS += J3.a Classpath.a J3.a J3Compiler.a
- endif
-
- ifeq ($(WITH_N3_PNETLIB), 1)
- USEDLIBS += N3.a PNetLib.a
- endif
-
- USEDLIBS += Allocator.a Mvm.a MvmCompiler.a $(GCLIB).a CommonThread.a
-
-endif
-
-LINK_COMPONENTS = jit nativecodegen scalaropts instrumentation ipa ipo bitreader asmparser linker
-
-include $(LEVEL)/Makefile.common
-
-ifeq ($(WITH_N3_PNETLIB), 1)
-LIBS += $(PNETLIB)/engine/libILEngine.a $(PNETLIB)/image/libILImage.a $(PNETLIB)/support/libILSupport.a \
- $(PNETLIB)/libffi/.libs/libffi.a $(PNETLIB)//dumpasm/libILDumpAsm.a
-endif
-
-
diff --git a/vmkit/tools/vtoffset/Makefile b/vmkit/tools/vtoffset/Makefile
deleted file mode 100644
index e1a30fc..0000000
--- a/vmkit/tools/vtoffset/Makefile
+++ /dev/null
@@ -1,17 +0,0 @@
-##===- tools/vtoffset/Makefile -------)---------------------*- Makefile -*-===##
-#
-# The vmkit project
-#
-# This file is distributed under the University of Illinois Open Source
-# License. See LICENSE.TXT for details.
-#
-##===----------------------------------------------------------------------===##
-LEVEL = ../..
-
-include $(LEVEL)/Makefile.config
-
-TOOLNAME = vtoffset
-USEDLIBS = Mvm CommonThread Allocator $(GCLIB)
-LINK_COMPONENTS = jit nativecodegen scalaropts instrumentation ipa ipo bitwriter
-
-include $(LEVEL)/Makefile.common
diff --git a/vmkit/tools/vtoffset/VTOffset.cpp b/vmkit/tools/vtoffset/VTOffset.cpp
deleted file mode 100644
index be46d20..0000000
--- a/vmkit/tools/vtoffset/VTOffset.cpp
+++ /dev/null
@@ -1,101 +0,0 @@
-//===-- VTOffset.cpp - Calculates compiler dependant VT offsets -----------===//
-//
-// The Micro Virtual Machine
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#include <dlfcn.h>
-#include <setjmp.h>
-#include <signal.h>
-#include <stdio.h>
-
-#include "mvm/GC.h"
-#include "mvm/PrintBuffer.h"
-#include "mvm/Threads/Thread.h"
-#include "mvm/Sigsegv.h"
-
-class Toto : public mvm::Object {
-public:
-
- static VirtualTable* VT;
- virtual void print(mvm::PrintBuffer* buf) const {
- printf("in print!\n");
- }
- virtual intptr_t hashCode() {
- printf("in hashcode!\n");
- return 1;
- }
-
- virtual void tracer() {
- printf("in tracer\n");
- }
-
- virtual void destroyer(size_t sz) {
- printf("in destroy!\n");
- }
-
- ~Toto() {
- printf("in delete Toto!\n");
- }
-};
-
-class Tata : public Toto {
- public:
- static VirtualTable* VT;
- ~Tata() {
- printf("in delete Tata!\n");
- }
-};
-
-VirtualTable* Toto::VT = 0;
-typedef void (*toto_t)(Toto* t);
-
-VirtualTable* Tata::VT = 0;
-typedef void (*tata_t)(Tata* t);
-
-int main(int argc, char **argv, char **envp) {
- int base;
-
- mvm::Object::initialise();
-
- /*void* handle = sys_dlopen("libLisp.so", RTLD_LAZY | RTLD_GLOBAL);
- boot func = (boot)sys_dlsym(handle, "boot");
- func(argc, argv, envp);*/
- {
- Toto t;
- Toto::VT =((void**)(void*)&t)[0];
- toto_t* ptr = (toto_t*)Toto::VT;
- printf("ptr[0] = %d, ptr[1]= %d, ptr[2] = %d ptr[3] = %d ptr[4] = %d ptr[5] = %d\n", ptr[0], ptr[1], ptr[2], ptr[3], ptr[4], ptr[5]);
- printf("0 = \n");
- ptr[0](&t);
- //ptr[1](&t); // operator delete
- printf("2 = \n");
- ptr[2](&t);
- printf("3 = \n");
- ptr[3](&t);
- printf("4 = \n");
- ptr[4](&t);
- printf("5 = \n");
- ptr[5](&t);
-}
-{
- Tata t;
- Tata::VT =((void**)(void*)&t)[0];
- tata_t* ptr = (tata_t*)Tata::VT;
- printf("ptr[0] = %d, ptr[1]= %d, ptr[2] = %d ptr[3] = %d ptr[4] = %d ptr[5] = %d\n", ptr[0], ptr[1], ptr[2], ptr[3], ptr[4], ptr[5]);
- ptr[0](&t);
- printf("End\n");
- //ptr[1](&t); // operator delete
- ptr[2](&t);
- ptr[3](&t);
- ptr[4](&t);
- ptr[5](&t);
-}
-Tata* t = gc_new(Tata)();
- mvm::Thread::exit(0);
-
- return 0;
-}
diff --git a/vmkit/www/OpenProjects.html b/vmkit/www/OpenProjects.html
deleted file mode 100644
index 11a831c..0000000
--- a/vmkit/www/OpenProjects.html
+++ /dev/null
@@ -1,63 +0,0 @@
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
- "http://www.w3.org/TR/html4/strict.dtd">
-<!-- Material used from: HTML 4.01 specs: http://www.w3.org/TR/html401/ -->
-<html>
-<head>
- <META http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
- <title>"VMKit" JVM and .Net runtimes for LLVM</title>
- <link type="text/css" rel="stylesheet" href="menu.css" />
- <link type="text/css" rel="stylesheet" href="content.css" />
-</head>
-<body>
-
-<!--#include virtual="menu.html.incl"-->
-
-<div id="content">
-
-<h1>Open VMKit Projects</h1>
-
-<p>Here are a few tasks that are available for newcomers to work on, depending
-on what your interests are. This list is provided to generate ideas, it is not
-intended to be comprehensive. Please ask on llvm-dev for more specifics. </p>
-
-<ul>
-
-<li><b>Port VMKit's JVM to Harmony or OpenJDK</b>:
-VMKit currently uses GNU Classpath for the standard Java classes. Interfacing
-with another library such as Apache Harmony (http://harmony.apache.org) or
-Sun's OpenJDK (http://openjdk.java.net) may help improving support for latest
-benchmarks (http://www.spec.org/jvm2008).</li>
-</ul>
-
-<p>
-On the LLVM side, here are a few interesting projects that would help VMKit:
-</p>
-
-<ul>
-<li><b>Adaptive Optimization System</b>:
-Being able to adaptively optimize JIT-compiled code would dramastically help
-the startup time of VMKit. All the non-adaptive bits are already there in LLVM:
-baseline compiler (with the -fast command line and the simple register
-allocator), optimized compiler (with the linear scan register allocator), and
-a full set of optimizations changeable at runtime. What's left is a system that
-dynamically lookup the hotness of methods and re-compile with optimizations the
-methods that are often executed.
-</li>
-
-<li><b>Type-based alias-analysis</b>:
-Safe languages such as ones supported by VMKit (Java, C#) benefit a lot from
-a type based alias analysis. LLVM currently lacks full support of this feature
-for safe languages.
-</li>
-
-<li><b>Misceallenous Java-related optimizations</b>:
-Removal of array bounds checks, null pointer checks, devirtualization,
-inlining, etc.
-</li>
-</ul>
-
-
-</div>
-</body>
-</html>
-
diff --git a/vmkit/www/UsersManual.html b/vmkit/www/UsersManual.html
deleted file mode 100644
index 4691b45..0000000
--- a/vmkit/www/UsersManual.html
+++ /dev/null
@@ -1,22 +0,0 @@
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
- "http://www.w3.org/TR/html4/strict.dtd">
-<html>
-<head>
- <META http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
- <title>VMKit - Getting Started</title>
- <link type="text/css" rel="stylesheet" href="menu.css" />
- <link type="text/css" rel="stylesheet" href="content.css" />
-</head>
-<body>
-
-<!--#include virtual="menu.html.incl"-->
-
-<div id="content">
-
-<h1>VMKit User's Manual</h1>
-
-<ul>
- <li><a href="/use_aot.html">Java Ahead of Time (AOT) Compilation</a></li>
- <li><a href="/use_mmtk.html">VMKit and MMTk</a></li>
-</li>
-
diff --git a/vmkit/www/content.css b/vmkit/www/content.css
deleted file mode 100644
index 9aa94e9..0000000
--- a/vmkit/www/content.css
+++ /dev/null
@@ -1,27 +0,0 @@
-html { margin: 0px; } body { margin: 8px; }
-
-html, body {
- padding:0px;
- font-size:14px; font-family:"Lucida Grande", "Lucida Sans Unicode", Arial, Verdana, Helvetica, sans-serif; background-color: #fff; color: #222;
- line-height:1.5;
-}
-
-h1, h2, h3, tt { color: #000 }
-
-h1 { padding-top:0px; margin-top:0px;}
-h2 { color:#333333; padding-top:0.5em; }
-h3 { padding-top: 0.5em; margin-bottom: -0.25em; color:#2d58b7}
-li { padding-bottom: 0.5em; }
-ul { padding-left:1.5em; }
-
-/* Slides */
-IMG.img_slide {
- display: block;
- margin-left: auto;
- margin-right: auto
-}
-
-.itemTitle { color:#2d58b7 }
-
-/* Tables */
-tr { vertical-align:top }
diff --git a/vmkit/www/get_involved.html b/vmkit/www/get_involved.html
deleted file mode 100644
index 3ec26de..0000000
--- a/vmkit/www/get_involved.html
+++ /dev/null
@@ -1,50 +0,0 @@
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
- "http://www.w3.org/TR/html4/strict.dtd">
-<html>
-<head>
- <META http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
- <title>VMKit - Get Involved</title>
- <link type="text/css" rel="stylesheet" href="menu.css" />
- <link type="text/css" rel="stylesheet" href="content.css" />
-</head>
-<body>
-
-<!--#include virtual="menu.html.incl"-->
-
-<div id="content">
-
-<h1>Getting Involved with the vmkit Project</h1>
-
-<p>Once you have <a href="get_started.html">checked out and built</a> vmkit and
-played around with it, you might be wondering what you can do to make it better
-and contribute to its development. Alternatively, maybe you just want to follow
-the development of the project to see it progress.
-</p>
-
-<h2>Follow what's going on</h2>
-
-<p>VMKit is a subproject of the <a href="http://llvm.org">LLVM Project</a>, and
-uses llvm dev mailing list for development question and the vmkit-commits
-mailing list for patches:</p>
-
-<ul>
-<li><a href="http://lists.cs.uiuc.edu/mailman/listinfo/vmkit-commits">vmkit-commits
-</a> - This list is for patch submission/discussion.</li>
-
-<li><a href="http://lists.cs.uiuc.edu/mailman/listinfo/llvmdev">llvmdev</a> -
-This list is for everything else llvm/vmkit related (questions and answers, bug
-reports, etc).</li>
-
-</ul>
-
-<p>The best way to talk with other developers on the project is through the <a
-href="http://lists.cs.uiuc.edu/mailman/listinfo/llvmdev">llvm-dev mailing
-list</a>. </p>
-
-
-<p>You can also visit the <a href="http://vmkit.llvm.org/OpenProjects.html">
-Open Projects</a> page for a list of interesting things to work on in VMKit.</p>
-
-</div>
-</body>
-</html>
diff --git a/vmkit/www/get_started.html b/vmkit/www/get_started.html
deleted file mode 100644
index 09a246f..0000000
--- a/vmkit/www/get_started.html
+++ /dev/null
@@ -1,120 +0,0 @@
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
- "http://www.w3.org/TR/html4/strict.dtd">
-<html>
-<head>
- <META http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
- <title>VMKit - Getting Started</title>
- <link type="text/css" rel="stylesheet" href="menu.css" />
- <link type="text/css" rel="stylesheet" href="content.css" />
-</head>
-<body>
-
-<!--#include virtual="menu.html.incl"-->
-
-<div id="content">
-
-<h1>Getting Started: Building and Running VMKit</h1>
-
-
-<p>This page gives you the shortest path to checking out vmkit and demos a few
-options. This should get you up and running with the minimum of muss and fuss.
-If you like what you see, please consider <a href="get_involved.html">getting
-involved</a> with the vmkit community.</p>
-
-
-<h2>A word of warning</h2>
-
-<p>While this work aims to provide a fully functional JVM, it
-is <em>still early work</em> and is under heavy development.
-<p>Some of the common missing pieces in vmkit/llvm are:</p>
-
-<ol>
- <li> Mixed interpretation/compilation.</li>
- <li> Adaptive optimization.</li>
-</ol>
-
-<h2 id="build">Building vmkit / working with the code</h2>
-
-<p>If you would like to check out and build the project, the current scheme
-is:</p>
-
-<ol>
- <li><a href="http://www.llvm.org/docs/GettingStarted.html#checkout">Checkout
- and build LLVM</a> from SVN head:</li>
-
- <ul>
- <li><tt>svn co http://llvm.org/svn/llvm-project/llvm/trunk llvm</tt></li>
- <li><tt>cd llvm</tt></li>
- <li><tt>./configure; make</tt></li>
- </ul>
-
-
- <li><a href="ftp://ftp.gnu.org/gnu/classpath/classpath-0.97.2.tar.gz">Download
- GNU Classpath 0.97.2</a>:</li>
-
- <ul>
- <li><tt>tar zxvf classpath-0.97.2.tar.gz</tt></li>
- <li><tt>cd classpath-0.97.2</tt></li>
- <li><tt>./configure --disable-plugin --disable-examples --disable-Werror; make</tt></li>
- <li><tt>cd lib</li></tt>
- <li><tt>If you are running on Linux:</li></tt>
- <ul>
- <li><tt>ln -s ../native/jni/gtk-peer/.libs/libgtkpeer.so;</li></tt>
- <li><tt>ln -s ../native/jni/gconf-peer/.libs/libgconfpeer.so;</li></tt>
- <li><tt>ln -s ../native/jni/java-io/.libs/libjavaio.so;</li></tt>
- <li><tt>ln -s ../native/jni/java-lang/.libs/libjavalangreflect.so;</li></tt>
- <li><tt>ln -s ../native/jni/java-lang/.libs/libjavalang.so;</li></tt>
- <li><tt>ln -s ../native/jni/java-net/.libs/libjavanet.so;</li></tt>
- <li><tt>ln -s ../native/jni/java-nio/.libs/libjavanio.so;</li></tt>
- <li><tt>ln -s ../native/jni/java-util/.libs/libjavautil.so;</li></tt>
- </ul>
- <li><tt>If you are running on MacOS:</li></tt>
- <ul>
- <li><tt>ln -s ../native/jni/gtk-peer/.libs/libgtkpeer.dylib;</li></tt>
- <li><tt>ln -s ../native/jni/gconf-peer/.libs/libgconfpeer.dylib;</li></tt>
- <li><tt>ln -s ../native/jni/java-io/.libs/libjavaio.dylib;</li></tt>
- <li><tt>ln -s ../native/jni/java-lang/.libs/libjavalangreflect.dylib;</li></tt>
- <li><tt>ln -s ../native/jni/java-lang/.libs/libjavalang.dylib;</li></tt>
- <li><tt>ln -s ../native/jni/java-net/.libs/libjavanet.dylib;</li></tt>
- <li><tt>ln -s ../native/jni/java-nio/.libs/libjavanio.dylib;</li></tt>
- <li><tt>ln -s ../native/jni/java-util/.libs/libjavautil.dylib;</li></tt>
- </ul>
- </ul>
-
- <li>Checkout vmkit:</li>
- <ul>
- <li><tt>svn co http://llvm.org/svn/llvm-project/vmkit/trunk vmkit</tt></li>
-
- </ul>
- <li>Configure vmkit:</li>
- <ul>
- <li><tt>./configure </tt></li>
- <dl>
- <dt><tt>--with-llvmsrc=<directory></tt></dt>
- <dd>Tell vmkit where the LLVM source tree is located.</dd>
- <dt><br/><tt>--with-llvmobj=<directory></tt></dt>
- <dd>Tell vmkit where the LLVM object tree is located.</dd>
- <dt><br/><tt>--with-gnu-classpath-glibj=<file or directory></tt></dt>
- <dd>Tell vmkit where GNU Classpath glibj.zip is located.</dd>
- <dt><br/><tt>--with-gnu-classpath-libs=<directory></tt></dt>
- <dd>Tell vmkit where GNU Classpath libs are located.</dd>
- </dl>
-
- </ul>
-
- <li>Build vmkit:</li>
- <ul>
- <li><tt>cd vmkit</tt></li>
- <li><tt>make</tt> (this will give you a debug build)</li>
- </ul>
-
- <li>Try it out: (assuming vmkit/Debug/bin is in your path)</li>
- <ul>
- <li><tt>j3 --help</tt></li>
- <li><tt>j3 HelloWorld</tt></li>
- </ul>
-</ol>
-
-</div>
-</body>
-</html>
diff --git a/vmkit/www/index.html b/vmkit/www/index.html
deleted file mode 100644
index e6e4b62..0000000
--- a/vmkit/www/index.html
+++ /dev/null
@@ -1,111 +0,0 @@
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
- "http://www.w3.org/TR/html4/strict.dtd">
-<!-- Material used from: HTML 4.01 specs: http://www.w3.org/TR/html401/ -->
-<html>
-<head>
- <META http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
- <title>VMKit: a substrate for virtual machines</title>
- <link type="text/css" rel="stylesheet" href="menu.css" />
- <link type="text/css" rel="stylesheet" href="content.css" />
-</head>
-<body>
-<!--#include virtual="menu.html.incl"-->
-<div id="content">
- <!--*********************************************************************-->
- <h1>VMKit: a substrate for virtual machines</h1>
- <!--*********************************************************************-->
-
- <p>The VMKit project is a framework for building virtual machines. It uses
- <a href="http://llvm.org">LLVM</a> for compiling and optimizing high-level
- languages to machine code, and <a href="http://jikesrvm.org/MMTk">MMTk</a>
- to manage memory. J3 is an implementation of a JVM with VMKit.
- You can <a href="get_started.html">get and build</a> the source of J3
- today.</p>
-
- <!--=====================================================================-->
- <h2 id="goals">Features</h2>
- <!--=====================================================================-->
-
- <p>VMKit provides the following features:</p>
-
- <p><b>End-User Features</a></b>:</p>
-
- <ul>
- <li>Precise garbage collection.</li>
- <li>Just-in-Time and Ahead-of-Time compilation.</li>
- <li>Portable on many architectures (x86, x64, ppc32, ppc64, arm).</li>
- </ul>
-
- <p><b>Developer Features</a></b>:</p>
-
- <ul>
- <li>Relatively small code base (~ 20k loc per VM)</li>
- <li>Infrastructure for running multiple VM/applications in a single
- process</li>
- <li>Infrastructure for virtual machine research and development</li>
- </ul>
-
- <!--=====================================================================-->
- <h2>Why?</h2>
- <!--=====================================================================-->
-
- <p>The development of VMKit was started out of a need to factorize virtual
- machine development. The JVM and CLI virtual machine have many
- similarities, but are too high-level to be the basis of a "universal"
- virtual machine. The LLVM IR on the opposite is low-level enough to be
- able to execute these VMs. VMKit is a proof of concept implementation
- towards that direction.</p>
-
- <p>Paper on the design of VMKit:
- <ul>
- <li><a href="publications/vmkit.html">VMKit: a Substrate for Managed Runtime Environments</a>
- </li>
- </ul>
-
- <p>The PhD thesis that initiated VMKit:
- <ul>
- <li><a href="publications/thesis.html">Nicolas Geoffray's PhD thesis</a>
- </li>
- </ul>
-
- <p>An introduction to VMKit can be found in the following video lectures:
- <ul>
- <li><a href="http://llvm.org/devmtg/2009-10/Geoffray_GarbageCollectionVMKit-700kbps.mov">
- Presentation of VMKit/MMTk at the 2009 LLVM Developer's Meeting</a>
- </li>
- <li><a href="http://llvm.org/devmtg/2008-08/Geoffray_VMKitProject_Lo.3gp">
- Presentation of VMKit at the 2008 LLVM Developer's Meeting</a>
- </li>
- </ul>
- </p>
-
- <!--=====================================================================-->
- <h2>Current Status</h2>
- <!--=====================================================================-->
-
- <p>VMKit currently has a decent implementation of a JVM. It executes
- large projects (e.g. OSGi Felix, Tomcat, Eclipse) and the
- <a href="http://dacapobench.org">DaCapo benchmarks</a>.
- </p>
-
- <p>The JVM has been tested on Linux/x64, Linux/x86, Linux/ppc32, MacOSX/x64,
- MacOSX/x86, MacOSX/ppc32. The JVM may work on ppc64. Support for
- Windows has not been investigated.
- </p>
-
-
- <!--=====================================================================-->
- <h2>Get it and get involved!</h2>
- <!--=====================================================================-->
-
- <p>Start by <a href="get_started.html">getting the code, building it, and
- playing with it</a>. This will show you the sorts of things we can do
- today.</p>
-
- <p>Once you've done that, please consider <a href="get_involved.html">getting
- involved in the VMKit community</a>. Currently, VMKit is tightly
- integrated into the LLVM community. You can sign up for the LLVM mailing
- list to ask and learn about how the project works.</p>
-</div>
-</body>
-</html>
diff --git a/vmkit/www/menu.css b/vmkit/www/menu.css
deleted file mode 100644
index f8f2adb..0000000
--- a/vmkit/www/menu.css
+++ /dev/null
@@ -1,47 +0,0 @@
-/***************/
-/* page layout */
-/***************/
-
-html,body {
- padding:0px;
- font-size:14px; font-family:"Lucida Grande", "Lucida Sans Unicode", Arial, Verdana, Helvetica, sans-serif; background-color: #fff; color: #222;
- line-height:1.5;
- margin-left: 10px;
-}
-
-
-[id=menu] {
- position:fixed;
- width:25ex;
-}
-[id=content] {
- /* ***** EDIT THIS VALUE IF CONTENT OVERLAPS MENU ***** */
- position:absolute;
- left:29ex;
- padding-right:4ex;
-}
-
-/**************/
-/* menu style */
-/**************/
-
-#menu .submenu {
- padding-top:1em;
- display:block;
-}
-
-#menu label {
- display:block;
- font-weight: bold;
- text-align: center;
- background-color: rgb(192,192,192);
-}
-#menu a {
- padding:0 .2em;
- display:block;
- text-align: center;
- background-color: rgb(235,235,235);
-}
-#menu a:visited {
- color:rgb(100,50,100);
-}
diff --git a/vmkit/www/menu.html.incl b/vmkit/www/menu.html.incl
deleted file mode 100644
index 147733d..0000000
--- a/vmkit/www/menu.html.incl
+++ /dev/null
@@ -1,30 +0,0 @@
-<div id="menu">
- <div>
- <a href="http://llvm.org/">LLVM Home</a>
- </div>
-
- <div class="submenu">
- <label>VMKit Info</label>
- <a href="/index.html">About</a>
- <a href="/get_started.html">Get Started</a>
- <a href="/get_involved.html">Get Involved</a>
- <a href="/UsersManual.html">Users Manual</a>
- <a href="/OpenProjects.html">Open Projects</a>
- <a href="/pubs.html">Publications</a>
- <a href="/releases/index.html">Releases</a>
- </div>
-
- <div class="submenu">
- <label>Quick Links</label>
- <a href="http://lists.cs.uiuc.edu/mailman/listinfo/llvmdev">llvm-dev</a>
- <a href="http://lists.cs.uiuc.edu/mailman/listinfo/vmkit-commits">vmkit-commits</a>
- <a href="http://llvm.org/bugs/">Bug Reports</a>
- <a href="http://llvm.org/viewvc/llvm-project/vmkit/trunk/">Browse Source</a>
- </div>
-
- <div class="submenu">
- <label>Events</label>
- <a href="http://llvm.org/devmtg/">LLVM/Clang Developer Meetings</a>
- </div>
-
-</div>
diff --git a/vmkit/www/publications/ladyvm.html b/vmkit/www/publications/ladyvm.html
deleted file mode 100644
index ce3185a..0000000
--- a/vmkit/www/publications/ladyvm.html
+++ /dev/null
@@ -1,51 +0,0 @@
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
-<html>
-<head>
- <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
- <link rel="stylesheet" href="http://llvm.org/llvm.css" type="text/css" media="screen" />
- <title>A Lazy Developer Approach: Building a JVM with Third Party Software</title>
-</head>
-<body>
-
-<div class="pub_title">
- A Lazy Developer Approach: Building a JVM with Third Party Software
-</div>
-<div class="pub_author">
- Nicolas Geoffray, Gael Thomas, Charles Clement and Bertil Folliot
-</div>
-
-<h2>Abstract:</h2>
-<blockquote>
-The development of a complete Java Virtual Machine (JVM)
-implementation is a tedious process which involves knowledge in different
-areas: garbage collection, just in time compilation, interpretation, file
-parsing, data structures, etc. The result is that developing its own virtual
-machine requires a considerable amount of man/year. In this paper we show that
-one can implement a JVM with third party software and with performance
-comparable to industrial and top open-source JVMs. Our proof-of-concept
-implementation uses existing versions of a garbage collector, a just in
-time compiler, and the base library, and is robust enough to
-execute complex Java applications such as the OSGi Felix
-implementation and the Tomcat servlet container.
-
-</blockquote>
-
-<h2>Bibtex:</h2>
-<pre>
-@inproceedings{geoffray08ladyvm,
- author = {N. Geoffray and G. Thomas and C. Cl\'ement and B. Folliot},
- title = { A Lazy Developer Approach: Building a JVM with Third Party Software },
- booktitle = {{International Conference on Principles and Practice of Programming In Java (PPPJ 2008) }},
- year = {2008},
- address = {Modena, Italy},
- month = {September},
-}
-</pre>
-
-<h2>Download:</h2>
-<ul>
- <li><a href="http://pagesperso-systeme.lip6.fr/Nicolas.Geoffray/files/pppj-08.pdf">A Lazy Developer Approach: Building a JVM with Third Party Software</a> (PDF)</li>
-</ul>
-
-</body>
-</html>
diff --git a/vmkit/www/publications/osgi_dsn.html b/vmkit/www/publications/osgi_dsn.html
deleted file mode 100644
index bc0b19e..0000000
--- a/vmkit/www/publications/osgi_dsn.html
+++ /dev/null
@@ -1,55 +0,0 @@
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
-<html>
-<head>
- <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
- <link rel="stylesheet" href="http://llvm.org/llvm.css" type="text/css" media="screen" />
- <title>I-JVM: a Java Virtual Machine for Component Isolation in OSGi</title>
-</head>
-<body>
-
-<div class="pub_title">
- I-JVM: a Java Virtual Machine for Component Isolation in OSGi
-</div>
-<div class="pub_author">
- Nicolas Geoffray, Gael Thomas, Gilles Muller, Pierre Parrend, Stephane Frenot, Bertil Folliot
-</div>
-
-<h2>Abstract:</h2>
-<blockquote>
-The OSGi framework is a Java-based, centralized, component oriented
-platform. It is being widely adopted as an execution environment for
-the development of extensible applications. However, current Java
-Virtual Machines are unable to isolate components from each other.
-For instance, a malicious component can freeze the complete platform
-by allocating too much memory or alter the behavior of other components by
-modifying shared variables.
-
-This paper presents I-JVM, a Java Virtual Machine that provides a
-lightweight approach to isolation while preserving compatibility with
-legacy OSGi applications. Our evaluation of I-JVM shows that it solves
-the 8 known OSGi vulnerabilities that are due to the Java Virtual
-Machine and that the overhead of I-JVM compared to the JVM on which
-it is based is below 20%.
-</blockquote>
-
-<h2>Bibtex:</h2>
-<pre>
-@inproceedings{geoffray09ijvm,
- author = {N. Geoffray and G. Thomas and G. Muller and P. Parrend and S. Fr\'enot and B. Folliot},
- title = {{I-JVM: a Java Virtual Machine for Component Isolation in OSGi}},
- booktitle = {International Conference on Dependable Systems and Networks (DSN 2009)},
- publisher = {IEEE Computer Society},
- pdf = {files/ijvm.pdf},
- year = {2009},
- month = {June},
- address = {Estoril, Portugal}
-}
-</pre>
-
-<h2>Download:</h2>
-<ul>
- <li><a href="http://pagesperso-systeme.lip6.fr/Nicolas.Geoffray/files/ijvm.pdf">I-JVM: a Java Virtual Machine for Component Isolation in OSGi</a> (PDF)</li>
-</ul>
-
-</body>
-</html>
diff --git a/vmkit/www/publications/osgi_iies.html b/vmkit/www/publications/osgi_iies.html
deleted file mode 100644
index bcc2edb..0000000
--- a/vmkit/www/publications/osgi_iies.html
+++ /dev/null
@@ -1,49 +0,0 @@
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
-<html>
-<head>
- <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
- <link rel="stylesheet" href="http://llvm.org/llvm.css" type="text/css" media="screen" />
- <title>Towards a new Isolation Abstraction for OSGi</title>
-</head>
-<body>
-
-<div class="pub_title">
- Towards a new Isolation Abstraction for OSGi
-</div>
-<div class="pub_author">
- Nicolas Geoffray, Gael Thomas, Charles Clement and Bertil Folliot
-</div>
-
-<h2>Abstract:</h2>
-<blockquote>
-The Open Service Gateway Initiative (OSGi) specification defines a dynamic Java-based service oriented architecture for networked environments such
-as home service gateways. To provide isolation between different services, it relies on the Java class loading mechanism.
-While class loaders have many advantages beside isolation, they are poor in protecting the system against
-malicious or buggy services. In this paper,
-we propose a new approach for service isolation. It is based on the Java isolate technology, without a
-task-oriented architecture. Our approach is more tailored to service-oriented architectures and in particular
-offers a complete isolation abstraction to the OSGi platform. It is currently under development, hence
-we do not provide in this paper any technical details nor results.
-
-</blockquote>
-
-<h2>Bibtex:</h2>
-<pre>
-@inproceedings{geoffray08isolationosgi,
- author = {N. Geoffray and G. Thomas and C. Cl\'ement and B. Folliot},
- title = {{Towards a new Isolation Abstraction for OSGi}},
- booktitle = {Proceedings of the First Workshop on Isolation and Integration in Embedded Systems (IIES 2008)},
- year = {2008},
- pages = {41-45},
- address = {Glasgow, Scotland, UK},
- month = {April},
-}
-</pre>
-
-<h2>Download:</h2>
-<ul>
- <li><a href="http://pagesperso-systeme.lip6.fr/Nicolas.Geoffray/files/iies-08.pdf">Towards a new Isolation Abstraction for OSGi</a> (PDF)</li>
-</ul>
-
-</body>
-</html>
diff --git a/vmkit/www/publications/thesis.html b/vmkit/www/publications/thesis.html
deleted file mode 100644
index e8f732b..0000000
--- a/vmkit/www/publications/thesis.html
+++ /dev/null
@@ -1,59 +0,0 @@
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
-<html>
-<head>
- <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
- <link rel="stylesheet" href="http://llvm.org/llvm.css" type="text/css" media="screen" />
- <title>Fostering Systems Research with Managed Runtimes</title>
-</head>
-<body>
-
-<div class="pub_title">
- Fostering Systems Research with Managed Runtimes
-</div>
-<div class="pub_author">
- Nicolas Geoffray
-</div>
-
-<h2>Abstract:</h2>
-<blockquote>
-Many systems research projects now target managed runtime environments (MRE)
-because they provide better productivity and safety compared to native
-environments. Still, developing and optimizing an MRE is a tedious
-task that requires many years of development. Although MREs share some common
-functionalities, such as a Just In Time Compiler or a Garbage Collector, this
-opportunity for sharing has not been yet exploited in implementing MREs.
-This thesis describes and evaluates VMKit, a first attempt to build a common
-substrate that eases the development and experimentation of high-level MREs and
-systems mechanisms. VMKit has been successfully used to build two MREs,
-a Java Virtual Machine and a Common Language Runtime, as well as a a new system
-mechanism that provides better security in the context of service-oriented
-architectures.
-
-We describe the lessons learnt in implementing such a common
-infrastructure from a performance and an ease of development standpoint.
-The performance of VMKit are reasonable compared to industrial MREs, and
-the high-level MREs are only 20,000 lines of code. Our new system
-mechanism only requires the addition of 600 lines of code in VMKit, and
-is a significant step towards better dependable systems.
-
-</blockquote>
-
-<h2>Bibtex:</h2>
-<pre>
-@PhdThesis{geoffray:phd,
- author = {N. Geoffray},
- title = { Fostering Systems Research with Managed Runtimes },
- schoold = {Universit\'e Pierre et Marie Curie},
- year = {2009},
- address = {Paris, France},
- month = {September},
-}
-</pre>
-
-<h2>Download:</h2>
-<ul>
- <li><a href="http://pagesperso-systeme.lip6.fr/Nicolas.Geoffray/these-geoffray.pdf">Fostering Systems Research with Managed Runtimes</a> (PDF)</li>
-</ul>
-
-</body>
-</html>
diff --git a/vmkit/www/publications/vmkit.html b/vmkit/www/publications/vmkit.html
deleted file mode 100644
index fe5eb0e..0000000
--- a/vmkit/www/publications/vmkit.html
+++ /dev/null
@@ -1,62 +0,0 @@
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
-<html>
-<head>
- <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
- <link rel="stylesheet" href="http://llvm.org/llvm.css" type="text/css" media="screen" />
- <title>VMKit: a Substrate for Managed Runtime Enviroments</title>
-</head>
-<body>
-
-<div class="pub_title">
- VMKit: a Substrate for Managed Runtime Environments
-</div>
-<div class="pub_author">
- Nicolas Geoffray, Gael Thomas, Julia Lawall, Gilles Muller and Bertil Folliot
-</div>
-
-<h2>Abstract:</h2>
-<blockquote>
-Managed Runtime Environments (MREs), such as the JVM and the CLI, form an
-attractive environment for program execution, by providing portability and
-safety, via the use of a bytecode language and automatic memory management,
-as well as good performance, via just-in-time (JIT) compilation.
-Nevertheless, developing a fully featured MRE, including e.g.
-a garbage collector and JIT compiler, is a herculean
-task. As a result, new languages cannot easily take advantage of the
-benefits of MREs, and it is difficult to experiment with
-extensions of existing MRE based languages.
-
-This paper describes and evaluates VMKit, a first attempt to build a common
-substrate that eases the development of high-level MREs. We have successfully
-used VMKit to build two MREs: a Java Virtual Machine and a Common
-Language Runtime. We provide an extensive study of the lessons learned in
-developing this infrastructure, and assess the ease of implementing new
-MREs or MRE extensions and the resulting performance. In
-particular, it took one of the authors only one month to develop a Common
-Language Runtime using VMKit. VMKit furthermore has performance comparable
-to the well established open source MREs Cacao, Apache Harmony and Mono, and is
-1.2 to 3 times slower than JikesRVM on most of the DaCapo
-benchmarks.
-
-</blockquote>
-
-<h2>Bibtex:</h2>
-<pre>
-@inproceedings{geoffray10vmkit,
- author = {N. Geoffray and G. Thomas and J.Lawall and G. Muller and B. Folliot},
- title = {{VMKit: a Substrate for Managed Runtime Environments}},
- booktitle = {Virtual Execution Environment Conference (VEE 2010)},
- publisher = {ACM Press},
- year = {2010},
- month = {March},
- address = {Pittsburgh, USA}
-}
-</pre>
-
-<h2>Download:</h2>
-<ul>
- <li><a href="http://llvm.org/pubs/2010-03-VEE-VMKit.pdf">VMKit: a Substrate for Managed Runtime Environments</a> (PDF)</li>
-</ul>
-
-</body>
-</html>
diff --git a/vmkit/www/pubs.html b/vmkit/www/pubs.html
deleted file mode 100644
index 0692a17..0000000
--- a/vmkit/www/pubs.html
+++ /dev/null
@@ -1,46 +0,0 @@
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
- "http://www.w3.org/TR/html4/strict.dtd">
-<html>
-<head>
- <META http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
- <title>VMKit - Getting Started</title>
- <link type="text/css" rel="stylesheet" href="menu.css" />
- <link type="text/css" rel="stylesheet" href="content.css" />
-</head>
-<body>
-
-<!--#include virtual="menu.html.incl"-->
-
-<div id="content">
-
-<h1>VMKit related publications</h1>
-
-
-<h2>2010</h2>
-<ol>
- <li><a href="publications/vmkit.html">VMKit: a Substrate for Managed Runtime Environments</a><br/>
- Nicolas Geoffray, Gael Thomas, Julia Lawall, Gilles Muller, Bertil Folliot<br>
- Proc. of the Virtual Execution Environments Conference (VEE'10), Pittsburgh, USA, Mar. 2010</li>
-</ol>
-<h2>2009</h2>
-<ol>
- <li><a href="publications/thesis.html">Fostering Systems Research with Managed Runtimes</a><br/>
- Nicolas Geoffray<br>
- PhD Thesis, Universite Pierre et Marie Curie, Paris, France, Sep. 2009</li>
- <li><a href="publications/osgi_dsn.html">I-JVM: a Java Virtual Machine for Component Isolation in OSGi</a><br/>
- Nicolas Geoffray, Gael Thomas, Gilles Muller, Pierre Parrend, Stephane Frenot, Bertil Folliot<br>
- Proc. of the Dependable Systems and Network Conference (DSN'09), Estoril, Portugal, Jun. 2009</li>
-</ol>
-<h2>2008</h2>
-<ol>
- <li><a href="publications/ladyvm.html">A Lazy Developer Approach: Building a JVM with Third Party Software</a><br/>
- Nicolas Geoffray, Gael Thomas, Charles Clement, Bertil Folliot<br>
- Proc. of the Principles and Practice of Programming in Java (PPPJ'08), Modena, Italy Sep. 2008</li>
- <li><a href="publications/osgi_dsn.html">Towards a new Isolation Abstraction for OSGi</a><br/>
- Nicolas Geoffray, Gael Thomas, Charles Clement, Bertil Folliot<br>
- Proc. of the Isolation and Integration in Embedded Systems (IIES'08), Glasgow, Scotland, Apr. 2008</li>
-</ol>
-
-</div>
-</body>
-</html>
diff --git a/vmkit/www/releases/index.html b/vmkit/www/releases/index.html
deleted file mode 100644
index 7bd9473..0000000
--- a/vmkit/www/releases/index.html
+++ /dev/null
@@ -1,59 +0,0 @@
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
- "http://www.w3.org/TR/html4/strict.dtd">
-<!-- Material used from: HTML 4.01 specs: http://www.w3.org/TR/html401/ -->
-<html>
-<head>
- <META http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
- <title>"vmkit" JVM and .Net runtimes for LLVM</title>
- <link type="text/css" rel="stylesheet" href="../menu.css" />
- <link type="text/css" rel="stylesheet" href="../content.css" />
-</head>
-<body>
-
-<!--#include virtual="../menu.html.incl"-->
-
-
-<div id="content">
- <!--*********************************************************************-->
- <h1>VMKit Releases</h1>
- <!--*********************************************************************-->
-
- <p>The VMKit project was publicly released in the time of LLVM 2.3. Since
- LLVM 2.4, VMKit follows each LLVM release. The first release of VMKit is
- version 0.24.</p>
-
- <!--=====================================================================-->
- <h2 id="dls">Downloads</h2>
- <!--=====================================================================-->
-
- <ul>
- <li><a href="http://llvm.org/viewvc/llvm-project/vmkit/branches/release_028/www/releases/vmkit-0.28.tar.bz2?revision=116299">
- VMKit release 0.28 </a> (
- <a href="http://llvm.org/releases/2.8/docs/ReleaseNotes.html#vmkit">
- Release notes </a>)
- </li>
- <li><a href="http://llvm.org/releases/2.7/vmkit-0.27.tar.bz2">
- VMKit release 0.27 </a> (
- <a href="http://llvm.org/releases/2.7/docs/ReleaseNotes.html#vmkit">
- Release notes </a>)
- </li>
- <li><a href="http://llvm.org/releases/2.6/vmkit-0.26.tar.bz2">
- VMKit release 0.26 </a> (
- <a href="http://llvm.org/releases/2.6/docs/ReleaseNotes.html#vmkit">
- Release notes </a>)
- </li>
- <li><a href="http://llvm.org/releases/2.5/vmkit-0.25.tar.bz2">
- VMKit release 0.25 </a> (
- <a href="http://llvm.org/releases/2.5/docs/ReleaseNotes.html#vmkit">
- Release notes </a>)
- </li>
- <li><a href="http://llvm.org/releases/2.4/vmkit-0.24.tar.bz2">
- VMKit release 0.24 </a> (
- <a href="http://llvm.org/releases/2.4/docs/ReleaseNotes.html#vmkit">
- Release notes </a>)
- </li>
- </ul>
-
-</div>
-</body>
-</html>
diff --git a/vmkit/www/use_aot.html b/vmkit/www/use_aot.html
deleted file mode 100644
index f1c7747..0000000
--- a/vmkit/www/use_aot.html
+++ /dev/null
@@ -1,60 +0,0 @@
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
- "http://www.w3.org/TR/html4/strict.dtd">
-<html>
-<head>
- <META http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
- <title>VMKit - Getting Started</title>
- <link type="text/css" rel="stylesheet" href="menu.css" />
- <link type="text/css" rel="stylesheet" href="content.css" />
-</head>
-<body>
-
-<!--#include virtual="menu.html.incl"-->
-
-<div id="content">
-
-<h1>Getting Started: Java Ahead of Time compilation with VMKit</h1>
-
-
-<p>This page gives you the instructions on how to use the Java ahead of time
-compiler of VMKit.</p>
-
-
-<ol>
- <li><a href="/get_started.html">Checkout
- and build VMKit</a> from SVN head.</li>
-
- <li>Compile into a dynamic library the core Java libs (e.g. GNU Classpath):
- </li>
-
- <ul>
- <li><tt>cd tools/vmjc/libvmjc</tt></li>
- <li><tt>make ENABLE_OPTIMIZED=1 (go get coffee)</tt></li>
- </ul>
-
- <li>Update PATH to include LLVM and VMKit binaries (replace *_OBJ with your
- directory):</li>
- <ul>
- <li><tt>export PATH=$(LLVM_OBJ)/Release/bin:$(VMKIT_OBJ)/Release/bin
- </tt></li>
- </ul>
-
- <li>Update LD_LIBRARY_PATH to include the dynamic library previously
- compiled (replace VMKIT_OBJ with your directory):</li>
- <ul>
- <li><tt>export LD_LIBRARY_PATH=$(VMKIT_OBJ)/Release/lib
- </tt></li>
- </ul>
-
- <li>Use the <tt>llcj</tt> tool on a class or a jar file:</li>
- <ul>
- <li><tt>llcj -S Foo.class (emit bytecode)</tt></li>
- <li><tt>llcj --main=Foo Foo.class (generate an executable)</tt></li>
- <li><tt>llcj -c Foo.class (generate an object file)</tt></li>
- </ul>
-
-</ol>
-
-</div>
-</body>
-</html>
diff --git a/vmkit/www/use_mmtk.html b/vmkit/www/use_mmtk.html
deleted file mode 100644
index cad8bd2..0000000
--- a/vmkit/www/use_mmtk.html
+++ /dev/null
@@ -1,41 +0,0 @@
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
- "http://www.w3.org/TR/html4/strict.dtd">
-<html>
-<head>
- <META http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
- <title>VMKit - Getting Started</title>
- <link type="text/css" rel="stylesheet" href="menu.css" />
- <link type="text/css" rel="stylesheet" href="content.css" />
-</head>
-<body>
-
-<!--#include virtual="menu.html.incl"-->
-
-<div id="content">
-
-<h1>Getting Started: VMKit and MMTk</h1>
-
-
-<p>This page gives you the instructions on how to build VMKit with a MMTk garbage collector.</p>
-
-
-<ol>
- <li><a href="http://www.llvm.org/docs/GCCFEBuildInstrs.html">Checkout
- and build LLVM-GCC</a> from SVN head.</li>
- <li> Update PATH to include the <tt>llvm-gcc</tt> binary. </li>
- <li> Re-configure LLVM. </li>
- <li> Configure VMKit with three additional options: <tt>--with-gc=mmtk</tt>, <tt>--with-llvmgcc</tt>, and <tt>--with-mmtk-plan={marksweep|copyms}</tt> </li>
- <li> Build VMKit:</li>
- <ul>
- <li><tt>make ENABLE_OPTIMIZED=1 </tt></li>
- </ul>
- <li>Run VMKit:</li>
- <ul>
- <li><tt>Release/bin/j3 Foo </tt></li>
- </ul>
-
-</ol>
-
-</div>
-</body>
-</html>