NewStringUTF(name))),
((jint)type),
((jlong)start),
diff --git a/com.amd.aparapi.jni/src/cpp/profileInfo.h b/com.amd.aparapi.jni/src/cpp/opencl/profileInfo.h
similarity index 100%
rename from com.amd.aparapi.jni/src/cpp/profileInfo.h
rename to com.amd.aparapi.jni/src/cpp/opencl/profileInfo.h
diff --git a/com.amd.aparapi/.classpath b/com.amd.aparapi/.classpath
index f8f3492a..05367a39 100644
--- a/com.amd.aparapi/.classpath
+++ b/com.amd.aparapi/.classpath
@@ -1,7 +1,7 @@
-
+
diff --git a/com.amd.aparapi/.externalToolBuilders/New_Builder.launch b/com.amd.aparapi/.externalToolBuilders/New_Builder.launch
new file mode 100644
index 00000000..d8d942c2
--- /dev/null
+++ b/com.amd.aparapi/.externalToolBuilders/New_Builder.launch
@@ -0,0 +1,8 @@
+
+
+
+
+
+
+
+
diff --git a/com.amd.aparapi/.externalToolBuilders/org.eclipse.jdt.core.javabuilder.launch b/com.amd.aparapi/.externalToolBuilders/org.eclipse.jdt.core.javabuilder.launch
new file mode 100644
index 00000000..851c9f55
--- /dev/null
+++ b/com.amd.aparapi/.externalToolBuilders/org.eclipse.jdt.core.javabuilder.launch
@@ -0,0 +1,7 @@
+
+
+
+
+
+
+
diff --git a/com.amd.aparapi/.project b/com.amd.aparapi/.project
index 54ce0fda..69443748 100644
--- a/com.amd.aparapi/.project
+++ b/com.amd.aparapi/.project
@@ -6,8 +6,23 @@
- org.eclipse.jdt.core.javabuilder
+ org.eclipse.ui.externaltools.ExternalToolBuilder
+ full,incremental,
+
+ LaunchConfigHandle
+ <project>/.externalToolBuilders/org.eclipse.jdt.core.javabuilder.launch
+
+
+
+
+ org.eclipse.ui.externaltools.ExternalToolBuilder
+ full,incremental,
+
+
+ LaunchConfigHandle
+ <project>/.externalToolBuilders/New_Builder.launch
+
diff --git a/com.amd.aparapi/build.xml b/com.amd.aparapi/build.xml
index d3017f52..4b7ada40 100644
--- a/com.amd.aparapi/build.xml
+++ b/com.amd.aparapi/build.xml
@@ -1,81 +1,38 @@
+
-
-
-
-
-
-
-
-
- OS Name: ${os.name}
- OS Version: ${os.version}
- OS Arch: ${os.arch}
+ OS Name: ${os.name}
+ OS Version: ${os.version}
+ OS Arch: ${os.arch}
-
-
-
+
+
+
-
+
+
+
+
+
+
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/com.amd.aparapi/src/java/com/amd/aparapi/Annotations.java b/com.amd.aparapi/src/java/com/amd/aparapi/Annotations.java
index 39368a17..3b2cba04 100644
--- a/com.amd.aparapi/src/java/com/amd/aparapi/Annotations.java
+++ b/com.amd.aparapi/src/java/com/amd/aparapi/Annotations.java
@@ -39,48 +39,54 @@ to national security controls as identified on the Commerce Control List (curren
/**
* A collection of annotations used at dev time to tag intent.
- *
- * We should be able to remove all of these before OpenSource release.
- *
+ *
+ * We should be able to remove all of these before OpenSource release.
+ *
* @author gfrost
*/
class Annotations{
/**
- * Use this annotation to tag stuff that needs Java Doc added.
- *
+ * Use this annotation to tag stuff that needs Java Doc added.
+ *
* @author gfrost
*/
- @interface DocMe {
+ @interface DocMe{
}
/**
* Use this annotation to tag fields that we think need to be removed (method/field/var).
- *
+ *
* @author gfrost
*/
- @interface RemoveMe {
+ @interface RemoveMe{
}
/**
- * Used to tag experimental features (methods/fields).
- *
- * Do not rely on anything tagged as experimental, it will probably be retracted/refactored.
- *
- * @author gfrost
+ * Used to tag experimental features (methods/fields).
+ *
+ * Do not rely on anything tagged as experimental, it will probably be retracted/refactored.
*
+ * @author gfrost
*/
- @interface Experimental {
+ @interface Experimental{
}
/**
- * Used to tag unused features (methods/fields).
- *
- * Do not rely on anything tagged as unused, it will probably be retracted/refactored.
- *
+ * Used to tag unused features (methods/fields).
+ *
+ * Do not rely on anything tagged as unused, it will probably be retracted/refactored.
+ *
* @author gfrost
+ */
+ @interface Unused{
+ }
+
+ /**
+ * Used to tag (methods/fields) which are used by JNI code.
*
+ * @author gfrost
*/
- @interface Unused {
+ @interface UsedByJNICode{
}
}
diff --git a/com.amd.aparapi/src/java/com/amd/aparapi/Aparapi.java b/com.amd.aparapi/src/java/com/amd/aparapi/Aparapi.java
new file mode 100644
index 00000000..eec297b6
--- /dev/null
+++ b/com.amd.aparapi/src/java/com/amd/aparapi/Aparapi.java
@@ -0,0 +1,358 @@
+package com.amd.aparapi;
+
+import java.lang.reflect.Field;
+import java.util.ArrayList;
+
+/**
+ * Created by gfrost on 3/14/14.
+ */
+public class Aparapi{
+ static public interface Lambda{
+ }
+
+ static public interface Mapper extends Lambda{
+ }
+
+ static public interface Reducer extends Lambda{
+ }
+
+ static public interface Terminal extends Lambda{
+ }
+
+ static public interface Int2IntMapper extends Mapper{
+ int map(int _in);
+ }
+
+ static public interface Int2BooleanMapper extends Mapper{
+ boolean map(int _in);
+ }
+
+ static public interface IntTerminal extends Terminal{
+ void accept(int t);
+ }
+
+ static public interface ObjectTerminal extends Terminal{
+ void accept(T t);
+ }
+
+ static public interface Object2IntMapper extends Mapper{
+ int map(T t);
+ }
+
+ static public interface Object2BooleanMapper extends Mapper{
+ boolean map(T t);
+ }
+
+ static public interface IntReducer extends Reducer{
+ int reduce(int lhs, int rhs);
+ }
+
+ static public interface BooleanReducer extends Reducer{
+ boolean reduce(int lhs, int rhs);
+ }
+
+ static public interface ObjectReducer extends Reducer{
+ T reduce(T lhs, T rhs);
+ }
+
+ static public class IntRange{
+ int from;
+ int to;
+
+ IntRange(int _from, int _to){
+ from = _from;
+ to = _to;
+ }
+
+ public ParallelIntRange parallel(){
+ return (new ParallelIntRange(this));
+ }
+
+ public void forEach(IntTerminal _it){
+
+ Device.seq().forEach(from, to, _it);
+
+ }
+
+ public MappedIntRange map(Int2IntMapper _im){
+ return (new MappedIntRange(this, _im));
+ }
+
+ public int reduce(IntReducer _ir){
+ int result = 0;
+ for (int i = from; i{
+ T[] arr;
+ int usableLength;
+
+ ArrayRange(T[] _arr, int _usableLength){
+
+ arr = _arr;
+ usableLength = _usableLength;
+ }
+
+ public ParallelArrayRange parallel(){
+ return (new ParallelArrayRange(this));
+ }
+
+ public void forEach(ObjectTerminal _oc){
+
+ for (int i = 0; i _im){
+ int sum = 0;
+
+ for (int i = 0; i map(Object2IntMapper _im){
+
+ return (new MappedArrayRange(this, _im));
+ }
+
+ public T[] filter(Object2BooleanMapper _im){
+ ArrayList list = new ArrayList();
+ if (arr.length>0){
+ arr[0].getClass();
+
+ for (T i : arr){
+ if (_im.map(i)){
+ list.add(i);
+ }
+ }
+ return (list.toArray((T[])java.lang.reflect.Array.newInstance((Class)arr.getClass().getComponentType(), 0)));
+ }else{
+ throw new IllegalStateException("array is empty!");
+ }
+
+ }
+ public int count(Object2BooleanMapper _im){
+ int counter = 0;
+ for (T t:arr){
+ if (_im.map(t)){
+ counter++;
+ }
+ }
+ return(counter);
+ }
+
+ public T select(ObjectReducer _or){
+
+ T best = null;
+
+ for (T o: arr){
+ if (best == null){
+ best = o;
+ }else{
+ best = _or.reduce(best,o);
+
+ }
+
+ }
+ return (best);
+ }
+
+ }
+
+ static public class MappedArrayRange{
+ ArrayRange arrayRange;
+ Object2IntMapper o2im;
+
+ MappedArrayRange(ArrayRange _arrayRange, Object2IntMapper _o2im){
+ arrayRange = _arrayRange;
+ o2im = _o2im;
+ }
+
+ public int reduce(IntReducer _ir){
+
+ int result = 0;
+ for (int i = 0; i{
+ ArrayRange range;
+
+ ParallelArrayRange(ArrayRange _range){
+ range = _range;
+ }
+
+ public void forEach(ObjectTerminal _ot){
+ Device.hsa().forEach(range.arr, range.usableLength, _ot);
+ }
+
+ public ParallelMappedArrayRange map(Object2IntMapper _im){
+ return (new ParallelMappedArrayRange(this, _im));
+ }
+
+ public T[] filter(Object2BooleanMapper _im){
+ throw new IllegalStateException("ParallelArrayRange.filter not implemented");
+
+ }
+
+
+ public T select(ObjectReducer _or){
+ throw new IllegalStateException("ParallelArrayRange.select not implemented");
+
+ }
+
+ public int count(Object2BooleanMapper _im){
+ throw new IllegalStateException("ParallelArrayRange.count not implemented");
+ }
+
+ }
+
+ static public class ParallelMappedArrayRange{
+ ParallelArrayRange parallelArrayRange;
+ Object2IntMapper o2im;
+
+ ParallelMappedArrayRange(ParallelArrayRange _parallelArrayRange, Object2IntMapper _o2im){
+ parallelArrayRange = _parallelArrayRange;
+ o2im = _o2im;
+ }
+
+ public int reduce(IntReducer _ir){
+ throw new IllegalStateException("ParallelMappedArrayRange.reduce not implemented");
+ }
+
+ public T select(BooleanReducer _ir){
+ throw new IllegalStateException("ParallelMappedArrayRange.select not implemented");
+ }
+ }
+
+ static public ArrayRange range(ArrayList _list){
+ T[] arr;
+ try{
+ Field f = ArrayList.class.getDeclaredField("elementData");
+ f.setAccessible(true);
+ arr = (T[])f.get(_list);
+ return ((ArrayRange)new ArrayRange(arr, _list.size()));
+ }catch (NoSuchFieldException e){
+ e.printStackTrace();
+ return (null);
+ }catch (IllegalAccessException e){
+ e.printStackTrace();
+ return (null);
+ }
+ }
+
+ static public ArrayRange range(T[] _arr){
+ return ((ArrayRange)new ArrayRange(_arr, _arr.length));
+ }
+
+ static public IntRange range(int _from, int _to){
+ return (new IntRange(_from, _to));
+ }
+
+ static public IntRange range(int _to){
+ return (new IntRange(0, _to));
+ }
+
+}
diff --git a/com.amd.aparapi/src/java/com/amd/aparapi/AparapiException.java b/com.amd.aparapi/src/java/com/amd/aparapi/AparapiException.java
index fe652679..c34a0851 100644
--- a/com.amd.aparapi/src/java/com/amd/aparapi/AparapiException.java
+++ b/com.amd.aparapi/src/java/com/amd/aparapi/AparapiException.java
@@ -39,25 +39,24 @@ to national security controls as identified on the Commerce Control List (curren
/**
* We use AparapiException class and subclasses to wrap other
- * Exception classes, mainly to allow differentiation between Aparapi specific issues at runtime.
- *
- * The class parser for example will throw a specific ClassParseException if any Aparapi unfriendly
+ * Exception classes, mainly to allow differentiation between Aparapi specific issues at runtime.
+ *
+ * The class parser for example will throw a specific ClassParseException if any Aparapi unfriendly
* constructs are found. This allows us to fail fast during classfile parsing.
- *
- * @see com.amd.aparapi.ClassParseException
- * @see com.amd.aparapi.CodeGenException
*
* @author gfrost
- *
+ * @see com.amd.aparapi.ClassParseException
+ * @see com.amd.aparapi.CodeGenException
*/
-@SuppressWarnings("serial") public class AparapiException extends Exception{
+@SuppressWarnings("serial")
+public class AparapiException extends Exception{
- AparapiException(String _msg) {
+ AparapiException(String _msg){
super(_msg);
}
- AparapiException(Throwable _t) {
+ AparapiException(Throwable _t){
super(_t);
}
diff --git a/com.amd.aparapi/src/java/com/amd/aparapi/AparapiJNI.java b/com.amd.aparapi/src/java/com/amd/aparapi/AparapiJNI.java
new file mode 100644
index 00000000..4b28d8b4
--- /dev/null
+++ b/com.amd.aparapi/src/java/com/amd/aparapi/AparapiJNI.java
@@ -0,0 +1,19 @@
+package com.amd.aparapi;
+
+import java.util.List;
+import java.util.logging.Logger;
+
+public class AparapiJNI{
+ private static Logger logger = Logger.getLogger(Config.getLoggerName());
+
+ static final AparapiJNI jni = new AparapiJNI();
+
+ public static AparapiJNI getAparapiJNI(){
+ return (jni);
+ }
+
+ native public byte[] getBytes(String className);
+
+ native public void dumpLoadedClassNames();
+
+}
diff --git a/com.amd.aparapi/src/java/com/amd/aparapi/BlockWriter.java b/com.amd.aparapi/src/java/com/amd/aparapi/BlockWriter.java
deleted file mode 100644
index e2336381..00000000
--- a/com.amd.aparapi/src/java/com/amd/aparapi/BlockWriter.java
+++ /dev/null
@@ -1,727 +0,0 @@
-/*
-Copyright (c) 2010-2011, Advanced Micro Devices, Inc.
-All rights reserved.
-
-Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
-following conditions are met:
-
-Redistributions of source code must retain the above copyright notice, this list of conditions and the following
-disclaimer.
-
-Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following
-disclaimer in the documentation and/or other materials provided with the distribution.
-
-Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products
-derived from this software without specific prior written permission.
-
-THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
-INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
-DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
-SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 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
-OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-If you use the software (in whole or in part), you shall adhere to all applicable U.S., European, and other export
-laws, including but not limited to the U.S. Export Administration Regulations ("EAR"), (15 C.F.R. Sections 730 through
-774), and E.U. Council Regulation (EC) No 1334/2000 of 22 June 2000. Further, pursuant to Section 740.6 of the EAR,
-you hereby certify that, except pursuant to a license granted by the United States Department of Commerce Bureau of
-Industry and Security or as otherwise permitted pursuant to a License Exception under the U.S. Export Administration
-Regulations ("EAR"), you will not (1) export, re-export or release to a national of a country in Country Groups D:1,
-E:1 or E:2 any restricted technology, software, or source code you receive hereunder, or (2) export to Country Groups
-D:1, E:1 or E:2 the direct product of such technology or software, if such foreign produced direct product is subject
-to national security controls as identified on the Commerce Control List (currently found in Supplement 1 to Part 774
-of EAR). For the most current Country Group listings, or for additional information about the EAR or your obligations
-under those regulations, please refer to the U.S. Bureau of Industry and Security's website at http://www.bis.doc.gov/.
-
-*/
-package com.amd.aparapi;
-
-import java.util.Stack;
-
-import com.amd.aparapi.BranchSet.CompoundLogicalExpressionNode;
-import com.amd.aparapi.BranchSet.LogicalExpressionNode;
-import com.amd.aparapi.BranchSet.SimpleLogicalExpressionNode;
-import com.amd.aparapi.ClassModel.ConstantPool.MethodEntry;
-import com.amd.aparapi.ClassModel.LocalVariableInfo;
-import com.amd.aparapi.InstructionSet.AccessArrayElement;
-import com.amd.aparapi.InstructionSet.AccessField;
-import com.amd.aparapi.InstructionSet.AccessInstanceField;
-import com.amd.aparapi.InstructionSet.AccessLocalVariable;
-import com.amd.aparapi.InstructionSet.AssignToArrayElement;
-import com.amd.aparapi.InstructionSet.AssignToField;
-import com.amd.aparapi.InstructionSet.AssignToInstanceField;
-import com.amd.aparapi.InstructionSet.AssignToLocalVariable;
-import com.amd.aparapi.InstructionSet.BinaryOperator;
-import com.amd.aparapi.InstructionSet.Branch;
-import com.amd.aparapi.InstructionSet.ByteCode;
-import com.amd.aparapi.InstructionSet.CastOperator;
-import com.amd.aparapi.InstructionSet.CloneInstruction;
-import com.amd.aparapi.InstructionSet.CompositeArbitraryScopeInstruction;
-import com.amd.aparapi.InstructionSet.CompositeEmptyLoopInstruction;
-import com.amd.aparapi.InstructionSet.CompositeForEclipseInstruction;
-import com.amd.aparapi.InstructionSet.CompositeForSunInstruction;
-import com.amd.aparapi.InstructionSet.CompositeIfElseInstruction;
-import com.amd.aparapi.InstructionSet.CompositeIfInstruction;
-import com.amd.aparapi.InstructionSet.CompositeInstruction;
-import com.amd.aparapi.InstructionSet.CompositeWhileInstruction;
-import com.amd.aparapi.InstructionSet.ConditionalBranch16;
-import com.amd.aparapi.InstructionSet.Constant;
-import com.amd.aparapi.InstructionSet.FieldArrayElementAssign;
-import com.amd.aparapi.InstructionSet.FieldArrayElementIncrement;
-import com.amd.aparapi.InstructionSet.I_ALOAD_0;
-import com.amd.aparapi.InstructionSet.I_ARRAYLENGTH;
-import com.amd.aparapi.InstructionSet.I_IFNONNULL;
-import com.amd.aparapi.InstructionSet.I_IFNULL;
-import com.amd.aparapi.InstructionSet.I_IINC;
-import com.amd.aparapi.InstructionSet.I_POP;
-import com.amd.aparapi.InstructionSet.If;
-import com.amd.aparapi.InstructionSet.IfUnary;
-import com.amd.aparapi.InstructionSet.IncrementInstruction;
-import com.amd.aparapi.InstructionSet.InlineAssignInstruction;
-import com.amd.aparapi.InstructionSet.MethodCall;
-import com.amd.aparapi.InstructionSet.MultiAssignInstruction;
-import com.amd.aparapi.InstructionSet.Return;
-import com.amd.aparapi.InstructionSet.UnaryOperator;
-import com.amd.aparapi.InstructionSet.VirtualMethodCall;
-
-/**
- * Base abstract class for converting Aparapi IR to text.
- *
- *
- * @author gfrost
- *
- */
-
-abstract class BlockWriter{
-
- final static String arrayLengthMangleSuffix = "__javaArrayLength";
-
- abstract void write(String _string);
-
- protected void writeln(String _string) {
- write(_string);
- newLine();
- }
-
- private int indent = 0;
-
- protected void in() {
- indent++;
- }
-
- protected void out() {
- indent--;
- }
-
- protected void newLine() {
- write("\n");
- for (int i = 0; i < indent; i++) {
- write(" ");
- }
- }
-
- protected void writeConditionalBranch16(ConditionalBranch16 _branch16, boolean _invert) throws CodeGenException {
-
- if (_branch16 instanceof If) {
- If iff = (If) _branch16;
-
- writeInstruction(iff.getLhs());
- write(_branch16.getOperator().getText(_invert));
- writeInstruction(iff.getRhs());
- } else if (_branch16 instanceof I_IFNULL) {
- I_IFNULL iff = (I_IFNULL) _branch16;
- writeInstruction(iff.getFirstChild());
-
- if (_invert) {
- write(" != NULL");
- } else {
- write(" == NULL");
- }
-
- } else if (_branch16 instanceof I_IFNONNULL) {
- I_IFNONNULL iff = (I_IFNONNULL) _branch16;
- writeInstruction(iff.getFirstChild());
-
- if (_invert) {
- write(" == NULL");
- } else {
- write(" != NULL");
- }
- } else if (_branch16 instanceof IfUnary) {
- IfUnary branch16 = (IfUnary) _branch16;
- Instruction comparison = branch16.getUnary();
- ByteCode comparisonByteCode = comparison.getByteCode();
- String comparisonOperator = _branch16.getOperator().getText(_invert);
-
- switch (comparisonByteCode) {
- case FCMPG:
- case DCMPG:
- case FCMPL:
- case DCMPL:
- if (Config.verboseComparitor)
- write("/* bytecode=" + comparisonByteCode.getName() + " invert=" + _invert + "*/");
- writeInstruction(comparison.getFirstChild());
- write(comparisonOperator);
- writeInstruction(comparison.getLastChild());
- break;
- default:
- if (Config.verboseComparitor)
- write("/* default bytecode=" + comparisonByteCode.getName() + " invert=" + _invert + "*/");
- writeInstruction(comparison);
- write(comparisonOperator);
- write("0");
- }
-
- }
- }
-
- protected void writeComposite(CompositeInstruction instruction) throws CodeGenException {
- if (instruction instanceof CompositeArbitraryScopeInstruction) {
- newLine();
-
- writeBlock(instruction.getFirstChild(), null);
- } else if (instruction instanceof CompositeIfInstruction) {
- newLine();
- write("if (");
- Instruction blockStart = writeConditional(((CompositeInstruction) instruction).getBranchSet());
-
- write(")");
- writeBlock(blockStart, null);
- } else if (instruction instanceof CompositeIfElseInstruction) {
- newLine();
- write("if (");
- Instruction blockStart = writeConditional(((CompositeInstruction) instruction).getBranchSet());
- write(")");
- Instruction elseGoto = blockStart;
- while (!(elseGoto.isBranch() && elseGoto.asBranch().isUnconditional())) {
- elseGoto = elseGoto.getNextExpr();
- }
- writeBlock(blockStart, elseGoto);
- write(" else ");
- writeBlock(elseGoto.getNextExpr(), null);
- } else if (instruction instanceof CompositeForSunInstruction) {
- newLine();
- write("for (");
- Instruction topBranch = instruction.getFirstChild();
- if (topBranch instanceof AssignToLocalVariable) {
- writeInstruction(topBranch);
- topBranch = topBranch.getNextExpr();
- }
- write("; ");
- BranchSet branchSet = ((CompositeInstruction) instruction).getBranchSet();
- Instruction blockStart = writeConditional(branchSet);
-
- Instruction lastGoto = instruction.getLastChild();
-
- if (branchSet.getFallThrough() == lastGoto) {
- // empty body no delta!
- write(";){}");
- } else {
- Instruction delta = lastGoto.getPrevExpr();
- write("; ");
- if (!(delta instanceof CompositeInstruction)) {
- writeInstruction(delta);
- write(")");
- writeBlock(blockStart, delta);
- } else {
- write("){");
- in();
- writeSequence(blockStart, delta);
-
- newLine();
- writeSequence(delta, delta.getNextExpr());
- out();
- newLine();
- write("}");
-
- }
- }
-
- } else if (instruction instanceof CompositeWhileInstruction) {
- newLine();
- write("while (");
- BranchSet branchSet = ((CompositeInstruction) instruction).getBranchSet();
- Instruction blockStart = writeConditional(branchSet);
- write(")");
- Instruction lastGoto = instruction.getLastChild();
- writeBlock(blockStart, lastGoto);
-
- } else if (instruction instanceof CompositeEmptyLoopInstruction) {
- newLine();
- write("for (");
- Instruction topBranch = instruction.getFirstChild();
- if (topBranch instanceof AssignToLocalVariable) {
- writeInstruction(topBranch);
- topBranch = topBranch.getNextExpr();
- }
- write("; ");
- writeConditional(((CompositeInstruction) instruction).getBranchSet());
- write(";){}");
-
- } else if (instruction instanceof CompositeForEclipseInstruction) {
- newLine();
- write("for (");
- Instruction topGoto = instruction.getFirstChild();
- if (topGoto instanceof AssignToLocalVariable) {
- writeInstruction(topGoto);
- topGoto = topGoto.getNextExpr();
- }
- write("; ");
- Instruction last = instruction.getLastChild();
- while (last.getPrevExpr().isBranch()) {
- last = last.getPrevExpr();
- }
- writeConditional(((CompositeInstruction) instruction).getBranchSet(), true);
- write("; ");
- Instruction delta = last.getPrevExpr();
- if (!(delta instanceof CompositeInstruction)) {
- writeInstruction(delta);
- write(")");
- writeBlock(topGoto.getNextExpr(), delta);
- } else {
- write("){");
- in();
- writeSequence(topGoto.getNextExpr(), delta);
-
- newLine();
- writeSequence(delta, delta.getNextExpr());
- out();
- newLine();
- write("}");
-
- }
- }
- }
-
- protected void writeSequence(Instruction _first, Instruction _last) throws CodeGenException {
-
- for (Instruction instruction = _first; instruction != _last; instruction = instruction.getNextExpr()) {
- if (instruction instanceof CompositeInstruction) {
- writeComposite((CompositeInstruction) instruction);
- } else if (!instruction.getByteCode().equals(ByteCode.NONE)) {
- newLine();
- writeInstruction(instruction);
- write(";");
-
- }
- }
-
- }
-
- protected void writeBlock(Instruction _first, Instruction _last) throws CodeGenException {
- write("{");
- in();
- writeSequence(_first, _last);
- out();
- newLine();
-
- write("}");
- }
-
- protected Instruction writeConditional(BranchSet _branchSet) throws CodeGenException {
- return (writeConditional(_branchSet, false));
- }
-
- protected Instruction writeConditional(BranchSet _branchSet, boolean _invert) throws CodeGenException {
-
- LogicalExpressionNode logicalExpression = _branchSet.getLogicalExpression();
- if (!_invert) {
- logicalExpression.invert();
- }
- write(logicalExpression);
- return (_branchSet.getLast().getNextExpr());
- }
-
- protected void write(LogicalExpressionNode _node) throws CodeGenException {
- if (_node instanceof SimpleLogicalExpressionNode) {
- SimpleLogicalExpressionNode sn = (SimpleLogicalExpressionNode) _node;
-
- writeConditionalBranch16((ConditionalBranch16) sn.getBranch(), sn.isInvert());
- } else {
- CompoundLogicalExpressionNode ln = (CompoundLogicalExpressionNode) _node;
- boolean needParenthesis = false;
- CompoundLogicalExpressionNode parent = (CompoundLogicalExpressionNode) ln.getParent();
- if (parent != null) {
- if (!ln.isAnd() && parent.isAnd()) {
- needParenthesis = true;
- }
- }
- if (needParenthesis) {
-
- write("(");
- }
- write(ln.getLhs());
- write(ln.isAnd() ? " && " : " || ");
- write(ln.getRhs());
- if (needParenthesis) {
-
- write(")");
- }
- }
- }
-
- protected String convertType(String _typeDesc, boolean useClassModel) {
- return (_typeDesc);
- }
-
- protected String convertCast(String _cast) {
- // Strip parens off cast
- //System.out.println("cast = " + _cast);
- String raw = convertType(_cast.substring(1, _cast.length() - 1), false);
- return ("(" + raw + ")");
- }
-
- void writeInstruction(Instruction _instruction) throws CodeGenException {
- if (_instruction instanceof CompositeIfElseInstruction) {
- write("(");
- Instruction lhs = writeConditional(((CompositeInstruction) _instruction).getBranchSet());
- write(")?");
- writeInstruction(lhs);
- write(":");
- writeInstruction(lhs.getNextExpr().getNextExpr());
- } else if (_instruction instanceof CompositeInstruction) {
- writeComposite((CompositeInstruction) _instruction);
-
- } else if (_instruction instanceof AssignToLocalVariable) {
- AssignToLocalVariable assignToLocalVariable = (AssignToLocalVariable) _instruction;
-
- LocalVariableInfo localVariableInfo = assignToLocalVariable.getLocalVariableInfo();
- if (assignToLocalVariable.isDeclaration()) {
- String descriptor = localVariableInfo.getVariableDescriptor();
- // Arrays always map to __global arrays
- if (descriptor.startsWith("[")) {
- write(" __global ");
- }
- write(convertType(descriptor, true));
- }
- if (localVariableInfo == null) {
- throw new CodeGenException("outOfScope" + _instruction.getThisPC() + " = ");
- } else {
- write(localVariableInfo.getVariableName() + " = ");
- }
-
- for (Instruction operand = _instruction.getFirstChild(); operand != null; operand = operand.getNextExpr()) {
- writeInstruction(operand);
- }
-
- } else if (_instruction instanceof AssignToArrayElement) {
- AssignToArrayElement arrayAssignmentInstruction = (AssignToArrayElement) _instruction;
- writeInstruction(arrayAssignmentInstruction.getArrayRef());
- write("[");
- writeInstruction(arrayAssignmentInstruction.getArrayIndex());
- write("]");
- write(" ");
- write(" = ");
- writeInstruction(arrayAssignmentInstruction.getValue());
- } else if (_instruction instanceof AccessArrayElement) {
- AccessArrayElement arrayLoadInstruction = (AccessArrayElement) _instruction;
- writeInstruction(arrayLoadInstruction.getArrayRef());
- write("[");
- writeInstruction(arrayLoadInstruction.getArrayIndex());
- write("]");
- } else if (_instruction instanceof AccessField) {
- AccessField accessField = (AccessField) _instruction;
- if (accessField instanceof AccessInstanceField) {
- Instruction accessInstanceField = ((AccessInstanceField) accessField).getInstance();
- if (accessInstanceField instanceof CloneInstruction) {
- accessInstanceField = ((CloneInstruction) accessInstanceField).getReal();
- }
- if (!(accessInstanceField instanceof I_ALOAD_0)) {
- writeInstruction(accessInstanceField);
- write(".");
- } else {
- writeThisRef();
- }
- }
- write(accessField.getConstantPoolFieldEntry().getNameAndTypeEntry().getNameUTF8Entry().getUTF8());
-
- } else if (_instruction instanceof I_ARRAYLENGTH) {
- AccessInstanceField child = (AccessInstanceField) _instruction.getFirstChild();
- String arrayName = child.getConstantPoolFieldEntry().getNameAndTypeEntry().getNameUTF8Entry().getUTF8();
- write("this->" + arrayName + arrayLengthMangleSuffix);
- } else if (_instruction instanceof AssignToField) {
- AssignToField assignedField = (AssignToField) _instruction;
-
- if (assignedField instanceof AssignToInstanceField) {
- Instruction accessInstanceField = ((AssignToInstanceField) assignedField).getInstance().getReal();
-
- if (!(accessInstanceField instanceof I_ALOAD_0)) {
- writeInstruction(accessInstanceField);
- write(".");
- } else {
- writeThisRef();
- }
- }
- write(assignedField.getConstantPoolFieldEntry().getNameAndTypeEntry().getNameUTF8Entry().getUTF8());
- write("=");
- writeInstruction(assignedField.getValueToAssign());
- } else if (_instruction instanceof Constant>) {
- Constant> constantInstruction = (Constant>) _instruction;
- Object value = constantInstruction.getValue();
-
- if (value instanceof Float) {
-
- Float f = (Float) value;
- if (f.isNaN()) {
- write("NAN");
- } else if (f.isInfinite()) {
- if (f < 0) {
- write("-");
- }
- write("INFINITY");
- } else {
- write(value.toString());
- write("f");
- }
- } else if (value instanceof Double) {
-
- Double d = (Double) value;
- if (d.isNaN()) {
- write("NAN");
- } else if (d.isInfinite()) {
- if (d < 0) {
- write("-");
- }
- write("INFINITY");
- } else {
- write(value.toString());
- }
- } else {
- write(value.toString());
- if (value instanceof Long) {
- write("L");
- }
- }
-
- } else if (_instruction instanceof AccessLocalVariable) {
- AccessLocalVariable localVariableLoadInstruction = (AccessLocalVariable) _instruction;
- LocalVariableInfo localVariable = localVariableLoadInstruction.getLocalVariableInfo();
- write(localVariable.getVariableName());
- } else if (_instruction instanceof I_IINC) {
- I_IINC location = (I_IINC) _instruction;
- LocalVariableInfo localVariable = location.getLocalVariableInfo();
- int adjust = location.getAdjust();
-
- write(localVariable.getVariableName());
- if (adjust == 1) {
- write("++");
- } else if (adjust == -1) {
- write("--");
- } else if (adjust > 1) {
- write("+=" + adjust);
- } else if (adjust < -1) {
- write("-=" + (-adjust));
- }
- } else if (_instruction instanceof BinaryOperator) {
- BinaryOperator binaryInstruction = (BinaryOperator) _instruction;
- Instruction parent = binaryInstruction.getParentExpr();
- boolean needsParenthesis = true;
-
- if (parent instanceof AssignToLocalVariable) {
- needsParenthesis = false;
- } else if (parent instanceof AssignToField) {
- needsParenthesis = false;
- } else if (parent instanceof AssignToArrayElement) {
- needsParenthesis = false;
- } else {
- /**
- if (parent instanceof BinaryOperator) {
- BinaryOperator parentBinaryOperator = (BinaryOperator) parent;
- if (parentBinaryOperator.getOperator().ordinal() > binaryInstruction.getOperator().ordinal()) {
- needsParenthesis = false;
- }
- }
- **/
- }
-
- if (needsParenthesis) {
- write("(");
- }
-
- writeInstruction(binaryInstruction.getLhs());
-
- write(" " + binaryInstruction.getOperator().getText() + " ");
- writeInstruction(binaryInstruction.getRhs());
-
- if (needsParenthesis) {
- write(")");
- }
-
- } else if (_instruction instanceof CastOperator) {
- CastOperator castInstruction = (CastOperator) _instruction;
- // write("(");
- write(convertCast(castInstruction.getOperator().getText()));
-
- writeInstruction(castInstruction.getUnary());
- // write(")");
- } else if (_instruction instanceof UnaryOperator) {
- UnaryOperator unaryInstruction = (UnaryOperator) _instruction;
- // write("(");
- write(unaryInstruction.getOperator().getText());
-
- writeInstruction(unaryInstruction.getUnary());
- // write(")");
- } else if (_instruction instanceof Return) {
-
- Return ret = (Return) _instruction;
- write("return");
- if (ret.getStackConsumeCount() > 0) {
- write("(");
- writeInstruction(ret.getFirstChild());
- write(")");
- }
-
- } else if (_instruction instanceof MethodCall) {
- MethodCall methodCall = (MethodCall) _instruction;
-
- MethodEntry methodEntry = methodCall.getConstantPoolMethodEntry();
-
- writeMethod(methodCall, methodEntry);
- } else if (_instruction.getByteCode().equals(ByteCode.CLONE)) {
- CloneInstruction cloneInstruction = (CloneInstruction) _instruction;
- writeInstruction(cloneInstruction.getReal());
- } else if (_instruction.getByteCode().equals(ByteCode.INCREMENT)) {
- IncrementInstruction incrementInstruction = (IncrementInstruction) _instruction;
-
- if (incrementInstruction.isPre()) {
- if (incrementInstruction.isInc()) {
- write("++");
- } else {
- write("--");
- }
- }
-
- writeInstruction(incrementInstruction.getFieldOrVariableReference());
- if (!incrementInstruction.isPre()) {
- if (incrementInstruction.isInc()) {
- write("++");
- } else {
- write("--");
- }
- }
- } else if (_instruction.getByteCode().equals(ByteCode.MULTI_ASSIGN)) {
- MultiAssignInstruction multiAssignInstruction = (MultiAssignInstruction) _instruction;
- AssignToLocalVariable from = (AssignToLocalVariable) multiAssignInstruction.getFrom();
- AssignToLocalVariable last = (AssignToLocalVariable) multiAssignInstruction.getTo();
- Instruction common = multiAssignInstruction.getCommon();
- Stack stack = new Stack();
-
- while (from != last) {
- stack.push(from);
- from = (AssignToLocalVariable) ((Instruction) from).getNextExpr();
- }
-
- for (AssignToLocalVariable alv = stack.pop(); alv != null; alv = stack.size() > 0 ? stack.pop() : null) {
-
- LocalVariableInfo localVariableInfo = alv.getLocalVariableInfo();
- if (alv.isDeclaration()) {
- write(convertType(localVariableInfo.getVariableDescriptor(), true));
- }
- if (localVariableInfo == null) {
- throw new CodeGenException("outOfScope" + _instruction.getThisPC() + " = ");
- } else {
- write(localVariableInfo.getVariableName() + " = ");
- }
-
- }
- writeInstruction(common);
- } else if (_instruction.getByteCode().equals(ByteCode.INLINE_ASSIGN)) {
- InlineAssignInstruction inlineAssignInstruction = (InlineAssignInstruction) _instruction;
- AssignToLocalVariable assignToLocalVariable = inlineAssignInstruction.getAssignToLocalVariable();
-
- LocalVariableInfo localVariableInfo = assignToLocalVariable.getLocalVariableInfo();
- if (assignToLocalVariable.isDeclaration()) {
- // this is bad! we need a general way to hoist up a required declaration
- throw new CodeGenException("/* we can't declare this " + convertType(localVariableInfo.getVariableDescriptor(), true)
- + " here */");
- }
- write(localVariableInfo.getVariableName());
- write("=");
- writeInstruction(inlineAssignInstruction.getRhs());
- } else if (_instruction.getByteCode().equals(ByteCode.FIELD_ARRAY_ELEMENT_ASSIGN)) {
- FieldArrayElementAssign inlineAssignInstruction = (FieldArrayElementAssign) _instruction;
- AssignToArrayElement arrayAssignmentInstruction = inlineAssignInstruction.getAssignToArrayElement();
-
- writeInstruction(arrayAssignmentInstruction.getArrayRef());
- write("[");
- writeInstruction(arrayAssignmentInstruction.getArrayIndex());
- write("]");
- write(" ");
- write(" = ");
-
- writeInstruction(inlineAssignInstruction.getRhs());
- } else if (_instruction.getByteCode().equals(ByteCode.FIELD_ARRAY_ELEMENT_INCREMENT)) {
-
- FieldArrayElementIncrement fieldArrayElementIncrement = (FieldArrayElementIncrement) _instruction;
- AssignToArrayElement arrayAssignmentInstruction = fieldArrayElementIncrement.getAssignToArrayElement();
- if (fieldArrayElementIncrement.isPre()) {
- if (fieldArrayElementIncrement.isInc()) {
- write("++");
- } else {
- write("--");
- }
- }
- writeInstruction(arrayAssignmentInstruction.getArrayRef());
-
- write("[");
- writeInstruction(arrayAssignmentInstruction.getArrayIndex());
- write("]");
- if (!fieldArrayElementIncrement.isPre()) {
- if (fieldArrayElementIncrement.isInc()) {
- write("++");
- } else {
- write("--");
- }
- }
-
- } else if (_instruction.getByteCode().equals(ByteCode.NONE)) {
- // we are done
- } else if (_instruction instanceof Branch) {
- throw new CodeGenException(String.format("%s -> %04d", _instruction.getByteCode().toString().toLowerCase(),
- ((Branch) _instruction).getTarget().getThisPC()));
- } else if (_instruction instanceof I_POP) {
- //POP discarded void call return?
- writeInstruction(_instruction.getFirstChild());
- } else {
- throw new CodeGenException(String.format("%s", _instruction.getByteCode().toString().toLowerCase()));
- }
-
- }
-
- protected void writeMethod(MethodCall _methodCall, MethodEntry _methodEntry) throws CodeGenException {
-
- if (_methodCall instanceof VirtualMethodCall) {
- Instruction instanceInstruction = ((VirtualMethodCall) _methodCall).getInstanceReference();
- if (!(instanceInstruction instanceof I_ALOAD_0)) {
- writeInstruction(instanceInstruction);
- write(".");
- } else {
- writeThisRef();
- }
- }
- int argc = _methodEntry.getStackConsumeCount();
- write(_methodEntry.getNameAndTypeEntry().getNameUTF8Entry().getUTF8());
- write("(");
-
- for (int arg = 0; arg < argc; arg++) {
- if (arg != 0) {
- write(", ");
- }
- writeInstruction(_methodCall.getArg(arg));
- }
- write(")");
-
- }
-
- protected void writeThisRef() {
- write("this.");
- }
-
- protected void writeMethodBody(MethodModel _methodModel) throws CodeGenException {
- writeBlock(_methodModel.getExprHead(), null);
- }
-
- abstract void write(Entrypoint entryPoint) throws CodeGenException;
-
-}
diff --git a/com.amd.aparapi/src/java/com/amd/aparapi/BranchSet.java b/com.amd.aparapi/src/java/com/amd/aparapi/BranchSet.java
index 5d807c71..356de735 100644
--- a/com.amd.aparapi/src/java/com/amd/aparapi/BranchSet.java
+++ b/com.amd.aparapi/src/java/com/amd/aparapi/BranchSet.java
@@ -37,82 +37,81 @@ to national security controls as identified on the Commerce Control List (curren
*/
package com.amd.aparapi;
+import com.amd.aparapi.InstructionSet.Branch;
+import com.amd.aparapi.InstructionSet.ConditionalBranch;
+
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
-import com.amd.aparapi.InstructionSet.Branch;
-import com.amd.aparapi.InstructionSet.ConditionalBranch;
-
/**
* Deals with the issue of recognizing that a sequence of bytecode branch instructions actually represent a single if/while with a logical expression.
- *
*
- * A logical expressions such as
+ *
+ * OREF logical expressions such as
*
- if (i>= 0 && i%2 == 0 && i<100){}
+ * if (i>= 0 && i%2 == 0 && i<100){}
*
- * gets translated into a sequence of bytecode level branches and targets. Which might look like the following.
+ * gets translated into a sequence of bytecode level branches and targets. Which might look like the following.
*
- a: if ? e +
- b: if ? d |+
- c: if ? e ||+
- d: if ? out |v|+
- e: ... v v|
- ... |
- out: _instruction v
+ * a: if ? e +
+ * b: if ? d |+
+ * c: if ? e ||+
+ * d: if ? out |v|+
+ * e: ... v v|
+ * ... |
+ * out: _instruction v
*
- * We need an algorithm for recognizing the underlying logical expression.
+ * We need an algorithm for recognizing the underlying logical expression.
*
* Essentially, given a set of branches, get the longest sequential sequence including the input set which target each other or _target.
- *
+ *
* Branches can legally branch to another in the valid set, or to the fall through of the last in the valid set or to _target
- *
- * So an
if(COND){IF_INSTRUCTIONS}else{ELSE_INSTUCTIONS}... will be
-
- branch[?? branch]*, instructions*,goto,instruction*,target
-
+ *
+ * So an
if(COND){IF_INSTRUCTIONS}else{ELSE_INSTUCTIONS}... will be
+ *
+ * branch[?? branch]*, instructions*,goto,instruction*,target
+ *
* and if(COND){IF_INSTRUCTIONS}... will be :-
-
- branch[?? branch]*,instruction*,target
-
- * The psuedo code code the algorithm looks like this:
-
- int n=0;
- while (exp.length >1){
- if (exp[n].target == exp[n+1].target){ #rule 1
- replace exp[n] and exp[n+1] with a single expression representing 'exp[n] || exp[n+1]'
- n=0;
- }else if (exp[n].target == exp[n+1].next){ #rule 2
- replace exp[n] and exp[n+1] with a single expression representing '!(exp[n]) && exp[n+1]
- n=0;
- }else{ #rule 3
- n++;
- }
- }
-
- result = !exp[0];
-
- * @author gfrost
+ *
+ * branch[?? branch]*,instruction*,target
+ *
+ * The psuedo code code the algorithm looks like this:
+ *
+ * int n=0;
+ * while (exp.length >1){
+ * if (exp[n].target == exp[n+1].target){ #rule 1
+ * replace exp[n] and exp[n+1] with a single expression representing 'exp[n] || exp[n+1]'
+ * n=0;
+ * }else if (exp[n].target == exp[n+1].next){ #rule 2
+ * replace exp[n] and exp[n+1] with a single expression representing '!(exp[n]) && exp[n+1]
+ * n=0;
+ * }else{ #rule 3
+ * n++;
+ * }
+ * }
+ *
+ * result = !exp[0];
+ *
+ *
+ * @author gfrost
*/
class BranchSet{
/**
- * Base abstract class used to hold information used to construct node tree for logical expressions.
- *
+ * Base abstract class used to hold information used to construct node tree for logical expressions.
+ *
+ * @author gfrost
* @see SimpleLogicalExpressionNode
* @see CompoundLogicalExpressionNode
- *
- * @author gfrost
- *
*/
- static abstract class LogicalExpressionNode{
+ static abstract class LogicalExpressionNode{
private LogicalExpressionNode next = null;
private LogicalExpressionNode parent = null;
- void setParent(LogicalExpressionNode _parent) {
+ void setParent(LogicalExpressionNode _parent){
parent = _parent;
}
@@ -120,126 +119,132 @@ void setParent(LogicalExpressionNode _parent) {
abstract int getFallThrough();
- abstract void invert();
+ abstract T invert();
- LogicalExpressionNode getRoot() {
- if (parent != null) {
+ LogicalExpressionNode getRoot(){
+ if (parent != null){
return (parent);
- } else {
+ }else{
return (this);
}
}
- LogicalExpressionNode getNext() {
- return (next == null ? next : next.getRoot());
+ LogicalExpressionNode getNext(){
+ return (next == null?next:next.getRoot());
}
- void setNext(LogicalExpressionNode _next) {
- next = _next == null ? _next : _next.getRoot();
+ void setNext(LogicalExpressionNode _next){
+ next = _next == null?_next:_next.getRoot();
}
- LogicalExpressionNode getParent() {
+ LogicalExpressionNode getParent(){
return (parent);
}
}
/**
- * A node in the expression tree representing a simple logical expression.
- *
+ * OREF node in the expression tree representing a simple logical expression.
+ *
* For example (i<3) in the following would appear as a SimpleLogicalExpressionNode
*
* if (i<3){}
*
- *
- * @author gfrost
*
+ * @author gfrost
*/
- static class SimpleLogicalExpressionNode extends LogicalExpressionNode{
+ static class SimpleLogicalExpressionNode extends LogicalExpressionNode{
private ConditionalBranch branch;
+ private boolean inverted;
- protected boolean invert = false;
-
- SimpleLogicalExpressionNode(ConditionalBranch _branch) {
+ SimpleLogicalExpressionNode(ConditionalBranch _branch){
branch = _branch;
}
- @Override int getTarget() {
+ @Override
+ int getTarget(){
return (getBranch().getTarget().getThisPC());
}
- @Override void invert() {
- invert = !invert;
+ @Override
+ int getFallThrough(){
+ return (getBranch().getNextPC().getThisPC());
}
- @Override int getFallThrough() {
- return (getBranch().getNextPC().getThisPC());
+ ConditionalBranch getBranch(){
+ return branch;
}
- boolean isInvert() {
- return (invert);
+ @Override
+ SimpleLogicalExpressionNode invert(){
+ inverted = !inverted;
+ return (this);
}
- ConditionalBranch getBranch() {
- return branch;
+ boolean isInverted(){
+ return (inverted);
}
}
/**
- * A node in the expression tree representing a simple logical expression.
- *
+ * OREF node in the expression tree representing a simple logical expression.
+ *
* For example (i<3 || i>10) in the following would appear as a CompoundLogicalExpressionNode
*
* if (i<3 || i>10){}
*
- *
- * @author gfrost
*
+ * @author gfrost
*/
- static class CompoundLogicalExpressionNode extends LogicalExpressionNode{
+ static class CompoundLogicalExpressionNode extends LogicalExpressionNode{
private LogicalExpressionNode lhs;
private LogicalExpressionNode rhs;
private boolean and;
- CompoundLogicalExpressionNode(boolean _and, LogicalExpressionNode _lhs, LogicalExpressionNode _rhs) {
+ CompoundLogicalExpressionNode(boolean _and, LogicalExpressionNode _lhs, LogicalExpressionNode _rhs){
lhs = _lhs;
and = _and;
rhs = _rhs;
setNext(_rhs.getNext());
- if (and) {
- lhs.invert();
- // rhs.invert();
- }
+
rhs.setParent(this);
lhs.setParent(this);
}
- @Override int getTarget() {
+ @Override
+ int getTarget(){
return (rhs.getTarget());
}
- @Override void invert() {
+ @Override
+ CompoundLogicalExpressionNode invert(){
and = !and;
lhs.invert();
rhs.invert();
+ return (this);
}
- boolean isAnd() {
+ boolean isAnd(){
return (and);
}
- @Override int getFallThrough() {
+ boolean isOr(){
+ return (!and);
+ }
+
+ @Override
+ int getFallThrough(){
return (rhs.getFallThrough());
}
- LogicalExpressionNode getLhs() {
+ LogicalExpressionNode getLhs(){
return lhs;
}
- LogicalExpressionNode getRhs() {
+ LogicalExpressionNode getRhs(){
return rhs;
}
@@ -259,75 +264,75 @@ LogicalExpressionNode getRhs() {
/**
* We construct a branch set with the 'last' branch. It is assumed that all nodes prior to _branch are folded.
- *
+ *
* This will walk backwards until it finds a non-branch or until it finds a branch that does not below to this set.
- *
+ *
* @param _branch
*/
- BranchSet(Branch _branch) {
+ BranchSet(Branch _branch){
target = _branch.getTarget();
last = _branch;
Set expandedSet = new LinkedHashSet();
Instruction fallThroughRoot = last.getNextExpr();
- fallThrough = fallThroughRoot == null ? last.getNextPC() : fallThroughRoot.getStartInstruction();
+ fallThrough = fallThroughRoot == null?last.getNextPC():fallThroughRoot.getStartInstruction();
first = last;
- while (first.getPrevExpr() != null && first.getPrevExpr().isBranch() && first.getPrevExpr().asBranch().isConditional()) {
+ while (first.getPrevExpr() != null && first.getPrevExpr().isBranch() && first.getPrevExpr().asBranch().isConditional()){
Instruction prevBranchTarget = first.getPrevExpr().asBranch().getTarget();
Instruction prevBranchTargetRoot = prevBranchTarget.getRootExpr();
- if (prevBranchTarget == target || prevBranchTarget == fallThrough || expandedSet.contains(prevBranchTargetRoot)) {
+ if (prevBranchTarget == target || prevBranchTarget == fallThrough || expandedSet.contains(prevBranchTargetRoot)){
expandedSet.add(first);
first = first.getPrevExpr().asBranch();
- } else {
+ }else{
break;
}
}
- for (Instruction i = first; i != fallThroughRoot; i = i.getNextExpr()) {
- set.add((ConditionalBranch) i.asBranch());
- ((ConditionalBranch) i.asBranch()).setBranchSet(this);
+ for (Instruction i = first; i != fallThroughRoot; i = i.getNextExpr()){
+ set.add((ConditionalBranch)i.asBranch());
+ ((ConditionalBranch)i.asBranch()).setBranchSet(this);
}
// ConditionalBranch16 branches[] = set.toArray(new ConditionalBranch16[0]);
LogicalExpressionNode end = null;
- for (ConditionalBranch cb : set) {
+ for (ConditionalBranch cb : set){
SimpleLogicalExpressionNode sn = new SimpleLogicalExpressionNode(cb);
- if (logicalExpressionNode == null) {
+ if (logicalExpressionNode == null){
logicalExpressionNode = sn;
- } else {
+ }else{
end.setNext(sn);
}
end = sn;
}
int count = 0;
- while (logicalExpressionNode.next != null) {
- if (++count > 20) {
+ while (logicalExpressionNode.next != null){
+ if (++count>20){
throw new IllegalStateException("Sanity check, we seem to have >20 iterations collapsing logical expression");
}
LogicalExpressionNode n = logicalExpressionNode;
LogicalExpressionNode prev = null;
int i = 0;
- while (n != null && n.getNext() != null) {
- if (n.getTarget() == n.getNext().getTarget() || n.getTarget() == n.getNext().getFallThrough()) {
+ while (n != null && n.getNext() != null){
+ if (n.getTarget() == n.getNext().getTarget() || n.getTarget() == n.getNext().getFallThrough()){
LogicalExpressionNode newNode = null;
- if (n.getTarget() == n.getNext().getTarget()) {
+ if (n.getTarget() == n.getNext().getTarget()){
// lhs(n) and rhs(n.next) are branching to the same location so we replace (lhs ?? rhs) with (lhs || rhs)
// System.out.println("exp["+i+"] exp["+(i+1)+"] replaced by (exp["+i+"] || exp["+(i+1)+"])");
newNode = new CompoundLogicalExpressionNode(false, n, n.getNext());
- } else if (n.getTarget() == n.getNext().getFallThrough()) {
+ }else if (n.getTarget() == n.getNext().getFallThrough()){
// lhs(n) target and rhs(n.next) fallthrough are the same so we replace (lhs ?? rhs) with !(lhs && rhs)
// System.out.println("exp["+i+"] exp["+(i+1)+"] replaced by (!exp["+i+"] && exp["+(i+1)+"])");
- newNode = new CompoundLogicalExpressionNode(true, n, n.getNext());
+ newNode = new CompoundLogicalExpressionNode(true, n.invert(), n.getNext());
}
- if (n == logicalExpressionNode) {
+ if (n == logicalExpressionNode){
logicalExpressionNode = newNode;
}
- if (prev != null) {
+ if (prev != null){
prev.setNext(newNode);
}
break;
- } else {
+ }else{
prev = n;
n = n.getNext();
i++;
@@ -338,34 +343,34 @@ LogicalExpressionNode getRhs() {
}
- List getBranches() {
+ List getBranches(){
return (set);
}
- Branch getFirst() {
+ Branch getFirst(){
return (first);
}
- Branch getLast() {
+ Branch getLast(){
return (last);
}
- void unhook() {
- for (Branch b : set) {
+ void unhook(){
+ for (Branch b : set){
b.unhook();
}
}
- Instruction getTarget() {
+ Instruction getTarget(){
return (target);
}
- Instruction getFallThrough() {
+ Instruction getFallThrough(){
return (fallThrough);
}
- LogicalExpressionNode getLogicalExpression() {
+ LogicalExpressionNode getLogicalExpression(){
return (logicalExpressionNode);
}
diff --git a/com.amd.aparapi/src/java/com/amd/aparapi/ByteBuffer.java b/com.amd.aparapi/src/java/com/amd/aparapi/ByteBuffer.java
index 5f220116..0f4cfbe6 100644
--- a/com.amd.aparapi/src/java/com/amd/aparapi/ByteBuffer.java
+++ b/com.amd.aparapi/src/java/com/amd/aparapi/ByteBuffer.java
@@ -43,15 +43,13 @@ to national security controls as identified on the Commerce Control List (curren
/**
* Used to parse ClassFile structure.
- *
+ *
* Provides low level access to sequential bytes in a stream given a specific offset.
- *
+ *
* Does not keep track of accesses. For this you will need a ByteReader
- *
- * @see com.amd.aparapi.ByteReader
- *
- * @author gfrost
*
+ * @author gfrost
+ * @see com.amd.aparapi.ByteReader
*/
class ByteBuffer{
@@ -59,20 +57,20 @@ class ByteBuffer{
/**
* Construct from an InputStream
- *
+ *
* @param _inputStream
*/
- ByteBuffer(InputStream _inputStream) {
+ ByteBuffer(InputStream _inputStream){
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bytes = new byte[4096];
int bytesRead = 0;
- try {
- while ((bytesRead = _inputStream.read(bytes)) > 0) {
+ try{
+ while ((bytesRead = _inputStream.read(bytes))>0){
baos.write(bytes, 0, bytesRead);
}
bytes = baos.toByteArray();
- } catch (IOException e) {
+ }catch (IOException e){
bytes = new byte[0];
// TODO Auto-generated catch block
e.printStackTrace();
@@ -80,64 +78,64 @@ class ByteBuffer{
}
- int u2(int _offset) {
- return (u1(_offset) << 8 | u1(_offset + 1));
+ int u2(int _offset){
+ return (u1(_offset)<<8|u1(_offset+1));
}
- int s2(int _offset) {
+ int s2(int _offset){
int s2 = u2(_offset);
- if (s2 > 0x7fff) {
- s2 = -(0x10000 - s2);
+ if (s2>0x7fff){
+ s2 = -(0x10000-s2);
}
return (s2);
}
- int u4(int _offset) {
- return ((u2(_offset) & 0xffff) << 16 | u2(_offset + 2));
+ int u4(int _offset){
+ return ((u2(_offset)&0xffff)<<16|u2(_offset+2));
}
- int s4(int _offset) {
+ int s4(int _offset){
int s4 = u4(_offset);
return (s4);
}
- ByteBuffer(byte[] _bytes) {
+ ByteBuffer(byte[] _bytes){
bytes = _bytes;
}
- int u1(int _offset) {
- return ((bytes[_offset] & 0xff));
+ int u1(int _offset){
+ return ((bytes[_offset]&0xff));
}
- int size() {
+ int size(){
return (bytes.length);
}
- double d8(int _offset) {
+ double d8(int _offset){
return (Double.longBitsToDouble(u8(_offset)));
}
- float f4(int _offset) {
+ float f4(int _offset){
return (Float.intBitsToFloat(u4(_offset)));
}
- long u8(int _offset) {
- return ((u4(_offset) & 0xffffffffL) << 32) | (u4(_offset + 4) & 0xffffffffL);
+ long u8(int _offset){
+ return ((u4(_offset)&0xffffffffL)<<32)|(u4(_offset+4)&0xffffffffL);
}
- int utf8bytes(int _offset) {
- return (2 + u2(_offset));
+ int utf8bytes(int _offset){
+ return (2+u2(_offset));
}
- byte[] bytes(int _offset, int _length) {
+ byte[] bytes(int _offset, int _length){
byte[] returnBytes = new byte[_length];
System.arraycopy(bytes, _offset, returnBytes, 0, _length);
return (returnBytes);
}
- String utf8(int _offset) {
+ String utf8(int _offset){
int utflen = u2(_offset);
_offset += 2;
byte[] bytearr = new byte[utflen];
@@ -147,22 +145,23 @@ String utf8(int _offset) {
int count = 0;
int chararr_count = 0;
- for (int i = 0; i < utflen; i++) {
- bytearr[i] = b(_offset + i);
+ for (int i = 0; i 127)
+ while (count127){
break;
+ }
count++;
- chararr[chararr_count++] = (char) c;
+ chararr[chararr_count++] = (char)c;
}
- while (count < utflen) {
- c = bytearr[count] & 0xff;
- switch (c >> 4) {
+ while (count>4){
case 0:
case 1:
case 2:
@@ -173,41 +172,41 @@ String utf8(int _offset) {
case 7:
/* 0xxxxxxx*/
count++;
- chararr[chararr_count++] = (char) c;
+ chararr[chararr_count++] = (char)c;
break;
case 12:
case 13:
/* 110x xxxx 10xx xxxx*/
count += 2;
- if (count > utflen) {
+ if (count>utflen){
System.out.println("malformed input: partial character at end");
return (null);
}
- char2 = bytearr[count - 1];
- if ((char2 & 0xC0) != 0x80) {
- System.out.println("malformed input around byte " + count);
+ char2 = bytearr[count-1];
+ if ((char2&0xC0) != 0x80){
+ System.out.println("malformed input around byte "+count);
return (null);
}
- chararr[chararr_count++] = (char) (((c & 0x1F) << 6) | (char2 & 0x3F));
+ chararr[chararr_count++] = (char)(((c&0x1F)<<6)|(char2&0x3F));
break;
case 14:
/* 1110 xxxx 10xx xxxx 10xx xxxx */
count += 3;
- if (count > utflen) {
+ if (count>utflen){
System.out.println("malformed input: partial character at end");
return (null);
}
- char2 = bytearr[count - 2];
- char3 = bytearr[count - 1];
- if (((char2 & 0xC0) != 0x80) || ((char3 & 0xC0) != 0x80)) {
- System.out.println("malformed input around byte " + (count - 1));
+ char2 = bytearr[count-2];
+ char3 = bytearr[count-1];
+ if (((char2&0xC0) != 0x80) || ((char3&0xC0) != 0x80)){
+ System.out.println("malformed input around byte "+(count-1));
return (null);
}
- chararr[chararr_count++] = (char) (((c & 0x0F) << 12) | ((char2 & 0x3F) << 6) | ((char3 & 0x3F) << 0));
+ chararr[chararr_count++] = (char)(((c&0x0F)<<12)|((char2&0x3F)<<6)|((char3&0x3F)<<0));
break;
default:
/* 10xx xxxx, 1111 xxxx */
- System.out.println("malformed input around byte " + count);
+ System.out.println("malformed input around byte "+count);
return (null);
}
}
@@ -217,7 +216,7 @@ String utf8(int _offset) {
return (returnString);
}
- byte b(int _offset) {
+ byte b(int _offset){
return bytes[_offset];
}
diff --git a/com.amd.aparapi/src/java/com/amd/aparapi/ByteReader.java b/com.amd.aparapi/src/java/com/amd/aparapi/ByteReader.java
index 3fae782e..d8ddc669 100644
--- a/com.amd.aparapi/src/java/com/amd/aparapi/ByteReader.java
+++ b/com.amd.aparapi/src/java/com/amd/aparapi/ByteReader.java
@@ -42,13 +42,12 @@ to national security controls as identified on the Commerce Control List (curren
/**
* Primarily used to parse various ClassFile structures. This class provides low level access to sequential bytes in a stream given stream.
*
- * Basically wraps a ByteBuffer and keeps track of the current offset. All requests on
+ * Basically wraps a ByteBuffer and keeps track of the current offset. All requests on
* this ByteReader will be delegated to wrappedByteBuffer.
*
- * @see com.amd.aparapi.ByteBuffer
- *
- * @author gfrost
*
+ * @author gfrost
+ * @see com.amd.aparapi.ByteBuffer
*/
class ByteReader{
private final ByteBuffer byteBuffer;
@@ -57,109 +56,109 @@ class ByteReader{
/**
* Construct form a given ByteBuffer.
- *
+ *
* @param _byteBuffer an existing ByteBuffer
*/
- ByteReader(ByteBuffer _byteBuffer) {
+ ByteReader(ByteBuffer _byteBuffer){
byteBuffer = _byteBuffer;
}
/**
* Construct form an array of bytes.
- *
+ *
* @param _bytes an existing byte array
*/
- ByteReader(byte[] _bytes) {
+ ByteReader(byte[] _bytes){
this(new ByteBuffer(_bytes));
}
/**
* Construct form an input stream (say a ClassFile).
- *
+ *
* @param _inputStream a stream of bytes
*/
- ByteReader(InputStream _inputStream) {
+ ByteReader(InputStream _inputStream){
this(new ByteBuffer(_inputStream));
}
- int u1() {
+ int u1(){
int value = byteBuffer.u1(offset);
offset += 1;
return (value);
}
- int u2() {
+ int u2(){
int value = byteBuffer.u2(offset);
offset += 2;
return (value);
}
- int s2() {
+ int s2(){
int value = byteBuffer.s2(offset);
offset += 2;
return (value);
}
- int peekU2() {
+ int peekU2(){
return (byteBuffer.u2(offset));
}
- int u4() {
+ int u4(){
int value = byteBuffer.u4(offset);
offset += 4;
return (value);
}
- int s4() {
+ int s4(){
int value = byteBuffer.s4(offset);
offset += 4;
return (value);
}
- long u8() {
+ long u8(){
long value = byteBuffer.u8(offset);
offset += 8;
return (value);
}
- float f4() {
+ float f4(){
float value = byteBuffer.f4(offset);
offset += 4;
return (value);
}
- double d8() {
+ double d8(){
double value = byteBuffer.d8(offset);
offset += 8;
return (value);
}
- String utf8() {
+ String utf8(){
String utf8 = byteBuffer.utf8(offset);
offset += byteBuffer.utf8bytes(offset);
return (utf8);
}
- byte[] bytes(int _length) {
+ byte[] bytes(int _length){
byte[] bytes = byteBuffer.bytes(offset, _length);
offset += _length;
return (bytes);
}
- void skip(int _length) {
+ void skip(int _length){
offset += _length;
}
- int getOffset() {
+ int getOffset(){
return (offset);
}
- void setOffset(int _offset) {
+ void setOffset(int _offset){
offset = _offset;
}
- boolean hasMore() {
- return (getOffset() < byteBuffer.size());
+ boolean hasMore(){
+ return (getOffset()java.lang.Class.
- *
+ *
+ * OREF ClassModel is constructed from an instance of a java.lang.Class.
+ *
* If the java class mode changes we may need to modify this to accommodate.
- *
+ *
+ * @author gfrost
* @see Java 5 Class File Format
* @see Java 7 Class File Format
- *
- * @author gfrost
- *
*/
-class ClassModel{
-
- interface LocalVariableInfo{
-
- int getStart();
-
- boolean isArray();
-
- int getEnd();
-
- String getVariableName();
-
- String getVariableDescriptor();
-
- int getVariableIndex();
-
- int getLength();
-
- }
-
- interface LocalVariableTableEntry extends Iterable{
- LocalVariableInfo getVariable(int _pc, int _index);
-
- }
-
- static final char SIGC_VOID = 'V';
-
- static final char SIGC_BOOLEAN = 'Z';
-
- static final char SIGC_BYTE = 'B';
-
- static final char SIGC_CHAR = 'C';
-
- static final char SIGC_SHORT = 'S';
-
- static final char SIGC_INT = 'I';
-
- static final char SIGC_LONG = 'J';
-
- static final char SIGC_FLOAT = 'F';
-
- static final char SIGC_DOUBLE = 'D';
-
- static final char SIGC_ARRAY = '[';
-
- static final char SIGC_CLASS = 'L';
-
- static final char SIGC_START_METHOD = '(';
-
- static final char SIGC_END_CLASS = ';';
-
- static final char SIGC_END_METHOD = ')';
-
- static final char SIGC_PACKAGE = '/';
+public class ClassModel{
private static Logger logger = Logger.getLogger(Config.getLoggerName());
- private ClassModel superClazz = null;
+ private ClassModel superClazzModel = null;
- /**
- * Create a ClassModel representing a given Class.
- *
- * The class's classfile must be available from the class's classloader via getClassLoader().getResourceAsStream(name)).
- * For dynamic languages creating classes on the fly we may need another approach.
- *
- * @param _class The class we will extract the model from
- * @throws ClassParseException
- */
+ private Class> clazz;
- ClassModel(Class> _class) throws ClassParseException {
+ static Map map = new LinkedHashMap();
- parse(_class);
+ public static void flush(){
+ map.clear();
+ }
- Class> mySuper = _class.getSuperclass();
- // Find better way to do this check
- // The java.lang.Object test is for unit test framework to succeed - should
- // not occur in normal use
- if ((mySuper != null) && (!mySuper.getName().equals(Kernel.class.getName()))
- && (!mySuper.getName().equals("java.lang.Object"))) {
- superClazz = new ClassModel(mySuper);
+ public static synchronized ClassModel getClassModel(Class> _clazz) throws ClassParseException{
+ String className = _clazz.getName();
+ ClassModel classModel = map.get(_clazz.getName());
+ if (classModel == null){
+ classModel = new ClassModel(_clazz);
+ map.put(_clazz.getName(), classModel);
}
+ return (classModel);
}
- ClassModel(InputStream _inputStream) throws ClassParseException {
-
- parse(_inputStream);
-
+ public static Class> getRealClassName(String _dotClassName){
+ for (String mappedName : map.keySet()){
+ if (mappedName.equals(_dotClassName)){
+ return (map.get(mappedName).clazz);
+ }
+ }
+ for (String mappedName : map.keySet()){
+ if (mappedName.startsWith(_dotClassName)){
+ return (map.get(mappedName).clazz);
+ }
+ }
+ return (null);
}
- ClassModel(Class> _clazz, byte[] _bytes) throws ClassParseException {
+ private ClassModel(Class> _clazz) throws ClassParseException{
+ String name = _clazz.getName();
+ int index = name.indexOf('/');
+ if (index>0){
+ name = name.substring(0, index);
+ }
+ byte[] _bytes = AparapiJNI.getAparapiJNI().getBytes(name);
clazz = _clazz;
parse(new ByteArrayInputStream(_bytes));
}
/**
* Determine if this is the superclass of some other named class.
- *
+ *
* @param otherClassName The name of the class to compare against
- * @return true if 'this' a superclass of another named class
+ * @return true if 'this' a superclass of another named class
*/
- boolean isSuperClass(String otherClassName) {
- if (getClassWeAreModelling().getName().equals(otherClassName)) {
+ boolean isSuperClass(String otherClassName){
+ if (getDotClassName().equals(otherClassName)){
return true;
- } else if (superClazz != null) {
- return superClazz.isSuperClass(otherClassName);
- } else {
+ }else if (superClazzModel != null){
+ return superClazzModel.isSuperClass(otherClassName);
+ }else{
return false;
}
}
/**
* Determine if this is the superclass of some other class.
- *
- * @param otherClass The class to compare against
- * @return true if 'this' a superclass of another class
+ *
+ * @param _otherClassModel The classModel to compare against
+ * @return true if 'this' a superclass of another class
*/
- boolean isSuperClass(Class> other) {
- Class> s = other.getSuperclass();
- while (s != null) {
- if (this.getClassWeAreModelling() == s || (this.getClassWeAreModelling().getName().equals(s.getName()))) {
+ boolean isSuperClass(ClassModel _otherClassModel){
+ ClassModel s = _otherClassModel.getSuperClazzModel();
+ while (s != null){
+ if (getDotClassName().equals(s.getDotClassName())){
return true;
}
- s = s.getSuperclass();
+ s = s.getSuperClazzModel();
}
return false;
}
/**
* Getter for superClazz
- *
- * @return the superClazz ClassModel
- */
- ClassModel getSuperClazz() {
- return superClazz;
- }
-
- @Annotations.DocMe void replaceSuperClazz(ClassModel c) {
- if (this.superClazz != null) {
- assert c.isSuperClass(this.getClassWeAreModelling()) == true : "not my super";
- if (this.superClazz.getClassWeAreModelling().getName().equals(c.getClassWeAreModelling().getName())) {
- this.superClazz = c;
- } else {
- this.superClazz.replaceSuperClazz(c);
- }
- }
- }
-
- /**
- * Convert a given JNI character type (say 'I') to its type name ('int').
- *
- * @param _typeChar
- * @return either a mapped type name or null if no mapping exists.
+ *
+ * @return the superClazz ClassModel
*/
- static String typeName(char _typeChar) {
- String returnName = null;
- switch (_typeChar) {
- case SIGC_VOID:
- returnName = "void";
- break;
- case SIGC_INT:
- returnName = "int";
- break;
- case SIGC_DOUBLE:
- returnName = "double";
- break;
- case SIGC_FLOAT:
- returnName = "float";
- break;
- case SIGC_SHORT:
- returnName = "short";
- break;
- case SIGC_CHAR:
- returnName = "char";
- break;
- case SIGC_BYTE:
- returnName = "byte";
- break;
- case SIGC_LONG:
- returnName = "long";
- break;
- case SIGC_BOOLEAN:
- returnName = "boolean";
- break;
- }
- return (returnName);
- }
-
- static String convert(String _string) {
- return (convert(_string, "", false));
- }
+ ClassModel getSuperClazzModel(){
+ if (superClazzModel == null){
+ if (getSuperClassConstantPoolIndex() != 0){
+ try{
+ superClazzModel = getClassModel(Class.forName(getSuperDotClassName()));
+ }catch (ClassNotFoundException cnf){
- static String convert(String _string, String _insert) {
- return (convert(_string, _insert, false));
- }
+ }catch (ClassParseException cpe){
- static String convert(String _string, String _insert, boolean _showFullClassName) {
- Stack stringStack = new Stack();
- Stack methodStack = null;
- int length = _string.length();
- char[] chars = _string.toCharArray();
- int i = 0;
- boolean inArray = false;
- boolean inMethod = false;
- boolean inArgs = false;
- int args = 0;
- while (i < length) {
- switch (chars[i]) {
- case SIGC_CLASS: {
- StringBuilder classNameBuffer = new StringBuilder();
- i++;
- while ((i < length) && chars[i] != SIGC_END_CLASS) {
- if (chars[i] == SIGC_PACKAGE) {
- classNameBuffer.append('.');
- } else {
- classNameBuffer.append(chars[i]);
- }
- i++;
- }
- i++; // step over SIGC_ENDCLASS
- String className = classNameBuffer.toString();
- if (_showFullClassName) {
- if (className.startsWith("java.lang")) {
- className = className.substring("java.lang.".length());
- }
- } else {
- int lastDot = className.lastIndexOf('.');
- if (lastDot > 0) {
- className = className.substring(lastDot + 1);
- }
- }
- if (inArray) {
- // swap the stack items
- String popped = stringStack.pop();
- if (inArgs && args > 0) {
- stringStack.push(", ");
- }
- stringStack.push(className);
- stringStack.push(popped);
- inArray = false;
- } else {
- if (inArgs && args > 0) {
- stringStack.push(", ");
- }
- stringStack.push(className);
- }
- args++;
- }
- break;
- case SIGC_ARRAY: {
- StringBuilder arrayDims = new StringBuilder();
- while ((i < length) && chars[i] == SIGC_ARRAY) {
- arrayDims.append("[]");
- i++;
- }
- stringStack.push(arrayDims.toString());
- inArray = true;
- }
- break;
- case SIGC_VOID:
- case SIGC_INT:
- case SIGC_DOUBLE:
- case SIGC_FLOAT:
- case SIGC_SHORT:
- case SIGC_CHAR:
- case SIGC_BYTE:
- case SIGC_LONG:
- case SIGC_BOOLEAN: {
- if (inArray) {
- // swap the stack items
- String popped = stringStack.pop();
- if (inArgs && args > 0) {
- stringStack.push(", ");
- }
- stringStack.push(typeName(chars[i]));
- stringStack.push(popped);
- inArray = false;
- } else {
- if (inArgs && args > 0) {
- stringStack.push(", ");
- }
- stringStack.push(typeName(chars[i]));
- }
- i++; // step over this
- }
- break;
- case SIGC_START_METHOD: {
- stringStack.push("(");
- i++; // step over this
- inArgs = true;
- args = 0;
- }
- break;
- case SIGC_END_METHOD: {
- inMethod = true;
- inArgs = false;
- stringStack.push(")");
- methodStack = stringStack;
- stringStack = new Stack();
- i++; // step over this
}
- break;
- }
- }
-
- StringBuilder returnValue = new StringBuilder();
- for (String s : stringStack) {
- returnValue.append(s);
- returnValue.append(" ");
-
- }
- if (inMethod) {
- for (String s : methodStack) {
- returnValue.append(s);
- returnValue.append(" ");
}
- } else {
- returnValue.append(_insert);
- }
- return (returnValue.toString());
- }
-
- static class MethodDescription{
- private String className;
-
- private String methodName;
-
- private String type;
-
- private String[] args;
-
- MethodDescription(String _className, String _methodName, String _type, String[] _args) {
- methodName = _methodName;
- className = _className;
- type = _type;
- args = _args;
- }
-
- String[] getArgs() {
- return (args);
- }
-
- String getType() {
- return (type);
- }
-
- String getClassName() {
- return (className);
- }
-
- String getMethodName() {
- return (methodName);
}
+ return superClazzModel;
}
- static MethodDescription getMethodDescription(String _string) {
- String className = null;
- String methodName = null;
- String descriptor = null;
- MethodDescription methodDescription = null;
- if (_string.startsWith("(")) {
- className = "?";
- methodName = "?";
- descriptor = _string;
- } else {
- int parenIndex = _string.indexOf("(");
- int dotIndex = _string.indexOf(".");
- descriptor = _string.substring(parenIndex);
- className = _string.substring(0, dotIndex);
- methodName = _string.substring(dotIndex + 1, parenIndex);
- }
- Stack stringStack = new Stack();
- Stack methodStack = null;
- int length = descriptor.length();
- char[] chars = new char[descriptor.length()];
- descriptor.getChars(0, descriptor.length(), chars, 0);
- int i = 0;
- boolean inArray = false;
- boolean inMethod = false;
- while (i < length) {
- switch (chars[i]) {
- case SIGC_CLASS: {
- StringBuilder stringBuffer = null;
- if (inArray) {
- stringBuffer = new StringBuilder(stringStack.pop());
- } else {
- stringBuffer = new StringBuilder();
- }
- while ((i < length) && chars[i] != SIGC_END_CLASS) {
- stringBuffer.append(chars[i]);
- i++;
- }
- stringBuffer.append(chars[i]);
- i++; // step over SIGC_ENDCLASS
- stringStack.push(stringBuffer.toString());
- inArray = false;
- }
- break;
- case SIGC_ARRAY: {
- StringBuilder stringBuffer = new StringBuilder();
- while ((i < length) && chars[i] == SIGC_ARRAY) {
- stringBuffer.append(chars[i]);
- i++;
- }
- stringStack.push(stringBuffer.toString());
- inArray = true;
- }
- break;
- case SIGC_VOID:
- case SIGC_INT:
- case SIGC_DOUBLE:
- case SIGC_FLOAT:
- case SIGC_SHORT:
- case SIGC_CHAR:
- case SIGC_BYTE:
- case SIGC_LONG:
- case SIGC_BOOLEAN: {
- StringBuilder stringBuffer = null;
- if (inArray) {
- stringBuffer = new StringBuilder(stringStack.pop());
- } else {
- stringBuffer = new StringBuilder();
- }
- stringBuffer.append(chars[i]);
- i++; // step over this
- stringStack.push(stringBuffer.toString());
- inArray = false;
- }
- break;
- case SIGC_START_METHOD: {
- i++; // step over this
- }
- break;
- case SIGC_END_METHOD: {
- inMethod = true;
- inArray = false;
- methodStack = stringStack;
- stringStack = new Stack();
- i++; // step over this
- }
- break;
+ /**
+ * Dont think we need this.
+ *
+ * @param c
+ */
+ @Annotations.DocMe
+ void replaceSuperClazz(ClassModel c){
+ if (this.superClazzModel != null){
+ // assert c.isSuperClass(this.getClassWeAreModelling()) == true : "not my super";
+ if (this.superClazzModel.getDotClassName().equals(c.getDotClassName())){
+ this.superClazzModel = c;
+ }else{
+ this.superClazzModel.replaceSuperClazz(c);
}
}
- if (inMethod) {
- methodDescription = new MethodDescription(className, methodName, stringStack.toArray(new String[0])[0],
- methodStack.toArray(new String[0]));
- } else {
- System.out.println("can't convert to a description");
- }
- return (methodDescription);
}
private int magic;
@@ -537,76 +212,83 @@ static MethodDescription getMethodDescription(String _string) {
private AttributePool attributePool;
- enum ConstantPoolType {
- EMPTY, //0
- UTF8, //1
- UNICODE, //2
- INTEGER, //3
- FLOAT, //4
- LONG, //5
- DOUBLE, //6
- CLASS, //7
- STRING, //8
- FIELD, //9
- METHOD, //10
- INTERFACEMETHOD, //11
- NAMEANDTYPE, //12
- UNUSED13,
- UNUSED14,
- METHODHANDLE, //15
- METHODTYPE, //16
- UNUSED17,
- INVOKEDYNAMIC
- //18
- };
-
- enum Access {
- PUBLIC(0x00000001),
- PRIVATE(0x00000002),
- PROTECTED(0x00000004),
- STATIC(0x00000008),
- FINAL(0x00000010),
- ACC_SYNCHRONIZED(0x00000020),
- ACC_VOLATILE(0x00000040),
- BRIDGE(0x00000040),
- TRANSIENT(0x00000080),
- VARARGS(0x00000080),
- NATIVE(0x00000100),
- INTERFACE(0x00000200),
- ABSTRACT(0x00000400),
- SUPER(0x00000020),
- STRICT(0x00000800),
- ANNOTATION(0x00002000),
- ACC_ENUM(0x00004000);
+ enum ConstantPoolType{
+ EMPTY(0, 1, "empty"), //0
+ UTF8(1, 1, "utf8"), //1
+ UNICODE(2, 1, "unicode"), //2
+ INTEGER(3, 1, "int"), //3
+ FLOAT(4, 1, "float"), //4
+ LONG(5, 2, "long"), //5
+ DOUBLE(6, 2, "double"), //6
+ CLASS(7, 1, "class"), //7
+ STRING(8, 1, "string"), //8
+ FIELD(9, 1, "field"), //9
+ METHOD(10, 1, "method"), //10
+ INTERFACEMETHOD(11, 1, "interface_method"), //11
+ NAMEANDTYPE(12, 1, "name and prefix"), //12
+ UNUSED13(13, 1, "unused13"),
+ UNUSED14(14, 1, "unused14"),
+ METHODHANDLE(15, 1, "method_handle"), //15
+ METHODTYPE(16, 1, "method_type"), //16
+ UNUSED17(17, 1, "unused17"), //17
+ INVOKEDYNAMIC(18, 1, "invoke_dynamic");//18
+
+ int index;
+ int slots;
+ String name;
+ ConstantPoolType[] types;
+
+ ConstantPoolType(int _index, int _slots, String _name, ConstantPoolType... _types){
+ index = _index;
+ slots = _slots;
+ name = _name;
+ types = _types;
+ }
+ }
+
+ ;
+
+ enum Access{
+ PUBLIC(0x00000001, "public"),
+ PRIVATE(0x00000002, "private"),
+ PROTECTED(0x00000004, "protected"),
+ STATIC(0x00000008, "static"),
+ FINAL(0x00000010, "final"),
+ ACC_SYNCHRONIZED(0x00000020, "synchronized"),
+ ACC_VOLATILE(0x00000040, "volatile"),
+ BRIDGE(0x00000040, "bridge"),
+ TRANSIENT(0x00000080, "transient"),
+ VARARGS(0x00000080, "varargs"),
+ NATIVE(0x00000100, "native"),
+ INTERFACE(0x00000200, "interface"),
+ ABSTRACT(0x00000400, "abstract"),
+ SUPER(0x00000020, "super"),
+ STRICT(0x00000800, "strict"),
+ ANNOTATION(0x00002000, "annotation"),
+ ACC_ENUM(0x00004000, "enum");
int bits;
+ String name;
- Access(int _bits) {
+ Access(int _bits, String _name){
bits = _bits;
+ name = _name;
}
- boolean bitIsSet(int _accessFlags) {
- return ((bits & _accessFlags) == bits);
+ boolean bitIsSet(int _accessFlags){
+ return ((bits&_accessFlags) == bits);
}
- String convert(int _accessFlags) {
+ String convert(int _accessFlags){
StringBuffer stringBuffer = new StringBuffer();
- for (Access access : Access.values()) {
- if (access.bitIsSet(_accessFlags)) {
- stringBuffer.append(" " + access.name().toLowerCase());
+ for (Access access : Access.values()){
+ if (access.bitIsSet(_accessFlags)){
+ stringBuffer.append(" "+access.name);
}
}
return (stringBuffer.toString());
}
}
- private static enum SignatureParseState {
- skipping,
- counting,
- inclass,
- inArray,
- done;
- };
-
class ConstantPool implements Iterable{
private List entries = new ArrayList();
@@ -616,56 +298,163 @@ abstract class Entry{
private int slot;
- Entry(ByteReader _byteReader, int _slot, ConstantPoolType _constantPoolType) {
+ Entry(ByteReader _byteReader, int _slot, ConstantPoolType _constantPoolType){
constantPoolType = _constantPoolType;
slot = _slot;
}
- ConstantPoolType getConstantPoolType() {
+ ConstantPoolType getConstantPoolType(){
return (constantPoolType);
}
- int getSlot() {
+ int getSlot(){
return (slot);
}
+ public boolean isEmptyEntry(){
+ return (this instanceof EmptyEntry);
+ }
+
+ public EmptyEntry asEmptyEntry(){
+ return ((EmptyEntry)this);
+ }
+
+ public boolean isDoubleEntry(){
+ return (this instanceof DoubleEntry);
+ }
+
+ public DoubleEntry asDoubleEntry(){
+ return ((DoubleEntry)this);
+ }
+
+ public boolean isLongEntry(){
+ return (this instanceof LongEntry);
+ }
+
+ public LongEntry asLongEntry(){
+ return ((LongEntry)this);
+ }
+
+ public boolean isClassEntry(){
+ return (this instanceof ClassEntry);
+ }
+
+ public ClassEntry asClassEntry(){
+ return ((ClassEntry)this);
+ }
+
+ public boolean isFloatEntry(){
+ return (this instanceof FloatEntry);
+ }
+
+ public FloatEntry asFloatEntry(){
+ return ((FloatEntry)this);
+ }
+
+ public boolean isIntegerEntry(){
+ return (this instanceof IntegerEntry);
+ }
+
+ public IntegerEntry asIntegerEntry(){
+ return ((IntegerEntry)this);
+ }
+
+ public boolean isStringEntry(){
+ return (this instanceof StringEntry);
+ }
+
+ public StringEntry asStringEntry(){
+ return ((StringEntry)this);
+ }
+
+ public boolean isUTF8Entry(){
+ return (this instanceof UTF8Entry);
+ }
+
+ public UTF8Entry asUTF8Entry(){
+ return ((UTF8Entry)this);
+ }
+
+ public boolean isNameAndTypeEntry(){
+ return (this instanceof NameAndTypeEntry);
+ }
+
+ public NameAndTypeEntry asNameAndTypeEntry(){
+ return ((NameAndTypeEntry)this);
+ }
+
+ public boolean isMethodEntry(){
+ return (this instanceof MethodEntry);
+ }
+
+ public MethodEntry asMethodEntry(){
+ return ((MethodEntry)this);
+ }
+
+ public boolean isInterfaceMethodEntry(){
+ return (this instanceof InterfaceMethodEntry);
+ }
+
+ public InterfaceMethodEntry asInterfaceMethodEntry(){
+ return ((InterfaceMethodEntry)this);
+ }
+
+ public boolean isFieldEntry(){
+ return (this instanceof FieldEntry);
+ }
+
+ public FieldEntry asFieldEntry(){
+ return ((FieldEntry)this);
+ }
+
}
class ClassEntry extends Entry{
private int nameIndex;
- ClassEntry(ByteReader _byteReader, int _slot) {
+ ClassEntry(ByteReader _byteReader, int _slot){
super(_byteReader, _slot, ConstantPoolType.CLASS);
nameIndex = _byteReader.u2();
}
- int getNameIndex() {
+ int getNameIndex(){
return (nameIndex);
}
- UTF8Entry getNameUTF8Entry() {
+ UTF8Entry getNameUTF8Entry(){
return (ConstantPool.this.getUTF8Entry(nameIndex));
}
- }
+ String getClassName(){
+ return (getNameUTF8Entry().getUTF8());
+ }
- class DoubleEntry extends Entry{
- private double doubleValue;
+ String getDotClassName(){
+ return (TypeHelper.slashClassNameToDotClassName(getNameUTF8Entry().getUTF8()));
+ }
- DoubleEntry(ByteReader _byteReader, int _slot) {
- super(_byteReader, _slot, ConstantPoolType.DOUBLE);
- doubleValue = _byteReader.d8();
+ String getMangledClassName(){
+ return (TypeHelper.slashClassNameToMangledClassName(getNameUTF8Entry().getUTF8()));
}
- double getDoubleValue() {
- return (doubleValue);
+ JavaType getType(){
+ String sig = getNameUTF8Entry().getUTF8();
+ return (JavaType.getJavaType("L"+sig+";"));
+ }
+ }
+
+ class DoubleEntry extends ConstantEntry{
+
+ DoubleEntry(ByteReader _byteReader, int _slot){
+ super(_byteReader, _slot, ConstantPoolType.DOUBLE);
+ value = _byteReader.d8();
}
}
class EmptyEntry extends Entry{
- EmptyEntry(ByteReader _byteReader, int _slot) {
+ EmptyEntry(ByteReader _byteReader, int _slot){
super(_byteReader, _slot, ConstantPoolType.EMPTY);
}
@@ -673,67 +462,70 @@ class EmptyEntry extends Entry{
class FieldEntry extends ReferenceEntry{
- FieldEntry(ByteReader _byteReader, int _slot) {
+ FieldEntry(ByteReader _byteReader, int _slot){
super(_byteReader, _slot, ConstantPoolType.FIELD);
}
+ final JavaType getType(){
+ return (JavaType.getJavaType(getNameAndTypeEntry().getDescriptorUTF8Entry().getUTF8()));
+ }
+
}
- class FloatEntry extends Entry{
- private float floatValue;
+ abstract class ConstantEntry extends Entry{
+ protected T value;
- FloatEntry(ByteReader _byteReader, int _slot) {
- super(_byteReader, _slot, ConstantPoolType.FLOAT);
- floatValue = _byteReader.f4();
+ ConstantEntry(ByteReader _byteReader, int _slot, ConstantPoolType _type){
+ super(_byteReader, _slot, _type);
}
- float getFloatValue() {
- return (floatValue);
+ T getValue(){
+ return value;
}
}
- class IntegerEntry extends Entry{
- private int intValue;
+ class FloatEntry extends ConstantEntry{
- IntegerEntry(ByteReader _byteReader, int _slot) {
- super(_byteReader, _slot, ConstantPoolType.INTEGER);
- intValue = _byteReader.u4();
+ FloatEntry(ByteReader _byteReader, int _slot){
+ super(_byteReader, _slot, ConstantPoolType.FLOAT);
+ value = _byteReader.f4();
}
- int getIntValue() {
- return (intValue);
+ }
+
+ class IntegerEntry extends ConstantEntry{
+
+ IntegerEntry(ByteReader _byteReader, int _slot){
+ super(_byteReader, _slot, ConstantPoolType.INTEGER);
+ value = _byteReader.u4();
}
}
class InterfaceMethodEntry extends MethodReferenceEntry{
- InterfaceMethodEntry(ByteReader _byteReader, int _slot) {
+ InterfaceMethodEntry(ByteReader _byteReader, int _slot){
super(_byteReader, _slot, ConstantPoolType.INTERFACEMETHOD);
}
}
- class LongEntry extends Entry{
- private long longValue;
+ class LongEntry extends ConstantEntry{
- LongEntry(ByteReader _byteReader, int _slot) {
+ LongEntry(ByteReader _byteReader, int _slot){
super(_byteReader, _slot, ConstantPoolType.LONG);
- longValue = _byteReader.u8();
- }
-
- long getLongValue() {
- return (longValue);
+ value = _byteReader.u8();
}
}
class MethodEntry extends MethodReferenceEntry{
- MethodEntry(ByteReader _byteReader, int _slot) {
+ MethodEntry(ByteReader _byteReader, int _slot){
super(_byteReader, _slot, ConstantPoolType.METHOD);
}
- @Override public String toString() {
+ @Override
+ public String toString(){
StringBuilder sb = new StringBuilder();
sb.append(getClassEntry().getNameUTF8Entry().getUTF8());
sb.append(".");
@@ -749,43 +541,50 @@ class NameAndTypeEntry extends Entry{
private int nameIndex;
- NameAndTypeEntry(ByteReader _byteReader, int _slot) {
+ NameAndTypeEntry(ByteReader _byteReader, int _slot){
super(_byteReader, _slot, ConstantPoolType.NAMEANDTYPE);
nameIndex = _byteReader.u2();
descriptorIndex = _byteReader.u2();
}
- int getDescriptorIndex() {
+ int getDescriptorIndex(){
return (descriptorIndex);
}
- UTF8Entry getDescriptorUTF8Entry() {
+ UTF8Entry getDescriptorUTF8Entry(){
return (ConstantPool.this.getUTF8Entry(descriptorIndex));
}
- int getNameIndex() {
+ int getNameIndex(){
return (nameIndex);
}
- UTF8Entry getNameUTF8Entry() {
+ UTF8Entry getNameUTF8Entry(){
return (ConstantPool.this.getUTF8Entry(nameIndex));
}
+ public String getName(){
+ return (getNameUTF8Entry().getUTF8());
+ }
+
+ public String getDescriptor(){
+ return (getDescriptorUTF8Entry().getUTF8());
+ }
}
class MethodTypeEntry extends Entry{
private int descriptorIndex;
- MethodTypeEntry(ByteReader _byteReader, int _slot) {
+ MethodTypeEntry(ByteReader _byteReader, int _slot){
super(_byteReader, _slot, ConstantPoolType.METHODTYPE);
descriptorIndex = _byteReader.u2();
}
- int getDescriptorIndex() {
+ int getDescriptorIndex(){
return (descriptorIndex);
}
- UTF8Entry getDescriptorUTF8Entry() {
+ UTF8Entry getDescriptorUTF8Entry(){
return (ConstantPool.this.getUTF8Entry(descriptorIndex));
}
@@ -798,17 +597,17 @@ class MethodHandleEntry extends Entry{
private int referenceIndex;
- MethodHandleEntry(ByteReader _byteReader, int _slot) {
+ MethodHandleEntry(ByteReader _byteReader, int _slot){
super(_byteReader, _slot, ConstantPoolType.METHODHANDLE);
referenceKind = _byteReader.u1();
referenceIndex = _byteReader.u2();
}
- int getReferenceIndex() {
+ int getReferenceIndex(){
return (referenceIndex);
}
- int getReferenceKind() {
+ int getReferenceKind(){
return (referenceKind);
}
@@ -821,17 +620,17 @@ class InvokeDynamicEntry extends Entry{
private int nameAndTypeIndex;
- InvokeDynamicEntry(ByteReader _byteReader, int _slot) {
+ InvokeDynamicEntry(ByteReader _byteReader, int _slot){
super(_byteReader, _slot, ConstantPoolType.INVOKEDYNAMIC);
bootstrapMethodAttrIndex = _byteReader.u2();
nameAndTypeIndex = _byteReader.u2();
}
- int getBootstrapMethodAttrIndex() {
+ int getBootstrapMethodAttrIndex(){
return (bootstrapMethodAttrIndex);
}
- int getNameAndTypeIndex() {
+ int getNameAndTypeIndex(){
return (nameAndTypeIndex);
}
@@ -839,133 +638,47 @@ int getNameAndTypeIndex() {
abstract class MethodReferenceEntry extends ReferenceEntry{
- class Arg extends Type{
- Arg(String _signature, int _start, int _pos, int _argc) {
- super(_signature.substring(_start, _pos + 1));
- argc = _argc;
- }
-
- private int argc;
-
- int getArgc() {
- return (argc);
- }
- }
-
- private Arg[] args = null;
-
- private Type returnType = null;
-
- @Override public int hashCode() {
+ @Override
+ public int hashCode(){
NameAndTypeEntry nameAndTypeEntry = getNameAndTypeEntry();
- return ((nameAndTypeEntry.getNameIndex() * 31 + nameAndTypeEntry.getDescriptorIndex()) * 31 + getClassIndex());
+ return ((nameAndTypeEntry.getNameIndex()*31+nameAndTypeEntry.getDescriptorIndex())*31+getClassIndex());
}
- @Override public boolean equals(Object _other) {
- if (_other == null || !(_other instanceof MethodReferenceEntry)) {
+ @Override
+ public boolean equals(Object _other){
+ if (_other == null || !(_other instanceof MethodReferenceEntry)){
return (false);
- } else {
- MethodReferenceEntry otherMethodReferenceEntry = (MethodReferenceEntry) _other;
+ }else{
+ MethodReferenceEntry otherMethodReferenceEntry = (MethodReferenceEntry)_other;
return (otherMethodReferenceEntry.getNameAndTypeEntry().getNameIndex() == getNameAndTypeEntry().getNameIndex()
&& otherMethodReferenceEntry.getNameAndTypeEntry().getDescriptorIndex() == getNameAndTypeEntry()
- .getDescriptorIndex() && otherMethodReferenceEntry.getClassIndex() == getClassIndex());
+ .getDescriptorIndex() && otherMethodReferenceEntry.getClassIndex() == getClassIndex());
}
}
- MethodReferenceEntry(ByteReader byteReader, int slot, ConstantPoolType constantPoolType) {
+ MethodReferenceEntry(ByteReader byteReader, int slot, ConstantPoolType constantPoolType){
super(byteReader, slot, constantPoolType);
}
- int getStackProduceCount() {
- return (getReturnType().isVoid() ? 0 : 1);
+ int getStackProduceCount(){
+ return (getArgsAndReturnType().getReturnType().isVoid()?0:1);
}
- Type getReturnType() {
- if (returnType == null) {
- getArgs();
- }
- return (returnType);
- }
-
- Arg[] getArgs() {
- if (args == null || returnType == null) {
- List argList = new ArrayList();
- NameAndTypeEntry nameAndTypeEntry = getNameAndTypeEntry();
-
- String signature = nameAndTypeEntry.getDescriptorUTF8Entry().getUTF8();// "([[IF)V" for a method that takes an int[][], float and returns void.
- // Sadly we need to parse this, we need the # of arguments for the call
- SignatureParseState state = SignatureParseState.skipping;
- int start = 0;
-
- for (int pos = 0; state != SignatureParseState.done; pos++) {
- char ch = signature.charAt(pos);
- switch (ch) {
- case '(':
- state = SignatureParseState.counting;
- break;
- case ')':
- state = SignatureParseState.done;
- returnType = new Type(signature.substring(pos + 1));
- break;
- case '[':
- switch (state) {
- case counting:
- state = SignatureParseState.inArray;
- start = pos;
- break;
-
- }
- // we don't care about arrays
- break;
- case 'L':
- // beginning of Ljava/lang/String; or something
-
- switch (state) {
- case counting:
- start = pos;
- // fallthrough intended!!
- case inArray:
- state = SignatureParseState.inclass;
- break;
- }
- break;
- case ';':
- // note we will only be in 'inclass' if we were previously counting, so this is safe
- switch (state) {
- case inclass:
- argList.add(new Arg(signature, start, pos, argList.size()));
- state = SignatureParseState.counting;
- break;
- }
- break;
-
- default:
- // we have IJBZDF so inc counter if we are still counting
- switch (state) {
- case counting:
- start = pos;
- // fallthrough intended!!
- case inArray:
- argList.add(new Arg(signature, start, pos, argList.size()));
- break;
-
- }
- break;
- }
+ // TypeHelper.JavaMethodArgsAndReturnType argsAndReturnType;
- }
- // System.out.println("method "+name+" has signature of "+signature+" which has "+count+" args");
+ TypeHelper.JavaMethodArgsAndReturnType getArgsAndReturnType(){
+ // if(argsAndReturnType == null){
+ NameAndTypeEntry nameAndTypeEntry = getNameAndTypeEntry();
- args = argList.toArray(new Arg[0]);
- }
- return (args);
+ String signature = nameAndTypeEntry.getDescriptorUTF8Entry().getUTF8();// "([[IF)V" for a method that takes an int[][], float and returns void.
+ return (TypeHelper.JavaMethodArgsAndReturnType.getArgsAndReturnType(signature));
}
- int getStackConsumeCount() {
- return (getArgs().length);
+ int getStackConsumeCount(){
+ return (getArgsAndReturnType().getArgs().length);
}
}
@@ -974,111 +687,91 @@ abstract class ReferenceEntry extends Entry{
protected int nameAndTypeIndex;
- protected int argCount = -1;
+ // protected int argCount = -1;
- ReferenceEntry(ByteReader _byteReader, int _slot, ConstantPoolType _constantPoolType) {
+ ReferenceEntry(ByteReader _byteReader, int _slot, ConstantPoolType _constantPoolType){
super(_byteReader, _slot, _constantPoolType);
referenceClassIndex = _byteReader.u2();
nameAndTypeIndex = _byteReader.u2();
}
- ClassEntry getClassEntry() {
+ ClassEntry getClassEntry(){
return (ConstantPool.this.getClassEntry(referenceClassIndex));
}
- int getClassIndex() {
+ String getName(){
+ return (getNameAndTypeEntry().getName());
+ }
+
+ int getClassIndex(){
return (referenceClassIndex);
}
- NameAndTypeEntry getNameAndTypeEntry() {
+ NameAndTypeEntry getNameAndTypeEntry(){
return (ConstantPool.this.getNameAndTypeEntry(nameAndTypeIndex));
}
- int getNameAndTypeIndex() {
+ int getNameAndTypeIndex(){
return (nameAndTypeIndex);
}
- boolean same(Entry _entry) {
- if (_entry instanceof ReferenceEntry) {
- ReferenceEntry entry = (ReferenceEntry) _entry;
+ boolean same(Entry _entry){
+ if (_entry instanceof ReferenceEntry){
+ ReferenceEntry entry = (ReferenceEntry)_entry;
return ((referenceClassIndex == entry.referenceClassIndex) && (nameAndTypeIndex == entry.nameAndTypeIndex));
}
return (false);
}
- class Type{
- private int arrayDimensions = 0;
-
- Type(String _type) {
- type = _type;
-
- while (type.charAt(arrayDimensions) == '[') {
- arrayDimensions++;
- }
- type = type.substring(arrayDimensions);
- }
-
- String getType() {
- return (type);
- }
-
- boolean isVoid() {
- return (type.equals("V"));
- }
-
- private String type;
-
- final boolean isArray() {
- return (arrayDimensions > 0);
- }
-
- final int getArrayDimensions() {
- return (arrayDimensions);
- }
-
- }
-
}
- class StringEntry extends Entry{
+ class StringEntry extends ConstantEntry{
private int utf8Index;
- StringEntry(ByteReader _byteReader, int _slot) {
+ StringEntry(ByteReader _byteReader, int _slot){
super(_byteReader, _slot, ConstantPoolType.STRING);
utf8Index = _byteReader.u2();
}
- int getUTF8Index() {
+ int getUTF8Index(){
return (utf8Index);
}
- UTF8Entry getStringUTF8Entry() {
+ UTF8Entry getStringUTF8Entry(){
return (ConstantPool.this.getUTF8Entry(utf8Index));
}
+
+ String getValue(){
+ if (value == null){
+ value = getStringUTF8Entry().getUTF8();
+ }
+ return (super.getValue());
+ }
+
}
class UTF8Entry extends Entry{
private String UTF8;
- UTF8Entry(ByteReader _byteReader, int _slot) {
+ UTF8Entry(ByteReader _byteReader, int _slot){
super(_byteReader, _slot, ConstantPoolType.UTF8);
UTF8 = _byteReader.utf8();
}
- String getUTF8() {
+ String getUTF8(){
return (UTF8);
}
}
- ConstantPool(ByteReader _byteReader) {
+ ConstantPool(ByteReader _byteReader){
int size = _byteReader.u2();
add(new EmptyEntry(_byteReader, 0)); // slot 0
- for (int i = 1; i < size; i++) {
+ for (int i = 1; i iterator() {
+ @Override
+ public Iterator iterator(){
return (entries.iterator());
}
- Entry get(int _index) {
+ Entry get(int _index){
return (entries.get(_index));
}
- String getDescription(ConstantPool.Entry _entry) {
+ String getDescription(ConstantPool.Entry _entry){
StringBuilder sb = new StringBuilder();
- if (_entry instanceof ConstantPool.EmptyEntry) {
- ;
- } else if (_entry instanceof ConstantPool.DoubleEntry) {
- ConstantPool.DoubleEntry doubleEntry = (ConstantPool.DoubleEntry) _entry;
- sb.append(doubleEntry.getDoubleValue());
- } else if (_entry instanceof ConstantPool.FloatEntry) {
- ConstantPool.FloatEntry floatEntry = (ConstantPool.FloatEntry) _entry;
- sb.append(floatEntry.getFloatValue());
- } else if (_entry instanceof ConstantPool.IntegerEntry) {
- ConstantPool.IntegerEntry integerEntry = (ConstantPool.IntegerEntry) _entry;
- sb.append(integerEntry.getIntValue());
- } else if (_entry instanceof ConstantPool.LongEntry) {
- ConstantPool.LongEntry longEntry = (ConstantPool.LongEntry) _entry;
- sb.append(longEntry.getLongValue());
- } else if (_entry instanceof ConstantPool.UTF8Entry) {
- ConstantPool.UTF8Entry utf8Entry = (ConstantPool.UTF8Entry) _entry;
- sb.append(utf8Entry.getUTF8());
- } else if (_entry instanceof ConstantPool.StringEntry) {
- ConstantPool.StringEntry stringEntry = (ConstantPool.StringEntry) _entry;
- ConstantPool.UTF8Entry utf8Entry = (ConstantPool.UTF8Entry) get(stringEntry.getUTF8Index());
- sb.append(utf8Entry.getUTF8());
- } else if (_entry instanceof ConstantPool.ClassEntry) {
- ConstantPool.ClassEntry classEntry = (ConstantPool.ClassEntry) _entry;
- ConstantPool.UTF8Entry utf8Entry = (ConstantPool.UTF8Entry) get(classEntry.getNameIndex());
- sb.append(utf8Entry.getUTF8());
- } else if (_entry instanceof ConstantPool.NameAndTypeEntry) {
- ConstantPool.NameAndTypeEntry nameAndTypeEntry = (ConstantPool.NameAndTypeEntry) _entry;
- ConstantPool.UTF8Entry utf8NameEntry = (ConstantPool.UTF8Entry) get(nameAndTypeEntry.getNameIndex());
- ConstantPool.UTF8Entry utf8DescriptorEntry = (ConstantPool.UTF8Entry) get(nameAndTypeEntry.getDescriptorIndex());
- sb.append(utf8NameEntry.getUTF8() + "." + utf8DescriptorEntry.getUTF8());
- } else if (_entry instanceof ConstantPool.MethodEntry) {
- ConstantPool.MethodEntry methodEntry = (ConstantPool.MethodEntry) _entry;
- ConstantPool.ClassEntry classEntry = (ConstantPool.ClassEntry) get(methodEntry.getClassIndex());
- ConstantPool.UTF8Entry utf8Entry = (ConstantPool.UTF8Entry) get(classEntry.getNameIndex());
- ConstantPool.NameAndTypeEntry nameAndTypeEntry = (ConstantPool.NameAndTypeEntry) get(methodEntry.getNameAndTypeIndex());
- ConstantPool.UTF8Entry utf8NameEntry = (ConstantPool.UTF8Entry) get(nameAndTypeEntry.getNameIndex());
- ConstantPool.UTF8Entry utf8DescriptorEntry = (ConstantPool.UTF8Entry) get(nameAndTypeEntry.getDescriptorIndex());
- sb.append(convert(utf8DescriptorEntry.getUTF8(), utf8Entry.getUTF8() + "." + utf8NameEntry.getUTF8()));
- } else if (_entry instanceof ConstantPool.InterfaceMethodEntry) {
- ConstantPool.InterfaceMethodEntry interfaceMethodEntry = (ConstantPool.InterfaceMethodEntry) _entry;
- ConstantPool.ClassEntry classEntry = (ConstantPool.ClassEntry) get(interfaceMethodEntry.getClassIndex());
- ConstantPool.UTF8Entry utf8Entry = (ConstantPool.UTF8Entry) get(classEntry.getNameIndex());
- ConstantPool.NameAndTypeEntry nameAndTypeEntry = (ConstantPool.NameAndTypeEntry) get(interfaceMethodEntry
- .getNameAndTypeIndex());
- ConstantPool.UTF8Entry utf8NameEntry = (ConstantPool.UTF8Entry) get(nameAndTypeEntry.getNameIndex());
- ConstantPool.UTF8Entry utf8DescriptorEntry = (ConstantPool.UTF8Entry) get(nameAndTypeEntry.getDescriptorIndex());
- sb.append(convert(utf8DescriptorEntry.getUTF8(), utf8Entry.getUTF8() + "." + utf8NameEntry.getUTF8()));
- } else if (_entry instanceof ConstantPool.FieldEntry) {
- ConstantPool.FieldEntry fieldEntry = (ConstantPool.FieldEntry) _entry;
- ConstantPool.ClassEntry classEntry = (ConstantPool.ClassEntry) get(fieldEntry.getClassIndex());
- ConstantPool.UTF8Entry utf8Entry = (ConstantPool.UTF8Entry) get(classEntry.getNameIndex());
- ConstantPool.NameAndTypeEntry nameAndTypeEntry = (ConstantPool.NameAndTypeEntry) get(fieldEntry.getNameAndTypeIndex());
- ConstantPool.UTF8Entry utf8NameEntry = (ConstantPool.UTF8Entry) get(nameAndTypeEntry.getNameIndex());
- ConstantPool.UTF8Entry utf8DescriptorEntry = (ConstantPool.UTF8Entry) get(nameAndTypeEntry.getDescriptorIndex());
- sb.append(convert(utf8DescriptorEntry.getUTF8(), utf8Entry.getUTF8() + "." + utf8NameEntry.getUTF8()));
- }
- return (sb.toString());
- }
-
- int[] getConstantPoolReferences(ConstantPool.Entry _entry) {
- int[] references = new int[0];
- if (_entry instanceof ConstantPool.StringEntry) {
- ConstantPool.StringEntry stringEntry = (ConstantPool.StringEntry) _entry;
- references = new int[] {
- stringEntry.getUTF8Index()
- };
- } else if (_entry instanceof ConstantPool.ClassEntry) {
- ConstantPool.ClassEntry classEntry = (ConstantPool.ClassEntry) _entry;
- references = new int[] {
- classEntry.getNameIndex()
- };
- } else if (_entry instanceof ConstantPool.NameAndTypeEntry) {
- ConstantPool.NameAndTypeEntry nameAndTypeEntry = (ConstantPool.NameAndTypeEntry) _entry;
- references = new int[] {
- nameAndTypeEntry.getNameIndex(),
- nameAndTypeEntry.getDescriptorIndex()
- };
- } else if (_entry instanceof ConstantPool.MethodEntry) {
- ConstantPool.MethodEntry methodEntry = (ConstantPool.MethodEntry) _entry;
- ConstantPool.ClassEntry classEntry = (ConstantPool.ClassEntry) get(methodEntry.getClassIndex());
- @SuppressWarnings("unused") ConstantPool.UTF8Entry utf8Entry = (ConstantPool.UTF8Entry) get(classEntry.getNameIndex());
- ConstantPool.NameAndTypeEntry nameAndTypeEntry = (ConstantPool.NameAndTypeEntry) get(methodEntry.getNameAndTypeIndex());
- @SuppressWarnings("unused") ConstantPool.UTF8Entry utf8NameEntry = (ConstantPool.UTF8Entry) get(nameAndTypeEntry
- .getNameIndex());
- @SuppressWarnings("unused") ConstantPool.UTF8Entry utf8DescriptorEntry = (ConstantPool.UTF8Entry) get(nameAndTypeEntry
- .getDescriptorIndex());
- references = new int[] {
- methodEntry.getClassIndex(),
- classEntry.getNameIndex(),
- nameAndTypeEntry.getNameIndex(),
- nameAndTypeEntry.getDescriptorIndex()
- };
- } else if (_entry instanceof ConstantPool.InterfaceMethodEntry) {
- ConstantPool.InterfaceMethodEntry interfaceMethodEntry = (ConstantPool.InterfaceMethodEntry) _entry;
- ConstantPool.ClassEntry classEntry = (ConstantPool.ClassEntry) get(interfaceMethodEntry.getClassIndex());
- @SuppressWarnings("unused") ConstantPool.UTF8Entry utf8Entry = (ConstantPool.UTF8Entry) get(classEntry.getNameIndex());
- ConstantPool.NameAndTypeEntry nameAndTypeEntry = (ConstantPool.NameAndTypeEntry) get(interfaceMethodEntry
- .getNameAndTypeIndex());
- @SuppressWarnings("unused") ConstantPool.UTF8Entry utf8NameEntry = (ConstantPool.UTF8Entry) get(nameAndTypeEntry
- .getNameIndex());
- @SuppressWarnings("unused") ConstantPool.UTF8Entry utf8DescriptorEntry = (ConstantPool.UTF8Entry) get(nameAndTypeEntry
- .getDescriptorIndex());
- references = new int[] {
- interfaceMethodEntry.getClassIndex(),
- classEntry.getNameIndex(),
- nameAndTypeEntry.getNameIndex(),
- nameAndTypeEntry.getDescriptorIndex()
- };
- } else if (_entry instanceof ConstantPool.FieldEntry) {
- ConstantPool.FieldEntry fieldEntry = (ConstantPool.FieldEntry) _entry;
- ConstantPool.ClassEntry classEntry = (ConstantPool.ClassEntry) get(fieldEntry.getClassIndex());
- @SuppressWarnings("unused") ConstantPool.UTF8Entry utf8Entry = (ConstantPool.UTF8Entry) get(classEntry.getNameIndex());
- ConstantPool.NameAndTypeEntry nameAndTypeEntry = (ConstantPool.NameAndTypeEntry) get(fieldEntry.getNameAndTypeIndex());
- @SuppressWarnings("unused") ConstantPool.UTF8Entry utf8NameEntry = (ConstantPool.UTF8Entry) get(nameAndTypeEntry
- .getNameIndex());
- @SuppressWarnings("unused") ConstantPool.UTF8Entry utf8DescriptorEntry = (ConstantPool.UTF8Entry) get(nameAndTypeEntry
- .getDescriptorIndex());
- references = new int[] {
- fieldEntry.getClassIndex(),
- classEntry.getNameIndex(),
- nameAndTypeEntry.getNameIndex(),
- nameAndTypeEntry.getDescriptorIndex()
- };
- }
- return (references);
- }
-
- String getType(ConstantPool.Entry _entry) {
- StringBuffer sb = new StringBuffer();
- if (_entry instanceof ConstantPool.EmptyEntry) {
- sb.append("empty");
- } else if (_entry instanceof ConstantPool.DoubleEntry) {
- sb.append("double");
- } else if (_entry instanceof ConstantPool.FloatEntry) {
- sb.append("float");
- } else if (_entry instanceof ConstantPool.IntegerEntry) {
- sb.append("int");
- } else if (_entry instanceof ConstantPool.LongEntry) {
- sb.append("long");
- } else if (_entry instanceof ConstantPool.UTF8Entry) {
- sb.append("utf8");
- } else if (_entry instanceof ConstantPool.StringEntry) {
- sb.append("string");
- } else if (_entry instanceof ConstantPool.ClassEntry) {
- sb.append("class");
- } else if (_entry instanceof ConstantPool.NameAndTypeEntry) {
- sb.append("name/type");
- } else if (_entry instanceof ConstantPool.MethodEntry) {
- sb.append("method");
- } else if (_entry instanceof ConstantPool.InterfaceMethodEntry) {
- sb.append("interface method");
- } else if (_entry instanceof ConstantPool.FieldEntry) {
- sb.append("field");
+ if (_entry.isEmptyEntry()){
+ sb.append("");
+ }else if (_entry.isDoubleEntry()){
+ sb.append(_entry.asDoubleEntry().getValue());
+ }else if (_entry.isFloatEntry()){
+ sb.append(_entry.asFloatEntry().getValue());
+ }else if (_entry.isIntegerEntry()){
+ sb.append(_entry.asIntegerEntry().getValue());
+ }else if (_entry.isLongEntry()){
+ sb.append(_entry.asLongEntry().getValue());
+ }else if (_entry.isUTF8Entry()){
+ sb.append(_entry.asUTF8Entry().getUTF8());
+ }else if (_entry.isStringEntry()){
+ sb.append(_entry.asStringEntry().getValue());
+ }else if (_entry.isClassEntry()){
+ sb.append(_entry.asClassEntry().getClassName());
+ }else if (_entry.isNameAndTypeEntry()){
+ sb.append(_entry.asNameAndTypeEntry().getName()+"."+_entry.asNameAndTypeEntry().getDescriptor());
+ }else if (_entry.isMethodEntry()){
+ sb.append(TypeHelper.convert(_entry.asMethodEntry().getNameAndTypeEntry().getDescriptor()));
+ sb.append(_entry.asMethodEntry().getClassEntry().getClassName()+"."+_entry.asMethodEntry().getName());
+ }else if (_entry.isInterfaceMethodEntry()){
+ sb.append(TypeHelper.convert(_entry.asInterfaceMethodEntry().getNameAndTypeEntry().getDescriptor()));
+ sb.append(_entry.asInterfaceMethodEntry().getClassEntry().getClassName()+"."+_entry.asInterfaceMethodEntry().getName());
+ }else if (_entry.isFieldEntry()){
+ sb.append(TypeHelper.convert(_entry.asFieldEntry().getNameAndTypeEntry().getDescriptor()));
+ sb.append(_entry.asFieldEntry().getClassEntry().getClassName()+"."+_entry.asFieldEntry().getNameAndTypeEntry().getName());
}
return (sb.toString());
}
- Object getConstantEntry(int _constantPoolIndex) {
+ T getConstantEntry(int _constantPoolIndex){
Entry entry = get(_constantPoolIndex);
- Object object = null;
- switch (entry.getConstantPoolType()) {
+ T object = null;
+ switch (entry.getConstantPoolType()){
case FLOAT:
- object = ((FloatEntry) entry).getFloatValue();
+ object = (T)entry.asFloatEntry().getValue();
break;
case DOUBLE:
- object = ((DoubleEntry) entry).getDoubleValue();
+ object = (T)entry.asDoubleEntry().getValue();
break;
case INTEGER:
- object = ((IntegerEntry) entry).getIntValue();
+ object = (T)entry.asIntegerEntry().getValue();
break;
case LONG:
- object = ((LongEntry) entry).getLongValue();
+ object = (T)entry.asLongEntry().getValue();
break;
case STRING:
- object = ((StringEntry) entry).getStringUTF8Entry().getUTF8();
+ object = (T)entry.asLongEntry().getValue();
break;
}
return (object);
@@ -1431,30 +999,30 @@ class ExceptionPoolEntry{
private int start;
- ExceptionPoolEntry(ByteReader _byteReader) {
+ ExceptionPoolEntry(ByteReader _byteReader){
start = _byteReader.u2();
end = _byteReader.u2();
handler = _byteReader.u2();
exceptionClassIndex = _byteReader.u2();
}
- ConstantPool.ClassEntry getClassEntry() {
+ ConstantPool.ClassEntry getClassEntry(){
return (constantPool.getClassEntry(exceptionClassIndex));
}
- int getClassIndex() {
+ int getClassIndex(){
return (exceptionClassIndex);
}
- int getEnd() {
+ int getEnd(){
return (end);
}
- int getHandler() {
+ int getHandler(){
return (handler);
}
- int getStart() {
+ int getStart(){
return (start);
}
@@ -1470,40 +1038,41 @@ int getStart() {
private int maxStack;
- CodeEntry(ByteReader _byteReader, int _nameIndex, int _length) {
+ CodeEntry(ByteReader _byteReader, int _nameIndex, int _length){
super(_byteReader, _nameIndex, _length);
maxStack = _byteReader.u2();
maxLocals = _byteReader.u2();
int codeLength = _byteReader.u4();
code = _byteReader.bytes(codeLength);
int exceptionTableLength = _byteReader.u2();
- for (int i = 0; i < exceptionTableLength; i++) {
+ for (int i = 0; i getExceptionPoolEntries() {
+ List getExceptionPoolEntries(){
return exceptionPoolEntries;
}
}
@@ -1511,19 +1080,19 @@ List getExceptionPoolEntries() {
class ConstantValueEntry extends AttributePoolEntry{
private int index;
- ConstantValueEntry(ByteReader _byteReader, int _nameIndex, int _length) {
+ ConstantValueEntry(ByteReader _byteReader, int _nameIndex, int _length){
super(_byteReader, _nameIndex, _length);
index = _byteReader.u2();
}
- int getIndex() {
+ int getIndex(){
return (index);
}
}
class DeprecatedEntry extends AttributePoolEntry{
- DeprecatedEntry(ByteReader _byteReader, int _nameIndex, int _length) {
+ DeprecatedEntry(ByteReader _byteReader, int _nameIndex, int _length){
super(_byteReader, _nameIndex, _length);
}
@@ -1534,24 +1103,24 @@ abstract class AttributePoolEntry{
protected int nameIndex;
- AttributePoolEntry(ByteReader _byteReader, int _nameIndex, int _length) {
+ AttributePoolEntry(ByteReader _byteReader, int _nameIndex, int _length){
nameIndex = _nameIndex;
length = _length;
}
- AttributePool getAttributePool() {
+ AttributePool getAttributePool(){
return (null);
}
- int getLength() {
+ int getLength(){
return (length);
}
- String getName() {
+ String getName(){
return (constantPool.getUTF8Entry(nameIndex).getUTF8());
}
- int getNameIndex() {
+ int getNameIndex(){
return (nameIndex);
}
@@ -1560,15 +1129,16 @@ int getNameIndex() {
abstract class PoolEntry extends AttributePoolEntry implements Iterable{
private List pool = new ArrayList();
- List getPool() {
+ List getPool(){
return (pool);
}
- PoolEntry(ByteReader _byteReader, int _nameIndex, int _length) {
+ PoolEntry(ByteReader _byteReader, int _nameIndex, int _length){
super(_byteReader, _nameIndex, _length);
}
- @Override public Iterator iterator() {
+ @Override
+ public Iterator iterator(){
return (pool.iterator());
}
@@ -1576,10 +1146,10 @@ List getPool() {
class ExceptionEntry extends PoolEntry{
- ExceptionEntry(ByteReader _byteReader, int _nameIndex, int _length) {
+ ExceptionEntry(ByteReader _byteReader, int _nameIndex, int _length){
super(_byteReader, _nameIndex, _length);
int exceptionTableLength = _byteReader.u2();
- for (int i = 0; i < exceptionTableLength; i++) {
+ for (int i = 0; i{
+
+ class StartLineNumberPair{
+ private int lineNumber;
+
+ private int start;
+
+ StartLineNumberPair(ByteReader _byteReader){
+ start = _byteReader.u2();
+ lineNumber = _byteReader.u2();
+ }
+
+ int getLineNumber(){
+ return (lineNumber);
+ }
+
+ int getStart(){
+ return (start);
+ }
+
+ }
+
+ LineNumberTableEntry(ByteReader _byteReader, int _nameIndex, int _length){
+ super(_byteReader, _nameIndex, _length);
+ int lineNumberTableLength = _byteReader.u2();
+ for (int i = 0; i i = getPool().iterator();
+ if (i.hasNext()){
+ StartLineNumberPair from = i.next();
+ while (i.hasNext()){
+ StartLineNumberPair to = i.next();
+ if (_exact){
+ if (_start == from.getStart()){
+ return (from.getLineNumber());
+ }
+ }else if (_start>=from.getStart() && _start=from.getStart()){
+ return (from.getLineNumber());
+ }
+ }
+ return (-1);
+ }
+
+ }
+
+ class EnclosingMethodEntry extends AttributePoolEntry{
+
+ EnclosingMethodEntry(ByteReader _byteReader, int _nameIndex, int _length){
+ super(_byteReader, _nameIndex, _length);
+ enclosingClassIndex = _byteReader.u2();
+ enclosingMethodIndex = _byteReader.u2();
+ }
+
+ private int enclosingClassIndex;
+
+ int getClassIndex(){
+ return (enclosingClassIndex);
+ }
+
+ private int enclosingMethodIndex;
+
+ int getMethodIndex(){
+ return (enclosingMethodIndex);
+ }
+
+ }
+
+ class SignatureEntry extends AttributePoolEntry{
+
+ SignatureEntry(ByteReader _byteReader, int _nameIndex, int _length){
+ super(_byteReader, _nameIndex, _length);
+ signatureIndex = _byteReader.u2();
+ }
+
+ private int signatureIndex;
+
+ int getSignatureIndex(){
+ return (signatureIndex);
+ }
+
+ }
+
+ public class LocalVariableTableEntry implements Iterable{
+
+ class LocalVariableInfo{
+
+ int startPc = 0;
+
+ int endPc = 0;
+
+ String name = null;
+
+ final String descriptor;
+
+ final TypeSpec typeSpec;
+
+ int slot;
+
+ LocalVariableInfo(InstructionSet.StoreSpec _storeSpec, int _slot, int _startPc){
+ slot = _slot;
+ startPc = _startPc;
+ name = _storeSpec.toString().toLowerCase()+"_"+_slot;
+ descriptor = _storeSpec.toString();
+ typeSpec = _storeSpec.getTypeSpec();
+ }
+
+ public boolean isArg(){
+ return (this instanceof ArgLocalVariableInfo);
+ }
+
+ LocalVariableInfo(){
+ name = "NONE";
+ descriptor = null;
+ typeSpec = TypeSpec.NONE;
+ }
+
+ public boolean equals(Object object){
+ return (object instanceof LocalVariableInfo && ((object == this) || ((LocalVariableInfo)object).name.equals(name)));
+ }
+
+ public String toString(){
+ return (name+"["+startPc+"-"+endPc+"]");
+ }
+
+ public int getStart(){
+ return startPc;
+ }
+
+ public int getEnd(){
+ return endPc;
+ }
+
+ public int getLength(){
+ return endPc-startPc;
+ }
+
+ public String getVariableName(){
+ return (name);
+ }
+
+ public String getVariableDescriptor(){
+ return (descriptor);
+ }
+
+ public int getSlot(){
+ return (slot);
+ }
+
+ public ArgLocalVariableInfo asArgLocalVariableInfo(){
+ return ((ArgLocalVariableInfo)this);
+ }
+
+ public TypeSpec getTypeSpec(){
+ return (typeSpec);
+ }
+ }
+
+ class ArgLocalVariableInfo extends LocalVariableInfo{
+ TypeHelper.JavaType realType;
+
+ ArgLocalVariableInfo(InstructionSet.StoreSpec _storeSpec, int _slot, int _startPc, JavaType _realType){
+ super(_storeSpec, _slot, _startPc);
+ realType = _realType;
+ }
+
+ public JavaType getRealType(){
+ return (realType);
+ }
+
+ public boolean isArray(){
+ return realType.isArray();
}
+
}
- }
+ List list = new ArrayList();
+ List argsList = new ArrayList();
- class LineNumberTableEntry extends PoolEntry{
+ public LocalVariableTableEntry(Map _pcMap, ClassModelMethod _method){
+ int numberOfSlots = _method.getCodeEntry().getMaxLocals();
- class StartLineNumberPair{
- private int lineNumber;
+ // MethodDescription description = TypeHelper.getMethodDescription(_method.getDescriptor());
- private int start;
+ TypeHelper.JavaMethodArgsAndReturnType argsAndReturnType = _method.getArgsAndReturnType();
+ TypeHelper.JavaMethodArg[] args = argsAndReturnType.getArgs();
- StartLineNumberPair(ByteReader _byteReader) {
- start = _byteReader.u2();
- lineNumber = _byteReader.u2();
- }
+ int thisOffset = _method.isStatic()?0:1;
- int getLineNumber() {
- return (lineNumber);
- }
+ LocalVariableInfo[] vars = new LocalVariableInfo[numberOfSlots+thisOffset];
+ // InstructionSet.StoreSpec[] argsAsStoreSpecs = new InstructionSet.StoreSpec[args.length + thisOffset];
+ if (_method.isVirtual()){
+ //argsAsStoreSpecs[0] = InstructionSet.StoreSpec.OREF;
+ ArgLocalVariableInfo arg = new ArgLocalVariableInfo(InstructionSet.StoreSpec.OREF, 0, 0, ClassModel.this.getClassType());
+ vars[0] = arg;
+ list.add(vars[0]);
+ argsList.add(arg);
- int getStart() {
- return (start);
}
- }
+ int currSlotIndex = thisOffset;
+ for (int i = 0; i i = getPool().iterator();
- if (i.hasNext()) {
- StartLineNumberPair from = i.next();
- while (i.hasNext()) {
- StartLineNumberPair to = i.next();
- if (_exact) {
- if (_start == from.getStart()) {
- return (from.getLineNumber());
- }
- } else if (_start >= from.getStart() && _start < to.getStart()) {
- return (from.getLineNumber());
+ int pc = 0;
+ Instruction instruction = null;
+ for (Instruction i : _pcMap.values()){
+ instruction = i;
+ pc = i.getThisPC();
+ InstructionSet.StoreSpec storeSpec = i.getByteCode().getStore();
+ if (storeSpec != InstructionSet.StoreSpec.NONE){
+ int slotIndex = ((InstructionSet.LocalVariableTableIndexAccessor)i).getLocalVariableTableIndex();
+ LocalVariableInfo prevVar = vars[slotIndex];
+ LocalVariableInfo var = new LocalVariableInfo(storeSpec, slotIndex, pc+i.getLength()); // will get collected pretty soon if this is not the same as the previous in this slot
+ if (!prevVar.equals(var)){
+ prevVar.endPc = pc;
+ vars[slotIndex] = var;
+ list.add(vars[slotIndex]);
}
- from = to;
- }
- if (_exact) {
- if (_start == from.getStart()) {
- return (from.getLineNumber());
+ }else if (i.isForwardBranchTarget()){ // Is there an earlier branch branching here ?
+ // If so we need to descope all vars declared between the brancher and here
+ // this stops
+ // if (){
+ // int var1=0;
+ // }
+ // int var2=0;
+ // Turning into OpenCL
+ // if (){
+ // int var=0;
+ // }
+ // var=0; // <- there is no var in scope for this
+
+ for (Branch b : instruction.getForwardBranches()){
+ for (int slot = 0; slot= from.getStart()) {
- return (from.getLineNumber());
}
}
- return (-1);
- }
-
- }
-
- class EnclosingMethodEntry extends AttributePoolEntry{
+ for (int i = 0; i(){
+ @Override
+ public int compare(LocalVariableInfo o1, LocalVariableInfo o2){
+ return o1.getStart()-o2.getStart();
+ }
+ });
- EnclosingMethodEntry(ByteReader _byteReader, int _nameIndex, int _length) {
- super(_byteReader, _nameIndex, _length);
- enclosingClassIndex = _byteReader.u2();
- enclosingMethodIndex = _byteReader.u2();
}
- private int enclosingClassIndex;
-
- int getClassIndex() {
- return (enclosingClassIndex);
+ public LocalVariableInfo getVariable(int _pc, int _slot){
+ LocalVariableInfo returnValue = null;
+ // System.out.println("pc = " + _pc + " index = " + _index);
+ for (LocalVariableInfo localVariableInfo : list){
+ // System.out.println(" start=" + localVariableInfo.getStart() + " length=" + localVariableInfo.getLength()
+ // + " varidx=" + localVariableInfo.getVariableIndex());
+ if (_pc>=localVariableInfo.getStart()-1 && _pc<=(localVariableInfo.getStart()+localVariableInfo.getLength())
+ && _slot == localVariableInfo.getSlot()){
+ returnValue = (LocalVariableInfo)localVariableInfo;
+ break;
+ }
+ }
+ return (returnValue);
}
- private int enclosingMethodIndex;
-
- int getMethodIndex() {
- return (enclosingMethodIndex);
+ String getVariableName(int _pc, int _index){
+ String returnValue = "unknown";
+ LocalVariableInfo localVariableInfo = (LocalVariableInfo)getVariable(_pc, _index);
+ if (localVariableInfo != null){
+ returnValue = ((LocalVariableInfo)localVariableInfo).name;
+ }
+ // System.out.println("returning " + returnValue);
+ return (returnValue);
}
- }
-
- class SignatureEntry extends AttributePoolEntry{
-
- SignatureEntry(ByteReader _byteReader, int _nameIndex, int _length) {
- super(_byteReader, _nameIndex, _length);
- signatureIndex = _byteReader.u2();
+ @Override
+ public Iterator iterator(){
+ return list.iterator();
}
- private int signatureIndex;
-
- int getSignatureIndex() {
- return (signatureIndex);
+ public List getArgs(){
+ return (argsList);
}
}
+ /*
- class RealLocalVariableTableEntry extends PoolEntry implements
- LocalVariableTableEntry{
+ class RealLocalVariableTableEntry extends PoolEntry implements
+ LocalVariableTableEntry{
- class RealLocalVariableInfo implements LocalVariableInfo{
+ class Var implements LocalVariableInfo{
private int descriptorIndex;
private int usageLength;
private int variableNameIndex;
- private int start;
+ private int startPc;
- private int variableIndex;
+ private int slot;
- RealLocalVariableInfo(ByteReader _byteReader) {
- start = _byteReader.u2();
+ private JavaType type;
+
+ String variableDescriptor;
+
+ String variableName;
+
+ Var(ByteReader _byteReader){
+ startPc = _byteReader.u2();
usageLength = _byteReader.u2();
variableNameIndex = _byteReader.u2();
descriptorIndex = _byteReader.u2();
- variableIndex = _byteReader.u2();
+ variableName = constantPool.getUTF8Entry(variableNameIndex).getUTF8();
+ variableDescriptor = constantPool.getUTF8Entry(descriptorIndex).getUTF8();
+ type = TypeHelper.getJavaType(variableDescriptor);
+
+ slot = _byteReader.u2();
}
- int getDescriptorIndex() {
+
+
+
+ int getDescriptorIndex(){
return (descriptorIndex);
}
- public int getLength() {
+ public int getLength(){
return (usageLength);
}
- int getNameIndex() {
+ int getNameIndex(){
return (variableNameIndex);
}
+ @Override
+ public boolean isArg(){
+ return (startPc==0);
+ }
+ @Override
+ public int getStart(){
+ return (startPc);
+ }
- @Override public int getStart() {
- return (start);
+ @Override
+ public int getSlot(){
+ return (slot);
+ }
+
+ @Override
+ public String getVariableName(){
+ return (variableName);
}
- @Override public int getVariableIndex() {
- return (variableIndex);
+ @Override
+ public String getVariableDescriptor(){
+ return (variableDescriptor);
}
- @Override public String getVariableName() {
- return (constantPool.getUTF8Entry(variableNameIndex).getUTF8());
+ @Override
+ public TypeHelper.JavaType getType(){
+ return (type);
}
- @Override public String getVariableDescriptor() {
- return (constantPool.getUTF8Entry(descriptorIndex).getUTF8());
+ @Override
+ public TypeHelper.JavaType getRealType(){
+ return (type);
}
- @Override public int getEnd() {
- return (start + usageLength);
+ @Override
+ public int getEnd(){
+ return (startPc + usageLength);
}
- @Override public boolean isArray() {
+ @Override
+ public boolean isArray(){
return (getVariableDescriptor().startsWith("["));
}
+
+ @Override
+ public boolean isObject(){
+ return (getVariableDescriptor().startsWith("L"));
+ }
}
- RealLocalVariableTableEntry(ByteReader _byteReader, int _nameIndex, int _length) {
+ RealLocalVariableTableEntry(ByteReader _byteReader, int _nameIndex, int _length){
super(_byteReader, _nameIndex, _length);
int localVariableTableLength = _byteReader.u2();
- for (int i = 0; i < localVariableTableLength; i++) {
- getPool().add(new RealLocalVariableInfo(_byteReader));
+ for(int i = 0; i < localVariableTableLength; i++){
+ getPool().add(new Var(_byteReader));
}
+
+
}
- public LocalVariableInfo getVariable(int _pc, int _index) {
- RealLocalVariableInfo returnValue = null;
+ public Var getVariable(int _pc, int _slot){
+ Var returnValue = null;
// System.out.println("pc = " + _pc + " index = " + _index);
- for (RealLocalVariableInfo localVariableInfo : getPool()) {
+ for(LocalVariableInfo localVariableInfo : getPool()){
// System.out.println(" start=" + localVariableInfo.getStart() + " length=" + localVariableInfo.getLength()
// + " varidx=" + localVariableInfo.getVariableIndex());
- if (_pc >= localVariableInfo.getStart() - 1 && _pc <= (localVariableInfo.getStart() + localVariableInfo.getLength())
- && _index == localVariableInfo.getVariableIndex()) {
- returnValue = localVariableInfo;
+ if(_pc >= localVariableInfo.getStart() - 1 && _pc <= (localVariableInfo.getStart() + localVariableInfo.getLength())
+ && _slot == localVariableInfo.getSlot()){
+ returnValue = (Var) localVariableInfo;
break;
}
}
@@ -1809,11 +1637,11 @@ public LocalVariableInfo getVariable(int _pc, int _index) {
return (returnValue);
}
- String getVariableName(int _pc, int _index) {
+ String getVariableName(int _pc, int _index){
String returnValue = "unknown";
- RealLocalVariableInfo localVariableInfo = (RealLocalVariableInfo) getVariable(_pc, _index);
- if (localVariableInfo != null) {
- returnValue = convert(constantPool.getUTF8Entry(localVariableInfo.getDescriptorIndex()).getUTF8(), constantPool
+ Var localVariableInfo = getVariable(_pc, _index);
+ if(localVariableInfo != null){
+ returnValue = TypeHelper.convert(constantPool.getUTF8Entry(localVariableInfo.getDescriptorIndex()).getUTF8(), constantPool
.getUTF8Entry(localVariableInfo.getNameIndex()).getUTF8());
}
// System.out.println("returning " + returnValue);
@@ -1821,23 +1649,24 @@ String getVariableName(int _pc, int _index) {
}
}
+ */
class BootstrapMethodsEntry extends AttributePoolEntry{
// http://docs.oracle.com/javase/specs/jvms/se7/html/jvms-4.html#jvms-4.7.21
class BootstrapMethod{
class BootstrapArgument{
- public BootstrapArgument(ByteReader _byteReader) {
+ public BootstrapArgument(ByteReader _byteReader){
argument = _byteReader.u2();
}
int argument;// u2;
}
- public BootstrapMethod(ByteReader _byteReader) {
+ public BootstrapMethod(ByteReader _byteReader){
bootstrapMethodRef = _byteReader.u2();
numBootstrapArguments = _byteReader.u2();
bootstrapArguments = new BootstrapArgument[numBootstrapArguments];
- for (int i = 0; i < numBootstrapArguments; i++) {
+ for (int i = 0; i getDeclaringClass() {
- String clazzName = getDescriptor().replaceAll("^L", "").replaceAll("/", ".").replaceAll(";$", "");
- try {
- return (Class.forName(clazzName, true, classModelLoader));
- } catch (ClassNotFoundException e) {
- System.out.println("no class found for " + clazzName);
- e.printStackTrace();
- return null;
+ TypeHelper.JavaType type;
+
+ JavaType getType(){
+ if (type == null){
+ type = TypeHelper.JavaType.getJavaType(getDescriptor());
}
+ return (type);
}
+
}
- class ClassModelMethod{
+ public class ClassModelMethod{
private int methodAccessFlags;
@@ -2320,7 +2168,7 @@ class ClassModelMethod{
private CodeEntry codeEntry;
- ClassModelMethod(ByteReader _byteReader, int _index) {
+ ClassModelMethod(ByteReader _byteReader, int _index){
index = _index;
methodAccessFlags = _byteReader.u2();
nameIndex = _byteReader.u2();
@@ -2329,81 +2177,492 @@ class ClassModelMethod{
codeEntry = methodAttributePool.getCodeEntry();
}
- int getAccessFlags() {
+ int getAccessFlags(){
return (methodAccessFlags);
}
- public boolean isStatic() {
+ public boolean isStatic(){
return (Access.STATIC.bitIsSet(methodAccessFlags));
}
- AttributePool getAttributePool() {
+ public boolean isNonStatic(){
+ return (!isStatic());
+ }
+
+ public boolean isVirtual(){
+ return (!Access.STATIC.bitIsSet(methodAccessFlags));
+ }
+
+ AttributePool getAttributePool(){
return (methodAttributePool);
}
- AttributePool.CodeEntry getCodeEntry() {
+ AttributePool.CodeEntry getCodeEntry(){
return (methodAttributePool.getCodeEntry());
}
- String getDescriptor() {
+ String getDescriptor(){
return (getDescriptorUTF8Entry().getUTF8());
}
- int getDescriptorIndex() {
+ int getDescriptorIndex(){
return (descriptorIndex);
}
- ConstantPool.UTF8Entry getDescriptorUTF8Entry() {
+ ConstantPool.UTF8Entry getDescriptorUTF8Entry(){
return (constantPool.getUTF8Entry(descriptorIndex));
}
- int getIndex() {
+ TypeHelper.JavaMethodArgsAndReturnType argsAndReturnType;
+
+ TypeHelper.JavaMethodArgsAndReturnType getArgsAndReturnType(){
+ if (argsAndReturnType == null){
+ argsAndReturnType = TypeHelper.JavaMethodArgsAndReturnType.getArgsAndReturnType(getDescriptor());
+ }
+ return (argsAndReturnType);
+ }
+
+ int getIndex(){
return (index);
}
- String getName() {
+ String getName(){
return (getNameUTF8Entry().getUTF8());
}
- int getNameIndex() {
+ int getNameIndex(){
return (nameIndex);
}
- ConstantPool.UTF8Entry getNameUTF8Entry() {
+ ConstantPool.UTF8Entry getNameUTF8Entry(){
return (constantPool.getUTF8Entry(nameIndex));
}
- ConstantPool getConstantPool() {
+ ConstantPool getConstantPool(){
return (constantPool);
}
- AttributePool.LineNumberTableEntry getLineNumberTableEntry() {
+ AttributePool.LineNumberTableEntry getLineNumberTableEntry(){
return (getAttributePool().codeEntry.codeEntryAttributePool.lineNumberTableEntry);
}
+ // AttributePool.RealLocalVariableTableEntry getRealLocalVariableTableEntry(){
+ // return (getAttributePool().codeEntry.codeEntryAttributePool.realLocalVariableTableEntry);
- LocalVariableTableEntry getLocalVariableTableEntry() {
+ // }
+ AttributePool.LocalVariableTableEntry getLocalVariableTableEntry(){
return (getAttributePool().codeEntry.codeEntryAttributePool.localVariableTableEntry);
+
}
+ // LocalVariableTableEntry getPreferredLocalVariableTableEntry(){
+ // if (Config.enableUseRealLocalVariableTableIfAvailable){
+ // return ((LocalVariableTableEntry)getRealLocalVariableTableEntry());
+ // }else{
+ // return ((LocalVariableTableEntry)getLocalVariableTableEntry());
+ // }
+ // }
- void setLocalVariableTableEntry(LocalVariableTableEntry _localVariableTableEntry) {
+ void setLocalVariableTableEntry(AttributePool.LocalVariableTableEntry _localVariableTableEntry){
getAttributePool().codeEntry.codeEntryAttributePool.localVariableTableEntry = _localVariableTableEntry;
}
- LocalVariableInfo getLocalVariable(int _pc, int _index) {
+ AttributePool.LocalVariableTableEntry.LocalVariableInfo getLocalVariable(int _pc, int _index){
return (getLocalVariableTableEntry().getVariable(_pc, _index));
}
- byte[] getCode() {
+ byte[] getCode(){
return (codeEntry.getCode());
}
- ClassModel getClassModel() {
+ ClassModel getClassModel(){
return (ClassModel.this);
}
-
- public String toString() {
- return getClassModel().getClassWeAreModelling().getName() + "." +
- getName() + " " + getDescriptor();
+
+ public String toString(){
+ return getClassModel().getDotClassName()+"."+getName()+" "+getDescriptor();
+ }
+
+ Map pcMap;
+ Set branches;
+
+ Set getBranches(){
+ getInstructionMap(); // remember it is lazy
+ return (branches);
+ }
+
+ Set branchTargets;
+
+ Set getBranchTargets(){
+ getInstructionMap(); // remember it is lazy
+ return (branchTargets);
+ }
+
+ Set methodCalls;
+
+ public Set getMethodCalls(){
+ getInstructionMap(); // remember it is lazy
+ return (methodCalls);
+ }
+
+ Set accessedFields;
+
+ public Set getFieldAccesses(){
+ getInstructionMap(); // remember it is lazy
+
+ return (accessedFields);
+ }
+
+ Set accessedLocalVariables;
+
+ public Set getLocalVariableAccesses(){
+ getInstructionMap(); // remember it is lazy
+
+ return (accessedLocalVariables);
+ }
+
+ class ConsumedInstructionTypeStack{
+
+ Instruction.InstructionType[] instructionTypes;
+ int index = 0;
+
+ ConsumedInstructionTypeStack(int _length){
+ instructionTypes = new Instruction.InstructionType[_length];
+
+ }
+
+ Instruction.InstructionType pop(){
+ Instruction.InstructionType retValue = null;
+ if (index>0){
+ retValue = instructionTypes[--index];
+ instructionTypes[index] = null;
+ }
+ return (retValue);
+ }
+
+ Instruction.InstructionType peek(){
+ Instruction.InstructionType retValue = null;
+ if (index>0){
+ retValue = instructionTypes[index-1];
+ }
+ return (retValue);
+
+ }
+
+ void push(Instruction _i, PrimitiveType _primitiveType){
+ if ((index+1)
+ * Returns a map of int (pc) to Instruction which to allow us to quickly get from a bytecode offset to the appropriate instruction.
+ *
+ * Note that not all int values from 0 to code.length values will map to a valid instruction, if pcMap.get(n) == null then this implies
+ * that 'n' is not the start of an instruction
+ *
+ * So either pcMap.get(i)== null or pcMap.get(i).getThisPC()==i
+ *
+ * @return Map the returned pc to Instruction map
+ */
+ Map getInstructionMap(){
+ // We build this lazily
+ if (pcMap == null){
+
+ Instruction pcHead = null;
+ Instruction pcTail = null;
+ pcMap = new LinkedHashMap();
+ branches = new LinkedHashSet();
+ branchTargets = new LinkedHashSet();
+ methodCalls = new LinkedHashSet();
+ accessedFields = new LinkedHashSet();
+ accessedLocalVariables = new LinkedHashSet();
+ byte[] code = getCode();
+
+ // We create a byteReader for reading the bytes from the code array
+ ByteReader codeReader = new ByteReader(code);
+ while (codeReader.hasMore()){
+ // Create an instruction from code reader's current position
+ int pc = codeReader.getOffset();
+ Instruction instruction = InstructionSet.ByteCode.create(this, codeReader);
+
+ if (instruction instanceof InstructionSet.Branch){
+ branches.add(instruction.asBranch());
+ }
+ if (instruction.isMethodCall()){
+ methodCalls.add(instruction.asMethodCall());
+ }
+ if (instruction.isFieldAccessor()){
+ accessedFields.add(instruction.asFieldAccessor());
+ }
+
+ if (instruction.isLocalVariableAccessor()){
+ accessedLocalVariables.add(instruction.asLocalVariableAccessor());
+ }
+ pcMap.put(pc, instruction);
+
+ // list maintenance, make this the pcHead if pcHead is null
+ if (pcHead == null){
+ pcHead = instruction;
+ }
+
+ // extend the list of instructions here we make the new instruction point to previous tail
+ instruction.setPrevPC(pcTail);
+ // if tail exists (not the first instruction in the list) link it to the new instruction
+ if (pcTail != null){
+ pcTail.setNextPC(instruction);
+ }
+ // now move the tail along
+ pcTail = instruction;
+
+ }
+
+ // Here we connect the branch nodes to the instruction that they branch to.
+ //
+ // Each branch node contains a 'target' field intended to reference the node that the branch targets. Each instruction also contain four separate lists of branch nodes that reference it.
+ // These lists hold forwardConditional, forwardUnconditional, reverseConditional and reverseUnconditional branches that reference it.
+ //
+ // So assuming that we had a branch node at pc offset 100 which represented 'goto 200'.
+ //
+ // Following this loop the branch node at pc offset 100 will have a 'target' field which actually references the instruction at pc offset 200, and the instruction at pc offset 200 will
+ // have the branch node (at 100) added to it's forwardUnconditional list.
+ //
+ // @see InstructionSet.Branch#getTarget()
+
+ for (InstructionSet.Branch branch : branches){
+ Instruction targetInstruction = pcMap.get(branch.getAbsolute());
+ branchTargets.add(targetInstruction);
+ branch.setTarget(targetInstruction);
+ }
+
+ // We need to remove some javac optimizations
+ // Javac optimizes some branches to avoid goto->goto, branch->goto etc.
+
+ for (InstructionSet.Branch branch : branches){
+ if (branch.isReverse()){
+ Instruction target = branch.getTarget();
+ LinkedList list = target.getReverseUnconditionalBranches();
+ if ((list != null) && (list.size()>0) && (list.get(list.size()-1) != branch)){
+ InstructionSet.Branch unconditional = list.get(list.size()-1).asBranch();
+ branch.retarget(unconditional);
+
+ }
+ }
+ }
+
+ int block = 0;
+ int depth = 0;
+ for (Instruction i : pcMap.values()){
+ if (i.isBranch() || i.isBranchTarget()){
+ block++;
+ }
+ if (i.isForwardBranch()){
+ depth++;
+ }
+ if (i.isReverseBranch()){
+ depth--;
+ }
+ depth -= i.getForwardBranches().size();
+ depth += i.getReverseBranches().size();
+
+ i.setBlock(block);
+ i.setDepth(depth);
+
+ }
+
+ // need to treat ternary else goto's special.
+
+ ConsumedInstructionTypeStack consumedInstructionTypeStack = new ConsumedInstructionTypeStack(codeEntry.getMaxStack()+1);
+
+ for (Instruction i : pcMap.values()){
+ i.setPostStackBase(consumedInstructionTypeStack.getIndex());
+ Instruction.InstructionType[] consumedInstructionTypes = new Instruction.InstructionType[i.getStackConsumeCount()];
+ for (int ci = 0; ci listOfBranches = firstInElseBlock.getForwardBranches();
+ Branch lastBranchElseBlock = listOfBranches.getLast();
+ Instruction firstInThenBlock = lastBranchElseBlock.getNextPC();
+ // System.out.println("firstInThenBlock "+ firstInThenBlock.getPreStackBase()+", "+firstInThenBlock.getPostStackBase()) ;
+ // System.out.println("last "+ last.getPreStackBase()+", "+last.getPostStackBase()) ;
+ //System.out.println("elseGoto "+elseGoto.getPreStackBase()+", "+elseGoto.getPostStackBase());
+ if (elseGoto.getPostStackBase()>firstInThenBlock.getPostStackBase()){
+ // System.out.println("@"+i.getStartPC()+" ternary!");
+
+ consumedInstructionTypeStack.pop(); // We throw one away!
+ }else{
+ // System.out.println("@"+i.getStartPC()+" not ternary!");
+ }
+
+ }
+
+ }
+
+ }
+
+
+ /* AttributePool.RealLocalVariableTableEntry realLocalVariableTableEntry = getRealLocalVariableTableEntry();
+
+ if(realLocalVariableTableEntry != null && Config.enableShowRealLocalVariableTable){
+ Table table = new Table("| %3d","| %3d", "| %3d", "| %2d", "|%4s", "| %8s|");
+ table.header("|Start","| End", "|Length", "|Slot", "|Name", "|Signature|");
+ AttributePool.RealLocalVariableTableEntry real = realLocalVariableTableEntry;
+ for(LocalVariableInfo var : real){
+ table.data(var.getStart());
+ table.data(var.getEnd());
+ table.data(var.getLength());
+ table.data(var.getSlot());
+ table.data(var.getVariableName());
+ table.data(var.getVariableDescriptor());
+ }
+ System.out.println("REAL!\n"+table);
+ }
+ */
+
+ AttributePool.LocalVariableTableEntry localVariableTableEntry = attributePool.new LocalVariableTableEntry(pcMap, this);
+
+ setLocalVariableTableEntry(localVariableTableEntry);
+ if (Config.enableShowLocalVariableTable){
+ Table table = new Table("| %3d", "| %3d", "| %3d", "| %2d", "|%4s", "| %8s|");
+ table.header("|Start", "| End", "|Length", "|Slot", "|Name", "|Signature|");
+ for (AttributePool.LocalVariableTableEntry.LocalVariableInfo var : localVariableTableEntry){
+ table.data(var.getStart());
+ table.data(var.getEnd());
+ table.data(var.getLength());
+ table.data(var.getSlot());
+ table.data(var.getVariableName());
+ table.data(var.getVariableDescriptor());
+ }
+
+ System.out.println("\n"+table);
+ }
+
+ // LocalVariableTableEntry localVariableTableEntry = getPreferredLocalVariableTableEntry();
+
+ for (InstructionSet.LocalVariableTableIndexAccessor instruction : accessedLocalVariables){
+ int pc = ((Instruction)instruction).getThisPC();
+ int len = ((Instruction)instruction).getLength();
+ int varIndex = instruction.getLocalVariableTableIndex();
+ AttributePool.LocalVariableTableEntry.LocalVariableInfo var = localVariableTableEntry.getVariable(pc+len, varIndex);
+ if (var == null){
+ System.out.println("Screwed!");
+ }
+ instruction.setLocalVariableInfo(var);
+ }
+
+ }
+ return (pcMap);
+ }
+
+ public Collection getInstructions(){
+ return (getInstructionMap().values());
+ }
+
+ public int getInstructionCount(){
+ return getInstructionMap().size();
}
}
@@ -2411,50 +2670,23 @@ public String toString() {
class ClassModelInterface{
private int interfaceIndex;
- ClassModelInterface(ByteReader _byteReader) {
+ ClassModelInterface(ByteReader _byteReader){
interfaceIndex = _byteReader.u2();
}
- ConstantPool.ClassEntry getClassEntry() {
+ ConstantPool.ClassEntry getClassEntry(){
return (constantPool.getClassEntry(interfaceIndex));
}
- int getInterfaceIndex() {
+ int getInterfaceIndex(){
return (interfaceIndex);
}
}
- private Class> clazz;
-
- /**
- * We extract the class's classloader and name and delegate to private parse method.
- * @param _class The class we wish to model
- * @throws ClassParseException
- */
- void parse(Class> _class) throws ClassParseException {
-
- clazz = _class;
- parse(_class.getClassLoader(), _class.getName());
- }
-
- /**
- * Populate this model by parsing a given classfile from the given classloader.
- *
- * We create a ByteReader (wrapper around the bytes representing the classfile) and pass it to local inner classes to handle the various sections of the class file.
- *
- * @see ByteReader
- * @see Java 5 Class File Format
- * @param _classLoader The classloader to access the classfile
- * @param _className The name of the class to load (we convert '.' to '/' and append ".class" so you don't have to).
- * @throws ClassParseException
- */
- private void parse(ClassLoader _classLoader, String _className) throws ClassParseException {
- parse(_classLoader.getResourceAsStream(_className.replace('.', '/') + ".class"));
-
- }
+ //private Class> clazz;
- void parse(InputStream _inputStream) throws ClassParseException {
+ void parse(InputStream _inputStream) throws ClassParseException{
ByteReader byteReader = new ByteReader(_inputStream);
magic = byteReader.u4();
@@ -2467,21 +2699,21 @@ void parse(InputStream _inputStream) throws ClassParseException {
superClassConstantPoolIndex = byteReader.u2();
int interfaceCount = byteReader.u2();
- for (int i = 0; i < interfaceCount; i++) {
+ for (int i = 0; i getFieldPoolEntries() {
+ public List getMethods(){
+ return (methods);
+ }
+
+ List getFieldPoolEntries(){
return (fields);
}
/**
- * Look up a ConstantPool MethodEntry and return the corresponding Method.
- *
+ * Look up a ConstantPool MethodEntry and return the corresponding Method.
+ *
* @param _methodEntry The ConstantPool MethodEntry we want.
- * @param _isSpecial True if we wish to delegate to super (to support super.foo())
- *
+ * @param _isSpecial True if we wish to delegate to super (to support super.foo())
* @return The Method or null if we fail to locate a given method.
*/
- ClassModelMethod getMethod(MethodEntry _methodEntry, boolean _isSpecial) {
- String entryClassNameInDotForm = _methodEntry.getClassEntry().getNameUTF8Entry().getUTF8().replace('/', '.');
+ ClassModelMethod getMethod(MethodEntry _methodEntry, boolean _isSpecial){
+ String entryClassNameInDotForm = _methodEntry.getClassEntry().getDotClassName();
- // Shortcut direct calls to supers to allow "foo() { super.foo() }" type stuff to work
- if (_isSpecial && (superClazz != null) && superClazz.isSuperClass(entryClassNameInDotForm)) {
- if (logger.isLoggable(Level.FINE)) {
- logger.fine("going to look in super:" + superClazz.getClassWeAreModelling().getName() + " on behalf of "
- + entryClassNameInDotForm);
+ // Shortcut direct calls to supers to allow "foo() { super.foo() }" prefix stuff to work
+ if (_isSpecial && (superClazzModel != null) && superClazzModel.isSuperClass(entryClassNameInDotForm)){
+ if (logger.isLoggable(Level.FINE)){
+ logger.fine("going to look in super:"+superClazzModel.getDotClassName()+" on behalf of "
+ +entryClassNameInDotForm);
}
- return superClazz.getMethod(_methodEntry, false);
+ return superClazzModel.getMethod(_methodEntry, false);
}
- for (ClassModelMethod entry : methods) {
- if (entry.getName().equals(_methodEntry.getNameAndTypeEntry().getNameUTF8Entry().getUTF8())
- && entry.getDescriptor().equals(_methodEntry.getNameAndTypeEntry().getDescriptorUTF8Entry().getUTF8())) {
- if (logger.isLoggable(Level.FINE)) {
- logger.fine("Found " + clazz.getName() + "." + entry.getName() + " " + entry.getDescriptor() + " for "
- + entryClassNameInDotForm);
+ for (ClassModelMethod entry : methods){
+ if (entry.getName().equals(_methodEntry.getNameAndTypeEntry().getName())
+ && entry.getDescriptor().equals(_methodEntry.getNameAndTypeEntry().getDescriptor())){
+ if (logger.isLoggable(Level.FINE)){
+ logger.fine("Found "+getDotClassName()
+ +"."+entry.getName()+" "+entry.getDescriptor()+" for "
+ +entryClassNameInDotForm);
}
return (entry);
}
}
- return superClazz != null ? superClazz.getMethod(_methodEntry, false) : (null);
+ return superClazzModel != null?superClazzModel.getMethod(_methodEntry, false):(null);
}
/**
* Create a MethodModel for a given method name and signature.
- *
+ *
* @param _name
* @param _signature
- * @return
+ * @return
* @throws AparapiException
*/
- MethodModel getMethodModel(String _name, String _signature) throws AparapiException {
+ public MethodModel getMethodModel(String _name, String _signature) throws AparapiException{
ClassModelMethod method = getMethod(_name, _signature);
- return new MethodModel(method);
+ return MethodModel.getMethodModel(method);
}
// These fields use for accessor conversion
@@ -2611,40 +2847,89 @@ MethodModel getMethodModel(String _name, String _signature) throws AparapiExcept
private int totalStructSize = 0;
- ArrayList getStructMembers() {
+ ArrayList getStructMembers(){
return structMembers;
}
- ArrayList getStructMemberOffsets() {
+ ArrayList getStructMemberOffsets(){
return structMemberOffsets;
}
- ArrayList getStructMemberTypes() {
+ ArrayList getStructMemberTypes(){
return structMemberTypes;
}
- int getTotalStructSize() {
+ int getTotalStructSize(){
return totalStructSize;
}
- void setTotalStructSize(int x) {
+ void setTotalStructSize(int x){
totalStructSize = x;
}
- Entrypoint getEntrypoint(String _entrypointName, String _descriptor, Object _k) throws AparapiException {
+ Entrypoint getLambdaEntrypoint(String _entrypointName, String _descriptor, Object _k) throws AparapiException{
+ MethodModel method = getMethodModel(_entrypointName, _descriptor);
+ return (Entrypoint.getEntryPoint(this, method, _k, true));
+ }
+
+ public Entrypoint getKernelEntrypoint(String _entrypointName, String _descriptor, Object _k) throws AparapiException{
MethodModel method = getMethodModel(_entrypointName, _descriptor);
- return (new Entrypoint(this, method, _k));
+ return (Entrypoint.getEntryPoint(this, method, _k, false));
}
- Class> getClassWeAreModelling() {
+ Class> getClassWeAreModelling(){
return clazz;
}
- public Entrypoint getEntrypoint(String _entrypointName, Object _k) throws AparapiException {
- return (getEntrypoint(_entrypointName, "()V", _k));
+ public Entrypoint getKernelEntrypoint(String _entrypointName, Object _k) throws AparapiException{
+ return (getKernelEntrypoint(_entrypointName, "()V", _k));
+ }
+
+ public Entrypoint getLambdaEntrypoint(String _entrypointName, Object _k) throws AparapiException{
+ return (getLambdaEntrypoint(_entrypointName, "()V", _k));
+ }
+
+ public Entrypoint getKernelEntrypoint() throws AparapiException{
+ return (getKernelEntrypoint("run", "()V", null));
+ }
+
+ public Entrypoint getLambdaEntrypoint() throws AparapiException{
+ return (getLambdaEntrypoint("run", "()V", null));
+ }
+
+ public String getClassName(){
+ ConstantPool.ClassEntry thisClassEntry = constantPool.getClassEntry(getThisClassConstantPoolIndex());
+ return (thisClassEntry.getClassName());
+ }
+
+ public JavaType getClassType(){
+ ConstantPool.ClassEntry thisClassEntry = constantPool.getClassEntry(getThisClassConstantPoolIndex());
+ return (thisClassEntry.getType());
+ }
+
+ public String getDotClassName(){
+ ConstantPool.ClassEntry thisClassEntry = constantPool.getClassEntry(getThisClassConstantPoolIndex());
+ return (thisClassEntry.getDotClassName());
+ }
+
+ public String getMangledClassName(){
+
+ ConstantPool.ClassEntry thisClassEntry = constantPool.getClassEntry(getThisClassConstantPoolIndex());
+ return (thisClassEntry.getMangledClassName());
+ }
+
+ public String getSuperClassName(){
+ ConstantPool.ClassEntry superClassEntry = constantPool.getClassEntry(getSuperClassConstantPoolIndex());
+ return (superClassEntry.getClassName());
}
- public Entrypoint getEntrypoint() throws AparapiException {
- return (getEntrypoint("run", "()V", null));
+ public String getSuperDotClassName(){
+ int superClassConstantPoolIndex = getSuperClassConstantPoolIndex();
+ ConstantPool.ClassEntry superClassEntry = constantPool.getClassEntry(superClassConstantPoolIndex);
+ if (superClassEntry == null){
+ superClassEntry = superClassEntry;
+ }
+ return (superClassEntry.getDotClassName());
}
+
}
diff --git a/com.amd.aparapi/src/java/com/amd/aparapi/ClassParseException.java b/com.amd.aparapi/src/java/com/amd/aparapi/ClassParseException.java
index c375baff..35890896 100644
--- a/com.amd.aparapi/src/java/com/amd/aparapi/ClassParseException.java
+++ b/com.amd.aparapi/src/java/com/amd/aparapi/ClassParseException.java
@@ -38,16 +38,15 @@ to national security controls as identified on the Commerce Control List (curren
package com.amd.aparapi;
/**
- * We throw ClassParseExceptions (derived from AparapiException) if we encounter any Aparapi unfriendly
+ * We throw ClassParseExceptions (derived from AparapiException) if we encounter any Aparapi unfriendly
* constructs. This allows us to fail fast.
- *
- * @see com.amd.aparapi.AparapiException
*
* @author gfrost
- *
+ * @see com.amd.aparapi.AparapiException
*/
-@SuppressWarnings("serial") public class ClassParseException extends AparapiException{
- public static enum TYPE {
+@SuppressWarnings("serial")
+public class ClassParseException extends AparapiException{
+ public static enum TYPE{
NONE("none"), //
ARRAY_RETURN("We don't support areturn instructions"), //
PUTFIELD("We don't support putstatic instructions"), //
@@ -56,21 +55,21 @@ public static enum TYPE {
ATHROW("We don't support athrow instructions"), //
SYNCHRONIZE("We don't support monitorenter or monitorexit instructions"), //
NEW("We don't support new instructions"), //
- ARRAYALIAS("We don't support copying refs in kernels"), //
+ ARRAYALIAS("We don't support copying refs in lambdaRunnerCache"), //
SWITCH("We don't support lookupswitch or tableswitch instructions"), //
METHODARRAYARG("We don't support passing arrays as method args"), //
RECURSION("We don't support recursion"), //
UNSUPPORTEDBYTECODE("This bytecode is not supported"), //
OPERANDCONSUMERPRODUCERMISSMATCH("Detected an non-reducable operand consumer/producer mismatch"), //
- BADGETTERTYPEMISMATCH("Getter return type does not match field var type"), //
+ BADGETTERTYPEMISMATCH("Getter return prefix does not match field var prefix"), //
BADGETTERNAMEMISMATCH("Getter name does not match fiels name"), //
BADGETTERNAMENOTFOUND("Getter not found"), //
- BADSETTERTYPEMISMATCH("Setter arg type does not match field var type"), //
+ BADSETTERTYPEMISMATCH("Setter arg prefix does not match field var prefix"), //
EXCEPTION("We don't support catch blocks"), //
ARRAYLOCALVARIABLE("Found an array local variable which assumes that we will alias a field array"), //
CONFUSINGBRANCHESPOSSIBLYCONTINUE("we don't support continue"), //
CONFUSINGBRANCHESPOSSIBLYBREAK("we don't support break"), //
- OBJECTFIELDREFERENCE("Using java objects inside kernels is not supported"), //
+ OBJECTFIELDREFERENCE("Using java objects inside lambdaRunnerCache is not supported"), //
OBJECTARRAYFIELDREFERENCE("Object array elements cannot contain"), //
OVERRIDENFIELD("Found overidden field"), //
LOCALARRAYLENGTHACCESS("Found array length access on local array. Might be a result of using ForEach()"), //
@@ -80,50 +79,53 @@ public static enum TYPE {
ACCESSEDOBJECTSETTERARRAY("Passing array arguments to Intrinsics in expression form is not supported"), //
MULTIDIMENSIONARRAYASSIGN("Can't assign to two dimension array"), //
MULTIDIMENSIONARRAYACCESS("Can't access through a two dimensional array"), //
- MISSINGLOCALVARIABLETABLE("Method does not contain a local variable table (recompile with -g?)");
+ MISSINGLOCALVARIABLETABLE("Method does not contain a local variable table (recompile with -g?)"),
+ UNHANDLEDMAPPEDMETHOD("Unhandled JDK mapped method ");
private String description;
- TYPE(final String _description) {
+ TYPE(final String _description){
description = _description;
}
- public String getDescription() {
+ public String getDescription(){
return (description);
}
- };
+ }
+
+ ;
Instruction instruction;
TYPE type;
- ClassParseException(final TYPE _type) {
+ ClassParseException(final TYPE _type){
super(_type.getDescription());
type = _type;
instruction = null;
}
- ClassParseException(final Instruction _instruction, final TYPE _type) {
- super("@" + _instruction.getThisPC() + " " + _instruction.getByteCode() + " " + _type.getDescription());
+ ClassParseException(final Instruction _instruction, final TYPE _type){
+ super("@"+_instruction.getThisPC()+" "+_instruction.getByteCode()+" "+_type.getDescription());
type = _type;
instruction = _instruction;
}
- ClassParseException(final TYPE _type, final String _methodName) {
- super("@" + _methodName + " " + _type.getDescription());
+ ClassParseException(final TYPE _type, final String _methodName){
+ super("@"+_methodName+" "+_type.getDescription());
type = _type;
instruction = null;
}
- public Instruction getInstruction() {
+ public Instruction getInstruction(){
return (instruction);
}
- public TYPE getType() {
+ public TYPE getType(){
return (type);
}
- ClassParseException(final Throwable _t) {
+ ClassParseException(final Throwable _t){
super(_t);
}
}
diff --git a/com.amd.aparapi/src/java/com/amd/aparapi/CodeGenException.java b/com.amd.aparapi/src/java/com/amd/aparapi/CodeGenException.java
index 920cad2d..02e9e5dd 100644
--- a/com.amd.aparapi/src/java/com/amd/aparapi/CodeGenException.java
+++ b/com.amd.aparapi/src/java/com/amd/aparapi/CodeGenException.java
@@ -37,13 +37,14 @@ to national security controls as identified on the Commerce Control List (curren
*/
package com.amd.aparapi;
-@SuppressWarnings("serial") class CodeGenException extends AparapiException{
+@SuppressWarnings("serial")
+public class CodeGenException extends AparapiException{
- CodeGenException(String msg) {
+ CodeGenException(String msg){
super(msg);
}
- CodeGenException(Throwable t) {
+ CodeGenException(Throwable t){
super(t);
}
}
diff --git a/com.amd.aparapi/src/java/com/amd/aparapi/Config.java b/com.amd.aparapi/src/java/com/amd/aparapi/Config.java
index f45c3f8e..e6dd2807 100644
--- a/com.amd.aparapi/src/java/com/amd/aparapi/Config.java
+++ b/com.amd.aparapi/src/java/com/amd/aparapi/Config.java
@@ -37,20 +37,19 @@ to national security controls as identified on the Commerce Control List (curren
*/
package com.amd.aparapi;
+import com.amd.aparapi.Annotations.UsedByJNICode;
+
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.Logger;
-import com.amd.aparapi.KernelRunner.UsedByJNICode;
-
/**
- * A central location for holding all runtime configurable properties as well as logging configuration.
- *
+ * OREF central location for holding all runtime configurable properties as well as logging configuration.
+ *
* Ideally we will find all properties used by Aparapi here. Please consider updating this class if you wish
- * to add new properties which control Aparapis behavior.
+ * to add new properties which control Aparapis behavior.
*
* @author gfrost
- *
*/
class Config{
@@ -58,185 +57,223 @@ class Config{
/**
* Allows the user to request to use a jvmti agent to access JNI code rather than loading explicitly.
- *
+ *
* Usage -agentpath=/full/path/to/agent.dll -Dcom.amd.aparapi.useAgent=true
*/
-
- static final boolean useAgent = Boolean.getBoolean(propPkgName + ".useAgent");
- static final boolean disableUnsafe = Boolean.getBoolean(propPkgName + ".disableUnsafe");
+ static final boolean useAgent = Boolean.getBoolean(propPkgName+".useAgent");
+
+ static final boolean disableUnsafe = Boolean.getBoolean(propPkgName+".disableUnsafe");
/**
* Allows the user to request a specific Kernel.EXECUTION_MODE enum value for all Kernels.
- *
- * Usage -Dcom.amd.aparapi.executionMode={SEQ|JTP|CPU|GPU}
- *
- * @see com.amd.aparapi.Kernel.EXECUTION_MODE
+ *
+ * Usage -Dcom.amd.aparapi.executionMode={SEQ|JTP|CPU|GPU}
+ *
+ * @see com.amd.aparapi.Kernel.EXECUTION_MODE
*/
- static final String executionMode = System.getProperty(propPkgName + ".executionMode");
+ static final String executionMode = System.getProperty(propPkgName+".executionMode");
/**
* Allows the user to turn on OpenCL profiling for the JNI/OpenCL layer.
- *
- * Usage -Dcom.amd.aparapi.enableProfiling={true|false}
- *
+ *
+ * Usage -Dcom.amd.aparapi.enableProfiling={true|false}
*/
- @UsedByJNICode static final boolean enableProfiling = Boolean.getBoolean(propPkgName + ".enableProfiling");
+ @UsedByJNICode
+ static final boolean enableProfiling = Boolean.getBoolean(propPkgName+".enableProfiling");
/**
* Allows the user to turn on OpenCL profiling for the JNI/OpenCL layer, this information will be written to CSV file
- *
- * Usage -Dcom.amd.aparapi.enableProfiling={true|false}
- *
+ *
+ * Usage -Dcom.amd.aparapi.enableProfiling={true|false}
*/
- @UsedByJNICode static final boolean enableProfilingCSV = Boolean.getBoolean(propPkgName + ".enableProfilingCSV");
+ @UsedByJNICode
+ static final boolean enableProfilingCSV = Boolean.getBoolean(propPkgName+".enableProfilingCSV");
/**
* Allows the user to request that verbose JNI messages be dumped to stderr.
- *
- * Usage -Dcom.amd.aparapi.enableVerboseJNI={true|false}
- *
+ *
+ * Usage -Dcom.amd.aparapi.enableVerboseJNI={true|false}
*/
- @UsedByJNICode static final boolean enableVerboseJNI = Boolean.getBoolean(propPkgName + ".enableVerboseJNI");
+ @UsedByJNICode
+ static final boolean enableVerboseJNI = Boolean.getBoolean(propPkgName+".enableVerboseJNI");
/**
- * Allows the user to request tracking of opencl resources.
- *
- * This is really a debugging option to help locate leaking OpenCL resources, this will be dumped to stderr.
- *
- * Usage -Dcom.amd.aparapi.enableOpenCLResourceTracking={true|false}
- *
+ * Allows the user to request tracking of opencl resources.
+ *
+ * This is really a debugging option to help locate leaking OpenCL resources, this will be dumped to stderr.
+ *
+ * Usage -Dcom.amd.aparapi.enableOpenCLResourceTracking={true|false}
*/
- @UsedByJNICode static final boolean enableVerboseJNIOpenCLResourceTracking = Boolean.getBoolean(propPkgName
- + ".enableVerboseJNIOpenCLResourceTracking");
+ @UsedByJNICode
+ static final boolean enableVerboseJNIOpenCLResourceTracking = Boolean.getBoolean(propPkgName
+ +".enableVerboseJNIOpenCLResourceTracking");
/**
* Allows the user to request that the execution mode of each kernel invocation be reported to stdout.
- *
- * Usage -Dcom.amd.aparapi.enableExecutionModeReporting={true|false}
- *
+ *
+ * Usage -Dcom.amd.aparapi.enableExecutionModeReporting={true|false}
+ */
+ static final boolean enableExecutionModeReporting = Boolean.getBoolean(propPkgName+".enableExecutionModeReporting");
+
+ /**
+ * Allows the user to request OKRA coherence mode (true|false).
+ *
+ * Usage -Dcom.amd.aparapi.enableSetOKRACoherence={true|false}
*/
- static final boolean enableExecutionModeReporting = Boolean.getBoolean(propPkgName + ".enableExecutionModeReporting");
+ static final boolean enableSetOKRACoherence = Boolean.getBoolean(propPkgName+".enableSetOKRACoherence");
/**
* Allows the user to request that generated OpenCL code is dumped to standard out.
- *
- * Usage -Dcom.amd.aparapi.enableShowGeneratedOpenCL={true|false}
- *
+ *
+ * Usage -Dcom.amd.aparapi.enableShowGeneratedOpenCL={true|false}
+ */
+ static final boolean enableShowGeneratedOpenCL = Boolean.getBoolean(propPkgName+".enableShowGeneratedOpenCL");
+
+ /**
+ * Allows the user to request that generated HSAIL code is dumped to standard out.
+ *
+ * Usage -Dcom.amd.aparapi.enableShowGeneratedHSAIL={true|false}
*/
- static final boolean enableShowGeneratedOpenCL = Boolean.getBoolean(propPkgName + ".enableShowGeneratedOpenCL");
+ static final boolean enableShowGeneratedHSAIL = Boolean.getBoolean(propPkgName+".enableShowGeneratedHSAIL");
+
+ /**
+ * Allows the user to request that generated HSAIL code is dumped to standard out.
+ *
+ * Usage -Dcom.amd.aparapi.enableShowGeneratedHSAIL={true|false}
+ */
+ static final boolean enableShowGeneratedHSAILAndExit = Boolean.getBoolean(propPkgName+".enableShowGeneratedHSAILAndExit");
// Pragma/OpenCL codegen related flags
- static final boolean enableAtomic32 = Boolean.getBoolean(propPkgName + ".enableAtomic32");
+ static final boolean enableAtomic32 = Boolean.getBoolean(propPkgName+".enableAtomic32");
- static final boolean enableAtomic64 = Boolean.getBoolean(propPkgName + ".enableAtomic64");
+ static final boolean enableAtomic64 = Boolean.getBoolean(propPkgName+".enableAtomic64");
- static final boolean enableByteWrites = Boolean.getBoolean(propPkgName + ".enableByteWrites");
+ static final boolean enableByteWrites = Boolean.getBoolean(propPkgName+".enableByteWrites");
- public static final boolean enableDoubles = Boolean.getBoolean(propPkgName + ".enableDoubles");
+ public static final boolean enableDoubles = Boolean.getBoolean(propPkgName+".enableDoubles");
// Debugging related flags
- static final boolean verboseComparitor = Boolean.getBoolean(propPkgName + ".verboseComparitor");
+ static final boolean verboseComparitor = Boolean.getBoolean(propPkgName+".verboseComparitor");
- static final boolean dumpFlags = Boolean.getBoolean(propPkgName + ".dumpFlags");
+ static final boolean dumpFlags = Boolean.getBoolean(propPkgName+".dumpFlags");
// Individual bytecode support related flags
- static final boolean enablePUTFIELD = Boolean.getBoolean(propPkgName + ".enable.PUTFIELD");
+ static final boolean enablePUTFIELD = Boolean.getBoolean(propPkgName+".enable.PUTFIELD");
+
+ static final boolean enableARETURN = !Boolean.getBoolean(propPkgName+".disable.ARETURN");
+
+ static final boolean enablePUTSTATIC = Boolean.getBoolean(propPkgName+".enable.PUTSTATIC");
- static final boolean enableARETURN = !Boolean.getBoolean(propPkgName + ".disable.ARETURN");
+ // Allow static array accesses
+ static final boolean enableGETSTATIC = true; //Boolean.getBoolean(propPkgName + ".enable.GETSTATIC");
- static final boolean enablePUTSTATIC = Boolean.getBoolean(propPkgName + ".enable.PUTSTATIC");
+ static final boolean enableINVOKEINTERFACE = Boolean.getBoolean(propPkgName+".enable.INVOKEINTERFACE");
- static final boolean enableGETSTATIC = Boolean.getBoolean(propPkgName + ".enable.GETSTATIC");
+ static final boolean enableMONITOR = Boolean.getBoolean(propPkgName+".enable.MONITOR");
- static final boolean enableINVOKEINTERFACE = Boolean.getBoolean(propPkgName + ".enable.INVOKEINTERFACE");
+ static final boolean enableNEW = Boolean.getBoolean(propPkgName+".enable.NEW");
- static final boolean enableMONITOR = Boolean.getBoolean(propPkgName + ".enable.MONITOR");
+ static final boolean enableATHROW = Boolean.getBoolean(propPkgName+".enable.ATHROW");
- static final boolean enableNEW = Boolean.getBoolean(propPkgName + ".enable.NEW");
+ static final boolean enableMETHODARRAYPASSING = !Boolean.getBoolean(propPkgName+".disable.METHODARRAYPASSING");
- static final boolean enableATHROW = Boolean.getBoolean(propPkgName + ".enable.ATHROW");
+ static final boolean enableARRAYLENGTH = Boolean.getBoolean(propPkgName+".enable.ARRAYLENGTH");
- static final boolean enableMETHODARRAYPASSING = !Boolean.getBoolean(propPkgName + ".disable.METHODARRAYPASSING");
+ static final boolean enableSWITCH = Boolean.getBoolean(propPkgName+".enable.SWITCH");
- static final boolean enableARRAYLENGTH = Boolean.getBoolean(propPkgName + ".enable.ARRAYLENGTH");
+ //public static boolean enableAlwaysCreateFakeLocalVariableTable = Boolean.getBoolean(propPkgName + ".enableAlwaysCreateFakeLocalVariableTable");
- static final boolean enableSWITCH = Boolean.getBoolean(propPkgName + ".enable.SWITCH");
+ // public static boolean enableUseRealLocalVariableTableIfAvailable = Boolean.getBoolean(propPkgName + ".enableUseRealLocalVariableTableIfAvailable");
- public static boolean enableShowFakeLocalVariableTable = Boolean.getBoolean(propPkgName + ".enableShowFakeLocalVariableTable");
+ public static boolean enableShowLocalVariableTable = Boolean.getBoolean(propPkgName+".enableShowLocalVariableTable");
+ public static boolean enableShowJavaP = Boolean.getBoolean(propPkgName+".enableShowJavaP");
+
+ //public static boolean enableShowRealLocalVariableTable = Boolean.getBoolean(propPkgName + ".enableRealFakeLocalVariableTable");
+
+ public static boolean enableOptimizeRegMoves = Boolean.getBoolean(propPkgName+".enableOptimizeRegMoves");
// Logging setup
- private static final String logPropName = propPkgName + ".logLevel";
+ private static final String logPropName = propPkgName+".logLevel";
- static String getLoggerName() {
+ static String getLoggerName(){
return logPropName;
}
static Logger logger = Logger.getLogger(Config.getLoggerName());
- static {
- try {
+ static{
+
+ try{
Level level = Level.parse(System.getProperty(getLoggerName(), "WARNING"));
Handler[] handlers = Logger.getLogger("").getHandlers();
- for (int index = 0; index < handlers.length; index++) {
+ for (int index = 0; index instructionListenerClass = Class.forName(instructionListenerClassName);
- instructionListener = (InstructionListener) instructionListenerClass.newInstance();
- } catch (ClassNotFoundException e) {
+ instructionListener = (InstructionListener)instructionListenerClass.newInstance();
+ }catch (ClassNotFoundException e){
// TODO Auto-generated catch block
e.printStackTrace();
- } catch (InstantiationException e) {
+ }catch (InstantiationException e){
// TODO Auto-generated catch block
e.printStackTrace();
- } catch (IllegalAccessException e) {
+ }catch (IllegalAccessException e){
// TODO Auto-generated catch block
e.printStackTrace();
}
}
- if (dumpFlags) {
-
- System.out.println(propPkgName + ".executionMode{GPU|CPU|JTP|SEQ}=" + executionMode);
- System.out.println(propPkgName + ".logLevel{OFF|FINEST|FINER|FINE|WARNING|SEVERE|ALL}=" + logger.getLevel());
- System.out.println(propPkgName + ".enableProfiling{true|false}=" + enableProfiling);
- System.out.println(propPkgName + ".enableProfilingCSV{true|false}=" + enableProfilingCSV);
- System.out.println(propPkgName + ".enableVerboseJNI{true|false}=" + enableVerboseJNI);
- System.out.println(propPkgName + ".enableVerboseJNIOpenCLResourceTracking{true|false}="
- + enableVerboseJNIOpenCLResourceTracking);
- System.out.println(propPkgName + ".enableShowGeneratedOpenCL{true|false}=" + enableShowGeneratedOpenCL);
- System.out.println(propPkgName + ".enableExecutionModeReporting{true|false}=" + enableExecutionModeReporting);
- System.out.println(propPkgName + ".enableInstructionDecodeViewer{true|false}=" + enableInstructionDecodeViewer);
+ if (dumpFlags){
+
+ System.out.println(propPkgName+".executionMode{GPU|CPU|JTP|SEQ}="+executionMode);
+ System.out.println(propPkgName+".logLevel{OFF|FINEST|FINER|FINE|WARNING|SEVERE|ALL}="+logger.getLevel());
+ System.out.println(propPkgName+".enableProfiling{true|false}="+enableProfiling);
+ System.out.println(propPkgName+".enableProfilingCSV{true|false}="+enableProfilingCSV);
+ System.out.println(propPkgName+".enableVerboseJNI{true|false}="+enableVerboseJNI);
+ System.out.println(propPkgName+".enableVerboseJNIOpenCLResourceTracking{true|false}="
+ +enableVerboseJNIOpenCLResourceTracking);
+ System.out.println(propPkgName+".enableShowGeneratedOpenCL{true|false}="+enableShowGeneratedOpenCL);
+ System.out.println(propPkgName+".enableShowGeneratedHSAIL{true|false}="+enableShowGeneratedHSAIL);
+ System.out.println(propPkgName+".enableShowGeneratedHSAILAndExit{true|false}="+enableShowGeneratedHSAILAndExit);
+ System.out.println(propPkgName+".enableShowJavaP{true|false}="+enableShowJavaP);
+ System.out.println(propPkgName+".enableSetOKRACoherence{true|false}="+enableSetOKRACoherence);
+ System.out.println(propPkgName+".enableExecutionModeReporting{true|false}="+enableExecutionModeReporting);
+ // System.out.println(propPkgName + ".enableUseRealLocalVariableTableIfAvailable{true|false}="+enableUseRealLocalVariableTableIfAvailable);
+ System.out.println(propPkgName+".enableShowLocalVariableTable{true|false}="+enableShowLocalVariableTable);
+ System.out.println(propPkgName+".enableInstructionDecodeViewer{true|false}="+enableInstructionDecodeViewer);
System.out.println(propPkgName
- + ".instructionListenerClassName{}="
- + instructionListenerClassName);
+ +".instructionListenerClassName{}="
+ +instructionListenerClassName);
}
}
diff --git a/com.amd.aparapi/src/java/com/amd/aparapi/DeprecatedException.java b/com.amd.aparapi/src/java/com/amd/aparapi/DeprecatedException.java
index 70ca856e..36146175 100644
--- a/com.amd.aparapi/src/java/com/amd/aparapi/DeprecatedException.java
+++ b/com.amd.aparapi/src/java/com/amd/aparapi/DeprecatedException.java
@@ -37,9 +37,10 @@ to national security controls as identified on the Commerce Control List (curren
*/
package com.amd.aparapi;
-@SuppressWarnings("serial") class DeprecatedException extends AparapiException{
+@SuppressWarnings("serial")
+class DeprecatedException extends AparapiException{
- DeprecatedException(String msg) {
+ DeprecatedException(String msg){
super(msg);
}
diff --git a/com.amd.aparapi/src/java/com/amd/aparapi/Device.java b/com.amd.aparapi/src/java/com/amd/aparapi/Device.java
index 39161560..f3640226 100644
--- a/com.amd.aparapi/src/java/com/amd/aparapi/Device.java
+++ b/com.amd.aparapi/src/java/com/amd/aparapi/Device.java
@@ -3,28 +3,48 @@
import com.amd.aparapi.OpenCLDevice.DeviceComparitor;
import com.amd.aparapi.OpenCLDevice.DeviceSelector;
-public abstract class Device{
- static public enum TYPE {
+public abstract class Device{
+
+ public static Device getByName(String _deviceName){
+ TYPE type = TYPE.valueOf(_deviceName.toUpperCase());
+ return (_deviceName.equals("hsa")?Device.hsa():
+ (_deviceName.equals("jtp")?Device.jtp():
+ (_deviceName.equals("seq")?Device.seq():
+ (_deviceName.equals("hyb")?Device.hyb():
+ (_deviceName.equals("best")?Device.best():
+ null)
+ )
+ )
+ )
+ );
+ }
+
+ static public enum TYPE{
UNKNOWN,
GPU,
CPU,
JTP,
- SEQ
- };
+ HSA,
+ SEQ,
+ HYB
+ }
+
+ ;
- public static Device best() {
+ public static Device best(){
return (OpenCLDevice.select(new DeviceComparitor(){
- @Override public OpenCLDevice select(OpenCLDevice _deviceLhs, OpenCLDevice _deviceRhs) {
- if (_deviceLhs.getType() != _deviceRhs.getType()) {
- if (_deviceLhs.getType() == TYPE.GPU) {
+ @Override
+ public OpenCLDevice select(OpenCLDevice _deviceLhs, OpenCLDevice _deviceRhs){
+ if (_deviceLhs.getType() != _deviceRhs.getType()){
+ if (_deviceLhs.getType() == TYPE.GPU){
return (_deviceLhs);
- } else {
+ }else{
return (_deviceRhs);
}
}
- if (_deviceLhs.getMaxComputeUnits() > _deviceRhs.getMaxComputeUnits()) {
+ if (_deviceLhs.getMaxComputeUnits()>_deviceRhs.getMaxComputeUnits()){
return (_deviceLhs);
- } else {
+ }else{
return (_deviceRhs);
}
@@ -32,90 +52,115 @@ public static Device best() {
}));
}
- public static Device first(final Device.TYPE _type) {
+ public static Device first(final Device.TYPE _type){
return (OpenCLDevice.select(new DeviceSelector(){
- @Override public OpenCLDevice select(OpenCLDevice _device) {
- return (_device.getType() == _type ? _device : null);
+ @Override
+ public OpenCLDevice select(OpenCLDevice _device){
+ return (_device.getType() == _type?_device:null);
}
}));
}
- public static Device firstGPU() {
+ public static Device firstGPU(){
return (first(Device.TYPE.GPU));
}
- public static Device firstCPU() {
+ public static Device firstCPU(){
return (first(Device.TYPE.CPU));
}
+ public static JavaThreadPoolDevice jtp(){
+ return (new JavaThreadPoolDevice());
+
+ }
+
+ public static JavaSequentialDevice seq(){
+ return (new JavaSequentialDevice());
+
+ }
+
+ public static HybridDevice hyb(){
+ return (new HybridDevice());
+
+ }
+
+ public static HSADevice hsa(){
+ return (new HSADevice());
+
+ }
+
protected TYPE type = TYPE.UNKNOWN;
protected int maxWorkGroupSize;
protected int maxWorkItemDimensions;
- protected int[] maxWorkItemSize = new int[] {
+ protected int[] maxWorkItemSize = new int[]{
0,
0,
0
};
- public TYPE getType() {
+ public TYPE getType(){
return type;
}
- public void setType(TYPE type) {
+ public void setType(TYPE type){
this.type = type;
}
- public int getMaxWorkItemDimensions() {
+ public int getMaxWorkItemDimensions(){
return maxWorkItemDimensions;
}
- public void setMaxWorkItemDimensions(int _maxWorkItemDimensions) {
+ public void setMaxWorkItemDimensions(int _maxWorkItemDimensions){
maxWorkItemDimensions = _maxWorkItemDimensions;
}
- public int getMaxWorkGroupSize() {
+ public int getMaxWorkGroupSize(){
return maxWorkGroupSize;
}
- public void setMaxWorkGroupSize(int _maxWorkGroupSize) {
+ public void setMaxWorkGroupSize(int _maxWorkGroupSize){
maxWorkGroupSize = _maxWorkGroupSize;
}
- public int[] getMaxWorkItemSize() {
+ public int[] getMaxWorkItemSize(){
return maxWorkItemSize;
}
- public void setMaxWorkItemSize(int[] maxWorkItemSize) {
+ public void setMaxWorkItemSize(int[] maxWorkItemSize){
this.maxWorkItemSize = maxWorkItemSize;
}
- public Range createRange(int _globalWidth) {
+ public Range createRange(int _globalWidth){
return (Range.create(this, _globalWidth));
}
- public Range createRange(int _globalWidth, int _localWidth) {
+ public Range createRange(int _globalWidth, int _localWidth){
return (Range.create(this, _globalWidth, _localWidth));
}
- public Range createRange2D(int _globalWidth, int _globalHeight) {
+ public Range createRange2D(int _globalWidth, int _globalHeight){
return (Range.create2D(this, _globalWidth, _globalHeight));
}
- public Range createRange2D(int _globalWidth, int _globalHeight, int _localWidth, int _localHeight) {
+ public Range createRange2D(int _globalWidth, int _globalHeight, int _localWidth, int _localHeight){
return (Range.create2D(this, _globalWidth, _globalHeight, _localWidth, _localHeight));
}
- public Range createRange3D(int _globalWidth, int _globalHeight, int _globalDepth) {
+ public Range createRange3D(int _globalWidth, int _globalHeight, int _globalDepth){
return (Range.create3D(this, _globalWidth, _globalHeight, _globalDepth));
}
public Range createRange3D(int _globalWidth, int _globalHeight, int _globalDepth, int _localWidth, int _localHeight,
- int _localDepth) {
+ int _localDepth){
return (Range.create3D(this, _globalWidth, _globalHeight, _globalDepth, _localWidth, _localHeight, _localDepth));
}
+ public abstract void forEach(int range, Aparapi.IntTerminal ic);
+
+ public abstract void forEach(int from, int to, Aparapi.IntTerminal ic);
+
}
diff --git a/com.amd.aparapi/src/java/com/amd/aparapi/Entrypoint.java b/com.amd.aparapi/src/java/com/amd/aparapi/Entrypoint.java
index 34868697..bb90da23 100644
--- a/com.amd.aparapi/src/java/com/amd/aparapi/Entrypoint.java
+++ b/com.amd.aparapi/src/java/com/amd/aparapi/Entrypoint.java
@@ -37,26 +37,10 @@ to national security controls as identified on the Commerce Control List (curren
*/
package com.amd.aparapi;
-import java.lang.reflect.Field;
-import java.lang.reflect.Modifier;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.Comparator;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.LinkedHashMap;
-import java.util.LinkedHashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.logging.Level;
-import java.util.logging.Logger;
-
import com.amd.aparapi.ClassModel.ClassModelField;
import com.amd.aparapi.ClassModel.ClassModelMethod;
import com.amd.aparapi.ClassModel.ConstantPool.FieldEntry;
import com.amd.aparapi.ClassModel.ConstantPool.MethodEntry;
-import com.amd.aparapi.ClassModel.ConstantPool.MethodReferenceEntry.Arg;
import com.amd.aparapi.InstructionSet.AccessArrayElement;
import com.amd.aparapi.InstructionSet.AccessField;
import com.amd.aparapi.InstructionSet.AssignToArrayElement;
@@ -70,7 +54,46 @@ to national security controls as identified on the Commerce Control List (curren
import com.amd.aparapi.InstructionSet.TypeSpec;
import com.amd.aparapi.InstructionSet.VirtualMethodCall;
-class Entrypoint{
+import java.lang.reflect.Field;
+import java.lang.reflect.Modifier;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.LinkedHashMap;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
+public class Entrypoint{
+
+ static final Map map = new HashMap();
+
+ static synchronized Entrypoint getEntryPoint(
+ ClassModel _classModel, MethodModel _methodModel, Object _kernelInstance, boolean _isLambda) throws AparapiException{
+ Entrypoint entrypoint = map.get(_methodModel.getMethod());
+ if (entrypoint == null){
+ entrypoint = new Entrypoint(_classModel, _methodModel, _kernelInstance, _isLambda, false);
+ map.put(_methodModel.getMethod(), entrypoint);
+ }else{
+ System.out.println("not new!");
+ }
+ return (entrypoint);
+ }
+
+ private boolean isLambda;
+
+ public boolean isLambda(){
+ return (isLambda);
+ }
+
+ public boolean isKernel(){
+ return (!isLambda);
+ }
private static Logger logger = Logger.getLogger(Config.getLoggerName());
@@ -104,60 +127,71 @@ class Entrypoint{
private MethodModel methodModel;
/**
- True is an indication to use the fp64 pragma
- */
+ * True is an indication to use the fp64 pragma
+ */
private boolean usesDoubles;
/**
- True is an indication to use the byte addressable store pragma
- */
+ * True is an indication to use the byte addressable array_store pragma
+ */
private boolean usesByteWrites;
/**
- True is an indication to use the atomics pragmas
- */
+ * True is an indication to use the atomics pragmas
+ */
private boolean usesAtomic32;
private boolean usesAtomic64;
- boolean requiresDoublePragma() {
+ boolean requiresDoublePragma(){
return usesDoubles;
}
- boolean requiresByteAddressableStorePragma() {
+ boolean requiresByteAddressableStorePragma(){
return usesByteWrites;
}
/* Atomics are detected in Entrypoint */
- void setRequiresAtomics32Pragma(boolean newVal) {
+ void setRequiresAtomics32Pragma(boolean newVal){
usesAtomic32 = newVal;
}
- void setRequiresAtomics64Pragma(boolean newVal) {
+ void setRequiresAtomics64Pragma(boolean newVal){
usesAtomic64 = newVal;
}
- boolean requiresAtomic32Pragma() {
+ boolean requiresAtomic32Pragma(){
return usesAtomic32;
}
- boolean requiresAtomic64Pragma() {
+ boolean requiresAtomic64Pragma(){
return usesAtomic64;
}
- Object getKernelInstance() {
+ Object getKernelInstance(){
return kernelInstance;
}
- void setKernelInstance(Object _k) {
+ void setKernelInstance(Object _k){
kernelInstance = _k;
}
- Map getObjectArrayFieldsClasses() {
+ int lambdaActualParamsCount = 0;
+
+ // This could be done by parsing the signature
+ void setLambdaActualParamsCount(int count){
+ lambdaActualParamsCount = count;
+ }
+
+ int getLambdaActualParamsCount(){
+ return lambdaActualParamsCount;
+ }
+
+ Map getObjectArrayFieldsClasses(){
return objectArrayFieldsClasses;
}
- static Field getFieldFromClassHierarchy(Class> _clazz, String _name) throws AparapiException {
+ static Field getFieldFromClassHierarchy(Class> _clazz, String _name) throws AparapiException{
// look in self
// if found, done
@@ -172,58 +206,61 @@ static Field getFieldFromClassHierarchy(Class> _clazz, String _name) throws Ap
Field field = null;
- assert _name != null : "_name should not be null";
+ assert _name != null:"_name should not be null";
- if (logger.isLoggable(Level.FINE)) {
- logger.fine("looking for " + _name + " in " + _clazz.getName());
+ if (logger.isLoggable(Level.FINE)){
+ logger.fine("looking for "+_name+" in "+_clazz.getName());
}
- try {
+ try{
field = _clazz.getDeclaredField(_name);
Class> type = field.getType();
- if (type.isPrimitive() || type.isArray()) {
+ if (type.isPrimitive() || type.isArray()){
return field;
}
- if (logger.isLoggable(Level.FINE)) {
- logger.fine("field type is " + type.getName());
+ if (logger.isLoggable(Level.FINE)){
+ logger.fine("field prefix is "+type.getName());
}
throw new ClassParseException(ClassParseException.TYPE.OBJECTFIELDREFERENCE);
- } catch (NoSuchFieldException nsfe) {
+ }catch (NoSuchFieldException nsfe){
// This should be looger fine...
- //System.out.println("no " + _name + " in " + _clazz.getName());
+ //System.out.println("no " + _name + " in " + _clazz.getHSAName());
}
Class> mySuper = _clazz.getSuperclass();
- if (logger.isLoggable(Level.FINE)) {
- logger.fine("looking for " + _name + " in " + mySuper.getName());
+ if (logger.isLoggable(Level.FINE)){
+ logger.fine("looking for "+_name+" in "+mySuper.getName());
}
- // Find better way to do this check
- while (!mySuper.getName().equals(Kernel.class.getName())) {
- try {
+ assert _clazz != null && mySuper != null:"Classes should not be null";
+
+ // For the jambi demo, we are not operating on Kernel subclass, keep looking
+ while ((!mySuper.getName().equals(Object.class.getName())) /* &&
+ (!mySuper.getHSAName().equals(Kernel.class.getHSAName())) */){
+ try{
field = mySuper.getDeclaredField(_name);
int modifiers = field.getModifiers();
- if ((Modifier.isStatic(modifiers) == false) && (Modifier.isPrivate(modifiers) == false)) {
+ if ((Modifier.isStatic(modifiers) == false) && (Modifier.isPrivate(modifiers) == false)){
Class> type = field.getType();
- if (logger.isLoggable(Level.FINE)) {
- logger.fine("field type is " + type.getName());
+ if (logger.isLoggable(Level.FINE)){
+ logger.fine("field prefix is "+type.getName());
}
- if (type.isPrimitive() || type.isArray()) {
+ if (type.isPrimitive() || type.isArray()){
return field;
}
throw new ClassParseException(ClassParseException.TYPE.OBJECTFIELDREFERENCE);
- } else {
+ }else{
// This should be looger fine...
//System.out.println("field " + _name + " not suitable: " + java.lang.reflect.Modifier.toString(modifiers));
return null;
}
- } catch (NoSuchFieldException nsfe) {
- if (logger.isLoggable(Level.FINE)) {
- logger.fine("no " + _name + " in " + mySuper.getName());
+ }catch (NoSuchFieldException nsfe){
+ if (logger.isLoggable(Level.FINE)){
+ logger.fine("no "+_name+" in "+mySuper.getName());
}
mySuper = mySuper.getSuperclass();
- assert mySuper != null : "mySuper is null!";
+ assert mySuper != null:"mySuper is null!";
}
}
return null;
@@ -231,46 +268,53 @@ static Field getFieldFromClassHierarchy(Class> _clazz, String _name) throws Ap
/*
* Update the list of object array member classes and all the superclasses
- * of those classes and the fields in each class.
- *
+ * of those classes and the fields in each class.
+ *
* It is important to have only one ClassModel for each class used in the kernel
* and only one MethodModel per method, so comparison operations work properly.
+ *
+ * The className param is in dot form, not slashes
*/
- ClassModel getOrUpdateAllClassAccesses(String className) throws AparapiException {
+ ClassModel getOrUpdateAllClassAccesses(String className) throws AparapiException{
ClassModel memberClassModel = allFieldsClasses.get(className);
- if (memberClassModel == null) {
- try {
+ if (memberClassModel == null){
+ try{
Class> memberClass = Class.forName(className);
+ // Quick and dirty way to bail out from unhandled Math methods etc
+ if (className.startsWith("java.lang")){
+ throw new ClassParseException(ClassParseException.TYPE.UNHANDLEDMAPPEDMETHOD);
+ }
+
// Immediately add this class and all its supers if necessary
- memberClassModel = new ClassModel(memberClass);
- if (logger.isLoggable(Level.FINEST)) {
- logger.finest("adding class " + className);
+ memberClassModel = ClassModel.getClassModel(memberClass);
+ if (logger.isLoggable(Level.FINEST)){
+ logger.finest("adding class "+className);
}
allFieldsClasses.put(className, memberClassModel);
- ClassModel superModel = memberClassModel.getSuperClazz();
- while (superModel != null) {
+ ClassModel superModel = memberClassModel.getSuperClazzModel();
+ while (superModel != null){
// See if super is already added
- ClassModel oldSuper = allFieldsClasses.get(superModel.getClassWeAreModelling().getName());
- if (oldSuper != null) {
- if (oldSuper != superModel) {
+ ClassModel oldSuper = allFieldsClasses.get(superModel.getDotClassName());
+ if (oldSuper != null){
+ if (oldSuper != superModel){
memberClassModel.replaceSuperClazz(oldSuper);
- if (logger.isLoggable(Level.FINEST)) {
- logger.finest("replaced super " + oldSuper.getClassWeAreModelling().getName() + " for " + className);
+ if (logger.isLoggable(Level.FINEST)){
+ logger.finest("replaced super "+oldSuper.getDotClassName()+" for "+className);
}
}
- } else {
- allFieldsClasses.put(superModel.getClassWeAreModelling().getName(), superModel);
- if (logger.isLoggable(Level.FINEST)) {
- logger.finest("add new super " + superModel.getClassWeAreModelling().getName() + " for " + className);
+ }else{
+ allFieldsClasses.put(superModel.getDotClassName(), superModel);
+ if (logger.isLoggable(Level.FINEST)){
+ logger.finest("add new super "+superModel.getDotClassName()+" for "+className);
}
}
- superModel = superModel.getSuperClazz();
+ superModel = superModel.getSuperClazzModel();
}
- } catch (Exception e) {
- if (logger.isLoggable(Level.INFO)) {
- logger.info("Cannot find: " + className);
+ }catch (Exception e){
+ if (logger.isLoggable(Level.INFO)){
+ logger.info("Cannot find: "+className);
}
throw new AparapiException(e);
}
@@ -279,21 +323,21 @@ ClassModel getOrUpdateAllClassAccesses(String className) throws AparapiException
return memberClassModel;
}
- ClassModelMethod resolveAccessorCandidate(MethodCall _methodCall, MethodEntry _methodEntry) throws AparapiException {
- String methodsActualClassName = (_methodEntry.getClassEntry().getNameUTF8Entry().getUTF8()).replace('/', '.');
+ ClassModelMethod resolveAccessorCandidate(MethodCall _methodCall, MethodEntry _methodEntry) throws AparapiException{
+ String methodsActualDotClassName = _methodEntry.getClassEntry().getDotClassName();
- if (_methodCall instanceof VirtualMethodCall) {
- Instruction callInstance = ((VirtualMethodCall) _methodCall).getInstanceReference();
- if (callInstance instanceof AccessArrayElement) {
- AccessArrayElement arrayAccess = (AccessArrayElement) callInstance;
+ if (_methodCall instanceof VirtualMethodCall){
+ Instruction callInstance = ((VirtualMethodCall)_methodCall).getInstanceReference();
+ if (callInstance instanceof AccessArrayElement){
+ AccessArrayElement arrayAccess = (AccessArrayElement)callInstance;
Instruction refAccess = arrayAccess.getArrayRef();
- if (refAccess instanceof I_GETFIELD) {
+ if (refAccess instanceof I_GETFIELD){
// It is a call from a member obj array element
- if (logger.isLoggable(Level.FINE)) {
- logger.fine("Looking for class in accessor call: " + methodsActualClassName);
+ if (logger.isLoggable(Level.FINE)){
+ logger.fine("Looking for class in accessor call: "+methodsActualDotClassName);
}
- ClassModel memberClassModel = getOrUpdateAllClassAccesses(methodsActualClassName);
+ ClassModel memberClassModel = getOrUpdateAllClassAccesses(methodsActualDotClassName);
// false = no invokespecial allowed here
return memberClassModel.getMethod(_methodEntry, false);
@@ -304,66 +348,66 @@ ClassModelMethod resolveAccessorCandidate(MethodCall _methodCall, MethodEntry _m
}
/*
- * Update accessor structures when there is a direct access to an
+ * Update accessor structures when there is a direct access to an
* obect array element's data members
*/
- void updateObjectMemberFieldAccesses(String className, FieldEntry field) throws AparapiException {
+ void updateObjectMemberFieldAccesses(String className, FieldEntry field) throws AparapiException{
String accessedFieldName = field.getNameAndTypeEntry().getNameUTF8Entry().getUTF8();
// Quickly bail if it is a ref
if (field.getNameAndTypeEntry().getDescriptorUTF8Entry().getUTF8().startsWith("L")
- || field.getNameAndTypeEntry().getDescriptorUTF8Entry().getUTF8().startsWith("[L")) {
+ || field.getNameAndTypeEntry().getDescriptorUTF8Entry().getUTF8().startsWith("[L")){
throw new ClassParseException(ClassParseException.TYPE.OBJECTARRAYFIELDREFERENCE);
}
- if (logger.isLoggable(Level.FINEST)) {
- logger.finest("Updating access: " + className + " field:" + accessedFieldName);
+ if (logger.isLoggable(Level.FINEST)){
+ logger.finest("Updating access: "+className+" field:"+accessedFieldName);
}
ClassModel memberClassModel = getOrUpdateAllClassAccesses(className);
- Class> memberClass = memberClassModel.getClassWeAreModelling();
+ //Class> memberClass = memberClassModel.getClassWeAreModelling();
ClassModel superCandidate = null;
// We may add this field if no superclass match
boolean add = true;
// No exact match, look for a superclass
- for (ClassModel c : allFieldsClasses.values()) {
- if (logger.isLoggable(Level.FINEST)) {
- logger.finest(" super: " + c.getClassWeAreModelling().getName() + " for " + className);
+ for (ClassModel c : allFieldsClasses.values()){
+ if (logger.isLoggable(Level.FINEST)){
+ logger.finest(" super: "+c.getDotClassName()+" for "+className);
}
- if (c.isSuperClass(memberClass)) {
- if (logger.isLoggable(Level.FINE)) {
- logger.fine("selected super: " + c.getClassWeAreModelling().getName() + " for " + className);
+ if (c.isSuperClass(memberClassModel)){
+ if (logger.isLoggable(Level.FINE)){
+ logger.fine("selected super: "+c.getDotClassName()+" for "+className);
}
superCandidate = c;
break;
}
- if (logger.isLoggable(Level.FINEST)) {
- logger.finest(" no super match for " + memberClass.getName());
+ if (logger.isLoggable(Level.FINEST)){
+ logger.finest(" no super match for "+memberClassModel.getDotClassName());
}
}
// Look at super's fields for a match
- if (superCandidate != null) {
+ if (superCandidate != null){
ArrayList structMemberSet = superCandidate.getStructMembers();
- for (FieldEntry f : structMemberSet) {
+ for (FieldEntry f : structMemberSet){
if (f.getNameAndTypeEntry().getNameUTF8Entry().getUTF8().equals(accessedFieldName)
&& f.getNameAndTypeEntry().getDescriptorUTF8Entry().getUTF8()
- .equals(field.getNameAndTypeEntry().getDescriptorUTF8Entry().getUTF8())) {
+ .equals(field.getNameAndTypeEntry().getDescriptorUTF8Entry().getUTF8())){
- if (logger.isLoggable(Level.FINE)) {
- logger.fine("Found match: " + accessedFieldName + " class: " + field.getClassEntry().getNameUTF8Entry().getUTF8()
- + " to class: " + f.getClassEntry().getNameUTF8Entry().getUTF8());
+ if (logger.isLoggable(Level.FINE)){
+ logger.fine("Found match: "+accessedFieldName+" class: "+field.getClassEntry().getNameUTF8Entry().getUTF8()
+ +" to class: "+f.getClassEntry().getNameUTF8Entry().getUTF8());
}
- if (!f.getClassEntry().getNameUTF8Entry().getUTF8().equals(field.getClassEntry().getNameUTF8Entry().getUTF8())) {
+ if (!f.getClassEntry().getNameUTF8Entry().getUTF8().equals(field.getClassEntry().getNameUTF8Entry().getUTF8())){
// Look up in class hierarchy to ensure it is the same field
Field superField = getFieldFromClassHierarchy(superCandidate.getClassWeAreModelling(), f.getNameAndTypeEntry()
.getNameUTF8Entry().getUTF8());
- Field classField = getFieldFromClassHierarchy(memberClass, f.getNameAndTypeEntry().getNameUTF8Entry().getUTF8());
- if (!superField.equals(classField)) {
+ Field classField = getFieldFromClassHierarchy(memberClassModel.getClassWeAreModelling(), f.getNameAndTypeEntry().getNameUTF8Entry().getUTF8());
+ if (!superField.equals(classField)){
throw new ClassParseException(ClassParseException.TYPE.OVERRIDENFIELD);
}
}
@@ -376,137 +420,137 @@ void updateObjectMemberFieldAccesses(String className, FieldEntry field) throws
// There was no matching field in the supers, add it to the memberClassModel
// if not already there
- if (add) {
+ if (add){
boolean found = false;
ArrayList structMemberSet = memberClassModel.getStructMembers();
- for (FieldEntry f : structMemberSet) {
+ for (FieldEntry f : structMemberSet){
if (f.getNameAndTypeEntry().getNameUTF8Entry().getUTF8().equals(accessedFieldName)
&& f.getNameAndTypeEntry().getDescriptorUTF8Entry().getUTF8()
- .equals(field.getNameAndTypeEntry().getDescriptorUTF8Entry().getUTF8())) {
+ .equals(field.getNameAndTypeEntry().getDescriptorUTF8Entry().getUTF8())){
found = true;
}
}
- if (!found) {
+ if (!found){
structMemberSet.add(field);
- if (logger.isLoggable(Level.FINE)) {
- logger.fine("Adding assigned field " + field.getNameAndTypeEntry().getNameUTF8Entry().getUTF8() + " type: "
- + field.getNameAndTypeEntry().getDescriptorUTF8Entry().getUTF8() + " to "
- + memberClassModel.getClassWeAreModelling().getName());
+ if (logger.isLoggable(Level.FINE)){
+ logger.fine("Adding assigned field "+field.getNameAndTypeEntry().getNameUTF8Entry().getUTF8()+" prefix: "
+ +field.getNameAndTypeEntry().getDescriptorUTF8Entry().getUTF8()+" to "
+ +memberClassModel.getDotClassName());
}
}
}
}
-
+
/*
* Find a suitable call target in the kernel class, supers, object members or static calls
*/
- ClassModelMethod resolveCalledMethod(MethodCall methodCall, ClassModel classModel) throws AparapiException {
+ ClassModelMethod resolveCalledMethod(MethodCall methodCall, ClassModel classModel) throws AparapiException{
MethodEntry methodEntry = methodCall.getConstantPoolMethodEntry();
int thisClassIndex = classModel.getThisClassConstantPoolIndex();//arf
boolean isMapped = (thisClassIndex != methodEntry.getClassIndex()) && Kernel.isMappedMethod(methodEntry);
- if (logger.isLoggable(Level.FINE)) {
- if (methodCall instanceof I_INVOKESPECIAL) {
- logger.fine("Method call to super: " + methodEntry);
- } else if (thisClassIndex != methodEntry.getClassIndex()) {
- logger.fine("Method call to ??: " + methodEntry + ", isMappedMethod=" + isMapped);
- } else {
- logger.fine("Method call in kernel class: " + methodEntry);
+ if (logger.isLoggable(Level.FINE)){
+ if (methodCall instanceof I_INVOKESPECIAL){
+ logger.fine("Method call to super: "+methodEntry);
+ }else if (thisClassIndex != methodEntry.getClassIndex()){
+ logger.fine("Method call to ??: "+methodEntry+", isMappedMethod="+isMapped);
+ }else{
+ logger.fine("Method call in kernel class: "+methodEntry);
}
}
- ClassModelMethod m = classModel.getMethod(methodEntry, (methodCall instanceof I_INVOKESPECIAL) ? true : false);
+ ClassModelMethod m = classModel.getMethod(methodEntry, (methodCall instanceof I_INVOKESPECIAL)?true:false);
// Did not find method in this class or supers. Look for data member object arrays
- if (m == null && !isMapped) {
+ if (m == null && !isMapped){
m = resolveAccessorCandidate(methodCall, methodEntry);
}
// Look for a intra-object call in a object member
- if (m == null && !isMapped) {
- for (ClassModel c : allFieldsClasses.values()) {
- if (c.getClassWeAreModelling().getName()
- .equals(methodEntry.getClassEntry().getNameUTF8Entry().getUTF8().replace('/', '.'))) {
- m = c.getMethod(methodEntry, (methodCall instanceof I_INVOKESPECIAL) ? true : false);
+ if (m == null && !isMapped){
+ for (ClassModel c : allFieldsClasses.values()){
+ if (c.getClassWeAreModelling().getName().equals(methodEntry.getClassEntry().getDotClassName())){
+ m = c.getMethod(methodEntry, (methodCall instanceof I_INVOKESPECIAL)?true:false);
assert m != null;
break;
}
}
}
-
+
// Look for static call to some other class
- if ((m == null) && !isMapped && (methodCall instanceof I_INVOKESTATIC)) {
- String otherClassName = methodEntry.getClassEntry().getNameUTF8Entry().getUTF8().replace('/', '.');
- ClassModel otherClassModel = getOrUpdateAllClassAccesses(otherClassName);
-
+ if ((m == null) && !isMapped && (methodCall instanceof I_INVOKESTATIC)){
+ String otherDotClassName = methodEntry.getClassEntry().getDotClassName();
+ ClassModel otherClassModel = getOrUpdateAllClassAccesses(otherDotClassName);
+
//if (logger.isLoggable(Level.FINE)) {
- // logger.fine("Looking for: " + methodEntry + " in other class " + otherClass.getName());
+ // logger.fine("Looking for: " + methodEntry + " in other class " + otherClass.getHSAName());
//}
- // false because INVOKESPECIAL not allowed here
+ // false because INVOKESPECIAL not allowed here
m = otherClassModel.getMethod(methodEntry, false);
}
- if (logger.isLoggable(Level.INFO)) {
- logger.fine("Selected method for: " + methodEntry + " is " + m);
+ if (logger.isLoggable(Level.INFO)){
+ logger.fine("Selected method for: "+methodEntry+" is "+m);
}
-
+
return m;
}
- Entrypoint(ClassModel _classModel, MethodModel _methodModel, Object _k) throws AparapiException {
+ Entrypoint(ClassModel _classModel, MethodModel _methodModel, Object _kernelInstance, boolean _isLambda, boolean junk) throws AparapiException{
+ isLambda = _isLambda;
classModel = _classModel;
methodModel = _methodModel;
- kernelInstance = _k;
+ kernelInstance = _kernelInstance;
Map methodMap = new LinkedHashMap();
boolean discovered = true;
// Record which pragmas we need to enable
- if (methodModel.requiresDoublePragma()) {
+ if (methodModel.requiresDoublePragma()){
usesDoubles = true;
- if (logger.isLoggable(Level.FINE)) {
- logger.fine("Enabling doubles on " + methodModel.getName());
+ if (logger.isLoggable(Level.FINE)){
+ logger.fine("Enabling doubles on "+methodModel.getName());
}
}
- if (methodModel.requiresByteAddressableStorePragma()) {
+ if (methodModel.requiresByteAddressableStorePragma()){
usesByteWrites = true;
- if (logger.isLoggable(Level.FINE)) {
- logger.fine("Enabling byte addressable on " + methodModel.getName());
+ if (logger.isLoggable(Level.FINE)){
+ logger.fine("Enabling byte addressable on "+methodModel.getName());
}
}
// Collect all methods called directly from kernel's run method
- for (MethodCall methodCall : methodModel.getMethodCalls()) {
+ for (MethodCall methodCall : methodModel.getMethod().getMethodCalls()){
ClassModelMethod m = resolveCalledMethod(methodCall, classModel);
- if (m != null && !methodMap.keySet().contains(m)) {
+ if (m != null && !methodMap.keySet().contains(m)){
MethodModel target = new MethodModel(m, this);
methodMap.put(m, target);
methodModel.getCalledMethods().add(target);
discovered = true;
- }
+ }
}
// methodMap now contains a list of method called by run itself().
// Walk the whole graph of called methods and add them to the methodMap
- while (!fallback && discovered) {
+ while (!fallback && discovered){
discovered = false;
- for (MethodModel mm : new ArrayList(methodMap.values())) {
- for (MethodCall methodCall : mm.getMethodCalls()) {
+ for (MethodModel mm : new ArrayList(methodMap.values())){
+ for (MethodCall methodCall : mm.getMethod().getMethodCalls()){
ClassModelMethod m = resolveCalledMethod(methodCall, classModel);
- if (m != null) {
+ if (m != null){
MethodModel target = null;
- if (methodMap.keySet().contains(m)) {
- // we remove and then add again. Because this is a LinkedHashMap this
+ if (methodMap.keySet().contains(m)){
+ // we remove and then add again. Because this is a LinkedHashMap this
// places this at the end of the list underlying the map
- // then when we reverse the collection (below) we get the method
+ // then when we reverse the collection (below) we get the method
// declarations in the correct order. We are trying to avoid creating forward references
target = methodMap.remove(m);
- if (logger.isLoggable(Level.FINEST)) {
- logger.fine("repositioning : " + m.getClassModel().getClassWeAreModelling().getName() + " " + m.getName()
- + " " + m.getDescriptor());
+ if (logger.isLoggable(Level.FINEST)){
+ logger.fine("repositioning : "+m.getClassModel().getDotClassName()+" "+m.getName()
+ +" "+m.getDescriptor());
}
- } else {
+ }else{
target = new MethodModel(m, this);
discovered = true;
}
@@ -520,11 +564,11 @@ ClassModelMethod resolveCalledMethod(MethodCall methodCall, ClassModel classMode
methodModel.checkForRecursion(new HashSet());
- if (logger.isLoggable(Level.FINE)) {
- logger.fine("fallback=" + fallback);
+ if (logger.isLoggable(Level.FINE)){
+ logger.fine("fallback="+fallback);
}
- if (!fallback) {
+ if (!fallback){
calledMethods.addAll(methodMap.values());
Collections.reverse(calledMethods);
List methods = new ArrayList(calledMethods);
@@ -535,151 +579,167 @@ ClassModelMethod resolveCalledMethod(MethodCall methodCall, ClassModel classMode
Set fieldAccesses = new HashSet();
- for (MethodModel methodModel : methods) {
+ for (MethodModel methodModel : methods){
// Record which pragmas we need to enable
- if (methodModel.requiresDoublePragma()) {
+ if (methodModel.requiresDoublePragma()){
usesDoubles = true;
- if (logger.isLoggable(Level.FINE)) {
- logger.fine("Enabling doubles on " + methodModel.getName());
+ if (logger.isLoggable(Level.FINE)){
+ logger.fine("Enabling doubles on "+methodModel.getName());
}
}
- if (methodModel.requiresByteAddressableStorePragma()) {
+ if (methodModel.requiresByteAddressableStorePragma()){
usesByteWrites = true;
- if (logger.isLoggable(Level.FINE)) {
- logger.fine("Enabling byte addressable on " + methodModel.getName());
+ if (logger.isLoggable(Level.FINE)){
+ logger.fine("Enabling byte addressable on "+methodModel.getName());
}
}
- for (Instruction instruction = methodModel.getPCHead(); instruction != null; instruction = instruction.getNextPC()) {
+ for (Instruction instruction : methodModel.getMethod().getInstructionMap().values()){
- if (instruction instanceof AssignToArrayElement) {
- AssignToArrayElement assignment = (AssignToArrayElement) instruction;
+ if (instruction instanceof AssignToArrayElement){
+ AssignToArrayElement assignment = (AssignToArrayElement)instruction;
Instruction arrayRef = assignment.getArrayRef();
- if (arrayRef instanceof I_GETFIELD) {
- I_GETFIELD getField = (I_GETFIELD) arrayRef;
+ // AccessField here allows instance and static array refs
+ if (isLambda && arrayRef instanceof I_GETFIELD){
+ I_GETFIELD getField = (I_GETFIELD)arrayRef;
+ FieldEntry field = getField.getConstantPoolFieldEntry();
+ String assignedArrayFieldName = field.getNameAndTypeEntry().getName();
+ arrayFieldAssignments.add(assignedArrayFieldName);
+ referencedFieldNames.add(assignedArrayFieldName);
+
+ }
+ if (!isLambda && arrayRef instanceof AccessField){
+ AccessField getField = (AccessField)arrayRef;
FieldEntry field = getField.getConstantPoolFieldEntry();
- String assignedArrayFieldName = field.getNameAndTypeEntry().getNameUTF8Entry().getUTF8();
+ String assignedArrayFieldName = field.getNameAndTypeEntry().getName();
arrayFieldAssignments.add(assignedArrayFieldName);
referencedFieldNames.add(assignedArrayFieldName);
}
- } else if (instruction instanceof AccessArrayElement) {
- AccessArrayElement access = (AccessArrayElement) instruction;
+ }else if (instruction instanceof AccessArrayElement){
+ AccessArrayElement access = (AccessArrayElement)instruction;
Instruction arrayRef = access.getArrayRef();
- if (arrayRef instanceof I_GETFIELD) {
- I_GETFIELD getField = (I_GETFIELD) arrayRef;
+ // AccessField here allows instance and static array refs
+
+ if (isLambda && arrayRef instanceof I_GETFIELD){
+ I_GETFIELD getField = (I_GETFIELD)arrayRef;
FieldEntry field = getField.getConstantPoolFieldEntry();
- String accessedArrayFieldName = field.getNameAndTypeEntry().getNameUTF8Entry().getUTF8();
+ String accessedArrayFieldName = field.getNameAndTypeEntry().getName();
arrayFieldAccesses.add(accessedArrayFieldName);
referencedFieldNames.add(accessedArrayFieldName);
}
- } else if (instruction instanceof I_ARRAYLENGTH) {
- if (!(instruction.getFirstChild() instanceof AccessField)) {
+ if (!isLambda && arrayRef instanceof AccessField){
+ arrayFieldAccesses.add(arrayRef.asFieldAccessor().getConstantPoolFieldEntry().getName());
+ referencedFieldNames.add(arrayRef.asFieldAccessor().getConstantPoolFieldEntry().getName());
+
+ }
+ }else if (instruction instanceof I_ARRAYLENGTH){
+ if (!(instruction.getFirstChild().isFieldAccessor())){
throw new ClassParseException(ClassParseException.TYPE.LOCALARRAYLENGTHACCESS);
}
- AccessField child = (AccessField) instruction.getFirstChild();
- String arrayName = child.getConstantPoolFieldEntry().getNameAndTypeEntry().getNameUTF8Entry().getUTF8();
+ String arrayName = instruction.getFirstChild().asFieldAccessor().getConstantPoolFieldEntry().getName();
arrayFieldArrayLengthUsed.add(arrayName);
- if (logger.isLoggable(Level.FINE)) {
- logger.fine("Noted arraylength in " + methodModel.getName() + " on " + arrayName);
+ if (logger.isLoggable(Level.FINE)){
+ logger.fine("Noted arraylength in "+methodModel.getName()+" on "+arrayName);
}
- } else if (instruction instanceof AccessField) {
- AccessField access = (AccessField) instruction;
+ }else if (instruction instanceof AccessField){
+ AccessField access = (AccessField)instruction;
FieldEntry field = access.getConstantPoolFieldEntry();
+ TypeHelper.JavaType accessedFieldType = field.getType();
String accessedFieldName = field.getNameAndTypeEntry().getNameUTF8Entry().getUTF8();
fieldAccesses.add(accessedFieldName);
referencedFieldNames.add(accessedFieldName);
- String signature = field.getNameAndTypeEntry().getDescriptorUTF8Entry().getUTF8();
- if (logger.isLoggable(Level.FINE)) {
- logger.fine("AccessField field type= " + signature + " in " + methodModel.getName());
+ // String signature = field.getNameAndTypeEntry().getDescriptorUTF8Entry().getUTF8();
+ if (logger.isLoggable(Level.FINE)){
+ logger.fine("AccessField field prefix= "+accessedFieldType+" in "+methodModel.getName());
}
// Add the class model for the referenced obj array
- if (signature.startsWith("[L")) {
+ if (accessedFieldType.isArray() && accessedFieldType.getArrayElementType().equals(PrimitiveType.ref)){ // is this a one dimension array of objects
// Turn [Lcom/amd/javalabs/opencl/demo/DummyOOA; into com.amd.javalabs.opencl.demo.DummyOOA for example
- String className = (signature.substring(2, signature.length() - 1)).replace("/", ".");
+ String className = accessedFieldType.getObjectClassName();
ClassModel arrayFieldModel = getOrUpdateAllClassAccesses(className);
- if (arrayFieldModel != null) {
- Class> memberClass = arrayFieldModel.getClassWeAreModelling();
- int modifiers = memberClass.getModifiers();
- if (!Modifier.isFinal(modifiers)) {
+ if (arrayFieldModel != null){
+ // Class> memberClass = arrayFieldModel.getClassWeAreModelling();
+ int modifiers = arrayFieldModel.getAccessFlags();
+ if (!Modifier.isFinal(modifiers)){
throw new ClassParseException(ClassParseException.TYPE.ACCESSEDOBJECTNONFINAL);
}
ClassModel refModel = objectArrayFieldsClasses.get(className);
- if (refModel == null) {
+ if (refModel == null){
// Verify no other member with common parent
- for (ClassModel memberObjClass : objectArrayFieldsClasses.values()) {
+ for (ClassModel memberObjClass : objectArrayFieldsClasses.values()){
ClassModel superModel = memberObjClass;
- while (superModel != null) {
- if (superModel.isSuperClass(memberClass)) {
+ while (superModel != null){
+ if (superModel.isSuperClass(arrayFieldModel)){
throw new ClassParseException(ClassParseException.TYPE.ACCESSEDOBJECTFIELDNAMECONFLICT);
}
- superModel = superModel.getSuperClazz();
+ superModel = superModel.getSuperClazzModel();
}
}
objectArrayFieldsClasses.put(className, arrayFieldModel);
- if (logger.isLoggable(Level.FINE)) {
- logger.fine("adding class to objectArrayFields: " + className);
+ if (logger.isLoggable(Level.FINE)){
+ logger.fine("adding class to objectArrayFields: "+className);
}
}
}
- } else {
- String className = (field.getClassEntry().getNameUTF8Entry().getUTF8()).replace("/", ".");
+ }else{
+ String dotClassName = (field.getClassEntry().getDotClassName());
// Look for object data member access
- if (!className.equals(this.getClassModel().getClassWeAreModelling().getName())
- && getFieldFromClassHierarchy(getClassModel().getClassWeAreModelling(), accessedFieldName) == null) {
- updateObjectMemberFieldAccesses(className, field);
+ if (!dotClassName.equals(this.getClassModel().getDotClassName())
+ && getFieldFromClassHierarchy(getClassModel().getClassWeAreModelling(), accessedFieldName) == null){
+ updateObjectMemberFieldAccesses(dotClassName, field);
}
}
- } else if (instruction instanceof AssignToField) {
- AssignToField assignment = (AssignToField) instruction;
+ }else if (instruction instanceof AssignToField){
+ AssignToField assignment = (AssignToField)instruction;
FieldEntry field = assignment.getConstantPoolFieldEntry();
String assignedFieldName = field.getNameAndTypeEntry().getNameUTF8Entry().getUTF8();
fieldAssignments.add(assignedFieldName);
referencedFieldNames.add(assignedFieldName);
- String className = (field.getClassEntry().getNameUTF8Entry().getUTF8()).replace("/", ".");
+ String dotClassName = field.getClassEntry().getDotClassName();
// Look for object data member access
- if (!className.equals(this.getClassModel().getClassWeAreModelling().getName())
- && getFieldFromClassHierarchy(getClassModel().getClassWeAreModelling(), assignedFieldName) == null) {
- updateObjectMemberFieldAccesses(className, field);
- } else {
+ if (!dotClassName.equals(this.getClassModel().getDotClassName())
+ && getFieldFromClassHierarchy(getClassModel().getClassWeAreModelling(), assignedFieldName) == null){
+ updateObjectMemberFieldAccesses(dotClassName, field);
+ }else{
- if ((!Config.enablePUTFIELD) && methodModel.methodUsesPutfield() && !methodModel.isSetter()) {
+ if ((!Config.enablePUTFIELD) && methodModel.methodUsesPutfield() && !methodModel.isSetter()){
throw new ClassParseException(ClassParseException.TYPE.ACCESSEDOBJECTONLYSUPPORTSSIMPLEPUTFIELD);
}
}
- } else if (instruction instanceof I_INVOKEVIRTUAL) {
- I_INVOKEVIRTUAL invokeInstruction = (I_INVOKEVIRTUAL) instruction;
+ }else if (instruction instanceof I_INVOKEVIRTUAL){
+ I_INVOKEVIRTUAL invokeInstruction = (I_INVOKEVIRTUAL)instruction;
MethodEntry methodEntry = invokeInstruction.getConstantPoolMethodEntry();
- if (Kernel.isMappedMethod(methodEntry)) { //only do this for intrinsics
+ if ((!isLambda && Kernel.isMappedMethod(methodEntry)) || (isLambda && KernelRunner.isMappedMethod(methodEntry))){ //only do this for intrinsics
- if (Kernel.usesAtomic32(methodEntry)) {
+ if (Kernel.usesAtomic32(methodEntry)){
setRequiresAtomics32Pragma(true);
}
- Arg methodArgs[] = methodEntry.getArgs();
- if (methodArgs.length > 0 && methodArgs[0].isArray()) { //currently array arg can only take slot 0
+ TypeHelper.JavaMethodArg methodArgs[] = methodEntry.getArgsAndReturnType().getArgs();
+ if (methodArgs.length>0 && methodArgs[0].getJavaType().isArray()){ //currently array arg can only take slot 0
Instruction arrInstruction = invokeInstruction.getArg(0);
- if (arrInstruction instanceof AccessField) {
- AccessField access = (AccessField) arrInstruction;
+ if (arrInstruction instanceof AccessField){
+ AccessField access = (AccessField)arrInstruction;
FieldEntry field = access.getConstantPoolFieldEntry();
String accessedFieldName = field.getNameAndTypeEntry().getNameUTF8Entry().getUTF8();
arrayFieldAssignments.add(accessedFieldName);
referencedFieldNames.add(accessedFieldName);
- } else {
+ }else{
throw new ClassParseException(ClassParseException.TYPE.ACCESSEDOBJECTSETTERARRAY);
}
}
@@ -689,76 +749,78 @@ && getFieldFromClassHierarchy(getClassModel().getClassWeAreModelling(), assigned
}
}
- for (String referencedFieldName : referencedFieldNames) {
+ for (String referencedFieldName : referencedFieldNames){
- try {
- Class> clazz = classModel.getClassWeAreModelling();
+ try{
+ Class> clazz = Class.forName(classModel.getDotClassName());
Field field = getFieldFromClassHierarchy(clazz, referencedFieldName);
- if (field != null) {
+ if (field != null){
referencedFields.add(field);
ClassModelField ff = classModel.getField(referencedFieldName);
- assert ff != null : "ff should not be null for " + clazz.getName() + "." + referencedFieldName;
+ assert ff != null:"ff should not be null for "+clazz.getName()+"."+referencedFieldName;
referencedClassModelFields.add(ff);
}
- } catch (SecurityException e) {
+ }catch (SecurityException e){
+ e.printStackTrace();
+ }catch (ClassNotFoundException e){
e.printStackTrace();
}
}
// Build data needed for oop form transforms if necessary
- if (!objectArrayFieldsClasses.keySet().isEmpty()) {
+ if (!objectArrayFieldsClasses.keySet().isEmpty()){
- for (ClassModel memberObjClass : objectArrayFieldsClasses.values()) {
+ for (ClassModel memberObjClass : objectArrayFieldsClasses.values()){
- // At this point we have already done the field override safety check, so
+ // At this point we have already done the field override safety check, so
// add all the superclass fields into the kernel member class to be
// sorted by size and emitted into the struct
- ClassModel superModel = memberObjClass.getSuperClazz();
- while (superModel != null) {
- if (logger.isLoggable(Level.FINEST)) {
- logger.finest("adding = " + superModel.getClassWeAreModelling().getName() + " fields into "
- + memberObjClass.getClassWeAreModelling().getName());
+ ClassModel superModel = memberObjClass.getSuperClazzModel();
+ while (superModel != null){
+ if (logger.isLoggable(Level.FINEST)){
+ logger.finest("adding = "+superModel.getDotClassName()+" fields into "
+ +memberObjClass.getDotClassName());
}
memberObjClass.getStructMembers().addAll(superModel.getStructMembers());
- superModel = superModel.getSuperClazz();
+ superModel = superModel.getSuperClazzModel();
}
}
// Sort fields of each class biggest->smallest
final Comparator fieldSizeComparator = new Comparator(){
- public int compare(FieldEntry aa, FieldEntry bb) {
+ public int compare(FieldEntry aa, FieldEntry bb){
String aType = aa.getNameAndTypeEntry().getDescriptorUTF8Entry().getUTF8();
String bType = bb.getNameAndTypeEntry().getDescriptorUTF8Entry().getUTF8();
// Booleans get converted down to bytes
- int aSize = InstructionSet.TypeSpec.valueOf(aType.equals("Z") ? "B" : aType).getSize();
- int bSize = InstructionSet.TypeSpec.valueOf(bType.equals("Z") ? "B" : bType).getSize();
+ int aSize = InstructionSet.TypeSpec.valueOf(aType).getPrimitiveType().getJavaBytes();
+ int bSize = InstructionSet.TypeSpec.valueOf(bType).getPrimitiveType().getJavaBytes();
- if (logger.isLoggable(Level.FINEST)) {
- logger.finest("aType= " + aType + " aSize= " + aSize + " . . bType= " + bType + " bSize= " + bSize);
+ if (logger.isLoggable(Level.FINEST)){
+ logger.finest("aType= "+aType+" aSize= "+aSize+" . . bType= "+bType+" bSize= "+bSize);
}
// Note this is sorting in reverse order so the biggest is first
- if (aSize > bSize) {
+ if (aSize>bSize){
return -1;
- } else if (aSize == bSize) {
+ }else if (aSize == bSize){
return 0;
- } else {
+ }else{
return 1;
}
}
};
- for (ClassModel c : objectArrayFieldsClasses.values()) {
+ for (ClassModel c : objectArrayFieldsClasses.values()){
ArrayList fields = c.getStructMembers();
- if (fields.size() > 0) {
+ if (fields.size()>0){
Collections.sort(fields, fieldSizeComparator);
// Now compute the total size for the struct
int totalSize = 0;
int alignTo = 0;
- for (FieldEntry f : fields) {
+ for (FieldEntry f : fields){
// Record field offset for use while copying
// Get field we will copy out of the kernel member object
Field rfield = getFieldFromClassHierarchy(c.getClassWeAreModelling(), f.getNameAndTypeEntry()
@@ -769,25 +831,25 @@ public int compare(FieldEntry aa, FieldEntry bb) {
String fType = f.getNameAndTypeEntry().getDescriptorUTF8Entry().getUTF8();
//c.getStructMemberTypes().add(TypeSpec.valueOf(fType.equals("Z") ? "B" : fType));
c.getStructMemberTypes().add(TypeSpec.valueOf(fType));
- int fSize = TypeSpec.valueOf(fType.equals("Z") ? "B" : fType).getSize();
- if (fSize > alignTo) {
+ int fSize = InstructionSet.TypeSpec.valueOf(fType).getPrimitiveType().getJavaBytes();
+ if (fSize>alignTo){
alignTo = fSize;
}
totalSize += fSize;
- if (logger.isLoggable(Level.FINEST)) {
- logger.finest("Field = " + f.getNameAndTypeEntry().getNameUTF8Entry().getUTF8() + " size=" + fSize
- + " totalSize=" + totalSize);
+ if (logger.isLoggable(Level.FINEST)){
+ logger.finest("Field = "+f.getNameAndTypeEntry().getNameUTF8Entry().getUTF8()+" size="+fSize
+ +" totalSize="+totalSize);
}
}
// compute total size for OpenCL buffer
int totalStructSize = 0;
- if (totalSize % alignTo == 0) {
+ if (totalSize%alignTo == 0){
totalStructSize = totalSize;
- } else {
+ }else{
// Pad up if necessary
- totalStructSize = ((totalSize / alignTo) + 1) * alignTo;
+ totalStructSize = ((totalSize/alignTo)+1)*alignTo;
}
c.setTotalStructSize(totalStructSize);
}
@@ -797,43 +859,43 @@ public int compare(FieldEntry aa, FieldEntry bb) {
}
}
- boolean shouldFallback() {
+ boolean shouldFallback(){
return (fallback);
}
- List getReferencedClassModelFields() {
+ List getReferencedClassModelFields(){
return (referencedClassModelFields);
}
- List getReferencedFields() {
+ List getReferencedFields(){
return (referencedFields);
}
- List getCalledMethods() {
+ List getCalledMethods(){
return calledMethods;
}
- Set getReferencedFieldNames() {
+ Set getReferencedFieldNames(){
return (referencedFieldNames);
}
- Set