diff --git a/pom.xml b/pom.xml index 68812b83..d809042d 100644 --- a/pom.xml +++ b/pom.xml @@ -20,8 +20,8 @@ UTF-8 - 1.7 - 1.7 + 1.8 + 1.8 Aparapi @@ -100,6 +100,10 @@ org.apache.maven.plugins maven-compiler-plugin + + 1.8 + 1.8 + org.apache.maven.plugins diff --git a/src/main/java/com/aparapi/Config.java b/src/main/java/com/aparapi/Config.java index 0986dcfd..eaaec5a6 100644 --- a/src/main/java/com/aparapi/Config.java +++ b/src/main/java/com/aparapi/Config.java @@ -56,6 +56,7 @@ to national security controls as identified on the Commerce Control List (curren import com.aparapi.internal.jni.*; import com.aparapi.internal.tool.*; +import java.lang.reflect.InvocationTargetException; import java.util.logging.*; /** @@ -141,7 +142,7 @@ public class Config extends ConfigJNI{ // Debugging related flags public static final boolean verboseComparitor = Boolean.getBoolean(propPkgName + ".verboseComparitor"); - public static final boolean dumpFlags = Boolean.getBoolean(propPkgName + ".dumpFlags"); + private static final boolean dumpFlags = Boolean.getBoolean(propPkgName + ".dumpFlags"); // Individual bytecode support related flags public static final boolean enablePUTFIELD = Boolean.getBoolean(propPkgName + ".enable.PUTFIELD"); @@ -169,11 +170,11 @@ public class Config extends ConfigJNI{ public static final boolean enableSWITCH = Boolean.getBoolean(propPkgName + ".enable.SWITCH"); - public static boolean enableShowFakeLocalVariableTable = Boolean.getBoolean(propPkgName + ".enableShowFakeLocalVariableTable"); + public static final boolean enableShowFakeLocalVariableTable = Boolean.getBoolean(propPkgName + ".enableShowFakeLocalVariableTable"); - public static final boolean enableInstructionDecodeViewer = Boolean.getBoolean(propPkgName + ".enableInstructionDecodeViewer"); + private static final boolean enableInstructionDecodeViewer = Boolean.getBoolean(propPkgName + ".enableInstructionDecodeViewer"); - public static String instructionListenerClassName = System.getProperty(propPkgName + ".instructionListenerClass"); + private static String instructionListenerClassName = System.getProperty(propPkgName + ".instructionListenerClass"); public static InstructionListener instructionListener = null; @@ -195,24 +196,18 @@ public interface InstructionListener{ System.out.println("Exception " + e + " in Aparapi logging setup"); e.printStackTrace(); } - }; + } - static { - if (enableInstructionDecodeViewer && ((instructionListenerClassName == null) || instructionListenerClassName.equals(""))) { + static { + if (enableInstructionDecodeViewer && ((instructionListenerClassName == null) || instructionListenerClassName.isEmpty())) { instructionListenerClassName = InstructionViewer.class.getName(); } - if ((instructionListenerClassName != null) && !instructionListenerClassName.equals("")) { + if ((instructionListenerClassName != null) && !instructionListenerClassName.isEmpty()) { try { final Class instructionListenerClass = Class.forName(instructionListenerClassName); - instructionListener = (InstructionListener) instructionListenerClass.newInstance(); - } catch (final ClassNotFoundException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (final InstantiationException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (final IllegalAccessException e) { + instructionListener = (InstructionListener) instructionListenerClass.getConstructor().newInstance(); + } catch (final ClassNotFoundException | IllegalAccessException | InstantiationException | InvocationTargetException | NoSuchMethodException e) { // TODO Auto-generated catch block e.printStackTrace(); } diff --git a/src/main/java/com/aparapi/Kernel.java b/src/main/java/com/aparapi/Kernel.java index 72bac0ca..34e45331 100644 --- a/src/main/java/com/aparapi/Kernel.java +++ b/src/main/java/com/aparapi/Kernel.java @@ -53,7 +53,11 @@ to national security controls as identified on the Commerce Control List (curren package com.aparapi; import com.aparapi.annotation.Experimental; +import com.aparapi.device.Device; +import com.aparapi.device.JavaDevice; +import com.aparapi.device.OpenCLDevice; import com.aparapi.exception.DeprecatedException; +import com.aparapi.internal.kernel.*; import com.aparapi.internal.model.CacheEnabler; import com.aparapi.internal.model.ClassModel.ConstantPool.MethodReferenceEntry; import com.aparapi.internal.model.ClassModel.ConstantPool.NameAndTypeEntry; @@ -61,36 +65,19 @@ to national security controls as identified on the Commerce Control List (curren import com.aparapi.internal.model.ValueCache.ThrowingValueComputer; import com.aparapi.internal.model.ValueCache.ValueComputer; import com.aparapi.internal.opencl.OpenCLLoader; +import com.aparapi.internal.util.Reflection; +import com.aparapi.internal.util.UnsafeWrapper; -import java.lang.annotation.Annotation; -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; +import java.lang.annotation.*; import java.lang.reflect.Method; -import java.util.ArrayDeque; -import java.util.Arrays; -import java.util.Collections; -import java.util.Deque; -import java.util.HashMap; -import java.util.Iterator; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Map; +import java.util.*; import java.util.concurrent.BrokenBarrierException; import java.util.concurrent.CyclicBarrier; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicIntegerArray; +import java.util.logging.Level; import java.util.logging.Logger; -import com.aparapi.device.Device; -import com.aparapi.device.JavaDevice; -import com.aparapi.device.OpenCLDevice; -import com.aparapi.internal.kernel.KernelArg; -import com.aparapi.internal.kernel.KernelManager; -import com.aparapi.internal.kernel.KernelProfile; -import com.aparapi.internal.kernel.KernelRunner; -import com.aparapi.internal.util.Reflection; -import com.aparapi.internal.util.UnsafeWrapper; - /** * A kernel encapsulates a data parallel algorithm that will execute either on a GPU * (through conversion to OpenCL) or on a CPU via a Java Thread Pool. @@ -109,7 +96,7 @@ to national security controls as identified on the Commerce Control List (curren *
    *
  1. Whether OpenCL is available (appropriate drivers are installed and the OpenCL and Aparapi dynamic libraries are included on the system path).
  2. *
  3. Whether the bytecode of the run() method (and every method that can be called directly or indirectly from the run() method) - * can be converted into OpenCL.
  4. + * can be converted into OpenCL. *
*

* Below is an example Kernel that calculates the square of a set of input values. @@ -154,12 +141,12 @@ to national security controls as identified on the Commerce Control List (curren * A different approach to creating kernels that avoids extending Kernel is to write an anonymous inner class: *

*

- *
+ * 

* final int[] values = new int[1024]; * // fill the values array * final int[] squares = new int[values.length]; * final Range range = Range.create(values.length); - * + *

* Kernel kernel = new Kernel(){ * public void run() { * int gid = getGlobalID(); @@ -170,559 +157,568 @@ to national security controls as identified on the Commerce Control List (curren * for (int i=0; i< values.length; i++){ * System.out.printf("%4d %4d %8d\n", i, values[i], squares[i]); * } - * + *

*

*

* - * @author gfrost AMD Javalabs + * @author gfrost AMD Javalabs * @version Alpha, 21/09/2010 */ public abstract class Kernel implements Cloneable { - private static Logger logger = Logger.getLogger(Config.getLoggerName()); - - /** - * We can use this Annotation to 'tag' intended local buffers. - * - * So we can either annotate the buffer - *


-    *  @Local int[] buffer = new int[1024];
-    *  
- * Or use a special suffix - *

-    *  int[] buffer_$local$ = new int[1024];
-    *  
- * - * @see #LOCAL_SUFFIX - * - * - */ - @Retention(RetentionPolicy.RUNTIME) - public @interface Local { - - } - - /** - * We can use this Annotation to 'tag' intended constant buffers. - * - * So we can either annotate the buffer - *

-    *  @Constant int[] buffer = new int[1024];
-    *  
- * Or use a special suffix - *

-    *  int[] buffer_$constant$ = new int[1024];
-    *  
- * - * @see #LOCAL_SUFFIX - * - * - */ - @Retention(RetentionPolicy.RUNTIME) - public @interface Constant { - - } - - /** - * - * We can use this Annotation to 'tag' __private (unshared) array fields. Data in the __private address space in OpenCL is accessible only from - * the current kernel instance. - * - * To so mark a field with a buffer size of 99, we can either annotate the buffer - *

-    *  @PrivateMemorySpace(99) int[] buffer = new int[99];
-    *  
- * Or use a special suffix - *

-    *  int[] buffer_$private$99 = new int[99];
-    *  
- * - *

Note that any code which must be runnable in {@link EXECUTION_MODE#JTP} will fail to work correctly if it uses such an - * array, as the array will be shared by all threads. The solution is to create a {@link NoCL} method called at the start of {@link #run()} which sets - * the field to an array returned from a static ThreadLocal

. Please see MedianKernel7x7 in the samples for an example. - * - * @see #PRIVATE_SUFFIX - */ - @Retention(RetentionPolicy.RUNTIME) - @Target({ElementType.FIELD}) - public @interface PrivateMemorySpace { - /** Size of the array used as __private buffer. */ - int value(); - } - - /** - * Annotation which can be applied to either a getter (with usual java bean naming convention relative to an instance field), or to any method - * with void return type, which prevents both the method body and any calls to the method being emitted in the generated OpenCL. (In the case of a getter, the - * underlying field is used in place of the NoCL getter method.) This allows for code specialization within a java/JTP execution path, for example to - * allow logging/breakpointing when debugging, or to apply ThreadLocal processing (see {@link PrivateMemorySpace}) in java to simulate OpenCL __private - * memory. - */ - @Retention(RetentionPolicy.RUNTIME) - @Target({ElementType.METHOD, ElementType.FIELD}) - public @interface NoCL { - // empty - } - - /** - * We can use this suffix to 'tag' intended local buffers. - * - * - * So either name the buffer - *

-    *  int[] buffer_$local$ = new int[1024];
-    *  
- * Or use the Annotation form - *

-    *  @Local int[] buffer = new int[1024];
-    *  
- */ - public final static String LOCAL_SUFFIX = "_$local$"; - - /** - * We can use this suffix to 'tag' intended constant buffers. - * - * - * So either name the buffer - *

-    *  int[] buffer_$constant$ = new int[1024];
-    *  
- * Or use the Annotation form - *

-    *  @Constant int[] buffer = new int[1024];
-    *  
- */ - public final static String CONSTANT_SUFFIX = "_$constant$"; - - /** - * We can use this suffix to 'tag' __private buffers. - * - *

So either name the buffer - *


-    *  int[] buffer_$private$32 = new int[32];
-    *  
- * Or use the Annotation form - *

-    *  @PrivateMemorySpace(32) int[] buffer = new int[32];
-    *  
- * - * @see PrivateMemorySpace for a more detailed usage summary - */ - public final static String PRIVATE_SUFFIX = "_$private$"; - - /** - * This annotation is for internal use only - */ - @Retention(RetentionPolicy.RUNTIME) - protected @interface OpenCLDelegate { - - } - - /** - * This annotation is for internal use only - */ - @Retention(RetentionPolicy.RUNTIME) - protected @interface OpenCLMapping { - String mapTo() default ""; - - boolean atomic32() default false; - - boolean atomic64() default false; - } - - public abstract class Entry { - public abstract void run(); - - public Kernel execute(Range _range) { - return (Kernel.this.execute("foo", _range, 1)); - } - } - - /** - * @deprecated It is no longer recommended that {@code EXECUTION_MODE}s are used, as a more sophisticated {@link com.aparapi.device.Device} - * preference mechanism is in place, see {@link com.aparapi.internal.kernel.KernelManager}. Though {@link #setExecutionMode(EXECUTION_MODE)} - * is still honored, the default EXECUTION_MODE is now {@link EXECUTION_MODE#AUTO}, which indicates that the KernelManager - * will determine execution behaviours. - * - *

- * The execution mode ENUM enumerates the possible modes of executing a kernel. - * One can request a mode of execution using the values below, and query a kernel after it first executes to - * determine how it executed. - * - *

- * Aparapi supports 5 execution modes. Default is GPU. - *

- *

- * To request that a kernel is executed in a specific mode, call Kernel.setExecutionMode(EXECUTION_MODE) before the - * kernel first executes. - *

- *

-    *     int[] values = new int[1024];
-    *     // fill values array
-    *     SquareKernel kernel = new SquareKernel(values);
-    *     kernel.setExecutionMode(Kernel.EXECUTION_MODE.JTP);
-    *     kernel.execute(values.length);
-    * 
- *

-<<<<<<< HEAD:src/main/java/com/codegen/Kernel.java - * Alternatively, the property com.codegen.executionMode can be set to one of JTP,GPU,ACC,CPU,SEQ - * when an application is launched. - *

-    *    java -classpath ....;codegen.jar -Dcom.codegen.executionMode=GPU MyApplication
-=======
-    * Alternatively, the property com.amd.codegen.executionMode can be set to one of JTP,GPU,ACC,CPU,SEQ
-    * when an application is launched.
-    * 

-    *    java -classpath ....;codegen.jar -Dcom.amd.codegen.executionMode=GPU MyApplication
->>>>>>> b118aad... added method to set execution mode without any fallback:com.amd.codegen/src/java/com/amd/codegen/Kernel.java
-    * 

- * Generally setting the execution mode is not recommended (it is best to let Aparapi decide automatically) but the option - * provides a way to compare a kernel's performance under multiple execution modes. - * - * @author gfrost AMD Javalabs - * @version Alpha, 21/09/2010 - */ - @Deprecated - public static enum EXECUTION_MODE { - /** - * - */ - AUTO, - /** - * A dummy value to indicate an unknown state. - */ - NONE, - /** - * The value representing execution on a GPU device via OpenCL. - */ - GPU, - /** - * The value representing execution on a CPU device via OpenCL. - *

- * Note not all OpenCL implementations support OpenCL compute on the CPU. - */ - CPU, - /** - * The value representing execution on a Java Thread Pool. - *

- * By default one Java thread is started for each available core and each core will execute globalSize/cores work items. - * This creates a total of globalSize%cores threads to complete the work. - * Choose suitable values for globalSize to minimize the number of threads that are spawned. - */ - JTP, - /** - * The value representing execution sequentially in a single loop. - *

- * This is meant to be used for debugging a kernel. - */ - SEQ, - /** - * The value representing execution on an accelerator device (Xeon Phi) via OpenCL. - */ - ACC; - - /** - * @deprecated See {@link EXECUTION_MODE}. - */ - @Deprecated - static LinkedHashSet getDefaultExecutionModes() { - LinkedHashSet defaultExecutionModes = new LinkedHashSet(); - - if (OpenCLLoader.isOpenCLAvailable()) { - defaultExecutionModes.add(GPU); - defaultExecutionModes.add(JTP); - } else { - defaultExecutionModes.add(JTP); - } - - final String executionMode = Config.executionMode; - - if (executionMode != null) { - try { - LinkedHashSet requestedExecutionModes; - requestedExecutionModes = EXECUTION_MODE.getExecutionModeFromString(executionMode); - logger.fine("requested execution mode ="); - for (final EXECUTION_MODE mode : requestedExecutionModes) { - logger.fine(" " + mode); - } - if ((OpenCLLoader.isOpenCLAvailable() && EXECUTION_MODE.anyOpenCL(requestedExecutionModes)) - || !EXECUTION_MODE.anyOpenCL(requestedExecutionModes)) { - defaultExecutionModes = requestedExecutionModes; - } - } catch (final Throwable t) { - // we will take the default - } - } - - logger.info("default execution modes = " + defaultExecutionModes); + final static AtomicInteger serials = new AtomicInteger(); + final int serial = serials.getAndIncrement(); - for (final EXECUTION_MODE e : defaultExecutionModes) { - logger.info("SETTING DEFAULT MODE: " + e.toString()); - } - - return (defaultExecutionModes); - } - - static LinkedHashSet getExecutionModeFromString(String executionMode) { - final LinkedHashSet executionModes = new LinkedHashSet(); - for (final String mode : executionMode.split(",")) { - executionModes.add(valueOf(mode.toUpperCase())); - } - return executionModes; - } + @Override + public int hashCode() { + return serial; + } - static EXECUTION_MODE getFallbackExecutionMode() { - final EXECUTION_MODE defaultFallbackExecutionMode = JTP; - logger.info("fallback execution mode = " + defaultFallbackExecutionMode); - return (defaultFallbackExecutionMode); - } + @Override + public boolean equals(Object obj) { + return this==obj; + } - static boolean anyOpenCL(LinkedHashSet _executionModes) { - for (final EXECUTION_MODE mode : _executionModes) { - if ((mode == GPU) || (mode == ACC) || (mode == CPU)) { - return true; - } - } - return false; - } + private static final Logger logger = Logger.getLogger(Config.getLoggerName()); - public boolean isOpenCL() { - return (this == GPU) || (this == ACC) || (this == CPU); - } - }; + public Kernel clone(Range range) { + Kernel k = clone(); + k.kernelState.range = range; + return k; + } - private KernelRunner kernelRunner = null; + /** + * We can use this Annotation to 'tag' intended local buffers. + *

+ * So we can either annotate the buffer + *


+     *  @Local int[] buffer = new int[1024];
+     *  
+ * Or use a special suffix + *

+     *  int[] buffer_$local$ = new int[1024];
+     *  
+ * + * @see #LOCAL_SUFFIX + */ + @Retention(RetentionPolicy.RUNTIME) + public @interface Local { - private boolean autoCleanUpArrays = false; + } - private KernelState kernelState = new KernelState(); + /** + * We can use this Annotation to 'tag' intended constant buffers. + *

+ * So we can either annotate the buffer + *


+     *  @Constant int[] buffer = new int[1024];
+     *  
+ * Or use a special suffix + *

+     *  int[] buffer_$constant$ = new int[1024];
+     *  
+ * + * @see #LOCAL_SUFFIX + */ + @Retention(RetentionPolicy.RUNTIME) + public @interface Constant { - /** - * This class is for internal Kernel state management

- * NOT INTENDED FOR USE BY USERS - */ - public final class KernelState { + } - private int[] globalIds = new int[] {0, 0, 0}; + /** + * We can use this Annotation to 'tag' __private (unshared) array fields. Data in the __private address space in OpenCL is accessible only from + * the current kernel instance. + *

+ * To so mark a field with a buffer size of 99, we can either annotate the buffer + *


+     *  @PrivateMemorySpace(99) int[] buffer = new int[99];
+     *  
+ * Or use a special suffix + *

+     *  int[] buffer_$private$99 = new int[99];
+     *  
+ *

+ *

Note that any code which must be runnable in {@link EXECUTION_MODE#JTP} will fail to work correctly if it uses such an + * array, as the array will be shared by all threads. The solution is to create a {@link NoCL} method called at the start of {@link #run()} which sets + * the field to an array returned from a static ThreadLocal

. Please see MedianKernel7x7 in the samples for an example. + * + * @see #PRIVATE_SUFFIX + */ + @Retention(RetentionPolicy.RUNTIME) + @Target({ElementType.FIELD}) + public @interface PrivateMemorySpace { + /** + * Size of the array used as __private buffer. + */ + int value(); + } - private int[] localIds = new int[] {0, 0, 0}; + /** + * Annotation which can be applied to either a getter (with usual java bean naming convention relative to an instance field), or to any method + * with void return type, which prevents both the method body and any calls to the method being emitted in the generated OpenCL. (In the case of a getter, the + * underlying field is used in place of the NoCL getter method.) This allows for code specialization within a java/JTP execution path, for example to + * allow logging/breakpointing when debugging, or to apply ThreadLocal processing (see {@link PrivateMemorySpace}) in java to simulate OpenCL __private + * memory. + */ + @Retention(RetentionPolicy.RUNTIME) + @Target({ElementType.METHOD, ElementType.FIELD}) + public @interface NoCL { + // empty + } - private int[] groupIds = new int[] {0, 0, 0}; + /** + * We can use this suffix to 'tag' intended local buffers. + *

+ *

+ * So either name the buffer + *


+     *  int[] buffer_$local$ = new int[1024];
+     *  
+ * Or use the Annotation form + *

+     *  @Local int[] buffer = new int[1024];
+     *  
+ */ + public final static String LOCAL_SUFFIX = "_$local$"; - private Range range; + /** + * We can use this suffix to 'tag' intended constant buffers. + *

+ *

+ * So either name the buffer + *


+     *  int[] buffer_$constant$ = new int[1024];
+     *  
+ * Or use the Annotation form + *

+     *  @Constant int[] buffer = new int[1024];
+     *  
+ */ + public final static String CONSTANT_SUFFIX = "_$constant$"; - private int passId; + /** + * We can use this suffix to 'tag' __private buffers. + *

+ *

So either name the buffer + *


+     *  int[] buffer_$private$32 = new int[32];
+     *  
+ * Or use the Annotation form + *

+     *  @PrivateMemorySpace(32) int[] buffer = new int[32];
+     *  
+ * + * @see PrivateMemorySpace for a more detailed usage summary + */ + public final static String PRIVATE_SUFFIX = "_$private$"; - private volatile CyclicBarrier localBarrier; + /** + * This annotation is for internal use only + */ + @Retention(RetentionPolicy.RUNTIME) + private @interface OpenCLDelegate { - private boolean localBarrierDisabled; + } - /** - * Default constructor - */ - protected KernelState() { + /** + * This annotation is for internal use only + */ + @Retention(RetentionPolicy.RUNTIME) + @interface OpenCLMapping { + String mapTo() default ""; - } + boolean atomic32() default false; - /** - * Copy constructor - */ - protected KernelState(KernelState kernelState) { - globalIds = kernelState.getGlobalIds(); - localIds = kernelState.getLocalIds(); - groupIds = kernelState.getGroupIds(); - range = kernelState.getRange(); - passId = kernelState.getPassId(); - localBarrier = kernelState.getLocalBarrier(); - } + boolean atomic64() default false; + } - /** - * @return the globalIds - */ - public int[] getGlobalIds() { - return globalIds; - } + public abstract class Entry { + public abstract void run(); - /** - * @param globalIds the globalIds to set - */ - public void setGlobalIds(int[] globalIds) { - this.globalIds = globalIds; - } + public Kernel execute(Range _range) { + return (Kernel.this.execute("foo", _range, 1)); + } + } - /** - * Set a specific index value - * - * @param _index - * @param value - */ - public void setGlobalId(int _index, int value) { - globalIds[_index] = value; - } + /** + * @author gfrost AMD Javalabs + * @version Alpha, 21/09/2010 + * @deprecated It is no longer recommended that {@code EXECUTION_MODE}s are used, as a more sophisticated {@link com.aparapi.device.Device} + * preference mechanism is in place, see {@link com.aparapi.internal.kernel.KernelManager}. Though {@link #setExecutionMode(EXECUTION_MODE)} + * is still honored, the default EXECUTION_MODE is now {@link EXECUTION_MODE#AUTO}, which indicates that the KernelManager + * will determine execution behaviours. + *

+ *

+ * The execution mode ENUM enumerates the possible modes of executing a kernel. + * One can request a mode of execution using the values below, and query a kernel after it first executes to + * determine how it executed. + *

+ *

+ * Aparapi supports 5 execution modes. Default is GPU. + *

    + * + * + * + * + * + * + * + *
    Enum valueExecution
    GPUExecute using OpenCL on first available GPU device
    ACCExecute using OpenCL on first available Accelerator device
    CPUExecute using OpenCL on first available CPU device
    JTPExecute using a Java Thread Pool (one thread spawned per available core)
    SEQExecute using a single loop. This is useful for debugging but will be less + * performant than the other modes
    + *
+ *

+ * To request that a kernel is executed in a specific mode, call Kernel.setExecutionMode(EXECUTION_MODE) before the + * kernel first executes. + *

+ *

+     *     int[] values = new int[1024];
+     *     // fill values array
+     *     SquareKernel kernel = new SquareKernel(values);
+     *     kernel.setExecutionMode(Kernel.EXECUTION_MODE.JTP);
+     *     kernel.execute(values.length);
+     * 
+ *

+ * <<<<<<< HEAD:src/main/java/com/codegen/Kernel.java + * Alternatively, the property com.codegen.executionMode can be set to one of JTP,GPU,ACC,CPU,SEQ + * when an application is launched. + *

+     *    java -classpath ....;codegen.jar -Dcom.codegen.executionMode=GPU MyApplication
+     * =======
+     * Alternatively, the property com.amd.codegen.executionMode can be set to one of JTP,GPU,ACC,CPU,SEQ
+     * when an application is launched.
+     * 

+     *    java -classpath ....;codegen.jar -Dcom.amd.codegen.executionMode=GPU MyApplication
+     * >>>>>>> b118aad... added method to set execution mode without any fallback:com.amd.codegen/src/java/com/amd/codegen/Kernel.java
+     * 

+ * Generally setting the execution mode is not recommended (it is best to let Aparapi decide automatically) but the option + * provides a way to compare a kernel's performance under multiple execution modes. + */ + @Deprecated + public enum EXECUTION_MODE { + /** + * + */ + AUTO, + /** + * A dummy value to indicate an unknown state. + */ + NONE, + /** + * The value representing execution on a GPU device via OpenCL. + */ + GPU, + /** + * The value representing execution on a CPU device via OpenCL. + *

+ * Note not all OpenCL implementations support OpenCL compute on the CPU. + */ + CPU, + /** + * The value representing execution on a Java Thread Pool. + *

+ * By default one Java thread is started for each available core and each core will execute globalSize/cores work items. + * This creates a total of globalSize%cores threads to complete the work. + * Choose suitable values for globalSize to minimize the number of threads that are spawned. + */ + JTP, + /** + * The value representing execution sequentially in a single loop. + *

+ * This is meant to be used for debugging a kernel. + */ + SEQ, + /** + * The value representing execution on an accelerator device (Xeon Phi) via OpenCL. + */ + ACC; + + /** + * @deprecated See {@link EXECUTION_MODE}. + */ + @Deprecated + static LinkedHashSet getDefaultExecutionModes() { + LinkedHashSet defaultExecutionModes = new LinkedHashSet<>(); + + if (OpenCLLoader.isOpenCLAvailable()) { + defaultExecutionModes.add(GPU); + defaultExecutionModes.add(JTP); + } else { + defaultExecutionModes.add(JTP); + } - /** - * @return the localIds - */ - public int[] getLocalIds() { - return localIds; - } + final String executionMode = Config.executionMode; + + if (executionMode != null) { + try { + LinkedHashSet requestedExecutionModes; + requestedExecutionModes = EXECUTION_MODE.getExecutionModeFromString(executionMode); + if (logger.isLoggable(Level.FINE)) { + logger.fine("requested execution mode ="); + for (final EXECUTION_MODE mode : requestedExecutionModes) { + logger.fine(" " + mode); + } + } + if ((OpenCLLoader.isOpenCLAvailable() && EXECUTION_MODE.anyOpenCL(requestedExecutionModes)) + || !EXECUTION_MODE.anyOpenCL(requestedExecutionModes)) { + defaultExecutionModes = requestedExecutionModes; + } + } catch (final Throwable t) { + // we will take the default + } + } - /** - * @param localIds the localIds to set - */ - public void setLocalIds(int[] localIds) { - this.localIds = localIds; - } + logger.info("default execution modes = " + defaultExecutionModes); - /** - * Set a specific index value - * - * @param _index - * @param value - */ - public void setLocalId(int _index, int value) { - localIds[_index] = value; - } + for (final EXECUTION_MODE e : defaultExecutionModes) { + logger.info("SETTING DEFAULT MODE: " + e.toString()); + } - /** - * @return the groupIds - */ - public int[] getGroupIds() { - return groupIds; - } + return (defaultExecutionModes); + } - /** - * @param groupIds the groupIds to set - */ - public void setGroupIds(int[] groupIds) { - this.groupIds = groupIds; - } + static LinkedHashSet getExecutionModeFromString(String executionMode) { + final LinkedHashSet executionModes = new LinkedHashSet<>(); + for (final String mode : executionMode.split(",")) { + executionModes.add(valueOf(mode.toUpperCase())); + } + return executionModes; + } + + static EXECUTION_MODE getFallbackExecutionMode() { + final EXECUTION_MODE defaultFallbackExecutionMode = JTP; + logger.info("fallback execution mode = " + defaultFallbackExecutionMode); + return (defaultFallbackExecutionMode); + } + + static boolean anyOpenCL(LinkedHashSet _executionModes) { + for (final EXECUTION_MODE mode : _executionModes) { + if ((mode == GPU) || (mode == ACC) || (mode == CPU)) { + return true; + } + } + return false; + } - /** - * Set a specific index value - * - * @param _index - * @param value - */ - public void setGroupId(int _index, int value) { - groupIds[_index] = value; - } + public boolean isOpenCL() { + return (this == GPU) || (this == ACC) || (this == CPU); + } + } - /** - * @return the range - */ - public Range getRange() { - return range; - } - /** - * @param range the range to set - */ - public void setRange(Range range) { - this.range = range; - } + private boolean autoCleanUpArrays = false; - /** - * @return the passId - */ - public int getPassId() { - return passId; - } + private KernelState kernelState = new KernelState(); - /** - * @param passId the passId to set - */ - public void setPassId(int passId) { - this.passId = passId; - } + /** + * This class is for internal Kernel state management

+ * NOT INTENDED FOR USE BY USERS + */ + public final class KernelState { + + public final AtomicIntegerArray globalIds = new AtomicIntegerArray(3); + + private int[] localIds = new int[]{0, 0, 0}; + + private int[] groupIds = new int[]{0, 0, 0}; + + private Range range; + + private int passId; + + private volatile CyclicBarrier localBarrier; + + private boolean localBarrierDisabled; + + /** + * Default constructor + */ + KernelState() { + + } + + /** + * Copy constructor + */ + KernelState(KernelState kernelState) { + for (int i = 0; i < globalIds.length(); i++) + globalIds.set(i, kernelState.globalIds.get(i)); + localIds = kernelState.getLocalIds(); + groupIds = kernelState.getGroupIds(); + range = kernelState.getRange(); + passId = kernelState.getPassId(); + localBarrier = kernelState.getLocalBarrier(); + } + + /** + * @param globalIds the globalIds to set + */ + void setGlobalIds(int[] globalIds) { + int i = 0; + for (int x : globalIds) + this.globalIds.set(i++, x); + } + + /** + * Set a specific index value + * + * @param _index + * @param value + */ + public void setGlobalId(int _index, int value) { + globalIds.set(_index, value); + } + + /** + * @return the localIds + */ + public int[] getLocalIds() { + return localIds; + } + + /** + * @param localIds the localIds to set + */ + void setLocalIds(int[] localIds) { + this.localIds = localIds; + } + + /** + * Set a specific index value + * + * @param _index + * @param value + */ + public void setLocalId(int _index, int value) { + localIds[_index] = value; + } + + /** + * @return the groupIds + */ + int[] getGroupIds() { + return groupIds; + } + + /** + * @param groupIds the groupIds to set + */ + void setGroupIds(int[] groupIds) { + this.groupIds = groupIds; + } + + /** + * Set a specific index value + * + * @param _index + * @param value + */ + public void setGroupId(int _index, int value) { + groupIds[_index] = value; + } + + /** + * @return the range + */ + Range getRange() { + return range; + } + + /** + * @param range the range to set + */ + public void setRange(Range range) { + this.range = range; + } + + /** + * @return the passId + */ + int getPassId() { + return passId; + } + + /** + * @param passId the passId to set + */ + public void setPassId(int passId) { + this.passId = passId; + } + + /** + * @return the localBarrier + */ + CyclicBarrier getLocalBarrier() { + return localBarrier; + } + + /** + * @param localBarrier the localBarrier to set + */ + public void setLocalBarrier(CyclicBarrier localBarrier) { + this.localBarrier = localBarrier; + } + + void awaitOnLocalBarrier() { + if (!localBarrierDisabled) { + try { + kernelState.getLocalBarrier().await(); + } catch (final InterruptedException | BrokenBarrierException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + } - /** - * @return the localBarrier - */ - public CyclicBarrier getLocalBarrier() { - return localBarrier; - } + public void disableLocalBarrier() { + localBarrierDisabled = true; + } + } - /** - * @param localBarrier the localBarrier to set - */ - public void setLocalBarrier(CyclicBarrier localBarrier) { - this.localBarrier = localBarrier; - } + /** + * Determine the globalId of an executing kernel. + *

+ * The kernel implementation uses the globalId to determine which of the executing kernels (in the global domain space) this invocation is expected to deal with. + *

+ * For example in a SquareKernel implementation: + *

+ *

+     *     class SquareKernel extends Kernel{
+     *         private int values[];
+     *         private int squares[];
+     *         public SquareKernel(int values[]){
+     *            this.values = values;
+     *            squares = new int[values.length];
+     *         }
+     *         public void run() {
+     *             int gid = getGlobalID();
+     *             squares[gid] = values[gid]*values[gid];
+     *         }
+     *         public int[] getSquares(){
+     *             return(squares);
+     *         }
+     *     }
+     * 
+ *

+ * Each invocation of SquareKernel.run() retrieves it's globalId by calling getGlobalId(), and then computes the value of square[gid] for a given value of value[gid]. + *

+ * + * @return The globalId for the Kernel being executed + * @see #getLocalId() + * @see #getGroupId() + * @see #getGlobalSize() + * @see #getNumGroups() + * @see #getLocalSize() + */ - public void awaitOnLocalBarrier() { - if (!localBarrierDisabled) { - try { - kernelState.getLocalBarrier().await(); - } catch (final InterruptedException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (final BrokenBarrierException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - } + @OpenCLDelegate + protected final int getGlobalId() { + return getGlobalId(0); + } - public void disableLocalBarrier() { - localBarrierDisabled = true; - } - } - - /** - * Determine the globalId of an executing kernel. - *

- * The kernel implementation uses the globalId to determine which of the executing kernels (in the global domain space) this invocation is expected to deal with. - *

- * For example in a SquareKernel implementation: - *

- *

-    *     class SquareKernel extends Kernel{
-    *         private int values[];
-    *         private int squares[];
-    *         public SquareKernel(int values[]){
-    *            this.values = values;
-    *            squares = new int[values.length];
-    *         }
-    *         public void run() {
-    *             int gid = getGlobalID();
-    *             squares[gid] = values[gid]*values[gid];
-    *         }
-    *         public int[] getSquares(){
-    *             return(squares);
-    *         }
-    *     }
-    * 
- *

- * Each invocation of SquareKernel.run() retrieves it's globalId by calling getGlobalId(), and then computes the value of square[gid] for a given value of value[gid]. - *

- * @return The globalId for the Kernel being executed - * - * @see #getLocalId() - * @see #getGroupId() - * @see #getGlobalSize() - * @see #getNumGroups() - * @see #getLocalSize() - */ - - @OpenCLDelegate - protected final int getGlobalId() { - return getGlobalId(0); - } - - @OpenCLDelegate - protected final int getGlobalId(int _dim) { - return kernelState.getGlobalIds()[_dim]; - } + @OpenCLDelegate + protected final int getGlobalId(int _dim) { + return kernelState.globalIds.get(_dim); + } /* @OpenCLDelegate protected final int getGlobalX() { @@ -737,46 +733,46 @@ protected final int getGlobalId(int _dim) { return (getGlobalId(2)); } */ - /** - * Determine the groupId of an executing kernel. - *

- * When a Kernel.execute(int globalSize) is invoked for a particular kernel, the runtime will break the work into various 'groups'. - *

- * A kernel can use getGroupId() to determine which group a kernel is currently - * dispatched to - *

- * The following code would capture the groupId for each kernel and map it against globalId. - *

-    *     final int[] groupIds = new int[1024];
-    *     Kernel kernel = new Kernel(){
-    *         public void run() {
-    *             int gid = getGlobalId();
-    *             groupIds[gid] = getGroupId();
-    *         }
-    *     };
-    *     kernel.execute(groupIds.length);
-    *     for (int i=0; i< values.length; i++){
-    *        System.out.printf("%4d %4d\n", i, groupIds[i]);
-    *     }
-    * 
- * - * @see #getLocalId() - * @see #getGlobalId() - * @see #getGlobalSize() - * @see #getNumGroups() - * @see #getLocalSize() - * - * @return The groupId for this Kernel being executed - */ - @OpenCLDelegate - protected final int getGroupId() { - return getGroupId(0); - } - - @OpenCLDelegate - protected final int getGroupId(int _dim) { - return kernelState.getGroupIds()[_dim]; - } + + /** + * Determine the groupId of an executing kernel. + *

+ * When a Kernel.execute(int globalSize) is invoked for a particular kernel, the runtime will break the work into various 'groups'. + *

+ * A kernel can use getGroupId() to determine which group a kernel is currently + * dispatched to + *

+ * The following code would capture the groupId for each kernel and map it against globalId. + *

+     *     final int[] groupIds = new int[1024];
+     *     Kernel kernel = new Kernel(){
+     *         public void run() {
+     *             int gid = getGlobalId();
+     *             groupIds[gid] = getGroupId();
+     *         }
+     *     };
+     *     kernel.execute(groupIds.length);
+     *     for (int i=0; i< values.length; i++){
+     *        System.out.printf("%4d %4d\n", i, groupIds[i]);
+     *     }
+     * 
+ * + * @return The groupId for this Kernel being executed + * @see #getLocalId() + * @see #getGlobalId() + * @see #getGlobalSize() + * @see #getNumGroups() + * @see #getLocalSize() + */ + @OpenCLDelegate + protected final int getGroupId() { + return getGroupId(0); + } + + @OpenCLDelegate + private int getGroupId(int _dim) { + return kernelState.getGroupIds()[_dim]; + } /* @OpenCLDelegate protected final int getGroupX() { @@ -791,65 +787,64 @@ protected final int getGroupId(int _dim) { return (getGroupId(2)); } */ - /** - * Determine the passId of an executing kernel. - *

- * When a Kernel.execute(int globalSize, int passes) is invoked for a particular kernel, the runtime will break the work into various 'groups'. - *

- * A kernel can use getPassId() to determine which pass we are in. This is ideal for 'reduce' type phases - * - * @see #getLocalId() - * @see #getGlobalId() - * @see #getGlobalSize() - * @see #getNumGroups() - * @see #getLocalSize() - * - * @return The groupId for this Kernel being executed - */ - @OpenCLDelegate - protected final int getPassId() { - return kernelState.getPassId(); - } - - /** - * Determine the local id of an executing kernel. - *

- * When a Kernel.execute(int globalSize) is invoked for a particular kernel, the runtime will break the work into - * various 'groups'. - * getLocalId() can be used to determine the relative id of the current kernel within a specific group. - *

- * The following code would capture the groupId for each kernel and map it against globalId. - *

-    *     final int[] localIds = new int[1024];
-    *     Kernel kernel = new Kernel(){
-    *         public void run() {
-    *             int gid = getGlobalId();
-    *             localIds[gid] = getLocalId();
-    *         }
-    *     };
-    *     kernel.execute(localIds.length);
-    *     for (int i=0; i< values.length; i++){
-    *        System.out.printf("%4d %4d\n", i, localIds[i]);
-    *     }
-    * 
- * - * @see #getGroupId() - * @see #getGlobalId() - * @see #getGlobalSize() - * @see #getNumGroups() - * @see #getLocalSize() - * - * @return The local id for this Kernel being executed - */ - @OpenCLDelegate - protected final int getLocalId() { - return getLocalId(0); - } - - @OpenCLDelegate - protected final int getLocalId(int _dim) { - return kernelState.getLocalIds()[_dim]; - } + + /** + * Determine the passId of an executing kernel. + *

+ * When a Kernel.execute(int globalSize, int passes) is invoked for a particular kernel, the runtime will break the work into various 'groups'. + *

+ * A kernel can use getPassId() to determine which pass we are in. This is ideal for 'reduce' type phases + * + * @return The groupId for this Kernel being executed + * @see #getLocalId() + * @see #getGlobalId() + * @see #getGlobalSize() + * @see #getNumGroups() + * @see #getLocalSize() + */ + @OpenCLDelegate + protected final int getPassId() { + return kernelState.getPassId(); + } + + /** + * Determine the local id of an executing kernel. + *

+ * When a Kernel.execute(int globalSize) is invoked for a particular kernel, the runtime will break the work into + * various 'groups'. + * getLocalId() can be used to determine the relative id of the current kernel within a specific group. + *

+ * The following code would capture the groupId for each kernel and map it against globalId. + *

+     *     final int[] localIds = new int[1024];
+     *     Kernel kernel = new Kernel(){
+     *         public void run() {
+     *             int gid = getGlobalId();
+     *             localIds[gid] = getLocalId();
+     *         }
+     *     };
+     *     kernel.execute(localIds.length);
+     *     for (int i=0; i< values.length; i++){
+     *        System.out.printf("%4d %4d\n", i, localIds[i]);
+     *     }
+     * 
+ * + * @return The local id for this Kernel being executed + * @see #getGroupId() + * @see #getGlobalId() + * @see #getGlobalSize() + * @see #getNumGroups() + * @see #getLocalSize() + */ + @OpenCLDelegate + protected final int getLocalId() { + return getLocalId(0); + } + + @OpenCLDelegate + protected final int getLocalId(int _dim) { + return kernelState.getLocalIds()[_dim]; + } /* @OpenCLDelegate protected final int getLocalX() { @@ -864,32 +859,32 @@ protected final int getLocalId(int _dim) { return (getLocalId(2)); } */ - /** - * Determine the size of the group that an executing kernel is a member of. - *

- * When a Kernel.execute(int globalSize) is invoked for a particular kernel, the runtime will break the work into - * various 'groups'. getLocalSize() allows a kernel to determine the size of the current group. - *

- * Note groups may not all be the same size. In particular, if (global size)%(# of compute devices)!=0, the runtime can choose to dispatch kernels to - * groups with differing sizes. - * - * @see #getGroupId() - * @see #getGlobalId() - * @see #getGlobalSize() - * @see #getNumGroups() - * @see #getLocalSize() - * - * @return The size of the currently executing group. - */ - @OpenCLDelegate - protected final int getLocalSize() { - return kernelState.getRange().getLocalSize(0); - } - - @OpenCLDelegate - protected final int getLocalSize(int _dim) { - return kernelState.getRange().getLocalSize(_dim); - } + + /** + * Determine the size of the group that an executing kernel is a member of. + *

+ * When a Kernel.execute(int globalSize) is invoked for a particular kernel, the runtime will break the work into + * various 'groups'. getLocalSize() allows a kernel to determine the size of the current group. + *

+ * Note groups may not all be the same size. In particular, if (global size)%(# of compute devices)!=0, the runtime can choose to dispatch kernels to + * groups with differing sizes. + * + * @return The size of the currently executing group. + * @see #getGroupId() + * @see #getGlobalId() + * @see #getGlobalSize() + * @see #getNumGroups() + * @see #getLocalSize() + */ + @OpenCLDelegate + protected final int getLocalSize() { + return kernelState.getRange().getLocalSize(0); + } + + @OpenCLDelegate + protected final int getLocalSize(int _dim) { + return kernelState.getRange().getLocalSize(_dim); + } /* @OpenCLDelegate protected final int getLocalWidth() { @@ -904,25 +899,25 @@ protected final int getLocalSize(int _dim) { return (range.getLocalSize(2)); } */ - /** - * Determine the value that was passed to Kernel.execute(int globalSize) method. - * - * @see #getGroupId() - * @see #getGlobalId() - * @see #getNumGroups() - * @see #getLocalSize() - * - * @return The value passed to Kernel.execute(int globalSize) causing the current execution. - */ - @OpenCLDelegate - protected final int getGlobalSize() { - return kernelState.getRange().getGlobalSize(0); - } - - @OpenCLDelegate - protected final int getGlobalSize(int _dim) { - return kernelState.getRange().getGlobalSize(_dim); - } + + /** + * Determine the value that was passed to Kernel.execute(int globalSize) method. + * + * @return The value passed to Kernel.execute(int globalSize) causing the current execution. + * @see #getGroupId() + * @see #getGlobalId() + * @see #getNumGroups() + * @see #getLocalSize() + */ + @OpenCLDelegate + protected final int getGlobalSize() { + return kernelState.getRange().getGlobalSize(0); + } + + @OpenCLDelegate + protected final int getGlobalSize(int _dim) { + return kernelState.getRange().getGlobalSize(_dim); + } /* @OpenCLDelegate protected final int getGlobalWidth() { @@ -937,29 +932,29 @@ protected final int getGlobalSize(int _dim) { return (range.getGlobalSize(2)); } */ - /** - * Determine the number of groups that will be used to execute a kernel - *

- * When Kernel.execute(int globalSize) is invoked, the runtime will split the work into - * multiple 'groups'. getNumGroups() returns the total number of groups that will be used. - * - * @see #getGroupId() - * @see #getGlobalId() - * @see #getGlobalSize() - * @see #getNumGroups() - * @see #getLocalSize() - * - * @return The number of groups that kernels will be dispatched into. - */ - @OpenCLDelegate - protected final int getNumGroups() { - return kernelState.getRange().getNumGroups(0); - } - - @OpenCLDelegate - protected final int getNumGroups(int _dim) { - return kernelState.getRange().getNumGroups(_dim); - } + + /** + * Determine the number of groups that will be used to execute a kernel + *

+ * When Kernel.execute(int globalSize) is invoked, the runtime will split the work into + * multiple 'groups'. getNumGroups() returns the total number of groups that will be used. + * + * @return The number of groups that kernels will be dispatched into. + * @see #getGroupId() + * @see #getGlobalId() + * @see #getGlobalSize() + * @see #getNumGroups() + * @see #getLocalSize() + */ + @OpenCLDelegate + protected final int getNumGroups() { + return kernelState.getRange().getNumGroups(0); + } + + @OpenCLDelegate + protected final int getNumGroups(int _dim) { + return kernelState.getRange().getNumGroups(_dim); + } /* @OpenCLDelegate protected final int getNumGroupsWidth() { @@ -974,377 +969,365 @@ protected final int getNumGroups(int _dim) { return (range.getGroups(2)); } */ - /** - * The entry point of a kernel. - * - *

- * Every kernel must override this method. - */ - public abstract void run(); - - /** False by default. In the event that all preferred devices fail to execute a kernel, it is possible to supply an alternate (possibly non-parallel) - * execution algorithm by overriding this method to return true, and overriding {@link #executeFallbackAlgorithm(Range, int)} with the alternate - * algorithm. - */ - public boolean hasFallbackAlgorithm() { - return false; - } - - /** If {@link #hasFallbackAlgorithm()} has been overriden to return true, this method should be overriden so as to - * apply a single pass of the kernel's logic to the entire _range. - * - *

- * This is not normally required, as fallback to {@link JavaDevice#THREAD_POOL} will implement the algorithm in parallel. However - * in the event that thread pool execution may be prohibitively slow, this method might implement a "quick and dirty" approximation - * to the desired result (for example, a simple box-blur as opposed to a gaussian blur in an image processing application). - */ - public void executeFallbackAlgorithm(Range _range, int _passId) { - // nothing - } - - /** - * Invoking this method flags that once the current pass is complete execution should be abandoned. Due to the complexity of intercommunication - * between java (or C) and executing OpenCL, this is the best we can do for general cancellation of execution at present. OpenCL 2.0 should introduce - * pipe mechanisms which will support mid-pass cancellation easily. - * - *

- * Note that in the case of thread-pool/pure java execution we could do better already, using Thread.interrupt() (and/or other means) to abandon - * execution mid-pass. However at present this is not attempted. - * - * @see #execute(int, int) - * @see #execute(Range, int) - * @see #execute(String, Range, int) - */ - public void cancelMultiPass() { - if (kernelRunner == null) { - return; - } - kernelRunner.cancelMultiPass(); - } - - public int getCancelState() { - return kernelRunner == null ? KernelRunner.CANCEL_STATUS_FALSE : kernelRunner.getCancelState(); - } - - /** - * @see KernelRunner#getCurrentPass() - */ - public int getCurrentPass() { - if (kernelRunner == null) { - return KernelRunner.PASS_ID_COMPLETED_EXECUTION; - } - return kernelRunner.getCurrentPass(); - } - - /** - * @see KernelRunner#isExecuting() - */ - public boolean isExecuting() { - if (kernelRunner == null) { - return false; - } - return kernelRunner.isExecuting(); - } - - /** - * When using a Java Thread Pool Aparapi uses clone to copy the initial instance to each thread. - * - *

- * If you choose to override clone() you are responsible for delegating to super.clone(); - */ - @Override - public Kernel clone() { - try { - final Kernel worker = (Kernel) super.clone(); - - // We need to be careful to also clone the KernelState - worker.kernelState = worker.new KernelState(kernelState); // Qualified copy constructor - - worker.kernelState.setGroupIds(new int[] {0, 0, 0}); - - worker.kernelState.setLocalIds(new int[] {0, 0, 0}); - - worker.kernelState.setGlobalIds(new int[] {0, 0, 0}); - - return worker; - } catch (final CloneNotSupportedException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - return (null); - } - } - /** - * Delegates to either {@link java.lang.Math#acos(double)} (Java) or acos(float) (OpenCL). - * + /** + * The entry point of a kernel. + *

+ *

+ * Every kernel must override this method. + */ + public abstract void run(); + + /** + * False by default. In the event that all preferred devices fail to execute a kernel, it is possible to supply an alternate (possibly non-parallel) + * execution algorithm by overriding this method to return true, and overriding {@link #executeFallbackAlgorithm(Range, int)} with the alternate + * algorithm. + */ + public boolean hasFallbackAlgorithm() { + return false; + } + + /** + * If {@link #hasFallbackAlgorithm()} has been overriden to return true, this method should be overriden so as to + * apply a single pass of the kernel's logic to the entire _range. + *

+ *

+ * This is not normally required, as fallback to {@link JavaDevice#THREAD_POOL} will implement the algorithm in parallel. However + * in the event that thread pool execution may be prohibitively slow, this method might implement a "quick and dirty" approximation + * to the desired result (for example, a simple box-blur as opposed to a gaussian blur in an image processing application). + */ + public void executeFallbackAlgorithm(Range _range, int _passId) { + // nothing + } + +// /** +// * Invoking this method flags that once the current pass is complete execution should be abandoned. Due to the complexity of intercommunication +// * between java (or C) and executing OpenCL, this is the best we can do for general cancellation of execution at present. OpenCL 2.0 should introduce +// * pipe mechanisms which will support mid-pass cancellation easily. +// *

+// *

+// * Note that in the case of thread-pool/pure java execution we could do better already, using Thread.interrupt() (and/or other means) to abandon +// * execution mid-pass. However at present this is not attempted. +// * +// * @see #execute(int, int) +// * @see #execute(Range, int) +// * @see #execute(String, Range, int) +// */ +// public void cancelMultiPass() { +// if (kernelRunner == null) { +// return; +// } +// kernelRunner.cancelMultiPass(); +// } +// +// public int getCancelState() { +// return kernelRunner == null ? KernelRunner.CANCEL_STATUS_FALSE : kernelRunner.getCancelState(); +// } +// +// /** +// * @see KernelRunner#getCurrentPass() +// */ +// public int getCurrentPass() { +// if (kernelRunner == null) { +// return KernelRunner.PASS_ID_COMPLETED_EXECUTION; +// } +// return kernelRunner.getCurrentPass(); +// } +// +// /** +// * @see KernelRunner#isExecuting() +// */ +// public boolean isExecuting() { +// if (kernelRunner == null) { +// return false; +// } +// return kernelRunner.isExecuting(); +// } + + /** + * When using a Java Thread Pool Aparapi uses clone to copy the initial instance to each thread. + *

+ *

+ * If you choose to override clone() you are responsible for delegating to super.clone(); + */ + @Override + public Kernel clone() { + try { + final Kernel worker = (Kernel) super.clone(); + + // We need to be careful to also clone the KernelState + worker.kernelState = worker.new KernelState(kernelState); // Qualified copy constructor + + worker.kernelState.setGroupIds(new int[]{0, 0, 0}); + + worker.kernelState.setLocalIds(new int[]{0, 0, 0}); + + worker.kernelState.setGlobalIds(new int[]{0, 0, 0}); + + return worker; + } catch (final CloneNotSupportedException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + return (null); + } + } + + /** + * Delegates to either {@link java.lang.Math#acos(double)} (Java) or acos(float) (OpenCL). + *

* User should note the differences in precision between Java and OpenCL's implementation of arithmetic functions to determine whether the difference in precision is acceptable. * * @param a value to delegate to {@link java.lang.Math#acos(double)}/acos(float) * @return {@link java.lang.Math#acos(double)} casted to float/acos(float) - * * @see java.lang.Math#acos(double) * @see acos(float) */ - @OpenCLMapping(mapTo = "acos") - protected float acos(float a) { - return (float) Math.acos(a); - } - - /** - * Delegates to either {@link java.lang.Math#acos(double)} (Java) or acos(double) (OpenCL). - * - * User should note the differences in precision between Java and OpenCL's implementation of arithmetic functions to determine whether the difference in precision is acceptable. - * - * @param a value to delegate to {@link java.lang.Math#acos(double)}/acos(double) - * @return {@link java.lang.Math#acos(double)}/acos(double) - * - * @see java.lang.Math#acos(double) - * @see acos(double) - */ - @OpenCLMapping(mapTo = "acos") - protected double acos(double a) { - return Math.acos(a); - } - - /** - * Delegates to either {@link java.lang.Math#asin(double)} (Java) or asin(float) (OpenCL). + @OpenCLMapping(mapTo = "acos") + protected float acos(float a) { + return (float) Math.acos(a); + } + + /** + * Delegates to either {@link java.lang.Math#acos(double)} (Java) or acos(double) (OpenCL). + *

+ * User should note the differences in precision between Java and OpenCL's implementation of arithmetic functions to determine whether the difference in precision is acceptable. * + * @param a value to delegate to {@link java.lang.Math#acos(double)}/acos(double) + * @return {@link java.lang.Math#acos(double)}/acos(double) + * @see java.lang.Math#acos(double) + * @see acos(double) + */ + @OpenCLMapping(mapTo = "acos") + protected double acos(double a) { + return Math.acos(a); + } + + /** + * Delegates to either {@link java.lang.Math#asin(double)} (Java) or asin(float) (OpenCL). + *

* User should note the differences in precision between Java and OpenCL's implementation of arithmetic functions to determine whether the difference in precision is acceptable. * * @param _f value to delegate to {@link java.lang.Math#asin(double)}/asin(float) * @return {@link java.lang.Math#asin(double)} casted to float/asin(float) - * * @see java.lang.Math#asin(double) * @see asin(float) */ - @OpenCLMapping(mapTo = "asin") - protected float asin(float _f) { - return (float) Math.asin(_f); - } + @OpenCLMapping(mapTo = "asin") + protected float asin(float _f) { + return (float) Math.asin(_f); + } - /** - * Delegates to either {@link java.lang.Math#asin(double)} (Java) or asin(double) (OpenCL). - * + /** + * Delegates to either {@link java.lang.Math#asin(double)} (Java) or asin(double) (OpenCL). + *

* User should note the differences in precision between Java and OpenCL's implementation of arithmetic functions to determine whether the difference in precision is acceptable. * * @param _d value to delegate to {@link java.lang.Math#asin(double)}/asin(double) * @return {@link java.lang.Math#asin(double)}/asin(double) - * * @see java.lang.Math#asin(double) * @see asin(double) */ - @OpenCLMapping(mapTo = "asin") - protected double asin(double _d) { - return Math.asin(_d); - } + @OpenCLMapping(mapTo = "asin") + protected double asin(double _d) { + return Math.asin(_d); + } - /** - * Delegates to either {@link java.lang.Math#atan(double)} (Java) or atan(float) (OpenCL). - * + /** + * Delegates to either {@link java.lang.Math#atan(double)} (Java) or atan(float) (OpenCL). + *

* User should note the differences in precision between Java and OpenCL's implementation of arithmetic functions to determine whether the difference in precision is acceptable. * * @param _f value to delegate to {@link java.lang.Math#atan(double)}/atan(float) * @return {@link java.lang.Math#atan(double)} casted to float/atan(float) - * * @see java.lang.Math#atan(double) * @see atan(float) */ - @OpenCLMapping(mapTo = "atan") - protected float atan(float _f) { - return (float) Math.atan(_f); - } + @OpenCLMapping(mapTo = "atan") + protected float atan(float _f) { + return (float) Math.atan(_f); + } - /** - * Delegates to either {@link java.lang.Math#atan(double)} (Java) or atan(double) (OpenCL). - * + /** + * Delegates to either {@link java.lang.Math#atan(double)} (Java) or atan(double) (OpenCL). + *

* User should note the differences in precision between Java and OpenCL's implementation of arithmetic functions to determine whether the difference in precision is acceptable. * * @param _d value to delegate to {@link java.lang.Math#atan(double)}/atan(double) * @return {@link java.lang.Math#atan(double)}/atan(double) - * * @see java.lang.Math#atan(double) * @see atan(double) */ - @OpenCLMapping(mapTo = "atan") - protected double atan(double _d) { - return Math.atan(_d); - } + @OpenCLMapping(mapTo = "atan") + protected double atan(double _d) { + return Math.atan(_d); + } - /** - * Delegates to either {@link java.lang.Math#atan2(double, double)} (Java) or atan2(float, float) (OpenCL). - * + /** + * Delegates to either {@link java.lang.Math#atan2(double, double)} (Java) or atan2(float, float) (OpenCL). + *

* User should note the differences in precision between Java and OpenCL's implementation of arithmetic functions to determine whether the difference in precision is acceptable. * * @param _f1 value to delegate to first argument of {@link java.lang.Math#atan2(double, double)}/atan2(float, float) * @param _f2 value to delegate to second argument of {@link java.lang.Math#atan2(double, double)}/atan2(float, float) * @return {@link java.lang.Math#atan2(double, double)} casted to float/atan2(float, float) - * * @see java.lang.Math#atan2(double, double) * @see atan2(float, float) */ - @OpenCLMapping(mapTo = "atan2") - protected float atan2(float _f1, float _f2) { - return (float) Math.atan2(_f1, _f2); - } + @OpenCLMapping(mapTo = "atan2") + protected float atan2(float _f1, float _f2) { + return (float) Math.atan2(_f1, _f2); + } - /** - * Delegates to either {@link java.lang.Math#atan2(double, double)} (Java) or atan2(double, double) (OpenCL). - * + /** + * Delegates to either {@link java.lang.Math#atan2(double, double)} (Java) or atan2(double, double) (OpenCL). + *

* User should note the differences in precision between Java and OpenCL's implementation of arithmetic functions to determine whether the difference in precision is acceptable. * * @param _d1 value to delegate to first argument of {@link java.lang.Math#atan2(double, double)}/atan2(double, double) * @param _d2 value to delegate to second argument of {@link java.lang.Math#atan2(double, double)}/atan2(double, double) * @return {@link java.lang.Math#atan2(double, double)}/atan2(double, double) - * * @see java.lang.Math#atan2(double, double) * @see atan2(double, double) */ - @OpenCLMapping(mapTo = "atan2") - protected double atan2(double _d1, double _d2) { - return Math.atan2(_d1, _d2); - } + @OpenCLMapping(mapTo = "atan2") + protected double atan2(double _d1, double _d2) { + return Math.atan2(_d1, _d2); + } - /** - * Delegates to either {@link java.lang.Math#ceil(double)} (Java) or ceil(float) (OpenCL). - * + /** + * Delegates to either {@link java.lang.Math#ceil(double)} (Java) or ceil(float) (OpenCL). + *

* User should note the differences in precision between Java and OpenCL's implementation of arithmetic functions to determine whether the difference in precision is acceptable. * * @param _f value to delegate to {@link java.lang.Math#ceil(double)}/ceil(float) * @return {@link java.lang.Math#ceil(double)} casted to float/ceil(float) - * * @see java.lang.Math#ceil(double) * @see ceil(float) */ - @OpenCLMapping(mapTo = "ceil") - protected float ceil(float _f) { - return (float) Math.ceil(_f); - } + @OpenCLMapping(mapTo = "ceil") + protected float ceil(float _f) { + return (float) Math.ceil(_f); + } - /** - * Delegates to either {@link java.lang.Math#ceil(double)} (Java) or ceil(double) (OpenCL). - * + /** + * Delegates to either {@link java.lang.Math#ceil(double)} (Java) or ceil(double) (OpenCL). + *

* User should note the differences in precision between Java and OpenCL's implementation of arithmetic functions to determine whether the difference in precision is acceptable. * * @param _d value to delegate to {@link java.lang.Math#ceil(double)}/ceil(double) * @return {@link java.lang.Math#ceil(double)}/ceil(double) - * * @see java.lang.Math#ceil(double) * @see ceil(double) */ - @OpenCLMapping(mapTo = "ceil") - protected double ceil(double _d) { - return Math.ceil(_d); - } + @OpenCLMapping(mapTo = "ceil") + protected double ceil(double _d) { + return Math.ceil(_d); + } - /** - * Delegates to either {@link java.lang.Math#cos(double)} (Java) or cos(float) (OpenCL). - * + /** + * Delegates to either {@link java.lang.Math#cos(double)} (Java) or cos(float) (OpenCL). + *

* User should note the differences in precision between Java and OpenCL's implementation of arithmetic functions to determine whether the difference in precision is acceptable. * * @param _f value to delegate to {@link java.lang.Math#cos(double)}/cos(float) * @return {@link java.lang.Math#cos(double)} casted to float/cos(float) - * * @see java.lang.Math#cos(double) * @see cos(float) */ - @OpenCLMapping(mapTo = "cos") - protected float cos(float _f) { - return (float) Math.cos(_f); - } + @OpenCLMapping(mapTo = "cos") + protected float cos(float _f) { + return (float) Math.cos(_f); + } - /** - * Delegates to either {@link java.lang.Math#cos(double)} (Java) or cos(double) (OpenCL). - * + /** + * Delegates to either {@link java.lang.Math#cos(double)} (Java) or cos(double) (OpenCL). + *

* User should note the differences in precision between Java and OpenCL's implementation of arithmetic functions to determine whether the difference in precision is acceptable. * * @param _d value to delegate to {@link java.lang.Math#cos(double)}/cos(double) * @return {@link java.lang.Math#cos(double)}/cos(double) - * * @see java.lang.Math#cos(double) * @see cos(double) */ - @OpenCLMapping(mapTo = "cos") - protected double cos(double _d) { - return Math.cos(_d); - } + @OpenCLMapping(mapTo = "cos") + protected double cos(double _d) { + return Math.cos(_d); + } - /** - * Delegates to either {@link java.lang.Math#exp(double)} (Java) or exp(float) (OpenCL). - * + /** + * Delegates to either {@link java.lang.Math#exp(double)} (Java) or exp(float) (OpenCL). + *

* User should note the differences in precision between Java and OpenCL's implementation of arithmetic functions to determine whether the difference in precision is acceptable. * * @param _f value to delegate to {@link java.lang.Math#exp(double)}/exp(float) * @return {@link java.lang.Math#exp(double)} casted to float/exp(float) - * * @see java.lang.Math#exp(double) * @see exp(float) */ - @OpenCLMapping(mapTo = "exp") - protected float exp(float _f) { - return (float) Math.exp(_f); - } + @OpenCLMapping(mapTo = "exp") + protected float exp(float _f) { + return (float) Math.exp(_f); + } - /** - * Delegates to either {@link java.lang.Math#exp(double)} (Java) or exp(double) (OpenCL). - * + /** + * Delegates to either {@link java.lang.Math#exp(double)} (Java) or exp(double) (OpenCL). + *

* User should note the differences in precision between Java and OpenCL's implementation of arithmetic functions to determine whether the difference in precision is acceptable. * * @param _d value to delegate to {@link java.lang.Math#exp(double)}/exp(double) * @return {@link java.lang.Math#exp(double)}/exp(double) - * * @see java.lang.Math#exp(double) * @see exp(double) */ - @OpenCLMapping(mapTo = "exp") - protected double exp(double _d) { - return Math.exp(_d); - } + @OpenCLMapping(mapTo = "exp") + protected double exp(double _d) { + return Math.exp(_d); + } - /** - * Delegates to either {@link java.lang.Math#abs(float)} (Java) or fabs(float) (OpenCL). - * + /** + * Delegates to either {@link java.lang.Math#abs(float)} (Java) or fabs(float) (OpenCL). + *

* User should note the differences in precision between Java and OpenCL's implementation of arithmetic functions to determine whether the difference in precision is acceptable. * * @param _f value to delegate to {@link java.lang.Math#abs(float)}/fabs(float) * @return {@link java.lang.Math#abs(float)}/fabs(float) - * * @see java.lang.Math#abs(float) * @see fabs(float) */ - @OpenCLMapping(mapTo = "fabs") - protected float abs(float _f) { - return Math.abs(_f); - } + @OpenCLMapping(mapTo = "fabs") + protected float abs(float _f) { + return Math.abs(_f); + } - /** - * Delegates to either {@link java.lang.Integer#bitCount(int)} (Java) or popcount(int) (OpenCL). + /** + * Delegates to either {@link java.lang.Integer#bitCount(int)} (Java) or popcount(int) (OpenCL). * * @param _i value to delegate to {@link java.lang.Integer#bitCount(int)}/popcount(int) * @return {@link java.lang.Integer#bitCount(int)}/popcount(int) * @see java.lang.Integer#bitCount(int) * @see popcount(int) */ - @OpenCLMapping(mapTo = "popcount") - protected int popcount(int _i) { - return Integer.bitCount(_i); - } + @OpenCLMapping(mapTo = "popcount") + protected int popcount(int _i) { + return Integer.bitCount(_i); + } - /** - * Delegates to either {@link java.lang.Long#bitCount(long)} (Java) or popcount(long) (OpenCL). + /** + * Delegates to either {@link java.lang.Long#bitCount(long)} (Java) or popcount(long) (OpenCL). * * @param _i value to delegate to {@link java.lang.Long#bitCount(long)}/popcount(long) * @return {@link java.lang.Long#bitCount(long)}/popcount(long) * @see java.lang.Long#bitCount(long) * @see popcount(long) */ - @OpenCLMapping(mapTo = "popcount") - protected long popcount(long _i) { - return Long.bitCount(_i); - } + @OpenCLMapping(mapTo = "popcount") + protected long popcount(long _i) { + return Long.bitCount(_i); + } - /** - * Delegates to either {@link java.lang.Integer#numberOfLeadingZeros(int)} (Java) or clz(int) (OpenCL). + /** + * Delegates to either {@link java.lang.Integer#numberOfLeadingZeros(int)} (Java) or clz(int) (OpenCL). * * @param _i value to delegate to {@link java.lang.Integer#numberOfLeadingZeros(int)}/clz(int) * @return {@link java.lang.Integer#numberOfLeadingZeros(int)}/clz(int) @@ -1352,566 +1335,531 @@ protected long popcount(long _i) { * @see clz(int) */ - @OpenCLMapping(mapTo = "clz") - protected int clz(int _i) { - return Integer.numberOfLeadingZeros(_i); - } + @OpenCLMapping(mapTo = "clz") + protected int clz(int _i) { + return Integer.numberOfLeadingZeros(_i); + } - /** - * Delegates to either {@link java.lang.Long#numberOfLeadingZeros(long)} (Java) or clz(long) (OpenCL). + /** + * Delegates to either {@link java.lang.Long#numberOfLeadingZeros(long)} (Java) or clz(long) (OpenCL). * * @param _l value to delegate to {@link java.lang.Long#numberOfLeadingZeros(long)}/clz(long) * @return {@link java.lang.Long#numberOfLeadingZeros(long)}/clz(long) * @see java.lang.Long#numberOfLeadingZeros(long) * @see clz(long) */ - - - @OpenCLMapping(mapTo = "clz") - protected long clz(long _l) { - return Long.numberOfLeadingZeros(_l); - } + @OpenCLMapping(mapTo = "clz") + protected long clz(long _l) { + return Long.numberOfLeadingZeros(_l); + } /** - * Delegates to either {@link java.lang.Math#abs(double)} (Java) or fabs(double) (OpenCL). - * + * Delegates to either {@link java.lang.Math#abs(double)} (Java) or fabs(double) (OpenCL). + *

* User should note the differences in precision between Java and OpenCL's implementation of arithmetic functions to determine whether the difference in precision is acceptable. * * @param _d value to delegate to {@link java.lang.Math#abs(double)}/fabs(double) * @return {@link java.lang.Math#abs(double)}/fabs(double) - * * @see java.lang.Math#abs(double) * @see fabs(double) */ - @OpenCLMapping(mapTo = "fabs") - protected double abs(double _d) { - return Math.abs(_d); - } + @OpenCLMapping(mapTo = "fabs") + protected double abs(double _d) { + return Math.abs(_d); + } - /** - * Delegates to either {@link java.lang.Math#abs(int)} (Java) or abs(int) (OpenCL). - * + /** + * Delegates to either {@link java.lang.Math#abs(int)} (Java) or abs(int) (OpenCL). + *

* User should note the differences in precision between Java and OpenCL's implementation of arithmetic functions to determine whether the difference in precision is acceptable. * * @param n value to delegate to {@link java.lang.Math#abs(int)}/abs(int) * @return {@link java.lang.Math#abs(int)}/abs(int) - * * @see java.lang.Math#abs(int) * @see abs(int) */ - @OpenCLMapping(mapTo = "abs") - protected int abs(int n) { - return Math.abs(n); - } + @OpenCLMapping(mapTo = "abs") + protected int abs(int n) { + return Math.abs(n); + } - /** - * Delegates to either {@link java.lang.Math#abs(long)} (Java) or abs(long) (OpenCL). - * + /** + * Delegates to either {@link java.lang.Math#abs(long)} (Java) or abs(long) (OpenCL). + *

* User should note the differences in precision between Java and OpenCL's implementation of arithmetic functions to determine whether the difference in precision is acceptable. * * @param n value to delegate to {@link java.lang.Math#abs(long)}/abs(long) * @return {@link java.lang.Math#abs(long)}/abs(long) - * * @see java.lang.Math#abs(long) * @see abs(long) */ - @OpenCLMapping(mapTo = "abs") - protected long abs(long n) { - return Math.abs(n); - } + @OpenCLMapping(mapTo = "abs") + protected long abs(long n) { + return Math.abs(n); + } - /** - * Delegates to either {@link java.lang.Math#floor(double)} (Java) or floor(float) (OpenCL). - * + /** + * Delegates to either {@link java.lang.Math#floor(double)} (Java) or floor(float) (OpenCL). + *

* User should note the differences in precision between Java and OpenCL's implementation of arithmetic functions to determine whether the difference in precision is acceptable. * * @param _f value to delegate to {@link java.lang.Math#floor(double)}/floor(float) * @return {@link java.lang.Math#floor(double)} casted to float/floor(float) - * * @see java.lang.Math#floor(double) * @see floor(float) */ - @OpenCLMapping(mapTo = "floor") - protected float floor(float _f) { - return (float) Math.floor(_f); - } + @OpenCLMapping(mapTo = "floor") + protected float floor(float _f) { + return (float) Math.floor(_f); + } - /** - * Delegates to either {@link java.lang.Math#floor(double)} (Java) or floor(double) (OpenCL). - * + /** + * Delegates to either {@link java.lang.Math#floor(double)} (Java) or floor(double) (OpenCL). + *

* User should note the differences in precision between Java and OpenCL's implementation of arithmetic functions to determine whether the difference in precision is acceptable. * * @param _d value to delegate to {@link java.lang.Math#floor(double)}/floor(double) * @return {@link java.lang.Math#floor(double)}/floor(double) - * * @see java.lang.Math#floor(double) * @see floor(double) */ - @OpenCLMapping(mapTo = "floor") - protected double floor(double _d) { - return Math.floor(_d); - } + @OpenCLMapping(mapTo = "floor") + protected double floor(double _d) { + return Math.floor(_d); + } - /** - * Delegates to either {@link java.lang.Math#max(float, float)} (Java) or fmax(float, float) (OpenCL). - * + /** + * Delegates to either {@link java.lang.Math#max(float, float)} (Java) or fmax(float, float) (OpenCL). + *

* User should note the differences in precision between Java and OpenCL's implementation of arithmetic functions to determine whether the difference in precision is acceptable. * * @param _f1 value to delegate to first argument of {@link java.lang.Math#max(float, float)}/fmax(float, float) * @param _f2 value to delegate to second argument of {@link java.lang.Math#max(float, float)}/fmax(float, float) * @return {@link java.lang.Math#max(float, float)}/fmax(float, float) - * * @see java.lang.Math#max(float, float) * @see fmax(float, float) */ - @OpenCLMapping(mapTo = "fmax") - protected float max(float _f1, float _f2) { - return Math.max(_f1, _f2); - } + @OpenCLMapping(mapTo = "fmax") + protected float max(float _f1, float _f2) { + return Math.max(_f1, _f2); + } - /** - * Delegates to either {@link java.lang.Math#max(double, double)} (Java) or fmax(double, double) (OpenCL). - * + /** + * Delegates to either {@link java.lang.Math#max(double, double)} (Java) or fmax(double, double) (OpenCL). + *

* User should note the differences in precision between Java and OpenCL's implementation of arithmetic functions to determine whether the difference in precision is acceptable. * * @param _d1 value to delegate to first argument of {@link java.lang.Math#max(double, double)}/fmax(double, double) * @param _d2 value to delegate to second argument of {@link java.lang.Math#max(double, double)}/fmax(double, double) * @return {@link java.lang.Math#max(double, double)}/fmax(double, double) - * * @see java.lang.Math#max(double, double) * @see fmax(double, double) */ - @OpenCLMapping(mapTo = "fmax") - protected double max(double _d1, double _d2) { - return Math.max(_d1, _d2); - } + @OpenCLMapping(mapTo = "fmax") + protected double max(double _d1, double _d2) { + return Math.max(_d1, _d2); + } - /** - * Delegates to either {@link java.lang.Math#max(int, int)} (Java) or max(int, int) (OpenCL). - * + /** + * Delegates to either {@link java.lang.Math#max(int, int)} (Java) or max(int, int) (OpenCL). + *

* User should note the differences in precision between Java and OpenCL's implementation of arithmetic functions to determine whether the difference in precision is acceptable. * * @param n1 value to delegate to {@link java.lang.Math#max(int, int)}/max(int, int) * @param n2 value to delegate to {@link java.lang.Math#max(int, int)}/max(int, int) * @return {@link java.lang.Math#max(int, int)}/max(int, int) - * * @see java.lang.Math#max(int, int) * @see max(int, int) */ - @OpenCLMapping(mapTo = "max") - protected int max(int n1, int n2) { - return Math.max(n1, n2); - } + @OpenCLMapping(mapTo = "max") + protected int max(int n1, int n2) { + return Math.max(n1, n2); + } - /** - * Delegates to either {@link java.lang.Math#max(long, long)} (Java) or max(long, long) (OpenCL). - * + /** + * Delegates to either {@link java.lang.Math#max(long, long)} (Java) or max(long, long) (OpenCL). + *

* User should note the differences in precision between Java and OpenCL's implementation of arithmetic functions to determine whether the difference in precision is acceptable. * * @param n1 value to delegate to first argument of {@link java.lang.Math#max(long, long)}/max(long, long) * @param n2 value to delegate to second argument of {@link java.lang.Math#max(long, long)}/max(long, long) * @return {@link java.lang.Math#max(long, long)}/max(long, long) - * * @see java.lang.Math#max(long, long) * @see max(long, long) */ - @OpenCLMapping(mapTo = "max") - protected long max(long n1, long n2) { - return Math.max(n1, n2); - } + @OpenCLMapping(mapTo = "max") + protected long max(long n1, long n2) { + return Math.max(n1, n2); + } - /** - * Delegates to either {@link java.lang.Math#min(float, float)} (Java) or fmin(float, float) (OpenCL). - * + /** + * Delegates to either {@link java.lang.Math#min(float, float)} (Java) or fmin(float, float) (OpenCL). + *

* User should note the differences in precision between Java and OpenCL's implementation of arithmetic functions to determine whether the difference in precision is acceptable. * * @param _f1 value to delegate to first argument of {@link java.lang.Math#min(float, float)}/fmin(float, float) * @param _f2 value to delegate to second argument of {@link java.lang.Math#min(float, float)}/fmin(float, float) * @return {@link java.lang.Math#min(float, float)}/fmin(float, float) - * * @see java.lang.Math#min(float, float) * @see fmin(float, float) */ - @OpenCLMapping(mapTo = "fmin") - protected float min(float _f1, float _f2) { - return Math.min(_f1, _f2); - } + @OpenCLMapping(mapTo = "fmin") + protected float min(float _f1, float _f2) { + return Math.min(_f1, _f2); + } - /** - * Delegates to either {@link java.lang.Math#min(double, double)} (Java) or fmin(double, double) (OpenCL). - * + /** + * Delegates to either {@link java.lang.Math#min(double, double)} (Java) or fmin(double, double) (OpenCL). + *

* User should note the differences in precision between Java and OpenCL's implementation of arithmetic functions to determine whether the difference in precision is acceptable. * * @param _d1 value to delegate to first argument of {@link java.lang.Math#min(double, double)}/fmin(double, double) * @param _d2 value to delegate to second argument of {@link java.lang.Math#min(double, double)}/fmin(double, double) * @return {@link java.lang.Math#min(double, double)}/fmin(double, double) - * * @see java.lang.Math#min(double, double) * @see fmin(double, double) */ - @OpenCLMapping(mapTo = "fmin") - protected double min(double _d1, double _d2) { - return Math.min(_d1, _d2); - } + @OpenCLMapping(mapTo = "fmin") + protected double min(double _d1, double _d2) { + return Math.min(_d1, _d2); + } - /** - * Delegates to either {@link java.lang.Math#min(int, int)} (Java) or min(int, int) (OpenCL). - * + /** + * Delegates to either {@link java.lang.Math#min(int, int)} (Java) or min(int, int) (OpenCL). + *

* User should note the differences in precision between Java and OpenCL's implementation of arithmetic functions to determine whether the difference in precision is acceptable. * * @param n1 value to delegate to first argument of {@link java.lang.Math#min(int, int)}/min(int, int) * @param n2 value to delegate to second argument of {@link java.lang.Math#min(int, int)}/min(int, int) * @return {@link java.lang.Math#min(int, int)}/min(int, int) - * * @see java.lang.Math#min(int, int) * @see min(int, int) */ - @OpenCLMapping(mapTo = "min") - protected int min(int n1, int n2) { - return Math.min(n1, n2); - } + @OpenCLMapping(mapTo = "min") + protected int min(int n1, int n2) { + return Math.min(n1, n2); + } - /** - * Delegates to either {@link java.lang.Math#min(long, long)} (Java) or min(long, long) (OpenCL). - * + /** + * Delegates to either {@link java.lang.Math#min(long, long)} (Java) or min(long, long) (OpenCL). + *

* User should note the differences in precision between Java and OpenCL's implementation of arithmetic functions to determine whether the difference in precision is acceptable. * * @param n1 value to delegate to first argument of {@link java.lang.Math#min(long, long)}/min(long, long) * @param n2 value to delegate to second argument of {@link java.lang.Math#min(long, long)}/min(long, long) * @return {@link java.lang.Math#min(long, long)}/min(long, long) - * * @see java.lang.Math#min(long, long) * @see min(long, long) */ - @OpenCLMapping(mapTo = "min") - protected long min(long n1, long n2) { - return Math.min(n1, n2); - } + @OpenCLMapping(mapTo = "min") + protected long min(long n1, long n2) { + return Math.min(n1, n2); + } - /** - * Delegates to either {@link java.lang.Math#log(double)} (Java) or log(float) (OpenCL). - * + /** + * Delegates to either {@link java.lang.Math#log(double)} (Java) or log(float) (OpenCL). + *

* User should note the differences in precision between Java and OpenCL's implementation of arithmetic functions to determine whether the difference in precision is acceptable. * * @param _f value to delegate to {@link java.lang.Math#log(double)}/log(float) * @return {@link java.lang.Math#log(double)} casted to float/log(float) - * * @see java.lang.Math#log(double) * @see log(float) */ - @OpenCLMapping(mapTo = "log") - protected float log(float _f) { - return (float) Math.log(_f); - } + @OpenCLMapping(mapTo = "log") + protected float log(float _f) { + return (float) Math.log(_f); + } - /** - * Delegates to either {@link java.lang.Math#log(double)} (Java) or log(double) (OpenCL). - * + /** + * Delegates to either {@link java.lang.Math#log(double)} (Java) or log(double) (OpenCL). + *

* User should note the differences in precision between Java and OpenCL's implementation of arithmetic functions to determine whether the difference in precision is acceptable. * * @param _d value to delegate to {@link java.lang.Math#log(double)}/log(double) * @return {@link java.lang.Math#log(double)}/log(double) - * * @see java.lang.Math#log(double) * @see log(double) */ - @OpenCLMapping(mapTo = "log") - protected double log(double _d) { - return Math.log(_d); - } + @OpenCLMapping(mapTo = "log") + protected double log(double _d) { + return Math.log(_d); + } - /** - * Delegates to either {@link java.lang.Math#pow(double, double)} (Java) or pow(float, float) (OpenCL). - * + /** + * Delegates to either {@link java.lang.Math#pow(double, double)} (Java) or pow(float, float) (OpenCL). + *

* User should note the differences in precision between Java and OpenCL's implementation of arithmetic functions to determine whether the difference in precision is acceptable. * * @param _f1 value to delegate to first argument of {@link java.lang.Math#pow(double, double)}/pow(float, float) * @param _f2 value to delegate to second argument of {@link java.lang.Math#pow(double, double)}/pow(float, float) * @return {@link java.lang.Math#pow(double, double)} casted to float/pow(float, float) - * * @see java.lang.Math#pow(double, double) * @see pow(float, float) */ - @OpenCLMapping(mapTo = "pow") - protected float pow(float _f1, float _f2) { - return (float) Math.pow(_f1, _f2); - } + @OpenCLMapping(mapTo = "pow") + protected float pow(float _f1, float _f2) { + return (float) Math.pow(_f1, _f2); + } - /** - * Delegates to either {@link java.lang.Math#pow(double, double)} (Java) or pow(double, double) (OpenCL). - * + /** + * Delegates to either {@link java.lang.Math#pow(double, double)} (Java) or pow(double, double) (OpenCL). + *

* User should note the differences in precision between Java and OpenCL's implementation of arithmetic functions to determine whether the difference in precision is acceptable. * * @param _d1 value to delegate to first argument of {@link java.lang.Math#pow(double, double)}/pow(double, double) * @param _d2 value to delegate to second argument of {@link java.lang.Math#pow(double, double)}/pow(double, double) * @return {@link java.lang.Math#pow(double, double)}/pow(double, double) - * * @see java.lang.Math#pow(double, double) * @see pow(double, double) */ - @OpenCLMapping(mapTo = "pow") - protected double pow(double _d1, double _d2) { - return Math.pow(_d1, _d2); - } + @OpenCLMapping(mapTo = "pow") + protected double pow(double _d1, double _d2) { + return Math.pow(_d1, _d2); + } - /** - * Delegates to either {@link java.lang.Math#IEEEremainder(double, double)} (Java) or remainder(float, float) (OpenCL). - * + /** + * Delegates to either {@link java.lang.Math#IEEEremainder(double, double)} (Java) or remainder(float, float) (OpenCL). + *

* User should note the differences in precision between Java and OpenCL's implementation of arithmetic functions to determine whether the difference in precision is acceptable. * * @param _f1 value to delegate to first argument of {@link java.lang.Math#IEEEremainder(double, double)}/remainder(float, float) * @param _f2 value to delegate to second argument of {@link java.lang.Math#IEEEremainder(double, double)}/remainder(float, float) * @return {@link java.lang.Math#IEEEremainder(double, double)} casted to float/remainder(float, float) - * * @see java.lang.Math#IEEEremainder(double, double) * @see remainder(float, float) */ - @OpenCLMapping(mapTo = "remainder") - protected float IEEEremainder(float _f1, float _f2) { - return (float) Math.IEEEremainder(_f1, _f2); - } + @OpenCLMapping(mapTo = "remainder") + protected float IEEEremainder(float _f1, float _f2) { + return (float) Math.IEEEremainder(_f1, _f2); + } - /** - * Delegates to either {@link java.lang.Math#IEEEremainder(double, double)} (Java) or remainder(double, double) (OpenCL). - * + /** + * Delegates to either {@link java.lang.Math#IEEEremainder(double, double)} (Java) or remainder(double, double) (OpenCL). + *

* User should note the differences in precision between Java and OpenCL's implementation of arithmetic functions to determine whether the difference in precision is acceptable. * * @param _d1 value to delegate to first argument of {@link java.lang.Math#IEEEremainder(double, double)}/remainder(double, double) * @param _d2 value to delegate to second argument of {@link java.lang.Math#IEEEremainder(double, double)}/remainder(double, double) * @return {@link java.lang.Math#IEEEremainder(double, double)}/remainder(double, double) - * * @see java.lang.Math#IEEEremainder(double, double) * @see remainder(double, double) */ - @OpenCLMapping(mapTo = "remainder") - protected double IEEEremainder(double _d1, double _d2) { - return Math.IEEEremainder(_d1, _d2); - } + @OpenCLMapping(mapTo = "remainder") + protected double IEEEremainder(double _d1, double _d2) { + return Math.IEEEremainder(_d1, _d2); + } - /** - * Delegates to either {@link java.lang.Math#toRadians(double)} (Java) or radians(float) (OpenCL). - * + /** + * Delegates to either {@link java.lang.Math#toRadians(double)} (Java) or radians(float) (OpenCL). + *

* User should note the differences in precision between Java and OpenCL's implementation of arithmetic functions to determine whether the difference in precision is acceptable. * * @param _f value to delegate to {@link java.lang.Math#toRadians(double)}/radians(float) * @return {@link java.lang.Math#toRadians(double)} casted to float/radians(float) - * * @see java.lang.Math#toRadians(double) * @see radians(float) */ - @OpenCLMapping(mapTo = "radians") - protected float toRadians(float _f) { - return (float) Math.toRadians(_f); - } + @OpenCLMapping(mapTo = "radians") + protected float toRadians(float _f) { + return (float) Math.toRadians(_f); + } - /** - * Delegates to either {@link java.lang.Math#toRadians(double)} (Java) or radians(double) (OpenCL). - * + /** + * Delegates to either {@link java.lang.Math#toRadians(double)} (Java) or radians(double) (OpenCL). + *

* User should note the differences in precision between Java and OpenCL's implementation of arithmetic functions to determine whether the difference in precision is acceptable. * * @param _d value to delegate to {@link java.lang.Math#toRadians(double)}/radians(double) * @return {@link java.lang.Math#toRadians(double)}/radians(double) - * * @see java.lang.Math#toRadians(double) * @see radians(double) */ - @OpenCLMapping(mapTo = "radians") - protected double toRadians(double _d) { - return Math.toRadians(_d); - } + @OpenCLMapping(mapTo = "radians") + protected double toRadians(double _d) { + return Math.toRadians(_d); + } - /** - * Delegates to either {@link java.lang.Math#toDegrees(double)} (Java) or degrees(float) (OpenCL). - * + /** + * Delegates to either {@link java.lang.Math#toDegrees(double)} (Java) or degrees(float) (OpenCL). + *

* User should note the differences in precision between Java and OpenCL's implementation of arithmetic functions to determine whether the difference in precision is acceptable. * * @param _f value to delegate to {@link java.lang.Math#toDegrees(double)}/degrees(float) * @return {@link java.lang.Math#toDegrees(double)} casted to float/degrees(float) - * * @see java.lang.Math#toDegrees(double) * @see degrees(float) */ - @OpenCLMapping(mapTo = "degrees") - protected float toDegrees(float _f) { - return (float) Math.toDegrees(_f); - } + @OpenCLMapping(mapTo = "degrees") + protected float toDegrees(float _f) { + return (float) Math.toDegrees(_f); + } - /** - * Delegates to either {@link java.lang.Math#toDegrees(double)} (Java) or degrees(double) (OpenCL). - * + /** + * Delegates to either {@link java.lang.Math#toDegrees(double)} (Java) or degrees(double) (OpenCL). + *

* User should note the differences in precision between Java and OpenCL's implementation of arithmetic functions to determine whether the difference in precision is acceptable. * * @param _d value to delegate to {@link java.lang.Math#toDegrees(double)}/degrees(double) * @return {@link java.lang.Math#toDegrees(double)}/degrees(double) - * * @see java.lang.Math#toDegrees(double) * @see degrees(double) */ - @OpenCLMapping(mapTo = "degrees") - protected double toDegrees(double _d) { - return Math.toDegrees(_d); - } + @OpenCLMapping(mapTo = "degrees") + protected double toDegrees(double _d) { + return Math.toDegrees(_d); + } - /** - * Delegates to either {@link java.lang.Math#rint(double)} (Java) or rint(float) (OpenCL). - * + /** + * Delegates to either {@link java.lang.Math#rint(double)} (Java) or rint(float) (OpenCL). + *

* User should note the differences in precision between Java and OpenCL's implementation of arithmetic functions to determine whether the difference in precision is acceptable. * * @param _f value to delegate to {@link java.lang.Math#rint(double)}/rint(float) * @return {@link java.lang.Math#rint(double)} casted to float/rint(float) - * * @see java.lang.Math#rint(double) * @see rint(float) */ - @OpenCLMapping(mapTo = "rint") - protected float rint(float _f) { - return (float) Math.rint(_f); - } + @OpenCLMapping(mapTo = "rint") + protected float rint(float _f) { + return (float) Math.rint(_f); + } - /** - * Delegates to either {@link java.lang.Math#rint(double)} (Java) or rint(double) (OpenCL). - * + /** + * Delegates to either {@link java.lang.Math#rint(double)} (Java) or rint(double) (OpenCL). + *

* User should note the differences in precision between Java and OpenCL's implementation of arithmetic functions to determine whether the difference in precision is acceptable. * * @param _d value to delegate to {@link java.lang.Math#rint(double)}/rint(double) * @return {@link java.lang.Math#rint(double)}/rint(double) - * * @see java.lang.Math#rint(double) * @see rint(double) */ - @OpenCLMapping(mapTo = "rint") - protected double rint(double _d) { - return Math.rint(_d); - } + @OpenCLMapping(mapTo = "rint") + protected double rint(double _d) { + return Math.rint(_d); + } - /** - * Delegates to either {@link java.lang.Math#round(float)} (Java) or round(float) (OpenCL). - * + /** + * Delegates to either {@link java.lang.Math#round(float)} (Java) or round(float) (OpenCL). + *

* User should note the differences in precision between Java and OpenCL's implementation of arithmetic functions to determine whether the difference in precision is acceptable. * * @param _f value to delegate to {@link java.lang.Math#round(float)}/round(float) * @return {@link java.lang.Math#round(float)}/round(float) - * * @see java.lang.Math#round(float) * @see round(float) */ - @OpenCLMapping(mapTo = "round") - protected int round(float _f) { - return Math.round(_f); - } + @OpenCLMapping(mapTo = "round") + protected int round(float _f) { + return Math.round(_f); + } - /** - * Delegates to either {@link java.lang.Math#round(double)} (Java) or round(double) (OpenCL). - * + /** + * Delegates to either {@link java.lang.Math#round(double)} (Java) or round(double) (OpenCL). + *

* User should note the differences in precision between Java and OpenCL's implementation of arithmetic functions to determine whether the difference in precision is acceptable. * * @param _d value to delegate to {@link java.lang.Math#round(double)}/round(double) * @return {@link java.lang.Math#round(double)}/round(double) - * * @see java.lang.Math#round(double) * @see round(double) */ - @OpenCLMapping(mapTo = "round") - protected long round(double _d) { - return Math.round(_d); - } + @OpenCLMapping(mapTo = "round") + protected long round(double _d) { + return Math.round(_d); + } - /** - * Delegates to either {@link java.lang.Math#sin(double)} (Java) or sin(float) (OpenCL). - * + /** + * Delegates to either {@link java.lang.Math#sin(double)} (Java) or sin(float) (OpenCL). + *

* User should note the differences in precision between Java and OpenCL's implementation of arithmetic functions to determine whether the difference in precision is acceptable. * * @param _f value to delegate to {@link java.lang.Math#sin(double)}/sin(float) * @return {@link java.lang.Math#sin(double)} casted to float/sin(float) - * * @see java.lang.Math#sin(double) * @see sin(float) */ - @OpenCLMapping(mapTo = "sin") - protected float sin(float _f) { - return (float) Math.sin(_f); - } + @OpenCLMapping(mapTo = "sin") + protected float sin(float _f) { + return (float) Math.sin(_f); + } - /** - * Delegates to either {@link java.lang.Math#sin(double)} (Java) or sin(double) (OpenCL). - * + /** + * Delegates to either {@link java.lang.Math#sin(double)} (Java) or sin(double) (OpenCL). + *

* User should note the differences in precision between Java and OpenCL's implementation of arithmetic functions to determine whether the difference in precision is acceptable. * * @param _d value to delegate to {@link java.lang.Math#sin(double)}/sin(double) * @return {@link java.lang.Math#sin(double)}/sin(double) - * * @see java.lang.Math#sin(double) * @see sin(double) */ - @OpenCLMapping(mapTo = "sin") - protected double sin(double _d) { - return Math.sin(_d); - } + @OpenCLMapping(mapTo = "sin") + protected double sin(double _d) { + return Math.sin(_d); + } - /** - * Delegates to either {@link java.lang.Math#sqrt(double)} (Java) or sqrt(float) (OpenCL). - * + /** + * Delegates to either {@link java.lang.Math#sqrt(double)} (Java) or sqrt(float) (OpenCL). + *

* User should note the differences in precision between Java and OpenCL's implementation of arithmetic functions to determine whether the difference in precision is acceptable. * * @param _f value to delegate to {@link java.lang.Math#sqrt(double)}/sqrt(float) * @return {@link java.lang.Math#sqrt(double)} casted to float/sqrt(float) - * * @see java.lang.Math#sqrt(double) * @see sqrt(float) */ - @OpenCLMapping(mapTo = "sqrt") - protected float sqrt(float _f) { - return (float) Math.sqrt(_f); - } + @OpenCLMapping(mapTo = "sqrt") + protected float sqrt(float _f) { + return (float) Math.sqrt(_f); + } - /** - * Delegates to either {@link java.lang.Math#sqrt(double)} (Java) or sqrt(double) (OpenCL). - * + /** + * Delegates to either {@link java.lang.Math#sqrt(double)} (Java) or sqrt(double) (OpenCL). + *

* User should note the differences in precision between Java and OpenCL's implementation of arithmetic functions to determine whether the difference in precision is acceptable. * * @param _d value to delegate to {@link java.lang.Math#sqrt(double)}/sqrt(double) * @return {@link java.lang.Math#sqrt(double)}/sqrt(double) - * * @see java.lang.Math#sqrt(double) * @see sqrt(double) */ - @OpenCLMapping(mapTo = "sqrt") - protected double sqrt(double _d) { - return Math.sqrt(_d); - } + @OpenCLMapping(mapTo = "sqrt") + protected double sqrt(double _d) { + return Math.sqrt(_d); + } - /** - * Delegates to either {@link java.lang.Math#tan(double)} (Java) or tan(float) (OpenCL). - * + /** + * Delegates to either {@link java.lang.Math#tan(double)} (Java) or tan(float) (OpenCL). + *

* User should note the differences in precision between Java and OpenCL's implementation of arithmetic functions to determine whether the difference in precision is acceptable. * * @param _f value to delegate to {@link java.lang.Math#tan(double)}/tan(float) * @return {@link java.lang.Math#tan(double)} casted to float/tan(float) - * * @see java.lang.Math#tan(double) * @see tan(float) */ - @OpenCLMapping(mapTo = "tan") - protected float tan(float _f) { - return (float) Math.tan(_f); - } + @OpenCLMapping(mapTo = "tan") + protected float tan(float _f) { + return (float) Math.tan(_f); + } - /** - * Delegates to either {@link java.lang.Math#tan(double)} (Java) or tan(double) (OpenCL). - * + /** + * Delegates to either {@link java.lang.Math#tan(double)} (Java) or tan(double) (OpenCL). + *

* User should note the differences in precision between Java and OpenCL's implementation of arithmetic functions to determine whether the difference in precision is acceptable. * * @param _d value to delegate to {@link java.lang.Math#tan(double)}/tan(double) * @return {@link java.lang.Math#tan(double)}/tan(double) - * * @see java.lang.Math#tan(double) * @see tan(double) */ - @OpenCLMapping(mapTo = "tan") - protected double tan(double _d) { - return Math.tan(_d); - } + @OpenCLMapping(mapTo = "tan") + protected double tan(double _d) { + return Math.tan(_d); + } private static final double LOG_2_RECIPROCAL = 1.0D / Math.log(2.0D); private static final double PI_RECIPROCAL = 1.0D / Math.PI; @@ -1923,7 +1871,7 @@ protected final double acospi(final double a) { @OpenCLMapping(mapTo = "acospi") protected final float acospi(final float a) { - return (float)(Math.acos(a) * PI_RECIPROCAL); + return (float) (Math.acos(a) * PI_RECIPROCAL); } @OpenCLMapping(mapTo = "asinpi") @@ -1933,7 +1881,7 @@ protected final double asinpi(final double a) { @OpenCLMapping(mapTo = "asinpi") protected final float asinpi(final float a) { - return (float)(Math.asin(a) * PI_RECIPROCAL); + return (float) (Math.asin(a) * PI_RECIPROCAL); } @OpenCLMapping(mapTo = "atanpi") @@ -1943,7 +1891,7 @@ protected final double atanpi(final double a) { @OpenCLMapping(mapTo = "atanpi") protected final float atanpi(final float a) { - return (float)(Math.atan(a) * PI_RECIPROCAL); + return (float) (Math.atan(a) * PI_RECIPROCAL); } @OpenCLMapping(mapTo = "atan2pi") @@ -1953,7 +1901,7 @@ protected final double atan2pi(final double y, final double x) { @OpenCLMapping(mapTo = "atan2pi") protected final float atan2pi(final float y, final double x) { - return (float)(Math.atan2(y, x) * PI_RECIPROCAL); + return (float) (Math.atan2(y, x) * PI_RECIPROCAL); } @OpenCLMapping(mapTo = "cbrt") @@ -1963,7 +1911,7 @@ protected final double cbrt(final double a) { @OpenCLMapping(mapTo = "cbrt") protected final float cbrt(final float a) { - return (float)(Math.cbrt(a)); + return (float) (Math.cbrt(a)); } @OpenCLMapping(mapTo = "cosh") @@ -1973,7 +1921,7 @@ protected final double cosh(final double x) { @OpenCLMapping(mapTo = "cosh") protected final float cosh(final float x) { - return (float)(Math.cosh(x)); + return (float) (Math.cosh(x)); } @OpenCLMapping(mapTo = "cospi") @@ -1983,7 +1931,7 @@ protected final double cospi(final double a) { @OpenCLMapping(mapTo = "cospi") protected final float cospi(final float a) { - return (float)(Math.cos(a * Math.PI)); + return (float) (Math.cos(a * Math.PI)); } @OpenCLMapping(mapTo = "exp2") @@ -1993,7 +1941,7 @@ protected final double exp2(final double a) { @OpenCLMapping(mapTo = "exp2") protected final float exp2(final float a) { - return (float)(Math.pow(2.0D, a)); + return (float) (Math.pow(2.0D, a)); } @OpenCLMapping(mapTo = "exp10") @@ -2003,7 +1951,7 @@ protected final double exp10(final double a) { @OpenCLMapping(mapTo = "exp10") protected final float exp10(final float a) { - return (float)(Math.pow(10.0D, a)); + return (float) (Math.pow(10.0D, a)); } @OpenCLMapping(mapTo = "expm1") @@ -2013,7 +1961,7 @@ protected final double expm1(final double x) { @OpenCLMapping(mapTo = "expm1") protected final float expm1(final float x) { - return (float)(Math.expm1(x)); + return (float) (Math.expm1(x)); } @OpenCLMapping(mapTo = "log2") @@ -2023,7 +1971,7 @@ protected final double log2(final double a) { @OpenCLMapping(mapTo = "log2") protected final float log2(final float a) { - return (float)(log(a) * LOG_2_RECIPROCAL); + return (float) (log(a) * LOG_2_RECIPROCAL); } @OpenCLMapping(mapTo = "log10") @@ -2033,7 +1981,7 @@ protected final double log10(final double a) { @OpenCLMapping(mapTo = "log10") protected final float log10(final float a) { - return (float)(Math.log10(a)); + return (float) (Math.log10(a)); } @OpenCLMapping(mapTo = "log1p") @@ -2043,7 +1991,7 @@ protected final double log1p(final double x) { @OpenCLMapping(mapTo = "log1p") protected final float log1p(final float x) { - return (float)(Math.log1p(x)); + return (float) (Math.log1p(x)); } @OpenCLMapping(mapTo = "mad") @@ -2058,36 +2006,34 @@ protected final float mad(final float a, final float b, final float c) { /** * Delegates to either {code}a*b+c{code} (Java) or fma(float, float, float) (OpenCL). - * - * User should note the differences in precision between Java and OpenCL's implementation of arithmetic functions to determine whether the difference in precision is acceptable. - * - * @param a value to delegate to first argument of fma(float, float, float) - * @param b value to delegate to second argument of fma(float, float, float) - * @param c value to delegate to third argument of fma(float, float, float) - * @return a * b + c / fma(float, float, float) - * - * @see fma(float, float, float) - */ + *

+ * User should note the differences in precision between Java and OpenCL's implementation of arithmetic functions to determine whether the difference in precision is acceptable. + * + * @param a value to delegate to first argument of fma(float, float, float) + * @param b value to delegate to second argument of fma(float, float, float) + * @param c value to delegate to third argument of fma(float, float, float) + * @return a * b + c / fma(float, float, float) + * @see fma(float, float, float) + */ @OpenCLMapping(mapTo = "fma") protected float fma(final float a, final float b, final float c) { - return a * b + c; + return a * b + c; } /** * Delegates to either {code}a*b+c{code} (Java) or fma(double, double, double) (OpenCL). - * - * User should note the differences in precision between Java and OpenCL's implementation of arithmetic functions to determine whether the difference in precision is acceptable. - * - * @param a value to delegate to first argument of fma(double, double, double) - * @param b value to delegate to second argument of fma(double, double, double) - * @param c value to delegate to third argument of fma(double, double, double) - * @return a * b + c / fma(double, double, double) - * - * @see fma(double, double, double) - */ + *

+ * User should note the differences in precision between Java and OpenCL's implementation of arithmetic functions to determine whether the difference in precision is acceptable. + * + * @param a value to delegate to first argument of fma(double, double, double) + * @param b value to delegate to second argument of fma(double, double, double) + * @param c value to delegate to third argument of fma(double, double, double) + * @return a * b + c / fma(double, double, double) + * @see fma(double, double, double) + */ @OpenCLMapping(mapTo = "fma") protected double fma(final double a, final double b, final double c) { - return a * b + c; + return a * b + c; } @OpenCLMapping(mapTo = "nextafter") @@ -2097,17 +2043,16 @@ protected final double nextAfter(final double start, final double direction) { @OpenCLMapping(mapTo = "nextafter") protected final float nextAfter(final float start, final float direction) { - return (float)(Math.nextAfter(start, direction)); + return Math.nextAfter(start, direction); } /** * Delegates to either {@link java.lang.Math#sinh(double)} (Java) or sinh(double) (OpenCL). - * + *

* User should note the differences in precision between Java and OpenCL's implementation of arithmetic functions to determine whether the difference in precision is acceptable. * * @param x value to delegate to {@link java.lang.Math#sinh(double)}/sinh(double) * @return {@link java.lang.Math#sinh(double)}/sinh(double) - * * @see java.lang.Math#sinh(double) * @see sinh(double) */ @@ -2118,30 +2063,28 @@ protected final double sinh(final double x) { /** * Delegates to either {@link java.lang.Math#sinh(double)} (Java) or sinh(float) (OpenCL). - * + *

* User should note the differences in precision between Java and OpenCL's implementation of arithmetic functions to determine whether the difference in precision is acceptable. * * @param x value to delegate to {@link java.lang.Math#sinh(double)}/sinh(float) * @return {@link java.lang.Math#sinh(double)}/sinh(float) - * * @see java.lang.Math#sinh(double) * @see sinh(float) */ @OpenCLMapping(mapTo = "sinh") protected final float sinh(final float x) { - return (float)(Math.sinh(x)); + return (float) (Math.sinh(x)); } /** * Backed by either {@link java.lang.Math#sin(double)} (Java) or sinpi(double) (OpenCL). - * + *

* This method is equivelant to Math.sin(a * Math.PI) - * + *

* User should note the differences in precision between Java and OpenCL's implementation of arithmetic functions to determine whether the difference in precision is acceptable. * * @param a value to delegate to sinpi(double) or java equivelant * @return sinpi(double) or java equivelant - * * @see java.lang.Math#sin(double) * @see sinpi(double) */ @@ -2152,30 +2095,28 @@ protected final double sinpi(final double a) { /** * Backed by either {@link java.lang.Math#sin(double)} (Java) or sinpi(float) (OpenCL). - * + *

* This method is equivelant to Math.sin(a * Math.PI) - * + *

* User should note the differences in precision between Java and OpenCL's implementation of arithmetic functions to determine whether the difference in precision is acceptable. * * @param a value to delegate to sinpi(float) or java equivelant * @return sinpi(float) or java equivelant - * * @see java.lang.Math#sin(double) * @see sinpi(float) */ @OpenCLMapping(mapTo = "sinpi") protected final float sinpi(final float a) { - return (float)(Math.sin(a * Math.PI)); + return (float) (Math.sin(a * Math.PI)); } /** * Delegates to either {@link java.lang.Math#tanh(double)} (Java) or tanh(double) (OpenCL). - * + *

* User should note the differences in precision between Java and OpenCL's implementation of arithmetic functions to determine whether the difference in precision is acceptable. * * @param x value to delegate to {@link java.lang.Math#tanh(double)}/tanh(double) * @return {@link java.lang.Math#tanh(double)}/tanh(double) - * * @see java.lang.Math#tanh(double) * @see tanh(double) */ @@ -2186,30 +2127,28 @@ protected final double tanh(final double x) { /** * Delegates to either {@link java.lang.Math#tanh(float)} (Java) or tanh(float) (OpenCL). - * + *

* User should note the differences in precision between Java and OpenCL's implementation of arithmetic functions to determine whether the difference in precision is acceptable. * * @param x value to delegate to {@link java.lang.Math#tanh(float)}/tanh(float) * @return {@link java.lang.Math#tanh(float)}/tanh(float) - * * @see java.lang.Math#tanh(float) * @see tanh(float) */ @OpenCLMapping(mapTo = "tanh") protected final float tanh(final float x) { - return (float)(Math.tanh(x)); + return (float) (Math.tanh(x)); } /** * Backed by either {@link java.lang.Math#tan(double)} (Java) or tanpi(double) (OpenCL). - * + *

* This method is equivelant to Math.tan(a * Math.PI) - * + *

* User should note the differences in precision between Java and OpenCL's implementation of arithmetic functions to determine whether the difference in precision is acceptable. * * @param a value to delegate to tanpi(double) or java equivelant * @return tanpi(double) or java equivelant - * * @see java.lang.Math#tan(double) * @see tanpi(double) */ @@ -2220,1188 +2159,1213 @@ protected final double tanpi(final double a) { /** * Backed by either {@link java.lang.Math#tan(double)} (Java) or tanpi(float) (OpenCL). - * + *

* This method is equivelant to Math.tan(a * Math.PI) - * + *

* User should note the differences in precision between Java and OpenCL's implementation of arithmetic functions to determine whether the difference in precision is acceptable. * * @param a value to delegate to tanpi(float) or java equivelant * @return tanpi(float) or java equivelant - * * @see java.lang.Math#tan(double) * @see tanpi(float) */ @OpenCLMapping(mapTo = "tanpi") protected final float tanpi(final float a) { - return (float)(Math.tan(a * Math.PI)); + return (float) (Math.tan(a * Math.PI)); } - // the following rsqrt and native_sqrt and native_rsqrt don't exist in java Math - // but added them here for nbody testing, not sure if we want to expose them - /** - * Computes inverse square root using {@link java.lang.Math#sqrt(double)} (Java) or delegates to rsqrt(double) (OpenCL). - * + // the following rsqrt and native_sqrt and native_rsqrt don't exist in java Math + // but added them here for nbody testing, not sure if we want to expose them + + /** + * Computes inverse square root using {@link java.lang.Math#sqrt(double)} (Java) or delegates to rsqrt(double) (OpenCL). + *

* User should note the differences in precision between Java and OpenCL's implementation of arithmetic functions to determine whether the difference in precision is acceptable. * * @param _f value to delegate to {@link java.lang.Math#sqrt(double)}/rsqrt(double) * @return ( 1.0f / {@link java.lang.Math#sqrt(double)} casted to float )/rsqrt(double) - * * @see java.lang.Math#sqrt(double) * @see rsqrt(double) */ - @OpenCLMapping(mapTo = "rsqrt") - protected float rsqrt(float _f) { - return (1.0f / (float) Math.sqrt(_f)); - } + @OpenCLMapping(mapTo = "rsqrt") + protected float rsqrt(float _f) { + return (1.0f / (float) Math.sqrt(_f)); + } - /** - * Computes inverse square root using {@link java.lang.Math#sqrt(double)} (Java) or delegates to rsqrt(double) (OpenCL). - * + /** + * Computes inverse square root using {@link java.lang.Math#sqrt(double)} (Java) or delegates to rsqrt(double) (OpenCL). + *

* User should note the differences in precision between Java and OpenCL's implementation of arithmetic functions to determine whether the difference in precision is acceptable. * * @param _d value to delegate to {@link java.lang.Math#sqrt(double)}/rsqrt(double) * @return ( 1.0f / {@link java.lang.Math#sqrt(double)} ) /rsqrt(double) - * * @see java.lang.Math#sqrt(double) * @see rsqrt(double) */ - @OpenCLMapping(mapTo = "rsqrt") - protected double rsqrt(double _d) { - return (1.0 / Math.sqrt(_d)); - } - - @OpenCLMapping(mapTo = "native_sqrt") - private float native_sqrt(float _f) { - int j = Float.floatToIntBits(_f); - j = ((1 << 29) + (j >> 1)) - (1 << 22) - 0x4c00; - return (Float.intBitsToFloat(j)); - // could add more precision using one iteration of newton's method, use the following - } - - @OpenCLMapping(mapTo = "native_rsqrt") - private float native_rsqrt(float _f) { - int j = Float.floatToIntBits(_f); - j = 0x5f3759df - (j >> 1); - final float x = (Float.intBitsToFloat(j)); - return x; - // if want more precision via one iteration of newton's method, use the following - // float fhalf = 0.5f*_f; - // return (x *(1.5f - fhalf * x * x)); - } - - // Hacked from AtomicIntegerArray.getAndAdd(i, delta) - /** - * Atomically adds _delta value to _index element of array _arr (Java) or delegates to atomic_add(volatile int*, int) (OpenCL). - * - * - * @param _arr array for which an element value needs to be atomically incremented by _delta + @OpenCLMapping(mapTo = "rsqrt") + protected double rsqrt(double _d) { + return (1.0 / Math.sqrt(_d)); + } + + @OpenCLMapping(mapTo = "native_sqrt") + private float native_sqrt(float _f) { + int j = Float.floatToIntBits(_f); + j = ((1 << 29) + (j >> 1)) - (1 << 22) - 0x4c00; + return (Float.intBitsToFloat(j)); + // could add more precision using one iteration of newton's method, use the following + } + + @OpenCLMapping(mapTo = "native_rsqrt") + private float native_rsqrt(float _f) { + int j = Float.floatToIntBits(_f); + j = 0x5f3759df - (j >> 1); + final float x = (Float.intBitsToFloat(j)); + return x; + // if want more precision via one iteration of newton's method, use the following + // float fhalf = 0.5f*_f; + // return (x *(1.5f - fhalf * x * x)); + } + + // Hacked from AtomicIntegerArray.getAndAdd(i, delta) + + /** + * Atomically adds _delta value to _index element of array _arr (Java) or delegates to atomic_add(volatile int*, int) (OpenCL). + * + * @param _arr array for which an element value needs to be atomically incremented by _delta * @param _index index of the _arr array that needs to be atomically incremented by _delta * @param _delta value by which _index element of _arr array needs to be atomically incremented * @return previous value of _index element of _arr array - * * @see atomic_add(volatile int*, int) */ - @OpenCLMapping(atomic32 = true) - protected int atomicAdd(int[] _arr, int _index, int _delta) { - if (!Config.disableUnsafe) { - return UnsafeWrapper.atomicAdd(_arr, _index, _delta); - } else { - synchronized (_arr) { - final int previous = _arr[_index]; - _arr[_index] += _delta; - return previous; - } - } - } - - /** - * Wait for all kernels in the current group to rendezvous at this call before continuing execution. - * - * @annotion Experimental - */ - @OpenCLDelegate - @Experimental - protected final void localBarrier() { - kernelState.awaitOnLocalBarrier(); - } - - /** - * Wait for all kernels in the current group to rendezvous at this call before continuing execution. - * - * - * Java version is identical to localBarrier() - * - * @annotion Experimental - * @deprecated - */ - @OpenCLDelegate - @Experimental - @Deprecated - protected final void globalBarrier() throws DeprecatedException { - throw new DeprecatedException( + @OpenCLMapping(atomic32 = true) + protected int atomicAdd(int[] _arr, int _index, int _delta) { + if (!Config.disableUnsafe) { + return UnsafeWrapper.atomicAdd(_arr, _index, _delta); + } else { + //synchronized (_arr) { + final int previous = _arr[_index]; + _arr[_index] += _delta; + return previous; + //} + } + } + + /** + * Wait for all kernels in the current group to rendezvous at this call before continuing execution. + * + * @annotion Experimental + */ + @OpenCLDelegate + @Experimental + protected final void localBarrier() { + kernelState.awaitOnLocalBarrier(); + } + + /** + * Wait for all kernels in the current group to rendezvous at this call before continuing execution. + *

+ *

+ * Java version is identical to localBarrier() + * + * @annotion Experimental + * @deprecated + */ + @OpenCLDelegate + @Experimental + @Deprecated + protected final void globalBarrier() throws DeprecatedException { + throw new DeprecatedException( "Kernel.globalBarrier() has been deprecated. It was based an incorrect understanding of OpenCL functionality."); - } + } + + @OpenCLMapping(mapTo = "hypot") + protected float hypot(final float a, final float b) { + return (float) Math.hypot(a, b); + } - @OpenCLMapping(mapTo = "hypot") - protected float hypot(final float a, final float b) { - return (float) Math.hypot(a, b); - } + @OpenCLMapping(mapTo = "hypot") + protected double hypot(final double a, final double b) { + return Math.hypot(a, b); + } - @OpenCLMapping(mapTo = "hypot") - protected double hypot(final double a, final double b) { - return Math.hypot(a, b); - } + public KernelState getKernelState() { + return kernelState; + } - public KernelState getKernelState() { - return kernelState; - } - private KernelRunner prepareKernelRunner() { - if (kernelRunner == null) { - kernelRunner = new KernelRunner(this); - } - return kernelRunner; - } - - /** - * Determine the execution time of the previous Kernel.execute(range) call. - * - * Note that for the first call this will include the conversion time. - * - * @return The time spent executing the kernel (ms) - * - * @see #getConversionTime(); - * @see #getAccumulatedExecutionTime(); - * - */ - public double getExecutionTime() { - KernelProfile profile = KernelManager.instance().getProfile(getClass()); - synchronized (profile) { - return profile.getLastExecutionTime(); - } - } - - /** - * Determine the total execution time of all previous Kernel.execute(range) calls. - * - * Note that this will include the initial conversion time. - * - * @return The total time spent executing the kernel (ms) - * - * @see #getExecutionTime(); - * @see #getConversionTime(); - * - */ - public double getAccumulatedExecutionTime() { - KernelProfile profile = KernelManager.instance().getProfile(getClass()); - synchronized (profile) { - return profile.getAccumulatedTotalTime(); - } - } - - /** - * Determine the time taken to convert bytecode to OpenCL for first Kernel.execute(range) call. - * @return The time spent preparing the kernel for execution using GPU - * - * @see #getExecutionTime(); - * @see #getAccumulatedExecutionTime(); - */ - public double getConversionTime() { - KernelProfile profile = KernelManager.instance().getProfile(getClass()); - synchronized (profile) { - return profile.getLastConversionTime(); - } - } - - /** - * Start execution of _range kernels. - *

- * When kernel.execute(globalSize) is invoked, Aparapi will schedule the execution of globalSize kernels. If the execution mode is GPU then - * the kernels will execute as OpenCL code on the GPU device. Otherwise, if the mode is JTP, the kernels will execute as a pool of Java threads on the CPU. - *

- * @param _range The number of Kernels that we would like to initiate. - * @returnThe Kernel instance (this) so we can chain calls to put(arr).execute(range).get(arr) - * - */ - public synchronized Kernel execute(Range _range) { - return (execute(_range, 1)); - } - - @Override - @SuppressWarnings("deprecation") - public String toString() { - if (executionMode == EXECUTION_MODE.AUTO) { - List preferredDevices = KernelManager.instance().getPreferences(this).getPreferredDevices(this); - StringBuilder preferredDevicesSummary = new StringBuilder("{"); - for (int i = 0; i < preferredDevices.size(); ++i) { - Device device = preferredDevices.get(i); - preferredDevicesSummary.append(device.getShortDescription()); - if (i < preferredDevices.size() - 1) { - preferredDevicesSummary.append("|"); - } - } - preferredDevicesSummary.append("}"); - return Reflection.getSimpleName(getClass()) + ", devices=" + preferredDevicesSummary.toString(); - } else { - return Reflection.getSimpleName(getClass()) + ", modes=" + executionModes + ", current = " + executionMode; - } - } - - /** - * Start execution of _range kernels. - *

- * When kernel.execute(_range) is 1invoked, Aparapi will schedule the execution of _range kernels. If the execution mode is GPU then - * the kernels will execute as OpenCL code on the GPU device. Otherwise, if the mode is JTP, the kernels will execute as a pool of Java threads on the CPU. - *

- * Since adding the new Range class this method offers backward compatibility and merely defers to return (execute(Range.create(_range), 1));. - * @param _range The number of Kernels that we would like to initiate. - * @returnThe Kernel instance (this) so we can chain calls to put(arr).execute(range).get(arr) - * - */ - public synchronized Kernel execute(int _range) { - return (execute(createRange(_range), 1)); - } - - @SuppressWarnings("deprecation") - protected Range createRange(int _range) { - if (executionMode.equals(EXECUTION_MODE.AUTO)) { - Device device = getTargetDevice(); - Range range = Range.create(device, _range); - return range; - } else { - return Range.create(null, _range); - } - } - - /** - * Start execution of _passes iterations of _range kernels. - *

- * When kernel.execute(_range, _passes) is invoked, Aparapi will schedule the execution of _reange kernels. If the execution mode is GPU then - * the kernels will execute as OpenCL code on the GPU device. Otherwise, if the mode is JTP, the kernels will execute as a pool of Java threads on the CPU. - *

- * @param _passes The number of passes to make - * @return The Kernel instance (this) so we can chain calls to put(arr).execute(range).get(arr) - * - */ - public synchronized Kernel execute(Range _range, int _passes) { - return (execute("run", _range, _passes)); - } - - /** - * Start execution of _passes iterations over the _range of kernels. - *

- * When kernel.execute(_range) is invoked, Aparapi will schedule the execution of _range kernels. If the execution mode is GPU then - * the kernels will execute as OpenCL code on the GPU device. Otherwise, if the mode is JTP, the kernels will execute as a pool of Java threads on the CPU. - *

- * Since adding the new Range class this method offers backward compatibility and merely defers to return (execute(Range.create(_range), 1));. - * @param _range The number of Kernels that we would like to initiate. - * @returnThe Kernel instance (this) so we can chain calls to put(arr).execute(range).get(arr) - * - */ - public synchronized Kernel execute(int _range, int _passes) { - return (execute(createRange(_range), _passes)); - } - - /** - * Start execution of globalSize kernels for the given entrypoint. - *

- * When kernel.execute("entrypoint", globalSize) is invoked, Aparapi will schedule the execution of globalSize kernels. If the execution mode is GPU then - * the kernels will execute as OpenCL code on the GPU device. Otherwise, if the mode is JTP, the kernels will execute as a pool of Java threads on the CPU. - *

- * @param _entrypoint is the name of the method we wish to use as the entrypoint to the kernel - * @return The Kernel instance (this) so we can chain calls to put(arr).execute(range).get(arr) - * - */ - public synchronized Kernel execute(String _entrypoint, Range _range) { - return (execute(_entrypoint, _range, 1)); - } - - /** - * Start execution of globalSize kernels for the given entrypoint. - *

- * When kernel.execute("entrypoint", globalSize) is invoked, Aparapi will schedule the execution of globalSize kernels. If the execution mode is GPU then - * the kernels will execute as OpenCL code on the GPU device. Otherwise, if the mode is JTP, the kernels will execute as a pool of Java threads on the CPU. - *

- * @param _entrypoint is the name of the method we wish to use as the entrypoint to the kernel - * @return The Kernel instance (this) so we can chain calls to put(arr).execute(range).get(arr) - * - */ - public synchronized Kernel execute(String _entrypoint, Range _range, int _passes) { - return prepareKernelRunner().execute(_entrypoint, _range, _passes); - } - - public boolean isAutoCleanUpArrays() { - return autoCleanUpArrays; - } - - /** - * Property which if true enables automatic calling of {@link #cleanUpArrays()} following each execution. - */ - public void setAutoCleanUpArrays(boolean autoCleanUpArrays) { - this.autoCleanUpArrays = autoCleanUpArrays; - } - - /** - * Frees the bulk of the resources used by this kernel, by setting array sizes in non-primitive {@link KernelArg}s to 1 (0 size is prohibited) and invoking kernel - * execution on a zero size range. Unlike {@link #dispose()}, this does not prohibit further invocations of this kernel, as sundry resources such as OpenCL queues are - * not freed by this method. - * - *

This allows a "dormant" Kernel to remain in existence without undue strain on GPU resources, which may be strongly preferable to disposing a Kernel and - * recreating another one later, as creation/use of a new Kernel (specifically creation of its associated OpenCL context) is expensive.

- * - *

Note that where the underlying array field is declared final, for obvious reasons it is not resized to zero.

- */ - public synchronized void cleanUpArrays() { - if (kernelRunner != null) { - kernelRunner.cleanUpArrays(); - } - } - - /** - * Release any resources associated with this Kernel. - *

- * When the execution mode is CPU or GPU, Aparapi stores some OpenCL resources in a data structure associated with the kernel instance. The - * dispose() method must be called to release these resources. - *

- * If execute(int _globalSize) is called after dispose() is called the results are undefined. - */ - public synchronized void dispose() { - if (kernelRunner != null) { - kernelRunner.dispose(); - kernelRunner = null; - } - } - - public boolean isRunningCL() { - return getTargetDevice() instanceof OpenCLDevice; - } - - public final Device getTargetDevice() { - return KernelManager.instance().getPreferences(this).getPreferredDevice(this); - } - - /** @return true by default, may be overriden to allow vetoing of a device or devices by a given Kernel instance. */ - public boolean isAllowDevice(Device _device) { - return true; - } - - /** - * @deprecated See {@link EXECUTION_MODE} - *

- * Return the current execution mode. - * - * Before a Kernel executes, this return value will be the execution mode as determined by the setting of - * the EXECUTION_MODE enumeration. By default, this setting is either GPU - * if OpenCL is available on the target system, or JTP otherwise. This default setting can be - * changed by calling setExecutionMode(). - * - *

- * After a Kernel executes, the return value will be the mode in which the Kernel actually executed. - * - * @return The current execution mode. - * - * @see #setExecutionMode(EXECUTION_MODE) - */ - @Deprecated - public EXECUTION_MODE getExecutionMode() { - return (executionMode); - } - - /** - * @deprecated See {@link EXECUTION_MODE} - *

- * Set the execution mode. - *

- * This should be regarded as a request. The real mode will be determined at runtime based on the availability of OpenCL and the characteristics of the workload. - * - * @param _executionMode the requested execution mode. - * - * @see #getExecutionMode() - */ - @Deprecated - public void setExecutionMode(EXECUTION_MODE _executionMode) { - executionMode = _executionMode; - } - - public void setExecutionModeWithoutFallback(EXECUTION_MODE _executionMode) { - executionModes.clear(); - executionModes.add(_executionMode); - currentMode = executionModes.iterator(); - executionMode = currentMode.next(); } - - /** - * @deprecated See {@link EXECUTION_MODE} - */ - @Deprecated - public void setFallbackExecutionMode() { - executionMode = EXECUTION_MODE.getFallbackExecutionMode(); - } - - final static Map typeToLetterMap = new HashMap(); - - static { - // only primitive types for now - typeToLetterMap.put("double", "D"); - typeToLetterMap.put("float", "F"); - typeToLetterMap.put("int", "I"); - typeToLetterMap.put("long", "J"); - typeToLetterMap.put("boolean", "Z"); - typeToLetterMap.put("byte", "B"); - typeToLetterMap.put("char", "C"); - typeToLetterMap.put("short", "S"); - typeToLetterMap.put("void", "V"); - } - - private static String descriptorToReturnTypeLetter(String desc) { - // find the letter after the closed parenthesis - return desc.substring(desc.lastIndexOf(')') + 1); - } - - private static String getReturnTypeLetter(Method meth) { - return toClassShortNameIfAny(meth.getReturnType()); - } - - private static String toClassShortNameIfAny(final Class retClass) { - if (retClass.isArray()) { - return "[" + toClassShortNameIfAny(retClass.getComponentType()); - } - final String strRetClass = retClass.toString(); - final String mapping = typeToLetterMap.get(strRetClass); - // System.out.println("strRetClass = <" + strRetClass + ">, mapping = " + mapping); - if (mapping == null) - return "[" + retClass.getName() + ";"; - return mapping; - } - - public static String getMappedMethodName(MethodReferenceEntry _methodReferenceEntry) { - if (CacheEnabler.areCachesEnabled()) - return getProperty(mappedMethodNamesCache, _methodReferenceEntry, null); - String mappedName = null; - final String name = _methodReferenceEntry.getNameAndTypeEntry().getNameUTF8Entry().getUTF8(); - Class currentClass = _methodReferenceEntry.getOwnerClassModel().getClassWeAreModelling(); - while (currentClass != Object.class) { - for (final Method kernelMethod : currentClass.getDeclaredMethods()) { - if (kernelMethod.isAnnotationPresent(OpenCLMapping.class)) { - // ultimately, need a way to constrain this based upon signature (to disambiguate abs(float) from abs(int); - // for Alpha, we will just disambiguate based on the return type - if (false) { - System.out.println("kernelMethod is ... " + kernelMethod.toGenericString()); - System.out.println("returnType = " + kernelMethod.getReturnType()); - System.out.println("returnTypeLetter = " + getReturnTypeLetter(kernelMethod)); - System.out.println("kernelMethod getName = " + kernelMethod.getName()); - System.out.println("methRefName = " + name + " descriptor = " - + _methodReferenceEntry.getNameAndTypeEntry().getDescriptorUTF8Entry().getUTF8()); - System.out.println("descToReturnTypeLetter = " - + descriptorToReturnTypeLetter(_methodReferenceEntry.getNameAndTypeEntry().getDescriptorUTF8Entry() - .getUTF8())); - } - if (toSignature(_methodReferenceEntry).equals(toSignature(kernelMethod))) { - final OpenCLMapping annotation = kernelMethod.getAnnotation(OpenCLMapping.class); - final String mapTo = annotation.mapTo(); - if (!mapTo.equals("")) { - mappedName = mapTo; - // System.out.println("mapTo = " + mapTo); - } - } - } - } - if (mappedName != null) - break; - currentClass = currentClass.getSuperclass(); - } - // System.out.println("... in getMappedMethodName, returning = " + mappedName); - return (mappedName); - } - - public static boolean isMappedMethod(MethodReferenceEntry methodReferenceEntry) { - if (CacheEnabler.areCachesEnabled()) - return getBoolean(mappedMethodFlags, methodReferenceEntry); - boolean isMapped = false; - for (final Method kernelMethod : Kernel.class.getDeclaredMethods()) { - if (kernelMethod.isAnnotationPresent(OpenCLMapping.class)) { - if (methodReferenceEntry.getNameAndTypeEntry().getNameUTF8Entry().getUTF8().equals(kernelMethod.getName())) { - - // well they have the same name ;) - isMapped = true; - } - } - } - return (isMapped); - } - - public static boolean isOpenCLDelegateMethod(MethodReferenceEntry methodReferenceEntry) { - if (CacheEnabler.areCachesEnabled()) - return getBoolean(openCLDelegateMethodFlags, methodReferenceEntry); - boolean isMapped = false; - for (final Method kernelMethod : Kernel.class.getDeclaredMethods()) { - if (kernelMethod.isAnnotationPresent(OpenCLDelegate.class)) { - if (methodReferenceEntry.getNameAndTypeEntry().getNameUTF8Entry().getUTF8().equals(kernelMethod.getName())) { - - // well they have the same name ;) - isMapped = true; - } - } - } - return (isMapped); - } - - public static boolean usesAtomic32(MethodReferenceEntry methodReferenceEntry) { - if (CacheEnabler.areCachesEnabled()) - return getProperty(atomic32Cache, methodReferenceEntry, false); - for (final Method kernelMethod : Kernel.class.getDeclaredMethods()) { - if (kernelMethod.isAnnotationPresent(OpenCLMapping.class)) { - if (methodReferenceEntry.getNameAndTypeEntry().getNameUTF8Entry().getUTF8().equals(kernelMethod.getName())) { - final OpenCLMapping annotation = kernelMethod.getAnnotation(OpenCLMapping.class); - return annotation.atomic32(); - } - } - } - return (false); - } - - // For alpha release atomic64 is not supported - public static boolean usesAtomic64(MethodReferenceEntry methodReferenceEntry) { - // if (CacheEnabler.areCachesEnabled()) - // return getProperty(atomic64Cache, methodReferenceEntry, false); - //for (java.lang.reflect.Method kernelMethod : Kernel.class.getDeclaredMethods()) { - // if (kernelMethod.isAnnotationPresent(Kernel.OpenCLMapping.class)) { - // if (methodReferenceEntry.getNameAndTypeEntry().getNameUTF8Entry().getUTF8().equals(kernelMethod.getName())) { - // OpenCLMapping annotation = kernelMethod.getAnnotation(Kernel.OpenCLMapping.class); - // return annotation.atomic64(); - // } - // } - //} - return (false); - } - - // the flag useNullForLocalSize is useful for testing that what we compute for localSize is what OpenCL - // would also compute if we passed in null. In non-testing mode, we just call execute with the - // same localSize that we computed in getLocalSizeJNI. We don't want do publicize these of course. - // GRF we can't access this from test classes without exposing in in javadoc so I left the flag but made the test/set of the flag reflectively - boolean useNullForLocalSize = false; - - // Explicit memory management API's follow - - /** - * For dev purposes (we should remove this for production) allow us to define that this Kernel uses explicit memory management - * @param _explicit (true if we want explicit memory management) - */ - public void setExplicit(boolean _explicit) { - prepareKernelRunner().setExplicit(_explicit); - } - - /** - * For dev purposes (we should remove this for production) determine whether this Kernel uses explicit memory management - * @return (true if we kernel is using explicit memory management) - */ - public boolean isExplicit() { - return prepareKernelRunner().isExplicit(); - } - - /** - * Tag this array so that it is explicitly enqueued before the kernel is executed - * @param array - * @return This kernel so that we can use the 'fluent' style API - */ - public Kernel put(long[] array) { - prepareKernelRunner().put(array); - return (this); - } - - /** - * Tag this array so that it is explicitly enqueued before the kernel is executed - * @param array - * @return This kernel so that we can use the 'fluent' style API - */ - public Kernel put(long[][] array) { - prepareKernelRunner().put(array); - return (this); - } - - /** - * Tag this array so that it is explicitly enqueued before the kernel is executed - * @param array - * @return This kernel so that we can use the 'fluent' style API - */ - public Kernel put(long[][][] array) { - prepareKernelRunner().put(array); - return (this); - } - - /** - * Tag this array so that it is explicitly enqueued before the kernel is executed - * @param array - * @return This kernel so that we can use the 'fluent' style API - */ - public Kernel put(double[] array) { - prepareKernelRunner().put(array); - return (this); - } - - /** - * Tag this array so that it is explicitly enqueued before the kernel is executed - * @param array - * @return This kernel so that we can use the 'fluent' style API - */ - public Kernel put(double[][] array) { - prepareKernelRunner().put(array); - return (this); - } - - /** - * Tag this array so that it is explicitly enqueued before the kernel is executed - * @param array - * @return This kernel so that we can use the 'fluent' style API - */ - public Kernel put(double[][][] array) { - prepareKernelRunner().put(array); - return (this); - } - - /** - * Tag this array so that it is explicitly enqueued before the kernel is executed - * @param array - * @return This kernel so that we can use the 'fluent' style API - */ - public Kernel put(float[] array) { - prepareKernelRunner().put(array); - return (this); - } - - /** - * Tag this array so that it is explicitly enqueued before the kernel is executed - * @param array - * @return This kernel so that we can use the 'fluent' style API - */ - public Kernel put(float[][] array) { - prepareKernelRunner().put(array); - return (this); - } - - /** - * Tag this array so that it is explicitly enqueued before the kernel is executed - * @param array - * @return This kernel so that we can use the 'fluent' style API - */ - public Kernel put(float[][][] array) { - prepareKernelRunner().put(array); - return (this); - } - - /** - * Tag this array so that it is explicitly enqueued before the kernel is executed - * @param array - * @return This kernel so that we can use the 'fluent' style API - */ - public Kernel put(int[] array) { - prepareKernelRunner().put(array); - return (this); - } - - /** - * Tag this array so that it is explicitly enqueued before the kernel is executed - * @param array - * @return This kernel so that we can use the 'fluent' style API - */ - public Kernel put(int[][] array) { - prepareKernelRunner().put(array); - return (this); - } - - /** - * Tag this array so that it is explicitly enqueued before the kernel is executed - * @param array - * @return This kernel so that we can use the 'fluent' style API - */ - public Kernel put(int[][][] array) { - prepareKernelRunner().put(array); - return (this); - } - - /** - * Tag this array so that it is explicitly enqueued before the kernel is executed - * @param array - * @return This kernel so that we can use the 'fluent' style API - */ - public Kernel put(byte[] array) { - prepareKernelRunner().put(array); - return (this); - } - - /** - * Tag this array so that it is explicitly enqueued before the kernel is executed - * @param array - * @return This kernel so that we can use the 'fluent' style API - */ - public Kernel put(byte[][] array) { - prepareKernelRunner().put(array); - return (this); - } - - /** - * Tag this array so that it is explicitly enqueued before the kernel is executed - * @param array - * @return This kernel so that we can use the 'fluent' style API - */ - public Kernel put(byte[][][] array) { - prepareKernelRunner().put(array); - return (this); - } - - /** - * Tag this array so that it is explicitly enqueued before the kernel is executed - * @param array - * @return This kernel so that we can use the 'fluent' style API + + //TODO use WeakConcurrent HashMap + private final Map runners = Collections.synchronizedMap( + new WeakHashMap(Runtime.getRuntime().availableProcessors() * 2, 0.95f) + ); + + + private KernelRunner runner() { + return runners.computeIfAbsent(Thread.currentThread(), (tt)-> new KernelRunner(this)); + } + + /** + * Determine the execution time of the previous Kernel.execute(range) call. + *

+ * Note that for the first call this will include the conversion time. + * + * @return The time spent executing the kernel (ms) + * @see #getConversionTime(); + * @see #getAccumulatedExecutionTime(); */ - public Kernel put(char[] array) { - prepareKernelRunner().put(array); - return (this); - } - - /** - * Tag this array so that it is explicitly enqueued before the kernel is executed - * @param array - * @return This kernel so that we can use the 'fluent' style API - */ - public Kernel put(char[][] array) { - prepareKernelRunner().put(array); - return (this); - } - - /** - * Tag this array so that it is explicitly enqueued before the kernel is executed - * @param array - * @return This kernel so that we can use the 'fluent' style API - */ - public Kernel put(char[][][] array) { - prepareKernelRunner().put(array); - return (this); - } - - /** - * Tag this array so that it is explicitly enqueued before the kernel is executed - * @param array - * @return This kernel so that we can use the 'fluent' style API - */ - public Kernel put(boolean[] array) { - prepareKernelRunner().put(array); - return (this); - } - - /** - * Tag this array so that it is explicitly enqueued before the kernel is executed - * @param array - * @return This kernel so that we can use the 'fluent' style API - */ - public Kernel put(boolean[][] array) { - prepareKernelRunner().put(array); - return (this); - } - - /** - * Tag this array so that it is explicitly enqueued before the kernel is executed - * @param array - * @return This kernel so that we can use the 'fluent' style API - */ - public Kernel put(boolean[][][] array) { - prepareKernelRunner().put(array); - return (this); - } - - /** - * Enqueue a request to return this buffer from the GPU. This method blocks until the array is available. - * @param array - * @return This kernel so that we can use the 'fluent' style API - */ - public Kernel get(long[] array) { - prepareKernelRunner().get(array); - return (this); - } - - /** - * Enqueue a request to return this buffer from the GPU. This method blocks until the array is available. - * @param array - * @return This kernel so that we can use the 'fluent' style API - */ - public Kernel get(long[][] array) { - prepareKernelRunner().get(array); - return (this); - } - - /** - * Enqueue a request to return this buffer from the GPU. This method blocks until the array is available. - * @param array - * @return This kernel so that we can use the 'fluent' style API - */ - public Kernel get(long[][][] array) { - prepareKernelRunner().get(array); - return (this); - } - - /** - * Enqueue a request to return this buffer from the GPU. This method blocks until the array is available. - * @param array - * @return This kernel so that we can use the 'fluent' style API - */ - public Kernel get(double[] array) { - prepareKernelRunner().get(array); - return (this); - } - - /** - * Enqueue a request to return this buffer from the GPU. This method blocks until the array is available. - * @param array - * @return This kernel so that we can use the 'fluent' style API - */ - public Kernel get(double[][] array) { - prepareKernelRunner().get(array); - return (this); - } - - /** - * Enqueue a request to return this buffer from the GPU. This method blocks until the array is available. - * @param array - * @return This kernel so that we can use the 'fluent' style API - */ - public Kernel get(double[][][] array) { - prepareKernelRunner().get(array); - return (this); - } - - /** - * Enqueue a request to return this buffer from the GPU. This method blocks until the array is available. - * @param array - * @return This kernel so that we can use the 'fluent' style API - */ - public Kernel get(float[] array) { - prepareKernelRunner().get(array); - return (this); - } - - /** - * Enqueue a request to return this buffer from the GPU. This method blocks until the array is available. - * @param array - * @return This kernel so that we can use the 'fluent' style API - */ - public Kernel get(float[][] array) { - prepareKernelRunner().get(array); - return (this); - } - - /** - * Enqueue a request to return this buffer from the GPU. This method blocks until the array is available. - * @param array - * @return This kernel so that we can use the 'fluent' style API - */ - public Kernel get(float[][][] array) { - prepareKernelRunner().get(array); - return (this); - } - - /** - * Enqueue a request to return this buffer from the GPU. This method blocks until the array is available. - * @param array - * @return This kernel so that we can use the 'fluent' style API - */ - public Kernel get(int[] array) { - prepareKernelRunner().get(array); - return (this); - } - - /** - * Enqueue a request to return this buffer from the GPU. This method blocks until the array is available. - * @param array - * @return This kernel so that we can use the 'fluent' style API - */ - public Kernel get(int[][] array) { - prepareKernelRunner().get(array); - return (this); - } - - /** - * Enqueue a request to return this buffer from the GPU. This method blocks until the array is available. - * @param array - * @return This kernel so that we can use the 'fluent' style API - */ - public Kernel get(int[][][] array) { - prepareKernelRunner().get(array); - return (this); - } - - /** - * Enqueue a request to return this buffer from the GPU. This method blocks until the array is available. - * @param array - * @return This kernel so that we can use the 'fluent' style API - */ - public Kernel get(byte[] array) { - prepareKernelRunner().get(array); - return (this); - } - - /** - * Enqueue a request to return this buffer from the GPU. This method blocks until the array is available. - * @param array - * @return This kernel so that we can use the 'fluent' style API - */ - public Kernel get(byte[][] array) { - prepareKernelRunner().get(array); - return (this); - } - - /** - * Enqueue a request to return this buffer from the GPU. This method blocks until the array is available. - * @param array - * @return This kernel so that we can use the 'fluent' style API - */ - public Kernel get(byte[][][] array) { - prepareKernelRunner().get(array); - return (this); - } - - /** - * Enqueue a request to return this buffer from the GPU. This method blocks until the array is available. - * @param array - * @return This kernel so that we can use the 'fluent' style API - */ - public Kernel get(char[] array) { - prepareKernelRunner().get(array); - return (this); - } - - /** - * Enqueue a request to return this buffer from the GPU. This method blocks until the array is available. - * @param array - * @return This kernel so that we can use the 'fluent' style API - */ - public Kernel get(char[][] array) { - prepareKernelRunner().get(array); - return (this); - } - - /** - * Enqueue a request to return this buffer from the GPU. This method blocks until the array is available. - * @param array - * @return This kernel so that we can use the 'fluent' style API - */ - public Kernel get(char[][][] array) { - prepareKernelRunner().get(array); - return (this); - } - - /** - * Enqueue a request to return this buffer from the GPU. This method blocks until the array is available. - * @param array - * @return This kernel so that we can use the 'fluent' style API - */ - public Kernel get(boolean[] array) { - prepareKernelRunner().get(array); - return (this); - } - - /** - * Enqueue a request to return this buffer from the GPU. This method blocks until the array is available. - * @param array - * @return This kernel so that we can use the 'fluent' style API - */ - public Kernel get(boolean[][] array) { - prepareKernelRunner().get(array); - return (this); - } - - /** - * Enqueue a request to return this buffer from the GPU. This method blocks until the array is available. - * @param array - * @return This kernel so that we can use the 'fluent' style API - */ - public Kernel get(boolean[][][] array) { - prepareKernelRunner().get(array); - return (this); - } - - /** - * Get the profiling information from the last successful call to Kernel.execute(). - * @return A list of ProfileInfo records - */ - public List getProfileInfo() { - return prepareKernelRunner().getProfileInfo(); - } - - /** - * @deprecated See {@link EXECUTION_MODE}. - */ - @Deprecated - private final LinkedHashSet executionModes = (Config.executionMode != null) ? EXECUTION_MODE.getDefaultExecutionModes() : new LinkedHashSet<>(Collections.singleton(EXECUTION_MODE.AUTO)); - - /** - * @deprecated See {@link EXECUTION_MODE}. - */ - @Deprecated - private Iterator currentMode = executionModes.iterator(); - - /** - * @deprecated See {@link EXECUTION_MODE}. - */ - @Deprecated - private EXECUTION_MODE executionMode = currentMode.next(); - - /** - * @deprecated See {@link EXECUTION_MODE}. - *

- * set possible fallback path for execution modes. - * for example setExecutionFallbackPath(GPU,CPU,JTP) will try to use the GPU - * if it fails it will fall back to OpenCL CPU and finally it will try JTP. - */ - @Deprecated - public void addExecutionModes(EXECUTION_MODE... platforms) { - executionModes.addAll(Arrays.asList(platforms)); - currentMode = executionModes.iterator(); - executionMode = currentMode.next(); - } - - /** - * @deprecated See {@link EXECUTION_MODE}. - * @return is there another execution path we can try - */ - @Deprecated - public boolean hasNextExecutionMode() { - return currentMode.hasNext(); - } - - /** - * @deprecated See {@link EXECUTION_MODE}. - * try the next execution path in the list if there aren't any more than give up - */ - @Deprecated - public void tryNextExecutionMode() { - if (currentMode.hasNext()) { - executionMode = currentMode.next(); - } - } + public double getExecutionTime() { + KernelProfile profile = KernelManager.instance().getProfile(getClass()); - private static final ValueCache, Map, RuntimeException> mappedMethodFlags = markedWith(OpenCLMapping.class); + return profile.getTotalExecutionTime(); - private static final ValueCache, Map, RuntimeException> openCLDelegateMethodFlags = markedWith(OpenCLDelegate.class); + } - private static final ValueCache, Map, RuntimeException> atomic32Cache = cacheProperty(new ValueComputer, Map>() { - @Override - public Map compute(Class key) { - Map properties = new HashMap<>(); - for (final Method method : key.getDeclaredMethods()) { - if (isRelevant(method) && method.isAnnotationPresent(OpenCLMapping.class)) { - properties.put(toSignature(method), method.getAnnotation(OpenCLMapping.class).atomic32()); - } - } - return properties; - } - }); + /** + * Determine the total execution time of all previous Kernel.execute(range) calls. + *

+ * Note that this will include the initial conversion time. + * + * @return The total time spent executing the kernel (ms) + * @see #getExecutionTime(); + * @see #getConversionTime(); + */ + public double getAccumulatedExecutionTime() { + KernelProfile profile = KernelManager.instance().getProfile(getClass()); - private static final ValueCache, Map, RuntimeException> atomic64Cache = cacheProperty(new ValueComputer, Map>() { - @Override - public Map compute(Class key) { - Map properties = new HashMap<>(); - for (final Method method : key.getDeclaredMethods()) { - if (isRelevant(method) && method.isAnnotationPresent(OpenCLMapping.class)) { - properties.put(toSignature(method), method.getAnnotation(OpenCLMapping.class).atomic64()); - } - } - return properties; - } - }); - - private static boolean getBoolean(ValueCache, Map, RuntimeException> methodNamesCache, - MethodReferenceEntry methodReferenceEntry) { - return getProperty(methodNamesCache, methodReferenceEntry, false); - } - - private static ValueCache, Map, RuntimeException> markedWith( - final Class annotationClass) { - return cacheProperty(new ValueComputer, Map>() { - @Override - public Map compute(Class key) { - Map markedMethodNames = new HashMap<>(); - for (final Method method : key.getDeclaredMethods()) { - markedMethodNames.put(toSignature(method), method.isAnnotationPresent(annotationClass)); - } - return markedMethodNames; - } - }); - } - - static String toSignature(Method method) { - return method.getName() + getArgumentsLetters(method) + getReturnTypeLetter(method); - } - - private static String getArgumentsLetters(Method method) { - StringBuilder sb = new StringBuilder("("); - for (Class parameterClass : method.getParameterTypes()) { - sb.append(toClassShortNameIfAny(parameterClass)); - } - sb.append(")"); - return sb.toString(); - } - - private static boolean isRelevant(Method method) { - return !method.isSynthetic() && !method.isBridge(); - } - - private static V getProperty(ValueCache, Map, T> cache, - MethodReferenceEntry methodReferenceEntry, V defaultValue) throws T { - Map map = cache.computeIfAbsent(methodReferenceEntry.getOwnerClassModel().getClassWeAreModelling()); - String key = toSignature(methodReferenceEntry); - if (map.containsKey(key)) - return map.get(key); - return defaultValue; - } - - private static String toSignature(MethodReferenceEntry methodReferenceEntry) { - NameAndTypeEntry nameAndTypeEntry = methodReferenceEntry.getNameAndTypeEntry(); - return nameAndTypeEntry.getNameUTF8Entry().getUTF8() + nameAndTypeEntry.getDescriptorUTF8Entry().getUTF8(); - } - - private static final ValueCache, Map, RuntimeException> mappedMethodNamesCache = cacheProperty(new ValueComputer, Map>() { - @Override - public Map compute(Class key) { - Map properties = new HashMap<>(); - for (final Method method : key.getDeclaredMethods()) { - if (isRelevant(method) && method.isAnnotationPresent(OpenCLMapping.class)) { - // ultimately, need a way to constrain this based upon signature (to disambiguate abs(float) from abs(int); - final OpenCLMapping annotation = method.getAnnotation(OpenCLMapping.class); - final String mapTo = annotation.mapTo(); - if (mapTo != null && !mapTo.equals("")) { - properties.put(toSignature(method), mapTo); - } - } - } - return properties; - } - }); + return profile.getTotalTime(); - private static ValueCache, Map, T> cacheProperty( - final ThrowingValueComputer, Map, T> throwingValueComputer) { - return ValueCache.on(new ThrowingValueComputer, Map, T>() { - @Override - public Map compute(Class key) throws T { - Map properties = new HashMap<>(); - Deque> superclasses = new ArrayDeque<>(); - Class currentSuperClass = key; - do { - superclasses.push(currentSuperClass); - currentSuperClass = currentSuperClass.getSuperclass(); - } while (currentSuperClass != Object.class); - for (Class clazz : superclasses) { - // Overwrite property values for shadowed/overriden methods - properties.putAll(throwingValueComputer.compute(clazz)); + } + + /** + * Determine the time taken to convert bytecode to OpenCL for first Kernel.execute(range) call. + * + * @return The time spent preparing the kernel for execution using GPU + * @see #getExecutionTime(); + * @see #getAccumulatedExecutionTime(); + */ + public double getTotalConversionTime() { + KernelProfile profile = KernelManager.instance().getProfile(getClass()); + + return profile.getTotalConversionTime(); + + } + + /** + * Start execution of _range kernels. + *

+ * When kernel.execute(globalSize) is invoked, Aparapi will schedule the execution of globalSize kernels. If the execution mode is GPU then + * the kernels will execute as OpenCL code on the GPU device. Otherwise, if the mode is JTP, the kernels will execute as a pool of Java threads on the CPU. + *

+ * + * @param _range The number of Kernels that we would like to initiate. + * @returnThe Kernel instance (this) so we can chain calls to put(arr).execute(range).get(arr) + */ + public Kernel execute(Range _range) { + return execute(_range, 1); + } + + @Override + @SuppressWarnings("deprecation") + public String toString() { + if (executionMode == EXECUTION_MODE.AUTO) { + List preferredDevices = KernelManager.instance().getPreferences(this).getPreferredDevices(this); + StringBuilder preferredDevicesSummary = new StringBuilder("{"); + for (int i = 0; i < preferredDevices.size(); ++i) { + Device device = preferredDevices.get(i); + preferredDevicesSummary.append(device.getShortDescription()); + if (i < preferredDevices.size() - 1) { + preferredDevicesSummary.append('|'); + } } - return properties; - } - }); - } - - public static void invalidateCaches() { - atomic32Cache.invalidate(); - atomic64Cache.invalidate(); - mappedMethodFlags.invalidate(); - mappedMethodNamesCache.invalidate(); - openCLDelegateMethodFlags.invalidate(); - } + preferredDevicesSummary.append('}'); + return Reflection.getSimpleName(getClass()) + ", devices=" + preferredDevicesSummary; + } else { + return Reflection.getSimpleName(getClass()) + ", modes=" + executionModes + ", current = " + executionMode; + } + } + + /** + * Start execution of _range kernels. + *

+ * When kernel.execute(_range) is 1invoked, Aparapi will schedule the execution of _range kernels. If the execution mode is GPU then + * the kernels will execute as OpenCL code on the GPU device. Otherwise, if the mode is JTP, the kernels will execute as a pool of Java threads on the CPU. + *

+ * Since adding the new Range class this method offers backward compatibility and merely defers to return (execute(Range.create(_range), 1));. + * + * @param _range The number of Kernels that we would like to initiate. + * @returnThe Kernel instance (this) so we can chain calls to put(arr).execute(range).get(arr) + */ + public Kernel execute(int _range) { + return execute(createRange(_range), 1); + } + + @SuppressWarnings("deprecation") + private Range createRange(int _range) { + if (executionMode.equals(EXECUTION_MODE.AUTO)) { + Device device = getTargetDevice(); + Range range = Range.create(device, _range); + return range; + } else { + return Range.create(null, _range); + } + } + + /** + * Start execution of _passes iterations of _range kernels. + *

+ * When kernel.execute(_range, _passes) is invoked, Aparapi will schedule the execution of _reange kernels. If the execution mode is GPU then + * the kernels will execute as OpenCL code on the GPU device. Otherwise, if the mode is JTP, the kernels will execute as a pool of Java threads on the CPU. + *

+ * + * @param _passes The number of passes to make + * @return The Kernel instance (this) so we can chain calls to put(arr).execute(range).get(arr) + */ + public Kernel execute(Range _range, int _passes) { + return execute("run", _range, _passes); + } + + /** + * Start execution of _passes iterations over the _range of kernels. + *

+ * When kernel.execute(_range) is invoked, Aparapi will schedule the execution of _range kernels. If the execution mode is GPU then + * the kernels will execute as OpenCL code on the GPU device. Otherwise, if the mode is JTP, the kernels will execute as a pool of Java threads on the CPU. + *

+ * Since adding the new Range class this method offers backward compatibility and merely defers to return (execute(Range.create(_range), 1));. + * + * @param _range The number of Kernels that we would like to initiate. + * @returnThe Kernel instance (this) so we can chain calls to put(arr).execute(range).get(arr) + */ + public Kernel execute(int _range, int _passes) { + return execute(createRange(_range), _passes); + } + + /** + * Start execution of globalSize kernels for the given entrypoint. + *

+ * When kernel.execute("entrypoint", globalSize) is invoked, Aparapi will schedule the execution of globalSize kernels. If the execution mode is GPU then + * the kernels will execute as OpenCL code on the GPU device. Otherwise, if the mode is JTP, the kernels will execute as a pool of Java threads on the CPU. + *

+ * + * @param _entrypoint is the name of the method we wish to use as the entrypoint to the kernel + * @return The Kernel instance (this) so we can chain calls to put(arr).execute(range).get(arr) + */ + public Kernel execute(String _entrypoint, Range _range) { + return execute(_entrypoint, _range, 1); + } + + /** + * Start execution of globalSize kernels for the given entrypoint. + *

+ * When kernel.execute("entrypoint", globalSize) is invoked, Aparapi will schedule the execution of globalSize kernels. If the execution mode is GPU then + * the kernels will execute as OpenCL code on the GPU device. Otherwise, if the mode is JTP, the kernels will execute as a pool of Java threads on the CPU. + *

+ * + * @param _entrypoint is the name of the method we wish to use as the entrypoint to the kernel + * @return The Kernel instance (this) so we can chain calls to put(arr).execute(range).get(arr) + */ + private Kernel execute(String _entrypoint, Range _range, int _passes) { + return runner().execute(_entrypoint, _range, _passes); + } + + public boolean isAutoCleanUpArrays() { + return autoCleanUpArrays; + } + + /** + * Property which if true enables automatic calling of {@link #cleanUpArrays()} following each execution. + */ + public void setAutoCleanUpArrays(boolean autoCleanUpArrays) { + this.autoCleanUpArrays = autoCleanUpArrays; + } + + /** + * Frees the bulk of the resources used by this kernel, by setting array sizes in non-primitive {@link KernelArg}s to 1 (0 size is prohibited) and invoking kernel + * execution on a zero size range. Unlike {@link #dispose()}, this does not prohibit further invocations of this kernel, as sundry resources such as OpenCL queues are + * not freed by this method. + *

+ *

This allows a "dormant" Kernel to remain in existence without undue strain on GPU resources, which may be strongly preferable to disposing a Kernel and + * recreating another one later, as creation/use of a new Kernel (specifically creation of its associated OpenCL context) is expensive.

+ *

+ *

Note that where the underlying array field is declared final, for obvious reasons it is not resized to zero.

+ */ + public void cleanUpArrays() { + runners.values().forEach(KernelRunner::cleanUpArrays); + } + + /** + * Release any resources associated with this Kernel. + *

+ * When the execution mode is CPU or GPU, Aparapi stores some OpenCL resources in a data structure associated with the kernel instance. The + * dispose() method must be called to release these resources. + *

+ * If execute(int _globalSize) is called after dispose() is called the results are undefined. + */ + public void dispose() { + runners.entrySet().removeIf(e -> { + e.getValue().dispose(); + return true; + }); + } + + public boolean isRunningCL() { + return getTargetDevice() instanceof OpenCLDevice; + } + + public final Device getTargetDevice() { + return KernelManager.instance().getPreferences(this).getPreferredDevice(this); + } + + /** + * @return true by default, may be overriden to allow vetoing of a device or devices by a given Kernel instance. + */ + public boolean isAllowDevice(Device _device) { + return true; + } + + /** + * @return The current execution mode. + * @see #setExecutionMode(EXECUTION_MODE) + * @deprecated See {@link EXECUTION_MODE} + *

+ * Return the current execution mode. + *

+ * Before a Kernel executes, this return value will be the execution mode as determined by the setting of + * the EXECUTION_MODE enumeration. By default, this setting is either GPU + * if OpenCL is available on the target system, or JTP otherwise. This default setting can be + * changed by calling setExecutionMode(). + *

+ *

+ * After a Kernel executes, the return value will be the mode in which the Kernel actually executed. + */ + @Deprecated + public EXECUTION_MODE getExecutionMode() { + return (executionMode); + } + + /** + * @param _executionMode the requested execution mode. + * @see #getExecutionMode() + * @deprecated See {@link EXECUTION_MODE} + *

+ * Set the execution mode. + *

+ * This should be regarded as a request. The real mode will be determined at runtime based on the availability of OpenCL and the characteristics of the workload. + */ + @Deprecated + public void setExecutionMode(EXECUTION_MODE _executionMode) { + executionMode = _executionMode; + } + + public void setExecutionModeWithoutFallback(EXECUTION_MODE _executionMode) { + executionModes.clear(); + executionModes.add(_executionMode); + currentMode = executionModes.iterator(); + executionMode = currentMode.next(); + } + + /** + * @deprecated See {@link EXECUTION_MODE} + */ + @Deprecated + public void setFallbackExecutionMode() { + executionMode = EXECUTION_MODE.getFallbackExecutionMode(); + } + + private final static Map typeToLetterMap = new HashMap<>(); + + static { + // only primitive types for now + typeToLetterMap.put("double", "D"); + typeToLetterMap.put("float", "F"); + typeToLetterMap.put("int", "I"); + typeToLetterMap.put("long", "J"); + typeToLetterMap.put("boolean", "Z"); + typeToLetterMap.put("byte", "B"); + typeToLetterMap.put("char", "C"); + typeToLetterMap.put("short", "S"); + typeToLetterMap.put("void", "V"); + } + + private static String descriptorToReturnTypeLetter(String desc) { + // find the letter after the closed parenthesis + return desc.substring(desc.lastIndexOf(')') + 1); + } + + private static String getReturnTypeLetter(Method meth) { + return toClassShortNameIfAny(meth.getReturnType()); + } + + private static String toClassShortNameIfAny(final Class retClass) { + if (retClass.isArray()) { + return '[' + toClassShortNameIfAny(retClass.getComponentType()); + } + final String strRetClass = retClass.toString(); + final String mapping = typeToLetterMap.get(strRetClass); + // System.out.println("strRetClass = <" + strRetClass + ">, mapping = " + mapping); + if (mapping == null) + return '[' + retClass.getName() + ';'; + return mapping; + } + + public static String getMappedMethodName(MethodReferenceEntry _methodReferenceEntry) { + if (CacheEnabler.areCachesEnabled()) + return getProperty(mappedMethodNamesCache, _methodReferenceEntry, null); + String mappedName = null; + final String name = _methodReferenceEntry.getNameAndTypeEntry().getNameUTF8Entry().getUTF8(); + Class currentClass = _methodReferenceEntry.getOwnerClassModel().clazz; + while (currentClass != Object.class) { + for (final Method kernelMethod : currentClass.getDeclaredMethods()) { + if (kernelMethod.isAnnotationPresent(OpenCLMapping.class)) { + // ultimately, need a way to constrain this based upon signature (to disambiguate abs(float) from abs(int); + // for Alpha, we will just disambiguate based on the return type + if (false) { + System.out.println("kernelMethod is ... " + kernelMethod.toGenericString()); + System.out.println("returnType = " + kernelMethod.getReturnType()); + System.out.println("returnTypeLetter = " + getReturnTypeLetter(kernelMethod)); + System.out.println("kernelMethod getName = " + kernelMethod.getName()); + System.out.println("methRefName = " + name + " descriptor = " + + _methodReferenceEntry.getNameAndTypeEntry().getDescriptorUTF8Entry().getUTF8()); + System.out.println("descToReturnTypeLetter = " + + descriptorToReturnTypeLetter(_methodReferenceEntry.getNameAndTypeEntry().getDescriptorUTF8Entry() + .getUTF8())); + } + if (toSignature(_methodReferenceEntry).equals(toSignature(kernelMethod))) { + final OpenCLMapping annotation = kernelMethod.getAnnotation(OpenCLMapping.class); + final String mapTo = annotation.mapTo(); + if (!mapTo.isEmpty()) { + mappedName = mapTo; + // System.out.println("mapTo = " + mapTo); + } + } + } + } + if (mappedName != null) + break; + currentClass = currentClass.getSuperclass(); + } + // System.out.println("... in getMappedMethodName, returning = " + mappedName); + return (mappedName); + } + + public static boolean isMappedMethod(MethodReferenceEntry methodReferenceEntry) { + if (CacheEnabler.areCachesEnabled()) + return getBoolean(mappedMethodFlags, methodReferenceEntry); + boolean isMapped = false; + for (final Method kernelMethod : Kernel.class.getDeclaredMethods()) { + if (kernelMethod.isAnnotationPresent(OpenCLMapping.class)) { + if (methodReferenceEntry.getNameAndTypeEntry().getNameUTF8Entry().getUTF8().equals(kernelMethod.getName())) { + + // well they have the same name ;) + isMapped = true; + } + } + } + return (isMapped); + } + + public static boolean isOpenCLDelegateMethod(MethodReferenceEntry methodReferenceEntry) { + if (CacheEnabler.areCachesEnabled()) + return getBoolean(openCLDelegateMethodFlags, methodReferenceEntry); + boolean isMapped = false; + for (final Method kernelMethod : Kernel.class.getDeclaredMethods()) { + if (kernelMethod.isAnnotationPresent(OpenCLDelegate.class)) { + if (methodReferenceEntry.getNameAndTypeEntry().getNameUTF8Entry().getUTF8().equals(kernelMethod.getName())) { + + // well they have the same name ;) + isMapped = true; + } + } + } + return (isMapped); + } + + public static boolean usesAtomic32(MethodReferenceEntry methodReferenceEntry) { + if (CacheEnabler.areCachesEnabled()) + return getProperty(atomic32Cache, methodReferenceEntry, false); + for (final Method kernelMethod : Kernel.class.getDeclaredMethods()) { + if (kernelMethod.isAnnotationPresent(OpenCLMapping.class)) { + if (methodReferenceEntry.getNameAndTypeEntry().getNameUTF8Entry().getUTF8().equals(kernelMethod.getName())) { + final OpenCLMapping annotation = kernelMethod.getAnnotation(OpenCLMapping.class); + return annotation.atomic32(); + } + } + } + return (false); + } + + // For alpha release atomic64 is not supported + public static boolean usesAtomic64(MethodReferenceEntry methodReferenceEntry) { + // if (CacheEnabler.areCachesEnabled()) + // return getProperty(atomic64Cache, methodReferenceEntry, false); + //for (java.lang.reflect.Method kernelMethod : Kernel.class.getDeclaredMethods()) { + // if (kernelMethod.isAnnotationPresent(Kernel.OpenCLMapping.class)) { + // if (methodReferenceEntry.getNameAndTypeEntry().getNameUTF8Entry().getUTF8().equals(kernelMethod.getName())) { + // OpenCLMapping annotation = kernelMethod.getAnnotation(Kernel.OpenCLMapping.class); + // return annotation.atomic64(); + // } + // } + //} + return (false); + } + + // the flag useNullForLocalSize is useful for testing that what we compute for localSize is what OpenCL + // would also compute if we passed in null. In non-testing mode, we just call execute with the + // same localSize that we computed in getLocalSizeJNI. We don't want do publicize these of course. + // GRF we can't access this from test classes without exposing in in javadoc so I left the flag but made the test/set of the flag reflectively + boolean useNullForLocalSize = false; + + // Explicit memory management API's follow + + /** + * For dev purposes (we should remove this for production) allow us to define that this Kernel uses explicit memory management + * + * @param _explicit (true if we want explicit memory management) + */ + public void setExplicit(boolean _explicit) { + runner().setExplicit(_explicit); + } + + /** + * For dev purposes (we should remove this for production) determine whether this Kernel uses explicit memory management + * + * @return (true if we kernel is using explicit memory management) + */ + public boolean isExplicit() { + return runner().isExplicit(); + } + + /** + * Tag this array so that it is explicitly enqueued before the kernel is executed + * + * @param array + * @return This kernel so that we can use the 'fluent' style API + */ + public Kernel put(long[] array) { + runner().put(array); + return (this); + } + + /** + * Tag this array so that it is explicitly enqueued before the kernel is executed + * + * @param array + * @return This kernel so that we can use the 'fluent' style API + */ + public Kernel put(long[][] array) { + runner().put(array); + return (this); + } + + /** + * Tag this array so that it is explicitly enqueued before the kernel is executed + * + * @param array + * @return This kernel so that we can use the 'fluent' style API + */ + public Kernel put(long[][][] array) { + runner().put(array); + return (this); + } + + /** + * Tag this array so that it is explicitly enqueued before the kernel is executed + * + * @param array + * @return This kernel so that we can use the 'fluent' style API + */ + public Kernel put(double[] array) { + runner().put(array); + return (this); + } + + /** + * Tag this array so that it is explicitly enqueued before the kernel is executed + * + * @param array + * @return This kernel so that we can use the 'fluent' style API + */ + public Kernel put(double[][] array) { + runner().put(array); + return (this); + } + + /** + * Tag this array so that it is explicitly enqueued before the kernel is executed + * + * @param array + * @return This kernel so that we can use the 'fluent' style API + */ + public Kernel put(double[][][] array) { + runner().put(array); + return (this); + } + + /** + * Tag this array so that it is explicitly enqueued before the kernel is executed + * + * @param array + * @return This kernel so that we can use the 'fluent' style API + */ + public Kernel put(float[] array) { + runner().put(array); + return (this); + } + + /** + * Tag this array so that it is explicitly enqueued before the kernel is executed + * + * @param array + * @return This kernel so that we can use the 'fluent' style API + */ + public Kernel put(float[][] array) { + runner().put(array); + return (this); + } + + /** + * Tag this array so that it is explicitly enqueued before the kernel is executed + * + * @param array + * @return This kernel so that we can use the 'fluent' style API + */ + public Kernel put(float[][][] array) { + runner().put(array); + return (this); + } + + /** + * Tag this array so that it is explicitly enqueued before the kernel is executed + * + * @param array + * @return This kernel so that we can use the 'fluent' style API + */ + public Kernel put(int[] array) { + runner().put(array); + return (this); + } + + /** + * Tag this array so that it is explicitly enqueued before the kernel is executed + * + * @param array + * @return This kernel so that we can use the 'fluent' style API + */ + public Kernel put(int[][] array) { + runner().put(array); + return (this); + } + + /** + * Tag this array so that it is explicitly enqueued before the kernel is executed + * + * @param array + * @return This kernel so that we can use the 'fluent' style API + */ + public Kernel put(int[][][] array) { + runner().put(array); + return (this); + } + + /** + * Tag this array so that it is explicitly enqueued before the kernel is executed + * + * @param array + * @return This kernel so that we can use the 'fluent' style API + */ + public Kernel put(byte[] array) { + runner().put(array); + return (this); + } + + /** + * Tag this array so that it is explicitly enqueued before the kernel is executed + * + * @param array + * @return This kernel so that we can use the 'fluent' style API + */ + public Kernel put(byte[][] array) { + runner().put(array); + return (this); + } + + /** + * Tag this array so that it is explicitly enqueued before the kernel is executed + * + * @param array + * @return This kernel so that we can use the 'fluent' style API + */ + public Kernel put(byte[][][] array) { + runner().put(array); + return (this); + } + + /** + * Tag this array so that it is explicitly enqueued before the kernel is executed + * + * @param array + * @return This kernel so that we can use the 'fluent' style API + */ + public Kernel put(char[] array) { + runner().put(array); + return (this); + } + + /** + * Tag this array so that it is explicitly enqueued before the kernel is executed + * + * @param array + * @return This kernel so that we can use the 'fluent' style API + */ + public Kernel put(char[][] array) { + runner().put(array); + return (this); + } + + /** + * Tag this array so that it is explicitly enqueued before the kernel is executed + * + * @param array + * @return This kernel so that we can use the 'fluent' style API + */ + public Kernel put(char[][][] array) { + runner().put(array); + return (this); + } + + /** + * Tag this array so that it is explicitly enqueued before the kernel is executed + * + * @param array + * @return This kernel so that we can use the 'fluent' style API + */ + public Kernel put(boolean[] array) { + runner().put(array); + return (this); + } + + /** + * Tag this array so that it is explicitly enqueued before the kernel is executed + * + * @param array + * @return This kernel so that we can use the 'fluent' style API + */ + public Kernel put(boolean[][] array) { + runner().put(array); + return (this); + } + + /** + * Tag this array so that it is explicitly enqueued before the kernel is executed + * + * @param array + * @return This kernel so that we can use the 'fluent' style API + */ + public Kernel put(boolean[][][] array) { + runner().put(array); + return (this); + } + + /** + * Enqueue a request to return this buffer from the GPU. This method blocks until the array is available. + * + * @param array + * @return This kernel so that we can use the 'fluent' style API + */ + public Kernel get(long[] array) { + runner().get(array); + return (this); + } + + /** + * Enqueue a request to return this buffer from the GPU. This method blocks until the array is available. + * + * @param array + * @return This kernel so that we can use the 'fluent' style API + */ + public Kernel get(long[][] array) { + runner().get(array); + return (this); + } + + /** + * Enqueue a request to return this buffer from the GPU. This method blocks until the array is available. + * + * @param array + * @return This kernel so that we can use the 'fluent' style API + */ + public Kernel get(long[][][] array) { + runner().get(array); + return (this); + } + + /** + * Enqueue a request to return this buffer from the GPU. This method blocks until the array is available. + * + * @param array + * @return This kernel so that we can use the 'fluent' style API + */ + public Kernel get(double[] array) { + runner().get(array); + return (this); + } + + /** + * Enqueue a request to return this buffer from the GPU. This method blocks until the array is available. + * + * @param array + * @return This kernel so that we can use the 'fluent' style API + */ + public Kernel get(double[][] array) { + runner().get(array); + return (this); + } + + /** + * Enqueue a request to return this buffer from the GPU. This method blocks until the array is available. + * + * @param array + * @return This kernel so that we can use the 'fluent' style API + */ + public Kernel get(double[][][] array) { + runner().get(array); + return (this); + } + + /** + * Enqueue a request to return this buffer from the GPU. This method blocks until the array is available. + * + * @param array + * @return This kernel so that we can use the 'fluent' style API + */ + public Kernel get(float[] array) { + runner().get(array); + return (this); + } + + /** + * Enqueue a request to return this buffer from the GPU. This method blocks until the array is available. + * + * @param array + * @return This kernel so that we can use the 'fluent' style API + */ + public Kernel get(float[][] array) { + runner().get(array); + return (this); + } + + /** + * Enqueue a request to return this buffer from the GPU. This method blocks until the array is available. + * + * @param array + * @return This kernel so that we can use the 'fluent' style API + */ + public Kernel get(float[][][] array) { + runner().get(array); + return (this); + } + + /** + * Enqueue a request to return this buffer from the GPU. This method blocks until the array is available. + * + * @param array + * @return This kernel so that we can use the 'fluent' style API + */ + public Kernel get(int[] array) { + runner().get(array); + return (this); + } + + /** + * Enqueue a request to return this buffer from the GPU. This method blocks until the array is available. + * + * @param array + * @return This kernel so that we can use the 'fluent' style API + */ + public Kernel get(int[][] array) { + runner().get(array); + return (this); + } + + /** + * Enqueue a request to return this buffer from the GPU. This method blocks until the array is available. + * + * @param array + * @return This kernel so that we can use the 'fluent' style API + */ + public Kernel get(int[][][] array) { + runner().get(array); + return (this); + } + + /** + * Enqueue a request to return this buffer from the GPU. This method blocks until the array is available. + * + * @param array + * @return This kernel so that we can use the 'fluent' style API + */ + public Kernel get(byte[] array) { + runner().get(array); + return (this); + } + + /** + * Enqueue a request to return this buffer from the GPU. This method blocks until the array is available. + * + * @param array + * @return This kernel so that we can use the 'fluent' style API + */ + public Kernel get(byte[][] array) { + runner().get(array); + return (this); + } + + /** + * Enqueue a request to return this buffer from the GPU. This method blocks until the array is available. + * + * @param array + * @return This kernel so that we can use the 'fluent' style API + */ + public Kernel get(byte[][][] array) { + runner().get(array); + return (this); + } + + /** + * Enqueue a request to return this buffer from the GPU. This method blocks until the array is available. + * + * @param array + * @return This kernel so that we can use the 'fluent' style API + */ + public Kernel get(char[] array) { + runner().get(array); + return (this); + } + + /** + * Enqueue a request to return this buffer from the GPU. This method blocks until the array is available. + * + * @param array + * @return This kernel so that we can use the 'fluent' style API + */ + public Kernel get(char[][] array) { + runner().get(array); + return (this); + } + + /** + * Enqueue a request to return this buffer from the GPU. This method blocks until the array is available. + * + * @param array + * @return This kernel so that we can use the 'fluent' style API + */ + public Kernel get(char[][][] array) { + runner().get(array); + return (this); + } + + /** + * Enqueue a request to return this buffer from the GPU. This method blocks until the array is available. + * + * @param array + * @return This kernel so that we can use the 'fluent' style API + */ + public Kernel get(boolean[] array) { + runner().get(array); + return (this); + } + + /** + * Enqueue a request to return this buffer from the GPU. This method blocks until the array is available. + * + * @param array + * @return This kernel so that we can use the 'fluent' style API + */ + public Kernel get(boolean[][] array) { + runner().get(array); + return (this); + } + + /** + * Enqueue a request to return this buffer from the GPU. This method blocks until the array is available. + * + * @param array + * @return This kernel so that we can use the 'fluent' style API + */ + public Kernel get(boolean[][][] array) { + runner().get(array); + return (this); + } + + /** + * Get the profiling information from the last successful call to Kernel.execute(). + * + * @return A list of ProfileInfo records + */ + public List getProfileInfo() { + return runner().getProfileInfo(); + } + + /** + * @deprecated See {@link EXECUTION_MODE}. + */ + @Deprecated + private final LinkedHashSet executionModes = (Config.executionMode != null) ? EXECUTION_MODE.getDefaultExecutionModes() : new LinkedHashSet<>(Collections.singleton(EXECUTION_MODE.AUTO)); + + /** + * @deprecated See {@link EXECUTION_MODE}. + */ + @Deprecated + private Iterator currentMode = executionModes.iterator(); + + /** + * @deprecated See {@link EXECUTION_MODE}. + */ + @Deprecated + private EXECUTION_MODE executionMode = currentMode.next(); + + /** + * @deprecated See {@link EXECUTION_MODE}. + *

+ * set possible fallback path for execution modes. + * for example setExecutionFallbackPath(GPU,CPU,JTP) will try to use the GPU + * if it fails it will fall back to OpenCL CPU and finally it will try JTP. + */ + @Deprecated + public void addExecutionModes(EXECUTION_MODE... platforms) { + executionModes.addAll(Arrays.asList(platforms)); + currentMode = executionModes.iterator(); + executionMode = currentMode.next(); + } + + /** + * @return is there another execution path we can try + * @deprecated See {@link EXECUTION_MODE}. + */ + @Deprecated + public boolean hasNextExecutionMode() { + return currentMode.hasNext(); + } + + /** + * @deprecated See {@link EXECUTION_MODE}. + * try the next execution path in the list if there aren't any more than give up + */ + @Deprecated + public void tryNextExecutionMode() { + if (currentMode.hasNext()) { + executionMode = currentMode.next(); + } + } + + private static final ValueCache, Map, RuntimeException> mappedMethodFlags = markedWith(OpenCLMapping.class); + + private static final ValueCache, Map, RuntimeException> openCLDelegateMethodFlags = markedWith(OpenCLDelegate.class); + + private static final ValueCache, Map, RuntimeException> atomic32Cache = cacheProperty((ValueComputer, Map>) key -> { + Map properties = new HashMap<>(); + for (final Method method : key.getDeclaredMethods()) { + if (isRelevant(method) && method.isAnnotationPresent(OpenCLMapping.class)) { + properties.put(toSignature(method), method.getAnnotation(OpenCLMapping.class).atomic32()); + } + } + return properties; + }); + + private static final ValueCache, Map, RuntimeException> atomic64Cache = cacheProperty((ValueComputer, Map>) key -> { + Map properties = new HashMap<>(); + for (final Method method : key.getDeclaredMethods()) { + if (isRelevant(method) && method.isAnnotationPresent(OpenCLMapping.class)) { + properties.put(toSignature(method), method.getAnnotation(OpenCLMapping.class).atomic64()); + } + } + return properties; + }); + + private static boolean getBoolean(ValueCache, Map, RuntimeException> methodNamesCache, + MethodReferenceEntry methodReferenceEntry) { + return getProperty(methodNamesCache, methodReferenceEntry, false); + } + + private static ValueCache, Map, RuntimeException> markedWith( + final Class annotationClass) { + return cacheProperty((ValueComputer, Map>) key -> { + Map markedMethodNames = new HashMap<>(); + for (final Method method : key.getDeclaredMethods()) { + markedMethodNames.put(toSignature(method), method.isAnnotationPresent(annotationClass)); + } + return markedMethodNames; + }); + } + + private static String toSignature(Method method) { + return method.getName() + getArgumentsLetters(method) + getReturnTypeLetter(method); + } + + private static String getArgumentsLetters(Method method) { + StringBuilder sb = new StringBuilder("("); + for (Class parameterClass : method.getParameterTypes()) { + sb.append(toClassShortNameIfAny(parameterClass)); + } + sb.append(')'); + return sb.toString(); + } + + private static boolean isRelevant(Method method) { + return !method.isSynthetic() && !method.isBridge(); + } + + private static V getProperty(ValueCache, Map, T> cache, + MethodReferenceEntry methodReferenceEntry, V defaultValue) throws T { + Map map = cache.computeIfAbsent(methodReferenceEntry.getOwnerClassModel().clazz); + String key = toSignature(methodReferenceEntry); + if (map.containsKey(key)) + return map.get(key); + return defaultValue; + } + + private static String toSignature(MethodReferenceEntry methodReferenceEntry) { + NameAndTypeEntry nameAndTypeEntry = methodReferenceEntry.getNameAndTypeEntry(); + return nameAndTypeEntry.getNameUTF8Entry().getUTF8() + nameAndTypeEntry.getDescriptorUTF8Entry().getUTF8(); + } + + private static final ValueCache, Map, RuntimeException> mappedMethodNamesCache = cacheProperty((ValueComputer, Map>) key -> { + Map properties = new HashMap<>(); + for (final Method method : key.getDeclaredMethods()) { + if (isRelevant(method) && method.isAnnotationPresent(OpenCLMapping.class)) { + // ultimately, need a way to constrain this based upon signature (to disambiguate abs(float) from abs(int); + final OpenCLMapping annotation = method.getAnnotation(OpenCLMapping.class); + final String mapTo = annotation.mapTo(); + if (mapTo != null && !mapTo.isEmpty()) { + properties.put(toSignature(method), mapTo); + } + } + } + return properties; + }); + + private static ValueCache, Map, T> cacheProperty( + final ThrowingValueComputer, Map, T> throwingValueComputer) { + return ValueCache.on(key -> { + Map properties = new HashMap<>(); + Deque> superclasses = new ArrayDeque<>(); + Class currentSuperClass = key; + do { + superclasses.push(currentSuperClass); + currentSuperClass = currentSuperClass.getSuperclass(); + } while (currentSuperClass != Object.class); + for (Class clazz : superclasses) { + // Overwrite property values for shadowed/overriden methods + properties.putAll(throwingValueComputer.compute(clazz)); + } + return properties; + }); + } + + public static void invalidateCaches() { + atomic32Cache.invalidate(); + atomic64Cache.invalidate(); + mappedMethodFlags.invalidate(); + mappedMethodNamesCache.invalidate(); + openCLDelegateMethodFlags.invalidate(); + } } diff --git a/src/main/java/com/aparapi/ProfileInfo.java b/src/main/java/com/aparapi/ProfileInfo.java index 47b1e5da..0391bab1 100644 --- a/src/main/java/com/aparapi/ProfileInfo.java +++ b/src/main/java/com/aparapi/ProfileInfo.java @@ -58,7 +58,7 @@ private enum TYPE { R, X, W - }; // 0 = write, 1 = execute, 2 = read + } // 0 = write, 1 = execute, 2 = read private final TYPE type; @@ -116,7 +116,7 @@ public TYPE getType() { } @Override public String toString() { - final StringBuilder sb = new StringBuilder(); + final StringBuilder sb = new StringBuilder(512); sb.append("ProfileInfo["); sb.append(type); sb.append(" '"); @@ -131,7 +131,7 @@ public TYPE getType() { sb.append(queued); sb.append(", duration="); sb.append((end - start)); - sb.append("]"); + sb.append(']'); return sb.toString(); } diff --git a/src/main/java/com/aparapi/Range.java b/src/main/java/com/aparapi/Range.java index c289d66a..5f27222e 100644 --- a/src/main/java/com/aparapi/Range.java +++ b/src/main/java/com/aparapi/Range.java @@ -64,14 +64,16 @@ */ public class Range extends RangeJNI{ - public static final int THREADS_PER_CORE = 16; + private static final int THREADS_PER_CORE = + 1; + //16; - public static final int MAX_OPENCL_GROUP_SIZE = 256; + private static final int MAX_OPENCL_GROUP_SIZE = 256; - public static final int MAX_GROUP_SIZE = Math.max(Runtime.getRuntime().availableProcessors() * THREADS_PER_CORE, + private static final int MAX_GROUP_SIZE = Math.max(Runtime.getRuntime().availableProcessors() * THREADS_PER_CORE, MAX_OPENCL_GROUP_SIZE); - private OpenCLDevice device = null; + public final Device device; private int maxWorkGroupSize; @@ -87,8 +89,8 @@ public class Range extends RangeJNI{ * @param _device * @param _dims */ - public Range(Device _device, int _dims) { - device = !(_device instanceof OpenCLDevice) ? null : (OpenCLDevice) _device; + private Range(Device _device, int _dims) { + device = _device; //!(_device instanceof OpenCLDevice) ? null : (OpenCLDevice) _device; dims = _dims; if (device != null) { @@ -99,6 +101,9 @@ public Range(Device _device, int _dims) { } } + public int volume() { + return globalSize_0 * globalSize_1 * globalSize_2; + } /** * Create a one dimensional range 0.._globalWidth which is processed in groups of size _localWidth. *
@@ -191,9 +196,7 @@ public static Range create(int _globalWidth, int _localWidth) { } public static Range create(int _globalWidth) { - final Range range = create(null, _globalWidth); - - return (range); + return create(null, _globalWidth); } /** @@ -429,15 +432,13 @@ public static Range create3D(int _globalWidth, int _globalHeight, int _globalDep switch (dims) { case 1: - sb.append("global:" + globalSize_0 + " local:" + (localIsDerived ? "(derived)" : "") + localSize_0); + sb.append("global:").append(globalSize_0).append(" local:").append(localIsDerived ? "(derived)" : "").append(localSize_0); break; case 2: - sb.append("2D(global:" + globalSize_0 + "x" + globalSize_1 + " local:" + (localIsDerived ? "(derived)" : "") - + localSize_0 + "x" + localSize_1 + ")"); + sb.append("2D(global:").append(globalSize_0).append('x').append(globalSize_1).append(" local:").append(localIsDerived ? "(derived)" : "").append(localSize_0).append('x').append(localSize_1).append(')'); break; case 3: - sb.append("3D(global:" + globalSize_0 + "x" + globalSize_1 + "x" + globalSize_2 + " local:" - + (localIsDerived ? "(derived)" : "") + localSize_0 + "x" + localSize_1 + "x" + localSize_2 + ")"); + sb.append("3D(global:").append(globalSize_0).append('x').append(globalSize_1).append('x').append(globalSize_2).append(" local:").append(localIsDerived ? "(derived)" : "").append(localSize_0).append('x').append(localSize_1).append('x').append(localSize_2).append(')'); break; } @@ -473,7 +474,19 @@ public int getGlobalSize(int _dim) { * @return the number of groups for the given dimension. */ public int getNumGroups(int _dim) { - return (_dim == 0 ? (globalSize_0 / localSize_0) : (_dim == 1 ? (globalSize_1 / localSize_1) : (globalSize_2 / localSize_2))); + int g, l; + switch (_dim) { + case 0: g = globalSize_0; l = localSize_0; break; + case 1: g = globalSize_1; l = localSize_1; break; + case 2: g = globalSize_2; l = localSize_2; break; + default: + throw new UnsupportedOperationException(); + } + return divideWork(g, l); + } + + static int divideWork(int total, int div) { + return (int) Math.ceil(((float)total)/div); } /** @@ -499,14 +512,14 @@ public int getGlobalSize_0() { * @param globalSize_0 * the globalSize_0 to set */ - public void setGlobalSize_0(int globalSize_0) { + private void setGlobalSize_0(int globalSize_0) { this.globalSize_0 = globalSize_0; } /** * @return the localSize_0 */ - public int getLocalSize_0() { + private int getLocalSize_0() { return localSize_0; } @@ -514,7 +527,7 @@ public int getLocalSize_0() { * @param localSize_0 * the localSize_0 to set */ - public void setLocalSize_0(int localSize_0) { + private void setLocalSize_0(int localSize_0) { this.localSize_0 = localSize_0; } @@ -529,14 +542,14 @@ public int getGlobalSize_1() { * @param globalSize_1 * the globalSize_1 to set */ - public void setGlobalSize_1(int globalSize_1) { + private void setGlobalSize_1(int globalSize_1) { this.globalSize_1 = globalSize_1; } /** * @return the localSize_1 */ - public int getLocalSize_1() { + private int getLocalSize_1() { return localSize_1; } @@ -544,7 +557,7 @@ public int getLocalSize_1() { * @param localSize_1 * the localSize_1 to set */ - public void setLocalSize_1(int localSize_1) { + private void setLocalSize_1(int localSize_1) { this.localSize_1 = localSize_1; } @@ -559,14 +572,14 @@ public int getGlobalSize_2() { * @param globalSize_2 * the globalSize_2 to set */ - public void setGlobalSize_2(int globalSize_2) { + private void setGlobalSize_2(int globalSize_2) { this.globalSize_2 = globalSize_2; } /** * @return the localSize_2 */ - public int getLocalSize_2() { + private int getLocalSize_2() { return localSize_2; } @@ -574,7 +587,7 @@ public int getLocalSize_2() { * @param localSize_2 * the localSize_2 to set */ - public void setLocalSize_2(int localSize_2) { + private void setLocalSize_2(int localSize_2) { this.localSize_2 = localSize_2; } @@ -598,7 +611,7 @@ public void setDims(int dims) { /** * @return the valid */ - public boolean isValid() { + private boolean isValid() { return valid; } @@ -606,7 +619,7 @@ public boolean isValid() { * @param valid * the valid to set */ - public void setValid(boolean valid) { + private void setValid(boolean valid) { this.valid = valid; } @@ -621,14 +634,14 @@ public boolean isLocalIsDerived() { * @param localIsDerived * the localIsDerived to set */ - public void setLocalIsDerived(boolean localIsDerived) { + private void setLocalIsDerived(boolean localIsDerived) { this.localIsDerived = localIsDerived; } /** * @return the maxWorkGroupSize */ - public int getMaxWorkGroupSize() { + private int getMaxWorkGroupSize() { return maxWorkGroupSize; } @@ -643,7 +656,7 @@ public void setMaxWorkGroupSize(int maxWorkGroupSize) { /** * @return the maxWorkItemSize */ - public int[] getMaxWorkItemSize() { + private int[] getMaxWorkItemSize() { return maxWorkItemSize; } diff --git a/src/main/java/com/aparapi/device/Device.java b/src/main/java/com/aparapi/device/Device.java index 670cf6ba..4408e8cf 100644 --- a/src/main/java/com/aparapi/device/Device.java +++ b/src/main/java/com/aparapi/device/Device.java @@ -15,168 +15,182 @@ */ package com.aparapi.device; -import com.aparapi.*; -import com.aparapi.internal.kernel.*; - -public abstract class Device{ - - public static enum TYPE { - UNKNOWN(Integer.MAX_VALUE), - GPU(2), - CPU(3), - JTP(5), - SEQ(6), - ACC(1), - ALT(4); - - /** Heuristic ranking of device types, lower is better. */ - public final int rank; - - TYPE(int rank) { - this.rank = rank; - } - }; - - /** @deprecated use {@link KernelManager#bestDevice()} - * @see com.aparapi.device - */ - @Deprecated - public static Device best() { - return KernelManager.instance().bestDevice(); - } - - /** - * @see com.aparapi.device - */ - @SuppressWarnings("deprecation") - @Deprecated - public static Device bestGPU() { - return firstGPU(); - } - - /** - * @see com.aparapi.device - */ - @Deprecated - public static Device first(final Device.TYPE _type) { - return KernelManager.DeprecatedMethods.firstDevice(_type); - } - - /** - * @see com.aparapi.device - */ - @SuppressWarnings("deprecation") - @Deprecated - public static Device firstGPU() { - return KernelManager.DeprecatedMethods.firstDevice(TYPE.GPU); - } - - /** - * @see com.aparapi.device - */ - @SuppressWarnings("deprecation") - @Deprecated - public static Device firstCPU() { - return KernelManager.DeprecatedMethods.firstDevice(TYPE.CPU); - } - - /** - * @see com.aparapi.device - */ - @Deprecated - public static Device bestACC() { - throw new UnsupportedOperationException(); - } - - protected TYPE type = TYPE.UNKNOWN; - - protected int maxWorkGroupSize; - - protected int maxWorkItemDimensions; - - protected int[] maxWorkItemSize = new int[] { - 0, - 0, - 0 - }; - - public abstract String getShortDescription(); - - public TYPE getType() { - return type; - } - - public void setType(TYPE type) { - this.type = type; - } - - public int getMaxWorkItemDimensions() { - return maxWorkItemDimensions; - } - - public void setMaxWorkItemDimensions(int _maxWorkItemDimensions) { - maxWorkItemDimensions = _maxWorkItemDimensions; - } - - public int getMaxWorkGroupSize() { - return maxWorkGroupSize; - } - - public void setMaxWorkGroupSize(int _maxWorkGroupSize) { - maxWorkGroupSize = _maxWorkGroupSize; - } - - public int[] getMaxWorkItemSize() { - return maxWorkItemSize; - } - - public void setMaxWorkItemSize(int[] maxWorkItemSize) { - this.maxWorkItemSize = maxWorkItemSize; - } - - public Range createRange(int _globalWidth) { - return (Range.create(this, _globalWidth)); - } - - public Range createRange(int _globalWidth, int _localWidth) { - return (Range.create(this, _globalWidth, _localWidth)); - } - - public Range createRange2D(int _globalWidth, int _globalHeight) { - return (Range.create2D(this, _globalWidth, _globalHeight)); - } - - 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) { - return (Range.create3D(this, _globalWidth, _globalHeight, _globalDepth)); - } - - public Range createRange3D(int _globalWidth, int _globalHeight, int _globalDepth, int _localWidth, int _localHeight, - int _localDepth) { - return (Range.create3D(this, _globalWidth, _globalHeight, _globalDepth, _localWidth, _localHeight, _localDepth)); - } - - public abstract long getDeviceId(); - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (!(o instanceof Device)) { - return false; - } - - Device device = (Device) o; - - return getDeviceId() == device.getDeviceId(); - } - - @Override - public int hashCode() { - return Long.valueOf(getDeviceId()).hashCode(); - } +import com.aparapi.Range; +import com.aparapi.internal.kernel.KernelManager; + +public abstract class Device { + + public final long deviceId; + + protected Device(long deviceId) { + this.deviceId = deviceId; + } + + public enum TYPE { + UNKNOWN(Integer.MAX_VALUE), + GPU(2), + CPU(3), + JTP(5), + SEQ(6), + ACC(1), + ALT(4); + + /** + * Heuristic ranking of device types, lower is better. + */ + public final int rank; + + TYPE(int rank) { + this.rank = rank; + } + } + + /** + * @see com.aparapi.device + * @deprecated use {@link KernelManager#bestDevice()} + */ + @Deprecated + public static Device best() { + return KernelManager.instance().bestDevice(); + } + + /** + * @see com.aparapi.device + */ + @SuppressWarnings("deprecation") + @Deprecated + public static Device bestGPU() { + return firstGPU(); + } + + /** + * @see com.aparapi.device + */ + @Deprecated + public static Device first(final Device.TYPE _type) { + return KernelManager.DeprecatedMethods.firstDevice(_type); + } + + /** + * @see com.aparapi.device + */ + @SuppressWarnings("deprecation") + @Deprecated + public static Device firstGPU() { + return KernelManager.DeprecatedMethods.firstDevice(TYPE.GPU); + } + + /** + * @see com.aparapi.device + */ + @SuppressWarnings("deprecation") + @Deprecated + public static Device firstCPU() { + return KernelManager.DeprecatedMethods.firstDevice(TYPE.CPU); + } + + /** + * @see com.aparapi.device + */ + @Deprecated + public static Device bestACC() { + throw new UnsupportedOperationException(); + } + + protected TYPE type = TYPE.UNKNOWN; + + protected int maxWorkGroupSize; + + protected int maxWorkItemDimensions; + + protected int[] maxWorkItemSize = new int[]{ + 0, + 0, + 0 + }; + + public abstract String getShortDescription(); + + public TYPE getType() { + return type; + } + + protected final void setType(TYPE type) { + this.type = type; + } + + public int getMaxWorkItemDimensions() { + return maxWorkItemDimensions; + } + + public void setMaxWorkItemDimensions(int _maxWorkItemDimensions) { + maxWorkItemDimensions = _maxWorkItemDimensions; + } + + public int getMaxWorkGroupSize() { + return maxWorkGroupSize; + } + + public void setMaxWorkGroupSize(int _maxWorkGroupSize) { + maxWorkGroupSize = _maxWorkGroupSize; + } + + public int[] getMaxWorkItemSize() { + return maxWorkItemSize; + } + + public void setMaxWorkItemSize(int[] maxWorkItemSize) { + this.maxWorkItemSize = maxWorkItemSize; + } + + public Range createRange(int _globalWidth) { + return (Range.create(this, _globalWidth)); + } + + public Range createRange(int _globalWidth, int _localWidth) { + return (Range.create(this, _globalWidth, _localWidth)); + } + + public Range createRange2D(int _globalWidth, int _globalHeight) { + return (Range.create2D(this, _globalWidth, _globalHeight)); + } + + 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) { + return (Range.create3D(this, _globalWidth, _globalHeight, _globalDepth)); + } + + public Range createRange3D(int _globalWidth, int _globalHeight, int _globalDepth, int _localWidth, int _localHeight, + int _localDepth) { + return (Range.create3D(this, _globalWidth, _globalHeight, _globalDepth, _localWidth, _localHeight, _localDepth)); + } + + public final long getDeviceId() { + return deviceId; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (!(o instanceof Device)) { + return false; + } + + Device device = (Device) o; + + return deviceId == device.deviceId; + } + + @Override + public int hashCode() { + long i = deviceId; + return (int) (i ^ (i >>> 32)); + //return Long.valueOf(getDeviceId()).hashCode(); + } + } diff --git a/src/main/java/com/aparapi/device/JavaDevice.java b/src/main/java/com/aparapi/device/JavaDevice.java index b7c9ab47..ee379872 100644 --- a/src/main/java/com/aparapi/device/JavaDevice.java +++ b/src/main/java/com/aparapi/device/JavaDevice.java @@ -22,11 +22,10 @@ public class JavaDevice extends Device { public static final JavaDevice SEQUENTIAL = new JavaDevice(TYPE.SEQ, "Java Sequential", -1); private final String name; - private final long deviceId; private JavaDevice(TYPE _type, String _name, long deviceId) { - this.deviceId = deviceId; - this.type = _type; + super(deviceId); + setType(_type); this.name = _name; } @@ -35,11 +34,6 @@ public String getShortDescription() { return name; } - @Override - public long getDeviceId() { - return deviceId; - } - @Override public String toString() { return getShortDescription(); diff --git a/src/main/java/com/aparapi/device/OpenCLDevice.java b/src/main/java/com/aparapi/device/OpenCLDevice.java index ac27440f..1dac4ab0 100644 --- a/src/main/java/com/aparapi/device/OpenCLDevice.java +++ b/src/main/java/com/aparapi/device/OpenCLDevice.java @@ -25,10 +25,7 @@ import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; +import java.util.*; import com.aparapi.Range; import com.aparapi.internal.opencl.OpenCLArgDescriptor; @@ -45,125 +42,126 @@ import com.aparapi.opencl.OpenCL.Resource; import com.aparapi.opencl.OpenCL.Source; -public class OpenCLDevice extends Device{ +public class OpenCLDevice extends Device { - private final OpenCLPlatform platform; + private final OpenCLPlatform platform; - private final long deviceId; + private int maxComputeUnits; - private int maxComputeUnits; + private long localMemSize; - private long localMemSize; + private long globalMemSize; - private long globalMemSize; - - private long maxMemAllocSize; - - private String shortDescription = null; - - private String name = null; - - /** - * Minimal constructor - * - * @param _platform - * @param _deviceId - * @param _type - */ - public OpenCLDevice(OpenCLPlatform _platform, long _deviceId, TYPE _type) { - platform = _platform; - deviceId = _deviceId; - type = _type; - } - - public OpenCLPlatform getOpenCLPlatform() { - return platform; - } - - public int getMaxComputeUnits() { - return maxComputeUnits; - } - - public void setMaxComputeUnits(int _maxComputeUnits) { - maxComputeUnits = _maxComputeUnits; - } - - public long getLocalMemSize() { - return localMemSize; - } - - public void setLocalMemSize(long _localMemSize) { - localMemSize = _localMemSize; - } - - public long getMaxMemAllocSize() { - return maxMemAllocSize; - } - - public void setMaxMemAllocSize(long _maxMemAllocSize) { - maxMemAllocSize = _maxMemAllocSize; - } - - public long getGlobalMemSize() { - return globalMemSize; - } - - public void setGlobalMemSize(long _globalMemSize) { - globalMemSize = _globalMemSize; - } - - void setMaxWorkItemSize(int _dim, int _value) { - maxWorkItemSize[_dim] = _value; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - @Override - public long getDeviceId() { - return (deviceId); - } - - @Override - public String getShortDescription() { - if (shortDescription == null) { - String vendor = platform.getName(); - // Hopefully(!) this equates to the recognisable name of the vendor, e.g. "Intel", "NVIDIA", "AMD" - // Note, it is not necessarily the hardware vendor, e.g. if the AMD CPU driver (i.e. platform) is used for an Intel CPU, this will be "AMD" - String[] split = vendor.split("[\\s\\(\\)]"); // split on whitespace or on '(' or ')' since Intel use "Intel(R)" here - shortDescription = split[0] + "<" + getType() + ">"; - } - return shortDescription; - } - - public static class OpenCLInvocationHandler> implements InvocationHandler{ - private final Map map; - - private final OpenCLProgram program; - private boolean disposed = false; - public OpenCLInvocationHandler(OpenCLProgram _program, Map _map) { - program = _program; - map = _map; - disposed = false; - } - - @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { - if (disposed){ - throw new IllegalStateException("bound interface already disposed"); - } - if (!isReservedInterfaceMethod(method)) { - final OpenCLKernel kernel = map.get(method.getName()); - if (kernel != null) { - kernel.invoke(args); + private long maxMemAllocSize; + + private String shortDescription = null; + + private String name = null; + + /** + * Minimal constructor + * + * @param _platform + * @param _deviceId + * @param _type + */ + public OpenCLDevice(OpenCLPlatform _platform, long _deviceId, TYPE _type) { + super(_deviceId); + platform = _platform; + setType(_type); + } + + public OpenCLPlatform getOpenCLPlatform() { + return platform; + } + + public int getMaxComputeUnits() { + return maxComputeUnits; + } + + public void setMaxComputeUnits(int _maxComputeUnits) { + maxComputeUnits = _maxComputeUnits; + } + + public long getLocalMemSize() { + return localMemSize; + } + + public void setLocalMemSize(long _localMemSize) { + localMemSize = _localMemSize; + } + + public long getMaxMemAllocSize() { + return maxMemAllocSize; + } + + public void setMaxMemAllocSize(long _maxMemAllocSize) { + maxMemAllocSize = _maxMemAllocSize; + } + + public long getGlobalMemSize() { + return globalMemSize; + } + + public void setGlobalMemSize(long _globalMemSize) { + globalMemSize = _globalMemSize; + } + + void setMaxWorkItemSize(int _dim, int _value) { + maxWorkItemSize[_dim] = _value; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + @Override + public String getShortDescription() { + if (shortDescription == null) { + String vendor = getName(); + // Hopefully(!) this equates to the recognisable name of the vendor, e.g. "Intel", "NVIDIA", "AMD" + // Note, it is not necessarily the hardware vendor, e.g. if the AMD CPU driver (i.e. platform) is used for an Intel CPU, this will be "AMD" + String[] split = vendor.split("[\\s\\(\\)]"); // split on whitespace or on '(' or ')' since Intel use "Intel(R)" here + if (split.length == 0 || split[0] == null + || !(split[0].equals("Intel") || split[0].equals("NVIDIA") || split[0].equals("AMD"))) { + vendor = platform.getName(); + split = vendor.split("[\\s\\(\\)]"); } - } else { - if (method.getName().equals("put")) { - System.out.println("put not implemented"); + shortDescription = split[0] + '<' + getType() + '>'; + } + return shortDescription; + } + + static class OpenCLInvocationHandler> implements InvocationHandler { + private final Map map; + + private final OpenCLProgram program; + private boolean disposed = false; + + OpenCLInvocationHandler(OpenCLProgram _program, Map _map) { + program = _program; + map = _map; + disposed = false; + } + + @Override + public Object invoke(Object proxy, Method method, Object[] args) { + if (disposed) { + throw new IllegalStateException("bound interface already disposed"); + } + if (!isReservedInterfaceMethod(method)) { + final OpenCLKernel kernel = map.get(method.getName()); + if (kernel != null) { + kernel.invoke(args); + } + } else { + switch (method.getName()) { + case "put": + throw new UnsupportedOperationException("put not implemented"); /* for (Object arg : args) { @@ -186,8 +184,9 @@ public OpenCLInvocationHandler(OpenCLProgram _program, Map } } */ - } else if (method.getName().equals("get")) { - System.out.println("get not implemented"); + + case "get": + throw new UnsupportedOperationException("get not implemented"); /* for (Object arg : args) { Class argClass = arg.getClass(); @@ -209,337 +208,344 @@ public OpenCLInvocationHandler(OpenCLProgram _program, Map } } */ - } else if (method.getName().equals("begin")) { - System.out.println("begin not implemented"); - } else if (method.getName().equals("dispose")) { - // System.out.println("dispose"); - for (OpenCLKernel k:map.values()){ - k.dispose(); - } - program.dispose(); - map.clear(); - disposed=true; - } else if (method.getName().equals("end")) { - System.out.println("end not implemented"); - } else if (method.getName().equals("getProfileInfo")){ - proxy = program.getProfileInfo(); - } - } - return proxy; - } - } - - public List getArgs(Method m) { - final List args = new ArrayList(); - final Annotation[][] parameterAnnotations = m.getParameterAnnotations(); - final Class[] parameterTypes = m.getParameterTypes(); - - for (int arg = 0; arg < parameterTypes.length; arg++) { - if (parameterTypes[arg].isAssignableFrom(Range.class)) { - - } else { - - long bits = 0L; - String name = null; - for (final Annotation pa : parameterAnnotations[arg]) { - if (pa instanceof GlobalReadOnly) { - name = ((GlobalReadOnly) pa).value(); - bits |= OpenCLArgDescriptor.ARG_GLOBAL_BIT | OpenCLArgDescriptor.ARG_READONLY_BIT; - } else if (pa instanceof GlobalWriteOnly) { - name = ((GlobalWriteOnly) pa).value(); - bits |= OpenCLArgDescriptor.ARG_GLOBAL_BIT | OpenCLArgDescriptor.ARG_WRITEONLY_BIT; - } else if (pa instanceof GlobalReadWrite) { - name = ((GlobalReadWrite) pa).value(); - bits |= OpenCLArgDescriptor.ARG_GLOBAL_BIT | OpenCLArgDescriptor.ARG_READWRITE_BIT; - } else if (pa instanceof Local) { - name = ((Local) pa).value(); - bits |= OpenCLArgDescriptor.ARG_LOCAL_BIT; - } else if (pa instanceof Constant) { - name = ((Constant) pa).value(); - bits |= OpenCLArgDescriptor.ARG_CONST_BIT | OpenCLArgDescriptor.ARG_READONLY_BIT; - } else if (pa instanceof Arg) { - name = ((Arg) pa).value(); - bits |= OpenCLArgDescriptor.ARG_ISARG_BIT; - } + case "begin": + throw new UnsupportedOperationException("begin not implemented"); + case "dispose": + // System.out.println("dispose"); + for (OpenCLKernel k : map.values()) + k.dispose(); + map.clear(); + program.dispose(); + disposed = true; + break; + case "end": + throw new UnsupportedOperationException("end not implemented"); + + case "getProfileInfo": + proxy = program.getProfileInfo(); + break; + } } - if (parameterTypes[arg].isArray()) { - if (parameterTypes[arg].isAssignableFrom(float[].class)) { - bits |= OpenCLArgDescriptor.ARG_FLOAT_BIT | OpenCLArgDescriptor.ARG_ARRAY_BIT; - } else if (parameterTypes[arg].isAssignableFrom(int[].class)) { - bits |= OpenCLArgDescriptor.ARG_INT_BIT | OpenCLArgDescriptor.ARG_ARRAY_BIT; - } else if (parameterTypes[arg].isAssignableFrom(double[].class)) { - bits |= OpenCLArgDescriptor.ARG_DOUBLE_BIT | OpenCLArgDescriptor.ARG_ARRAY_BIT; - } else if (parameterTypes[arg].isAssignableFrom(byte[].class)) { - bits |= OpenCLArgDescriptor.ARG_BYTE_BIT | OpenCLArgDescriptor.ARG_ARRAY_BIT; - } else if (parameterTypes[arg].isAssignableFrom(short[].class)) { - bits |= OpenCLArgDescriptor.ARG_SHORT_BIT | OpenCLArgDescriptor.ARG_ARRAY_BIT; - } else if (parameterTypes[arg].isAssignableFrom(long[].class)) { - bits |= OpenCLArgDescriptor.ARG_LONG_BIT | OpenCLArgDescriptor.ARG_ARRAY_BIT; - } - } else if (parameterTypes[arg].isPrimitive()) { - if (parameterTypes[arg].isAssignableFrom(float.class)) { - bits |= OpenCLArgDescriptor.ARG_FLOAT_BIT | OpenCLArgDescriptor.ARG_PRIMITIVE_BIT; - } else if (parameterTypes[arg].isAssignableFrom(int.class)) { - bits |= OpenCLArgDescriptor.ARG_INT_BIT | OpenCLArgDescriptor.ARG_PRIMITIVE_BIT; - } else if (parameterTypes[arg].isAssignableFrom(double.class)) { - bits |= OpenCLArgDescriptor.ARG_DOUBLE_BIT | OpenCLArgDescriptor.ARG_PRIMITIVE_BIT; - } else if (parameterTypes[arg].isAssignableFrom(byte.class)) { - bits |= OpenCLArgDescriptor.ARG_BYTE_BIT | OpenCLArgDescriptor.ARG_PRIMITIVE_BIT; - } else if (parameterTypes[arg].isAssignableFrom(short.class)) { - bits |= OpenCLArgDescriptor.ARG_SHORT_BIT | OpenCLArgDescriptor.ARG_PRIMITIVE_BIT; - } else if (parameterTypes[arg].isAssignableFrom(long.class)) { - bits |= OpenCLArgDescriptor.ARG_LONG_BIT | OpenCLArgDescriptor.ARG_PRIMITIVE_BIT; - } - } else { - System.out.println("OUch!"); - } - if (name == null) { - throw new IllegalStateException("no name!"); - } - final OpenCLArgDescriptor kernelArg = new OpenCLArgDescriptor(name, bits); - args.add(kernelArg); + return proxy; + } + } - } - } + private static List getArgs(Method m) { + final Annotation[][] parameterAnnotations = m.getParameterAnnotations(); + final Class[] parameterTypes = m.getParameterTypes(); - return (args); - } + final List args = new ArrayList<>(parameterTypes.length); + for (int arg = 0; arg < parameterTypes.length; arg++) { + Class t = parameterTypes[arg]; + if (t.isAssignableFrom(Range.class)) { - private static boolean isReservedInterfaceMethod(Method _methods) { - return ( _methods.getName().equals("put") - || _methods.getName().equals("get") - || _methods.getName().equals("dispose") - || _methods.getName().equals("begin") - || _methods.getName().equals("end") - || _methods.getName().equals("getProfileInfo")); - } - - private String streamToString(InputStream _inputStream) { - final StringBuilder sourceBuilder = new StringBuilder(); - - if (_inputStream != null) { - - final BufferedReader reader = new BufferedReader(new InputStreamReader(_inputStream)); + } else { - try { - for (String line = reader.readLine(); line != null; line = reader.readLine()) { - sourceBuilder.append(line).append("\n"); + long bits = 0L; + String name = null; + for (final Annotation pa : parameterAnnotations[arg]) { + if (pa instanceof GlobalReadOnly) { + name = ((GlobalReadOnly) pa).value(); + bits |= OpenCLArgDescriptor.ARG_GLOBAL_BIT | OpenCLArgDescriptor.ARG_READONLY_BIT; + } else if (pa instanceof GlobalWriteOnly) { + name = ((GlobalWriteOnly) pa).value(); + bits |= OpenCLArgDescriptor.ARG_GLOBAL_BIT | OpenCLArgDescriptor.ARG_WRITEONLY_BIT; + } else if (pa instanceof GlobalReadWrite) { + name = ((GlobalReadWrite) pa).value(); + bits |= OpenCLArgDescriptor.ARG_GLOBAL_BIT | OpenCLArgDescriptor.ARG_READWRITE_BIT; + } else if (pa instanceof Local) { + name = ((Local) pa).value(); + bits |= OpenCLArgDescriptor.ARG_LOCAL_BIT; + } else if (pa instanceof Constant) { + name = ((Constant) pa).value(); + bits |= OpenCLArgDescriptor.ARG_CONST_BIT | OpenCLArgDescriptor.ARG_READONLY_BIT; + } else if (pa instanceof Arg) { + name = ((Arg) pa).value(); + bits |= OpenCLArgDescriptor.ARG_ISARG_BIT; + } + + } + if (t.isArray()) { + if (t.isAssignableFrom(float[].class)) { + bits |= OpenCLArgDescriptor.ARG_FLOAT_BIT | OpenCLArgDescriptor.ARG_ARRAY_BIT; + } else if (t.isAssignableFrom(int[].class)) { + bits |= OpenCLArgDescriptor.ARG_INT_BIT | OpenCLArgDescriptor.ARG_ARRAY_BIT; + } else if (t.isAssignableFrom(double[].class)) { + bits |= OpenCLArgDescriptor.ARG_DOUBLE_BIT | OpenCLArgDescriptor.ARG_ARRAY_BIT; + } else if (t.isAssignableFrom(byte[].class)) { + bits |= OpenCLArgDescriptor.ARG_BYTE_BIT | OpenCLArgDescriptor.ARG_ARRAY_BIT; + } else if (t.isAssignableFrom(short[].class)) { + bits |= OpenCLArgDescriptor.ARG_SHORT_BIT | OpenCLArgDescriptor.ARG_ARRAY_BIT; + } else if (t.isAssignableFrom(long[].class)) { + bits |= OpenCLArgDescriptor.ARG_LONG_BIT | OpenCLArgDescriptor.ARG_ARRAY_BIT; + } + } else if (t.isPrimitive()) { + if (t.isAssignableFrom(float.class)) { + bits |= OpenCLArgDescriptor.ARG_FLOAT_BIT | OpenCLArgDescriptor.ARG_PRIMITIVE_BIT; + } else if (t.isAssignableFrom(int.class)) { + bits |= OpenCLArgDescriptor.ARG_INT_BIT | OpenCLArgDescriptor.ARG_PRIMITIVE_BIT; + } else if (t.isAssignableFrom(double.class)) { + bits |= OpenCLArgDescriptor.ARG_DOUBLE_BIT | OpenCLArgDescriptor.ARG_PRIMITIVE_BIT; + } else if (t.isAssignableFrom(byte.class)) { + bits |= OpenCLArgDescriptor.ARG_BYTE_BIT | OpenCLArgDescriptor.ARG_PRIMITIVE_BIT; + } else if (t.isAssignableFrom(short.class)) { + bits |= OpenCLArgDescriptor.ARG_SHORT_BIT | OpenCLArgDescriptor.ARG_PRIMITIVE_BIT; + } else if (t.isAssignableFrom(long.class)) { + bits |= OpenCLArgDescriptor.ARG_LONG_BIT | OpenCLArgDescriptor.ARG_PRIMITIVE_BIT; + } + } else { + //System.out.println("OUch!"); + throw new IllegalStateException(t + " unsupported type"); + } + if (name == null) { + throw new IllegalStateException("no name!"); + } + + args.add(new OpenCLArgDescriptor(name, bits)); } - } catch (final IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - try { - _inputStream.close(); - } catch (final IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - - - return (sourceBuilder.toString()); - } - - public > T bind(Class _interface, InputStream _inputStream) { - return (bind(_interface, streamToString(_inputStream))); - } - - public > T bind(Class _interface) { - return (bind(_interface, (String) null)); - } - - public > T bind(Class _interface, String _source) { - final Map> kernelNameToArgsMap = new HashMap>(); - - if (_source == null) { - final StringBuilder sourceBuilder = new StringBuilder(); - boolean interfaceIsAnnotated = false; - for (final Annotation a : _interface.getAnnotations()) { - if (a instanceof Source) { - final Source source = (Source) a; - sourceBuilder.append(source.value()).append("\n"); - interfaceIsAnnotated = true; - } else if (a instanceof Resource) { - final Resource sourceResource = (Resource) a; - final InputStream stream = _interface.getClassLoader().getResourceAsStream(sourceResource.value()); - sourceBuilder.append(streamToString(stream)); - interfaceIsAnnotated = true; + } + + return (args); + } + + final static Set reservedInterfaceMethods = new HashSet(6) {{ + add("put"); + add("get"); + add("dispose"); + add("begin"); + add("end"); + add("getProfileInfo"); + }}; + + private static boolean isReservedInterfaceMethod(Method _methods) { + return reservedInterfaceMethods.contains(_methods.getName()); + } + + private static String streamToString(InputStream _inputStream) { + final StringBuilder sourceBuilder = new StringBuilder(); + + if (_inputStream != null) { + + final BufferedReader reader = new BufferedReader(new InputStreamReader(_inputStream)); + + try { + for (String line = reader.readLine(); line != null; line = reader.readLine()) { + sourceBuilder.append(line).append('\n'); + } + } catch (final IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); } - } - if (interfaceIsAnnotated) { - // just crawl the methods (non put or get) and create kernels - for (final Method m : _interface.getDeclaredMethods()) { - if (!isReservedInterfaceMethod(m)) { - final List args = getArgs(m); - kernelNameToArgsMap.put(m.getName(), args); - } + try { + _inputStream.close(); + } catch (final IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + + return (sourceBuilder.toString()); + } + + public > T bind(Class _interface, InputStream _inputStream) { + return (bind(_interface, streamToString(_inputStream))); + } + + public > T bind(Class _interface) { + return (bind(_interface, (String) null)); + } + + public > T bind(Class _interface, String _source) { + final Map> kernelNameToArgsMap = new HashMap<>(); + + if (_source == null) { + final StringBuilder sourceBuilder = new StringBuilder(); + boolean interfaceIsAnnotated = false; + for (final Annotation a : _interface.getAnnotations()) { + if (a instanceof Source) { + final Source source = (Source) a; + sourceBuilder.append(source.value()).append('\n'); + interfaceIsAnnotated = true; + } else if (a instanceof Resource) { + final Resource sourceResource = (Resource) a; + final InputStream stream = _interface.getClassLoader().getResourceAsStream(sourceResource.value()); + sourceBuilder.append(streamToString(stream)); + interfaceIsAnnotated = true; + } } - } else { - for (final Method m : _interface.getDeclaredMethods()) { - if (!isReservedInterfaceMethod(m)) { - for (final Annotation a : m.getAnnotations()) { - // System.out.println(" annotation "+a); - // System.out.println(" annotation type " + a.annotationType()); - if (a instanceof Kernel) { - sourceBuilder.append("__kernel void " + m.getName() + "("); + if (interfaceIsAnnotated) { + // just crawl the methods (non put or get) and create kernels + for (final Method m : _interface.getDeclaredMethods()) { + if (!isReservedInterfaceMethod(m)) { final List args = getArgs(m); + kernelNameToArgsMap.put(m.getName(), args); + } + } + } else { - boolean first = true; - for (final OpenCLArgDescriptor arg : args) { - if (first) { - first = false; - } else { - sourceBuilder.append(","); - } - sourceBuilder.append("\n " + arg); + for (final Method m : _interface.getDeclaredMethods()) { + if (!isReservedInterfaceMethod(m)) { + for (final Annotation a : m.getAnnotations()) { + // System.out.println(" annotation "+a); + // System.out.println(" annotation type " + a.annotationType()); + if (a instanceof Kernel) { + sourceBuilder.append("__kernel void ").append(m.getName()).append('('); + final List args = getArgs(m); + + boolean first = true; + for (final OpenCLArgDescriptor arg : args) { + if (first) { + first = false; + } else { + sourceBuilder.append(','); + } + sourceBuilder.append("\n ").append(arg); + } + + sourceBuilder.append(')'); + final Kernel kernel = (Kernel) a; + sourceBuilder.append(kernel.value()); + kernelNameToArgsMap.put(m.getName(), args); + + } } + } + } - sourceBuilder.append(")"); - final Kernel kernel = (Kernel) a; - sourceBuilder.append(kernel.value()); - kernelNameToArgsMap.put(m.getName(), args); - - } - } - } } - - } - _source = sourceBuilder.toString(); - } else { - for (final Method m : _interface.getDeclaredMethods()) { - if (!isReservedInterfaceMethod(m)) { - final List args = getArgs(m); - kernelNameToArgsMap.put(m.getName(), args); + _source = sourceBuilder.toString(); + } else { + for (final Method m : _interface.getDeclaredMethods()) { + if (!isReservedInterfaceMethod(m)) { + kernelNameToArgsMap.put(m.getName(), getArgs(m)); + } } - } - } + } - final OpenCLProgram program = new OpenCLProgram(this, _source).createProgram(this); + final OpenCLProgram program = new OpenCLProgram(this, _source).createProgram(this); - final Map map = new HashMap(); - for (final String name : kernelNameToArgsMap.keySet()) { - final OpenCLKernel kernel = OpenCLKernel.createKernel(program, name, kernelNameToArgsMap.get(name)); - //final OpenCLKernel kernel = new OpenCLKernel(program, name, kernelNameToArgsMap.get(name)); - if (kernel == null) { - throw new IllegalStateException("kernel is null"); - } + final Map map = new HashMap<>(); + for (final Map.Entry> stringListEntry : kernelNameToArgsMap.entrySet()) { + final OpenCLKernel kernel = OpenCLKernel.createKernel(program, stringListEntry.getKey(), stringListEntry.getValue()); + //final OpenCLKernel kernel = new OpenCLKernel(program, name, kernelNameToArgsMap.get(name)); + if (kernel == null) { + throw new IllegalStateException("kernel is null"); + } - map.put(name, kernel); - } + map.put(stringListEntry.getKey(), kernel); + } - final OpenCLInvocationHandler invocationHandler = new OpenCLInvocationHandler(program, map); - final T instance = (T) Proxy.newProxyInstance(OpenCLDevice.class.getClassLoader(), new Class[] { + final OpenCLInvocationHandler invocationHandler = new OpenCLInvocationHandler<>(program, map); + final T instance = (T) Proxy.newProxyInstance(OpenCLDevice.class.getClassLoader(), new Class[]{ _interface, OpenCL.class - }, invocationHandler); + }, invocationHandler); - return instance; - } + return instance; + } - public interface DeviceSelector{ - OpenCLDevice select(OpenCLDevice _device); - } + public interface DeviceSelector { + OpenCLDevice select(OpenCLDevice _device); + } - public interface DeviceComparitor{ - OpenCLDevice select(OpenCLDevice _deviceLhs, OpenCLDevice _deviceRhs); - } + public interface DeviceComparitor { + OpenCLDevice select(OpenCLDevice _deviceLhs, OpenCLDevice _deviceRhs); + } - /** List OpenCLDevices of a given TYPE, or all OpenCLDevices if type == null. */ - public static List listDevices(TYPE type) { - final OpenCLPlatform platform = new OpenCLPlatform(0, null, null, null); - final ArrayList results = new ArrayList<>(); + /** List OpenCLDevices of a given TYPE, or all OpenCLDevices if type == null. */ + public static List listDevices(TYPE type, Iterable platforms) { + final ArrayList results = new ArrayList<>(); - for (final OpenCLPlatform p : platform.getOpenCLPlatforms()) { - for (final OpenCLDevice device : p.getOpenCLDevices()) { - if (type == null || device.getType() == type) { - results.add(device); + for (final OpenCLPlatform p : platforms) { + for (final OpenCLDevice device : p.getOpenCLDevices()) { + if (type == null || device.getType() == type) { + results.add(device); + } } - } - } + } - return results; - } + return results; + } - public static OpenCLDevice select(DeviceSelector _deviceSelector) { - OpenCLDevice device = null; - final OpenCLPlatform platform = new OpenCLPlatform(0, null, null, null); + public static OpenCLDevice select(DeviceSelector _deviceSelector) { + OpenCLDevice device = null; + final OpenCLPlatform platform = new OpenCLPlatform(0, null, null, null); - for (final OpenCLPlatform p : platform.getOpenCLPlatforms()) { - for (final OpenCLDevice d : p.getOpenCLDevices()) { - device = _deviceSelector.select(d); + for (final OpenCLPlatform p : platform.getOpenCLPlatforms()) { + for (final OpenCLDevice d : p.getOpenCLDevices()) { + device = _deviceSelector.select(d); + if (device != null) { + break; + } + } if (device != null) { - break; + break; } - } - if (device != null) { - break; - } - } - - return (device); - } - - public static OpenCLDevice select(DeviceComparitor _deviceComparitor) { - OpenCLDevice device = null; - final OpenCLPlatform platform = new OpenCLPlatform(0, null, null, null); - - List openCLPlatforms = platform.getOpenCLPlatforms(); - for (final OpenCLPlatform p : openCLPlatforms) { - List openCLDevices = p.getOpenCLDevices(); - for (final OpenCLDevice d : openCLDevices) { - if (device == null) { - device = d; - } else { - device = _deviceComparitor.select(device, d); + } + + return (device); + } + + public static OpenCLDevice select(DeviceComparitor _deviceComparitor) { + OpenCLDevice device = null; + final OpenCLPlatform platform = new OpenCLPlatform(0, null, null, null); + + List openCLPlatforms = platform.getOpenCLPlatforms(); + for (final OpenCLPlatform p : openCLPlatforms) { + List openCLDevices = p.getOpenCLDevices(); + for (final OpenCLDevice d : openCLDevices) { + if (device == null) { + device = d; + } else { + device = _deviceComparitor.select(device, d); + } } - } - } - - return (device); - } - - public static OpenCLDevice select(DeviceComparitor _deviceComparitor, Device.TYPE _type) { - OpenCLDevice device = null; - final OpenCLPlatform platform = new OpenCLPlatform(0, null, null, null); - - for (final OpenCLPlatform p : platform.getOpenCLPlatforms()) { - for (final OpenCLDevice d : p.getOpenCLDevices()) { - if (d.getType() != _type) continue; - if (device == null) { - device = d; + } + + return (device); + } + + public static OpenCLDevice select(DeviceComparitor _deviceComparitor, Device.TYPE _type) { + OpenCLDevice device = null; + final OpenCLPlatform platform = new OpenCLPlatform(0, null, null, null); + + for (final OpenCLPlatform p : platform.getOpenCLPlatforms()) { + for (final OpenCLDevice d : p.getOpenCLDevices()) { + if (d.getType() != _type) continue; + if (device == null) { + device = d; + } else { + device = _deviceComparitor.select(device, d); + } + } + } + + return (device); + } + + @Override + public String toString() { + final StringBuilder s = new StringBuilder("{"); + boolean first = true; + for (final int workItemSize : maxWorkItemSize) { + if (first) { + first = false; } else { - device = _deviceComparitor.select(device, d); + s.append(", "); } - } - } - - return (device); - } - - @Override public String toString() { - final StringBuilder s = new StringBuilder("{"); - boolean first = true; - for (final int workItemSize : maxWorkItemSize) { - if (first) { - first = false; - } else { - s.append(", "); - } - s.append(workItemSize); - } + s.append(workItemSize); + } - s.append("}"); + s.append('}'); - return ("Device " + deviceId + "\n vendor = " + getOpenCLPlatform().getVendor() + return ("Device " + deviceId + "\n vendor = " + getOpenCLPlatform().getVendor() + "\n type:" + type + "\n maxComputeUnits=" + maxComputeUnits + "\n maxWorkItemDimensions=" + maxWorkItemDimensions + "\n maxWorkItemSizes=" + s + "\n maxWorkWorkGroupSize=" + maxWorkGroupSize + "\n globalMemSize=" + globalMemSize + "\n localMemSize=" + localMemSize); - } + } } diff --git a/src/main/java/com/aparapi/internal/exception/ClassParseException.java b/src/main/java/com/aparapi/internal/exception/ClassParseException.java index 39aac1fa..a38e8261 100644 --- a/src/main/java/com/aparapi/internal/exception/ClassParseException.java +++ b/src/main/java/com/aparapi/internal/exception/ClassParseException.java @@ -65,7 +65,7 @@ to national security controls as identified on the Commerce Control List (curren */ @SuppressWarnings("serial") public class ClassParseException extends AparapiException{ - public static enum TYPE { + public enum TYPE { NONE("none"), // ARRAY_RETURN("We don't support areturn instructions"), // PUTFIELD("We don't support putstatic instructions"), // @@ -103,18 +103,18 @@ public static enum TYPE { MISSINGLOCALVARIABLETABLE("Method does not contain a local variable table (recompile with -g?)"), // IMPROPERPRIVATENAMEMANGLING("Could not parse private array size from field name"); - private String description; + private final String description; TYPE(final String _description) { description = _description; } - public String getDescription() { + String getDescription() { return (description); } - }; + } - private Instruction instruction; + private Instruction instruction; private TYPE type; @@ -125,13 +125,13 @@ public ClassParseException(final TYPE _type) { } public ClassParseException(final Instruction _instruction, final TYPE _type) { - super("@" + _instruction.getThisPC() + " " + _instruction.getByteCode() + " " + _type.getDescription()); + super("@" + _instruction.getThisPC() + ' ' + _instruction.getByteCode() + ' ' + _type.getDescription()); type = _type; instruction = _instruction; } public ClassParseException(final TYPE _type, final String _methodName) { - super("@" + _methodName + " " + _type.getDescription()); + super('@' + _methodName + ' ' + _type.getDescription()); type = _type; instruction = null; } diff --git a/src/main/java/com/aparapi/internal/exception/RangeException.java b/src/main/java/com/aparapi/internal/exception/RangeException.java index f8b8c757..ce0afeab 100644 --- a/src/main/java/com/aparapi/internal/exception/RangeException.java +++ b/src/main/java/com/aparapi/internal/exception/RangeException.java @@ -52,7 +52,8 @@ to national security controls as identified on the Commerce Control List (curren */ package com.aparapi.internal.exception; -@SuppressWarnings("serial") public class RangeException extends AparapiException{ +@SuppressWarnings("serial") +class RangeException extends AparapiException{ public RangeException(String msg) { super(msg); diff --git a/src/main/java/com/aparapi/internal/instruction/BranchSet.java b/src/main/java/com/aparapi/internal/instruction/BranchSet.java index a0437b55..f9044aa8 100644 --- a/src/main/java/com/aparapi/internal/instruction/BranchSet.java +++ b/src/main/java/com/aparapi/internal/instruction/BranchSet.java @@ -127,19 +127,19 @@ public static abstract class LogicalExpressionNode { private LogicalExpressionNode parent = null; - public void setParent(LogicalExpressionNode _parent) { + void setParent(LogicalExpressionNode _parent) { parent = _parent; } - public abstract int getTarget(); + protected abstract int getTarget(); - public abstract int getFallThrough(); + protected abstract int getFallThrough(); - public abstract void invert(); + protected abstract void invert(); public abstract LogicalExpressionNode cloneInverted(); - public LogicalExpressionNode getRoot() { + LogicalExpressionNode getRoot() { if (parent != null) { return (parent); } else { @@ -147,11 +147,11 @@ public LogicalExpressionNode getRoot() { } } - public LogicalExpressionNode getNext() { + LogicalExpressionNode getNext() { return (next == null ? next : next.getRoot()); } - public void setNext(LogicalExpressionNode _next) { + void setNext(LogicalExpressionNode _next) { next = _next == null ? _next : _next.getRoot(); } @@ -176,7 +176,7 @@ public static class SimpleLogicalExpressionNode extends LogicalExpressionNode { private boolean invert; - public SimpleLogicalExpressionNode(ConditionalBranch _branch) { + SimpleLogicalExpressionNode(ConditionalBranch _branch) { this(_branch, false); } @@ -215,7 +215,7 @@ public ConditionalBranch getBranch() { @Override public String toString() { - return invert ? ("!(" + getBranch() + ")") : getBranch().toString(); + return invert ? ("!(" + getBranch() + ')') : getBranch().toString(); } } @@ -253,7 +253,7 @@ private CompoundLogicalExpressionNode(boolean _and, LogicalExpressionNode _lhs, lhs.setParent(this); } - public CompoundLogicalExpressionNode(boolean _and, LogicalExpressionNode _lhs, LogicalExpressionNode _rhs) { + CompoundLogicalExpressionNode(boolean _and, LogicalExpressionNode _lhs, LogicalExpressionNode _rhs) { this(_and, _lhs, _rhs, true); } @@ -295,12 +295,12 @@ public LogicalExpressionNode getRhs() { @Override public String toString() { - return getLhs().toString() + " " + (isAnd() ? "&&" : "||") + " " + getRhs().toString(); + return getLhs().toString() + ' ' + (isAnd() ? "&&" : "||") + ' ' + getRhs().toString(); } } - private final List set = new ArrayList(); + private final List set = new ArrayList<>(); private final Instruction fallThrough; @@ -323,7 +323,7 @@ public BranchSet(Branch _branch) { target = _branch.getTarget(); last = _branch; - final Set expandedSet = new LinkedHashSet(); + final Set expandedSet = new LinkedHashSet<>(); final Instruction fallThroughRoot = last.getNextExpr(); fallThrough = fallThroughRoot == null ? last.getNextPC() : fallThroughRoot.getStartInstruction(); first = last; diff --git a/src/main/java/com/aparapi/internal/instruction/ExpressionList.java b/src/main/java/com/aparapi/internal/instruction/ExpressionList.java index 2aac1c00..e3134337 100644 --- a/src/main/java/com/aparapi/internal/instruction/ExpressionList.java +++ b/src/main/java/com/aparapi/internal/instruction/ExpressionList.java @@ -83,7 +83,7 @@ to national security controls as identified on the Commerce Control List (curren */ public class ExpressionList{ - private static Logger logger = Logger.getLogger(Config.getLoggerName()); + private static final Logger logger = Logger.getLogger(Config.getLoggerName()); private final MethodModel methodModel; @@ -124,12 +124,13 @@ public ExpressionList(MethodModel _methodModel) { * @param _extent * @return */ - public boolean doesNotContainContinueOrBreak(Instruction _start, Instruction _extent) { + private static boolean doesNotContainContinueOrBreak(Instruction _start, Instruction _extent) { boolean ok = true; boolean breakOrContinue = false; for (Instruction i = _start; i != null; i = i.getNextExpr()) { if (i.isBranch()) { - if (i.asBranch().isForwardUnconditional() && i.asBranch().getTarget().isAfter(_extent)) { + Branch br = i.asBranch(); + if (br.isForwardUnconditional() && br.getTarget().isAfter(_extent)) { breakOrContinue = true; } else { ok = false; @@ -149,7 +150,7 @@ public boolean doesNotContainContinueOrBreak(Instruction _start, Instruction _ex return (ok); } - public boolean doesNotContainCompositeOrBranch(Instruction _start, Instruction _exclusiveEnd) { + private static boolean doesNotContainCompositeOrBranch(Instruction _start, Instruction _exclusiveEnd) { boolean ok = true; for (Instruction i = _start; (i != null) && (i != _exclusiveEnd); i = i.getNextExpr()) { if (!(i instanceof CompositeInstruction) && (i.isBranch())) { @@ -160,7 +161,7 @@ public boolean doesNotContainCompositeOrBranch(Instruction _start, Instruction _ return (ok); } - public void unwind() { + private void unwind() { if (parent != null) { if (instruction != null) { tail.setNextExpr(instruction); @@ -481,7 +482,7 @@ public boolean foldComposite(final Instruction _instruction) throws ClassParseEx loopTop = loopTop.getPrevExpr(); if (loopTop instanceof AssignToLocalVariable) { - final LocalVariableInfo localVariableInfo = ((AssignToLocalVariable) loopTop).getLocalVariableInfo(); + final LocalVariableInfo localVariableInfo = ((InstructionSet.LocalVariableTableIndexAccessor) loopTop).getLocalVariableInfo(); if ((localVariableInfo.getStart() == loopTop.getNextExpr().getStartPC()) && (localVariableInfo.getEnd() == _instruction.getThisPC())) { loopTop = loopTop.getPrevExpr(); // back up over the initialization @@ -500,7 +501,7 @@ public boolean foldComposite(final Instruction _instruction) throws ClassParseEx // looptop == the unconditional? loopTop = loopTop.getPrevExpr(); if (loopTop instanceof AssignToLocalVariable) { - final LocalVariableInfo localVariableInfo = ((AssignToLocalVariable) loopTop).getLocalVariableInfo(); + final LocalVariableInfo localVariableInfo = ((InstructionSet.LocalVariableTableIndexAccessor) loopTop).getLocalVariableInfo(); if ((localVariableInfo.getStart() == loopTop.getNextExpr().getStartPC()) && (localVariableInfo.getEnd() == _instruction.getThisPC())) { loopTop = loopTop.getPrevExpr(); // back up over the initialization @@ -618,7 +619,7 @@ public boolean foldComposite(final Instruction _instruction) throws ClassParseEx Instruction loopTop = topOfRealLoop.getPrevExpr(); if (loopTop instanceof AssignToLocalVariable) { - final LocalVariableInfo localVariableInfo = ((AssignToLocalVariable) loopTop).getLocalVariableInfo(); + final LocalVariableInfo localVariableInfo = ((InstructionSet.LocalVariableTableIndexAccessor) loopTop).getLocalVariableInfo(); if ((localVariableInfo.getStart() == loopTop.getNextExpr().getStartPC()) && (localVariableInfo.getEnd() == _instruction.getThisPC())) { loopTop = loopTop.getPrevExpr(); // back up over the initialization @@ -652,7 +653,7 @@ public boolean foldComposite(final Instruction _instruction) throws ClassParseEx } if (loopTop instanceof AssignToLocalVariable) { - final LocalVariableInfo localVariableInfo = ((AssignToLocalVariable) loopTop).getLocalVariableInfo(); + final LocalVariableInfo localVariableInfo = ((InstructionSet.LocalVariableTableIndexAccessor) loopTop).getLocalVariableInfo(); if ((localVariableInfo.getStart() == loopTop.getNextExpr().getStartPC()) && (localVariableInfo.getEnd() == _instruction.getThisPC())) { loopTop = loopTop.getPrevExpr(); // back up over the initialization @@ -802,19 +803,26 @@ public boolean foldComposite(final Instruction _instruction) throws ClassParseEx for (final LocalVariableInfo localVariableInfo : localVariableTable) { if (localVariableInfo.getEnd() == _instruction.getThisPC()) { - logger.fine(localVariableInfo.getVariableName() + " scope " + localVariableInfo.getStart() + " ," - + localVariableInfo.getEnd()); + if (logger.isLoggable(Level.FINE)) { + logger.fine(localVariableInfo.getVariableName() + " scope " + localVariableInfo.getStart() + " ," + + localVariableInfo.getEnd()); + } if (localVariableInfo.getStart() < startPc) { startPc = localVariableInfo.getStart(); } } } if (startPc < Short.MAX_VALUE) { - logger.fine("Scope block from " + startPc + " to " + (tail.getThisPC() + tail.getLength())); + + if (logger.isLoggable(Level.FINE)) + logger.fine("Scope block from " + startPc + " to " + (tail.getThisPC() + tail.getLength())); + for (Instruction i = head; i != null; i = i.getNextPC()) { if (i.getThisPC() == startPc) { final Instruction startInstruction = i.getRootExpr().getPrevExpr(); - logger.fine("Start = " + startInstruction); + + if (logger.isLoggable(Level.FINE)) + logger.fine("Start = " + startInstruction); addAsComposites(ByteCode.COMPOSITE_ARBITRARY_SCOPE, startInstruction.getPrevExpr(), null); handled = true; @@ -830,8 +838,6 @@ public boolean foldComposite(final Instruction _instruction) throws ClassParseEx Config.instructionListener.showAndTell("after folding", head, _instruction); } - } catch (final ClassParseException _classParseException) { - throw new ClassParseException(_classParseException); } catch (final Throwable t) { throw new ClassParseException(t); @@ -861,7 +867,7 @@ private void addAsComposites(ByteCode _byteCode, Instruction _start, BranchSet _ */ public String dumpDiagram(Instruction _instruction) { final StringBuilder sb = new StringBuilder(); - final List list = new ArrayList(); + final List list = new ArrayList<>(); for (Instruction i = head; i != null; i = i.getNextExpr()) { list.add(i); @@ -871,20 +877,20 @@ public String dumpDiagram(Instruction _instruction) { list.add(i); } - final Instruction[] array = list.toArray(new Instruction[0]); + final Instruction[] array = list.toArray(new Instruction[list.size()]); boolean lastWasCursor = false; - final List branches = new ArrayList(); + final List branches = new ArrayList<>(); for (final Instruction i : list) { sb.append(String.format(" %3d", i.getStartPC())); } - sb.append("\n"); + sb.append('\n'); for (final Instruction i : list) { sb.append(String.format(" %3d", i.getThisPC())); } - sb.append("\n"); + sb.append('\n'); for (final Instruction i : list) { if (i == _instruction) { diff --git a/src/main/java/com/aparapi/internal/instruction/Instruction.java b/src/main/java/com/aparapi/internal/instruction/Instruction.java index 055f2424..d5a7c413 100644 --- a/src/main/java/com/aparapi/internal/instruction/Instruction.java +++ b/src/main/java/com/aparapi/internal/instruction/Instruction.java @@ -74,13 +74,13 @@ to national security controls as identified on the Commerce Control List (curren */ public abstract class Instruction{ - protected MethodModel method; + final MethodModel method; private final ByteCode byteCode; private int length; - protected int pc; + private final int pc; abstract String getDescription(); @@ -172,13 +172,13 @@ public int getStartPC() { return (getFirstChild() == null ? pc : getFirstChild().getStartPC()); } - protected Instruction(MethodModel _method, ByteCode _byteCode, int _pc) { + Instruction(MethodModel _method, ByteCode _byteCode, int _pc) { method = _method; pc = _pc; byteCode = _byteCode; } - protected Instruction(MethodModel _method, ByteCode _byteCode, ByteReader _byteReader, boolean _wide) { + Instruction(MethodModel _method, ByteCode _byteCode, ByteReader _byteReader, boolean _wide) { this(_method, _byteCode, _wide ? _byteReader.getOffset() - 2 : _byteReader.getOffset() - 1); } @@ -187,7 +187,7 @@ public int getStackConsumeCount() { return (byteCode.getPop().getStackAdjust()); } - public int getStackProduceCount() { + int getStackProduceCount() { return (byteCode.getPush().getStackAdjust()); } @@ -247,7 +247,7 @@ public Instruction getPrevPC() { return (prevPC); } - public void setParentExpr(Instruction _parentExpr) { + private void setParentExpr(Instruction _parentExpr) { parentExpr = _parentExpr; } @@ -259,7 +259,7 @@ public Instruction getRootExpr() { return (parentExpr == null ? this : parentExpr.getRootExpr()); } - public boolean isReverseConditionalBranchTarget() { + private boolean isReverseConditionalBranchTarget() { return ((reverseConditionalBranchTargets != null) && (reverseConditionalBranchTargets.size() > 0)); } @@ -267,7 +267,7 @@ public boolean isForwardConditionalBranchTarget() { return ((forwardConditionalBranchTargets != null) && (forwardConditionalBranchTargets.size() > 0)); } - public boolean isReverseUnconditionalBranchTarget() { + private boolean isReverseUnconditionalBranchTarget() { return ((reverseUnconditionalBranchTargets != null) && (reverseUnconditionalBranchTargets.size() > 0)); } @@ -275,7 +275,7 @@ public boolean isForwardUnconditionalBranchTarget() { return ((forwardUnconditionalBranchTargets != null) && (forwardUnconditionalBranchTargets.size() > 0)); } - public boolean isReverseBranchTarget() { + private boolean isReverseBranchTarget() { return (isReverseConditionalBranchTarget() || isReverseUnconditionalBranchTarget()); } @@ -316,31 +316,31 @@ public void addBranchTarget(Branch _branch) { if (_branch.isReverse()) { if (_branch.isConditional()) { if (reverseConditionalBranchTargets == null) { - reverseConditionalBranchTargets = new LinkedList(); + reverseConditionalBranchTargets = new LinkedList<>(); } reverseConditionalBranchTargets.add((ConditionalBranch) _branch); } else { if (reverseUnconditionalBranchTargets == null) { - reverseUnconditionalBranchTargets = new LinkedList(); + reverseUnconditionalBranchTargets = new LinkedList<>(); } reverseUnconditionalBranchTargets.add(_branch); } } else { if (_branch.isConditional()) { if (forwardConditionalBranchTargets == null) { - forwardConditionalBranchTargets = new LinkedList(); + forwardConditionalBranchTargets = new LinkedList<>(); } forwardConditionalBranchTargets.add((ConditionalBranch) _branch); } else { if (forwardUnconditionalBranchTargets == null) { - forwardUnconditionalBranchTargets = new LinkedList(); + forwardUnconditionalBranchTargets = new LinkedList<>(); } forwardUnconditionalBranchTargets.add(_branch); } } } - public void removeBranchTarget(Branch _branch) { + void removeBranchTarget(Branch _branch) { if (_branch.isReverse()) { if (_branch.isConditional()) { if (reverseConditionalBranchTargets != null) { diff --git a/src/main/java/com/aparapi/internal/instruction/InstructionPattern.java b/src/main/java/com/aparapi/internal/instruction/InstructionPattern.java index c0ad9ac9..7b2ed535 100644 --- a/src/main/java/com/aparapi/internal/instruction/InstructionPattern.java +++ b/src/main/java/com/aparapi/internal/instruction/InstructionPattern.java @@ -68,7 +68,9 @@ to national security controls as identified on the Commerce Control List (curren public class InstructionPattern{ - @SuppressWarnings("unused") private boolean compareSubTrees(Instruction _lhs, Instruction _rhs) { + @SuppressWarnings("unused") private static boolean compareSubTrees(Instruction _lhs, Instruction _rhs) { + if (_lhs == _rhs) + return true; _lhs = _lhs.getReal(); _rhs = _rhs.getReal(); boolean same = _lhs.sameAs(_rhs); @@ -91,15 +93,15 @@ public class InstructionPattern{ public static class InstructionMatch{ public final boolean ok; - public static final InstructionMatch TRUE = new InstructionMatch(true); + static final InstructionMatch TRUE = new InstructionMatch(true); - public static final InstructionMatch FALSE = new InstructionMatch(false); + static final InstructionMatch FALSE = new InstructionMatch(false); - public InstructionMatch(boolean _ok) { + InstructionMatch(boolean _ok) { ok = _ok; } - public static InstructionMatch test(boolean _condition) { + static InstructionMatch test(boolean _condition) { return (_condition ? TRUE : FALSE); } } @@ -120,7 +122,7 @@ public InstructionMatch matches(Instruction _instruction, InstructionMatcher _in return (InstructionMatch.FALSE); } - public InstructionMatcher(String _description) { + InstructionMatcher(String _description) { description = _description; } @@ -129,7 +131,7 @@ public String getDescription() { } } - public class AssignableInstructionMatcher extends InstructionMatcher{ + static class AssignableInstructionMatcher extends InstructionMatcher{ private final Class[] classes; public AssignableInstructionMatcher(Class... _classes) { diff --git a/src/main/java/com/aparapi/internal/instruction/InstructionSet.java b/src/main/java/com/aparapi/internal/instruction/InstructionSet.java index b16536ab..d9b86562 100644 --- a/src/main/java/com/aparapi/internal/instruction/InstructionSet.java +++ b/src/main/java/com/aparapi/internal/instruction/InstructionSet.java @@ -66,7 +66,7 @@ to national security controls as identified on the Commerce Control List (curren public class InstructionSet{ - public static enum LoadSpec { + public enum LoadSpec { NONE, // F, // Float D, // Double @@ -76,7 +76,7 @@ public static enum LoadSpec { O, // Object } - public static enum StoreSpec { + public enum StoreSpec { NONE, // F, // Float D, // Double @@ -86,7 +86,7 @@ public static enum StoreSpec { O, // Object } - public static enum TypeSpec { + public enum TypeSpec { NONE("none", "none", 0, 0), // Z("Z", "boolean", 4, 1), // Note 'Z' is the java code for 'boolean' type C("C", "char", 2, 1), // @@ -114,7 +114,7 @@ public static enum TypeSpec { private final int slots; - private TypeSpec(String _shortName, String _longName, int _size, int _slots) { + TypeSpec(String _shortName, String _longName, int _size, int _slots) { shortName = _shortName; longName = _longName; size = _size; @@ -145,7 +145,7 @@ public String getShortName() { * */ - public static enum Operator { + public enum Operator { NONE, LogicalOr(true, "||"), // LogicalAnd(true, "&&", LogicalOr), // @@ -198,19 +198,19 @@ public static enum Operator { private Operator compliment; - private Operator(boolean _binary, String _text) { + Operator(boolean _binary, String _text) { text = _text; binary = _binary; } - private Operator(boolean _binary, String _text, Operator _c) { + Operator(boolean _binary, String _text, Operator _c) { this(_binary, _text); compliment = _c; compliment.compliment = this; } - private Operator() { + Operator() { this(false, null); } @@ -226,7 +226,7 @@ public String getText(boolean _invert) { return (_invert ? compliment.getText() : getText()); } - public boolean isBinary() { + boolean isBinary() { return (binary); } @@ -237,7 +237,7 @@ public boolean isUnary() { } } - public static enum PushSpec { + public enum PushSpec { NONE, // UNKNOWN, // I(TypeSpec.I), // @@ -256,7 +256,7 @@ public static enum PushSpec { LorD(TypeSpec.LorD), // RA(TypeSpec.RA); - private PushSpec(TypeSpec... _types) { + PushSpec(TypeSpec... _types) { types = _types; } @@ -267,7 +267,7 @@ public int getStackAdjust() { } } - public static enum PopSpec { + public enum PopSpec { NONE, // UNKNOWN(TypeSpec.UNKNOWN), // I(TypeSpec.I), // @@ -299,7 +299,7 @@ public static enum PopSpec { OARGS(TypeSpec.O, TypeSpec.ARGS), // ; - private PopSpec(TypeSpec... _types) { + PopSpec(TypeSpec... _types) { types = _types; } @@ -310,7 +310,7 @@ public int getStackAdjust() { } } - public static enum ImmediateSpec { + public enum ImmediateSpec { NONE("NONE"), // UNKNOWN("UNKNOWN"), // Bconst("byte constant value", TypeSpec.B), // @@ -329,7 +329,7 @@ public static enum ImmediateSpec { private final String name; - private ImmediateSpec(String _name, TypeSpec... _types) { + ImmediateSpec(String _name, TypeSpec... _types) { name = _name; types = _types; @@ -346,7 +346,7 @@ public TypeSpec[] getTypes() { } } - public static enum ByteCode { + public enum ByteCode { // name, operation type, immediateOperands, pop operands, push operands NOP(null, LoadSpec.NONE, StoreSpec.NONE, ImmediateSpec.NONE, PopSpec.NONE, PushSpec.NONE, Operator.NONE), // ACONST_NULL(I_ACONST_NULL.class, PushSpec.N), // @@ -640,14 +640,14 @@ public static enum ByteCode { private final Operator operator; - private LoadSpec loadSpec; + private final LoadSpec loadSpec; - private StoreSpec storeSpec; + private final StoreSpec storeSpec; private Constructor constructor; - private ByteCode(Class _class, LoadSpec _loadSpec, StoreSpec _storeSpec, ImmediateSpec _immediate, PopSpec _pop, - PushSpec _push, Operator _operator) { + ByteCode(Class _class, LoadSpec _loadSpec, StoreSpec _storeSpec, ImmediateSpec _immediate, PopSpec _pop, + PushSpec _push, Operator _operator) { clazz = _class; immediate = _immediate; push = _push; @@ -660,68 +660,62 @@ private ByteCode(Class _class, LoadSpec _loadSpec, StoreSpec _storeSpec, Imme try { constructor = clazz.getDeclaredConstructor(MethodModel.class, ByteReader.class, boolean.class); - } catch (final SecurityException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (final NoSuchMethodException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (final IllegalArgumentException e) { + } catch (final SecurityException | IllegalArgumentException | NoSuchMethodException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } - private ByteCode(Class _class, ImmediateSpec _immediate) { + ByteCode(Class _class, ImmediateSpec _immediate) { this(_class, LoadSpec.NONE, StoreSpec.NONE, _immediate, PopSpec.NONE, PushSpec.NONE, Operator.NONE); } - private ByteCode(Class _class, PushSpec _push) { + ByteCode(Class _class, PushSpec _push) { this(_class, LoadSpec.NONE, StoreSpec.NONE, ImmediateSpec.NONE, PopSpec.NONE, _push, Operator.NONE); } - private ByteCode(Class _class, StoreSpec _store, ImmediateSpec _immediate, PopSpec _pop) { + ByteCode(Class _class, StoreSpec _store, ImmediateSpec _immediate, PopSpec _pop) { this(_class, LoadSpec.NONE, _store, _immediate, _pop, PushSpec.NONE, Operator.NONE); } - private ByteCode(Class _class, StoreSpec _store, PopSpec _pop) { + ByteCode(Class _class, StoreSpec _store, PopSpec _pop) { this(_class, LoadSpec.NONE, _store, ImmediateSpec.NONE, _pop, PushSpec.NONE, Operator.NONE); } - private ByteCode(Class _class, ImmediateSpec _immediate, PopSpec _pop) { + ByteCode(Class _class, ImmediateSpec _immediate, PopSpec _pop) { this(_class, LoadSpec.NONE, StoreSpec.NONE, _immediate, _pop, PushSpec.NONE, Operator.NONE); } - private ByteCode(Class _class, ImmediateSpec _immediate, PopSpec _pop, Operator _operator) { + ByteCode(Class _class, ImmediateSpec _immediate, PopSpec _pop, Operator _operator) { this(_class, LoadSpec.NONE, StoreSpec.NONE, _immediate, _pop, PushSpec.NONE, _operator); } - private ByteCode(Class _class, LoadSpec _load, ImmediateSpec _immediate, PushSpec _push) { + ByteCode(Class _class, LoadSpec _load, ImmediateSpec _immediate, PushSpec _push) { this(_class, _load, StoreSpec.NONE, _immediate, PopSpec.NONE, _push, Operator.NONE); } - private ByteCode(Class _class, LoadSpec _load, PushSpec _push) { + ByteCode(Class _class, LoadSpec _load, PushSpec _push) { this(_class, _load, StoreSpec.NONE, ImmediateSpec.NONE, PopSpec.NONE, _push, Operator.NONE); } - private ByteCode(Class _class, ImmediateSpec _immediate, PushSpec _push) { + ByteCode(Class _class, ImmediateSpec _immediate, PushSpec _push) { this(_class, LoadSpec.NONE, StoreSpec.NONE, _immediate, PopSpec.NONE, _push, Operator.NONE); } - private ByteCode(Class _class, PopSpec _pop, PushSpec _push) { + ByteCode(Class _class, PopSpec _pop, PushSpec _push) { this(_class, LoadSpec.NONE, StoreSpec.NONE, ImmediateSpec.NONE, _pop, _push, Operator.NONE); } - private ByteCode(Class _class, PopSpec _pop, PushSpec _push, Operator _operator) { + ByteCode(Class _class, PopSpec _pop, PushSpec _push, Operator _operator) { this(_class, LoadSpec.NONE, StoreSpec.NONE, ImmediateSpec.NONE, _pop, _push, _operator); } - private ByteCode(Class _class, PopSpec _pop) { + ByteCode(Class _class, PopSpec _pop) { this(_class, LoadSpec.NONE, StoreSpec.NONE, ImmediateSpec.NONE, _pop, PushSpec.NONE, Operator.NONE); } - private ByteCode() { + ByteCode() { this(null, LoadSpec.NONE, StoreSpec.NONE, ImmediateSpec.NONE, PopSpec.NONE, PushSpec.NONE, Operator.NONE); } @@ -737,7 +731,7 @@ public ImmediateSpec getImmediate() { return (immediate); } - public static ByteCode get(int _idx) { + static ByteCode get(int _idx) { return (values()[_idx]); } @@ -754,32 +748,17 @@ public boolean usesDouble() { final PushSpec push = getPush(); final PopSpec pop = getPop(); - if ((push == PushSpec.D) || (pop == PopSpec.D) || (pop == PopSpec.DD) || (pop == PopSpec.AID)) { - return true; - } + return (push == PushSpec.D) || (pop == PopSpec.D) || (pop == PopSpec.DD) || (pop == PopSpec.AID); - return false; } - public Instruction newInstruction(MethodModel _methodModel, ByteReader byteReader, boolean _isWide) { + Instruction newInstruction(MethodModel _methodModel, ByteReader byteReader, boolean _isWide) { Instruction newInstruction = null; if (constructor != null) { try { newInstruction = (Instruction) constructor.newInstance(_methodModel, byteReader, _isWide); newInstruction.setLength(byteReader.getOffset() - newInstruction.getThisPC()); - } catch (final SecurityException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (final IllegalArgumentException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (final InstantiationException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (final IllegalAccessException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (final InvocationTargetException e) { + } catch (final SecurityException | InvocationTargetException | IllegalAccessException | InstantiationException | IllegalArgumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } @@ -804,7 +783,7 @@ public static Instruction create(MethodModel _methodModel, ByteReader _byteReade return (newInstruction); } - public Operator getOperator() { + Operator getOperator() { return (operator); } @@ -819,10 +798,10 @@ public StoreSpec getStore() { public static class CompositeInstruction extends Instruction{ - protected BranchSet branchSet; + final BranchSet branchSet; - public CompositeInstruction(MethodModel method, ByteCode _byteCode, Instruction _firstChild, Instruction _lastChild, - BranchSet _branchSet) { + CompositeInstruction(MethodModel method, ByteCode _byteCode, Instruction _firstChild, Instruction _lastChild, + BranchSet _branchSet) { super(method, _byteCode, -1); branchSet = _branchSet; setChildren(_firstChild, _lastChild); @@ -879,60 +858,60 @@ public BranchSet getBranchSet() { } public static class CompositeIfInstruction extends CompositeInstruction{ - public CompositeIfInstruction(MethodModel method, Instruction _firstChild, Instruction _lastChild, BranchSet _branchSet) { + CompositeIfInstruction(MethodModel method, Instruction _firstChild, Instruction _lastChild, BranchSet _branchSet) { super(method, ByteCode.COMPOSITE_IF, _firstChild, _lastChild, _branchSet); } } public static class CompositeIfElseInstruction extends CompositeInstruction{ - public CompositeIfElseInstruction(MethodModel method, Instruction _firstChild, Instruction _lastChild, BranchSet _branchSet) { + CompositeIfElseInstruction(MethodModel method, Instruction _firstChild, Instruction _lastChild, BranchSet _branchSet) { super(method, ByteCode.COMPOSITE_IF_ELSE, _firstChild, _lastChild, _branchSet); } } public static class CompositeForSunInstruction extends CompositeInstruction{ - public CompositeForSunInstruction(MethodModel method, Instruction _firstChild, Instruction _lastChild, BranchSet _branchSet) { + CompositeForSunInstruction(MethodModel method, Instruction _firstChild, Instruction _lastChild, BranchSet _branchSet) { super(method, ByteCode.COMPOSITE_FOR_SUN, _firstChild, _lastChild, _branchSet); } } public static class CompositeWhileInstruction extends CompositeInstruction{ - public CompositeWhileInstruction(MethodModel method, Instruction _firstChild, Instruction _lastChild, BranchSet _branchSet) { + CompositeWhileInstruction(MethodModel method, Instruction _firstChild, Instruction _lastChild, BranchSet _branchSet) { super(method, ByteCode.COMPOSITE_WHILE, _firstChild, _lastChild, _branchSet); } } public static class CompositeEmptyLoopInstruction extends CompositeInstruction{ - public CompositeEmptyLoopInstruction(MethodModel method, Instruction _firstChild, Instruction _lastChild, BranchSet _branchSet) { + CompositeEmptyLoopInstruction(MethodModel method, Instruction _firstChild, Instruction _lastChild, BranchSet _branchSet) { super(method, ByteCode.COMPOSITE_EMPTY_LOOP, _firstChild, _lastChild, _branchSet); } } public static class CompositeDoWhileInstruction extends CompositeInstruction{ - protected CompositeDoWhileInstruction(MethodModel method, Instruction _firstChild, Instruction _lastChild, - BranchSet _branchSet) { + CompositeDoWhileInstruction(MethodModel method, Instruction _firstChild, Instruction _lastChild, + BranchSet _branchSet) { super(method, ByteCode.COMPOSITE_DO_WHILE, _firstChild, _lastChild, _branchSet); } } public static class CompositeForEclipseInstruction extends CompositeInstruction{ - protected CompositeForEclipseInstruction(MethodModel method, Instruction _firstChild, Instruction _lastChild, - BranchSet _branchSet) { + CompositeForEclipseInstruction(MethodModel method, Instruction _firstChild, Instruction _lastChild, + BranchSet _branchSet) { super(method, ByteCode.COMPOSITE_FOR_ECLIPSE, _firstChild, _lastChild, _branchSet); } } public static class CompositeArbitraryScopeInstruction extends CompositeInstruction{ - protected CompositeArbitraryScopeInstruction(MethodModel method, Instruction _firstChild, Instruction _lastChild, - BranchSet _branchSet) { + CompositeArbitraryScopeInstruction(MethodModel method, Instruction _firstChild, Instruction _lastChild, + BranchSet _branchSet) { super(method, ByteCode.COMPOSITE_ARBITRARY_SCOPE, _firstChild, _lastChild, _branchSet); } } public static abstract class OperatorInstruction extends Instruction{ - protected OperatorInstruction(MethodModel _methodPoolEntry, ByteCode code, ByteReader reader, boolean _wide) { + OperatorInstruction(MethodModel _methodPoolEntry, ByteCode code, ByteReader reader, boolean _wide) { super(_methodPoolEntry, code, reader, _wide); } @@ -950,7 +929,7 @@ public static abstract class BinaryOperator extends OperatorInstruction implemen return (getLastChild()); } - protected BinaryOperator(MethodModel _methodPoolEntry, ByteCode code, ByteReader reader, boolean _wide) { + BinaryOperator(MethodModel _methodPoolEntry, ByteCode code, ByteReader reader, boolean _wide) { super(_methodPoolEntry, code, reader, _wide); } } @@ -960,23 +939,23 @@ public static abstract class UnaryOperator extends OperatorInstruction implement return (getFirstChild()); } - protected UnaryOperator(MethodModel _methodPoolEntry, ByteCode code, ByteReader reader, boolean _wide) { + UnaryOperator(MethodModel _methodPoolEntry, ByteCode code, ByteReader reader, boolean _wide) { super(_methodPoolEntry, code, reader, _wide); } } public static abstract class CastOperator extends UnaryOperator{ - protected CastOperator(MethodModel _methodPoolEntry, ByteCode code, ByteReader reader, boolean _wide) { + CastOperator(MethodModel _methodPoolEntry, ByteCode code, ByteReader reader, boolean _wide) { super(_methodPoolEntry, code, reader, _wide); } } public static abstract class Branch extends Instruction{ - protected int offset; + int offset; - protected boolean breakOrContinue; + boolean breakOrContinue; - protected Instruction target; + Instruction target; public int getAbsolute() { return (getThisPC() + getOffset()); @@ -986,11 +965,11 @@ private int getOffset() { return (offset); } - public Branch(MethodModel _methodPoolEntry, ByteCode _byteCode, ByteReader _byteReader, boolean _wide) { + Branch(MethodModel _methodPoolEntry, ByteCode _byteCode, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, _byteCode, _byteReader, _wide); } - public Branch(MethodModel _methodPoolEntry, ByteCode _byteCode, Instruction _target) { + Branch(MethodModel _methodPoolEntry, ByteCode _byteCode, Instruction _target) { super(_methodPoolEntry, _byteCode, -1); setTarget(_target); } @@ -1017,7 +996,7 @@ public boolean isReverseConditional() { return (isConditional() && isReverse()); } - public boolean isForwardConditional() { + boolean isForwardConditional() { return (isConditional() && isForward()); } @@ -1061,7 +1040,7 @@ public void retarget(Instruction _newTarget) { public static abstract class ConditionalBranch extends Branch{ private BranchSet branchSet; - public ConditionalBranch(MethodModel _methodPoolEntry, ByteCode _byteCode, ByteReader _byteReader, boolean _wide) { + ConditionalBranch(MethodModel _methodPoolEntry, ByteCode _byteCode, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, _byteCode, _byteReader, _wide); } @@ -1118,17 +1097,17 @@ public ConditionalBranch findEndOfConditionalBranchSet(Instruction _extent) { } public static abstract class UnconditionalBranch extends Branch{ - public UnconditionalBranch(MethodModel _methodPoolEntry, ByteCode _byteCode, ByteReader _byteReader, boolean _wide) { + UnconditionalBranch(MethodModel _methodPoolEntry, ByteCode _byteCode, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, _byteCode, _byteReader, _wide); } - public UnconditionalBranch(MethodModel _methodPoolEntry, ByteCode _byteCode, Instruction _target) { + UnconditionalBranch(MethodModel _methodPoolEntry, ByteCode _byteCode, Instruction _target) { super(_methodPoolEntry, _byteCode, _target); } } public static abstract class IfUnary extends ConditionalBranch16 implements Unary{ - public IfUnary(MethodModel _methodPoolEntry, ByteCode _byteCode, ByteReader _byteReader, boolean _wide) { + IfUnary(MethodModel _methodPoolEntry, ByteCode _byteCode, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, _byteCode, _byteReader, _wide); } @@ -1138,7 +1117,7 @@ public IfUnary(MethodModel _methodPoolEntry, ByteCode _byteCode, ByteReader _byt } public static abstract class If extends ConditionalBranch16 implements Binary{ - public If(MethodModel _methodPoolEntry, ByteCode _byteCode, ByteReader _byteReader, boolean _wide) { + If(MethodModel _methodPoolEntry, ByteCode _byteCode, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, _byteCode, _byteReader, _wide); } @@ -1152,7 +1131,7 @@ public If(MethodModel _methodPoolEntry, ByteCode _byteCode, ByteReader _byteRead } public static abstract class ConditionalBranch16 extends ConditionalBranch implements HasOperator{ - public ConditionalBranch16(MethodModel _methodPoolEntry, ByteCode _byteCode, ByteReader _byteReader, boolean _wide) { + ConditionalBranch16(MethodModel _methodPoolEntry, ByteCode _byteCode, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, _byteCode, _byteReader, _wide); offset = _byteReader.s2(); } @@ -1162,22 +1141,22 @@ public ConditionalBranch16(MethodModel _methodPoolEntry, ByteCode _byteCode, Byt } } - public static abstract class UnconditionalBranch16 extends UnconditionalBranch{ - public UnconditionalBranch16(MethodModel _methodPoolEntry, ByteCode _byteCode, ByteReader _byteReader, boolean _wide) { + static abstract class UnconditionalBranch16 extends UnconditionalBranch{ + UnconditionalBranch16(MethodModel _methodPoolEntry, ByteCode _byteCode, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, _byteCode, _byteReader, _wide); offset = _byteReader.s2(); } } - public static abstract class Branch32 extends UnconditionalBranch{ - public Branch32(MethodModel _methodPoolEntry, ByteCode _byteCode, ByteReader _byteReader, boolean _wide) { + static abstract class Branch32 extends UnconditionalBranch{ + Branch32(MethodModel _methodPoolEntry, ByteCode _byteCode, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, _byteCode, _byteReader, _wide); offset = _byteReader.s4(); } } public static abstract class ArrayAccess extends Instruction{ - public ArrayAccess(MethodModel _methodPoolEntry, ByteCode _byteCode, ByteReader _byteReader, boolean _wide) { + ArrayAccess(MethodModel _methodPoolEntry, ByteCode _byteCode, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, _byteCode, _byteReader, _wide); } @@ -1191,13 +1170,13 @@ public Instruction getArrayIndex() { } public static abstract class AccessArrayElement extends ArrayAccess{ - protected AccessArrayElement(MethodModel _methodPoolEntry, ByteCode _byteCode, ByteReader _byteReader, boolean _wide) { + AccessArrayElement(MethodModel _methodPoolEntry, ByteCode _byteCode, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, _byteCode, _byteReader, _wide); } } public static class I_AALOAD extends AccessArrayElement{ - public I_AALOAD(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + I_AALOAD(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.AALOAD, _byteReader, _wide); } @@ -1211,13 +1190,13 @@ public Instruction getValue() { return (getFirstChild().getNextExpr().getNextExpr()); } - protected AssignToArrayElement(MethodModel _methodPoolEntry, ByteCode _byteCode, ByteReader _byteReader, boolean _wide) { + AssignToArrayElement(MethodModel _methodPoolEntry, ByteCode _byteCode, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, _byteCode, _byteReader, _wide); } } - public static class I_AASTORE extends AssignToArrayElement{ - public I_AASTORE(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + static class I_AASTORE extends AssignToArrayElement{ + I_AASTORE(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.AASTORE, _byteReader, _wide); } @@ -1227,7 +1206,7 @@ public I_AASTORE(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _ } public static class I_ACONST_NULL extends Instruction implements Constant{ - public I_ACONST_NULL(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + I_ACONST_NULL(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.ACONST_NULL, _byteReader, _wide); } @@ -1241,8 +1220,8 @@ public I_ACONST_NULL(MethodModel _methodPoolEntry, ByteReader _byteReader, boole } public static abstract class LocalVariableConstIndexAccessor extends IndexConst implements AccessLocalVariable{ - public LocalVariableConstIndexAccessor(MethodModel methodPoolEntry, ByteCode byteCode, ByteReader byteReader, boolean _wide, - int index) { + LocalVariableConstIndexAccessor(MethodModel methodPoolEntry, ByteCode byteCode, ByteReader byteReader, boolean _wide, + int index) { super(methodPoolEntry, byteCode, byteReader, _wide, index); } @@ -1255,9 +1234,9 @@ public LocalVariableConstIndexAccessor(MethodModel methodPoolEntry, ByteCode byt } } - public static abstract class LocalVariableConstIndexLoad extends LocalVariableConstIndexAccessor{ - public LocalVariableConstIndexLoad(MethodModel methodPoolEntry, ByteCode byteCode, ByteReader byteReader, boolean _wide, - int index) { + static abstract class LocalVariableConstIndexLoad extends LocalVariableConstIndexAccessor{ + LocalVariableConstIndexLoad(MethodModel methodPoolEntry, ByteCode byteCode, ByteReader byteReader, boolean _wide, + int index) { super(methodPoolEntry, byteCode, byteReader, _wide, index); } @@ -1268,8 +1247,8 @@ public LocalVariableConstIndexLoad(MethodModel methodPoolEntry, ByteCode byteCod public static abstract class LocalVariableConstIndexStore extends LocalVariableConstIndexAccessor implements AssignToLocalVariable{ - public LocalVariableConstIndexStore(MethodModel methodPoolEntry, ByteCode byteCode, ByteReader byteReader, boolean _wide, - int index) { + LocalVariableConstIndexStore(MethodModel methodPoolEntry, ByteCode byteCode, ByteReader byteReader, boolean _wide, + int index) { super(methodPoolEntry, byteCode, byteReader, _wide, index); } @@ -1285,7 +1264,7 @@ public LocalVariableConstIndexStore(MethodModel methodPoolEntry, ByteCode byteCo } public static abstract class LocalVariableIndex08Accessor extends Index08 implements AccessLocalVariable{ - public LocalVariableIndex08Accessor(MethodModel methodPoolEntry, ByteCode byteCode, ByteReader byteReader, boolean _wide) { + LocalVariableIndex08Accessor(MethodModel methodPoolEntry, ByteCode byteCode, ByteReader byteReader, boolean _wide) { super(methodPoolEntry, byteCode, byteReader, _wide); } @@ -1298,8 +1277,8 @@ public LocalVariableIndex08Accessor(MethodModel methodPoolEntry, ByteCode byteCo } } - public static abstract class LocalVariableIndex08Load extends LocalVariableIndex08Accessor{ - public LocalVariableIndex08Load(MethodModel methodPoolEntry, ByteCode byteCode, ByteReader byteReader, boolean _wide) { + static abstract class LocalVariableIndex08Load extends LocalVariableIndex08Accessor{ + LocalVariableIndex08Load(MethodModel methodPoolEntry, ByteCode byteCode, ByteReader byteReader, boolean _wide) { super(methodPoolEntry, byteCode, byteReader, _wide); } @@ -1309,7 +1288,7 @@ public LocalVariableIndex08Load(MethodModel methodPoolEntry, ByteCode byteCode, } public static abstract class LocalVariableIndex08Store extends LocalVariableIndex08Accessor implements AssignToLocalVariable{ - public LocalVariableIndex08Store(MethodModel methodPoolEntry, ByteCode byteCode, ByteReader byteReader, boolean _wide) { + LocalVariableIndex08Store(MethodModel methodPoolEntry, ByteCode byteCode, ByteReader byteReader, boolean _wide) { super(methodPoolEntry, byteCode, byteReader, _wide); } @@ -1325,38 +1304,38 @@ public LocalVariableIndex08Store(MethodModel methodPoolEntry, ByteCode byteCode, } } - public static class I_ALOAD extends LocalVariableIndex08Load{ - public I_ALOAD(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + static class I_ALOAD extends LocalVariableIndex08Load{ + I_ALOAD(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.ALOAD, _byteReader, _wide); } } public static class I_ALOAD_0 extends LocalVariableConstIndexLoad{ - public I_ALOAD_0(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + I_ALOAD_0(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.ALOAD_0, _byteReader, _wide, 0); } } - public static class I_ALOAD_1 extends LocalVariableConstIndexLoad{ - public I_ALOAD_1(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + static class I_ALOAD_1 extends LocalVariableConstIndexLoad{ + I_ALOAD_1(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.ALOAD_1, _byteReader, _wide, 1); } } - public static class I_ALOAD_2 extends LocalVariableConstIndexLoad{ - public I_ALOAD_2(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + static class I_ALOAD_2 extends LocalVariableConstIndexLoad{ + I_ALOAD_2(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.ALOAD_2, _byteReader, _wide, 2); } } - public static class I_ALOAD_3 extends LocalVariableConstIndexLoad{ - public I_ALOAD_3(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + static class I_ALOAD_3 extends LocalVariableConstIndexLoad{ + I_ALOAD_3(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.ALOAD_3, _byteReader, _wide, 3); } } - public static class I_ANEWARRAY extends Index16 implements New{ - public I_ANEWARRAY(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + static class I_ANEWARRAY extends Index16 implements New{ + I_ANEWARRAY(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.ANEWARRAY, _byteReader, _wide); } @@ -1366,7 +1345,7 @@ public I_ANEWARRAY(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean } public static class I_ARETURN extends Return{ - public I_ARETURN(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + I_ARETURN(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.ARETURN, _byteReader, _wide); } @@ -1376,7 +1355,7 @@ public I_ARETURN(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _ } public static class I_ARRAYLENGTH extends Instruction{ - public I_ARRAYLENGTH(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + I_ARRAYLENGTH(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.ARRAYLENGTH, _byteReader, _wide); } @@ -1385,38 +1364,38 @@ public I_ARRAYLENGTH(MethodModel _methodPoolEntry, ByteReader _byteReader, boole } } - public static class I_ASTORE extends LocalVariableIndex08Store{ - public I_ASTORE(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + static class I_ASTORE extends LocalVariableIndex08Store{ + I_ASTORE(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.ASTORE, _byteReader, _wide); } } - public static class I_ASTORE_0 extends LocalVariableConstIndexStore{ - public I_ASTORE_0(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + static class I_ASTORE_0 extends LocalVariableConstIndexStore{ + I_ASTORE_0(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.ASTORE_0, _byteReader, _wide, 0); } } - public static class I_ASTORE_1 extends LocalVariableConstIndexStore{ - public I_ASTORE_1(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + static class I_ASTORE_1 extends LocalVariableConstIndexStore{ + I_ASTORE_1(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.ASTORE_1, _byteReader, _wide, 1); } } - public static class I_ASTORE_2 extends LocalVariableConstIndexStore{ - public I_ASTORE_2(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + static class I_ASTORE_2 extends LocalVariableConstIndexStore{ + I_ASTORE_2(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.ASTORE_2, _byteReader, _wide, 2); } } - public static class I_ASTORE_3 extends LocalVariableConstIndexStore{ - public I_ASTORE_3(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + static class I_ASTORE_3 extends LocalVariableConstIndexStore{ + I_ASTORE_3(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.ASTORE_3, _byteReader, _wide, 3); } } public static class I_ATHROW extends Instruction{ - public I_ATHROW(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + I_ATHROW(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.ATHROW, _byteReader, _wide); } @@ -1425,8 +1404,8 @@ public I_ATHROW(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _w } } - public static class I_BALOAD extends AccessArrayElement{ - public I_BALOAD(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + static class I_BALOAD extends AccessArrayElement{ + I_BALOAD(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.BALOAD, _byteReader, _wide); } @@ -1436,7 +1415,7 @@ public I_BALOAD(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _w } public static class I_BASTORE extends AssignToArrayElement{ - public I_BASTORE(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + I_BASTORE(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.BASTORE, _byteReader, _wide); } @@ -1446,7 +1425,7 @@ public I_BASTORE(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _ } public static class I_BIPUSH extends ImmediateConstant{ - public I_BIPUSH(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + I_BIPUSH(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.BIPUSH, _byteReader, _wide); value = _byteReader.u1(); } @@ -1464,8 +1443,8 @@ public I_BIPUSH(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _w } } - public static class I_CALOAD extends AccessArrayElement{ - public I_CALOAD(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + static class I_CALOAD extends AccessArrayElement{ + I_CALOAD(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.CALOAD, _byteReader, _wide); } @@ -1475,7 +1454,7 @@ public I_CALOAD(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _w } public static class I_CASTORE extends AssignToArrayElement{ - public I_CASTORE(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + I_CASTORE(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.CASTORE, _byteReader, _wide); } @@ -1484,8 +1463,8 @@ public I_CASTORE(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _ } } - public static class I_CHECKCAST extends Index16{ - public I_CHECKCAST(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + static class I_CHECKCAST extends Index16{ + I_CHECKCAST(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.CHECKCAST, _byteReader, _wide); } @@ -1494,8 +1473,8 @@ public I_CHECKCAST(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean } } - public static class I_D2F extends CastOperator{ - public I_D2F(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + static class I_D2F extends CastOperator{ + I_D2F(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.D2F, _byteReader, _wide); } @@ -1504,8 +1483,8 @@ public I_D2F(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide } } - public static class I_D2I extends CastOperator{ - public I_D2I(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + static class I_D2I extends CastOperator{ + I_D2I(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.D2I, _byteReader, _wide); } @@ -1514,8 +1493,8 @@ public I_D2I(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide } } - public static class I_D2L extends CastOperator{ - public I_D2L(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + static class I_D2L extends CastOperator{ + I_D2L(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.D2L, _byteReader, _wide); } @@ -1524,8 +1503,8 @@ public I_D2L(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide } } - public static class I_DADD extends BinaryOperator{ - public I_DADD(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + static class I_DADD extends BinaryOperator{ + I_DADD(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.DADD, _byteReader, _wide); } @@ -1534,8 +1513,8 @@ public I_DADD(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wid } } - public static class I_DALOAD extends AccessArrayElement{ - public I_DALOAD(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + static class I_DALOAD extends AccessArrayElement{ + I_DALOAD(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.DALOAD, _byteReader, _wide); } @@ -1544,8 +1523,8 @@ public I_DALOAD(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _w } } - public static class I_DASTORE extends AssignToArrayElement{ - public I_DASTORE(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + static class I_DASTORE extends AssignToArrayElement{ + I_DASTORE(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.DASTORE, _byteReader, _wide); } @@ -1554,8 +1533,8 @@ public I_DASTORE(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _ } } - public static class I_DCMPG extends Instruction{ - public I_DCMPG(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + static class I_DCMPG extends Instruction{ + I_DCMPG(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.DCMPG, _byteReader, _wide); } @@ -1564,8 +1543,8 @@ public I_DCMPG(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wi } } - public static class I_DCMPL extends Instruction{ - public I_DCMPL(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + static class I_DCMPL extends Instruction{ + I_DCMPL(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.DCMPL, _byteReader, _wide); } @@ -1577,8 +1556,8 @@ public I_DCMPL(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wi public static abstract class BytecodeEncodedConstant extends Instruction implements Constant{ private final T value; - public BytecodeEncodedConstant(MethodModel _methodPoolEntry, ByteCode _byteCode, ByteReader _byteReader, boolean _wide, - T _value) { + BytecodeEncodedConstant(MethodModel _methodPoolEntry, ByteCode _byteCode, ByteReader _byteReader, boolean _wide, + T _value) { super(_methodPoolEntry, _byteCode, _byteReader, _wide); value = _value; } @@ -1589,9 +1568,9 @@ public BytecodeEncodedConstant(MethodModel _methodPoolEntry, ByteCode _byteCode, } public static abstract class ImmediateConstant extends Instruction implements Constant{ - protected T value; + T value; - public ImmediateConstant(MethodModel _methodPoolEntry, ByteCode _byteCode, ByteReader _byteReader, boolean _wide) { + ImmediateConstant(MethodModel _methodPoolEntry, ByteCode _byteCode, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, _byteCode, _byteReader, _wide); } @@ -1600,8 +1579,8 @@ public ImmediateConstant(MethodModel _methodPoolEntry, ByteCode _byteCode, ByteR } } - public static class I_DCONST_0 extends BytecodeEncodedConstant{ - public I_DCONST_0(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + static class I_DCONST_0 extends BytecodeEncodedConstant{ + I_DCONST_0(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.DCONST_0, _byteReader, _wide, 0.0); } @@ -1610,8 +1589,8 @@ public I_DCONST_0(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean } } - public static class I_DCONST_1 extends BytecodeEncodedConstant{ - public I_DCONST_1(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + static class I_DCONST_1 extends BytecodeEncodedConstant{ + I_DCONST_1(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.DCONST_1, _byteReader, _wide, 1.0); } @@ -1620,8 +1599,8 @@ public I_DCONST_1(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean } } - public static class I_DDIV extends BinaryOperator{ - public I_DDIV(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + static class I_DDIV extends BinaryOperator{ + I_DDIV(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.DDIV, _byteReader, _wide); } @@ -1630,38 +1609,38 @@ public I_DDIV(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wid } } - public static class I_DLOAD extends LocalVariableIndex08Load{ - public I_DLOAD(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + static class I_DLOAD extends LocalVariableIndex08Load{ + I_DLOAD(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.DLOAD, _byteReader, _wide); } } - public static class I_DLOAD_0 extends LocalVariableConstIndexLoad{ - public I_DLOAD_0(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + static class I_DLOAD_0 extends LocalVariableConstIndexLoad{ + I_DLOAD_0(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.DLOAD_0, _byteReader, _wide, 0); } } - public static class I_DLOAD_1 extends LocalVariableConstIndexLoad{ - public I_DLOAD_1(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + static class I_DLOAD_1 extends LocalVariableConstIndexLoad{ + I_DLOAD_1(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.DLOAD_1, _byteReader, _wide, 1); } } - public static class I_DLOAD_2 extends LocalVariableConstIndexLoad{ - public I_DLOAD_2(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + static class I_DLOAD_2 extends LocalVariableConstIndexLoad{ + I_DLOAD_2(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.DLOAD_2, _byteReader, _wide, 2); } } - public static class I_DLOAD_3 extends LocalVariableConstIndexLoad{ - public I_DLOAD_3(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + static class I_DLOAD_3 extends LocalVariableConstIndexLoad{ + I_DLOAD_3(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.DLOAD_3, _byteReader, _wide, 3); } } - public static class I_DMUL extends BinaryOperator{ - public I_DMUL(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + static class I_DMUL extends BinaryOperator{ + I_DMUL(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.DMUL, _byteReader, _wide); } @@ -1670,8 +1649,8 @@ public I_DMUL(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wid } } - public static class I_DNEG extends UnaryOperator{ - public I_DNEG(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + static class I_DNEG extends UnaryOperator{ + I_DNEG(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.DNEG, _byteReader, _wide); } @@ -1680,8 +1659,8 @@ public I_DNEG(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wid } } - public static class I_DREM extends BinaryOperator{ - public I_DREM(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + static class I_DREM extends BinaryOperator{ + I_DREM(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.DREM, _byteReader, _wide); } @@ -1690,8 +1669,8 @@ public I_DREM(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wid } } - public static class I_DRETURN extends Return{ - public I_DRETURN(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + static class I_DRETURN extends Return{ + I_DRETURN(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.DRETURN, _byteReader, _wide); } @@ -1700,38 +1679,38 @@ public I_DRETURN(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _ } } - public static class I_DSTORE extends LocalVariableIndex08Store{ - public I_DSTORE(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + static class I_DSTORE extends LocalVariableIndex08Store{ + I_DSTORE(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.DSTORE, _byteReader, _wide); } } - public static class I_DSTORE_0 extends LocalVariableConstIndexStore{ - public I_DSTORE_0(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + static class I_DSTORE_0 extends LocalVariableConstIndexStore{ + I_DSTORE_0(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.DSTORE_0, _byteReader, _wide, 0); } } - public static class I_DSTORE_1 extends LocalVariableConstIndexStore{ - public I_DSTORE_1(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + static class I_DSTORE_1 extends LocalVariableConstIndexStore{ + I_DSTORE_1(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.DSTORE_1, _byteReader, _wide, 1); } } - public static class I_DSTORE_2 extends LocalVariableConstIndexStore{ - public I_DSTORE_2(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + static class I_DSTORE_2 extends LocalVariableConstIndexStore{ + I_DSTORE_2(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.DSTORE_2, _byteReader, _wide, 2); } } - public static class I_DSTORE_3 extends LocalVariableConstIndexStore{ - public I_DSTORE_3(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + static class I_DSTORE_3 extends LocalVariableConstIndexStore{ + I_DSTORE_3(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.DSTORE_3, _byteReader, _wide, 3); } } - public static class I_DSUB extends BinaryOperator{ - public I_DSUB(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + static class I_DSUB extends BinaryOperator{ + I_DSUB(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.DSUB, _byteReader, _wide); } @@ -1741,13 +1720,13 @@ public I_DSUB(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wid } public static abstract class DUP extends Instruction{ - public DUP(MethodModel _methodPoolEntry, ByteCode _byteCode, ByteReader _byteReader, boolean _wide) { + DUP(MethodModel _methodPoolEntry, ByteCode _byteCode, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, _byteCode, _byteReader, _wide); } } public static class I_DUP extends DUP{ - public I_DUP(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + I_DUP(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.DUP, _byteReader, _wide); } @@ -1757,7 +1736,7 @@ public I_DUP(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide } public static class I_DUP_X1 extends DUP{ - public I_DUP_X1(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + I_DUP_X1(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.DUP_X1, _byteReader, _wide); } @@ -1767,7 +1746,7 @@ public I_DUP_X1(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _w } public static class I_DUP_X2 extends DUP{ - public I_DUP_X2(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + I_DUP_X2(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.DUP_X2, _byteReader, _wide); } @@ -1777,7 +1756,7 @@ public I_DUP_X2(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _w } public static class I_DUP2 extends DUP{ - public I_DUP2(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + I_DUP2(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.DUP2, _byteReader, _wide); } @@ -1786,8 +1765,8 @@ public I_DUP2(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wid } } - public static class I_DUP2_X1 extends DUP{ - public I_DUP2_X1(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + static class I_DUP2_X1 extends DUP{ + I_DUP2_X1(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.DUP2_X1, _byteReader, _wide); } @@ -1796,8 +1775,8 @@ public I_DUP2_X1(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _ } } - public static class I_DUP2_X2 extends DUP{ - public I_DUP2_X2(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + static class I_DUP2_X2 extends DUP{ + I_DUP2_X2(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.DUP_X2, _byteReader, _wide); } @@ -1806,8 +1785,8 @@ public I_DUP2_X2(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _ } } - public static class I_F2D extends CastOperator{ - public I_F2D(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + static class I_F2D extends CastOperator{ + I_F2D(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.F2D, _byteReader, _wide); } @@ -1816,8 +1795,8 @@ public I_F2D(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide } } - public static class I_F2I extends CastOperator{ - public I_F2I(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + static class I_F2I extends CastOperator{ + I_F2I(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.F2I, _byteReader, _wide); } @@ -1826,8 +1805,8 @@ public I_F2I(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide } } - public static class I_F2L extends CastOperator{ - public I_F2L(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + static class I_F2L extends CastOperator{ + I_F2L(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.F2L, _byteReader, _wide); } @@ -1836,8 +1815,8 @@ public I_F2L(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide } } - public static class I_FADD extends BinaryOperator{ - public I_FADD(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + static class I_FADD extends BinaryOperator{ + I_FADD(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.FADD, _byteReader, _wide); } @@ -1846,8 +1825,8 @@ public I_FADD(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wid } } - public static class I_FALOAD extends AccessArrayElement{ - public I_FALOAD(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + static class I_FALOAD extends AccessArrayElement{ + I_FALOAD(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.FALOAD, _byteReader, _wide); } @@ -1856,8 +1835,8 @@ public I_FALOAD(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _w } } - public static class I_FASTORE extends AssignToArrayElement{ - public I_FASTORE(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + static class I_FASTORE extends AssignToArrayElement{ + I_FASTORE(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.FASTORE, _byteReader, _wide); } @@ -1866,8 +1845,8 @@ public I_FASTORE(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _ } } - public static class I_FCMPG extends BinaryOperator{ - public I_FCMPG(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + static class I_FCMPG extends BinaryOperator{ + I_FCMPG(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.FCMPG, _byteReader, _wide); } @@ -1876,8 +1855,8 @@ public I_FCMPG(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wi } } - public static class I_FCMPL extends BinaryOperator{ - public I_FCMPL(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + static class I_FCMPL extends BinaryOperator{ + I_FCMPL(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.FCMPL, _byteReader, _wide); } @@ -1886,8 +1865,8 @@ public I_FCMPL(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wi } } - public static class I_FCONST_0 extends BytecodeEncodedConstant{ - public I_FCONST_0(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + static class I_FCONST_0 extends BytecodeEncodedConstant{ + I_FCONST_0(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.FCONST_0, _byteReader, _wide, 0f); } @@ -1896,8 +1875,8 @@ public I_FCONST_0(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean } } - public static class I_FCONST_1 extends BytecodeEncodedConstant{ - public I_FCONST_1(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + static class I_FCONST_1 extends BytecodeEncodedConstant{ + I_FCONST_1(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.FCONST_1, _byteReader, _wide, 1f); } @@ -1906,8 +1885,8 @@ public I_FCONST_1(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean } } - public static class I_FCONST_2 extends BytecodeEncodedConstant{ - public I_FCONST_2(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + static class I_FCONST_2 extends BytecodeEncodedConstant{ + I_FCONST_2(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.FCONST_2, _byteReader, _wide, 2f); } @@ -1916,8 +1895,8 @@ public I_FCONST_2(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean } } - public static class I_FDIV extends BinaryOperator{ - public I_FDIV(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + static class I_FDIV extends BinaryOperator{ + I_FDIV(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.FDIV, _byteReader, _wide); } @@ -1926,38 +1905,38 @@ public I_FDIV(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wid } } - public static class I_FLOAD extends LocalVariableIndex08Load{ - public I_FLOAD(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + static class I_FLOAD extends LocalVariableIndex08Load{ + I_FLOAD(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.FLOAD, _byteReader, _wide); } } - public static class I_FLOAD_0 extends LocalVariableConstIndexLoad{ - public I_FLOAD_0(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + static class I_FLOAD_0 extends LocalVariableConstIndexLoad{ + I_FLOAD_0(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.FLOAD_0, _byteReader, _wide, 0); } } - public static class I_FLOAD_1 extends LocalVariableConstIndexLoad{ - public I_FLOAD_1(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + static class I_FLOAD_1 extends LocalVariableConstIndexLoad{ + I_FLOAD_1(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.FLOAD_1, _byteReader, _wide, 1); } } - public static class I_FLOAD_2 extends LocalVariableConstIndexLoad{ - public I_FLOAD_2(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + static class I_FLOAD_2 extends LocalVariableConstIndexLoad{ + I_FLOAD_2(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.FLOAD_2, _byteReader, _wide, 2); } } - public static class I_FLOAD_3 extends LocalVariableConstIndexLoad{ - public I_FLOAD_3(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + static class I_FLOAD_3 extends LocalVariableConstIndexLoad{ + I_FLOAD_3(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.FLOAD_3, _byteReader, _wide, 3); } } - public static class I_FMUL extends BinaryOperator{ - public I_FMUL(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + static class I_FMUL extends BinaryOperator{ + I_FMUL(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.FMUL, _byteReader, _wide); } @@ -1966,8 +1945,8 @@ public I_FMUL(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wid } } - public static class I_FNEG extends UnaryOperator{ - public I_FNEG(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + static class I_FNEG extends UnaryOperator{ + I_FNEG(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.FNEG, _byteReader, _wide); } @@ -1976,8 +1955,8 @@ public I_FNEG(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wid } } - public static class I_FREM extends BinaryOperator{ - public I_FREM(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + static class I_FREM extends BinaryOperator{ + I_FREM(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.FREM, _byteReader, _wide); } @@ -1986,8 +1965,8 @@ public I_FREM(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wid } } - public static class I_FRETURN extends Return{ - public I_FRETURN(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + static class I_FRETURN extends Return{ + I_FRETURN(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.FRETURN, _byteReader, _wide); } @@ -1996,38 +1975,38 @@ public I_FRETURN(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _ } } - public static class I_FSTORE extends LocalVariableIndex08Store{ - public I_FSTORE(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + static class I_FSTORE extends LocalVariableIndex08Store{ + I_FSTORE(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.FSTORE, _byteReader, _wide); } } - public static class I_FSTORE_0 extends LocalVariableConstIndexStore{ - public I_FSTORE_0(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + static class I_FSTORE_0 extends LocalVariableConstIndexStore{ + I_FSTORE_0(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.FSTORE_0, _byteReader, _wide, 0); } } - public static class I_FSTORE_1 extends LocalVariableConstIndexStore{ - public I_FSTORE_1(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + static class I_FSTORE_1 extends LocalVariableConstIndexStore{ + I_FSTORE_1(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.FSTORE_1, _byteReader, _wide, 1); } } - public static class I_FSTORE_2 extends LocalVariableConstIndexStore{ + static class I_FSTORE_2 extends LocalVariableConstIndexStore{ I_FSTORE_2(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.FSTORE_2, _byteReader, _wide, 2); } } - public static class I_FSTORE_3 extends LocalVariableConstIndexStore{ - public I_FSTORE_3(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + static class I_FSTORE_3 extends LocalVariableConstIndexStore{ + I_FSTORE_3(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.FSTORE_3, _byteReader, _wide, 3); } } - public static class I_FSUB extends BinaryOperator{ - public I_FSUB(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + static class I_FSUB extends BinaryOperator{ + I_FSUB(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.FSUB, _byteReader, _wide); } @@ -2038,7 +2017,7 @@ public I_FSUB(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wid public static class I_GETFIELD extends Index16 implements AccessInstanceField{ - public I_GETFIELD(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + I_GETFIELD(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.GETFIELD, _byteReader, _wide); } @@ -2068,7 +2047,7 @@ public I_GETFIELD(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean } public static class I_GETSTATIC extends Index16 implements AccessField{ - public I_GETSTATIC(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + I_GETSTATIC(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.GETSTATIC, _byteReader, _wide); } @@ -2093,8 +2072,8 @@ public I_GETSTATIC(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean } } - public static class I_GOTO extends UnconditionalBranch16{ - public I_GOTO(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + static class I_GOTO extends UnconditionalBranch16{ + I_GOTO(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.GOTO, _byteReader, _wide); } @@ -2103,8 +2082,8 @@ public I_GOTO(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wid } } - public static class I_GOTO_W extends Branch32{ - public I_GOTO_W(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + static class I_GOTO_W extends Branch32{ + I_GOTO_W(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.GOTO_W, _byteReader, _wide); } @@ -2113,8 +2092,8 @@ public I_GOTO_W(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _w } } - public static class I_I2B extends CastOperator{ - public I_I2B(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + static class I_I2B extends CastOperator{ + I_I2B(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.I2B, _byteReader, _wide); } @@ -2123,8 +2102,8 @@ public I_I2B(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide } } - public static class I_I2C extends CastOperator{ - public I_I2C(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + static class I_I2C extends CastOperator{ + I_I2C(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.I2C, _byteReader, _wide); } @@ -2133,8 +2112,8 @@ public I_I2C(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide } } - public static class I_I2D extends CastOperator{ - public I_I2D(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + static class I_I2D extends CastOperator{ + I_I2D(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.I2D, _byteReader, _wide); } @@ -2143,8 +2122,8 @@ public I_I2D(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide } } - public static class I_I2F extends CastOperator{ - public I_I2F(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + static class I_I2F extends CastOperator{ + I_I2F(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.I2F, _byteReader, _wide); } @@ -2153,8 +2132,8 @@ public I_I2F(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide } } - public static class I_I2L extends CastOperator{ - public I_I2L(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + static class I_I2L extends CastOperator{ + I_I2L(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.I2L, _byteReader, _wide); } @@ -2163,8 +2142,8 @@ public I_I2L(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide } } - public static class I_I2S extends CastOperator{ - public I_I2S(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + static class I_I2S extends CastOperator{ + I_I2S(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.I2S, _byteReader, _wide); } @@ -2174,7 +2153,7 @@ public I_I2S(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide } public static class I_IADD extends BinaryOperator{ - public I_IADD(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + I_IADD(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.IADD, _byteReader, _wide); } @@ -2183,8 +2162,8 @@ public I_IADD(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wid } } - public static class I_IALOAD extends AccessArrayElement{ - public I_IALOAD(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + static class I_IALOAD extends AccessArrayElement{ + I_IALOAD(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.IALOAD, _byteReader, _wide); } @@ -2193,8 +2172,8 @@ public I_IALOAD(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _w } } - public static class I_IAND extends BinaryOperator{ - public I_IAND(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + static class I_IAND extends BinaryOperator{ + I_IAND(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.IAND, _byteReader, _wide); } @@ -2203,8 +2182,8 @@ public I_IAND(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wid } } - public static class I_IASTORE extends AssignToArrayElement{ - public I_IASTORE(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + static class I_IASTORE extends AssignToArrayElement{ + I_IASTORE(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.IASTORE, _byteReader, _wide); } @@ -2213,8 +2192,8 @@ public I_IASTORE(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _ } } - public static class I_ICONST_0 extends BytecodeEncodedConstant{ - public I_ICONST_0(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + static class I_ICONST_0 extends BytecodeEncodedConstant{ + I_ICONST_0(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.ICONST_0, _byteReader, _wide, 0); } @@ -2224,7 +2203,7 @@ public I_ICONST_0(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean } public static class I_ICONST_1 extends BytecodeEncodedConstant{ - public I_ICONST_1(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + I_ICONST_1(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.ICONST_1, _byteReader, _wide, 1); } @@ -2233,8 +2212,8 @@ public I_ICONST_1(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean } } - public static class I_ICONST_2 extends BytecodeEncodedConstant{ - public I_ICONST_2(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + static class I_ICONST_2 extends BytecodeEncodedConstant{ + I_ICONST_2(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.ICONST_2, _byteReader, _wide, 2); } @@ -2243,8 +2222,8 @@ public I_ICONST_2(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean } } - public static class I_ICONST_3 extends BytecodeEncodedConstant{ - public I_ICONST_3(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + static class I_ICONST_3 extends BytecodeEncodedConstant{ + I_ICONST_3(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.ICONST_3, _byteReader, _wide, 3); } @@ -2253,8 +2232,8 @@ public I_ICONST_3(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean } } - public static class I_ICONST_4 extends BytecodeEncodedConstant{ - public I_ICONST_4(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + static class I_ICONST_4 extends BytecodeEncodedConstant{ + I_ICONST_4(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.ICONST_4, _byteReader, _wide, 4); } @@ -2263,8 +2242,8 @@ public I_ICONST_4(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean } } - public static class I_ICONST_5 extends BytecodeEncodedConstant{ - public I_ICONST_5(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + static class I_ICONST_5 extends BytecodeEncodedConstant{ + I_ICONST_5(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.ICONST_5, _byteReader, _wide, 5); } @@ -2273,8 +2252,8 @@ public I_ICONST_5(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean } } - public static class I_ICONST_M1 extends BytecodeEncodedConstant{ - public I_ICONST_M1(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + static class I_ICONST_M1 extends BytecodeEncodedConstant{ + I_ICONST_M1(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.ICONST_M1, _byteReader, _wide, -1); } @@ -2283,8 +2262,8 @@ public I_ICONST_M1(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean } } - public static class I_IDIV extends BinaryOperator{ - public I_IDIV(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + static class I_IDIV extends BinaryOperator{ + I_IDIV(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.IDIV, _byteReader, _wide); } @@ -2293,8 +2272,8 @@ public I_IDIV(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wid } } - public static class I_IF_ACMPEQ extends If{ - public I_IF_ACMPEQ(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + static class I_IF_ACMPEQ extends If{ + I_IF_ACMPEQ(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.IF_ACMPEQ, _byteReader, _wide); } @@ -2303,8 +2282,8 @@ public I_IF_ACMPEQ(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean } } - public static class I_IF_ACMPNE extends If{ - public I_IF_ACMPNE(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + static class I_IF_ACMPNE extends If{ + I_IF_ACMPNE(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.IF_ACMPNE, _byteReader, _wide); } @@ -2313,8 +2292,8 @@ public I_IF_ACMPNE(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean } } - public static class I_IF_ICMPEQ extends If{ - public I_IF_ICMPEQ(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + static class I_IF_ICMPEQ extends If{ + I_IF_ICMPEQ(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.IF_ICMPEQ, _byteReader, _wide); } @@ -2323,8 +2302,8 @@ public I_IF_ICMPEQ(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean } } - public static class I_IF_ICMPGE extends If{ - public I_IF_ICMPGE(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + static class I_IF_ICMPGE extends If{ + I_IF_ICMPGE(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.IF_ICMPGE, _byteReader, _wide); } @@ -2333,8 +2312,8 @@ public I_IF_ICMPGE(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean } } - public static class I_IF_ICMPGT extends If{ - public I_IF_ICMPGT(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + static class I_IF_ICMPGT extends If{ + I_IF_ICMPGT(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.IF_ICMPGT, _byteReader, _wide); } @@ -2343,8 +2322,8 @@ public I_IF_ICMPGT(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean } } - public static class I_IF_ICMPLE extends If{ - public I_IF_ICMPLE(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + static class I_IF_ICMPLE extends If{ + I_IF_ICMPLE(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.IF_ICMPLE, _byteReader, _wide); } @@ -2353,8 +2332,8 @@ public I_IF_ICMPLE(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean } } - public static class I_IF_ICMPLT extends If{ - public I_IF_ICMPLT(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + static class I_IF_ICMPLT extends If{ + I_IF_ICMPLT(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.IF_ICMPLT, _byteReader, _wide); } @@ -2363,8 +2342,8 @@ public I_IF_ICMPLT(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean } } - public static class I_IF_ICMPNE extends If{ - public I_IF_ICMPNE(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + static class I_IF_ICMPNE extends If{ + I_IF_ICMPNE(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.IF_ICMPNE, _byteReader, _wide); } @@ -2373,8 +2352,8 @@ public I_IF_ICMPNE(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean } } - public static class I_IFEQ extends IfUnary{ - public I_IFEQ(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + static class I_IFEQ extends IfUnary{ + I_IFEQ(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.IFEQ, _byteReader, _wide); } @@ -2383,8 +2362,8 @@ public I_IFEQ(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wid } } - public static class I_IFGE extends IfUnary{ - public I_IFGE(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + static class I_IFGE extends IfUnary{ + I_IFGE(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.IFGE, _byteReader, _wide); } @@ -2393,8 +2372,8 @@ public I_IFGE(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wid } } - public static class I_IFGT extends IfUnary{ - public I_IFGT(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + static class I_IFGT extends IfUnary{ + I_IFGT(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.IFGT, _byteReader, _wide); } @@ -2403,8 +2382,8 @@ public I_IFGT(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wid } } - public static class I_IFLE extends IfUnary{ - public I_IFLE(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + static class I_IFLE extends IfUnary{ + I_IFLE(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.IFLE, _byteReader, _wide); } @@ -2413,8 +2392,8 @@ public I_IFLE(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wid } } - public static class I_IFLT extends IfUnary{ - public I_IFLT(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + static class I_IFLT extends IfUnary{ + I_IFLT(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.IFLT, _byteReader, _wide); } @@ -2423,8 +2402,8 @@ public I_IFLT(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wid } } - public static class I_IFNE extends IfUnary{ - public I_IFNE(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + static class I_IFNE extends IfUnary{ + I_IFNE(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.IFNE, _byteReader, _wide); } @@ -2434,7 +2413,7 @@ public I_IFNE(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wid } public static class I_IFNONNULL extends ConditionalBranch16{ - public I_IFNONNULL(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + I_IFNONNULL(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.IFNONNULL, _byteReader, _wide); } @@ -2444,7 +2423,7 @@ public I_IFNONNULL(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean } public static class I_IFNULL extends ConditionalBranch16{ - public I_IFNULL(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + I_IFNULL(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.IFNULL, _byteReader, _wide); } @@ -2454,11 +2433,11 @@ public I_IFNULL(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _w } public static class I_IINC extends Index08{ - private int delta; + private final int delta; private final boolean wide; - public I_IINC(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + I_IINC(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.IINC, _byteReader, _wide); wide = _wide; if (wide) { @@ -2504,38 +2483,38 @@ public int getAdjust() { } } - public static class I_ILOAD extends LocalVariableIndex08Load{ - public I_ILOAD(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + static class I_ILOAD extends LocalVariableIndex08Load{ + I_ILOAD(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.ILOAD, _byteReader, _wide); } } - public static class I_ILOAD_0 extends LocalVariableConstIndexLoad{ - public I_ILOAD_0(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + static class I_ILOAD_0 extends LocalVariableConstIndexLoad{ + I_ILOAD_0(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.ILOAD_0, _byteReader, _wide, 0); } } - public static class I_ILOAD_1 extends LocalVariableConstIndexLoad{ - public I_ILOAD_1(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + static class I_ILOAD_1 extends LocalVariableConstIndexLoad{ + I_ILOAD_1(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.ILOAD_1, _byteReader, _wide, 1); } } - public static class I_ILOAD_2 extends LocalVariableConstIndexLoad{ - public I_ILOAD_2(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + static class I_ILOAD_2 extends LocalVariableConstIndexLoad{ + I_ILOAD_2(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.ILOAD_2, _byteReader, _wide, 2); } } - public static class I_ILOAD_3 extends LocalVariableConstIndexLoad{ - public I_ILOAD_3(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + static class I_ILOAD_3 extends LocalVariableConstIndexLoad{ + I_ILOAD_3(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.ILOAD_3, _byteReader, _wide, 3); } } - public static class I_IMUL extends BinaryOperator{ - public I_IMUL(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + static class I_IMUL extends BinaryOperator{ + I_IMUL(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.IMUL, _byteReader, _wide); } @@ -2544,8 +2523,8 @@ public I_IMUL(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wid } } - public static class I_INEG extends UnaryOperator{ - public I_INEG(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + static class I_INEG extends UnaryOperator{ + I_INEG(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.INEG, _byteReader, _wide); } @@ -2554,8 +2533,8 @@ public I_INEG(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wid } } - public static class I_INSTANCEOF extends Index16{ - public I_INSTANCEOF(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + static class I_INSTANCEOF extends Index16{ + I_INSTANCEOF(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.INSTANCEOF, _byteReader, _wide); } @@ -2567,7 +2546,7 @@ public I_INSTANCEOF(MethodModel _methodPoolEntry, ByteReader _byteReader, boolea public static class I_INVOKEINTERFACE extends Index16 implements InterfaceConstantPoolMethodIndexAccessor{ private final int args; - public I_INVOKEINTERFACE(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + I_INVOKEINTERFACE(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.INVOKEINTERFACE, _byteReader, _wide); args = _byteReader.u1(); @SuppressWarnings("unused") final int zeroByte = _byteReader.u1(); @@ -2618,7 +2597,7 @@ public I_INVOKEINTERFACE(MethodModel _methodPoolEntry, ByteReader _byteReader, b public static class I_INVOKEDYNAMIC extends Index16 implements InterfaceConstantPoolMethodIndexAccessor{ private final int args; - public I_INVOKEDYNAMIC(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + I_INVOKEDYNAMIC(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.INVOKEDYNAMIC, _byteReader, _wide); args = _byteReader.u1(); @SuppressWarnings("unused") final int zeroByte = _byteReader.u1(); @@ -2666,7 +2645,7 @@ public I_INVOKEDYNAMIC(MethodModel _methodPoolEntry, ByteReader _byteReader, boo public static class I_INVOKESPECIAL extends Index16 implements VirtualMethodCall{ - public I_INVOKESPECIAL(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + I_INVOKESPECIAL(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.INVOKESPECIAL, _byteReader, _wide); } @@ -2708,7 +2687,7 @@ public I_INVOKESPECIAL(MethodModel _methodPoolEntry, ByteReader _byteReader, boo public static class I_INVOKESTATIC extends Index16 implements MethodCall{ - public I_INVOKESTATIC(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + I_INVOKESTATIC(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.INVOKESTATIC, _byteReader, _wide); } @@ -2746,7 +2725,7 @@ public I_INVOKESTATIC(MethodModel _methodPoolEntry, ByteReader _byteReader, bool public static class I_INVOKEVIRTUAL extends Index16 implements VirtualMethodCall{ - public I_INVOKEVIRTUAL(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + I_INVOKEVIRTUAL(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.INVOKEVIRTUAL, _byteReader, _wide); } @@ -2787,8 +2766,8 @@ public I_INVOKEVIRTUAL(MethodModel _methodPoolEntry, ByteReader _byteReader, boo } } - public static class I_IOR extends BinaryOperator{ - public I_IOR(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + static class I_IOR extends BinaryOperator{ + I_IOR(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.IOR, _byteReader, _wide); } @@ -2797,8 +2776,8 @@ public I_IOR(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide } } - public static class I_IREM extends BinaryOperator{ - public I_IREM(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + static class I_IREM extends BinaryOperator{ + I_IREM(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.IREM, _byteReader, _wide); } @@ -2807,8 +2786,8 @@ public I_IREM(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wid } } - public static class I_IRETURN extends Return{ - public I_IRETURN(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + static class I_IRETURN extends Return{ + I_IRETURN(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.IRETURN, _byteReader, _wide); } @@ -2817,8 +2796,8 @@ public I_IRETURN(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _ } } - public static class I_ISHL extends BinaryOperator{ - public I_ISHL(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + static class I_ISHL extends BinaryOperator{ + I_ISHL(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.ISHL, _byteReader, _wide); } @@ -2827,8 +2806,8 @@ public I_ISHL(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wid } } - public static class I_ISHR extends BinaryOperator{ - public I_ISHR(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + static class I_ISHR extends BinaryOperator{ + I_ISHR(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.ISHR, _byteReader, _wide); } @@ -2837,38 +2816,38 @@ public I_ISHR(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wid } } - public static class I_ISTORE extends LocalVariableIndex08Store{ - public I_ISTORE(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + static class I_ISTORE extends LocalVariableIndex08Store{ + I_ISTORE(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.ISTORE, _byteReader, _wide); } } - public static class I_ISTORE_0 extends LocalVariableConstIndexStore{ - public I_ISTORE_0(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + static class I_ISTORE_0 extends LocalVariableConstIndexStore{ + I_ISTORE_0(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.ISTORE_0, _byteReader, _wide, 0); } } - public static class I_ISTORE_1 extends LocalVariableConstIndexStore{ - public I_ISTORE_1(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + static class I_ISTORE_1 extends LocalVariableConstIndexStore{ + I_ISTORE_1(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.ISTORE_1, _byteReader, _wide, 1); } } - public static class I_ISTORE_2 extends LocalVariableConstIndexStore{ - public I_ISTORE_2(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + static class I_ISTORE_2 extends LocalVariableConstIndexStore{ + I_ISTORE_2(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.ISTORE_2, _byteReader, _wide, 2); } } - public static class I_ISTORE_3 extends LocalVariableConstIndexStore{ - public I_ISTORE_3(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + static class I_ISTORE_3 extends LocalVariableConstIndexStore{ + I_ISTORE_3(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.ISTORE_3, _byteReader, _wide, 3); } } public static class I_ISUB extends BinaryOperator{ - public I_ISUB(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + I_ISUB(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.ISUB, _byteReader, _wide); } @@ -2878,7 +2857,7 @@ public I_ISUB(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wid } public static class I_IUSHR extends BinaryOperator{ - public I_IUSHR(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + I_IUSHR(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.IUSHR, _byteReader, _wide); } @@ -2887,8 +2866,8 @@ public I_IUSHR(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wi } } - public static class I_IXOR extends BinaryOperator{ - public I_IXOR(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + static class I_IXOR extends BinaryOperator{ + I_IXOR(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.IXOR, _byteReader, _wide); } @@ -2897,8 +2876,8 @@ public I_IXOR(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wid } } - public static class I_JSR extends UnconditionalBranch16{ - public I_JSR(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + static class I_JSR extends UnconditionalBranch16{ + I_JSR(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.JSR, _byteReader, _wide); } @@ -2907,8 +2886,8 @@ public I_JSR(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide } } - public static class I_JSR_W extends Branch32{ - public I_JSR_W(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + static class I_JSR_W extends Branch32{ + I_JSR_W(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.JSR_W, _byteReader, _wide); } @@ -2917,8 +2896,8 @@ public I_JSR_W(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wi } } - public static class I_L2D extends CastOperator{ - public I_L2D(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + static class I_L2D extends CastOperator{ + I_L2D(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.L2D, _byteReader, _wide); } @@ -2927,8 +2906,8 @@ public I_L2D(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide } } - public static class I_L2F extends CastOperator{ - public I_L2F(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + static class I_L2F extends CastOperator{ + I_L2F(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.L2F, _byteReader, _wide); } @@ -2937,8 +2916,8 @@ public I_L2F(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide } } - public static class I_L2I extends CastOperator{ - public I_L2I(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + static class I_L2I extends CastOperator{ + I_L2I(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.L2I, _byteReader, _wide); } @@ -2947,8 +2926,8 @@ public I_L2I(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide } } - public static class I_LADD extends BinaryOperator{ - public I_LADD(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + static class I_LADD extends BinaryOperator{ + I_LADD(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.LADD, _byteReader, _wide); } @@ -2957,8 +2936,8 @@ public I_LADD(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wid } } - public static class I_LALOAD extends AccessArrayElement{ - public I_LALOAD(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + static class I_LALOAD extends AccessArrayElement{ + I_LALOAD(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.LALOAD, _byteReader, _wide); } @@ -2967,8 +2946,8 @@ public I_LALOAD(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _w } } - public static class I_LAND extends BinaryOperator{ - public I_LAND(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + static class I_LAND extends BinaryOperator{ + I_LAND(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.LAND, _byteReader, _wide); } @@ -2977,8 +2956,8 @@ public I_LAND(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wid } } - public static class I_LASTORE extends AssignToArrayElement{ - public I_LASTORE(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + static class I_LASTORE extends AssignToArrayElement{ + I_LASTORE(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.LASTORE, _byteReader, _wide); } @@ -2987,8 +2966,8 @@ public I_LASTORE(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _ } } - public static class I_LCMP extends BinaryOperator{ - public I_LCMP(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + static class I_LCMP extends BinaryOperator{ + I_LCMP(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.LCMP, _byteReader, _wide); } @@ -2997,8 +2976,8 @@ public I_LCMP(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wid } } - public static class I_LCONST_0 extends BytecodeEncodedConstant{ - public I_LCONST_0(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + static class I_LCONST_0 extends BytecodeEncodedConstant{ + I_LCONST_0(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.LCONST_0, _byteReader, _wide, 0L); } @@ -3007,8 +2986,8 @@ public I_LCONST_0(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean } } - public static class I_LCONST_1 extends BytecodeEncodedConstant{ - public I_LCONST_1(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + static class I_LCONST_1 extends BytecodeEncodedConstant{ + I_LCONST_1(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.LCONST_1, _byteReader, _wide, 1L); } @@ -3018,7 +2997,7 @@ public I_LCONST_1(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean } public static class I_LDC extends Index08 implements ConstantPoolEntryConstant{ - public I_LDC(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + I_LDC(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.LDC, _byteReader, _wide); } @@ -3041,7 +3020,7 @@ public I_LDC(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide } public static class I_LDC_W extends Index16 implements ConstantPoolEntryConstant{ - public I_LDC_W(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + I_LDC_W(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.LDC_W, _byteReader, _wide); } @@ -3064,7 +3043,7 @@ public I_LDC_W(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wi } public static class I_LDC2_W extends Index16 implements ConstantPoolEntryConstant{ - public I_LDC2_W(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + I_LDC2_W(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.LDC2_W, _byteReader, _wide); } @@ -3085,8 +3064,8 @@ public I_LDC2_W(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _w } } - public static class I_LDIV extends BinaryOperator{ - public I_LDIV(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + static class I_LDIV extends BinaryOperator{ + I_LDIV(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.LDIV, _byteReader, _wide); } @@ -3095,38 +3074,38 @@ public I_LDIV(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wid } } - public static class I_LLOAD extends LocalVariableIndex08Load{ - public I_LLOAD(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + static class I_LLOAD extends LocalVariableIndex08Load{ + I_LLOAD(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.LLOAD, _byteReader, _wide); } } - public static class I_LLOAD_0 extends LocalVariableConstIndexLoad{ - public I_LLOAD_0(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + static class I_LLOAD_0 extends LocalVariableConstIndexLoad{ + I_LLOAD_0(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.LLOAD_0, _byteReader, _wide, 0); } } - public static class I_LLOAD_1 extends LocalVariableConstIndexLoad{ - public I_LLOAD_1(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + static class I_LLOAD_1 extends LocalVariableConstIndexLoad{ + I_LLOAD_1(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.LLOAD_1, _byteReader, _wide, 1); } } - public static class I_LLOAD_2 extends LocalVariableConstIndexLoad{ - public I_LLOAD_2(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + static class I_LLOAD_2 extends LocalVariableConstIndexLoad{ + I_LLOAD_2(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.LLOAD_2, _byteReader, _wide, 2); } } - public static class I_LLOAD_3 extends LocalVariableConstIndexLoad{ - public I_LLOAD_3(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + static class I_LLOAD_3 extends LocalVariableConstIndexLoad{ + I_LLOAD_3(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.LLOAD_3, _byteReader, _wide, 3); } } - public static class I_LMUL extends BinaryOperator{ - public I_LMUL(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + static class I_LMUL extends BinaryOperator{ + I_LMUL(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.LMUL, _byteReader, _wide); } @@ -3135,8 +3114,8 @@ public I_LMUL(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wid } } - public static class I_LNEG extends UnaryOperator{ - public I_LNEG(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + static class I_LNEG extends UnaryOperator{ + I_LNEG(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.LNEG, _byteReader, _wide); } @@ -3150,7 +3129,7 @@ public static class I_LOOKUPSWITCH extends Switch{ private final int npairs; - public I_LOOKUPSWITCH(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + I_LOOKUPSWITCH(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.LOOKUPSWITCH, _byteReader, _wide); final int operandStart = _byteReader.getOffset(); final int padLength = ((operandStart % 4) == 0) ? 0 : 4 - (operandStart % 4); @@ -3178,8 +3157,8 @@ public int getNpairs() { } } - public static class I_LOR extends BinaryOperator{ - public I_LOR(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + static class I_LOR extends BinaryOperator{ + I_LOR(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.LOR, _byteReader, _wide); } @@ -3188,8 +3167,8 @@ public I_LOR(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide } } - public static class I_LREM extends BinaryOperator{ - public I_LREM(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + static class I_LREM extends BinaryOperator{ + I_LREM(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.LREM, _byteReader, _wide); } @@ -3199,8 +3178,8 @@ public I_LREM(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wid } } - public static class I_LRETURN extends Return{ - public I_LRETURN(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + static class I_LRETURN extends Return{ + I_LRETURN(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.LRETURN, _byteReader, _wide); } @@ -3209,8 +3188,8 @@ public I_LRETURN(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _ } } - public static class I_LSHL extends BinaryOperator{ - public I_LSHL(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + static class I_LSHL extends BinaryOperator{ + I_LSHL(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.LSHL, _byteReader, _wide); } @@ -3219,8 +3198,8 @@ public I_LSHL(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wid } } - public static class I_LSHR extends BinaryOperator{ - public I_LSHR(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + static class I_LSHR extends BinaryOperator{ + I_LSHR(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.LSHR, _byteReader, _wide); } @@ -3229,38 +3208,38 @@ public I_LSHR(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wid } } - public static class I_LSTORE extends LocalVariableIndex08Store{ - public I_LSTORE(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + static class I_LSTORE extends LocalVariableIndex08Store{ + I_LSTORE(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.LSTORE, _byteReader, _wide); } } - public static class I_LSTORE_0 extends LocalVariableConstIndexStore{ - public I_LSTORE_0(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + static class I_LSTORE_0 extends LocalVariableConstIndexStore{ + I_LSTORE_0(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.LSTORE_0, _byteReader, _wide, 0); } } - public static class I_LSTORE_1 extends LocalVariableConstIndexStore{ - public I_LSTORE_1(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + static class I_LSTORE_1 extends LocalVariableConstIndexStore{ + I_LSTORE_1(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.LSTORE_1, _byteReader, _wide, 1); } } - public static class I_LSTORE_2 extends LocalVariableConstIndexStore{ - public I_LSTORE_2(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + static class I_LSTORE_2 extends LocalVariableConstIndexStore{ + I_LSTORE_2(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.LSTORE_2, _byteReader, _wide, 2); } } - public static class I_LSTORE_3 extends LocalVariableConstIndexStore{ - public I_LSTORE_3(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + static class I_LSTORE_3 extends LocalVariableConstIndexStore{ + I_LSTORE_3(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.LSTORE_3, _byteReader, _wide, 3); } } - public static class I_LSUB extends BinaryOperator{ - public I_LSUB(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + static class I_LSUB extends BinaryOperator{ + I_LSUB(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.LSUB, _byteReader, _wide); } @@ -3270,7 +3249,7 @@ public I_LSUB(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wid } public static class I_LUSHR extends BinaryOperator{ - public I_LUSHR(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + I_LUSHR(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.LUSHR, _byteReader, _wide); } @@ -3279,8 +3258,8 @@ public I_LUSHR(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wi } } - public static class I_LXOR extends BinaryOperator{ - public I_LXOR(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + static class I_LXOR extends BinaryOperator{ + I_LXOR(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.LXOR, _byteReader, _wide); } @@ -3290,7 +3269,7 @@ public I_LXOR(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wid } public static class I_MONITORENTER extends Instruction{ - public I_MONITORENTER(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + I_MONITORENTER(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.MONITORENTER, _byteReader, _wide); } @@ -3300,7 +3279,7 @@ public I_MONITORENTER(MethodModel _methodPoolEntry, ByteReader _byteReader, bool } public static class I_MONITOREXIT extends Instruction{ - public I_MONITOREXIT(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + I_MONITOREXIT(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.MONITOREXIT, _byteReader, _wide); } @@ -3312,7 +3291,7 @@ public I_MONITOREXIT(MethodModel _methodPoolEntry, ByteReader _byteReader, boole public static class I_MULTIANEWARRAY extends Index16 implements New{ private final int dimensions; - public I_MULTIANEWARRAY(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + I_MULTIANEWARRAY(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.MULTIANEWARRAY, _byteReader, _wide); dimensions = _byteReader.u1(); } @@ -3326,8 +3305,8 @@ public int getDimensions() { } } - public static class I_NEW extends Index16 implements New{ - public I_NEW(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + static class I_NEW extends Index16 implements New{ + I_NEW(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.NEW, _byteReader, _wide); } @@ -3339,7 +3318,7 @@ public I_NEW(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide public static class I_NEWARRAY extends Instruction implements New{ private final int type; - public I_NEWARRAY(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + I_NEWARRAY(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.NEWARRAY, _byteReader, _wide); type = _byteReader.u1(); } @@ -3353,7 +3332,7 @@ public int getType() { } } - public static class I_NOP extends Instruction{ + static class I_NOP extends Instruction{ public I_NOP(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.NOP, _byteReader, _wide); } @@ -3364,7 +3343,7 @@ public I_NOP(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide } public static class I_POP extends Instruction{ - public I_POP(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + I_POP(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.POP, _byteReader, _wide); } @@ -3373,8 +3352,8 @@ public I_POP(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide } } - public static class I_POP2 extends Instruction{ - public I_POP2(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + static class I_POP2 extends Instruction{ + I_POP2(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.POP2, _byteReader, _wide); } @@ -3384,7 +3363,7 @@ public I_POP2(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wid } public static class I_PUTFIELD extends Index16 implements AssignToInstanceField{ - public I_PUTFIELD(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + I_PUTFIELD(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.PUTFIELD, _byteReader, _wide); } @@ -3418,7 +3397,7 @@ public I_PUTFIELD(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean } public static class I_PUTSTATIC extends Index16 implements AssignToField{ - public I_PUTSTATIC(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + I_PUTSTATIC(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.PUTSTATIC, _byteReader, _wide); } @@ -3448,7 +3427,7 @@ public I_PUTSTATIC(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean } public static class I_RET extends Index08 implements AssignToLocalVariable{ - public I_RET(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + I_RET(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.RET, _byteReader, _wide); } @@ -3474,8 +3453,8 @@ public I_RET(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide //} } - public static class I_RETURN extends Return{ - public I_RETURN(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + static class I_RETURN extends Return{ + I_RETURN(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.RETURN, _byteReader, _wide); } @@ -3484,8 +3463,8 @@ public I_RETURN(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _w } } - public static class I_SALOAD extends AccessArrayElement{ - public I_SALOAD(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + static class I_SALOAD extends AccessArrayElement{ + I_SALOAD(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.SALOAD, _byteReader, _wide); } @@ -3494,8 +3473,8 @@ public I_SALOAD(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _w } } - public static class I_SASTORE extends AssignToArrayElement{ - public I_SASTORE(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + static class I_SASTORE extends AssignToArrayElement{ + I_SASTORE(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.SASTORE, _byteReader, _wide); } @@ -3504,8 +3483,8 @@ public I_SASTORE(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _ } } - public static class I_SIPUSH extends ImmediateConstant{ - public I_SIPUSH(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + static class I_SIPUSH extends ImmediateConstant{ + I_SIPUSH(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.SIPUSH, _byteReader, _wide); value = _byteReader.u2(); } @@ -3515,8 +3494,8 @@ public I_SIPUSH(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _w } } - public static class I_SWAP extends Instruction{ - public I_SWAP(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + static class I_SWAP extends Instruction{ + I_SWAP(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.SWAP, _byteReader, _wide); } @@ -3530,7 +3509,7 @@ public static class I_TABLESWITCH extends Switch{ private final int low; - public I_TABLESWITCH(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + I_TABLESWITCH(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.TABLESWITCH, _byteReader, _wide); final int operandStart = _byteReader.getOffset(); final int padLength = ((operandStart % 4) == 0) ? 0 : 4 - (operandStart % 4); @@ -3557,8 +3536,8 @@ public int getLow() { } } - public static class I_WIDE extends Instruction{ - private boolean iinc; + static class I_WIDE extends Instruction{ + private final boolean iinc; private int increment; @@ -3566,7 +3545,7 @@ public static class I_WIDE extends Instruction{ private final int wideopcode; - public I_WIDE(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { + I_WIDE(MethodModel _methodPoolEntry, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, ByteCode.WIDE, _byteReader, _wide); wideopcode = _byteReader.u1(); index = _byteReader.u2(); @@ -3599,7 +3578,7 @@ public boolean isiinc() { } } - public static class I_END extends Instruction{ + static class I_END extends Instruction{ public I_END(MethodModel method, int _pc) { super(method, ByteCode.NONE, _pc); } @@ -3609,23 +3588,23 @@ public I_END(MethodModel method, int _pc) { } } - public static abstract class Index extends Instruction{ - protected int index; + static abstract class Index extends Instruction{ + int index; - public Index(MethodModel _methodPoolEntry, ByteCode _byteCode, ByteReader _byteReader, boolean _wide) { + Index(MethodModel _methodPoolEntry, ByteCode _byteCode, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, _byteCode, _byteReader, _wide); } } - public static abstract class IndexConst extends Index{ - public IndexConst(MethodModel _methodPoolEntry, ByteCode _byteCode, ByteReader _byteReader, boolean _wide, int _index) { + static abstract class IndexConst extends Index{ + IndexConst(MethodModel _methodPoolEntry, ByteCode _byteCode, ByteReader _byteReader, boolean _wide, int _index) { super(_methodPoolEntry, _byteCode, _byteReader, _wide); index = _index; } } - public static abstract class Index08 extends Index{ - public Index08(MethodModel _methodPoolEntry, ByteCode _byteCode, ByteReader _byteReader, boolean _wide) { + static abstract class Index08 extends Index{ + Index08(MethodModel _methodPoolEntry, ByteCode _byteCode, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, _byteCode, _byteReader, _wide); if (_wide) { index = _byteReader.u2(); @@ -3635,27 +3614,27 @@ public Index08(MethodModel _methodPoolEntry, ByteCode _byteCode, ByteReader _byt } } - public static abstract class Index16 extends Index{ - public Index16(MethodModel _methodPoolEntry, ByteCode _byteCode, ByteReader _byteReader, boolean _wide) { + static abstract class Index16 extends Index{ + Index16(MethodModel _methodPoolEntry, ByteCode _byteCode, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, _byteCode, _byteReader, _wide); index = _byteReader.u2(); } } public static abstract class Return extends Instruction{ - public Return(MethodModel _methodPoolEntry, ByteCode _byteCode, ByteReader _byteReader, boolean _wide) { + Return(MethodModel _methodPoolEntry, ByteCode _byteCode, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, _byteCode, _byteReader, _wide); } } - public static abstract class Switch extends Branch{ - public Switch(MethodModel _methodPoolEntry, ByteCode _code, ByteReader _byteReader, boolean _wide) { + static abstract class Switch extends Branch{ + Switch(MethodModel _methodPoolEntry, ByteCode _code, ByteReader _byteReader, boolean _wide) { super(_methodPoolEntry, _code, _byteReader, _wide); } - protected int[] offsets; + int[] offsets; - protected Instruction[] targets; + Instruction[] targets; public Instruction getTarget(int _index) { return (targets[_index]); @@ -3694,25 +3673,25 @@ public interface VirtualMethodCall extends MethodCall{ Instruction getInstanceReference(); } - public interface InterfaceConstantPoolMethodIndexAccessor{ - public int getConstantPoolInterfaceMethodIndex(); + interface InterfaceConstantPoolMethodIndexAccessor{ + int getConstantPoolInterfaceMethodIndex(); - public ConstantPool.InterfaceMethodEntry getConstantPoolInterfaceMethodEntry(); + ConstantPool.InterfaceMethodEntry getConstantPoolInterfaceMethodEntry(); - public Instruction getInstanceReference(); + Instruction getInstanceReference(); - public int getArgs(); + int getArgs(); - public Instruction getArg(int _arg); + Instruction getArg(int _arg); } - public static interface New{ + public interface New{ } public interface FieldReference{ - public int getConstantPoolFieldIndex(); + int getConstantPoolFieldIndex(); - public FieldEntry getConstantPoolFieldEntry(); + FieldEntry getConstantPoolFieldEntry(); } public interface AccessField extends FieldReference{ @@ -3749,23 +3728,24 @@ public interface Constant { T getValue(); } - @SuppressWarnings("unchecked") public interface ConstantPoolEntryConstant extends Constant{ + @SuppressWarnings("unchecked") + interface ConstantPoolEntryConstant extends Constant{ int getConstantPoolIndex(); ConstantPool.Entry getConstantPoolEntry(); - }; + } - public interface HasOperator{ + interface HasOperator{ Operator getOperator(); } - public interface Binary extends HasOperator{ + interface Binary extends HasOperator{ Instruction getLhs(); Instruction getRhs(); } - public interface Unary extends HasOperator{ + interface Unary extends HasOperator{ Instruction getUnary(); } diff --git a/src/main/java/com/aparapi/internal/instruction/InstructionTransformer.java b/src/main/java/com/aparapi/internal/instruction/InstructionTransformer.java index b6d35993..367d39e1 100644 --- a/src/main/java/com/aparapi/internal/instruction/InstructionTransformer.java +++ b/src/main/java/com/aparapi/internal/instruction/InstructionTransformer.java @@ -58,7 +58,7 @@ public abstract class InstructionTransformer{ public abstract Instruction transform(final ExpressionList _expressionList, final Instruction i); - public InstructionTransformer(String _description) { + protected InstructionTransformer(String _description) { description = _description; } diff --git a/src/main/java/com/aparapi/internal/jni/ConfigJNI.java b/src/main/java/com/aparapi/internal/jni/ConfigJNI.java index 78050b0b..904939a0 100644 --- a/src/main/java/com/aparapi/internal/jni/ConfigJNI.java +++ b/src/main/java/com/aparapi/internal/jni/ConfigJNI.java @@ -34,7 +34,8 @@ public abstract class ConfigJNI{ * Usage -Dcom.codegen.enableProfiling={true|false} * */ - @UsedByJNICode public static final boolean enableProfiling = Boolean.getBoolean(propPkgName + ".enableProfiling"); + @UsedByJNICode + protected 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 @@ -42,7 +43,8 @@ public abstract class ConfigJNI{ * Usage -Dcom.codegen.enableProfiling={true|false} * */ - @UsedByJNICode public static final boolean enableProfilingCSV = Boolean.getBoolean(propPkgName + ".enableProfilingCSV"); + @UsedByJNICode + protected static final boolean enableProfilingCSV = Boolean.getBoolean(propPkgName + ".enableProfilingCSV"); /** * Allows the user to request that verbose JNI messages be dumped to stderr. @@ -50,7 +52,8 @@ public abstract class ConfigJNI{ * Usage -Dcom.codegen.enableVerboseJNI={true|false} * */ - @UsedByJNICode public static final boolean enableVerboseJNI = Boolean.getBoolean(propPkgName + ".enableVerboseJNI"); + @UsedByJNICode + protected static final boolean enableVerboseJNI = Boolean.getBoolean(propPkgName + ".enableVerboseJNI"); /** * Allows the user to request tracking of opencl resources. @@ -60,7 +63,8 @@ public abstract class ConfigJNI{ * Usage -Dcom.codegen.enableOpenCLResourceTracking={true|false} * */ - @UsedByJNICode public static final boolean enableVerboseJNIOpenCLResourceTracking = Boolean.getBoolean(propPkgName + @UsedByJNICode + protected static final boolean enableVerboseJNIOpenCLResourceTracking = Boolean.getBoolean(propPkgName + ".enableVerboseJNIOpenCLResourceTracking"); } diff --git a/src/main/java/com/aparapi/internal/jni/KernelRunnerJNI.java b/src/main/java/com/aparapi/internal/jni/KernelRunnerJNI.java index 2ef6a54f..7d107b5e 100644 --- a/src/main/java/com/aparapi/internal/jni/KernelRunnerJNI.java +++ b/src/main/java/com/aparapi/internal/jni/KernelRunnerJNI.java @@ -318,7 +318,7 @@ public abstract class KernelRunnerJNI{ * @param _flags * @return */ - @DocMe protected native synchronized long initJNI(Kernel _kernel, OpenCLDevice _device, int _flags); + @DocMe protected native long initJNI(Kernel _kernel, OpenCLDevice _device, int _flags); protected native int getJNI(long _jniContextHandle, Object _array); @@ -340,5 +340,5 @@ public abstract class KernelRunnerJNI{ protected native String getExtensionsJNI(long _jniContextHandle); - protected native synchronized List getProfileInfoJNI(long _jniContextHandle); + protected native List getProfileInfoJNI(long _jniContextHandle); } diff --git a/src/main/java/com/aparapi/internal/jni/OpenCLJNI.java b/src/main/java/com/aparapi/internal/jni/OpenCLJNI.java index 9b762534..79bf0d39 100644 --- a/src/main/java/com/aparapi/internal/jni/OpenCLJNI.java +++ b/src/main/java/com/aparapi/internal/jni/OpenCLJNI.java @@ -32,7 +32,7 @@ public abstract class OpenCLJNI{ protected native List getPlatforms(); - public OpenCLProgram createProgram(OpenCLDevice context, String openCLSource) + protected OpenCLProgram createProgram(OpenCLDevice context, String openCLSource) { return this.createProgram(context, openCLSource, ""); } diff --git a/src/main/java/com/aparapi/internal/kernel/KernelArg.java b/src/main/java/com/aparapi/internal/kernel/KernelArg.java index 4a7830ae..213b7212 100644 --- a/src/main/java/com/aparapi/internal/kernel/KernelArg.java +++ b/src/main/java/com/aparapi/internal/kernel/KernelArg.java @@ -278,6 +278,6 @@ protected void setDims(int[] dims) { @Override public String toString() { - return Reflection.getSimpleName(field.getType()) + " " + field.getName(); + return Reflection.getSimpleName(field.getType()) + ' ' + field.getName(); } } diff --git a/src/main/java/com/aparapi/internal/kernel/KernelDeviceProfile.java b/src/main/java/com/aparapi/internal/kernel/KernelDeviceProfile.java index c4ca0fb8..42c20dd0 100644 --- a/src/main/java/com/aparapi/internal/kernel/KernelDeviceProfile.java +++ b/src/main/java/com/aparapi/internal/kernel/KernelDeviceProfile.java @@ -15,198 +15,265 @@ */ package com.aparapi.internal.kernel; -import com.aparapi.*; -import com.aparapi.device.*; +import com.aparapi.Config; +import com.aparapi.Kernel; +import com.aparapi.device.Device; -import java.text.*; -import java.util.*; -import java.util.logging.*; +import java.text.DecimalFormat; +import java.text.NumberFormat; +import java.util.Arrays; +import java.util.Collections; +import java.util.Map; +import java.util.WeakHashMap; +import java.util.concurrent.atomic.AtomicLong; +import java.util.concurrent.atomic.AtomicLongArray; +import java.util.logging.Level; +import java.util.logging.Logger; /** * Created by Barney on 02/09/2015. */ public class KernelDeviceProfile { - private static Logger logger = Logger.getLogger(Config.getLoggerName()); - private static final double MILLION = 1000 * 1000; - private static final int TABLE_COLUMN_HEADER_WIDTH = 21; - private static final int TABLE_COLUMN_COUNT_WIDTH = 8; - private static final int TABLE_COLUMN_WIDTH; - private static String tableHeader = null; - private final Class kernel; - private final Device device; - private long[] currentTimes = new long[ProfilingEvent.values().length]; - private long[] accumulatedTimes = new long[ProfilingEvent.values().length]; - private ProfilingEvent lastEvent = null; - private final DecimalFormat format; - private long invocationCount = 0; - - static { - assert ProfilingEvent.START.ordinal() == 0 : "ProfilingEvent.START.ordinal() != 0"; - int max = 0; - for (ProfilingEvent event : ProfilingEvent.values()) { - max = Math.max(max, event.name().length()); - } - TABLE_COLUMN_WIDTH = max + 1; - } - - public KernelDeviceProfile(Class kernel, Device device) { - this.kernel = kernel; - this.device = device; - this.format = (DecimalFormat) DecimalFormat.getNumberInstance(); - format.setMinimumFractionDigits(3); - format.setMaximumFractionDigits(3); - } - - public void onEvent(ProfilingEvent event) { - if (event == ProfilingEvent.START) { - if (lastEvent != null) { - logger.log(Level.SEVERE, "ProfilingEvent.START encountered without ProfilingEvent.EXECUTED"); - } else if (lastEvent == ProfilingEvent.START) { - logger.log(Level.SEVERE, "Duplicate event ProfilingEvent.START"); - } - Arrays.fill(currentTimes, 0L); - ++invocationCount; - } else { - if (lastEvent == null) { - if (event != ProfilingEvent.EXECUTED) { - logger.log(Level.SEVERE, "ProfilingEvent.START was not invoked prior to ProfilingEvent." + event); + private static final Logger logger = Logger.getLogger(Config.getLoggerName()); + private static final double MILLION = 1000 * 1000; + private static final int TABLE_COLUMN_HEADER_WIDTH = 21; + private static final int TABLE_COLUMN_COUNT_WIDTH = 8; + private static final int TABLE_COLUMN_WIDTH; + private static String tableHeader = null; + + private final Class kernel; + private final Device device; + private final DecimalFormat format; + + private final static int NUM_EVENTS = ProfilingEvent.values().length; + + private class Accumulator { + private final long[] currentTimes = new long[NUM_EVENTS]; + private final AtomicLongArray accumulatedTimes = new AtomicLongArray(NUM_EVENTS); + private ProfilingEvent lastEvent = null; + + void onEvent(ProfilingEvent event) { + + //System.out.println(kernel + " " + Thread.currentThread() + " " + event); + + int eo = event.ordinal(); + long[] cur = this.currentTimes; + if (event == ProfilingEvent.START) { + + if (lastEvent != null) { + logger.log(Level.SEVERE, "ProfilingEvent.START encountered without ProfilingEvent.EXECUTED, instead: " + lastEvent); + } + if (lastEvent == ProfilingEvent.START) { + logger.log(Level.SEVERE, "Duplicate event ProfilingEvent.START"); + } + + Arrays.fill(cur, 0L); + + invocationCount.incrementAndGet(); + + } else { + if (lastEvent != null) { + for (int i = lastEvent.ordinal() + 1; i < eo; ++i) { + cur[i] = cur[i - 1]; + } + } else { + if (event != ProfilingEvent.EXECUTED) { + logger.log(Level.SEVERE, "ProfilingEvent.START was not invoked prior to ProfilingEvent." + event); + } + } + } + + cur[eo] = System.nanoTime(); + + if (event == ProfilingEvent.EXECUTED) { + AtomicLongArray accumulatedTimes = this.accumulatedTimes; + for (int i = 1; i < cur.length; ++i) { + long elapsed = cur[i] - cur[i - 1]; + if (elapsed < 0) { + logger.log(Level.SEVERE, "negative elapsed time for event " + event); + break; + } + accumulatedTimes.addAndGet(i, elapsed); + } + } + lastEvent = event; + if (event == ProfilingEvent.EXECUTED) { + lastEvent = null; + } + } + } + + private final Accumulator combined = new Accumulator(); + + private final Map acc = Collections.synchronizedMap( + new WeakHashMap(Runtime.getRuntime().availableProcessors()*2, 0.95f) + ); + + private final AtomicLong invocationCount = new AtomicLong(); + + static { + assert ProfilingEvent.START.ordinal() == 0 : "ProfilingEvent.START.ordinal() != 0"; + int max = 0; + for (ProfilingEvent event : ProfilingEvent.values()) { + max = Math.max(max, event.name().length()); + } + TABLE_COLUMN_WIDTH = max + 1; + } + + public KernelDeviceProfile(Class kernel, Device device) { + this.kernel = kernel; + this.device = device; + this.format = (DecimalFormat) NumberFormat.getNumberInstance(); + format.setMinimumFractionDigits(3); + format.setMaximumFractionDigits(3); + } + + private Accumulator acc() { + Thread t = Thread.currentThread(); + Accumulator a = acc.computeIfAbsent(t, k -> new Accumulator()); + return a; + } + + private void commit() { + synchronized (combined) { + long[] c = combined.currentTimes; + AtomicLongArray a = combined.accumulatedTimes; + for (Accumulator x : this.acc.values()) { + for (int i = 0; i < NUM_EVENTS; i++) { + long[] xc = x.currentTimes; + AtomicLongArray xa = x.accumulatedTimes; + c[i] = Math.max(c[i], xc[i]); + a.addAndGet( i, xa.getAndSet(i, 0) ); + } } - } else { - for (int i = lastEvent.ordinal() + 1; i < event.ordinal(); ++i) { - currentTimes[i] = currentTimes[i - 1]; + } + } + + public void on(ProfilingEvent event) { + acc().onEvent(event); + } + + /** Elapsed time for a single event only, i.e. since the previous stage rather than from the start. */ + private double getLastElapsedTime(int stageOrdinal) { + if (stageOrdinal == ProfilingEvent.START.ordinal()) { + return 0; + } + long[] cc = combined.currentTimes; + return (cc[stageOrdinal] - cc[stageOrdinal - 1]) / MILLION; + } + + /** Elapsed time for all events {@code from} through {@code to}.*/ + public double getLastElapsedTime(ProfilingEvent from, ProfilingEvent to) { + commit(); + return (combined.currentTimes[to.ordinal()] - combined.currentTimes[from.ordinal()]) / MILLION; + } + + /** Elapsed time for a single event only, i.e. since the previous stage rather than from the start, summed over all executions. */ + private double getCumulativeElapsedTime(int stageOrdinal) { + commit(); + return (combined.accumulatedTimes.get(stageOrdinal)) / MILLION; + } + + /** Elapsed time of entire execution, summed over all executions. */ + public double getCumulativeElapsedTimeAll() { + double sum = 0; + commit(); + for (int i = 1; i <= ProfilingEvent.EXECUTED.ordinal(); ++i) { + sum += combined.accumulatedTimes.get(i); + } + return sum; + } + + public static synchronized String getTableHeader() { + if (tableHeader == null) { + int length = ProfilingEvent.values().length; + StringBuilder builder = new StringBuilder(150); + appendRowHeaders(builder, "Device", "Count"); + for (int i = 1; i < length; ++i) { + ProfilingEvent stage = ProfilingEvent.values()[i]; + String heading = stage.name(); + appendCell(builder, heading); } - } - } - currentTimes[event.ordinal()] = System.nanoTime(); - if (event == ProfilingEvent.EXECUTED) { - for (int i = 1; i < currentTimes.length; ++i) { - long elapsed = currentTimes[i] - currentTimes[i - 1]; - if (elapsed < 0) { - logger.log(Level.SEVERE, "negative elapsed time for event " + event); - break; + builder.append(" ").append("Total"); + tableHeader = builder.toString(); + } + return tableHeader; + } + + public String getLastAsTableRow() { + + + commit(); + + StringBuilder builder = new StringBuilder(150); + appendRowHeaders(builder, device.getShortDescription(), String.valueOf(invocationCount.get())); + double total = 0; + for (int i = 1; i < combined.currentTimes.length; ++i) { + double time = getLastElapsedTime(i); + total += time; + String formatted = format.format(time); + appendCell(builder, formatted); + } + builder.append(" ").append(format.format(total)); + return builder.toString(); + } + + public String getCumulativeAsTableRow() { + return internalCumulativeAsTableRow(false); + } + + public String getAverageAsTableRow() { + return internalCumulativeAsTableRow(true); + } + + private String internalCumulativeAsTableRow(boolean mean) { + commit(); + + double total = 0; + double count = mean ? invocationCount.doubleValue() : 1; + StringBuilder builder = new StringBuilder(150); + appendRowHeaders(builder, device.getShortDescription(), String.valueOf(invocationCount.get())); + for (int i = 1; i < combined.currentTimes.length; ++i) { + double time = getCumulativeElapsedTime(i); + if (mean) { + time /= count; } - accumulatedTimes[i] += elapsed; - } - } - lastEvent = event; - if (event == ProfilingEvent.EXECUTED) { - lastEvent = null; - } - } - - /** Elapsed time for a single event only, i.e. since the previous stage rather than from the start. */ - public double getLastElapsedTime(ProfilingEvent stage) { - if (stage == ProfilingEvent.START) { - return 0; - } - return (currentTimes[stage.ordinal()] - currentTimes[stage.ordinal() - 1]) / MILLION; - } - - /** Elapsed time for all events {@code from} through {@code to}.*/ - public double getLastElapsedTime(ProfilingEvent from, ProfilingEvent to) { - return (currentTimes[to.ordinal()] - currentTimes[from.ordinal()]) / MILLION; - } - - /** Elapsed time for a single event only, i.e. since the previous stage rather than from the start, summed over all executions. */ - public double getCumulativeElapsedTime(ProfilingEvent stage) { - return (accumulatedTimes[stage.ordinal()]) / MILLION; - } - - /** Elapsed time of entire execution, summed over all executions. */ - public double getCumulativeElapsedTimeAll() { - double sum = 0; - for (int i = 1; i <= ProfilingEvent.EXECUTED.ordinal(); ++i) { - sum += accumulatedTimes[i]; - } - return sum; - } - - public static synchronized String getTableHeader() { - if (tableHeader == null) { - int length = ProfilingEvent.values().length; - StringBuilder builder = new StringBuilder(150); - appendRowHeaders(builder, "Device", "Count"); - for (int i = 1; i < length; ++i) { - ProfilingEvent stage = ProfilingEvent.values()[i]; - String heading = stage.name(); - appendCell(builder, heading); - } - builder.append(" ").append("Total"); - tableHeader = builder.toString(); - } - return tableHeader; - } - - public String getLastAsTableRow() { - double total = 0; - StringBuilder builder = new StringBuilder(150); - appendRowHeaders(builder, device.getShortDescription(), String.valueOf(invocationCount)); - for (int i = 1; i < currentTimes.length; ++i) { - ProfilingEvent stage = ProfilingEvent.values()[i]; - double time = getLastElapsedTime(stage); - total += time; - String formatted = format.format(time); - appendCell(builder, formatted); - } - builder.append(" ").append(format.format(total)); - return builder.toString(); - } - - public String getCumulativeAsTableRow() { - return internalCumulativeAsTableRow(false); - } - - public String getAverageAsTableRow() { - return internalCumulativeAsTableRow(true); - } - - private String internalCumulativeAsTableRow(boolean mean) { - double total = 0; - double count = mean ? invocationCount : 1; - StringBuilder builder = new StringBuilder(150); - appendRowHeaders(builder, device.getShortDescription(), String.valueOf(invocationCount)); - for (int i = 1; i < currentTimes.length; ++i) { - ProfilingEvent stage = ProfilingEvent.values()[i]; - double time = getCumulativeElapsedTime(stage); - if (mean) { - time /= count; - } - total += time; - String formatted = format.format(time); - appendCell(builder, formatted); - } - builder.append(" ").append(format.format(total)); - return builder.toString(); - } - - private static void appendRowHeaders(StringBuilder builder, String device, String count) { - if (device.length() > TABLE_COLUMN_HEADER_WIDTH - 1) { - device = device.substring(0, TABLE_COLUMN_HEADER_WIDTH - 1); - } - builder.append(device); - int padding = TABLE_COLUMN_HEADER_WIDTH - device.length(); - for (int i = 0; i < padding; ++i) { - builder.append(' '); - } - - builder.append(count); - padding = TABLE_COLUMN_COUNT_WIDTH - count.length(); - for (int i = 0; i < padding; ++i) { - builder.append(' '); - } - } - - private static void appendCell(StringBuilder builder, String cell) { - int padding = TABLE_COLUMN_WIDTH - cell.length(); - for (int paddingIndex = 0; paddingIndex < padding; ++paddingIndex) { - builder.append(' '); - } - builder.append(cell); - } - - @Override - public String toString() { - return "KernelDeviceProfile{" + kernel.toString() + ", " + device.getShortDescription() + "}"; - } + total += time; + String formatted = format.format(time); + appendCell(builder, formatted); + } + builder.append(" ").append(format.format(total)); + return builder.toString(); + } + + private static void appendRowHeaders(StringBuilder builder, String device, String count) { + if (device.length() > TABLE_COLUMN_HEADER_WIDTH - 1) { + device = device.substring(0, TABLE_COLUMN_HEADER_WIDTH - 1); + } + builder.append(device); + int padding = TABLE_COLUMN_HEADER_WIDTH - device.length(); + for (int i = 0; i < padding; ++i) { + builder.append(' '); + } + + builder.append(count); + padding = TABLE_COLUMN_COUNT_WIDTH - count.length(); + for (int i = 0; i < padding; ++i) { + builder.append(' '); + } + } + + private static void appendCell(StringBuilder builder, String cell) { + int padding = TABLE_COLUMN_WIDTH - cell.length(); + for (int paddingIndex = 0; paddingIndex < padding; ++paddingIndex) { + builder.append(' '); + } + builder.append(cell); + } + + @Override + public String toString() { + return "KernelDeviceProfile{" + kernel.toString() + ", " + device.getShortDescription() + '}'; + } } diff --git a/src/main/java/com/aparapi/internal/kernel/KernelManager.java b/src/main/java/com/aparapi/internal/kernel/KernelManager.java index 9bdce715..ef2a4da0 100644 --- a/src/main/java/com/aparapi/internal/kernel/KernelManager.java +++ b/src/main/java/com/aparapi/internal/kernel/KernelManager.java @@ -16,18 +16,15 @@ package com.aparapi.internal.kernel; import java.lang.reflect.Constructor; -import java.util.Arrays; -import java.util.Collections; -import java.util.Comparator; -import java.util.LinkedHashMap; -import java.util.LinkedHashSet; -import java.util.List; +import java.util.*; +import java.util.concurrent.ConcurrentHashMap; import com.aparapi.Config; import com.aparapi.Kernel; import com.aparapi.device.Device; import com.aparapi.device.JavaDevice; import com.aparapi.device.OpenCLDevice; +import com.aparapi.internal.opencl.OpenCLPlatform; import com.aparapi.internal.util.Reflection; /** @@ -35,298 +32,295 @@ */ public class KernelManager { - private static KernelManager INSTANCE = new KernelManager(); - private LinkedHashMap preferences = new LinkedHashMap<>(); - private LinkedHashMap, KernelProfile> profiles = new LinkedHashMap<>(); - private LinkedHashMap, Kernel> sharedInstances = new LinkedHashMap<>(); - - private KernelPreferences defaultPreferences; - - protected KernelManager() { - defaultPreferences = createDefaultPreferences(); - } - - public static KernelManager instance() { - return INSTANCE; - } - - public static void setKernelManager(KernelManager manager) { - INSTANCE = manager; - } - - static { - if (Config.dumpProfilesOnExit) { - Runtime.getRuntime().addShutdownHook(new Thread() { - @Override - public void run() { - StringBuilder builder = new StringBuilder(2048); - instance().reportProfilingSummary(builder); - System.out.println(builder); + private static KernelManager INSTANCE = new KernelManager(); + private final Map preferences = new ConcurrentHashMap<>(); + private final Map, KernelProfile> profiles = new ConcurrentHashMap<>(); + private final Map, Kernel> sharedInstances = new ConcurrentHashMap<>(); + + public final KernelPreferences defaultPreferences; + + protected KernelManager() { + defaultPreferences = createDefaultPreferences(); + } + + public static KernelManager instance() { + return INSTANCE; + } + + public static void setKernelManager(KernelManager manager) { + INSTANCE = manager; + } + + static { + if (Config.dumpProfilesOnExit) { + Runtime.getRuntime().addShutdownHook(new Thread(() -> { + StringBuilder builder = new StringBuilder(2048); + instance().reportProfilingSummary(builder); + System.out.println(builder); + })); + } + } + + /** + * This method returns a shared instance of a given Kernel subclass. The kernelClass needs a no-args constructor, which + * need not be public. + *

+ *

Each new Kernel instance requires a new JNIContext, the creation of which is expensive. There is apparently no simple solution by which a cached JNIContext can be reused + * for all instances of a given Kernel class, since it is intimately connected with resource aquisition and release. In the absence of a context caching solution, it is often + * highly desirable to only ever create one instance of any given Kernel subclass, which this method facilitates.

+ *

+ *

In order to maintain thread saftey when using a shared instance, it is necessary to synchronize on the returned kernel for the duration of the process of setting up, + * executing and extracting the results from that kernel.

+ *

+ *

This method instantiates a Kernel (per Kernel class) via Reflection, and thus can only be used where the Kernel class has a no-args constructor, which need not be public. + * In fact, if a Kernel subclass is designed to be used in conjunction with this method, it is recommended that its only constructor is a private no-args constructor. + *

+ * + * @throws RuntimeException if the class cannot be instantiated + */ + public static T sharedKernelInstance(Class kernelClass) { + return instance().getSharedKernelInstance(kernelClass); + } + + /** + * Append a report to {@code builder} which contains information, per Kernel subclass, on which device is currently being used for the + * kernel class, and which (if any) devices failed to execute a given Kernel. + */ + public void reportDeviceUsage(StringBuilder builder, boolean withProfilingInfo) { + builder.append("Device Usage by Kernel Subclass"); + if (withProfilingInfo) { + builder.append(" (showing mean elapsed times in milliseconds)"); + } + builder.append("\n\n"); + for (PreferencesWrapper wrapper : preferences.values()) { + KernelPreferences preferences = wrapper.getPreferences(); + Class klass = wrapper.getKernelClass(); + KernelProfile profile = withProfilingInfo ? profiles.get(klass) : null; + builder.append(klass.getName()).append(":\n\tusing ").append(preferences.getPreferredDevice(null).getShortDescription()); + Collection failedDevices = preferences.failedDevices; + if (failedDevices.size() > 0) { + builder.append(", failed devices = "); + for (Device failure : failedDevices) { + builder.append(failure.getShortDescription()); + //if (i < failedDevices.size() - 1) { + builder.append(" | "); + //} + } } - }); - } - } - - /** This method returns a shared instance of a given Kernel subclass. The kernelClass needs a no-args constructor, which - * need not be public. - * - *

Each new Kernel instance requires a new JNIContext, the creation of which is expensive. There is apparently no simple solution by which a cached JNIContext can be reused - * for all instances of a given Kernel class, since it is intimately connected with resource aquisition and release. In the absence of a context caching solution, it is often - * highly desirable to only ever create one instance of any given Kernel subclass, which this method facilitates.

- * - *

In order to maintain thread saftey when using a shared instance, it is necessary to synchronize on the returned kernel for the duration of the process of setting up, - * executing and extracting the results from that kernel.

- * - *

This method instantiates a Kernel (per Kernel class) via Reflection, and thus can only be used where the Kernel class has a no-args constructor, which need not be public. - * In fact, if a Kernel subclass is designed to be used in conjunction with this method, it is recommended that its only constructor is a private no-args constructor. - *

- * - * @throws RuntimeException if the class cannot be instantiated - */ - public static T sharedKernelInstance(Class kernelClass) { - return instance().getSharedKernelInstance(kernelClass); - } - - /** Append a report to {@code builder} which contains information, per Kernel subclass, on which device is currently being used for the - * kernel class, and which (if any) devices failed to execute a given Kernel. - */ - public void reportDeviceUsage(StringBuilder builder, boolean withProfilingInfo) { - builder.append("Device Usage by Kernel Subclass"); - if (withProfilingInfo) { - builder.append(" (showing mean elapsed times in milliseconds)"); - } - builder.append("\n\n"); - for (PreferencesWrapper wrapper : preferences.values()) { - KernelPreferences preferences = wrapper.getPreferences(); - Class klass = wrapper.getKernelClass(); - KernelProfile profile = withProfilingInfo ? profiles.get(klass) : null; - builder.append(klass.getName()).append(":\n\tusing ").append(preferences.getPreferredDevice(null).getShortDescription()); - List failedDevices = preferences.getFailedDevices(); - if (failedDevices.size() > 0) { - builder.append(", failed devices = "); - for (int i = 0; i < failedDevices.size(); ++i) { - builder.append(failedDevices.get(i).getShortDescription()); - if (i < failedDevices.size() - 1) { - builder.append(" | "); - } + if (profile != null) { + builder.append('\n'); + int row = 0; + for (KernelDeviceProfile deviceProfile : profile.getDeviceProfiles()) { + if (row == 0) { + builder.append(KernelDeviceProfile.getTableHeader()).append('\n'); + } + builder.append(deviceProfile.getAverageAsTableRow()).append('\n'); + ++row; + } } - } - if (profile != null) { - builder.append("\n"); - int row = 0; - for (KernelDeviceProfile deviceProfile : profile.getDeviceProfiles()) { - if (row == 0) { - builder.append(deviceProfile.getTableHeader()).append("\n"); - } - builder.append(deviceProfile.getAverageAsTableRow()).append("\n"); - ++row; + builder.append('\n'); + } + } + + private void reportProfilingSummary(StringBuilder builder) { + builder.append("\nProfiles by Kernel Subclass (mean elapsed times in milliseconds)\n\n"); + builder.append(KernelDeviceProfile.getTableHeader()).append('\n'); + for (Map.Entry, KernelProfile> classKernelProfileEntry : profiles.entrySet()) { + String simpleName = Reflection.getSimpleName(classKernelProfileEntry.getKey()); + String kernelName = "----------------- [[ " + simpleName + " ]] "; + builder.append(kernelName); + int dashes = 132 - kernelName.length(); + for (int i = 0; i < dashes; ++i) { + builder.append('-'); } - } - builder.append("\n"); - } - } - - public void reportProfilingSummary(StringBuilder builder) { - builder.append("\nProfiles by Kernel Subclass (mean elapsed times in milliseconds)\n\n"); - builder.append(KernelDeviceProfile.getTableHeader()).append("\n"); - for (Class kernelClass : profiles.keySet()) { - String simpleName = Reflection.getSimpleName(kernelClass); - String kernelName = "----------------- [[ " + simpleName + " ]] "; - builder.append(kernelName); - int dashes = 132 - kernelName.length(); - for (int i = 0; i < dashes; ++i) { - builder.append('-'); - } - builder.append("\n"); - KernelProfile kernelProfile = profiles.get(kernelClass); - for (KernelDeviceProfile deviceProfile : kernelProfile.getDeviceProfiles()) { - builder.append(deviceProfile.getAverageAsTableRow()).append("\n"); - } - } - } - - - public KernelPreferences getPreferences(Kernel kernel) { - synchronized (preferences) { - PreferencesWrapper wrapper = preferences.get(kernel.hashCode()); - KernelPreferences kernelPreferences; - if (wrapper == null) { - kernelPreferences = new KernelPreferences(this, kernel.getClass()); - preferences.put(kernel.hashCode(), new PreferencesWrapper(kernel.getClass(), kernelPreferences)); - }else{ - kernelPreferences = preferences.get(kernel.hashCode()).getPreferences(); - } - return kernelPreferences; - } - } - - public void setPreferredDevices(Kernel _kernel, LinkedHashSet _devices) { - KernelPreferences kernelPreferences = getPreferences(_kernel); - kernelPreferences.setPreferredDevices(_devices); - } - - public KernelPreferences getDefaultPreferences() { - return defaultPreferences; - } - - public void setDefaultPreferredDevices(LinkedHashSet _devices) { - defaultPreferences.setPreferredDevices(_devices); - } - - protected KernelPreferences createDefaultPreferences() { - KernelPreferences preferences = new KernelPreferences(this, null); - preferences.setPreferredDevices(createDefaultPreferredDevices()); - return preferences; - } - - private T getSharedKernelInstance(Class kernelClass) { - synchronized (sharedInstances) { - T shared = (T) sharedInstances.get(kernelClass); - if (shared == null) { + builder.append('\n'); + KernelProfile kernelProfile = classKernelProfileEntry.getValue(); + for (KernelDeviceProfile deviceProfile : kernelProfile.getDeviceProfiles()) { + builder.append(deviceProfile.getAverageAsTableRow()).append('\n'); + } + } + } + + + public KernelPreferences getPreferences(Kernel kernel) { + //synchronized (preferences) { + + return preferences.computeIfAbsent(kernel.hashCode(), (kHash)-> + new PreferencesWrapper(kernel.getClass(), + new KernelPreferences(KernelManager.this, kernel.getClass())) + ).getPreferences(); + +// PreferencesWrapper wrapper = preferences.get(kernel.hashCode()); +// KernelPreferences kernelPreferences; +// if (wrapper == null) { +// } else { +// kernelPreferences = preferences.get(kernel.hashCode()).getPreferences(); +// } +// return kernelPreferences; +// //} + } + + public void setPreferredDevices(Kernel _kernel, LinkedHashSet _devices) { + getPreferences(_kernel).setPreferredDevices(_devices); + } + +// public void setDefaultPreferredDevices(LinkedHashSet _devices) { +// defaultPreferences.setPreferredDevices(_devices); +// } + + private KernelPreferences createDefaultPreferences() { + KernelPreferences preferences = new KernelPreferences(this, null); + preferences.setPreferredDevices(createDefaultPreferredDevices()); + return preferences; + } + + private T getSharedKernelInstance(Class kernelClass) { + return (T)sharedInstances.computeIfAbsent(kernelClass, (k)->{ try { - Constructor constructor = kernelClass.getConstructor(); - constructor.setAccessible(true); - shared = constructor.newInstance(); - sharedInstances.put(kernelClass, shared); + Constructor ctor = kernelClass.getConstructor(); + ctor.setAccessible(true); + return ctor.newInstance(); + } catch (Throwable e) { + throw new RuntimeException(e); } - catch (Exception e) { - throw new RuntimeException(e); + }); +// synchronized (sharedInstances) { +// T shared = (T) sharedInstances.get(kernelClass); +// if (shared == null) { +// try { +// } catch (Exception e) { +// throw new RuntimeException(e); +// } +// } +// return shared; +// } + } + + private LinkedHashSet createDefaultPreferredDevices() { + LinkedHashSet devices = new LinkedHashSet<>(); + + final OpenCLPlatform p = new OpenCLPlatform(0, null, null, null); + List platforms = p.getOpenCLPlatforms(); + + List accelerators = OpenCLDevice.listDevices(Device.TYPE.ACC, platforms); + List gpus = OpenCLDevice.listDevices(Device.TYPE.GPU, platforms); + List cpus = OpenCLDevice.listDevices(Device.TYPE.CPU, platforms); + + accelerators.sort(defaultAcceleratorComparator); + gpus.sort(defaultGPUComparator); + + List preferredDeviceTypes = getPreferredDeviceTypes(); + + for (Device.TYPE type : preferredDeviceTypes) { + switch (type) { + case UNKNOWN: + throw new AssertionError("UNKNOWN device type not supported"); + case GPU: + devices.addAll(gpus); + break; + case CPU: + devices.addAll(cpus); + break; + case JTP: + devices.add(JavaDevice.THREAD_POOL); + break; + case SEQ: + devices.add(JavaDevice.SEQUENTIAL); + break; + case ACC: + devices.addAll(accelerators); + break; + case ALT: + devices.add(JavaDevice.ALTERNATIVE_ALGORITHM); + break; } - } - return shared; - } - } - - protected LinkedHashSet createDefaultPreferredDevices() { - LinkedHashSet devices = new LinkedHashSet<>(); - - List accelerators = OpenCLDevice.listDevices(Device.TYPE.ACC); - List gpus = OpenCLDevice.listDevices(Device.TYPE.GPU); - List cpus = OpenCLDevice.listDevices(Device.TYPE.CPU); - - Collections.sort(accelerators, getDefaultAcceleratorComparator()); - Collections.sort(gpus, getDefaultGPUComparator()); - - List preferredDeviceTypes = getPreferredDeviceTypes(); - - for (Device.TYPE type : preferredDeviceTypes) { - switch (type) { - case UNKNOWN: - throw new AssertionError("UNKNOWN device type not supported"); - case GPU: - devices.addAll(gpus); - break; - case CPU: - devices.addAll(cpus); - break; - case JTP: - devices.add(JavaDevice.THREAD_POOL); - break; - case SEQ: - devices.add(JavaDevice.SEQUENTIAL); - break; - case ACC: - devices.addAll(accelerators); - break; - case ALT: - devices.add(JavaDevice.ALTERNATIVE_ALGORITHM); - break; - } - } - - return devices; - } - - protected List getPreferredDeviceTypes() { - return Arrays.asList(Device.TYPE.ACC, Device.TYPE.GPU, Device.TYPE.CPU, Device.TYPE.ALT, Device.TYPE.JTP); - } - - /** NB, returns -ve for the better device. */ - protected Comparator getDefaultAcceleratorComparator() { - return new Comparator() { - @Override - public int compare(OpenCLDevice left, OpenCLDevice right) { - return (right.getMaxComputeUnits() - left.getMaxComputeUnits()); - } - }; - } - - /** NB, returns -ve for the better device. */ - protected Comparator getDefaultGPUComparator() { - return new Comparator() { - @Override - public int compare(OpenCLDevice left, OpenCLDevice right) { - return selectLhs(left, right) ? -1 : 1; - } - }; - } - - public Device bestDevice() { - return getDefaultPreferences().getPreferredDevice(null); - } - - protected static boolean selectLhs(OpenCLDevice _deviceLhs, OpenCLDevice _deviceRhs) { - boolean nvidiaLhs = _deviceLhs.getOpenCLPlatform().getVendor().toLowerCase().contains("nvidia"); - boolean nvidiaRhs = _deviceRhs.getOpenCLPlatform().getVendor().toLowerCase().contains("nvidia"); - if (nvidiaLhs || nvidiaRhs) { - return selectLhsIfCUDA(_deviceLhs, _deviceRhs); - } - return _deviceLhs.getMaxComputeUnits() > _deviceRhs.getMaxComputeUnits(); + } + + return devices; + } + + List getPreferredDeviceTypes() { + return Arrays.asList(Device.TYPE.ACC, Device.TYPE.GPU, Device.TYPE.CPU, Device.TYPE.ALT, Device.TYPE.JTP); + } + + /** + * NB, returns -ve for the better device. + */ + private static final Comparator defaultAcceleratorComparator = (left, right) -> + Integer.compare(right.getMaxComputeUnits(), left.getMaxComputeUnits()); + + + /** + * NB, returns -ve for the better device. + */ + private static final Comparator defaultGPUComparator = (left, right) -> + left==right? 0 : (selectLhs(left, right) ? -1 : 1); + + + public Device bestDevice() { + return defaultPreferences.getPreferredDevice(null); } - /** NVidia/CUDA architecture reports maxComputeUnits in a completely different context, i.e. maxComputeUnits is not same as + private static boolean selectLhs(OpenCLDevice _deviceLhs, OpenCLDevice _deviceRhs) { + boolean nvidiaLhs = _deviceLhs.getOpenCLPlatform().getVendor().toLowerCase().contains("nvidia"); + boolean nvidiaRhs = _deviceRhs.getOpenCLPlatform().getVendor().toLowerCase().contains("nvidia"); + if (nvidiaLhs || nvidiaRhs) { + return selectLhsIfCUDA(_deviceLhs, _deviceRhs); + } + return _deviceLhs.getMaxComputeUnits() > _deviceRhs.getMaxComputeUnits(); + } + + /** + * NVidia/CUDA architecture reports maxComputeUnits in a completely different context, i.e. maxComputeUnits is not same as * (is much less than) the number of OpenCL cores available. - * + *

*

Therefore when comparing an NVidia device we use different criteria.

*/ - protected static boolean selectLhsIfCUDA(OpenCLDevice _deviceLhs, OpenCLDevice _deviceRhs) { - if (_deviceLhs.getType() != _deviceRhs.getType()) { - return selectLhsByType(_deviceLhs.getType(), _deviceRhs.getType()); - } - return _deviceLhs.getMaxWorkGroupSize() == _deviceRhs.getMaxWorkGroupSize() - ? _deviceLhs.getGlobalMemSize() > _deviceRhs.getGlobalMemSize() - : _deviceLhs.getMaxWorkGroupSize() > _deviceRhs.getMaxWorkGroupSize(); + private static boolean selectLhsIfCUDA(OpenCLDevice _deviceLhs, OpenCLDevice _deviceRhs) { + if (_deviceLhs.getType() != _deviceRhs.getType()) { + return selectLhsByType(_deviceLhs.getType(), _deviceRhs.getType()); + } + return _deviceLhs.getMaxWorkGroupSize() == _deviceRhs.getMaxWorkGroupSize() + ? _deviceLhs.getGlobalMemSize() > _deviceRhs.getGlobalMemSize() + : _deviceLhs.getMaxWorkGroupSize() > _deviceRhs.getMaxWorkGroupSize(); } - private static boolean selectLhsByType(Device.TYPE lhs, Device.TYPE rhs) { - return lhs.rank < rhs.rank; - } - - public KernelProfile getProfile(Class kernelClass) { - synchronized (profiles) { - KernelProfile profile = profiles.get(kernelClass); - if (profile == null) { - profile = new KernelProfile(kernelClass); - profiles.put(kernelClass, profile); - } - return profile; - } - } - - /** New home for deprecated methods of {@link Device}. */ - public static class DeprecatedMethods { - - @Deprecated - public static Device firstDevice(Device.TYPE _type) { - List devices = instance().getDefaultPreferences().getPreferredDevices(null); - for (Device device : devices) { - if(device.getType() == _type) { - return device; + private static boolean selectLhsByType(Device.TYPE lhs, Device.TYPE rhs) { + return lhs.rank < rhs.rank; + } + + public KernelProfile getProfile(Class kernelClass) { + //synchronized (profiles) { + return profiles.computeIfAbsent(kernelClass, k -> new KernelProfile(kernelClass)); + //} + } + + /** + * New home for deprecated methods of {@link Device}. + */ + public static class DeprecatedMethods { + + @Deprecated + public static Device firstDevice(Device.TYPE _type) { + List devices = instance().defaultPreferences.getPreferredDevices(null); + for (Device device : devices) { + if (device.getType() == _type) { + return device; + } } - } - return null; - } - - @SuppressWarnings("deprecation") - @Deprecated - public static Device bestGPU() { - return firstDevice(Device.TYPE.GPU); - } - - @SuppressWarnings("deprecation") - @Deprecated - public static Device bestACC() { - return firstDevice(Device.TYPE.ACC); - } - } + return null; + } + + @SuppressWarnings("deprecation") + @Deprecated + public static Device bestGPU() { + return firstDevice(Device.TYPE.GPU); + } + + @SuppressWarnings("deprecation") + @Deprecated + public static Device bestACC() { + return firstDevice(Device.TYPE.ACC); + } + } } diff --git a/src/main/java/com/aparapi/internal/kernel/KernelPreferences.java b/src/main/java/com/aparapi/internal/kernel/KernelPreferences.java index 20d2954e..3964f9a0 100644 --- a/src/main/java/com/aparapi/internal/kernel/KernelPreferences.java +++ b/src/main/java/com/aparapi/internal/kernel/KernelPreferences.java @@ -1,12 +1,12 @@ /** * Copyright (c) 2016 - 2017 Syncleus, Inc. - * + *

* Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + *

+ * http://www.apache.org/licenses/LICENSE-2.0 + *

* Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -21,73 +21,72 @@ import java.util.*; public class KernelPreferences { - private final Class kernelClass; - private final KernelManager manager; - private volatile LinkedList preferredDevices = null; - private final LinkedHashSet failedDevices = new LinkedHashSet<>(); + private final Class kernelClass; + private final KernelManager manager; + private final LinkedList preferredDevices = new LinkedList(); + protected final LinkedHashSet failedDevices = new LinkedHashSet<>(); - public KernelPreferences(KernelManager manager, Class kernelClass) { - this.kernelClass = kernelClass; - this.manager = manager; - } + public KernelPreferences(KernelManager manager, Class kernelClass) { + this.kernelClass = kernelClass; + this.manager = manager; + } - /** What Kernel subclass is this the preferences for? */ - public Class getKernelClass() { - return kernelClass; - } + /** What Kernel subclass is this the preferences for? */ + public Class getKernelClass() { + return kernelClass; + } - public List getPreferredDevices(Kernel kernel) { - maybeSetUpDefaultPreferredDevices(); + public List getPreferredDevices(Kernel kernel) { - if (kernel == null) { - return Collections.unmodifiableList(preferredDevices); - } - List localPreferredDevices = new ArrayList<>(); - ArrayList copy; - synchronized (preferredDevices) { - copy = new ArrayList(preferredDevices); - } - for (Device device : copy) { - if (kernel.isAllowDevice(device)) { - localPreferredDevices.add(device); - } - } - return Collections.unmodifiableList(localPreferredDevices); - } + maybeSetUpDefaultPreferredDevices(); - synchronized void setPreferredDevices(LinkedHashSet _preferredDevices) { - if (preferredDevices != null) { - preferredDevices.clear(); - preferredDevices.addAll(_preferredDevices); - } - else { - preferredDevices = new LinkedList<>(_preferredDevices); - } - failedDevices.clear(); - } + ArrayList copy; + synchronized (preferredDevices) { + if (kernel == null) + return Collections.unmodifiableList(preferredDevices); + else + copy = new ArrayList(preferredDevices); + } + List localPreferredDevices = new ArrayList<>(); + for (Device device : copy) { + if (kernel.isAllowDevice(device)) + localPreferredDevices.add(device); + } + return Collections.unmodifiableList(localPreferredDevices); + } - public Device getPreferredDevice(Kernel kernel) { - List localPreferredDevices = getPreferredDevices(kernel); - return localPreferredDevices.isEmpty() ? null : localPreferredDevices.get(0); - } + void setPreferredDevices(LinkedHashSet _preferredDevices) { + synchronized (preferredDevices) { + preferredDevices.clear(); + preferredDevices.addAll(_preferredDevices); + failedDevices.clear(); + } + } - synchronized void markPreferredDeviceFailed() { - if (preferredDevices.size() > 0) { - failedDevices.add(preferredDevices.remove(0)); - } - } + public Device getPreferredDevice(Kernel kernel) { + List localPreferredDevices = getPreferredDevices(kernel); + return localPreferredDevices.isEmpty() ? null : localPreferredDevices.get(0); + } - private void maybeSetUpDefaultPreferredDevices() { - if (preferredDevices == null) { - synchronized (this) { - if (preferredDevices == null) { - preferredDevices = new LinkedList<>(manager.getDefaultPreferences().getPreferredDevices(null)); + void markPreferredDeviceFailed() { + synchronized (preferredDevices) { + if (!preferredDevices.isEmpty()) { + failedDevices.add(preferredDevices.removeFirst()); } - } - } - } + } + } - public List getFailedDevices() { - return new ArrayList<>(failedDevices); - } + private void maybeSetUpDefaultPreferredDevices() { + + synchronized (preferredDevices) { + if (preferredDevices.isEmpty()) { + preferredDevices.addAll(manager.defaultPreferences.getPreferredDevices(null)); + } + } + + } + +// public List getFailedDevices() { +// return new ArrayList<>(failedDevices); +// } } diff --git a/src/main/java/com/aparapi/internal/kernel/KernelProfile.java b/src/main/java/com/aparapi/internal/kernel/KernelProfile.java index 017ce761..3753e1d4 100644 --- a/src/main/java/com/aparapi/internal/kernel/KernelProfile.java +++ b/src/main/java/com/aparapi/internal/kernel/KernelProfile.java @@ -19,7 +19,7 @@ import com.aparapi.device.*; import java.util.*; -import java.util.logging.*; +import java.util.concurrent.ConcurrentHashMap; /** * Collects profiling information per kernel class per device. Not thread safe, it is necessary for client code to correctly synchronize on @@ -28,83 +28,62 @@ public class KernelProfile { private static final double MILLION = 1000000d; - private static Logger logger = Logger.getLogger(Config.getLoggerName()); + //private static Logger logger = Logger.getLogger(Config.getLoggerName()); private final Class kernelClass; - private LinkedHashMap deviceProfiles = new LinkedHashMap<>(); - private Device currentDevice; - private Device lastDevice; - private KernelDeviceProfile currentDeviceProfile; + public final Map deviceProfiles = new ConcurrentHashMap<>(); public KernelProfile(Class _kernelClass) { kernelClass = _kernelClass; } - public double getLastExecutionTime() { - KernelDeviceProfile lastDeviceProfile = getLastDeviceProfile(); - return lastDeviceProfile == null ? Double.NaN : lastDeviceProfile.getLastElapsedTime(ProfilingEvent.START, ProfilingEvent.EXECUTED) / MILLION; + public double getTotalExecutionTime() { + double sum = 0; + for (KernelDeviceProfile p : deviceProfiles.values()) + sum += p.getLastElapsedTime(ProfilingEvent.START, ProfilingEvent.EXECUTED); + return sum / MILLION; } - public double getLastConversionTime() { - KernelDeviceProfile lastDeviceProfile = getLastDeviceProfile(); - return lastDeviceProfile == null ? Double.NaN : lastDeviceProfile.getLastElapsedTime(ProfilingEvent.START, ProfilingEvent.PREPARE_EXECUTE) / MILLION; + public double getTotalConversionTime() { + double sum = 0; + for (KernelDeviceProfile p : deviceProfiles.values()) + sum += p.getLastElapsedTime(ProfilingEvent.START, ProfilingEvent.PREPARE_EXECUTE); + return sum / MILLION; } - public double getAccumulatedTotalTime() { - KernelDeviceProfile lastDeviceProfile = getLastDeviceProfile(); - if (lastDeviceProfile == null) { - return Double.NaN; - } - else { - return lastDeviceProfile.getCumulativeElapsedTimeAll() / MILLION; - } + public double getTotalTime() { + double sum = 0; + for (KernelDeviceProfile p : deviceProfiles.values()) + sum += p.getCumulativeElapsedTimeAll(); + return sum / MILLION; } - public KernelDeviceProfile getLastDeviceProfile() { - return deviceProfiles.get(currentDevice); - } - void onStart(Device device) { - currentDevice = device; - synchronized (deviceProfiles) { - currentDeviceProfile = deviceProfiles.get(device); - if (currentDeviceProfile == null) { - currentDeviceProfile = new KernelDeviceProfile(kernelClass, device); - deviceProfiles.put(device, currentDeviceProfile); - } - } - currentDeviceProfile.onEvent(ProfilingEvent.START); - } - void onEvent(ProfilingEvent event) { - switch (event) { - case CLASS_MODEL_BUILT: // fallthrough - case OPENCL_GENERATED: // fallthrough - case INIT_JNI: // fallthrough - case OPENCL_COMPILED: // fallthrough - case PREPARE_EXECUTE: // fallthrough - case EXECUTED: // fallthrough - { - if (currentDeviceProfile == null) { - logger.log(Level.SEVERE, "Error in KernelProfile, no currentDevice (synchronization error?"); - } - currentDeviceProfile.onEvent(event); - break; - } - case START: - throw new IllegalArgumentException("must use onStart(Device) to start profiling"); - default: - throw new IllegalArgumentException("Unhandled event " + event); - } + KernelDeviceProfile start(Device device) { + KernelDeviceProfile currentDeviceProfile; + //synchronized (deviceProfiles) { + currentDeviceProfile = deviceProfiles.computeIfAbsent(device, d -> new KernelDeviceProfile(kernelClass, d)); + //} + currentDeviceProfile.on(ProfilingEvent.START); + return currentDeviceProfile; } - void onFinishedExecution() { - reset(); - } - - private void reset() { - lastDevice = currentDevice; - currentDevice = null; - currentDeviceProfile = null; + public KernelDeviceProfile profiler(Device device) { +// switch (event) { +// case CLASS_MODEL_BUILT: // fallthrough +// case OPENCL_GENERATED: // fallthrough +// case INIT_JNI: // fallthrough +// case OPENCL_COMPILED: // fallthrough +// case PREPARE_EXECUTE: // fallthrough +// case EXECUTED: // fallthrough +// { + return deviceProfiles.get(device); +// } +// case START: +// throw new IllegalArgumentException("must use onStart(Device) to start profiling"); +// default: +// throw new IllegalArgumentException("Unhandled event " + event); +// } } public Collection getDevices() { @@ -115,7 +94,4 @@ public Collection getDeviceProfiles() { return deviceProfiles.values(); } - public KernelDeviceProfile getDeviceProfile(Device device) { - return deviceProfiles.get(device); - } } diff --git a/src/main/java/com/aparapi/internal/kernel/KernelRunner.java b/src/main/java/com/aparapi/internal/kernel/KernelRunner.java index 66f8e72b..e7a2c0bd 100644 --- a/src/main/java/com/aparapi/internal/kernel/KernelRunner.java +++ b/src/main/java/com/aparapi/internal/kernel/KernelRunner.java @@ -52,1089 +52,1159 @@ to national security controls as identified on the Commerce Control List (curren */ package com.aparapi.internal.kernel; -import com.aparapi.*; +import com.aparapi.Config; +import com.aparapi.Kernel; import com.aparapi.Kernel.Constant; -import com.aparapi.Kernel.*; -import com.aparapi.device.*; -import com.aparapi.internal.annotation.*; -import com.aparapi.internal.exception.*; -import com.aparapi.internal.instruction.InstructionSet.*; -import com.aparapi.internal.jni.*; -import com.aparapi.internal.model.*; -import com.aparapi.internal.util.*; -import com.aparapi.internal.writer.*; -import com.aparapi.opencl.*; - -import java.lang.reflect.*; -import java.nio.*; +import com.aparapi.Kernel.EXECUTION_MODE; +import com.aparapi.Kernel.KernelState; +import com.aparapi.Kernel.Local; +import com.aparapi.ProfileInfo; +import com.aparapi.Range; +import com.aparapi.device.Device; +import com.aparapi.device.JavaDevice; +import com.aparapi.device.OpenCLDevice; +import com.aparapi.internal.annotation.UsedByJNICode; +import com.aparapi.internal.exception.AparapiException; +import com.aparapi.internal.exception.CodeGenException; +import com.aparapi.internal.instruction.InstructionSet.TypeSpec; +import com.aparapi.internal.jni.KernelRunnerJNI; +import com.aparapi.internal.model.ClassModel; +import com.aparapi.internal.model.Entrypoint; +import com.aparapi.internal.util.UnsafeWrapper; +import com.aparapi.internal.writer.KernelWriter; +import com.aparapi.opencl.OpenCL; + +import java.lang.reflect.Array; +import java.lang.reflect.Field; +import java.lang.reflect.Modifier; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.nio.IntBuffer; import java.util.*; import java.util.concurrent.*; -import java.util.concurrent.ForkJoinPool.*; -import java.util.logging.*; +import java.util.concurrent.ForkJoinPool.ManagedBlocker; +import java.util.logging.Level; +import java.util.logging.Logger; /** * The class is responsible for executing Kernel implementations.
- * + * * The KernelRunner is the real workhorse for Aparapi. Each Kernel instance creates a single * KernelRunner to encapsulate state and to help coordinate interactions between the Kernel * and it's execution logic.
- * + * * The KernelRunner is created lazily as a result of calling Kernel.execute(). A this * time the ExecutionMode is consulted to determine the default requested mode. This will dictate how * the KernelRunner will attempt to execute the Kernel - * + * * @see com.aparapi.Kernel#execute(int _globalSize) - * + * * @author gfrost * */ -public class KernelRunner extends KernelRunnerJNI{ - - public static boolean BINARY_CACHING_DISABLED = false; - - private static final int MINIMUM_ARRAY_SIZE = 1; - - /** @see #getCurrentPass() */ - @UsedByJNICode public static final int PASS_ID_PREPARING_EXECUTION = -2; - /** @see #getCurrentPass() */ - @UsedByJNICode public static final int PASS_ID_COMPLETED_EXECUTION = -1; - @UsedByJNICode public static final int CANCEL_STATUS_FALSE = 0; - @UsedByJNICode public static final int CANCEL_STATUS_TRUE = 1; - private static final String CODE_GEN_ERROR_MARKER = CodeGenException.class.getName(); - - private static Logger logger = Logger.getLogger(Config.getLoggerName()); - - private long jniContextHandle = 0; - - private final Kernel kernel; - - private Entrypoint entryPoint; - - private int argc; - - // may be read by a thread other than the control thread, hence volatile - private volatile boolean executing; - - // may be read by a thread other than the control thread, hence volatile - private volatile int passId = PASS_ID_PREPARING_EXECUTION; - - /** - * A direct ByteBuffer used for asynchronous intercommunication between java and JNI C code. - * - *

- * At present this is a 4 byte buffer to be interpreted as an int[1], used for passing from java to C a single integer interpreted as a cancellation indicator. - */ - private final ByteBuffer inBufferRemote; - private final IntBuffer inBufferRemoteInt; - - /** A direct ByteBuffer used for asynchronous intercommunication between java and JNI C code. - *

- * At present this is a 4 byte buffer to be interpreted as an int[1], used for passing from C to java a single integer interpreted as a - * the current pass id. - */ - private final ByteBuffer outBufferRemote; - private final IntBuffer outBufferRemoteInt; - - private boolean isFallBack = false; // If isFallBack, rebuild the kernel (necessary?) - - private static final ForkJoinWorkerThreadFactory lowPriorityThreadFactory = new ForkJoinWorkerThreadFactory(){ - @Override public ForkJoinWorkerThread newThread(ForkJoinPool pool) { - ForkJoinWorkerThread newThread = ForkJoinPool.defaultForkJoinWorkerThreadFactory.newThread(pool); - newThread.setPriority(Thread.MIN_PRIORITY); - return newThread; - } - }; - - private static final ForkJoinPool threadPool = new ForkJoinPool(Runtime.getRuntime().availableProcessors(), - lowPriorityThreadFactory, null, false); - private static HashMap, String> openCLCache = new HashMap<>(); - private static LinkedHashSet seenBinaryKeys = new LinkedHashSet<>(); - - /** - * Create a KernelRunner for a specific Kernel instance. - * - * @param _kernel - */ - public KernelRunner(Kernel _kernel) { - kernel = _kernel; - - inBufferRemote = ByteBuffer.allocateDirect(4); - outBufferRemote = ByteBuffer.allocateDirect(4); - - inBufferRemote.order(ByteOrder.nativeOrder()); - outBufferRemote.order(ByteOrder.nativeOrder()); - - inBufferRemoteInt = inBufferRemote.asIntBuffer(); - outBufferRemoteInt = outBufferRemote.asIntBuffer(); - - KernelManager.instance(); // ensures static initialization of KernelManager - } - - /** - * @see Kernel#cleanUpArrays(). - */ - public void cleanUpArrays() { - if (args != null && kernel.isRunningCL()) { - for (KernelArg arg : args) { - if ((arg.getType() & KernelRunnerJNI.ARG_ARRAY) != 0) { - Field field = arg.getField(); - if (field != null && field.getType().isArray() && !Modifier.isFinal(field.getModifiers())) { - field.setAccessible(true); - Class componentType = field.getType().getComponentType(); - Object newValue = Array.newInstance(componentType, MINIMUM_ARRAY_SIZE); - try { - field.set(kernel, newValue); - } - catch (IllegalAccessException e) { - throw new RuntimeException(e); - } - } +public class KernelRunner extends KernelRunnerJNI { + + public static boolean BINARY_CACHING_DISABLED = false; + + private static final int MINIMUM_ARRAY_SIZE = 1; + + /** @see #getCurrentPass() */ + @UsedByJNICode + public static final int PASS_ID_PREPARING_EXECUTION = -2; + /** @see #getCurrentPass() */ + @UsedByJNICode + public static final int PASS_ID_COMPLETED_EXECUTION = -1; + @UsedByJNICode + public static final int CANCEL_STATUS_FALSE = 0; + @UsedByJNICode + public static final int CANCEL_STATUS_TRUE = 1; + private static final String CODE_GEN_ERROR_MARKER = CodeGenException.class.getName(); + + private static final Logger logger = Logger.getLogger(Config.getLoggerName()); + + private volatile long jniContextHandle = 0; + + private final Kernel kernel; + + private volatile Entrypoint entryPoint; + + private int argc; + + // may be read by a thread other than the control thread, hence volatile + private volatile boolean executing; + +// // may be read by a thread other than the control thread, hence volatile +// private volatile int passId = PASS_ID_PREPARING_EXECUTION; + + /** + * A direct ByteBuffer used for asynchronous intercommunication between java and JNI C code. + * + *

+ * At present this is a 4 byte buffer to be interpreted as an int[1], used for passing from java to C a single integer interpreted as a cancellation indicator. + */ + private final ByteBuffer inBufferRemote; + private final IntBuffer inBufferRemoteInt; + + /** A direct ByteBuffer used for asynchronous intercommunication between java and JNI C code. + *

+ * At present this is a 4 byte buffer to be interpreted as an int[1], used for passing from C to java a single integer interpreted as a + * the current pass id. + */ + private final ByteBuffer outBufferRemote; + private final IntBuffer outBufferRemoteInt; + + private volatile boolean isFallBack = false; // If isFallBack, rebuild the kernel (necessary?) + +// private static final ForkJoinWorkerThreadFactory lowPriorityThreadFactory = new ForkJoinWorkerThreadFactory() { +// @Override +// public ForkJoinWorkerThread newThread(ForkJoinPool pool) { +// ForkJoinWorkerThread newThread = ForkJoinPool.defaultForkJoinWorkerThreadFactory.newThread(pool); +// newThread.setPriority(Thread.MIN_PRIORITY); +// return newThread; +// } +// }; + + private static final ForkJoinPool threadPool = + ForkJoinPool.commonPool(); +// new ForkJoinPool(Runtime.getRuntime().availableProcessors(), +// lowPriorityThreadFactory, null, false); + + private static final Map, String> openCLCache = new ConcurrentHashMap<>(); + private static final Set seenBinaryKeys = + //new LinkedHashSet<>(); + Collections.newSetFromMap(new ConcurrentHashMap<>()); + + /** + * Create a KernelRunner for a specific Kernel instance. + * + * @param _kernel + */ + public KernelRunner(Kernel _kernel) { + kernel = _kernel; + + inBufferRemote = ByteBuffer.allocateDirect(4); + outBufferRemote = ByteBuffer.allocateDirect(4); + + inBufferRemote.order(ByteOrder.nativeOrder()); + outBufferRemote.order(ByteOrder.nativeOrder()); + + inBufferRemoteInt = inBufferRemote.asIntBuffer(); + outBufferRemoteInt = outBufferRemote.asIntBuffer(); + + KernelManager.instance(); // ensures static initialization of KernelManager + } + + /** + * @see Kernel#cleanUpArrays(). + */ + public void cleanUpArrays() { + /*synchronized (kernel)*/ { + + if (args != null && kernel.isRunningCL()) { + for (KernelArg arg : args) { + if ((arg.getType() & KernelRunnerJNI.ARG_ARRAY) != 0) { + Field field = arg.getField(); + if (field != null && field.getType().isArray() && !Modifier.isFinal(field.getModifiers())) { + field.setAccessible(true); + Class componentType = field.getType().getComponentType(); + Object newValue = Array.newInstance(componentType, MINIMUM_ARRAY_SIZE); + try { + field.set(kernel, newValue); + } catch (IllegalAccessException e) { + throw new RuntimeException(e); + } + } + } + } + kernel.execute(0); + } else if (kernel.isRunningCL()) { + logger.log(Level.SEVERE, "KernelRunner#cleanUpArrays() could not execute as no args available (Kernel has not been executed?)"); + } + } + } + + /** + * Kernel.dispose() delegates to KernelRunner.dispose() which delegates to disposeJNI() to actually close JNI data structures.
+ * + * @see KernelRunnerJNI#disposeJNI(long) + */ + public void dispose() { + synchronized (kernel) { + if (kernel.isRunningCL()) { + + disposeJNI(jniContextHandle); + seenBinaryKeys.clear(); } - } - kernel.execute(0); - } else if (kernel.isRunningCL()) { - logger.log(Level.SEVERE, "KernelRunner#cleanUpArrays() could not execute as no args available (Kernel has not been executed?)"); - } - } - - /** - * Kernel.dispose() delegates to KernelRunner.dispose() which delegates to disposeJNI() to actually close JNI data structures.
- * - * @see KernelRunnerJNI#disposeJNI(long) - */ - public synchronized void dispose() { - if (kernel.isRunningCL()) { - disposeJNI(jniContextHandle); - seenBinaryKeys.clear(); - } - // We are using a shared pool, so there's no need no shutdown it when kernel is disposed - // threadPool.shutdownNow(); - } - - private Set capabilitiesSet; - - boolean hasFP64Support() { - if (capabilitiesSet == null) { - throw new IllegalStateException("Capabilities queried before they were initialized"); - } - return (capabilitiesSet.contains(OpenCL.CL_KHR_FP64)); - } - - boolean hasSelectFPRoundingModeSupport() { - if (capabilitiesSet == null) { - throw new IllegalStateException("Capabilities queried before they were initialized"); - } - return capabilitiesSet.contains(OpenCL.CL_KHR_SELECT_FPROUNDING_MODE); - } - - boolean hasGlobalInt32BaseAtomicsSupport() { - if (capabilitiesSet == null) { - throw new IllegalStateException("Capabilities queried before they were initialized"); - } - return capabilitiesSet.contains(OpenCL.CL_KHR_GLOBAL_INT32_BASE_ATOMICS); - } - - boolean hasGlobalInt32ExtendedAtomicsSupport() { - if (capabilitiesSet == null) { - throw new IllegalStateException("Capabilities queried before they were initialized"); - } - return capabilitiesSet.contains(OpenCL.CL_KHR_GLOBAL_INT32_EXTENDED_ATOMICS); - } - - boolean hasLocalInt32BaseAtomicsSupport() { - if (capabilitiesSet == null) { - throw new IllegalStateException("Capabilities queried before they were initialized"); - } - return capabilitiesSet.contains(OpenCL.CL_KHR_LOCAL_INT32_BASE_ATOMICS); - } - - boolean hasLocalInt32ExtendedAtomicsSupport() { - if (capabilitiesSet == null) { - throw new IllegalStateException("Capabilities queried before they were initialized"); - } - return capabilitiesSet.contains(OpenCL.CL_KHR_LOCAL_INT32_EXTENDED_ATOMICS); - } - - boolean hasInt64BaseAtomicsSupport() { - if (capabilitiesSet == null) { - throw new IllegalStateException("Capabilities queried before they were initialized"); - } - return capabilitiesSet.contains(OpenCL.CL_KHR_INT64_BASE_ATOMICS); - } - - boolean hasInt64ExtendedAtomicsSupport() { - if (capabilitiesSet == null) { - throw new IllegalStateException("Capabilities queried before they were initialized"); - } - return capabilitiesSet.contains(OpenCL.CL_KHR_INT64_EXTENDED_ATOMICS); - } - - boolean has3DImageWritesSupport() { - if (capabilitiesSet == null) { - throw new IllegalStateException("Capabilities queried before they were initialized"); - } - return capabilitiesSet.contains(OpenCL.CL_KHR_3D_IMAGE_WRITES); - } - - boolean hasByteAddressableStoreSupport() { - if (capabilitiesSet == null) { - throw new IllegalStateException("Capabilities queried before they were initialized"); - } - return capabilitiesSet.contains(OpenCL.CL_KHR_BYTE_ADDRESSABLE_SUPPORT); - } - - boolean hasFP16Support() { - if (capabilitiesSet == null) { - throw new IllegalStateException("Capabilities queried before they were initialized"); - } - return capabilitiesSet.contains(OpenCL.CL_KHR_FP16); - } - - boolean hasGLSharingSupport() { - if (capabilitiesSet == null) { - throw new IllegalStateException("Capabilities queried before they were initialized"); - } - return capabilitiesSet.contains(OpenCL.CL_KHR_GL_SHARING); - } - - private static final class FJSafeCyclicBarrier extends CyclicBarrier{ - FJSafeCyclicBarrier(final int threads) { - super(threads); - } - - @Override public int await() throws InterruptedException, BrokenBarrierException { - class Awaiter implements ManagedBlocker{ - private int value; - - private boolean released; - - @Override public boolean block() throws InterruptedException { - try { - value = superAwait(); - released = true; - return true; - } catch (final BrokenBarrierException e) { - throw new RuntimeException(e); - } + } + // We are using a shared pool, so there's no need no shutdown it when kernel is disposed + // threadPool.shutdownNow(); + } + + + private Set capabilitiesSet; + + boolean hasFP64Support() { + if (capabilitiesSet == null) { + throw new IllegalStateException("Capabilities queried before they were initialized"); + } + return (capabilitiesSet.contains(OpenCL.CL_KHR_FP64)); + } + + boolean hasSelectFPRoundingModeSupport() { + if (capabilitiesSet == null) { + throw new IllegalStateException("Capabilities queried before they were initialized"); + } + return capabilitiesSet.contains(OpenCL.CL_KHR_SELECT_FPROUNDING_MODE); + } + + boolean hasGlobalInt32BaseAtomicsSupport() { + if (capabilitiesSet == null) { + throw new IllegalStateException("Capabilities queried before they were initialized"); + } + return capabilitiesSet.contains(OpenCL.CL_KHR_GLOBAL_INT32_BASE_ATOMICS); + } + + boolean hasGlobalInt32ExtendedAtomicsSupport() { + if (capabilitiesSet == null) { + throw new IllegalStateException("Capabilities queried before they were initialized"); + } + return capabilitiesSet.contains(OpenCL.CL_KHR_GLOBAL_INT32_EXTENDED_ATOMICS); + } + + boolean hasLocalInt32BaseAtomicsSupport() { + if (capabilitiesSet == null) { + throw new IllegalStateException("Capabilities queried before they were initialized"); + } + return capabilitiesSet.contains(OpenCL.CL_KHR_LOCAL_INT32_BASE_ATOMICS); + } + + boolean hasLocalInt32ExtendedAtomicsSupport() { + if (capabilitiesSet == null) { + throw new IllegalStateException("Capabilities queried before they were initialized"); + } + return capabilitiesSet.contains(OpenCL.CL_KHR_LOCAL_INT32_EXTENDED_ATOMICS); + } + + boolean hasInt64BaseAtomicsSupport() { + if (capabilitiesSet == null) { + throw new IllegalStateException("Capabilities queried before they were initialized"); + } + return capabilitiesSet.contains(OpenCL.CL_KHR_INT64_BASE_ATOMICS); + } + + boolean hasInt64ExtendedAtomicsSupport() { + if (capabilitiesSet == null) { + throw new IllegalStateException("Capabilities queried before they were initialized"); + } + return capabilitiesSet.contains(OpenCL.CL_KHR_INT64_EXTENDED_ATOMICS); + } + + boolean has3DImageWritesSupport() { + if (capabilitiesSet == null) { + throw new IllegalStateException("Capabilities queried before they were initialized"); + } + return capabilitiesSet.contains(OpenCL.CL_KHR_3D_IMAGE_WRITES); + } + + boolean hasByteAddressableStoreSupport() { + if (capabilitiesSet == null) { + throw new IllegalStateException("Capabilities queried before they were initialized"); + } + return capabilitiesSet.contains(OpenCL.CL_KHR_BYTE_ADDRESSABLE_SUPPORT); + } + + boolean hasFP16Support() { + if (capabilitiesSet == null) { + throw new IllegalStateException("Capabilities queried before they were initialized"); + } + return capabilitiesSet.contains(OpenCL.CL_KHR_FP16); + } + + boolean hasGLSharingSupport() { + if (capabilitiesSet == null) { + throw new IllegalStateException("Capabilities queried before they were initialized"); + } + return capabilitiesSet.contains(OpenCL.CL_KHR_GL_SHARING); + } + + private static final class FJSafeCyclicBarrier extends CyclicBarrier { + FJSafeCyclicBarrier(final int threads) { + super(threads); + } + + @Override + public int await() throws InterruptedException { + class Awaiter implements ManagedBlocker { + private int value; + + private boolean released; + + @Override + public boolean block() throws InterruptedException { + try { + value = superAwait(); + released = true; + return true; + } catch (final BrokenBarrierException e) { + throw new RuntimeException(e); + } + } + + @Override + public boolean isReleasable() { + return released; + } + + int getValue() { + return value; + } } + final Awaiter awaiter = new Awaiter(); + ForkJoinPool.managedBlock(awaiter); + return awaiter.getValue(); + } + + int superAwait() throws InterruptedException, BrokenBarrierException { + return super.await(); + } + } + + // @FunctionalInterface + private interface ThreadIdSetter { + void set(KernelState kernelState, int globalGroupId, int threadId); + } + + /** + * Execute using a Java thread pool, or sequentially, or using an alternative algorithm, usually as a result of failing to compile or execute OpenCL + */ + @SuppressWarnings("deprecation") + protected void executeJava(ExecutionSettings _settings) { + Device device = _settings.device(); + if (logger.isLoggable(Level.FINE)) { + logger.fine("executeJava: range = " + _settings.range + ", device = " + device); + } + boolean legacySequentialMode = kernel.getExecutionMode() == Kernel.EXECUTION_MODE.SEQ; + + int passId = PASS_ID_PREPARING_EXECUTION; + _settings.profile.profiler(device).on(ProfilingEvent.PREPARE_EXECUTE); + + try { + if (device == JavaDevice.ALTERNATIVE_ALGORITHM) { + if (kernel.hasFallbackAlgorithm()) { + for (passId = 0; passId < _settings.passes; ++passId) { + kernel.executeFallbackAlgorithm(_settings.range, passId); + } + } else { + boolean silently = true; // not having an alternative algorithm is the normal state, and does not need reporting + fallBackToNextDevice(_settings, null, silently); + } + } else { + final int localSize0 = _settings.range.getLocalSize(0); + final int localSize1 = _settings.range.getLocalSize(1); + final int localSize2 = _settings.range.getLocalSize(2); + final int globalSize1 = _settings.range.getGlobalSize(1); + if (legacySequentialMode || device == JavaDevice.SEQUENTIAL) { + /** + * SEQ mode is useful for testing trivial logic, but kernels which use SEQ mode cannot be used if the + * product of localSize(0..3) is >1. So we can use multi-dim ranges but only if the local size is 1 in all dimensions. + * + * As a result of this barrier is only ever 1 work item wide and probably should be turned into a no-op. + * + * So we need to check if the range is valid here. If not we have no choice but to punt. + */ + if ((localSize0 * localSize1 * localSize2) > 1) { + throw new IllegalStateException("Can't run range with group size >1 sequentially. Barriers would deadlock!"); + } + + final Kernel kernelClone = kernel.clone(_settings.range); + final KernelState kernelState = kernelClone.getKernelState(); + + kernelState.setRange(_settings.range); + kernelState.setGroupId(0, 0); + kernelState.setGroupId(1, 0); + kernelState.setGroupId(2, 0); + kernelState.setLocalId(0, 0); + kernelState.setLocalId(1, 0); + kernelState.setLocalId(2, 0); + kernelState.setLocalBarrier(new FJSafeCyclicBarrier(1)); + + for (passId = 0; passId < _settings.passes; passId++) { + if (getCancelState() == CANCEL_STATUS_TRUE) { + break; + } + kernelState.setPassId(passId); + + int ds = _settings.range.getGlobalSize(0); + switch (_settings.range.getDims()) { + case 1: + for (int id = 0; id < ds; id++) { + kernelState.setGlobalId(0, id); + kernelClone.run(); + } + break; + case 2: + for (int x = 0; x < ds; x++) { + kernelState.setGlobalId(0, x); + + for (int y = 0; y < globalSize1; y++) { + kernelState.setGlobalId(1, y); + kernelClone.run(); + } + } + break; + case 3: + for (int x = 0; x < ds; x++) { + kernelState.setGlobalId(0, x); + + for (int y = 0; y < globalSize1; y++) { + kernelState.setGlobalId(1, y); + + for (int z = 0; z < _settings.range.getGlobalSize(2); z++) { + kernelState.setGlobalId(2, z); + kernelClone.run(); + } + + kernelClone.run(); + } + } + break; + } + } + passId = PASS_ID_COMPLETED_EXECUTION; + } else { + if (device != JavaDevice.THREAD_POOL && kernel.getExecutionMode() != Kernel.EXECUTION_MODE.JTP) { + throw new AssertionError("unexpected JavaDevice or EXECUTION_MODE"); + } + final int threads = localSize0 * localSize1 * localSize2; + final int numGroups0 = _settings.range.getNumGroups(0); + final int numGroups1 = _settings.range.getNumGroups(1); + final int globalGroups = numGroups0 * numGroups1 * _settings.range.getNumGroups(2); + + assert(globalGroups > 0); + + /** + * This joinBarrier is the barrier that we provide for the kernel threads to rendezvous with the current dispatch thread. + * So this barrier is threadCount+1 wide (the +1 is for the dispatch thread) + */ + //final CyclicBarrier joinBarrier = new FJSafeCyclicBarrier(threads + 1); + + /** + * This localBarrier is only ever used by the kernels. If the kernel does not use the barrier the threads + * can get out of sync, we promised nothing in JTP mode. + * + * As with OpenCL all threads within a group must wait at the barrier or none. It is a user error (possible deadlock!) + * if the barrier is in a conditional that is only executed by some of the threads within a group. + * + * Kernel developer must understand this. + * + * This barrier is threadCount wide. We never hit the barrier from the dispatch thread. + */ + //final CyclicBarrier localBarrier = new FJSafeCyclicBarrier(threads); + + final ThreadIdSetter threadIdSetter; + + switch (_settings.range.getDims()) { + case 1: + threadIdSetter = (kernelState, globalGroupId, threadId) -> { + // (kernelState, globalGroupId, threadId) ->{ + kernelState.setLocalId(0, (threadId % localSize0)); + kernelState.setGlobalId(0, (threadId + (globalGroupId * threads))); + kernelState.setGroupId(0, globalGroupId); + }; + break; + case 2: + + /** + * Consider a 12x4 grid of 4*2 local groups + *

+                             *                                             threads = 4*2 = 8
+                             *                                             localWidth=4
+                             *                                             localHeight=2
+                             *                                             globalWidth=12
+                             *                                             globalHeight=4
+                             *
+                             *    00 01 02 03 | 04 05 06 07 | 08 09 10 11
+                             *    12 13 14 15 | 16 17 18 19 | 20 21 22 23
+                             *    ------------+-------------+------------
+                             *    24 25 26 27 | 28 29 30 31 | 32 33 34 35
+                             *    36 37 38 39 | 40 41 42 43 | 44 45 46 47
+                             *
+                             *    00 01 02 03 | 00 01 02 03 | 00 01 02 03  threadIds : [0..7]*6
+                             *    04 05 06 07 | 04 05 06 07 | 04 05 06 07
+                             *    ------------+-------------+------------
+                             *    00 01 02 03 | 00 01 02 03 | 00 01 02 03
+                             *    04 05 06 07 | 04 05 06 07 | 04 05 06 07
+                             *
+                             *    00 00 00 00 | 01 01 01 01 | 02 02 02 02  groupId[0] : 0..6
+                             *    00 00 00 00 | 01 01 01 01 | 02 02 02 02
+                             *    ------------+-------------+------------
+                             *    00 00 00 00 | 01 01 01 01 | 02 02 02 02
+                             *    00 00 00 00 | 01 01 01 01 | 02 02 02 02
+                             *
+                             *    00 00 00 00 | 00 00 00 00 | 00 00 00 00  groupId[1] : 0..6
+                             *    00 00 00 00 | 00 00 00 00 | 00 00 00 00
+                             *    ------------+-------------+------------
+                             *    01 01 01 01 | 01 01 01 01 | 01 01 01 01
+                             *    01 01 01 01 | 01 01 01 01 | 01 01 01 01
+                             *
+                             *    00 01 02 03 | 08 09 10 11 | 16 17 18 19  globalThreadIds == threadId + groupId * threads;
+                             *    04 05 06 07 | 12 13 14 15 | 20 21 22 23
+                             *    ------------+-------------+------------
+                             *    24 25 26 27 | 32[33]34 35 | 40 41 42 43
+                             *    28 29 30 31 | 36 37 38 39 | 44 45 46 47
+                             *
+                             *    00 01 02 03 | 00 01 02 03 | 00 01 02 03  localX = threadId % localWidth; (for globalThreadId 33 = threadId = 01 : 01%4 =1)
+                             *    00 01 02 03 | 00 01 02 03 | 00 01 02 03
+                             *    ------------+-------------+------------
+                             *    00 01 02 03 | 00[01]02 03 | 00 01 02 03
+                             *    00 01 02 03 | 00 01 02 03 | 00 01 02 03
+                             *
+                             *    00 00 00 00 | 00 00 00 00 | 00 00 00 00  localY = threadId /localWidth  (for globalThreadId 33 = threadId = 01 : 01/4 =0)
+                             *    01 01 01 01 | 01 01 01 01 | 01 01 01 01
+                             *    ------------+-------------+------------
+                             *    00 00 00 00 | 00[00]00 00 | 00 00 00 00
+                             *    01 01 01 01 | 01 01 01 01 | 01 01 01 01
+                             *
+                             *    00 01 02 03 | 04 05 06 07 | 08 09 10 11  globalX=
+                             *    00 01 02 03 | 04 05 06 07 | 08 09 10 11     groupsPerLineWidth=globalWidth/localWidth (=12/4 =3)
+                             *    ------------+-------------+------------     groupInset =groupId%groupsPerLineWidth (=4%3 = 1)
+                             *    00 01 02 03 | 04[05]06 07 | 08 09 10 11
+                             *    00 01 02 03 | 04 05 06 07 | 08 09 10 11     globalX = groupInset*localWidth+localX (= 1*4+1 = 5)
+                             *
+                             *    00 00 00 00 | 00 00 00 00 | 00 00 00 00  globalY
+                             *    01 01 01 01 | 01 01 01 01 | 01 01 01 01
+                             *    ------------+-------------+------------
+                             *    02 02 02 02 | 02[02]02 02 | 02 02 02 02
+                             *    03 03 03 03 | 03 03 03 03 | 03 03 03 03
+                             *
+                             * 
+ * Assume we are trying to locate the id's for #33 + * + */ + threadIdSetter = (kernelState, globalGroupId, threadId) -> { + // (kernelState, globalGroupId, threadId) ->{ + kernelState.setLocalId(0, (threadId % localSize0)); // threadId % localWidth = (for 33 = 1 % 4 = 1) + kernelState.setLocalId(1, (threadId / localSize0)); // threadId / localWidth = (for 33 = 1 / 4 == 0) + + final int groupInset = globalGroupId % numGroups0; // 4%3 = 1 + kernelState.setGlobalId(0, ((groupInset * localSize0) + kernelState.getLocalIds()[0])); // 1*4+1=5 + + final int completeLines = (globalGroupId / numGroups0) * localSize1;// (4/3) * 2 + kernelState.setGlobalId(1, (completeLines + kernelState.getLocalIds()[1])); // 2+0 = 2 + kernelState.setGroupId(0, (globalGroupId % numGroups0)); + kernelState.setGroupId(1, (globalGroupId / numGroups0)); + }; + break; + case 3: + //Same as 2D actually turns out that localId[0] is identical for all three dims so could be hoisted out of conditional code + threadIdSetter = (kernelState, globalGroupId, threadId) -> { + // (kernelState, globalGroupId, threadId) ->{ + kernelState.setLocalId(0, (threadId % localSize0)); + + kernelState.setLocalId(1, ((threadId / localSize0) % localSize1)); + + // the thread id's span WxHxD so threadId/(WxH) should yield the local depth + kernelState.setLocalId(2, (threadId / (localSize0 * localSize1))); + + kernelState.setGlobalId(0, (((globalGroupId % numGroups0) * localSize0) + kernelState.getLocalIds()[0])); + + kernelState.setGlobalId(1, + ((((globalGroupId / numGroups0) * localSize1) % globalSize1) + kernelState.getLocalIds()[1])); + + kernelState.setGlobalId(2, + (((globalGroupId / (numGroups0 * numGroups1)) * localSize2) + kernelState.getLocalIds()[2])); + + kernelState.setGroupId(0, (globalGroupId % numGroups0)); + kernelState.setGroupId(1, ((globalGroupId / numGroups0) % numGroups1)); + kernelState.setGroupId(2, (globalGroupId / (numGroups0 * numGroups1))); + }; + break; + default: + throw new IllegalArgumentException("Expected 1,2 or 3 dimensions, found " + _settings.range.getDims()); + } + for (passId = 0; passId < _settings.passes; passId++) { + if (getCancelState() == CANCEL_STATUS_TRUE) { + break; + } + /** + * Note that we emulate OpenCL by creating one thread per localId (across the group). + * + * So threadCount == range.getLocalSize(0)*range.getLocalSize(1)*range.getLocalSize(2); + * + * For a 1D range of 12 groups of 4 we create 4 threads. One per localId(0). + * + * We also clone the kernel 4 times. One per thread. + * + * We create local barrier which has a width of 4 + * + * Thread-0 handles localId(0) (global 0,4,8) + * Thread-1 handles localId(1) (global 1,5,7) + * Thread-2 handles localId(2) (global 2,6,10) + * Thread-3 handles localId(3) (global 3,7,11) + * + * This allows all threads to synchronize using the local barrier. + * + * Initially the use of local buffers seems broken as the buffers appears to be per Kernel. + * Thankfully Kernel.clone() performs a shallow clone of all buffers (local and global) + * So each of the cloned kernels actually still reference the same underlying local/global buffers. + * + * If the kernel uses local buffers but does not use barriers then it is possible for different groups + * to see mutations from each other (unlike OpenCL), however if the kernel does not us barriers then it + * cannot assume any coherence in OpenCL mode either (the failure mode will be different but still wrong) + * + * So even JTP mode use of local buffers will need to use barriers. Not for the same reason as OpenCL but to keep groups in lockstep. + * + **/ + final int volume = _settings.range.volume(); + + int threadsActivated = + //threads; + Math.min(volume, threads); + + + + final CountDownLatch countdown = new CountDownLatch(threadsActivated); + + for (int id = 0; id < threadsActivated; id++) { + final int threadId = id; + + /** + * We clone one kernel for each thread. + * + * They will all share references to the same range, localBarrier and global/local buffers because the clone is shallow. + * We need clones so that each thread can assign 'state' (localId/globalId/groupId) without worrying + * about other threads. + */ + final Kernel kernelClone = kernel.clone(_settings.range); + final KernelState kernelState = kernelClone.getKernelState(); + kernelState.setPassId(passId); + +// if (threads == 1) { + kernelState.disableLocalBarrier(); +// } else { +// kernelState.setLocalBarrier(localBarrier); +// } + + threadPool.submit( + () -> { + try { + for (int globalGroupId = 0; globalGroupId < globalGroups; globalGroupId++) { + threadIdSetter.set(kernelState, globalGroupId, threadId); + if (kernelState.globalIds.get(0) < volume) + kernelClone.run(); + } + } catch (Throwable e) { + logger.log(Level.SEVERE, "Execution failed", e); + } finally { + //await(joinBarrier); // This thread will rendezvous with dispatch thread here. This is effectively a join. + countdown.countDown(); + } + }); + } - @Override public boolean isReleasable() { - return released; + try { + countdown.await(); + } catch (InterruptedException e) { + throw new RuntimeException(e); + } + //await(joinBarrier); // This dispatch thread waits for all worker threads here. + } + passId = PASS_ID_COMPLETED_EXECUTION; + } // execution mode == JTP + } + } finally { + passId = PASS_ID_COMPLETED_EXECUTION; + } + } + + private static void await(CyclicBarrier _barrier) { + try { + _barrier.await(); + } catch (final InterruptedException | BrokenBarrierException e) { + //e.printStackTrace(); + logger.severe(()->"await: " + e.getMessage()); + } + } + + private volatile KernelArg[] args = null; + + private boolean usesOopConversion = false; + + /** + * + * @param arg + * @return + * @throws AparapiException + */ + private boolean prepareOopConversionBuffer(KernelArg arg) throws AparapiException { + usesOopConversion = true; + final Class arrayClass = arg.getField().getType(); + ClassModel c = null; + boolean didReallocate = false; + + if (arg.getObjArrayElementModel() == null) { + final String tmp = arrayClass.getName().substring(2).replace('/', '.'); + final String arrayClassInDotForm = tmp.substring(0, tmp.length() - 1); + + if (logger.isLoggable(Level.FINE)) { + logger.fine("looking for type = " + arrayClassInDotForm); } - int getValue() { - return value; + // get ClassModel of obj array from entrypt.objectArrayFieldsClasses + c = entryPoint.getObjectArrayFieldsClasses().get(arrayClassInDotForm); + arg.setObjArrayElementModel(c); + } else { + c = arg.getObjArrayElementModel(); + } + assert c != null : "should find class for elements " + arrayClass.getName(); + + final int arrayBaseOffset = UnsafeWrapper.arrayBaseOffset(arrayClass); + final int arrayScale = UnsafeWrapper.arrayIndexScale(arrayClass); + + if (logger.isLoggable(Level.FINEST)) { + logger.finest("Syncing obj array type = " + arrayClass + " cvtd= " + c.clazz.getName() + + "arrayBaseOffset=" + arrayBaseOffset + " arrayScale=" + arrayScale); + } + + int objArraySize = 0; + Object newRef = null; + try { + newRef = arg.getField().get(kernel); + objArraySize = Array.getLength(newRef); + } catch (final IllegalAccessException e) { + throw new AparapiException(e); + } + + assert (newRef != null) && (objArraySize != 0) : "no data"; + + final int totalStructSize = c.getTotalStructSize(); + final int totalBufferSize = objArraySize * totalStructSize; + + // allocate ByteBuffer if first time or array changed + if ((arg.getObjArrayBuffer() == null) || (newRef != arg.getArray())) { + final ByteBuffer structBuffer = ByteBuffer.allocate(totalBufferSize); + arg.setObjArrayByteBuffer(structBuffer.order(ByteOrder.LITTLE_ENDIAN)); + arg.setObjArrayBuffer(arg.getObjArrayByteBuffer().array()); + didReallocate = true; + if (logger.isLoggable(Level.FINEST)) { + logger.finest("objArraySize = " + objArraySize + " totalStructSize= " + totalStructSize + " totalBufferSize=" + + totalBufferSize); } - } - final Awaiter awaiter = new Awaiter(); - ForkJoinPool.managedBlock(awaiter); - return awaiter.getValue(); - } - - int superAwait() throws InterruptedException, BrokenBarrierException { - return super.await(); - } - } - - // @FunctionalInterface - private interface ThreadIdSetter{ - void set(KernelState kernelState, int globalGroupId, int threadId); - } - - /** - * Execute using a Java thread pool, or sequentially, or using an alternative algorithm, usually as a result of failing to compile or execute OpenCL - */ - @SuppressWarnings("deprecation") - protected void executeJava(ExecutionSettings _settings, Device device) { - if (logger.isLoggable(Level.FINE)) { - logger.fine("executeJava: range = " + _settings.range + ", device = " + device); - } - boolean legacySequentialMode = kernel.getExecutionMode().equals(Kernel.EXECUTION_MODE.SEQ); - - passId = PASS_ID_PREPARING_EXECUTION; - _settings.profile.onEvent(ProfilingEvent.PREPARE_EXECUTE); - - try { - if (device == JavaDevice.ALTERNATIVE_ALGORITHM) { - if (kernel.hasFallbackAlgorithm()) { - for (passId = 0; passId < _settings.passes; ++passId) { - kernel.executeFallbackAlgorithm(_settings.range, passId); - } - } else { - boolean silently = true; // not having an alternative algorithm is the normal state, and does not need reporting - fallBackToNextDevice(_settings, (Exception) null, silently); + } else { + arg.getObjArrayByteBuffer().clear(); + } + + // copy the fields that the JNI uses + arg.setJavaArray(arg.getObjArrayBuffer()); + arg.setNumElements(objArraySize); + arg.setSizeInBytes(totalBufferSize); + + for (int j = 0; j < objArraySize; j++) { + int sizeWritten = 0; + + final Object object = UnsafeWrapper.getObject(newRef, arrayBaseOffset + (arrayScale * j)); + for (int i = 0; i < c.getStructMemberTypes().size(); i++) { + final TypeSpec t = c.getStructMemberTypes().get(i); + final long offset = c.getStructMemberOffsets().get(i); + + if (logger.isLoggable(Level.FINEST)) { + logger.finest("name = " + c.getStructMembers().get(i).getNameAndTypeEntry().getNameUTF8Entry().getUTF8() + " t= " + + t); + } + + switch (t) { + case I: { + final int x = UnsafeWrapper.getInt(object, offset); + arg.getObjArrayByteBuffer().putInt(x); + sizeWritten += t.getSize(); + break; + } + case F: { + final float x = UnsafeWrapper.getFloat(object, offset); + arg.getObjArrayByteBuffer().putFloat(x); + sizeWritten += t.getSize(); + break; + } + case J: { + final long x = UnsafeWrapper.getLong(object, offset); + arg.getObjArrayByteBuffer().putLong(x); + sizeWritten += t.getSize(); + break; + } + case Z: { + final boolean x = UnsafeWrapper.getBoolean(object, offset); + arg.getObjArrayByteBuffer().put(x == true ? (byte) 1 : (byte) 0); + // Booleans converted to 1 byte C chars for opencl + sizeWritten += TypeSpec.B.getSize(); + break; + } + case B: { + final byte x = UnsafeWrapper.getByte(object, offset); + arg.getObjArrayByteBuffer().put(x); + sizeWritten += t.getSize(); + break; + } + case D: { + throw new AparapiException("Double not implemented yet"); + } + default: + assert true == false : "typespec did not match anything"; + throw new AparapiException("Unhandled type in buffer conversion"); + } } - } else { - final int localSize0 = _settings.range.getLocalSize(0); - final int localSize1 = _settings.range.getLocalSize(1); - final int localSize2 = _settings.range.getLocalSize(2); - final int globalSize1 = _settings.range.getGlobalSize(1); - if (legacySequentialMode || device == JavaDevice.SEQUENTIAL) { - /** - * SEQ mode is useful for testing trivial logic, but kernels which use SEQ mode cannot be used if the - * product of localSize(0..3) is >1. So we can use multi-dim ranges but only if the local size is 1 in all dimensions. - * - * As a result of this barrier is only ever 1 work item wide and probably should be turned into a no-op. - * - * So we need to check if the range is valid here. If not we have no choice but to punt. - */ - if ((localSize0 * localSize1 * localSize2) > 1) { - throw new IllegalStateException("Can't run range with group size >1 sequentially. Barriers would deadlock!"); - } - - final Kernel kernelClone = kernel.clone(); - final KernelState kernelState = kernelClone.getKernelState(); - - kernelState.setRange(_settings.range); - kernelState.setGroupId(0, 0); - kernelState.setGroupId(1, 0); - kernelState.setGroupId(2, 0); - kernelState.setLocalId(0, 0); - kernelState.setLocalId(1, 0); - kernelState.setLocalId(2, 0); - kernelState.setLocalBarrier(new FJSafeCyclicBarrier(1)); - - for (passId = 0; passId < _settings.passes; passId++) { - if (getCancelState() == CANCEL_STATUS_TRUE) { - break; - } - kernelState.setPassId(passId); - - if (_settings.range.getDims() == 1) { - for (int id = 0; id < _settings.range.getGlobalSize(0); id++) { - kernelState.setGlobalId(0, id); - kernelClone.run(); - } - } - else if (_settings.range.getDims() == 2) { - for (int x = 0; x < _settings.range.getGlobalSize(0); x++) { - kernelState.setGlobalId(0, x); - - for (int y = 0; y < globalSize1; y++) { - kernelState.setGlobalId(1, y); - kernelClone.run(); - } - } - } - else if (_settings.range.getDims() == 3) { - for (int x = 0; x < _settings.range.getGlobalSize(0); x++) { - kernelState.setGlobalId(0, x); - for (int y = 0; y < globalSize1; y++) { - kernelState.setGlobalId(1, y); + // add padding here if needed + if (logger.isLoggable(Level.FINEST)) { + logger.finest("sizeWritten = " + sizeWritten + " totalStructSize= " + totalStructSize); + } - for (int z = 0; z < _settings.range.getGlobalSize(2); z++) { - kernelState.setGlobalId(2, z); - kernelClone.run(); - } + assert sizeWritten <= totalStructSize : "wrote too much into buffer"; - kernelClone.run(); - } - } - } - } - passId = PASS_ID_COMPLETED_EXECUTION; + while (sizeWritten < totalStructSize) { + if (logger.isLoggable(Level.FINEST)) { + logger.finest(arg.getName() + " struct pad byte = " + sizeWritten + " totalStructSize= " + totalStructSize); + } + arg.getObjArrayByteBuffer().put((byte) -1); + sizeWritten++; } - else { - if (device != JavaDevice.THREAD_POOL && kernel.getExecutionMode() != Kernel.EXECUTION_MODE.JTP) { - throw new AssertionError("unexpected JavaDevice or EXECUTION_MODE"); - } - final int threads = localSize0 * localSize1 * localSize2; - final int numGroups0 = _settings.range.getNumGroups(0); - final int numGroups1 = _settings.range.getNumGroups(1); - final int globalGroups = numGroups0 * numGroups1 * _settings.range.getNumGroups(2); - /** - * This joinBarrier is the barrier that we provide for the kernel threads to rendezvous with the current dispatch thread. - * So this barrier is threadCount+1 wide (the +1 is for the dispatch thread) - */ - final CyclicBarrier joinBarrier = new FJSafeCyclicBarrier(threads + 1); - - /** - * This localBarrier is only ever used by the kernels. If the kernel does not use the barrier the threads - * can get out of sync, we promised nothing in JTP mode. - * - * As with OpenCL all threads within a group must wait at the barrier or none. It is a user error (possible deadlock!) - * if the barrier is in a conditional that is only executed by some of the threads within a group. - * - * Kernel developer must understand this. - * - * This barrier is threadCount wide. We never hit the barrier from the dispatch thread. - */ - final CyclicBarrier localBarrier = new FJSafeCyclicBarrier(threads); - - final ThreadIdSetter threadIdSetter; - - if (_settings.range.getDims() == 1) { - threadIdSetter = new ThreadIdSetter() { - @Override - public void set(KernelState kernelState, int globalGroupId, int threadId) { - // (kernelState, globalGroupId, threadId) ->{ - kernelState.setLocalId(0, (threadId % localSize0)); - kernelState.setGlobalId(0, (threadId + (globalGroupId * threads))); - kernelState.setGroupId(0, globalGroupId); - } - }; - } - else if (_settings.range.getDims() == 2) { - - /** - * Consider a 12x4 grid of 4*2 local groups - *
-                   *                                             threads = 4*2 = 8
-                   *                                             localWidth=4
-                   *                                             localHeight=2
-                   *                                             globalWidth=12
-                   *                                             globalHeight=4
-                   *
-                   *    00 01 02 03 | 04 05 06 07 | 08 09 10 11
-                   *    12 13 14 15 | 16 17 18 19 | 20 21 22 23
-                   *    ------------+-------------+------------
-                   *    24 25 26 27 | 28 29 30 31 | 32 33 34 35
-                   *    36 37 38 39 | 40 41 42 43 | 44 45 46 47
-                   *
-                   *    00 01 02 03 | 00 01 02 03 | 00 01 02 03  threadIds : [0..7]*6
-                   *    04 05 06 07 | 04 05 06 07 | 04 05 06 07
-                   *    ------------+-------------+------------
-                   *    00 01 02 03 | 00 01 02 03 | 00 01 02 03
-                   *    04 05 06 07 | 04 05 06 07 | 04 05 06 07
-                   *
-                   *    00 00 00 00 | 01 01 01 01 | 02 02 02 02  groupId[0] : 0..6
-                   *    00 00 00 00 | 01 01 01 01 | 02 02 02 02
-                   *    ------------+-------------+------------
-                   *    00 00 00 00 | 01 01 01 01 | 02 02 02 02
-                   *    00 00 00 00 | 01 01 01 01 | 02 02 02 02
-                   *
-                   *    00 00 00 00 | 00 00 00 00 | 00 00 00 00  groupId[1] : 0..6
-                   *    00 00 00 00 | 00 00 00 00 | 00 00 00 00
-                   *    ------------+-------------+------------
-                   *    01 01 01 01 | 01 01 01 01 | 01 01 01 01
-                   *    01 01 01 01 | 01 01 01 01 | 01 01 01 01
-                   *
-                   *    00 01 02 03 | 08 09 10 11 | 16 17 18 19  globalThreadIds == threadId + groupId * threads;
-                   *    04 05 06 07 | 12 13 14 15 | 20 21 22 23
-                   *    ------------+-------------+------------
-                   *    24 25 26 27 | 32[33]34 35 | 40 41 42 43
-                   *    28 29 30 31 | 36 37 38 39 | 44 45 46 47
-                   *
-                   *    00 01 02 03 | 00 01 02 03 | 00 01 02 03  localX = threadId % localWidth; (for globalThreadId 33 = threadId = 01 : 01%4 =1)
-                   *    00 01 02 03 | 00 01 02 03 | 00 01 02 03
-                   *    ------------+-------------+------------
-                   *    00 01 02 03 | 00[01]02 03 | 00 01 02 03
-                   *    00 01 02 03 | 00 01 02 03 | 00 01 02 03
-                   *
-                   *    00 00 00 00 | 00 00 00 00 | 00 00 00 00  localY = threadId /localWidth  (for globalThreadId 33 = threadId = 01 : 01/4 =0)
-                   *    01 01 01 01 | 01 01 01 01 | 01 01 01 01
-                   *    ------------+-------------+------------
-                   *    00 00 00 00 | 00[00]00 00 | 00 00 00 00
-                   *    01 01 01 01 | 01 01 01 01 | 01 01 01 01
-                   *
-                   *    00 01 02 03 | 04 05 06 07 | 08 09 10 11  globalX=
-                   *    00 01 02 03 | 04 05 06 07 | 08 09 10 11     groupsPerLineWidth=globalWidth/localWidth (=12/4 =3)
-                   *    ------------+-------------+------------     groupInset =groupId%groupsPerLineWidth (=4%3 = 1)
-                   *    00 01 02 03 | 04[05]06 07 | 08 09 10 11
-                   *    00 01 02 03 | 04 05 06 07 | 08 09 10 11     globalX = groupInset*localWidth+localX (= 1*4+1 = 5)
-                   *
-                   *    00 00 00 00 | 00 00 00 00 | 00 00 00 00  globalY
-                   *    01 01 01 01 | 01 01 01 01 | 01 01 01 01
-                   *    ------------+-------------+------------
-                   *    02 02 02 02 | 02[02]02 02 | 02 02 02 02
-                   *    03 03 03 03 | 03 03 03 03 | 03 03 03 03
-                   *
-                   * 
- * Assume we are trying to locate the id's for #33 - * - */ - threadIdSetter = new ThreadIdSetter() { - @Override - public void set(KernelState kernelState, int globalGroupId, int threadId) { - // (kernelState, globalGroupId, threadId) ->{ - kernelState.setLocalId(0, (threadId % localSize0)); // threadId % localWidth = (for 33 = 1 % 4 = 1) - kernelState.setLocalId(1, (threadId / localSize0)); // threadId / localWidth = (for 33 = 1 / 4 == 0) - - final int groupInset = globalGroupId % numGroups0; // 4%3 = 1 - kernelState.setGlobalId(0, ((groupInset * localSize0) + kernelState.getLocalIds()[0])); // 1*4+1=5 - - final int completeLines = (globalGroupId / numGroups0) * localSize1;// (4/3) * 2 - kernelState.setGlobalId(1, (completeLines + kernelState.getLocalIds()[1])); // 2+0 = 2 - kernelState.setGroupId(0, (globalGroupId % numGroups0)); - kernelState.setGroupId(1, (globalGroupId / numGroups0)); - } - }; - } - else if (_settings.range.getDims() == 3) { - //Same as 2D actually turns out that localId[0] is identical for all three dims so could be hoisted out of conditional code - threadIdSetter = new ThreadIdSetter() { - @Override - public void set(KernelState kernelState, int globalGroupId, int threadId) { - // (kernelState, globalGroupId, threadId) ->{ - kernelState.setLocalId(0, (threadId % localSize0)); - - kernelState.setLocalId(1, ((threadId / localSize0) % localSize1)); - - // the thread id's span WxHxD so threadId/(WxH) should yield the local depth - kernelState.setLocalId(2, (threadId / (localSize0 * localSize1))); - - kernelState.setGlobalId(0, (((globalGroupId % numGroups0) * localSize0) + kernelState.getLocalIds()[0])); - - kernelState.setGlobalId(1, - ((((globalGroupId / numGroups0) * localSize1) % globalSize1) + kernelState.getLocalIds()[1])); - - kernelState.setGlobalId(2, - (((globalGroupId / (numGroups0 * numGroups1)) * localSize2) + kernelState.getLocalIds()[2])); - - kernelState.setGroupId(0, (globalGroupId % numGroups0)); - kernelState.setGroupId(1, ((globalGroupId / numGroups0) % numGroups1)); - kernelState.setGroupId(2, (globalGroupId / (numGroups0 * numGroups1))); - } - }; - } - else - throw new IllegalArgumentException("Expected 1,2 or 3 dimensions, found " + _settings.range.getDims()); - for (passId = 0; passId < _settings.passes; passId++) { - if (getCancelState() == CANCEL_STATUS_TRUE) { - break; - } - /** - * Note that we emulate OpenCL by creating one thread per localId (across the group). - * - * So threadCount == range.getLocalSize(0)*range.getLocalSize(1)*range.getLocalSize(2); - * - * For a 1D range of 12 groups of 4 we create 4 threads. One per localId(0). - * - * We also clone the kernel 4 times. One per thread. - * - * We create local barrier which has a width of 4 - * - * Thread-0 handles localId(0) (global 0,4,8) - * Thread-1 handles localId(1) (global 1,5,7) - * Thread-2 handles localId(2) (global 2,6,10) - * Thread-3 handles localId(3) (global 3,7,11) - * - * This allows all threads to synchronize using the local barrier. - * - * Initially the use of local buffers seems broken as the buffers appears to be per Kernel. - * Thankfully Kernel.clone() performs a shallow clone of all buffers (local and global) - * So each of the cloned kernels actually still reference the same underlying local/global buffers. - * - * If the kernel uses local buffers but does not use barriers then it is possible for different groups - * to see mutations from each other (unlike OpenCL), however if the kernel does not us barriers then it - * cannot assume any coherence in OpenCL mode either (the failure mode will be different but still wrong) - * - * So even JTP mode use of local buffers will need to use barriers. Not for the same reason as OpenCL but to keep groups in lockstep. - * - **/ - for (int id = 0; id < threads; id++) { - final int threadId = id; - - /** - * We clone one kernel for each thread. - * - * They will all share references to the same range, localBarrier and global/local buffers because the clone is shallow. - * We need clones so that each thread can assign 'state' (localId/globalId/groupId) without worrying - * about other threads. - */ - final Kernel kernelClone = kernel.clone(); - final KernelState kernelState = kernelClone.getKernelState(); - kernelState.setRange(_settings.range); - kernelState.setPassId(passId); - - if (threads == 1) { - kernelState.disableLocalBarrier(); - } - else { - kernelState.setLocalBarrier(localBarrier); - } - - threadPool.submit( - // () -> { - new Runnable() { - public void run() { - try { - for (int globalGroupId = 0; globalGroupId < globalGroups; globalGroupId++) { - threadIdSetter.set(kernelState, globalGroupId, threadId); - kernelClone.run(); - } - } - catch (RuntimeException | Error e) { - logger.log(Level.SEVERE, "Execution failed", e); - } - finally { - await(joinBarrier); // This thread will rendezvous with dispatch thread here. This is effectively a join. - } + } + + assert arg.getObjArrayByteBuffer().arrayOffset() == 0 : "should be zero"; + + return didReallocate; + } + + private void extractOopConversionBuffer(KernelArg arg) throws AparapiException { + final Class arrayClass = arg.getField().getType(); + final ClassModel c = arg.getObjArrayElementModel(); + assert c != null : "should find class for elements: " + arrayClass.getName(); + assert arg.getArray() != null : "array is null"; + + final int arrayBaseOffset = UnsafeWrapper.arrayBaseOffset(arrayClass); + final int arrayScale = UnsafeWrapper.arrayIndexScale(arrayClass); + if (logger.isLoggable(Level.FINEST)) { + logger.finest("Syncing field:" + arg.getName() + ", bb=" + arg.getObjArrayByteBuffer() + ", type = " + arrayClass); + } + + int objArraySize = 0; + try { + objArraySize = Array.getLength(arg.getField().get(kernel)); + } catch (final IllegalAccessException e) { + throw new AparapiException(e); + } + + assert objArraySize > 0 : "should be > 0"; + + final int totalStructSize = c.getTotalStructSize(); + // int totalBufferSize = objArraySize * totalStructSize; + // assert arg.objArrayBuffer.length == totalBufferSize : "size should match"; + + arg.getObjArrayByteBuffer().rewind(); + + for (int j = 0; j < objArraySize; j++) { + int sizeWritten = 0; + final Object object = UnsafeWrapper.getObject(arg.getArray(), arrayBaseOffset + (arrayScale * j)); + for (int i = 0; i < c.getStructMemberTypes().size(); i++) { + final TypeSpec t = c.getStructMemberTypes().get(i); + final long offset = c.getStructMemberOffsets().get(i); + switch (t) { + case I: { + // read int value from buffer and store into obj in the array + final int x = arg.getObjArrayByteBuffer().getInt(); + if (logger.isLoggable(Level.FINEST)) { + logger.finest("fType = " + t.getShortName() + " x= " + x); + } + UnsafeWrapper.putInt(object, offset, x); + sizeWritten += t.getSize(); + break; + } + case F: { + final float x = arg.getObjArrayByteBuffer().getFloat(); + if (logger.isLoggable(Level.FINEST)) { + logger.finest("fType = " + t.getShortName() + " x= " + x); + } + UnsafeWrapper.putFloat(object, offset, x); + sizeWritten += t.getSize(); + break; + } + case J: { + final long x = arg.getObjArrayByteBuffer().getLong(); + if (logger.isLoggable(Level.FINEST)) { + logger.finest("fType = " + t.getShortName() + " x= " + x); } - }); - } - - await(joinBarrier); // This dispatch thread waits for all worker threads here. - } - passId = PASS_ID_COMPLETED_EXECUTION; - } // execution mode == JTP - } - } finally { - passId = PASS_ID_COMPLETED_EXECUTION; - } - } - - private static void await(CyclicBarrier _barrier) { - try { - _barrier.await(); - } catch (final InterruptedException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (final BrokenBarrierException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - - private KernelArg[] args = null; - - private boolean usesOopConversion = false; - - /** - * - * @param arg - * @return - * @throws AparapiException - */ - private boolean prepareOopConversionBuffer(KernelArg arg) throws AparapiException { - usesOopConversion = true; - final Class arrayClass = arg.getField().getType(); - ClassModel c = null; - boolean didReallocate = false; - - if (arg.getObjArrayElementModel() == null) { - final String tmp = arrayClass.getName().substring(2).replace('/', '.'); - final String arrayClassInDotForm = tmp.substring(0, tmp.length() - 1); - - if (logger.isLoggable(Level.FINE)) { - logger.fine("looking for type = " + arrayClassInDotForm); - } - - // get ClassModel of obj array from entrypt.objectArrayFieldsClasses - c = entryPoint.getObjectArrayFieldsClasses().get(arrayClassInDotForm); - arg.setObjArrayElementModel(c); - } else { - c = arg.getObjArrayElementModel(); - } - assert c != null : "should find class for elements " + arrayClass.getName(); - - final int arrayBaseOffset = UnsafeWrapper.arrayBaseOffset(arrayClass); - final int arrayScale = UnsafeWrapper.arrayIndexScale(arrayClass); - - if (logger.isLoggable(Level.FINEST)) { - logger.finest("Syncing obj array type = " + arrayClass + " cvtd= " + c.getClassWeAreModelling().getName() - + "arrayBaseOffset=" + arrayBaseOffset + " arrayScale=" + arrayScale); - } - - int objArraySize = 0; - Object newRef = null; - try { - newRef = arg.getField().get(kernel); - objArraySize = Array.getLength(newRef); - } catch (final IllegalAccessException e) { - throw new AparapiException(e); - } - - assert (newRef != null) && (objArraySize != 0) : "no data"; - - final int totalStructSize = c.getTotalStructSize(); - final int totalBufferSize = objArraySize * totalStructSize; - - // allocate ByteBuffer if first time or array changed - if ((arg.getObjArrayBuffer() == null) || (newRef != arg.getArray())) { - final ByteBuffer structBuffer = ByteBuffer.allocate(totalBufferSize); - arg.setObjArrayByteBuffer(structBuffer.order(ByteOrder.LITTLE_ENDIAN)); - arg.setObjArrayBuffer(arg.getObjArrayByteBuffer().array()); - didReallocate = true; - if (logger.isLoggable(Level.FINEST)) { - logger.finest("objArraySize = " + objArraySize + " totalStructSize= " + totalStructSize + " totalBufferSize=" - + totalBufferSize); - } - } else { - arg.getObjArrayByteBuffer().clear(); - } - - // copy the fields that the JNI uses - arg.setJavaArray(arg.getObjArrayBuffer()); - arg.setNumElements(objArraySize); - arg.setSizeInBytes(totalBufferSize); - - for (int j = 0; j < objArraySize; j++) { - int sizeWritten = 0; - - final Object object = UnsafeWrapper.getObject(newRef, arrayBaseOffset + (arrayScale * j)); - for (int i = 0; i < c.getStructMemberTypes().size(); i++) { - final TypeSpec t = c.getStructMemberTypes().get(i); - final long offset = c.getStructMemberOffsets().get(i); + UnsafeWrapper.putLong(object, offset, x); + sizeWritten += t.getSize(); + break; + } + case Z: { + final byte x = arg.getObjArrayByteBuffer().get(); + if (logger.isLoggable(Level.FINEST)) { + logger.finest("fType = " + t.getShortName() + " x= " + x); + } + UnsafeWrapper.putBoolean(object, offset, (x == 1)); + // Booleans converted to 1 byte C chars for open cl + sizeWritten += TypeSpec.B.getSize(); + break; + } + case B: { + final byte x = arg.getObjArrayByteBuffer().get(); + if (logger.isLoggable(Level.FINEST)) { + logger.finest("fType = " + t.getShortName() + " x= " + x); + } + UnsafeWrapper.putByte(object, offset, x); + sizeWritten += t.getSize(); + break; + } + case D: { + throw new AparapiException("Double not implemented yet"); + } + default: + assert true == false : "typespec did not match anything"; + throw new AparapiException("Unhandled type in buffer conversion"); + } + } + // add padding here if needed if (logger.isLoggable(Level.FINEST)) { - logger.finest("name = " + c.getStructMembers().get(i).getNameAndTypeEntry().getNameUTF8Entry().getUTF8() + " t= " - + t); + logger.finest("sizeWritten = " + sizeWritten + " totalStructSize= " + totalStructSize); } - switch (t) { - case I: { - final int x = UnsafeWrapper.getInt(object, offset); - arg.getObjArrayByteBuffer().putInt(x); - sizeWritten += t.getSize(); - break; - } - case F: { - final float x = UnsafeWrapper.getFloat(object, offset); - arg.getObjArrayByteBuffer().putFloat(x); - sizeWritten += t.getSize(); - break; - } - case J: { - final long x = UnsafeWrapper.getLong(object, offset); - arg.getObjArrayByteBuffer().putLong(x); - sizeWritten += t.getSize(); - break; - } - case Z: { - final boolean x = UnsafeWrapper.getBoolean(object, offset); - arg.getObjArrayByteBuffer().put(x == true ? (byte) 1 : (byte) 0); - // Booleans converted to 1 byte C chars for opencl - sizeWritten += TypeSpec.B.getSize(); - break; - } - case B: { - final byte x = UnsafeWrapper.getByte(object, offset); - arg.getObjArrayByteBuffer().put(x); - sizeWritten += t.getSize(); - break; - } - case D: { - throw new AparapiException("Double not implemented yet"); - } - default: - assert true == false : "typespec did not match anything"; - throw new AparapiException("Unhandled type in buffer conversion"); - } - } + assert sizeWritten <= totalStructSize : "wrote too much into buffer"; - // add padding here if needed - if (logger.isLoggable(Level.FINEST)) { - logger.finest("sizeWritten = " + sizeWritten + " totalStructSize= " + totalStructSize); - } + while (sizeWritten < totalStructSize) { + // skip over pad bytes + arg.getObjArrayByteBuffer().get(); + sizeWritten++; + } + } + } + + private void restoreObjects() throws AparapiException { + for (int i = 0; i < argc; i++) { + final KernelArg arg = args[i]; + if ((arg.getType() & ARG_OBJ_ARRAY_STRUCT) != 0) { + extractOopConversionBuffer(arg); + } + } + } + + private boolean updateKernelArrayRefs() throws AparapiException { + boolean needsSync = false; + + for (int i = 0; i < argc; i++) { + final KernelArg arg = args[i]; + try { + if ((arg.getType() & ARG_ARRAY) != 0) { + Object newArrayRef; + newArrayRef = arg.getField().get(kernel); + + if (newArrayRef == null) { + throw new IllegalStateException("Cannot send null refs to kernel, reverting to java"); + } + + String fieldName = arg.getField().getName(); + int arrayLength = Array.getLength(newArrayRef); + Integer privateMemorySize = ClassModel.getPrivateMemorySizeFromField(arg.getField()); + if (privateMemorySize == null) { + privateMemorySize = ClassModel.getPrivateMemorySizeFromFieldName(fieldName); + } + if (privateMemorySize != null) { + if (arrayLength > privateMemorySize) { + throw new IllegalStateException("__private array field " + fieldName + " has illegal length " + arrayLength + + " > " + privateMemorySize); + } + } + + if ((arg.getType() & ARG_OBJ_ARRAY_STRUCT) != 0) { + prepareOopConversionBuffer(arg); + } else { + // set up JNI fields for normal arrays + arg.setJavaArray(newArrayRef); + arg.setNumElements(arrayLength); + arg.setSizeInBytes(arg.getNumElements() * arg.getPrimitiveSize()); + + if (((args[i].getType() & ARG_EXPLICIT) != 0) && puts.contains(newArrayRef)) { + args[i].setType(args[i].getType() | ARG_EXPLICIT_WRITE); + // System.out.println("detected an explicit write " + args[i].name); + puts.remove(newArrayRef); + } + } - assert sizeWritten <= totalStructSize : "wrote too much into buffer"; + if (newArrayRef != arg.getArray()) { + needsSync = true; - while (sizeWritten < totalStructSize) { - if (logger.isLoggable(Level.FINEST)) { - logger.finest(arg.getName() + " struct pad byte = " + sizeWritten + " totalStructSize= " + totalStructSize); - } - arg.getObjArrayByteBuffer().put((byte) -1); - sizeWritten++; - } - } - - assert arg.getObjArrayByteBuffer().arrayOffset() == 0 : "should be zero"; - - return didReallocate; - } - - private void extractOopConversionBuffer(KernelArg arg) throws AparapiException { - final Class arrayClass = arg.getField().getType(); - final ClassModel c = arg.getObjArrayElementModel(); - assert c != null : "should find class for elements: " + arrayClass.getName(); - assert arg.getArray() != null : "array is null"; - - final int arrayBaseOffset = UnsafeWrapper.arrayBaseOffset(arrayClass); - final int arrayScale = UnsafeWrapper.arrayIndexScale(arrayClass); - if (logger.isLoggable(Level.FINEST)) { - logger.finest("Syncing field:" + arg.getName() + ", bb=" + arg.getObjArrayByteBuffer() + ", type = " + arrayClass); - } - - int objArraySize = 0; - try { - objArraySize = Array.getLength(arg.getField().get(kernel)); - } catch (final IllegalAccessException e) { - throw new AparapiException(e); - } - - assert objArraySize > 0 : "should be > 0"; - - final int totalStructSize = c.getTotalStructSize(); - // int totalBufferSize = objArraySize * totalStructSize; - // assert arg.objArrayBuffer.length == totalBufferSize : "size should match"; - - arg.getObjArrayByteBuffer().rewind(); - - for (int j = 0; j < objArraySize; j++) { - int sizeWritten = 0; - final Object object = UnsafeWrapper.getObject(arg.getArray(), arrayBaseOffset + (arrayScale * j)); - for (int i = 0; i < c.getStructMemberTypes().size(); i++) { - final TypeSpec t = c.getStructMemberTypes().get(i); - final long offset = c.getStructMemberOffsets().get(i); - switch (t) { - case I: { - // read int value from buffer and store into obj in the array - final int x = arg.getObjArrayByteBuffer().getInt(); - if (logger.isLoggable(Level.FINEST)) { - logger.finest("fType = " + t.getShortName() + " x= " + x); - } - UnsafeWrapper.putInt(object, offset, x); - sizeWritten += t.getSize(); - break; - } - case F: { - final float x = arg.getObjArrayByteBuffer().getFloat(); - if (logger.isLoggable(Level.FINEST)) { - logger.finest("fType = " + t.getShortName() + " x= " + x); - } - UnsafeWrapper.putFloat(object, offset, x); - sizeWritten += t.getSize(); - break; - } - case J: { - final long x = arg.getObjArrayByteBuffer().getLong(); - if (logger.isLoggable(Level.FINEST)) { - logger.finest("fType = " + t.getShortName() + " x= " + x); - } - UnsafeWrapper.putLong(object, offset, x); - sizeWritten += t.getSize(); - break; - } - case Z: { - final byte x = arg.getObjArrayByteBuffer().get(); - if (logger.isLoggable(Level.FINEST)) { - logger.finest("fType = " + t.getShortName() + " x= " + x); - } - UnsafeWrapper.putBoolean(object, offset, (x == 1 ? true : false)); - // Booleans converted to 1 byte C chars for open cl - sizeWritten += TypeSpec.B.getSize(); - break; - } - case B: { - final byte x = arg.getObjArrayByteBuffer().get(); - if (logger.isLoggable(Level.FINEST)) { - logger.finest("fType = " + t.getShortName() + " x= " + x); - } - UnsafeWrapper.putByte(object, offset, x); - sizeWritten += t.getSize(); - break; - } - case D: { - throw new AparapiException("Double not implemented yet"); - } - default: - assert true == false : "typespec did not match anything"; - throw new AparapiException("Unhandled type in buffer conversion"); + if (logger.isLoggable(Level.FINE)) { + logger.fine("saw newArrayRef for " + arg.getName() + " = " + newArrayRef + ", newArrayLen = " + + Array.getLength(newArrayRef)); + } + } + + arg.setArray(newArrayRef); + assert arg.getArray() != null : "null array ref"; + } else if ((arg.getType() & ARG_APARAPI_BUFFER) != 0) { + // TODO: check if the 2D/3D array is changed. + // can Arrays.equals help? + needsSync = true; // Always need syn + Object buffer = new Object(); + try { + buffer = arg.getField().get(kernel); + } catch (IllegalAccessException e) { + e.printStackTrace(); + } + int numDims = arg.getNumDims(); + Object subBuffer = buffer; + int[] dims = new int[numDims]; + for (int d = 0; d < numDims - 1; d++) { + dims[d] = Array.getLength(subBuffer); + subBuffer = Array.get(subBuffer, 0); + } + dims[numDims - 1] = Array.getLength(subBuffer); + arg.setDims(dims); + + int primitiveSize = getPrimitiveSize(arg.getType()); + int totalElements = 1; + for (int d = 0; d < numDims; d++) { + totalElements *= dims[d]; + } + arg.setJavaBuffer(buffer); + arg.setSizeInBytes(totalElements * primitiveSize); + arg.setArray(buffer); + } + } catch (final IllegalArgumentException | IllegalAccessException e) { + e.printStackTrace(); } - } - - // add padding here if needed - if (logger.isLoggable(Level.FINEST)) { - logger.finest("sizeWritten = " + sizeWritten + " totalStructSize= " + totalStructSize); - } - - assert sizeWritten <= totalStructSize : "wrote too much into buffer"; - - while (sizeWritten < totalStructSize) { - // skip over pad bytes - arg.getObjArrayByteBuffer().get(); - sizeWritten++; - } - } - } - - private void restoreObjects() throws AparapiException { - for (int i = 0; i < argc; i++) { - final KernelArg arg = args[i]; - if ((arg.getType() & ARG_OBJ_ARRAY_STRUCT) != 0) { - extractOopConversionBuffer(arg); - } - } - } - - private boolean updateKernelArrayRefs() throws AparapiException { - boolean needsSync = false; - - for (int i = 0; i < argc; i++) { - final KernelArg arg = args[i]; - try { - if ((arg.getType() & ARG_ARRAY) != 0) { - Object newArrayRef; - newArrayRef = arg.getField().get(kernel); - - if (newArrayRef == null) { - throw new IllegalStateException("Cannot send null refs to kernel, reverting to java"); - } - - String fieldName = arg.getField().getName(); - int arrayLength = Array.getLength(newArrayRef); - Integer privateMemorySize = ClassModel.getPrivateMemorySizeFromField(arg.getField()); - if (privateMemorySize == null) { - privateMemorySize = ClassModel.getPrivateMemorySizeFromFieldName(fieldName); - } - if (privateMemorySize != null) { - if (arrayLength > privateMemorySize) { - throw new IllegalStateException("__private array field " + fieldName + " has illegal length " + arrayLength - + " > " + privateMemorySize); - } - } - - if ((arg.getType() & ARG_OBJ_ARRAY_STRUCT) != 0) { - prepareOopConversionBuffer(arg); - } else { - // set up JNI fields for normal arrays - arg.setJavaArray(newArrayRef); - arg.setNumElements(arrayLength); - arg.setSizeInBytes(arg.getNumElements() * arg.getPrimitiveSize()); - - if (((args[i].getType() & ARG_EXPLICIT) != 0) && puts.contains(newArrayRef)) { - args[i].setType(args[i].getType() | ARG_EXPLICIT_WRITE); - // System.out.println("detected an explicit write " + args[i].name); - puts.remove(newArrayRef); - } - } - - if (newArrayRef != arg.getArray()) { - needsSync = true; - - if (logger.isLoggable(Level.FINE)) { - logger.fine("saw newArrayRef for " + arg.getName() + " = " + newArrayRef + ", newArrayLen = " - + Array.getLength(newArrayRef)); - } - } - - arg.setArray(newArrayRef); - assert arg.getArray() != null : "null array ref"; - } else if ((arg.getType() & ARG_APARAPI_BUFFER) != 0) { - // TODO: check if the 2D/3D array is changed. - // can Arrays.equals help? - needsSync = true; // Always need syn - Object buffer = new Object(); - try { - buffer = arg.getField().get(kernel); - } catch (IllegalAccessException e) { - e.printStackTrace(); - } - int numDims = arg.getNumDims(); - Object subBuffer = buffer; - int[] dims = new int[numDims]; - for (int d = 0; d < numDims - 1; d++) { - dims[d] = Array.getLength(subBuffer); - subBuffer = Array.get(subBuffer, 0); - } - dims[numDims - 1] = Array.getLength(subBuffer); - arg.setDims(dims); - - int primitiveSize = getPrimitiveSize(arg.getType()); - int totalElements = 1; - for (int d = 0; d < numDims; d++) { - totalElements *= dims[d]; - } - arg.setJavaBuffer(buffer); - arg.setSizeInBytes(totalElements * primitiveSize); - arg.setArray(buffer); + } + return needsSync; + } + + @SuppressWarnings("deprecation") + private Kernel executeOpenCL(ExecutionSettings _settings) throws AparapiException { + + + assert(args != null); + + // native side will reallocate array buffers if necessary + int returnValue; + //synchronized (kernel) { + // Read the array refs after kernel may have changed them + // We need to do this as input to computing the localSize + final boolean needSync = updateKernelArrayRefs(); + + if (needSync && logger.isLoggable(Level.FINE)) { + logger.fine("Need to resync arrays on " + kernel); } - } catch (final IllegalArgumentException e) { - e.printStackTrace(); - } catch (final IllegalAccessException e) { - e.printStackTrace(); - } - } - return needsSync; - } - - @SuppressWarnings("deprecation") - private Kernel executeOpenCL(ExecutionSettings _settings) throws AparapiException { - - // Read the array refs after kernel may have changed them - // We need to do this as input to computing the localSize - assert args != null : "args should not be null"; - final boolean needSync = updateKernelArrayRefs(); - if (needSync && logger.isLoggable(Level.FINE)) { - logger.fine("Need to resync arrays on " + kernel); - } - - // native side will reallocate array buffers if necessary - int returnValue = runKernelJNI(jniContextHandle, _settings.range, needSync, _settings.passes, inBufferRemote, outBufferRemote); - if (returnValue != 0) { - String reason = "OpenCL execution seems to have failed (runKernelJNI returned " + returnValue + ")"; - return fallBackToNextDevice(_settings, new AparapiException(reason)); - } - - if (usesOopConversion == true) { - restoreObjects(); - } - - if (logger.isLoggable(Level.FINE)) { - logger.fine("executeOpenCL completed. " + _settings.range); - } - - return kernel; - } - - @SuppressWarnings("deprecation") - synchronized private Kernel fallBackByExecutionMode(ExecutionSettings _settings) { - isFallBack = true; - if (kernel.hasNextExecutionMode()) { - kernel.tryNextExecutionMode(); - if (logger.isLoggable(Level.WARNING)) { - logger.warning("Trying next execution mode " + kernel.getExecutionMode()); - } - } else { - kernel.setFallbackExecutionMode(); - } - recreateRange(_settings); - return executeInternalInner(_settings); - } - - private void recreateRange(ExecutionSettings _settings) { - if (_settings.range.isLocalIsDerived() && !_settings.legacyExecutionMode) { - Device device = kernel.getTargetDevice(); - Range result; - switch (_settings.range.getDims()) { - case 1: { - result = Range.create(device, _settings.range.getGlobalSize_0()); - break; + + returnValue = runKernelJNI(jniContextHandle, _settings.range, needSync, _settings.passes, inBufferRemote, outBufferRemote); + //} + if (returnValue != 0) { + String reason = "OpenCL execution seems to have failed (runKernelJNI returned " + returnValue + ')'; + return fallBackToNextDevice(_settings, new AparapiException(reason)); + } + + if (usesOopConversion) { + restoreObjects(); + } + + if (logger.isLoggable(Level.FINE)) { + logger.fine("executeOpenCL completed. " + _settings.range); + } + + return kernel; + } + + @SuppressWarnings("deprecation") + private Kernel fallBackByExecutionMode(ExecutionSettings _settings) { + isFallBack = true; + if (kernel.hasNextExecutionMode()) { + kernel.tryNextExecutionMode(); + if (logger.isLoggable(Level.WARNING)) { + logger.warning("Trying next execution mode " + kernel.getExecutionMode()); } - case 2: { - result = Range.create2D(device, _settings.range.getGlobalSize_0(), _settings.range.getGlobalSize_1()); - break; + } else { + kernel.setFallbackExecutionMode(); + } + recreateRange(kernel.getTargetDevice(), _settings); + return executeInternalInner(_settings); + } + + public static void recreateRange(Device device, ExecutionSettings _settings) { + if (!_settings.legacyExecutionMode) { + Range result; + if (_settings.range.isLocalIsDerived()) { + switch (_settings.range.getDims()) { + case 1: { + result = Range.create(device, _settings.range.getGlobalSize_0()); + break; + } + case 2: { + result = Range.create2D(device, _settings.range.getGlobalSize_0(), _settings.range.getGlobalSize_1()); + break; + } + case 3: { + result = Range.create3D(device, _settings.range.getGlobalSize_0(), _settings.range.getGlobalSize_1(), _settings.range.getGlobalSize_2()); + break; + } + default: { + throw new AssertionError("Range.getDims() = " + _settings.range.getDims()); + } + } + } else { + switch (_settings.range.getDims()) { + case 1: { + result = Range.create(device, _settings.range.getGlobalSize_0(), _settings.range.getLocalSize(0)); + break; + } + case 2: { + result = Range.create2D(device, _settings.range.getGlobalSize_0(), _settings.range.getGlobalSize_1(), + _settings.range.getLocalSize(0), _settings.range.getLocalSize(1)); + break; + } + case 3: { + result = Range.create3D(device, _settings.range.getGlobalSize_0(), _settings.range.getGlobalSize_1(), + _settings.range.getGlobalSize_2(), _settings.range.getLocalSize(0), + _settings.range.getLocalSize(1), _settings.range.getLocalSize(2)); + break; + } + default: { + throw new AssertionError("Range.getDims() = " + _settings.range.getDims()); + } + } } - case 3: { - result = Range.create3D(device, _settings.range.getGlobalSize_0(), _settings.range.getGlobalSize_1(), _settings.range.getGlobalSize_2()); - break; + _settings.range = result; + } + } + + private Kernel fallBackToNextDevice(ExecutionSettings _settings, String _reason) { + + return fallBackToNextDevice(_settings, new AparapiException(_reason)); + } + + @SuppressWarnings("deprecation") + private Kernel fallBackToNextDevice(ExecutionSettings _settings, Exception _exception) { + return fallBackToNextDevice(_settings, _exception, false); + } + + @SuppressWarnings("deprecation") + private Kernel fallBackToNextDevice(final ExecutionSettings _settings, Exception _exception, boolean _silently) { + isFallBack = true; + + final KernelDeviceProfile profiler = _settings.profile.profiler(_settings.device()); + + profiler.on(ProfilingEvent.EXECUTED); + + if (_settings.legacyExecutionMode) { + if (!_silently && logger.isLoggable(Level.WARNING)) { + logger.warning("Execution mode " + kernel.getExecutionMode() + " failed for " + kernel + ": " + _exception.getMessage()); + _exception.printStackTrace(); } - default: { - throw new AssertionError("Range.getDims() = " + _settings.range.getDims()); + return fallBackByExecutionMode(_settings); + } else { + KernelPreferences preferences = KernelManager.instance().getPreferences(kernel); + if (!_silently && logger.isLoggable(Level.WARNING)) { + logger.warning("Device failed for " + kernel + ": " + _exception.getMessage()); } - } - _settings.range = result; - } - } - - private Kernel fallBackToNextDevice(ExecutionSettings _settings, String _reason) { - return fallBackToNextDevice(_settings, new AparapiException(_reason)); - } - - @SuppressWarnings("deprecation") - synchronized private Kernel fallBackToNextDevice(ExecutionSettings _settings, Exception _exception) { - return fallBackToNextDevice(_settings, _exception, false); - } - - @SuppressWarnings("deprecation") - synchronized private Kernel fallBackToNextDevice(ExecutionSettings _settings, Exception _exception, boolean _silently) { - isFallBack = true; - _settings.profile.onEvent(ProfilingEvent.EXECUTED); - if (_settings.legacyExecutionMode) { - if (!_silently && logger.isLoggable(Level.WARNING)) { - logger.warning("Execution mode " + kernel.getExecutionMode() + " failed for " + kernel + ": " + _exception.getMessage()); - _exception.printStackTrace(); - } - return fallBackByExecutionMode(_settings); - } else { - KernelPreferences preferences = KernelManager.instance().getPreferences(kernel); - if (!_silently && logger.isLoggable(Level.WARNING)) { - logger.warning("Device failed for " + kernel + ": " + _exception.getMessage()); - } - - preferences.markPreferredDeviceFailed(); + + preferences.markPreferredDeviceFailed(); // Device nextDevice = preferences.getPreferredDevice(kernel); // @@ -1144,647 +1214,717 @@ synchronized private Kernel fallBackToNextDevice(ExecutionSettings _settings, Ex // } // throw new RuntimeException(_exception); // } - if (!_silently && logger.isLoggable(Level.WARNING)) { - _exception.printStackTrace(); - logger.warning("Trying next device: " + describeDevice()); - } - } - - recreateRange(_settings); - return executeInternalInner(_settings); - } - - @SuppressWarnings("deprecation") - public synchronized Kernel execute(String _entrypoint, final Range _range, final int _passes) { - executing = true; - try { - clearCancelMultiPass(); - KernelProfile profile = KernelManager.instance().getProfile(kernel.getClass()); - KernelPreferences preferences = KernelManager.instance().getPreferences(kernel); - boolean legacyExecutionMode = kernel.getExecutionMode() != Kernel.EXECUTION_MODE.AUTO; - - ExecutionSettings settings = new ExecutionSettings(preferences, profile, _entrypoint, _range, _passes, legacyExecutionMode); - // Two Kernels of the same class share the same KernelPreferences object, and since failure (fallback) generally mutates - // the preferences object, we must lock it. Note this prevents two Kernels of the same class executing simultaneously. - synchronized (preferences) { - return executeInternalOuter(settings); - } - } finally { - executing = false; - clearCancelMultiPass(); - } - } - - private synchronized Kernel executeInternalOuter(ExecutionSettings _settings) { - try { - return executeInternalInner(_settings); - } finally { - if (kernel.isAutoCleanUpArrays() &&_settings.range.getGlobalSize_0() != 0) { - cleanUpArrays(); - } - } - } - - @SuppressWarnings("deprecation") - private synchronized Kernel executeInternalInner(ExecutionSettings _settings) { - - if (_settings.range == null) { - throw new IllegalStateException("range can't be null"); - } - - EXECUTION_MODE requestedExecutionMode = kernel.getExecutionMode(); - - if (requestedExecutionMode.isOpenCL() && _settings.range.getDevice() != null && !(_settings.range.getDevice() instanceof OpenCLDevice)) { - fallBackToNextDevice(_settings, "OpenCL EXECUTION_MODE was requested but Device supplied was not an OpenCLDevice"); - } - - Device device = _settings.range.getDevice(); - boolean userSpecifiedDevice = true; - if (device == null) { - userSpecifiedDevice = false; - if (!_settings.legacyExecutionMode) { - device = _settings.preferences.getPreferredDevice(kernel); - if (device == null) { - // the default fallback when KernelPreferences has run out of options is JTP - device = JavaDevice.THREAD_POOL; - } - } else { - if (requestedExecutionMode == EXECUTION_MODE.JTP) { - device = JavaDevice.THREAD_POOL; - } else if (requestedExecutionMode == EXECUTION_MODE.SEQ) { - device = JavaDevice.SEQUENTIAL; - } - } - } else { - boolean compatible = isDeviceCompatible(device); - if (!compatible) { - throw new AssertionError("user supplied Device incompatible with current EXECUTION_MODE or getTargetDevice(); device = " - + device.getShortDescription() + "; kernel = " + kernel); - } - } - - try { - OpenCLDevice openCLDevice = device instanceof OpenCLDevice ? (OpenCLDevice) device : null; - - int jniFlags = 0; - // for legacy reasons use old logic where Kernel.EXECUTION_MODE is not AUTO - if (_settings.legacyExecutionMode && !userSpecifiedDevice && requestedExecutionMode.isOpenCL()) { - if (requestedExecutionMode.equals(EXECUTION_MODE.GPU)) { - // Get the best GPU - openCLDevice = (OpenCLDevice) KernelManager.DeprecatedMethods.bestGPU(); - jniFlags |= JNI_FLAG_USE_GPU; // this flag might be redundant now. - if (openCLDevice == null) { - return fallBackToNextDevice(_settings, "GPU request can't be honored, no GPU device"); - } - } else if (requestedExecutionMode.equals(EXECUTION_MODE.ACC)) { - // Get the best ACC - openCLDevice = (OpenCLDevice) KernelManager.DeprecatedMethods.bestACC(); - jniFlags |= JNI_FLAG_USE_ACC; // this flag might be redundant now. - if (openCLDevice == null) { - return fallBackToNextDevice(_settings, "ACC request can't be honored, no ACC device"); - } - } else { - // We fetch the first CPU device - openCLDevice = (OpenCLDevice) KernelManager.DeprecatedMethods.firstDevice(Device.TYPE.CPU); - if (openCLDevice == null) { - return fallBackToNextDevice(_settings, "CPU request can't be honored, no CPU device"); - } + if (!_silently && logger.isLoggable(Level.WARNING)) { + _exception.printStackTrace(); + logger.warning("Trying next device: " + describeDevice()); } - } else { - if (device.getType() == Device.TYPE.GPU) { - jniFlags |= JNI_FLAG_USE_GPU; // this flag might be redundant now. - } else if (device.getType() == Device.TYPE.ACC) { - jniFlags |= JNI_FLAG_USE_ACC; // this flag might be redundant now. + } + + recreateRange(kernel.getTargetDevice(), _settings); + return executeInternalInner(_settings); + } + + @SuppressWarnings("deprecation") + public Kernel execute(String _entrypoint, final Range _range, final int _passes) { + executing = true; + try { + + clearCancelMultiPass(); + + KernelManager kernels = KernelManager.instance(); + + KernelProfile profile = kernels.getProfile(kernel.getClass()); + + KernelPreferences preferences = kernels.getPreferences(kernel); + + boolean legacyExecutionMode = kernel.getExecutionMode() != Kernel.EXECUTION_MODE.AUTO; + + //synchronized (preferences) { + ExecutionSettings settings = new ExecutionSettings(preferences, profile, _entrypoint, _range, _passes, legacyExecutionMode); + // Two Kernels of the same class share the same KernelPreferences object, and since failure (fallback) generally mutates + // the preferences object, we must lock it. Note this prevents two Kernels of the same class executing simultaneously. + return executeInternalOuter(settings); + //} + + } finally { + executing = false; + clearCancelMultiPass(); + } + } + + private Kernel executeInternalOuter(ExecutionSettings _settings) { + try { + return executeInternalInner(_settings); + } finally { + if (kernel.isAutoCleanUpArrays() && _settings.range.getGlobalSize_0() != 0) { + cleanUpArrays(); } - } - if (device == null && openCLDevice != null) { - device = openCLDevice; - } - assert device != null : "No device available"; - _settings.profile.onStart(device); - /* for backward compatibility reasons we still honor execution mode */ - boolean isOpenCl = requestedExecutionMode.isOpenCL() || device instanceof OpenCLDevice; - if (isOpenCl) { - if ((entryPoint == null) || (isFallBack)) { - if (entryPoint == null) { - try { - final ClassModel classModel = ClassModel.createClassModel(kernel.getClass()); - entryPoint = classModel.getEntrypoint(_settings.entrypoint, kernel); - _settings.profile.onEvent(ProfilingEvent.CLASS_MODEL_BUILT); - } catch (final Exception exception) { - _settings.profile.onEvent(ProfilingEvent.CLASS_MODEL_BUILT); - return fallBackToNextDevice(_settings, exception); - } - } - - if ((entryPoint != null)) { - synchronized (Kernel.class) { // This seems to be needed because of a race condition uncovered with issue #68 http://code.google.com/p/aparapi/issues/detail?id=68 - - // jniFlags |= (Config.enableProfiling ? JNI_FLAG_ENABLE_PROFILING : 0); - // jniFlags |= (Config.enableProfilingCSV ? JNI_FLAG_ENABLE_PROFILING_CSV | JNI_FLAG_ENABLE_PROFILING : 0); - // jniFlags |= (Config.enableVerboseJNI ? JNI_FLAG_ENABLE_VERBOSE_JNI : 0); - // jniFlags |= (Config.enableVerboseJNIOpenCLResourceTracking ? JNI_FLAG_ENABLE_VERBOSE_JNI_OPENCL_RESOURCE_TRACKING :0); - // jniFlags |= (kernel.getExecutionMode().equals(Kernel.EXECUTION_MODE.GPU) ? JNI_FLAG_USE_GPU : 0); - // Init the device to check capabilities before emitting the - // code that requires the capabilities. - jniContextHandle = initJNI(kernel, openCLDevice, jniFlags); // openCLDevice will not be null here - _settings.profile.onEvent(ProfilingEvent.INIT_JNI); - } // end of synchronized! issue 68 - - if (jniContextHandle == 0) { - return fallBackToNextDevice(_settings, "initJNI failed to return a valid handle"); - } - - final String extensions = getExtensionsJNI(jniContextHandle); - capabilitiesSet = new HashSet(); - - final StringTokenizer strTok = new StringTokenizer(extensions); - while (strTok.hasMoreTokens()) { - capabilitiesSet.add(strTok.nextToken()); - } - - if (logger.isLoggable(Level.FINE)) { - logger.fine("Capabilities initialized to :" + capabilitiesSet.toString()); - } - - if (entryPoint.requiresDoublePragma() && !hasFP64Support()) { - return fallBackToNextDevice(_settings, "FP64 required but not supported"); - } - - if (entryPoint.requiresByteAddressableStorePragma() && !hasByteAddressableStoreSupport()) { - return fallBackToNextDevice(_settings, "Byte addressable stores required but not supported"); - } - - final boolean all32AtomicsAvailable = hasGlobalInt32BaseAtomicsSupport() - && hasGlobalInt32ExtendedAtomicsSupport() && hasLocalInt32BaseAtomicsSupport() - && hasLocalInt32ExtendedAtomicsSupport(); - - if (entryPoint.requiresAtomic32Pragma() && !all32AtomicsAvailable) { - - return fallBackToNextDevice(_settings, "32 bit Atomics required but not supported"); - } - - String openCL; - synchronized (openCLCache) { - openCL = openCLCache.get(kernel.getClass()); - if (openCL == null) { + } + } + + @SuppressWarnings("deprecation") + private Kernel executeInternalInner(final ExecutionSettings settings) { + + EXECUTION_MODE requestedExecutionMode = kernel.getExecutionMode(); + + ExecutionSettings _settings = settings.validate(this); + if (_settings == null) + return kernel; + final Device device = settings.device(); + if (device == null) + return kernel; + + + OpenCLDevice openCLDevice = device instanceof OpenCLDevice ? (OpenCLDevice) device : null; + + KernelDeviceProfile profiler = _settings.profile.start(device); + try { + assert device != null : "No device available"; + + /* for backward compatibility reasons we still honor execution mode */ + boolean isOpenCl = requestedExecutionMode.isOpenCL() || device instanceof OpenCLDevice; + if (isOpenCl) { + if ((entryPoint == null) || (isFallBack)) { + final Class kernelClass = kernel.getClass(); + if (entryPoint == null) { try { - openCL = KernelWriter.writeToString(entryPoint); - if (logger.isLoggable(Level.INFO)) { - logger.info(openCL); - } - else if (Config.enableShowGeneratedOpenCL) { - System.out.println(openCL); - } - _settings.profile.onEvent(ProfilingEvent.OPENCL_GENERATED); - openCLCache.put(kernel.getClass(), openCL); + final ClassModel classModel = ClassModel.createClassModel(kernelClass); + entryPoint = classModel.getEntrypoint(_settings.entrypoint, kernel); + profiler.on(ProfilingEvent.CLASS_MODEL_BUILT); + } catch (final Exception exception) { + profiler.on(ProfilingEvent.CLASS_MODEL_BUILT); + return fallBackToNextDevice(_settings, exception); } - catch (final CodeGenException codeGenException) { - openCLCache.put(kernel.getClass(), CODE_GEN_ERROR_MARKER); - _settings.profile.onEvent(ProfilingEvent.OPENCL_GENERATED); - return fallBackToNextDevice(_settings, codeGenException); + } + + if ((entryPoint != null)) { + + //synchronized (kernel) { + + // jniFlags |= (Config.enableProfiling ? JNI_FLAG_ENABLE_PROFILING : 0); + // jniFlags |= (Config.enableProfilingCSV ? JNI_FLAG_ENABLE_PROFILING_CSV | JNI_FLAG_ENABLE_PROFILING : 0); + // jniFlags |= (Config.enableVerboseJNI ? JNI_FLAG_ENABLE_VERBOSE_JNI : 0); + // jniFlags |= (Config.enableVerboseJNIOpenCLResourceTracking ? JNI_FLAG_ENABLE_VERBOSE_JNI_OPENCL_RESOURCE_TRACKING :0); + // jniFlags |= (kernel.getExecutionMode().equals(Kernel.EXECUTION_MODE.GPU) ? JNI_FLAG_USE_GPU : 0); + // Init the device to check capabilities before emitting the + // code that requires the capabilities. + jniContextHandle = initJNI(kernel, openCLDevice, _settings.jniFlags); // openCLDevice will not be null here + //} // end of synchronized! issue 68 + profiler.on(ProfilingEvent.INIT_JNI); + + if (jniContextHandle == 0) { + return fallBackToNextDevice(_settings, "initJNI failed to return a valid handle"); } - } - else { - if (openCL.equals(CODE_GEN_ERROR_MARKER)) { - _settings.profile.onEvent(ProfilingEvent.OPENCL_GENERATED); - boolean silently = true; // since we must have already reported the CodeGenException - return fallBackToNextDevice(_settings, null, silently); + + final String extensions; + //synchronized (kernel) { + extensions = getExtensionsJNI(jniContextHandle); + //} + + final StringTokenizer strTok = new StringTokenizer(extensions); + capabilitiesSet = new HashSet<>(); + while (strTok.hasMoreTokens()) { + capabilitiesSet.add(strTok.nextToken()); } - } - } - - // Send the string to OpenCL to compile it, or if the compiled binary is already cached on JNI side just empty string to use cached binary - long handle; - if (BINARY_CACHING_DISABLED) { - handle = buildProgramJNI(jniContextHandle, openCL, ""); - } else { - synchronized (seenBinaryKeys) { - String binaryKey = kernel.getClass().getName() + ":" + device.getDeviceId(); - if (seenBinaryKeys.contains(binaryKey)) { - // use cached binary - logger.log(Level.INFO, "reusing cached binary for " + binaryKey); - handle = buildProgramJNI(jniContextHandle, "", binaryKey); + + if (logger.isLoggable(Level.FINE)) { + logger.fine("Capabilities initialized to :" + capabilitiesSet.toString()); } - else { - // create and cache binary - logger.log(Level.INFO, "compiling new binary for " + binaryKey); - handle = buildProgramJNI(jniContextHandle, openCL, binaryKey); - seenBinaryKeys.add(binaryKey); + + if (entryPoint.requiresDoublePragma() && !hasFP64Support()) { + return fallBackToNextDevice(_settings, "FP64 required but not supported"); } - } - } - _settings.profile.onEvent(ProfilingEvent.OPENCL_COMPILED); - if (handle == 0) { - return fallBackToNextDevice(_settings, "OpenCL compile failed"); - } - - args = new KernelArg[entryPoint.getReferencedFields().size()]; - int i = 0; - - for (final Field field : entryPoint.getReferencedFields()) { - try { - field.setAccessible(true); - args[i] = new KernelArg(); - args[i].setName(field.getName()); - args[i].setField(field); - if ((field.getModifiers() & Modifier.STATIC) == Modifier.STATIC) { - args[i].setType(args[i].getType() | ARG_STATIC); + + if (entryPoint.requiresByteAddressableStorePragma() && !hasByteAddressableStoreSupport()) { + return fallBackToNextDevice(_settings, "Byte addressable stores required but not supported"); + } + + final boolean all32AtomicsAvailable = hasGlobalInt32BaseAtomicsSupport() + && hasGlobalInt32ExtendedAtomicsSupport() && hasLocalInt32BaseAtomicsSupport() + && hasLocalInt32ExtendedAtomicsSupport(); + + if (entryPoint.requiresAtomic32Pragma() && !all32AtomicsAvailable) { + + return fallBackToNextDevice(_settings, "32 bit Atomics required but not supported"); } - final Class type = field.getType(); - if (type.isArray()) { - - if (field.getAnnotation(Local.class) != null || args[i].getName().endsWith(Kernel.LOCAL_SUFFIX)) { - args[i].setType(args[i].getType() | ARG_LOCAL); - } else if ((field.getAnnotation(Constant.class) != null) - || args[i].getName().endsWith(Kernel.CONSTANT_SUFFIX)) { - args[i].setType(args[i].getType() | ARG_CONSTANT); - } else { - args[i].setType(args[i].getType() | ARG_GLOBAL); - } - if (isExplicit()) { - args[i].setType(args[i].getType() | ARG_EXPLICIT); - } - // for now, treat all write arrays as read-write, see bugzilla issue 4859 - // we might come up with a better solution later - args[i].setType(args[i].getType() - | (entryPoint.getArrayFieldAssignments().contains(field.getName()) ? (ARG_WRITE | ARG_READ) : 0)); - args[i].setType(args[i].getType() - | (entryPoint.getArrayFieldAccesses().contains(field.getName()) ? ARG_READ : 0)); - // args[i].type |= ARG_GLOBAL; - - if (type.getName().startsWith("[L")) { - args[i].setArray(null); // will get updated in updateKernelArrayRefs - args[i].setType(args[i].getType() - | (ARG_ARRAY | ARG_OBJ_ARRAY_STRUCT | ARG_WRITE | ARG_READ)); - - if (logger.isLoggable(Level.FINE)) { - logger.fine("tagging " + args[i].getName() + " as (ARG_ARRAY | ARG_OBJ_ARRAY_STRUCT | ARG_WRITE | ARG_READ)"); - } - } else if (type.getName().startsWith("[[")) { - - try { - setMultiArrayType(args[i], type); - } catch (AparapiException e) { - return fallBackToNextDevice(_settings, "failed to set kernel arguement " - + args[i].getName() + ". Aparapi only supports 2D and 3D arrays."); - } - } else { - - args[i].setArray(null); // will get updated in updateKernelArrayRefs - args[i].setType(args[i].getType() | ARG_ARRAY); - - args[i].setType(args[i].getType() | (type.isAssignableFrom(float[].class) ? ARG_FLOAT : 0)); - args[i].setType(args[i].getType() | (type.isAssignableFrom(int[].class) ? ARG_INT : 0)); - args[i].setType(args[i].getType() | (type.isAssignableFrom(boolean[].class) ? ARG_BOOLEAN : 0)); - args[i].setType(args[i].getType() | (type.isAssignableFrom(byte[].class) ? ARG_BYTE : 0)); - args[i].setType(args[i].getType() | (type.isAssignableFrom(char[].class) ? ARG_CHAR : 0)); - args[i].setType(args[i].getType() | (type.isAssignableFrom(double[].class) ? ARG_DOUBLE : 0)); - args[i].setType(args[i].getType() | (type.isAssignableFrom(long[].class) ? ARG_LONG : 0)); - args[i].setType(args[i].getType() | (type.isAssignableFrom(short[].class) ? ARG_SHORT : 0)); - - // arrays whose length is used will have an int arg holding - // the length as a kernel param - if (entryPoint.getArrayFieldArrayLengthUsed().contains(args[i].getName())) { - args[i].setType(args[i].getType() | ARG_ARRAYLENGTH); - } - - if (type.getName().startsWith("[L")) { - args[i].setType(args[i].getType() | (ARG_OBJ_ARRAY_STRUCT | ARG_WRITE | ARG_READ)); - if (logger.isLoggable(Level.FINE)) { - logger.fine("tagging " + args[i].getName() - + " as (ARG_OBJ_ARRAY_STRUCT | ARG_WRITE | ARG_READ)"); - } - } - } - } else if (type.isAssignableFrom(float.class)) { - args[i].setType(args[i].getType() | ARG_PRIMITIVE); - args[i].setType(args[i].getType() | ARG_FLOAT); - } else if (type.isAssignableFrom(int.class)) { - args[i].setType(args[i].getType() | ARG_PRIMITIVE); - args[i].setType(args[i].getType() | ARG_INT); - } else if (type.isAssignableFrom(double.class)) { - args[i].setType(args[i].getType() | ARG_PRIMITIVE); - args[i].setType(args[i].getType() | ARG_DOUBLE); - } else if (type.isAssignableFrom(long.class)) { - args[i].setType(args[i].getType() | ARG_PRIMITIVE); - args[i].setType(args[i].getType() | ARG_LONG); - } else if (type.isAssignableFrom(boolean.class)) { - args[i].setType(args[i].getType() | ARG_PRIMITIVE); - args[i].setType(args[i].getType() | ARG_BOOLEAN); - } else if (type.isAssignableFrom(byte.class)) { - args[i].setType(args[i].getType() | ARG_PRIMITIVE); - args[i].setType(args[i].getType() | ARG_BYTE); - } else if (type.isAssignableFrom(char.class)) { - args[i].setType(args[i].getType() | ARG_PRIMITIVE); - args[i].setType(args[i].getType() | ARG_CHAR); - } else if (type.isAssignableFrom(short.class)) { - args[i].setType(args[i].getType() | ARG_PRIMITIVE); - args[i].setType(args[i].getType() | ARG_SHORT); + String openCL; + boolean isInfoLogging = logger.isLoggable(Level.INFO); + //synchronized (openCLCache) { + openCL = openCLCache.get(kernelClass); + if (openCL == null) { + try { + openCL = KernelWriter.writeToString(entryPoint); + if (isInfoLogging) { + logger.info(openCL); + } else if (Config.enableShowGeneratedOpenCL) { + System.out.println(openCL); + } + profiler.on(ProfilingEvent.OPENCL_GENERATED); + openCLCache.put(kernelClass, openCL); + } catch (final CodeGenException codeGenException) { + openCLCache.put(kernelClass, CODE_GEN_ERROR_MARKER); + profiler.on(ProfilingEvent.OPENCL_GENERATED); + return fallBackToNextDevice(_settings, codeGenException); + } + } else { + if (openCL.equals(CODE_GEN_ERROR_MARKER)) { + profiler.on(ProfilingEvent.OPENCL_GENERATED); + boolean silently = true; // since we must have already reported the CodeGenException + return fallBackToNextDevice(_settings, null, silently); + } + } + //} + + // Send the string to OpenCL to compile it, or if the compiled binary is already cached on JNI side just empty string to use cached binary + long handle; + if (BINARY_CACHING_DISABLED) { + //synchronized (kernel) { + handle = buildProgramJNI(jniContextHandle, openCL, ""); + //} + } else { + //synchronized (seenBinaryKeys) { + String binaryKey = kernelClass.getName() + ':' + device.getDeviceId(); + if (seenBinaryKeys.contains(binaryKey)) { + // use cached binary + if (isInfoLogging) + logger.log(Level.INFO, "reusing cached binary for " + binaryKey); + //synchronized (kernel) { + handle = buildProgramJNI(jniContextHandle, "", binaryKey); + //} + } else { + // create and cache binary + if (isInfoLogging) + logger.log(Level.INFO, "compiling new binary for " + binaryKey); + //synchronized (kernel) { + handle = buildProgramJNI(jniContextHandle, openCL, binaryKey); + //} + seenBinaryKeys.add(binaryKey); + } + //} } - // System.out.printf("in execute, arg %d %s %08x\n", i,args[i].name,args[i].type ); - } catch (final IllegalArgumentException e) { - e.printStackTrace(); - } - - args[i].setPrimitiveSize(getPrimitiveSize(args[i].getType())); - - if (logger.isLoggable(Level.FINE)) { - logger.fine("arg " + i + ", " + args[i].getName() + ", type=" + Integer.toHexString(args[i].getType()) - + ", primitiveSize=" + args[i].getPrimitiveSize()); - } - - i++; - } - - // at this point, i = the actual used number of arguments - // (private buffers do not get treated as arguments) - - argc = i; - - setArgsJNI(jniContextHandle, args, argc); - _settings.profile.onEvent(ProfilingEvent.PREPARE_EXECUTE); - try { - executeOpenCL(_settings); - isFallBack = false; - } catch (final AparapiException e) { - fallBackToNextDevice(_settings, e); - } - } else { // (entryPoint != null) && !entryPoint.shouldFallback() - fallBackToNextDevice(_settings, "failed to locate entrypoint"); - } - } else { // (entryPoint == null) || (isFallBack) - try { - executeOpenCL(_settings); - isFallBack = false; - } catch (final AparapiException e) { - fallBackToNextDevice(_settings, e); - } + profiler.on(ProfilingEvent.OPENCL_COMPILED); + if (handle == 0) { + return fallBackToNextDevice(_settings, "OpenCL compile failed"); + } + + List referencedFields = entryPoint.getReferencedFields(); + + KernelArg[] args = new KernelArg[referencedFields.size()]; + this.args = args; + int i = 0; + + for (final Field field : referencedFields) { + KernelArg ai; + try { + field.setAccessible(true); + args[i] = ai = new KernelArg(); + ai.setName(field.getName()); + ai.setField(field); + if ((field.getModifiers() & Modifier.STATIC) == Modifier.STATIC) { + ai.setType(ai.getType() | ARG_STATIC); + } + + final Class type = field.getType(); + if (type.isArray()) { + + if (field.getAnnotation(Local.class) != null || ai.getName().endsWith(Kernel.LOCAL_SUFFIX)) { + ai.setType(ai.getType() | ARG_LOCAL); + } else if ((field.getAnnotation(Constant.class) != null) + || ai.getName().endsWith(Kernel.CONSTANT_SUFFIX)) { + ai.setType(ai.getType() | ARG_CONSTANT); + } else { + ai.setType(ai.getType() | ARG_GLOBAL); + } + if (isExplicit()) { + ai.setType(ai.getType() | ARG_EXPLICIT); + } + // for now, treat all write arrays as read-write, see bugzilla issue 4859 + // we might come up with a better solution later + ai.setType(ai.getType() + | (entryPoint.getArrayFieldAssignments().contains(field.getName()) ? (ARG_WRITE | ARG_READ) : 0)); + ai.setType(ai.getType() + | (entryPoint.getArrayFieldAccesses().contains(field.getName()) ? ARG_READ : 0)); + // args[i].type |= ARG_GLOBAL; + + if (type.getName().startsWith("[L")) { + ai.setArray(null); // will get updated in updateKernelArrayRefs + ai.setType(ai.getType() + | (ARG_ARRAY | ARG_OBJ_ARRAY_STRUCT | ARG_WRITE | ARG_READ)); + + if (logger.isLoggable(Level.FINE)) { + logger.fine("tagging " + ai.getName() + " as (ARG_ARRAY | ARG_OBJ_ARRAY_STRUCT | ARG_WRITE | ARG_READ)"); + } + } else if (type.getName().startsWith("[[")) { + + try { + setMultiArrayType(ai, type); + } catch (AparapiException e) { + return fallBackToNextDevice(_settings, "failed to set kernel arguement " + + ai.getName() + ". Aparapi only supports 2D and 3D arrays."); + } + } else { + + ai.setArray(null); // will get updated in updateKernelArrayRefs + ai.setType(ai.getType() | ARG_ARRAY); + + ai.setType(ai.getType() | (type.isAssignableFrom(float[].class) ? ARG_FLOAT : 0)); + ai.setType(ai.getType() | (type.isAssignableFrom(int[].class) ? ARG_INT : 0)); + ai.setType(ai.getType() | (type.isAssignableFrom(boolean[].class) ? ARG_BOOLEAN : 0)); + ai.setType(ai.getType() | (type.isAssignableFrom(byte[].class) ? ARG_BYTE : 0)); + ai.setType(ai.getType() | (type.isAssignableFrom(char[].class) ? ARG_CHAR : 0)); + ai.setType(ai.getType() | (type.isAssignableFrom(double[].class) ? ARG_DOUBLE : 0)); + ai.setType(ai.getType() | (type.isAssignableFrom(long[].class) ? ARG_LONG : 0)); + ai.setType(ai.getType() | (type.isAssignableFrom(short[].class) ? ARG_SHORT : 0)); + + // arrays whose length is used will have an int arg holding + // the length as a kernel param + if (entryPoint.getArrayFieldArrayLengthUsed().contains(ai.getName())) { + ai.setType(ai.getType() | ARG_ARRAYLENGTH); + } + + if (type.getName().startsWith("[L")) { + ai.setType(ai.getType() | (ARG_OBJ_ARRAY_STRUCT | ARG_WRITE | ARG_READ)); + if (logger.isLoggable(Level.FINE)) { + logger.fine("tagging " + ai.getName() + + " as (ARG_OBJ_ARRAY_STRUCT | ARG_WRITE | ARG_READ)"); + } + } + } + } else if (type.isAssignableFrom(float.class)) { + ai.setType(ai.getType() | ARG_PRIMITIVE); + ai.setType(ai.getType() | ARG_FLOAT); + } else if (type.isAssignableFrom(int.class)) { + ai.setType(ai.getType() | ARG_PRIMITIVE); + ai.setType(ai.getType() | ARG_INT); + } else if (type.isAssignableFrom(double.class)) { + ai.setType(ai.getType() | ARG_PRIMITIVE); + ai.setType(ai.getType() | ARG_DOUBLE); + } else if (type.isAssignableFrom(long.class)) { + ai.setType(ai.getType() | ARG_PRIMITIVE); + ai.setType(ai.getType() | ARG_LONG); + } else if (type.isAssignableFrom(boolean.class)) { + ai.setType(ai.getType() | ARG_PRIMITIVE); + ai.setType(ai.getType() | ARG_BOOLEAN); + } else if (type.isAssignableFrom(byte.class)) { + ai.setType(ai.getType() | ARG_PRIMITIVE); + ai.setType(ai.getType() | ARG_BYTE); + } else if (type.isAssignableFrom(char.class)) { + ai.setType(ai.getType() | ARG_PRIMITIVE); + ai.setType(ai.getType() | ARG_CHAR); + } else if (type.isAssignableFrom(short.class)) { + ai.setType(ai.getType() | ARG_PRIMITIVE); + ai.setType(ai.getType() | ARG_SHORT); + } + // System.out.printf("in execute, arg %d %s %08x\n", i,args[i].name,args[i].type ); + + ai.setPrimitiveSize(getPrimitiveSize(ai.getType())); + + if (logger.isLoggable(Level.FINE)) { + logger.fine("arg " + i + ", " + ai.getName() + ", type=" + Integer.toHexString(ai.getType()) + + ", primitiveSize=" + ai.getPrimitiveSize()); + } + + i++; + + } catch (final IllegalArgumentException e) { + //e.printStackTrace(); + throw new RuntimeException(e); + } + + + } + + // at this point, i = the actual used number of arguments + // (private buffers do not get treated as arguments) + + argc = i; + + //synchronized (kernel) { + setArgsJNI(jniContextHandle, args, argc); + //} + profiler.on(ProfilingEvent.PREPARE_EXECUTE); + try { + executeOpenCL(_settings); + isFallBack = false; + } catch (final AparapiException e) { + fallBackToNextDevice(_settings, e); + } + } else { // (entryPoint != null) && !entryPoint.shouldFallback() + fallBackToNextDevice(_settings, "failed to locate entrypoint"); + } + } else { // (entryPoint == null) || (isFallBack) + try { + executeOpenCL(_settings); + isFallBack = false; + } catch (final AparapiException e) { + fallBackToNextDevice(_settings, e); + } + } + } else { // isOpenCL + if (!(device instanceof JavaDevice)) { + fallBackToNextDevice(_settings, "Non-OpenCL Kernel.EXECUTION_MODE requested but device is not a JavaDevice "); + } + executeJava(_settings); + } + + if (Config.enableExecutionModeReporting) { + System.out.println("execution complete: " + kernel); + } + + return kernel; + } finally { + if (device!=null) { + profiler.on(ProfilingEvent.EXECUTED); + maybeReportProfile(device, _settings); + } + } + } + + @Override + public String toString() { + return "KernelRunner{" + kernel + '}'; + } + + private String describeDevice() { + Device device = KernelManager.instance().getPreferences(kernel).getPreferredDevice(kernel); + return (device == null) ? "" : device.getShortDescription(); + } + + private static void maybeReportProfile(Device device, ExecutionSettings _settings) { + if (Config.dumpProfileOnExecution) { + StringBuilder report = new StringBuilder(); + report.append(KernelDeviceProfile.getTableHeader()).append('\n'); + report.append(_settings.profile.deviceProfiles.get(device).getLastAsTableRow()); + System.out.println(report); + } + } + + @SuppressWarnings("deprecation") + private boolean isDeviceCompatible(Device device) { + Kernel.EXECUTION_MODE mode = kernel.getExecutionMode(); + if (mode != Kernel.EXECUTION_MODE.AUTO) { + switch (device.getType()) { + case GPU: + return mode == Kernel.EXECUTION_MODE.GPU; + case CPU: + return mode == Kernel.EXECUTION_MODE.CPU; + case JTP: + return mode == Kernel.EXECUTION_MODE.JTP; + case SEQ: + return mode == Kernel.EXECUTION_MODE.SEQ; + case ACC: + return mode == Kernel.EXECUTION_MODE.ACC; + default: + return false; + } + } else { + return kernel.isAllowDevice(device); + //return (device == kernel.getTargetDevice()); + } + } + + public int getCancelState() { + return inBufferRemoteInt.get(0); + } + + public void cancelMultiPass() { + inBufferRemoteInt.put(0, CANCEL_STATUS_TRUE); + } + + private void clearCancelMultiPass() { + inBufferRemoteInt.put(0, CANCEL_STATUS_FALSE); + } + +// /** +// * Returns the index of the current pass, or one of two special constants with negative values to indicate special progress states. Those constants are +// * {@link #PASS_ID_PREPARING_EXECUTION} to indicate that the Kernel has started executing but not reached the initial pass, or +// * {@link #PASS_ID_COMPLETED_EXECUTION} to indicate that execution is complete (possibly due to early termination via {@link #cancelMultiPass()}), i.e. the Kernel +// * is idle. {@link #PASS_ID_COMPLETED_EXECUTION} is also returned before the first execution has been invoked. +// * +// *

This can be used, for instance, to update a visual progress bar. +// * +// * @see #execute(String, Range, int) +// */ +// public int getCurrentPass() { +// if (!executing) { +// return PASS_ID_COMPLETED_EXECUTION; +// } +// +// if (kernel.isRunningCL()) { +// return getCurrentPassRemote(); +// } else { +// return getCurrentPassLocal(); +// } +// } + + /** + * True while any of the {@code execute()} methods are in progress. + */ + public boolean isExecuting() { + return executing; + } + + protected int getCurrentPassRemote() { + return outBufferRemoteInt.get(0); + } + +// private int getCurrentPassLocal() { +// return passId; +// } + + private static int getPrimitiveSize(int type) { + if ((type & ARG_FLOAT) != 0) { + return 4; + } else if ((type & ARG_INT) != 0) { + return 4; + } else if ((type & ARG_BYTE) != 0) { + return 1; + } else if ((type & ARG_CHAR) != 0) { + return 2; + } else if ((type & ARG_BOOLEAN) != 0) { + return 1; + } else if ((type & ARG_SHORT) != 0) { + return 2; + } else if ((type & ARG_LONG) != 0) { + return 8; + } else if ((type & ARG_DOUBLE) != 0) { + return 8; + } + return 0; + } + + private static void setMultiArrayType(KernelArg arg, Class type) throws AparapiException { + arg.setType(arg.getType() | (ARG_WRITE | ARG_READ | ARG_APARAPI_BUFFER)); + int numDims = 0; + while (type.getName().startsWith("[[[[")) { + throw new AparapiException("Aparapi only supports 2D and 3D arrays."); + } + arg.setType(arg.getType() | ARG_ARRAYLENGTH); + while (type.getName().charAt(numDims) == '[') { + numDims++; + } + arg.setNumDims(numDims); + arg.setJavaBuffer(null); // will get updated in updateKernelArrayRefs + arg.setArray(null); // will get updated in updateKernelArrayRefs + + Class elementType = arg.getField().getType(); + while (elementType.isArray()) { + elementType = elementType.getComponentType(); + } + + if (elementType.isAssignableFrom(float.class)) { + arg.setType(arg.getType() | ARG_FLOAT); + } else if (elementType.isAssignableFrom(int.class)) { + arg.setType(arg.getType() | ARG_INT); + } else if (elementType.isAssignableFrom(boolean.class)) { + arg.setType(arg.getType() | ARG_BOOLEAN); + } else if (elementType.isAssignableFrom(byte.class)) { + arg.setType(arg.getType() | ARG_BYTE); + } else if (elementType.isAssignableFrom(char.class)) { + arg.setType(arg.getType() | ARG_CHAR); + } else if (elementType.isAssignableFrom(double.class)) { + arg.setType(arg.getType() | ARG_DOUBLE); + } else if (elementType.isAssignableFrom(long.class)) { + arg.setType(arg.getType() | ARG_LONG); + } else if (elementType.isAssignableFrom(short.class)) { + arg.setType(arg.getType() | ARG_SHORT); + } + } + + private final Set puts = new HashSet<>(); + + /** + * Enqueue a request to return this array from the GPU. This method blocks until the array is available. + *
+ * Note that Kernel.put(type []) calls will delegate to this call. + *
+ * Package public + * + * @param array + * It is assumed that this parameter is indeed an array (of int, float, short etc). + * + * @see Kernel#get(int[] arr) + * @see Kernel#get(float[] arr) + * @see Kernel#get(double[] arr) + * @see Kernel#get(long[] arr) + * @see Kernel#get(char[] arr) + * @see Kernel#get(boolean[] arr) + */ + public void get(Object array) { + if (explicit && (kernel.isRunningCL())) { + // Only makes sense when we are using OpenCL + getJNI(jniContextHandle, array); + } + } + + public List getProfileInfo() { + if (explicit && (kernel.isRunningCL())) { + // Only makes sense when we are using OpenCL + return (getProfileInfoJNI(jniContextHandle)); + } else { + return (null); + } + } + + /** + * Tag this array so that it is explicitly enqueued before the kernel is executed.
+ * Note that Kernel.put(type []) calls will delegate to this call.
+ * Package public + * + * @param array + * It is assumed that this parameter is indeed an array (of int, float, short etc). + * @see Kernel#put(int[] arr) + * @see Kernel#put(float[] arr) + * @see Kernel#put(double[] arr) + * @see Kernel#put(long[] arr) + * @see Kernel#put(char[] arr) + * @see Kernel#put(boolean[] arr) + */ + + public void put(Object array) { + if (explicit && (kernel.isRunningCL())) { + // Only makes sense when we are using OpenCL + puts.add(array); + } + } + + private boolean explicit = false; + + public void setExplicit(boolean _explicit) { + explicit = _explicit; + } + + public boolean isExplicit() { + return (explicit); + } + + private static class ExecutionSettings { + final KernelPreferences preferences; + final KernelProfile profile; + final String entrypoint; + Range range; + final int passes; + final boolean legacyExecutionMode; + private int jniFlags; + + private ExecutionSettings(KernelPreferences preferences, KernelProfile profile, String entrypoint, Range range, int passes, boolean legacyExecutionMode) { + this.preferences = preferences; + this.profile = profile; + this.entrypoint = entrypoint; + this.range = range; + this.passes = passes; + this.legacyExecutionMode = legacyExecutionMode; + } + + @Override + public String toString() { + return "ExecutionSettings{" + + "preferences=" + preferences + + ", profile=" + profile + + ", entrypoint='" + entrypoint + '\'' + + ", range=" + range + + ", passes=" + passes + + ", legacyExecutionMode=" + legacyExecutionMode + + '}'; + } + + + public Device device() { + return range.device; + } + + public ExecutionSettings validate(KernelRunner runner) { + + + if (range == null) { + throw new IllegalStateException("range can't be null"); + } + + EXECUTION_MODE requestedExecutionMode = runner.kernel.getExecutionMode(); + + final Device preDevice = range.getDevice(); + Device device = preDevice; + if (requestedExecutionMode.isOpenCL() && device != null && !(device instanceof OpenCLDevice)) { + runner.fallBackToNextDevice(this, "OpenCL EXECUTION_MODE was requested but Device supplied was not an OpenCLDevice"); + } + + boolean userSpecifiedDevice = true; + if (preDevice == null) { + userSpecifiedDevice = false; + if (!legacyExecutionMode) { + device = preferences.getPreferredDevice(runner.kernel); + if (device == null) { + // the default fallback when KernelPreferences has run out of options is JTP + device = JavaDevice.THREAD_POOL; + } + } else { + if (requestedExecutionMode == EXECUTION_MODE.JTP) { + device = JavaDevice.THREAD_POOL; + } else if (requestedExecutionMode == EXECUTION_MODE.SEQ) { + device = JavaDevice.SEQUENTIAL; + } + } + } else { + boolean compatible = runner.isDeviceCompatible(device); + if (!compatible) { + throw new AssertionError("user supplied Device incompatible with current EXECUTION_MODE or getTargetDevice(); device = " + + device.getShortDescription() + "; kernel = " + runner.kernel); + } + } + + OpenCLDevice openCLDevice = device instanceof OpenCLDevice ? (OpenCLDevice) device : null; + + int jniFlags = 0; + // for legacy reasons use old logic where Kernel.EXECUTION_MODE is not AUTO + if (legacyExecutionMode && !userSpecifiedDevice && requestedExecutionMode.isOpenCL()) { + if (requestedExecutionMode.equals(EXECUTION_MODE.GPU)) { + // Get the best GPU + openCLDevice = (OpenCLDevice) KernelManager.DeprecatedMethods.bestGPU(); + jniFlags |= JNI_FLAG_USE_GPU; // this flag might be redundant now. + if (openCLDevice == null) { + runner.fallBackToNextDevice(this, "GPU request can't be honored, no GPU device"); + return null; + } + } else if (requestedExecutionMode.equals(EXECUTION_MODE.ACC)) { + // Get the best ACC + openCLDevice = (OpenCLDevice) KernelManager.DeprecatedMethods.bestACC(); + jniFlags |= JNI_FLAG_USE_ACC; // this flag might be redundant now. + if (openCLDevice == null) { + runner.fallBackToNextDevice(this, "ACC request can't be honored, no ACC device"); + return null; + } + } else { + // We fetch the first CPU device + openCLDevice = (OpenCLDevice) KernelManager.DeprecatedMethods.firstDevice(Device.TYPE.CPU); + if (openCLDevice == null) { + runner.fallBackToNextDevice(this, "CPU request can't be honored, no CPU device"); + return null; + } + } + } else { + if (device.getType() == Device.TYPE.GPU) { + jniFlags |= JNI_FLAG_USE_GPU; // this flag might be redundant now. + } else if (device.getType() == Device.TYPE.ACC) { + jniFlags |= JNI_FLAG_USE_ACC; // this flag might be redundant now. + } } - } else { // isOpenCL - if (!(device instanceof JavaDevice)) { - fallBackToNextDevice(_settings, "Non-OpenCL Kernel.EXECUTION_MODE requested but device is not a JavaDevice "); + if (device == null && openCLDevice != null) { + device = openCLDevice; } - executeJava(_settings, (JavaDevice) device); - } - - if (Config.enableExecutionModeReporting) { - System.out.println("execution complete: " + kernel); - } - - return kernel; - } - finally { - _settings.profile.onEvent(ProfilingEvent.EXECUTED); - maybeReportProfile(_settings); - } - } - - @Override - public String toString() { - return "KernelRunner{" + kernel + "}"; - } - - private String describeDevice() { - Device device = KernelManager.instance().getPreferences(kernel).getPreferredDevice(kernel); - return (device == null) ? "" : device.getShortDescription(); - } - - private void maybeReportProfile(ExecutionSettings _settings) { - if (Config.dumpProfileOnExecution) { - StringBuilder report = new StringBuilder(); - report.append(KernelDeviceProfile.getTableHeader()).append('\n'); - report.append(_settings.profile.getLastDeviceProfile().getLastAsTableRow()); - System.out.println(report); - } - } - - @SuppressWarnings("deprecation") - private boolean isDeviceCompatible(Device device) { - Kernel.EXECUTION_MODE mode = kernel.getExecutionMode(); - if (mode != Kernel.EXECUTION_MODE.AUTO) { - switch (device.getType()) { - case GPU: - return mode == Kernel.EXECUTION_MODE.GPU; - case CPU: - return mode == Kernel.EXECUTION_MODE.CPU; - case JTP: - return mode == Kernel.EXECUTION_MODE.JTP; - case SEQ: - return mode == Kernel.EXECUTION_MODE.SEQ; - case ACC: - return mode == Kernel.EXECUTION_MODE.ACC; - default: - return false; - } - } else { - return (device == kernel.getTargetDevice()); - } - } - - public int getCancelState() { - return inBufferRemoteInt.get(0); - } - - public void cancelMultiPass() { - inBufferRemoteInt.put(0, CANCEL_STATUS_TRUE); - } - - private void clearCancelMultiPass() { - inBufferRemoteInt.put(0, CANCEL_STATUS_FALSE); - } - - /** - * Returns the index of the current pass, or one of two special constants with negative values to indicate special progress states. Those constants are - * {@link #PASS_ID_PREPARING_EXECUTION} to indicate that the Kernel has started executing but not reached the initial pass, or - * {@link #PASS_ID_COMPLETED_EXECUTION} to indicate that execution is complete (possibly due to early termination via {@link #cancelMultiPass()}), i.e. the Kernel - * is idle. {@link #PASS_ID_COMPLETED_EXECUTION} is also returned before the first execution has been invoked. - * - *

This can be used, for instance, to update a visual progress bar. - * - * @see #execute(String, Range, int) - */ - public int getCurrentPass() { - if (!executing) { - return PASS_ID_COMPLETED_EXECUTION; - } - - if (kernel.isRunningCL()) { - return getCurrentPassRemote(); - } else { - return getCurrentPassLocal(); - } - } - - /** - * True while any of the {@code execute()} methods are in progress. - */ - public boolean isExecuting() { - return executing; - } - - protected int getCurrentPassRemote() { - return outBufferRemoteInt.get(0); - } - - private int getCurrentPassLocal() { - return passId; - } - - private int getPrimitiveSize(int type) { - if ((type & ARG_FLOAT) != 0) { - return 4; - } else if ((type & ARG_INT) != 0) { - return 4; - } else if ((type & ARG_BYTE) != 0) { - return 1; - } else if ((type & ARG_CHAR) != 0) { - return 2; - } else if ((type & ARG_BOOLEAN) != 0) { - return 1; - } else if ((type & ARG_SHORT) != 0) { - return 2; - } else if ((type & ARG_LONG) != 0) { - return 8; - } else if ((type & ARG_DOUBLE) != 0) { - return 8; - } - return 0; - } - - private void setMultiArrayType(KernelArg arg, Class type) throws AparapiException { - arg.setType(arg.getType() | (ARG_WRITE | ARG_READ | ARG_APARAPI_BUFFER)); - int numDims = 0; - while (type.getName().startsWith("[[[[")) { - throw new AparapiException("Aparapi only supports 2D and 3D arrays."); - } - arg.setType(arg.getType() | ARG_ARRAYLENGTH); - while (type.getName().charAt(numDims) == '[') { - numDims++; - } - arg.setNumDims(numDims); - arg.setJavaBuffer(null); // will get updated in updateKernelArrayRefs - arg.setArray(null); // will get updated in updateKernelArrayRefs - - Class elementType = arg.getField().getType(); - while (elementType.isArray()) { - elementType = elementType.getComponentType(); - } - - if (elementType.isAssignableFrom(float.class)) { - arg.setType(arg.getType() | ARG_FLOAT); - } else if (elementType.isAssignableFrom(int.class)) { - arg.setType(arg.getType() | ARG_INT); - } else if (elementType.isAssignableFrom(boolean.class)) { - arg.setType(arg.getType() | ARG_BOOLEAN); - } else if (elementType.isAssignableFrom(byte.class)) { - arg.setType(arg.getType() | ARG_BYTE); - } else if (elementType.isAssignableFrom(char.class)) { - arg.setType(arg.getType() | ARG_CHAR); - } else if (elementType.isAssignableFrom(double.class)) { - arg.setType(arg.getType() | ARG_DOUBLE); - } else if (elementType.isAssignableFrom(long.class)) { - arg.setType(arg.getType() | ARG_LONG); - } else if (elementType.isAssignableFrom(short.class)) { - arg.setType(arg.getType() | ARG_SHORT); - } - } - - private final Set puts = new HashSet(); - - /** - * Enqueue a request to return this array from the GPU. This method blocks until the array is available. - *
- * Note that Kernel.put(type []) calls will delegate to this call. - *
- * Package public - * - * @param array - * It is assumed that this parameter is indeed an array (of int, float, short etc). - * - * @see Kernel#get(int[] arr) - * @see Kernel#get(float[] arr) - * @see Kernel#get(double[] arr) - * @see Kernel#get(long[] arr) - * @see Kernel#get(char[] arr) - * @see Kernel#get(boolean[] arr) - */ - public void get(Object array) { - if (explicit && (kernel.isRunningCL())) { - // Only makes sense when we are using OpenCL - getJNI(jniContextHandle, array); - } - } - - public List getProfileInfo() { - if (explicit && (kernel.isRunningCL())) { - // Only makes sense when we are using OpenCL - return (getProfileInfoJNI(jniContextHandle)); - } else { - return (null); - } - } - - /** - * Tag this array so that it is explicitly enqueued before the kernel is executed.
- * Note that Kernel.put(type []) calls will delegate to this call.
- * Package public - * - * @param array - * It is assumed that this parameter is indeed an array (of int, float, short etc). - * @see Kernel#put(int[] arr) - * @see Kernel#put(float[] arr) - * @see Kernel#put(double[] arr) - * @see Kernel#put(long[] arr) - * @see Kernel#put(char[] arr) - * @see Kernel#put(boolean[] arr) - */ - - public void put(Object array) { - if (explicit && (kernel.isRunningCL())) { - // Only makes sense when we are using OpenCL - puts.add(array); - } - } - - private boolean explicit = false; - - public void setExplicit(boolean _explicit) { - explicit = _explicit; - } - - public boolean isExplicit() { - return (explicit); - } - - private static class ExecutionSettings { - final KernelPreferences preferences; - final KernelProfile profile; - final String entrypoint; - Range range; - final int passes; - final boolean legacyExecutionMode; - - private ExecutionSettings(KernelPreferences preferences, KernelProfile profile, String entrypoint, Range range, int passes, boolean legacyExecutionMode) { - this.preferences = preferences; - this.profile = profile; - this.entrypoint = entrypoint; - this.range = range; - this.passes = passes; - this.legacyExecutionMode = legacyExecutionMode; - } - - @Override - public String toString() { - return "ExecutionSettings{" + - "preferences=" + preferences + - ", profile=" + profile + - ", entrypoint='" + entrypoint + '\'' + - ", range=" + range + - ", passes=" + passes + - ", legacyExecutionMode=" + legacyExecutionMode + - '}'; - } - } + + + + if (device!=null) { + this.jniFlags = jniFlags; + if (device != preDevice) { + KernelRunner.recreateRange(device, this); + } + return this; + } else { + return null; + } + + } + } } diff --git a/src/main/java/com/aparapi/internal/kernel/PreferencesWrapper.java b/src/main/java/com/aparapi/internal/kernel/PreferencesWrapper.java index ba8bb0d4..473b04f1 100644 --- a/src/main/java/com/aparapi/internal/kernel/PreferencesWrapper.java +++ b/src/main/java/com/aparapi/internal/kernel/PreferencesWrapper.java @@ -17,10 +17,10 @@ import com.aparapi.Kernel; -public class PreferencesWrapper { +class PreferencesWrapper { - private Class klass; - private KernelPreferences preferences; + private final Class klass; + private final KernelPreferences preferences; public PreferencesWrapper(Class klass, KernelPreferences preferences) { super(); diff --git a/src/main/java/com/aparapi/internal/model/ClassModel.java b/src/main/java/com/aparapi/internal/model/ClassModel.java index db20a86b..f940b109 100644 --- a/src/main/java/com/aparapi/internal/model/ClassModel.java +++ b/src/main/java/com/aparapi/internal/model/ClassModel.java @@ -69,2796 +69,2832 @@ to national security controls as identified on the Commerce Control List (curren /** * Class represents a ClassFile (MyClass.class). - * + *

* A 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. - * - * @see Java 5 Class File Format -+ * @see Java 7 Class File Format - * - * @author gfrost * + * @author gfrost + * @see Java 5 Class File Format + * + * @see Java 7 Class File Format */ public class ClassModel { - public interface LocalVariableInfo { + /** reflection cache */ + private Method[] _methods; - int getStart(); + public interface LocalVariableInfo { - boolean isArray(); + int getStart(); - int getEnd(); + boolean isArray(); - String getVariableName(); + int getEnd(); - String getVariableDescriptor(); + String getVariableName(); - int getVariableIndex(); + String getVariableDescriptor(); - int getLength(); + int getVariableIndex(); - } + int getLength(); - public interface LocalVariableTableEntry extends Iterable{ - LocalVariableInfo getVariable(int _pc, int _index); + } - } + public interface LocalVariableTableEntry extends Iterable { + LocalVariableInfo getVariable(int _pc, int _index); - public static final char SIGC_VOID = 'V'; + } - public static final char SIGC_BOOLEAN = 'Z'; + private static final char SIGC_VOID = 'V'; - public static final char SIGC_BYTE = 'B'; + private static final char SIGC_BOOLEAN = 'Z'; - public static final char SIGC_CHAR = 'C'; + private static final char SIGC_BYTE = 'B'; - public static final char SIGC_SHORT = 'S'; + private static final char SIGC_CHAR = 'C'; - public static final char SIGC_INT = 'I'; + private static final char SIGC_SHORT = 'S'; - public static final char SIGC_LONG = 'J'; + private static final char SIGC_INT = 'I'; - public static final char SIGC_FLOAT = 'F'; + private static final char SIGC_LONG = 'J'; - public static final char SIGC_DOUBLE = 'D'; + private static final char SIGC_FLOAT = 'F'; - public static final char SIGC_ARRAY = '['; + private static final char SIGC_DOUBLE = 'D'; - public static final char SIGC_CLASS = 'L'; + private static final char SIGC_ARRAY = '['; - public static final char SIGC_START_METHOD = '('; + private static final char SIGC_CLASS = 'L'; - public static final char SIGC_END_CLASS = ';'; + private static final char SIGC_START_METHOD = '('; - public static final char SIGC_END_METHOD = ')'; + private static final char SIGC_END_CLASS = ';'; - public static final char SIGC_PACKAGE = '/'; + private static final char SIGC_END_METHOD = ')'; - private static Logger logger = Logger.getLogger(Config.getLoggerName()); + private static final char SIGC_PACKAGE = '/'; - private ClassModel superClazz = null; + private static final Logger logger = Logger.getLogger(Config.getLoggerName()); - // private Memoizer> noClMethods = Memoizer.of(this::computeNoCLMethods); - private Memoizer> noClMethods = Memoizer.Impl.of(new Supplier>(){ - @Override - public Set get() { - return computeNoCLMethods(); - } - }); + private ClassModel superClazz; - // private Memoizer> privateMemoryFields = Memoizer.of(this::computePrivateMemoryFields); - private Memoizer> privateMemoryFields = Memoizer.Impl - .of(new Supplier>(){ - @Override - public Map get() { - return computePrivateMemoryFields(); - } - }); + // private Memoizer> noClMethods = Memoizer.of(this::computeNoCLMethods); +// private final Memoizer> noClMethods = Memoizer.Impl.of(new Supplier>() { +// @Override +// public Set get() { +// return computeNoCLMethods(); +// } +// }); - // private ValueCache privateMemorySizes = ValueCache.on(this::computePrivateMemorySize); - private ValueCache privateMemorySizes = ValueCache - .on(new ThrowingValueComputer(){ - @Override - public Integer compute(String fieldName) throws ClassParseException { - return computePrivateMemorySize(fieldName); - } - }); - - /** - * 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 ClassModel(Class _class) throws ClassParseException { - - parse(_class); - - final 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())) + private final Memoizer> privateMemoryFields = Memoizer.Impl + .of(this::computePrivateMemoryFields); + + private final ValueCache privateMemorySizes = ValueCache + .on(this::computePrivateMemorySize); + + /** + * 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 ClassModel(Class _class) throws ClassParseException { + + clazz = _class; + parse(_class.getClassLoader(), _class.getName()); + + final 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 = createClassModel(mySuper); - } - } - - ClassModel(InputStream _inputStream) throws ClassParseException { - - parse(_inputStream); - - } - - ClassModel(Class _clazz, byte[] _bytes) throws ClassParseException { - 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 - */ - public boolean isSuperClass(String otherClassName) { - if (getClassWeAreModelling().getName().equals(otherClassName)) { - return true; - } else if (superClazz != null) { - return superClazz.isSuperClass(otherClassName); - } else { - return false; - } - } - - /** - * Determine if this is the superclass of some other class. - * - * @param other The class to compare against - * @return true if 'this' a superclass of another class - */ - public boolean isSuperClass(Class other) { - Class s = other.getSuperclass(); - while (s != null) { - if ((getClassWeAreModelling() == s) || (getClassWeAreModelling().getName().equals(s.getName()))) { - return true; - } - s = s.getSuperclass(); - } - return false; - } - - /** - * Getter for superClazz - * - * @return the superClazz ClassModel - */ - public ClassModel getSuperClazz() { - return superClazz; - } - - @DocMe - public void replaceSuperClazz(ClassModel c) { - if (superClazz != null) { - assert c.isSuperClass(getClassWeAreModelling()) == true : "not my super"; - if (superClazz.getClassWeAreModelling().getName().equals(c.getClassWeAreModelling().getName())) { - superClazz = c; - } else { - 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. - */ - public 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); - } - - /** - * If a field does not satisfy the private memory conditions, null, otherwise the size of private memory required. - */ - public Integer getPrivateMemorySize(String fieldName) throws ClassParseException { - if (CacheEnabler.areCachesEnabled()) - return privateMemorySizes.computeIfAbsent(fieldName); - return computePrivateMemorySize(fieldName); - } - - private Integer computePrivateMemorySize(String fieldName) throws ClassParseException { - Kernel.PrivateMemorySpace annotation = privateMemoryFields.get().get(fieldName); - if (annotation != null) { - return annotation.value(); - } - return getPrivateMemorySizeFromFieldName(fieldName); - } - - private Map computePrivateMemoryFields() { - Map tempPrivateMemoryFields = new HashMap(); - Map privateMemoryFields = new HashMap(); - for (Field field : getClassWeAreModelling().getDeclaredFields()) { - Kernel.PrivateMemorySpace privateMemorySpace = field.getAnnotation(Kernel.PrivateMemorySpace.class); - if (privateMemorySpace != null) { - privateMemoryFields.put(field, privateMemorySpace); - } - } - for (Field field : getClassWeAreModelling().getFields()) { - Kernel.PrivateMemorySpace privateMemorySpace = field.getAnnotation(Kernel.PrivateMemorySpace.class); - if (privateMemorySpace != null) { - privateMemoryFields.put(field, privateMemorySpace); - } - } - for (Map.Entry entry : privateMemoryFields.entrySet()) { - tempPrivateMemoryFields.put(entry.getKey().getName(), entry.getValue()); - } - return tempPrivateMemoryFields; - } - - public static Integer getPrivateMemorySizeFromField(Field field) { - Kernel.PrivateMemorySpace privateMemorySpace = field.getAnnotation(Kernel.PrivateMemorySpace.class); - if (privateMemorySpace != null) { - return privateMemorySpace.value(); - } else { - return null; - } - } - - public static Integer getPrivateMemorySizeFromFieldName(String fieldName) throws ClassParseException { - if (fieldName.contains(Kernel.PRIVATE_SUFFIX)) { - int lastDollar = fieldName.lastIndexOf('$'); - String sizeText = fieldName.substring(lastDollar + 1); - try { - return new Integer(Integer.parseInt(sizeText)); - } catch (NumberFormatException e) { - throw new ClassParseException(ClassParseException.TYPE.IMPROPERPRIVATENAMEMANGLING, fieldName); - } - } - return null; - } - - public Set getNoCLMethods() { - return computeNoCLMethods(); - } - - private Set computeNoCLMethods() { - Set tempNoClMethods = new HashSet(); - HashSet methods = new HashSet(); - for (Method method : getClassWeAreModelling().getDeclaredMethods()) { - if (method.getAnnotation(Kernel.NoCL.class) != null) { - methods.add(method); - } - } - for (Method method : getClassWeAreModelling().getMethods()) { - if (method.getAnnotation(Kernel.NoCL.class) != null) { - methods.add(method); - } - } - for (Method method : methods) { - tempNoClMethods.add(method.getName()); - } - return tempNoClMethods; - } - - public static String convert(String _string) { - return (convert(_string, "", false)); - } - - public static String convert(String _string, String _insert) { - return (convert(_string, _insert, false)); - } - - public static String convert(String _string, String _insert, boolean _showFullClassName) { - Stack stringStack = new Stack(); - Stack methodStack = null; - final int length = _string.length(); - final 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: { - final 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 { - final int lastDot = className.lastIndexOf('.'); - if (lastDot > 0) { - className = className.substring(lastDot + 1); - } - } - if (inArray) { - // swap the stack items - final 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: { - final StringBuilder arrayDims = new StringBuilder(); - while ((i < length) && (chars[i] == SIGC_ARRAY)) { - arrayDims.append("[]"); - i++; - } - stringStack.push(arrayDims.toString()); - inArray = true; - } - break; + superClazz = createClassModel(mySuper); + } else { + superClazz = null; + } + } + +// private ClassModel(InputStream _inputStream) { +// +// parse(_inputStream); +// +// } + +// private ClassModel(Class _clazz, byte[] _bytes) { +// 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 + */ + private boolean isSuperClass(String otherClassName) { + ClassModel other = this; + while (true) { + if (other.clazz.getName().equals(otherClassName)) { + return true; + } else if (other.superClazz != null) { + other = other.superClazz; + } else { + return false; + } + } + } + + /** + * Determine if this is the superclass of some other class. + * + * @param other The class to compare against + * @return true if 'this' a superclass of another class + */ + public boolean isSuperClass(Class other) { + Class s = other.getSuperclass(); + while (s != null) { + if ((clazz == s) || (clazz.getName().equals(s.getName()))) { + return true; + } + s = s.getSuperclass(); + } + return false; + } + + /** + * Getter for superClazz + * + * @return the superClazz ClassModel + */ + public ClassModel getSuperClazz() { + return superClazz; + } + + @DocMe + public void replaceSuperClazz(ClassModel c) { + if (superClazz != null) { + assert c.isSuperClass(clazz) == true : "not my super"; + if (superClazz.clazz.getName().equals(c.clazz.getName())) { + superClazz = c; + } else { + 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. + */ + public 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: - case SIGC_BOOLEAN: { - if (inArray) { - // swap the stack items - final 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; - } - } - - final StringBuilder returnValue = new StringBuilder(); - for (final String s : stringStack) { - returnValue.append(s); - returnValue.append(" "); - - } - - if (inMethod) { - for (final String s : methodStack) { + returnName = "long"; + break; + case SIGC_BOOLEAN: + returnName = "boolean"; + break; + } + + return (returnName); + } + + /** + * If a field does not satisfy the private memory conditions, null, otherwise the size of private memory required. + */ + public Integer getPrivateMemorySize(String fieldName) throws ClassParseException { + if (CacheEnabler.areCachesEnabled()) + return privateMemorySizes.computeIfAbsent(fieldName); + return computePrivateMemorySize(fieldName); + } + + private Integer computePrivateMemorySize(String fieldName) throws ClassParseException { + Kernel.PrivateMemorySpace annotation = privateMemoryFields.get().get(fieldName); + if (annotation != null) { + return annotation.value(); + } + return getPrivateMemorySizeFromFieldName(fieldName); + } + + private Map computePrivateMemoryFields() { + Map tempPrivateMemoryFields = new HashMap<>(); + Map privateMemoryFields = new HashMap<>(); + for (Field field : clazz.getDeclaredFields()) { + Kernel.PrivateMemorySpace privateMemorySpace = field.getAnnotation(Kernel.PrivateMemorySpace.class); + if (privateMemorySpace != null) { + privateMemoryFields.put(field, privateMemorySpace); + } + } + for (Field field : clazz.getFields()) { + Kernel.PrivateMemorySpace privateMemorySpace = field.getAnnotation(Kernel.PrivateMemorySpace.class); + if (privateMemorySpace != null) { + privateMemoryFields.put(field, privateMemorySpace); + } + } + for (Map.Entry entry : privateMemoryFields.entrySet()) { + tempPrivateMemoryFields.put(entry.getKey().getName(), entry.getValue()); + } + return tempPrivateMemoryFields; + } + + public static Integer getPrivateMemorySizeFromField(Field field) { + Kernel.PrivateMemorySpace privateMemorySpace = field.getAnnotation(Kernel.PrivateMemorySpace.class); + if (privateMemorySpace != null) { + return privateMemorySpace.value(); + } else { + return null; + } + } + + public static Integer getPrivateMemorySizeFromFieldName(String fieldName) throws ClassParseException { + if (fieldName.contains(Kernel.PRIVATE_SUFFIX)) { + int lastDollar = fieldName.lastIndexOf('$'); + String sizeText = fieldName.substring(lastDollar + 1); + try { + return Integer.parseInt(sizeText); + } catch (NumberFormatException e) { + throw new ClassParseException(ClassParseException.TYPE.IMPROPERPRIVATENAMEMANGLING, fieldName); + } + } + return null; + } + + public boolean isNoCLMethod(String name) { +// return computeNoCLMethods(); +// } +// +// private Set computeNoCLMethods() { +// Set tempNoClMethods = new HashSet<>(); +// HashSet methods = new HashSet<>(); +// for (Method method : getClassWeAreModelling().getDeclaredMethods()) { +// if (method.getAnnotation(Kernel.NoCL.class) != null) { +// methods.add(method); +// } +// } + if (_methods == null) { + _methods = clazz.getMethods(); + } + for (Method method : _methods) { + if (method.getName().equals(name) && method.getAnnotation(Kernel.NoCL.class) != null) { + //methods.add(method); + return true; + } + } +// for (Method method : methods) { +// tempNoClMethods.add(method.getName()); +// } + return false; + } + + public static String convert(String _string) { + return (convert(_string, "", false)); + } + + private static String convert(String _string, String _insert) { + return (convert(_string, _insert, false)); + } + + public static String convert(String _string, String _insert, boolean _showFullClassName) { + List stringStack = new ArrayList<>(); + List methodStack = null; + final int length = _string.length(); + final 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: { + final 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 { + final int lastDot = className.lastIndexOf('.'); + if (lastDot > 0) { + className = className.substring(lastDot + 1); + } + } + if (inArray) { + // swap the stack items + final String popped = pop(stringStack); + if (inArgs && (args > 0)) { + stringStack.add(", "); + } + stringStack.add(className); + stringStack.add(popped); + inArray = false; + } else { + if (inArgs && (args > 0)) { + stringStack.add(", "); + } + stringStack.add(className); + } + args++; + } + break; + case SIGC_ARRAY: { + final StringBuilder arrayDims = new StringBuilder(); + while ((i < length) && (chars[i] == SIGC_ARRAY)) { + arrayDims.append("[]"); + i++; + } + stringStack.add(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 + final String popped = pop(stringStack); + if (inArgs && (args > 0)) { + stringStack.add(", "); + } + stringStack.add(typeName(chars[i])); + stringStack.add(popped); + inArray = false; + } else { + if (inArgs && (args > 0)) { + stringStack.add(", "); + } + stringStack.add(typeName(chars[i])); + } + i++; // step over this + } + break; + case SIGC_START_METHOD: { + stringStack.add("("); + i++; // step over this + inArgs = true; + args = 0; + } + break; + case SIGC_END_METHOD: { + inMethod = true; + inArgs = false; + stringStack.add(")"); + methodStack = stringStack; + stringStack = new Stack<>(); + i++; // step over this + } + break; + } + } + + final StringBuilder returnValue = new StringBuilder(); + for (final String s : stringStack) { returnValue.append(s); - returnValue.append(" "); - } - } else { - returnValue.append(_insert); - } - - return (returnValue.toString()); - } - - public static class MethodDescription{ - private final String className; - - private final String methodName; - - private final String type; - - private final String[] args; - - public MethodDescription(String _className, String _methodName, String _type, String[] _args) { - methodName = _methodName; - className = _className; - type = _type; - args = _args; - } - - public String[] getArgs() { - return (args); - } - - public String getType() { - return (type); - } - - public String getClassName() { - return (className); - } - - public String getMethodName() { - return (methodName); - } - } - - public 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 { - final int parenIndex = _string.indexOf("("); - final 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; - final int length = descriptor.length(); - final 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: { - final 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; - } - } - - 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 static final ValueCache, ClassModel, ClassParseException> classModelCache = ValueCache - .on(new ThrowingValueComputer, ClassModel, ClassParseException>(){ - @Override - public ClassModel compute(Class key) throws ClassParseException { - return createClassModelInternal(key); - } - }); - - private static ClassModel createClassModelInternal(Class key) throws ClassParseException { - ClassModel classModel = new ClassModel(key); - return classModel; - } - - public static ClassModel createClassModel(Class _class) throws ClassParseException { - if (CacheEnabler.areCachesEnabled()) { - return classModelCache.computeIfAbsent(_class); - } - - return createClassModelInternal(_class); - } - - private int magic; - - private int minorVersion; - - private int majorVersion; - - private ConstantPool constantPool; - - private int accessFlags; - - private int thisClassConstantPoolIndex; - - private int superClassConstantPoolIndex; - - private final List interfaces = new ArrayList(); - - private final List fields = new ArrayList(); - - private final List methods = new ArrayList(); - - private AttributePool attributePool; - - public 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 - }; - - public 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); - int bits; - - private Access(int _bits) { - bits = _bits; - } - - public boolean bitIsSet(int _accessFlags) { - return ((bits & _accessFlags) == bits); - } - - public String convert(int _accessFlags) { - final StringBuffer stringBuffer = new StringBuffer(); - for (final Access access : Access.values()) { - if (access.bitIsSet(_accessFlags)) { - stringBuffer.append(" " + access.name().toLowerCase()); - } - } - - return (stringBuffer.toString()); - } - } - - private static enum SignatureParseState { - skipping, - counting, - inclass, - inArray, - done; - }; - - public class ConstantPool implements Iterable{ - - private final List entries = new ArrayList(); - - public abstract class Entry { - private final ConstantPoolType constantPoolType; - - private final int slot; - - public Entry(ByteReader _byteReader, int _slot, ConstantPoolType _constantPoolType) { - constantPoolType = _constantPoolType; - slot = _slot; - } - - public ConstantPoolType getConstantPoolType() { - return (constantPoolType); - } - - public int getSlot() { - return (slot); - } - - public ClassModel getOwnerClassModel() { - return ClassModel.this; - } - } + returnValue.append(' '); - public class ClassEntry extends Entry{ - private final int nameIndex; + } - public ClassEntry(ByteReader _byteReader, int _slot) { - super(_byteReader, _slot, ConstantPoolType.CLASS); - nameIndex = _byteReader.u2(); - } + if (inMethod) { + for (final String s : methodStack) { + returnValue.append(s); + returnValue.append(' '); + } + } else { + returnValue.append(_insert); + } - public int getNameIndex() { - return (nameIndex); - } - - public UTF8Entry getNameUTF8Entry() { - return (getUTF8Entry(nameIndex)); - } - } - - public class DoubleEntry extends Entry{ - private final double doubleValue; - - public DoubleEntry(ByteReader _byteReader, int _slot) { - super(_byteReader, _slot, ConstantPoolType.DOUBLE); - doubleValue = _byteReader.d8(); - } - - public double getDoubleValue() { - return (doubleValue); - } - } - - public class EmptyEntry extends Entry{ - public EmptyEntry(ByteReader _byteReader, int _slot) { - super(_byteReader, _slot, ConstantPoolType.EMPTY); - } - } - - public class FieldEntry extends ReferenceEntry{ - public FieldEntry(ByteReader _byteReader, int _slot) { - super(_byteReader, _slot, ConstantPoolType.FIELD); - } - } - - public class FloatEntry extends Entry{ - private final float floatValue; - - public FloatEntry(ByteReader _byteReader, int _slot) { - super(_byteReader, _slot, ConstantPoolType.FLOAT); - floatValue = _byteReader.f4(); - } - - public float getFloatValue() { - return (floatValue); - } - } - - public class IntegerEntry extends Entry{ - private final int intValue; - - public IntegerEntry(ByteReader _byteReader, int _slot) { - super(_byteReader, _slot, ConstantPoolType.INTEGER); - intValue = _byteReader.u4(); - } - - public int getIntValue() { - return (intValue); - } - } - - public class InterfaceMethodEntry extends MethodReferenceEntry{ - InterfaceMethodEntry(ByteReader _byteReader, int _slot) { - super(_byteReader, _slot, ConstantPoolType.INTERFACEMETHOD); - } - } - - public class LongEntry extends Entry{ - private final long longValue; - - public LongEntry(ByteReader _byteReader, int _slot) { - super(_byteReader, _slot, ConstantPoolType.LONG); - longValue = _byteReader.u8(); - } - - public long getLongValue() { - return (longValue); - } - } - - public class MethodEntry extends MethodReferenceEntry{ - public MethodEntry(ByteReader _byteReader, int _slot) { - super(_byteReader, _slot, ConstantPoolType.METHOD); - } - - @Override - public String toString() { - final StringBuilder sb = new StringBuilder(); - sb.append(getClassEntry().getNameUTF8Entry().getUTF8()); - sb.append("."); - sb.append(getNameAndTypeEntry().getNameUTF8Entry().getUTF8()); - sb.append(getNameAndTypeEntry().getDescriptorUTF8Entry().getUTF8()); - return (sb.toString()); - } - } + return (returnValue.toString()); + } - public class NameAndTypeEntry extends Entry{ - private final int descriptorIndex; + public static class MethodDescription { + private final String className; - private final int nameIndex; + private final String methodName; - public NameAndTypeEntry(ByteReader _byteReader, int _slot) { - super(_byteReader, _slot, ConstantPoolType.NAMEANDTYPE); - nameIndex = _byteReader.u2(); - descriptorIndex = _byteReader.u2(); - } + private final String type; - public int getDescriptorIndex() { - return (descriptorIndex); - } + private final String[] args; - public UTF8Entry getDescriptorUTF8Entry() { - return (getUTF8Entry(descriptorIndex)); - } + MethodDescription(String _className, String _methodName, String _type, String[] _args) { + methodName = _methodName; + className = _className; + type = _type; + args = _args; + } - public int getNameIndex() { - return (nameIndex); - } + public String[] getArgs() { + return (args); + } + + public String getType() { + return (type); + } + + public String getClassName() { + return (className); + } + + public String getMethodName() { + return (methodName); + } + } + + public 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 { + final int parenIndex = _string.indexOf('('); + final int dotIndex = _string.indexOf('.'); + descriptor = _string.substring(parenIndex); + className = _string.substring(0, dotIndex); + methodName = _string.substring(dotIndex + 1, parenIndex); + } + + List stringStack = new ArrayList<>(); + List methodStack = null; + final int length = descriptor.length(); + final 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(pop(stringStack)); + } else { + stringBuffer = new StringBuilder(); + } + stringBuffer.ensureCapacity(length); + while ((i < length) && (chars[i] != SIGC_END_CLASS)) { + stringBuffer.append(chars[i]); + i++; + } + stringBuffer.append(chars[i]); + i++; // step over SIGC_ENDCLASS + stringStack.add(stringBuffer.toString()); + inArray = false; + } + break; + case SIGC_ARRAY: { + final StringBuilder stringBuffer = new StringBuilder(length); + while ((i < length) && (chars[i] == SIGC_ARRAY)) { + stringBuffer.append(chars[i]); + i++; + } + stringStack.add(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(pop(stringStack)); + } else { + stringBuffer = new StringBuilder(); + } + stringBuffer.append(chars[i]); + i++; // step over this + stringStack.add(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 ArrayList<>(); + i++; // step over this + } + break; + } + } + + if (inMethod) { + methodDescription = new MethodDescription(className, methodName, stringStack.toArray(new String[stringStack.size()])[0], + methodStack.toArray(new String[methodStack.size()])); + } else { + //System.out.println("can't convert to a description"); + throw new UnsupportedOperationException("can't create MethodDescription: " + methodName); + } + + return (methodDescription); + } + + private static String pop(List stringStack) { + return stringStack.remove(stringStack.size()-1); + } + + private static final ValueCache, ClassModel, ClassParseException> classModelCache = ValueCache + .on(ClassModel::createClassModelInternal); + + private static ClassModel createClassModelInternal(Class key) throws ClassParseException { + return new ClassModel(key); + } + + public static ClassModel createClassModel(Class _class) throws ClassParseException { + if (CacheEnabler.areCachesEnabled()) { + return classModelCache.computeIfAbsent(_class); + } else { + return createClassModelInternal(_class); + } + } + + private int magic; + + private int minorVersion; + + private int majorVersion; + + private ConstantPool constantPool; + + private int accessFlags; + + private int thisClassConstantPoolIndex; + + private int superClassConstantPoolIndex; + + private final List interfaces = new ArrayList<>(); + + private final List fields = new ArrayList<>(); + + private final List methods = new ArrayList<>(); + + private AttributePool attributePool; + + public 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 + } + + public 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); + final int bits; - public UTF8Entry getNameUTF8Entry() { - return (getUTF8Entry(nameIndex)); - } - } + Access(int _bits) { + bits = _bits; + } - class MethodTypeEntry extends Entry{ - private int descriptorIndex; + boolean bitIsSet(int _accessFlags) { + return ((bits & _accessFlags) == bits); + } - MethodTypeEntry(ByteReader _byteReader, int _slot) { - super(_byteReader, _slot, ConstantPoolType.METHODTYPE); - descriptorIndex = _byteReader.u2(); - } + public static String convert(int _accessFlags) { + final StringBuilder stringBuffer = new StringBuilder(); + for (final Access access : Access.values()) { + if (access.bitIsSet(_accessFlags)) { + stringBuffer.append(' ').append(access.name().toLowerCase()); + } + } - int getDescriptorIndex() { - return (descriptorIndex); - } + return (stringBuffer.toString()); + } + } - UTF8Entry getDescriptorUTF8Entry() { - return (ConstantPool.this.getUTF8Entry(descriptorIndex)); - } + private enum SignatureParseState { + skipping, + counting, + inclass, + inArray, + done + } - } + public class ConstantPool implements Iterable { - class MethodHandleEntry extends Entry{ - // http://docs.oracle.com/javase/specs/jvms/se7/html/jvms-4.html#jvms-4.4 + private final List entries = new ArrayList<>(); - private int referenceKind; + public abstract class Entry { + private final ConstantPoolType constantPoolType; - private int referenceIndex; + private final int slot; - MethodHandleEntry(ByteReader _byteReader, int _slot) { - super(_byteReader, _slot, ConstantPoolType.METHODHANDLE); - referenceKind = _byteReader.u1(); - referenceIndex = _byteReader.u2(); - } + Entry(ByteReader _byteReader, int _slot, ConstantPoolType _constantPoolType) { + constantPoolType = _constantPoolType; + slot = _slot; + } - int getReferenceIndex() { - return (referenceIndex); - } + ConstantPoolType getConstantPoolType() { + return (constantPoolType); + } - int getReferenceKind() { - return (referenceKind); - } + public int getSlot() { + return (slot); + } - } + public ClassModel getOwnerClassModel() { + return ClassModel.this; + } + } - class InvokeDynamicEntry extends Entry{ - // http://docs.oracle.com/javase/specs/jvms/se7/html/jvms-4.html#jvms-4.4 + public class ClassEntry extends Entry { + private final int nameIndex; - private int bootstrapMethodAttrIndex; + ClassEntry(ByteReader _byteReader, int _slot) { + super(_byteReader, _slot, ConstantPoolType.CLASS); + nameIndex = _byteReader.u2(); + } - private int nameAndTypeIndex; + int getNameIndex() { + return (nameIndex); + } - InvokeDynamicEntry(ByteReader _byteReader, int _slot) { - super(_byteReader, _slot, ConstantPoolType.INVOKEDYNAMIC); - bootstrapMethodAttrIndex = _byteReader.u2(); - nameAndTypeIndex = _byteReader.u2(); - } + public UTF8Entry getNameUTF8Entry() { + return (getUTF8Entry(nameIndex)); + } + } - int getBootstrapMethodAttrIndex() { - return (bootstrapMethodAttrIndex); - } + public class DoubleEntry extends Entry { + private final double doubleValue; - int getNameAndTypeIndex() { - return (nameAndTypeIndex); - } + DoubleEntry(ByteReader _byteReader, int _slot) { + super(_byteReader, _slot, ConstantPoolType.DOUBLE); + doubleValue = _byteReader.d8(); + } - } + double getDoubleValue() { + return (doubleValue); + } + } - public abstract class MethodReferenceEntry extends ReferenceEntry{ + class EmptyEntry extends Entry { + EmptyEntry(ByteReader _byteReader, int _slot) { + super(_byteReader, _slot, ConstantPoolType.EMPTY); + } + } - public class Arg extends Type{ - Arg(String _signature, int _start, int _pos, int _argc) { - super(_signature.substring(_start, _pos + 1)); - argc = _argc; + public class FieldEntry extends ReferenceEntry { + FieldEntry(ByteReader _byteReader, int _slot) { + super(_byteReader, _slot, ConstantPoolType.FIELD); } + } - private final int argc; + public class FloatEntry extends Entry { + private final float floatValue; - int getArgc() { - return (argc); + FloatEntry(ByteReader _byteReader, int _slot) { + super(_byteReader, _slot, ConstantPoolType.FLOAT); + floatValue = _byteReader.f4(); } - } - private Arg[] args = null; + float getFloatValue() { + return (floatValue); + } + } - private Type returnType = null; + public class IntegerEntry extends Entry { + private final int intValue; - @Override - public int hashCode() { - final NameAndTypeEntry nameAndTypeEntry = getNameAndTypeEntry(); + IntegerEntry(ByteReader _byteReader, int _slot) { + super(_byteReader, _slot, ConstantPoolType.INTEGER); + intValue = _byteReader.u4(); + } - return ((((nameAndTypeEntry.getNameIndex() * 31) + nameAndTypeEntry.getDescriptorIndex()) * 31) + getClassIndex()); - } + int getIntValue() { + return (intValue); + } + } - @Override - public boolean equals(Object _other) { - if ((_other == null) || !(_other instanceof MethodReferenceEntry)) { - return (false); - } else { - final MethodReferenceEntry otherMethodReferenceEntry = (MethodReferenceEntry) _other; - return ((otherMethodReferenceEntry.getNameAndTypeEntry().getNameIndex() == getNameAndTypeEntry().getNameIndex()) - && (otherMethodReferenceEntry.getNameAndTypeEntry().getDescriptorIndex() == getNameAndTypeEntry() - .getDescriptorIndex()) && (otherMethodReferenceEntry.getClassIndex() == getClassIndex())); + public class InterfaceMethodEntry extends MethodReferenceEntry { + InterfaceMethodEntry(ByteReader _byteReader, int _slot) { + super(_byteReader, _slot, ConstantPoolType.INTERFACEMETHOD); } - } + } - public MethodReferenceEntry(ByteReader byteReader, int slot, ConstantPoolType constantPoolType) { - super(byteReader, slot, constantPoolType); + public class LongEntry extends Entry { + private final long longValue; - } + LongEntry(ByteReader _byteReader, int _slot) { + super(_byteReader, _slot, ConstantPoolType.LONG); + longValue = _byteReader.u8(); + } - public int getStackProduceCount() { - return (getReturnType().isVoid() ? 0 : 1); - } + long getLongValue() { + return (longValue); + } + } - public Type getReturnType() { - if (returnType == null) { - getArgs(); + public class MethodEntry extends MethodReferenceEntry { + MethodEntry(ByteReader _byteReader, int _slot) { + super(_byteReader, _slot, ConstantPoolType.METHOD); } - return (returnType); - } + @Override + public String toString() { + final StringBuilder sb = new StringBuilder(256); + sb.append(getClassEntry().getNameUTF8Entry().getUTF8()); + sb.append('.'); + NameAndTypeEntry nte = getNameAndTypeEntry(); + sb.append(nte.getNameUTF8Entry().getUTF8()); + sb.append(nte.getDescriptorUTF8Entry().getUTF8()); + return (sb.toString()); + } + } + + public class NameAndTypeEntry extends Entry { + private final int descriptorIndex; - public Arg[] getArgs() { - if ((args == null) || (returnType == null)) { - final List argList = new ArrayList(); - final NameAndTypeEntry nameAndTypeEntry = getNameAndTypeEntry(); + private final int nameIndex; - final 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; + NameAndTypeEntry(ByteReader _byteReader, int _slot) { + super(_byteReader, _slot, ConstantPoolType.NAMEANDTYPE); + nameIndex = _byteReader.u2(); + descriptorIndex = _byteReader.u2(); + } - for (int pos = 0; state != SignatureParseState.done; pos++) { - final 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; + int getDescriptorIndex() { + return (descriptorIndex); + } - } - // 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; + public UTF8Entry getDescriptorUTF8Entry() { + return (getUTF8Entry(descriptorIndex)); + } - 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; + int getNameIndex() { + return (nameIndex); + } - } - break; - } - } - // System.out.println("method "+name+" has signature of "+signature+" which has "+count+" args"); + public UTF8Entry getNameUTF8Entry() { + return (getUTF8Entry(nameIndex)); + } + } + + class MethodTypeEntry extends Entry { + private final int descriptorIndex; - args = argList.toArray(new Arg[0]); + MethodTypeEntry(ByteReader _byteReader, int _slot) { + super(_byteReader, _slot, ConstantPoolType.METHODTYPE); + descriptorIndex = _byteReader.u2(); } - return (args); - } + int getDescriptorIndex() { + return (descriptorIndex); + } - public int getStackConsumeCount() { - return (getArgs().length); - } - } + UTF8Entry getDescriptorUTF8Entry() { + return (ConstantPool.this.getUTF8Entry(descriptorIndex)); + } - public abstract class ReferenceEntry extends Entry{ - protected int referenceClassIndex; + } - protected int nameAndTypeIndex; + class MethodHandleEntry extends Entry { + // http://docs.oracle.com/javase/specs/jvms/se7/html/jvms-4.html#jvms-4.4 - protected int argCount = -1; + private final int referenceKind; - public ReferenceEntry(ByteReader _byteReader, int _slot, ConstantPoolType _constantPoolType) { - super(_byteReader, _slot, _constantPoolType); - referenceClassIndex = _byteReader.u2(); - nameAndTypeIndex = _byteReader.u2(); - } + private final int referenceIndex; - public ClassEntry getClassEntry() { - return (ConstantPool.this.getClassEntry(referenceClassIndex)); - } + MethodHandleEntry(ByteReader _byteReader, int _slot) { + super(_byteReader, _slot, ConstantPoolType.METHODHANDLE); + referenceKind = _byteReader.u1(); + referenceIndex = _byteReader.u2(); + } - public int getClassIndex() { - return (referenceClassIndex); - } + int getReferenceIndex() { + return (referenceIndex); + } + + int getReferenceKind() { + return (referenceKind); + } + + } - public NameAndTypeEntry getNameAndTypeEntry() { - return (ConstantPool.this.getNameAndTypeEntry(nameAndTypeIndex)); - } + class InvokeDynamicEntry extends Entry { + // http://docs.oracle.com/javase/specs/jvms/se7/html/jvms-4.html#jvms-4.4 - public int getNameAndTypeIndex() { - return (nameAndTypeIndex); - } + private final int bootstrapMethodAttrIndex; - public boolean same(Entry _entry) { - if (_entry instanceof ReferenceEntry) { - final ReferenceEntry entry = (ReferenceEntry) _entry; - return ((referenceClassIndex == entry.referenceClassIndex) && (nameAndTypeIndex == entry.nameAndTypeIndex)); + private final int nameAndTypeIndex; + + InvokeDynamicEntry(ByteReader _byteReader, int _slot) { + super(_byteReader, _slot, ConstantPoolType.INVOKEDYNAMIC); + bootstrapMethodAttrIndex = _byteReader.u2(); + nameAndTypeIndex = _byteReader.u2(); } - return (false); - } - - public class Type{ - private int arrayDimensions = 0; - - public Type(String _type) { - type = _type; - - while (type.charAt(arrayDimensions) == '[') { - arrayDimensions++; - } - type = type.substring(arrayDimensions); - } - - public String getType() { - return (type); - } - - public boolean isVoid() { - return (type.equals("V")); - } - - private String type; - - public boolean isArray() { - return (arrayDimensions > 0); - } - - public int getArrayDimensions() { - return (arrayDimensions); - } - } - } - - public class StringEntry extends Entry{ - private final int utf8Index; - - public StringEntry(ByteReader _byteReader, int _slot) { - super(_byteReader, _slot, ConstantPoolType.STRING); - utf8Index = _byteReader.u2(); - } - - public int getUTF8Index() { - return (utf8Index); - } - - public UTF8Entry getStringUTF8Entry() { - return (getUTF8Entry(utf8Index)); - } - } - - public class UTF8Entry extends Entry{ - private final String UTF8; - - public UTF8Entry(ByteReader _byteReader, int _slot) { - super(_byteReader, _slot, ConstantPoolType.UTF8); - UTF8 = _byteReader.utf8(); - } - - public String getUTF8() { - return (UTF8); - } - } - - public ConstantPool(ByteReader _byteReader) { - final int size = _byteReader.u2(); - add(new EmptyEntry(_byteReader, 0)); // slot 0 - - for (int i = 1; i < size; i++) { - final ConstantPoolType constantPoolType = ConstantPoolType.values()[_byteReader.u1()]; - - switch (constantPoolType) { - case UTF8: - add(new UTF8Entry(_byteReader, i)); - break; - case INTEGER: - add(new IntegerEntry(_byteReader, i)); - break; - case FLOAT: - add(new FloatEntry(_byteReader, i)); - break; - case LONG: - add(new LongEntry(_byteReader, i)); - i++;// Longs take two slots in the ConstantPool - add(new EmptyEntry(_byteReader, i)); - break; - case DOUBLE: - add(new DoubleEntry(_byteReader, i)); - i++; // Doubles take two slots in the ConstantPool - add(new EmptyEntry(_byteReader, i)); - break; - case CLASS: - add(new ClassEntry(_byteReader, i)); - break; - case STRING: - add(new StringEntry(_byteReader, i)); - break; - case FIELD: - add(new FieldEntry(_byteReader, i)); - break; - case METHOD: - add(new MethodEntry(_byteReader, i)); - break; - case INTERFACEMETHOD: - add(new InterfaceMethodEntry(_byteReader, i)); - break; - case NAMEANDTYPE: - add(new NameAndTypeEntry(_byteReader, i)); - break; - case METHODHANDLE: - add(new MethodHandleEntry(_byteReader, i)); - break; - case METHODTYPE: - add(new MethodTypeEntry(_byteReader, i)); - break; - case INVOKEDYNAMIC: - add(new InvokeDynamicEntry(_byteReader, i)); - break; - default: - System.out.printf("slot %04x unexpected Constant constantPoolType = %s\n", i, constantPoolType); - } - } - } - - public ClassEntry getClassEntry(int _index) { - try { - return ((ClassEntry) entries.get(_index)); - } catch (final ClassCastException e) { - return (null); - } - } - - public DoubleEntry getDoubleEntry(int _index) { - try { - return ((DoubleEntry) entries.get(_index)); - } catch (final ClassCastException e) { - return (null); - } - } - - public FieldEntry getFieldEntry(int _index) { - try { - return ((FieldEntry) entries.get(_index)); - } catch (final ClassCastException e) { - return (null); - } - } - - FieldEntry getFieldEntry(String _name) { - for (Entry entry : entries) { - if (entry instanceof FieldEntry) { - String fieldName = ((FieldEntry) entry).getNameAndTypeEntry().getNameUTF8Entry().getUTF8(); - if (_name.equals(fieldName)) { - return (FieldEntry) entry; - } - } - } - return null; - } - - public FloatEntry getFloatEntry(int _index) { - try { - return ((FloatEntry) entries.get(_index)); - } catch (final ClassCastException e) { - return (null); - } - } - - public IntegerEntry getIntegerEntry(int _index) { - try { - return ((IntegerEntry) entries.get(_index)); - } catch (final ClassCastException e) { - return (null); - } - } - - public InterfaceMethodEntry getInterfaceMethodEntry(int _index) { - try { - return ((InterfaceMethodEntry) entries.get(_index)); - } catch (final ClassCastException e) { - return (null); - } - } - - public LongEntry getLongEntry(int _index) { - try { - return ((LongEntry) entries.get(_index)); - } catch (final ClassCastException e) { - return (null); - } - } - - public MethodEntry getMethodEntry(int _index) { - try { - return ((MethodEntry) entries.get(_index)); - } catch (final ClassCastException e) { - return (null); - } - } - - public NameAndTypeEntry getNameAndTypeEntry(int _index) { - try { - return ((NameAndTypeEntry) entries.get(_index)); - } catch (final ClassCastException e) { - return (null); - } - } - - public StringEntry getStringEntry(int _index) { - try { - return ((StringEntry) entries.get(_index)); - } catch (final ClassCastException e) { - return (null); - } - } - - public UTF8Entry getUTF8Entry(int _index) { - try { - return ((UTF8Entry) entries.get(_index)); - } catch (final ClassCastException e) { - return (null); - } - } - - public void add(Entry _entry) { - entries.add(_entry); - - } - - @Override - public Iterator iterator() { - return (entries.iterator()); - } - - public Entry get(int _index) { - return (entries.get(_index)); - } - - public String getDescription(ConstantPool.Entry _entry) { - final StringBuilder sb = new StringBuilder(); - if (_entry instanceof ConstantPool.EmptyEntry) { - ; - } else if (_entry instanceof ConstantPool.DoubleEntry) { - final ConstantPool.DoubleEntry doubleEntry = (ConstantPool.DoubleEntry) _entry; - sb.append(doubleEntry.getDoubleValue()); - } else if (_entry instanceof ConstantPool.FloatEntry) { - final ConstantPool.FloatEntry floatEntry = (ConstantPool.FloatEntry) _entry; - sb.append(floatEntry.getFloatValue()); - } else if (_entry instanceof ConstantPool.IntegerEntry) { - final ConstantPool.IntegerEntry integerEntry = (ConstantPool.IntegerEntry) _entry; - sb.append(integerEntry.getIntValue()); - } else if (_entry instanceof ConstantPool.LongEntry) { - final ConstantPool.LongEntry longEntry = (ConstantPool.LongEntry) _entry; - sb.append(longEntry.getLongValue()); - } else if (_entry instanceof ConstantPool.UTF8Entry) { - final ConstantPool.UTF8Entry utf8Entry = (ConstantPool.UTF8Entry) _entry; - sb.append(utf8Entry.getUTF8()); - } else if (_entry instanceof ConstantPool.StringEntry) { - final ConstantPool.StringEntry stringEntry = (ConstantPool.StringEntry) _entry; - final ConstantPool.UTF8Entry utf8Entry = (ConstantPool.UTF8Entry) get(stringEntry.getUTF8Index()); - sb.append(utf8Entry.getUTF8()); - } else if (_entry instanceof ConstantPool.ClassEntry) { - final ConstantPool.ClassEntry classEntry = (ConstantPool.ClassEntry) _entry; - final ConstantPool.UTF8Entry utf8Entry = (ConstantPool.UTF8Entry) get(classEntry.getNameIndex()); - sb.append(utf8Entry.getUTF8()); - } else if (_entry instanceof ConstantPool.NameAndTypeEntry) { - final ConstantPool.NameAndTypeEntry nameAndTypeEntry = (ConstantPool.NameAndTypeEntry) _entry; - final ConstantPool.UTF8Entry utf8NameEntry = (ConstantPool.UTF8Entry) get(nameAndTypeEntry.getNameIndex()); - final ConstantPool.UTF8Entry utf8DescriptorEntry = (ConstantPool.UTF8Entry) get(nameAndTypeEntry.getDescriptorIndex()); - sb.append(utf8NameEntry.getUTF8() + "." + utf8DescriptorEntry.getUTF8()); - } else if (_entry instanceof ConstantPool.MethodEntry) { - final ConstantPool.MethodEntry methodEntry = (ConstantPool.MethodEntry) _entry; - final ConstantPool.ClassEntry classEntry = (ConstantPool.ClassEntry) get(methodEntry.getClassIndex()); - final ConstantPool.UTF8Entry utf8Entry = (ConstantPool.UTF8Entry) get(classEntry.getNameIndex()); - final ConstantPool.NameAndTypeEntry nameAndTypeEntry = (ConstantPool.NameAndTypeEntry) get(methodEntry - .getNameAndTypeIndex()); - final ConstantPool.UTF8Entry utf8NameEntry = (ConstantPool.UTF8Entry) get(nameAndTypeEntry.getNameIndex()); - final ConstantPool.UTF8Entry utf8DescriptorEntry = (ConstantPool.UTF8Entry) get(nameAndTypeEntry.getDescriptorIndex()); - sb.append(convert(utf8DescriptorEntry.getUTF8(), utf8Entry.getUTF8() + "." + utf8NameEntry.getUTF8())); - } else if (_entry instanceof ConstantPool.InterfaceMethodEntry) { - final ConstantPool.InterfaceMethodEntry interfaceMethodEntry = (ConstantPool.InterfaceMethodEntry) _entry; - final ConstantPool.ClassEntry classEntry = (ConstantPool.ClassEntry) get(interfaceMethodEntry.getClassIndex()); - final ConstantPool.UTF8Entry utf8Entry = (ConstantPool.UTF8Entry) get(classEntry.getNameIndex()); - final ConstantPool.NameAndTypeEntry nameAndTypeEntry = (ConstantPool.NameAndTypeEntry) get(interfaceMethodEntry - .getNameAndTypeIndex()); - final ConstantPool.UTF8Entry utf8NameEntry = (ConstantPool.UTF8Entry) get(nameAndTypeEntry.getNameIndex()); - final ConstantPool.UTF8Entry utf8DescriptorEntry = (ConstantPool.UTF8Entry) get(nameAndTypeEntry.getDescriptorIndex()); - sb.append(convert(utf8DescriptorEntry.getUTF8(), utf8Entry.getUTF8() + "." + utf8NameEntry.getUTF8())); - } else if (_entry instanceof ConstantPool.FieldEntry) { - final ConstantPool.FieldEntry fieldEntry = (ConstantPool.FieldEntry) _entry; - final ConstantPool.ClassEntry classEntry = (ConstantPool.ClassEntry) get(fieldEntry.getClassIndex()); - final ConstantPool.UTF8Entry utf8Entry = (ConstantPool.UTF8Entry) get(classEntry.getNameIndex()); - final ConstantPool.NameAndTypeEntry nameAndTypeEntry = (ConstantPool.NameAndTypeEntry) get(fieldEntry - .getNameAndTypeIndex()); - final ConstantPool.UTF8Entry utf8NameEntry = (ConstantPool.UTF8Entry) get(nameAndTypeEntry.getNameIndex()); - final ConstantPool.UTF8Entry utf8DescriptorEntry = (ConstantPool.UTF8Entry) get(nameAndTypeEntry.getDescriptorIndex()); - sb.append(convert(utf8DescriptorEntry.getUTF8(), utf8Entry.getUTF8() + "." + utf8NameEntry.getUTF8())); - } - - return (sb.toString()); - } - - public int[] getConstantPoolReferences(ConstantPool.Entry _entry) { - int[] references = new int[0]; - if (_entry instanceof ConstantPool.StringEntry) { - final ConstantPool.StringEntry stringEntry = (ConstantPool.StringEntry) _entry; - references = new int[] { - stringEntry.getUTF8Index() - }; - } else if (_entry instanceof ConstantPool.ClassEntry) { - final ConstantPool.ClassEntry classEntry = (ConstantPool.ClassEntry) _entry; - references = new int[] { - classEntry.getNameIndex() - }; - } else if (_entry instanceof ConstantPool.NameAndTypeEntry) { - final ConstantPool.NameAndTypeEntry nameAndTypeEntry = (ConstantPool.NameAndTypeEntry) _entry; - references = new int[] { - nameAndTypeEntry.getNameIndex(), nameAndTypeEntry.getDescriptorIndex() - }; - } else if (_entry instanceof ConstantPool.MethodEntry) { - final ConstantPool.MethodEntry methodEntry = (ConstantPool.MethodEntry) _entry; - final ConstantPool.ClassEntry classEntry = (ConstantPool.ClassEntry) get(methodEntry.getClassIndex()); - @SuppressWarnings("unused") - final ConstantPool.UTF8Entry utf8Entry = (ConstantPool.UTF8Entry) get(classEntry.getNameIndex()); - final ConstantPool.NameAndTypeEntry nameAndTypeEntry = (ConstantPool.NameAndTypeEntry) get(methodEntry - .getNameAndTypeIndex()); - @SuppressWarnings("unused") - final ConstantPool.UTF8Entry utf8NameEntry = (ConstantPool.UTF8Entry) get(nameAndTypeEntry.getNameIndex()); - @SuppressWarnings("unused") - final 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) { - final ConstantPool.InterfaceMethodEntry interfaceMethodEntry = (ConstantPool.InterfaceMethodEntry) _entry; - final ConstantPool.ClassEntry classEntry = (ConstantPool.ClassEntry) get(interfaceMethodEntry.getClassIndex()); - @SuppressWarnings("unused") - final ConstantPool.UTF8Entry utf8Entry = (ConstantPool.UTF8Entry) get(classEntry.getNameIndex()); - final ConstantPool.NameAndTypeEntry nameAndTypeEntry = (ConstantPool.NameAndTypeEntry) get(interfaceMethodEntry - .getNameAndTypeIndex()); - @SuppressWarnings("unused") - final ConstantPool.UTF8Entry utf8NameEntry = (ConstantPool.UTF8Entry) get(nameAndTypeEntry.getNameIndex()); - @SuppressWarnings("unused") - final 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) { - final ConstantPool.FieldEntry fieldEntry = (ConstantPool.FieldEntry) _entry; - final ConstantPool.ClassEntry classEntry = (ConstantPool.ClassEntry) get(fieldEntry.getClassIndex()); - @SuppressWarnings("unused") - final ConstantPool.UTF8Entry utf8Entry = (ConstantPool.UTF8Entry) get(classEntry.getNameIndex()); - final ConstantPool.NameAndTypeEntry nameAndTypeEntry = (ConstantPool.NameAndTypeEntry) get(fieldEntry - .getNameAndTypeIndex()); - @SuppressWarnings("unused") - final ConstantPool.UTF8Entry utf8NameEntry = (ConstantPool.UTF8Entry) get(nameAndTypeEntry.getNameIndex()); - @SuppressWarnings("unused") - final ConstantPool.UTF8Entry utf8DescriptorEntry = (ConstantPool.UTF8Entry) get(nameAndTypeEntry.getDescriptorIndex()); - references = new int[] { - fieldEntry.getClassIndex(), classEntry.getNameIndex(), nameAndTypeEntry.getNameIndex(), - nameAndTypeEntry.getDescriptorIndex() - }; - } - - return (references); - } - - public String getType(ConstantPool.Entry _entry) { - final 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"); - } - - return (sb.toString()); - } - - public Object getConstantEntry(int _constantPoolIndex) { - final Entry entry = get(_constantPoolIndex); - Object object = null; - switch (entry.getConstantPoolType()) { - case FLOAT: - object = ((FloatEntry) entry).getFloatValue(); - break; - case DOUBLE: - object = ((DoubleEntry) entry).getDoubleValue(); - break; - case INTEGER: - object = ((IntegerEntry) entry).getIntValue(); - break; - case LONG: - object = ((LongEntry) entry).getLongValue(); - break; - case STRING: - object = ((StringEntry) entry).getStringUTF8Entry().getUTF8(); - break; - } - - return (object); - } - } - - public class AttributePool { - private final List attributePoolEntries = new ArrayList(); - - public class CodeEntry extends AttributePoolEntry{ - - public class ExceptionPoolEntry{ - private final int exceptionClassIndex; - - private final int end; - - private final int handler; - - private final int start; - - public ExceptionPoolEntry(ByteReader _byteReader) { - start = _byteReader.u2(); - end = _byteReader.u2(); - handler = _byteReader.u2(); - exceptionClassIndex = _byteReader.u2(); - } - - public ConstantPool.ClassEntry getClassEntry() { - return (constantPool.getClassEntry(exceptionClassIndex)); + int getBootstrapMethodAttrIndex() { + return (bootstrapMethodAttrIndex); } - public int getClassIndex() { - return (exceptionClassIndex); + int getNameAndTypeIndex() { + return (nameAndTypeIndex); } - public int getEnd() { - return (end); + } + + public abstract class MethodReferenceEntry extends ReferenceEntry { + + public class Arg extends Type { + Arg(String _signature, int _start, int _pos, int _argc) { + super(_signature.substring(_start, _pos + 1)); + argc = _argc; + } + + private final int argc; + + int getArgc() { + return (argc); + } } - public int getHandler() { - return (handler); + private Arg[] args = null; + + private Type returnType = null; + + @Override + public int hashCode() { + final NameAndTypeEntry nameAndTypeEntry = getNameAndTypeEntry(); + + return ((((nameAndTypeEntry.getNameIndex() * 31) + nameAndTypeEntry.getDescriptorIndex()) * 31) + getClassIndex()); } - public int getStart() { - return (start); + @Override + public boolean equals(Object _other) { + if ((_other == null) || !(_other instanceof MethodReferenceEntry)) { + return (false); + } else { + final MethodReferenceEntry otherMethodReferenceEntry = (MethodReferenceEntry) _other; + return ((otherMethodReferenceEntry.getNameAndTypeEntry().getNameIndex() == getNameAndTypeEntry().getNameIndex()) + && (otherMethodReferenceEntry.getNameAndTypeEntry().getDescriptorIndex() == getNameAndTypeEntry() + .getDescriptorIndex()) && (otherMethodReferenceEntry.getClassIndex() == getClassIndex())); + } + } + + MethodReferenceEntry(ByteReader byteReader, int slot, ConstantPoolType constantPoolType) { + super(byteReader, slot, constantPoolType); + + } + + public int getStackProduceCount() { + return (getReturnType().isVoid() ? 0 : 1); + } + + Type getReturnType() { + if (returnType == null) { + getArgs(); + } + + return (returnType); + } + + public Arg[] getArgs() { + if ((args == null) || (returnType == null)) { + final List argList = new ArrayList<>(); + final NameAndTypeEntry nameAndTypeEntry = getNameAndTypeEntry(); + + final 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++) { + final 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; + } + } + // System.out.println("method "+name+" has signature of "+signature+" which has "+count+" args"); + + args = argList.toArray(new Arg[argList.size()]); + } + + return (args); } - } - private final List exceptionPoolEntries = new ArrayList(); + public int getStackConsumeCount() { + return (getArgs().length); + } + } - private final AttributePool codeEntryAttributePool; + public abstract class ReferenceEntry extends Entry { + final int referenceClassIndex; - private final byte[] code; + final int nameAndTypeIndex; - private final int maxLocals; + protected int argCount = -1; - private final int maxStack; + ReferenceEntry(ByteReader _byteReader, int _slot, ConstantPoolType _constantPoolType) { + super(_byteReader, _slot, _constantPoolType); + referenceClassIndex = _byteReader.u2(); + nameAndTypeIndex = _byteReader.u2(); + } - public CodeEntry(ByteReader _byteReader, int _nameIndex, int _length) { - super(_byteReader, _nameIndex, _length); - maxStack = _byteReader.u2(); - maxLocals = _byteReader.u2(); - final int codeLength = _byteReader.u4(); - code = _byteReader.bytes(codeLength); - final int exceptionTableLength = _byteReader.u2(); + public ClassEntry getClassEntry() { + return (ConstantPool.this.getClassEntry(referenceClassIndex)); + } - for (int i = 0; i < exceptionTableLength; i++) { - exceptionPoolEntries.add(new ExceptionPoolEntry(_byteReader)); + public int getClassIndex() { + return (referenceClassIndex); } - codeEntryAttributePool = new AttributePool(_byteReader, getName()); - } + public NameAndTypeEntry getNameAndTypeEntry() { + return (ConstantPool.this.getNameAndTypeEntry(nameAndTypeIndex)); + } - @Override - public AttributePool getAttributePool() { - return (codeEntryAttributePool); - } + int getNameAndTypeIndex() { + return (nameAndTypeIndex); + } - public LineNumberTableEntry getLineNumberTableEntry() { - return (codeEntryAttributePool.getLineNumberTableEntry()); - } + public boolean same(Entry _entry) { + if (_entry instanceof ReferenceEntry) { + final ReferenceEntry entry = (ReferenceEntry) _entry; + return ((referenceClassIndex == entry.referenceClassIndex) && (nameAndTypeIndex == entry.nameAndTypeIndex)); + } - public int getMaxLocals() { - return (maxLocals); - } + return (false); + } - public int getMaxStack() { - return (maxStack); - } + public class Type { + private int arrayDimensions = 0; - public byte[] getCode() { - return code; - } + Type(String _type) { + type = _type; - public List getExceptionPoolEntries() { - return exceptionPoolEntries; - } - } + while (type.charAt(arrayDimensions) == '[') { + arrayDimensions++; + } + type = type.substring(arrayDimensions); + } - public class ConstantValueEntry extends AttributePoolEntry{ - private final int index; + public String getType() { + return (type); + } - public ConstantValueEntry(ByteReader _byteReader, int _nameIndex, int _length) { - super(_byteReader, _nameIndex, _length); - index = _byteReader.u2(); - } + boolean isVoid() { + return (type.equals("V")); + } - public int getIndex() { - return (index); - } + private String type; - } + public boolean isArray() { + return (arrayDimensions > 0); + } - public class DeprecatedEntry extends AttributePoolEntry{ - public DeprecatedEntry(ByteReader _byteReader, int _nameIndex, int _length) { - super(_byteReader, _nameIndex, _length); - } - } + public int getArrayDimensions() { + return (arrayDimensions); + } + } + } - public abstract class AttributePoolEntry { - protected int length; + public class StringEntry extends Entry { + private final int utf8Index; - protected int nameIndex; + StringEntry(ByteReader _byteReader, int _slot) { + super(_byteReader, _slot, ConstantPoolType.STRING); + utf8Index = _byteReader.u2(); + } - public AttributePoolEntry(ByteReader _byteReader, int _nameIndex, int _length) { - nameIndex = _nameIndex; - length = _length; - } + int getUTF8Index() { + return (utf8Index); + } - public AttributePool getAttributePool() { - return (null); - } + UTF8Entry getStringUTF8Entry() { + return (getUTF8Entry(utf8Index)); + } + } - public int getLength() { - return (length); - } + public class UTF8Entry extends Entry { + private final String UTF8; - public String getName() { - return (constantPool.getUTF8Entry(nameIndex).getUTF8()); - } + UTF8Entry(ByteReader _byteReader, int _slot) { + super(_byteReader, _slot, ConstantPoolType.UTF8); + UTF8 = _byteReader.utf8(); + } - public int getNameIndex() { - return (nameIndex); - } - } + public String getUTF8() { + return (UTF8); + } + } - public abstract class PoolEntry extends AttributePoolEntry implements Iterable{ - private final List pool = new ArrayList(); + ConstantPool(ByteReader _byteReader) { + final int size = _byteReader.u2(); + add(new EmptyEntry(_byteReader, 0)); // slot 0 - public List getPool() { - return (pool); - } + for (int i = 1; i < size; i++) { + final ConstantPoolType constantPoolType = ConstantPoolType.values()[_byteReader.u1()]; - public PoolEntry(ByteReader _byteReader, int _nameIndex, int _length) { - super(_byteReader, _nameIndex, _length); - } + switch (constantPoolType) { + case UTF8: + add(new UTF8Entry(_byteReader, i)); + break; + case INTEGER: + add(new IntegerEntry(_byteReader, i)); + break; + case FLOAT: + add(new FloatEntry(_byteReader, i)); + break; + case LONG: + add(new LongEntry(_byteReader, i)); + i++;// Longs take two slots in the ConstantPool + add(new EmptyEntry(_byteReader, i)); + break; + case DOUBLE: + add(new DoubleEntry(_byteReader, i)); + i++; // Doubles take two slots in the ConstantPool + add(new EmptyEntry(_byteReader, i)); + break; + case CLASS: + add(new ClassEntry(_byteReader, i)); + break; + case STRING: + add(new StringEntry(_byteReader, i)); + break; + case FIELD: + add(new FieldEntry(_byteReader, i)); + break; + case METHOD: + add(new MethodEntry(_byteReader, i)); + break; + case INTERFACEMETHOD: + add(new InterfaceMethodEntry(_byteReader, i)); + break; + case NAMEANDTYPE: + add(new NameAndTypeEntry(_byteReader, i)); + break; + case METHODHANDLE: + add(new MethodHandleEntry(_byteReader, i)); + break; + case METHODTYPE: + add(new MethodTypeEntry(_byteReader, i)); + break; + case INVOKEDYNAMIC: + add(new InvokeDynamicEntry(_byteReader, i)); + break; + default: + System.out.printf("slot %04x unexpected Constant constantPoolType = %s\n", i, constantPoolType); + } + } + } - @Override - public Iterator iterator() { - return (pool.iterator()); - } - } + ClassEntry getClassEntry(int _index) { + try { + return ((ClassEntry) entries.get(_index)); + } catch (final ClassCastException e) { + return (null); + } + } - public class ExceptionEntry extends PoolEntry{ - public ExceptionEntry(ByteReader _byteReader, int _nameIndex, int _length) { - super(_byteReader, _nameIndex, _length); - final int exceptionTableLength = _byteReader.u2(); - for (int i = 0; i < exceptionTableLength; i++) { - getPool().add(_byteReader.u2()); + public DoubleEntry getDoubleEntry(int _index) { + try { + return ((DoubleEntry) entries.get(_index)); + } catch (final ClassCastException e) { + return (null); } - } - } + } - public class InnerClassesEntry extends PoolEntry{ - public class InnerClassInfo { - private final int innerAccess; + public FieldEntry getFieldEntry(int _index) { + try { + return ((FieldEntry) entries.get(_index)); + } catch (final ClassCastException e) { + return (null); + } + } - private final int innerIndex; + FieldEntry getFieldEntry(String _name) { + for (Entry entry : entries) { + if (entry instanceof FieldEntry) { + String fieldName = ((ReferenceEntry) entry).getNameAndTypeEntry().getNameUTF8Entry().getUTF8(); + if (_name.equals(fieldName)) { + return (FieldEntry) entry; + } + } + } + return null; + } - private final int innerNameIndex; + public FloatEntry getFloatEntry(int _index) { + try { + return ((FloatEntry) entries.get(_index)); + } catch (final ClassCastException e) { + return (null); + } + } - private final int outerIndex; + public IntegerEntry getIntegerEntry(int _index) { + try { + return ((IntegerEntry) entries.get(_index)); + } catch (final ClassCastException e) { + return (null); + } + } - public InnerClassInfo(ByteReader _byteReader) { - innerIndex = _byteReader.u2(); - outerIndex = _byteReader.u2(); - innerNameIndex = _byteReader.u2(); - innerAccess = _byteReader.u2(); + public InterfaceMethodEntry getInterfaceMethodEntry(int _index) { + try { + return ((InterfaceMethodEntry) entries.get(_index)); + } catch (final ClassCastException e) { + return (null); } + } - public int getInnerAccess() { - return (innerAccess); + public LongEntry getLongEntry(int _index) { + try { + return ((LongEntry) entries.get(_index)); + } catch (final ClassCastException e) { + return (null); } + } - public int getInnerIndex() { - return (innerIndex); + public MethodEntry getMethodEntry(int _index) { + try { + return ((MethodEntry) entries.get(_index)); + } catch (final ClassCastException e) { + return (null); } + } - public int getInnerNameIndex() { - return (innerNameIndex); + NameAndTypeEntry getNameAndTypeEntry(int _index) { + try { + return ((NameAndTypeEntry) entries.get(_index)); + } catch (final ClassCastException e) { + return (null); } + } - public int getOuterIndex() { - return (outerIndex); + public StringEntry getStringEntry(int _index) { + try { + return ((StringEntry) entries.get(_index)); + } catch (final ClassCastException e) { + return (null); } - } + } - public InnerClassesEntry(ByteReader _byteReader, int _nameIndex, int _length) { - super(_byteReader, _nameIndex, _length); - final int innerClassesTableLength = _byteReader.u2(); - for (int i = 0; i < innerClassesTableLength; i++) { - getPool().add(new InnerClassInfo(_byteReader)); + UTF8Entry getUTF8Entry(int _index) { + try { + return ((UTF8Entry) entries.get(_index)); + } catch (final ClassCastException e) { + return (null); } - } - } + } - public class LineNumberTableEntry extends PoolEntry{ + void add(Entry _entry) { + entries.add(_entry); - public class StartLineNumberPair { - private final int lineNumber; + } - private final int start; + @Override + public Iterator iterator() { + return (entries.iterator()); + } - public StartLineNumberPair(ByteReader _byteReader) { - start = _byteReader.u2(); - lineNumber = _byteReader.u2(); + public Entry get(int _index) { + return (entries.get(_index)); + } + + public String getDescription(ConstantPool.Entry _entry) { + final StringBuilder sb = new StringBuilder(); + if (_entry instanceof ConstantPool.EmptyEntry) { + } else if (_entry instanceof ConstantPool.DoubleEntry) { + final ConstantPool.DoubleEntry doubleEntry = (ConstantPool.DoubleEntry) _entry; + sb.append(doubleEntry.getDoubleValue()); + } else if (_entry instanceof ConstantPool.FloatEntry) { + final ConstantPool.FloatEntry floatEntry = (ConstantPool.FloatEntry) _entry; + sb.append(floatEntry.getFloatValue()); + } else if (_entry instanceof ConstantPool.IntegerEntry) { + final ConstantPool.IntegerEntry integerEntry = (ConstantPool.IntegerEntry) _entry; + sb.append(integerEntry.getIntValue()); + } else if (_entry instanceof ConstantPool.LongEntry) { + final ConstantPool.LongEntry longEntry = (ConstantPool.LongEntry) _entry; + sb.append(longEntry.getLongValue()); + } else if (_entry instanceof ConstantPool.UTF8Entry) { + final ConstantPool.UTF8Entry utf8Entry = (ConstantPool.UTF8Entry) _entry; + sb.append(utf8Entry.getUTF8()); + } else if (_entry instanceof ConstantPool.StringEntry) { + final ConstantPool.StringEntry stringEntry = (ConstantPool.StringEntry) _entry; + final ConstantPool.UTF8Entry utf8Entry = (ConstantPool.UTF8Entry) get(stringEntry.getUTF8Index()); + sb.append(utf8Entry.getUTF8()); + } else if (_entry instanceof ConstantPool.ClassEntry) { + final ConstantPool.ClassEntry classEntry = (ConstantPool.ClassEntry) _entry; + final ConstantPool.UTF8Entry utf8Entry = (ConstantPool.UTF8Entry) get(classEntry.getNameIndex()); + sb.append(utf8Entry.getUTF8()); + } else if (_entry instanceof ConstantPool.NameAndTypeEntry) { + final ConstantPool.NameAndTypeEntry nameAndTypeEntry = (ConstantPool.NameAndTypeEntry) _entry; + final ConstantPool.UTF8Entry utf8NameEntry = (ConstantPool.UTF8Entry) get(nameAndTypeEntry.getNameIndex()); + final ConstantPool.UTF8Entry utf8DescriptorEntry = (ConstantPool.UTF8Entry) get(nameAndTypeEntry.getDescriptorIndex()); + sb.append(utf8NameEntry.getUTF8()).append('.').append(utf8DescriptorEntry.getUTF8()); + } else if (_entry instanceof ConstantPool.MethodEntry) { + final ConstantPool.MethodEntry methodEntry = (ConstantPool.MethodEntry) _entry; + final ConstantPool.ClassEntry classEntry = (ConstantPool.ClassEntry) get(methodEntry.getClassIndex()); + final ConstantPool.UTF8Entry utf8Entry = (ConstantPool.UTF8Entry) get(classEntry.getNameIndex()); + final ConstantPool.NameAndTypeEntry nameAndTypeEntry = (ConstantPool.NameAndTypeEntry) get(methodEntry + .getNameAndTypeIndex()); + final ConstantPool.UTF8Entry utf8NameEntry = (ConstantPool.UTF8Entry) get(nameAndTypeEntry.getNameIndex()); + final ConstantPool.UTF8Entry utf8DescriptorEntry = (ConstantPool.UTF8Entry) get(nameAndTypeEntry.getDescriptorIndex()); + sb.append(convert(utf8DescriptorEntry.getUTF8(), utf8Entry.getUTF8() + '.' + utf8NameEntry.getUTF8())); + } else if (_entry instanceof ConstantPool.InterfaceMethodEntry) { + final ConstantPool.InterfaceMethodEntry interfaceMethodEntry = (ConstantPool.InterfaceMethodEntry) _entry; + final ConstantPool.ClassEntry classEntry = (ConstantPool.ClassEntry) get(interfaceMethodEntry.getClassIndex()); + final ConstantPool.UTF8Entry utf8Entry = (ConstantPool.UTF8Entry) get(classEntry.getNameIndex()); + final ConstantPool.NameAndTypeEntry nameAndTypeEntry = (ConstantPool.NameAndTypeEntry) get(interfaceMethodEntry + .getNameAndTypeIndex()); + final ConstantPool.UTF8Entry utf8NameEntry = (ConstantPool.UTF8Entry) get(nameAndTypeEntry.getNameIndex()); + final ConstantPool.UTF8Entry utf8DescriptorEntry = (ConstantPool.UTF8Entry) get(nameAndTypeEntry.getDescriptorIndex()); + sb.append(convert(utf8DescriptorEntry.getUTF8(), utf8Entry.getUTF8() + '.' + utf8NameEntry.getUTF8())); + } else if (_entry instanceof ConstantPool.FieldEntry) { + final ConstantPool.FieldEntry fieldEntry = (ConstantPool.FieldEntry) _entry; + final ConstantPool.ClassEntry classEntry = (ConstantPool.ClassEntry) get(fieldEntry.getClassIndex()); + final ConstantPool.UTF8Entry utf8Entry = (ConstantPool.UTF8Entry) get(classEntry.getNameIndex()); + final ConstantPool.NameAndTypeEntry nameAndTypeEntry = (ConstantPool.NameAndTypeEntry) get(fieldEntry + .getNameAndTypeIndex()); + final ConstantPool.UTF8Entry utf8NameEntry = (ConstantPool.UTF8Entry) get(nameAndTypeEntry.getNameIndex()); + final ConstantPool.UTF8Entry utf8DescriptorEntry = (ConstantPool.UTF8Entry) get(nameAndTypeEntry.getDescriptorIndex()); + sb.append(convert(utf8DescriptorEntry.getUTF8(), utf8Entry.getUTF8() + '.' + utf8NameEntry.getUTF8())); } - public int getLineNumber() { - return (lineNumber); + return (sb.toString()); + } + + + public int[] getConstantPoolReferences(ConstantPool.Entry _entry) { + int[] references; + if (_entry instanceof ConstantPool.StringEntry) { + final ConstantPool.StringEntry stringEntry = (ConstantPool.StringEntry) _entry; + references = new int[]{ + stringEntry.getUTF8Index() + }; + } else if (_entry instanceof ConstantPool.ClassEntry) { + final ConstantPool.ClassEntry classEntry = (ConstantPool.ClassEntry) _entry; + references = new int[]{ + classEntry.getNameIndex() + }; + } else if (_entry instanceof ConstantPool.NameAndTypeEntry) { + final ConstantPool.NameAndTypeEntry nameAndTypeEntry = (ConstantPool.NameAndTypeEntry) _entry; + references = new int[]{ + nameAndTypeEntry.getNameIndex(), nameAndTypeEntry.getDescriptorIndex() + }; + } else if (_entry instanceof ConstantPool.MethodEntry) { + final ConstantPool.MethodEntry methodEntry = (ConstantPool.MethodEntry) _entry; + final ConstantPool.ClassEntry classEntry = (ConstantPool.ClassEntry) get(methodEntry.getClassIndex()); + @SuppressWarnings("unused") final ConstantPool.UTF8Entry utf8Entry = (ConstantPool.UTF8Entry) get(classEntry.getNameIndex()); + final ConstantPool.NameAndTypeEntry nameAndTypeEntry = (ConstantPool.NameAndTypeEntry) get(methodEntry + .getNameAndTypeIndex()); + @SuppressWarnings("unused") final ConstantPool.UTF8Entry utf8NameEntry = (ConstantPool.UTF8Entry) get(nameAndTypeEntry.getNameIndex()); + @SuppressWarnings("unused") final 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) { + final ConstantPool.InterfaceMethodEntry interfaceMethodEntry = (ConstantPool.InterfaceMethodEntry) _entry; + final ConstantPool.ClassEntry classEntry = (ConstantPool.ClassEntry) get(interfaceMethodEntry.getClassIndex()); + @SuppressWarnings("unused") final ConstantPool.UTF8Entry utf8Entry = (ConstantPool.UTF8Entry) get(classEntry.getNameIndex()); + final ConstantPool.NameAndTypeEntry nameAndTypeEntry = (ConstantPool.NameAndTypeEntry) get(interfaceMethodEntry + .getNameAndTypeIndex()); + @SuppressWarnings("unused") final ConstantPool.UTF8Entry utf8NameEntry = (ConstantPool.UTF8Entry) get(nameAndTypeEntry.getNameIndex()); + @SuppressWarnings("unused") final 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) { + final ConstantPool.FieldEntry fieldEntry = (ConstantPool.FieldEntry) _entry; + final ConstantPool.ClassEntry classEntry = (ConstantPool.ClassEntry) get(fieldEntry.getClassIndex()); + @SuppressWarnings("unused") final ConstantPool.UTF8Entry utf8Entry = (ConstantPool.UTF8Entry) get(classEntry.getNameIndex()); + final ConstantPool.NameAndTypeEntry nameAndTypeEntry = (ConstantPool.NameAndTypeEntry) get(fieldEntry + .getNameAndTypeIndex()); + @SuppressWarnings("unused") final ConstantPool.UTF8Entry utf8NameEntry = (ConstantPool.UTF8Entry) get(nameAndTypeEntry.getNameIndex()); + @SuppressWarnings("unused") final ConstantPool.UTF8Entry utf8DescriptorEntry = (ConstantPool.UTF8Entry) get(nameAndTypeEntry.getDescriptorIndex()); + references = new int[]{ + fieldEntry.getClassIndex(), classEntry.getNameIndex(), nameAndTypeEntry.getNameIndex(), + nameAndTypeEntry.getDescriptorIndex() + }; + } else { + references = new int[0]; } - public int getStart() { - return (start); + return (references); + } + + public String getType(ConstantPool.Entry _entry) { + final StringBuilder sb = new StringBuilder(); + 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"); } - } - public LineNumberTableEntry(ByteReader _byteReader, int _nameIndex, int _length) { - super(_byteReader, _nameIndex, _length); - final int lineNumberTableLength = _byteReader.u2(); - for (int i = 0; i < lineNumberTableLength; i++) { - getPool().add(new StartLineNumberPair(_byteReader)); + return (sb.toString()); + } + + public Object getConstantEntry(int _constantPoolIndex) { + final Entry entry = get(_constantPoolIndex); + Object object = null; + switch (entry.getConstantPoolType()) { + case FLOAT: + object = ((FloatEntry) entry).getFloatValue(); + break; + case DOUBLE: + object = ((DoubleEntry) entry).getDoubleValue(); + break; + case INTEGER: + object = ((IntegerEntry) entry).getIntValue(); + break; + case LONG: + object = ((LongEntry) entry).getLongValue(); + break; + case STRING: + object = ((StringEntry) entry).getStringUTF8Entry().getUTF8(); + break; } - } - public int getSourceLineNumber(int _start, boolean _exact) { - final Iterator i = getPool().iterator(); - if (i.hasNext()) { - StartLineNumberPair from = i.next(); - while (i.hasNext()) { - final StartLineNumberPair to = i.next(); - if (_exact) { - if (_start == from.getStart()) { - return (from.getLineNumber()); - } - } else if ((_start >= from.getStart()) && (_start < to.getStart())) { - return (from.getLineNumber()); - } - from = to; - } - if (_exact) { - if (_start == from.getStart()) { - return (from.getLineNumber()); - } - } else if (_start >= from.getStart()) { - return (from.getLineNumber()); - } + return (object); + } + } + + public class AttributePool { + private final List attributePoolEntries = new ArrayList<>(); + + public class CodeEntry extends AttributePoolEntry { + + class ExceptionPoolEntry { + private final int exceptionClassIndex; + + private final int end; + + private final int handler; + + private final int start; + + ExceptionPoolEntry(ByteReader _byteReader) { + start = _byteReader.u2(); + end = _byteReader.u2(); + handler = _byteReader.u2(); + exceptionClassIndex = _byteReader.u2(); + } + + public ConstantPool.ClassEntry getClassEntry() { + return (constantPool.getClassEntry(exceptionClassIndex)); + } + + public int getClassIndex() { + return (exceptionClassIndex); + } + + public int getEnd() { + return (end); + } + + public int getHandler() { + return (handler); + } + + public int getStart() { + return (start); + } } - return (-1); - } - } + private final List exceptionPoolEntries = new ArrayList<>(); - public class EnclosingMethodEntry extends AttributePoolEntry{ + private final AttributePool codeEntryAttributePool; - public EnclosingMethodEntry(ByteReader _byteReader, int _nameIndex, int _length) { - super(_byteReader, _nameIndex, _length); - enclosingClassIndex = _byteReader.u2(); - enclosingMethodIndex = _byteReader.u2(); - } + private final byte[] code; - private final int enclosingClassIndex; + private final int maxLocals; - public int getClassIndex() { - return (enclosingClassIndex); - } + private final int maxStack; - private final int enclosingMethodIndex; + CodeEntry(ByteReader _byteReader, int _nameIndex, int _length) { + super(_byteReader, _nameIndex, _length); + maxStack = _byteReader.u2(); + maxLocals = _byteReader.u2(); + final int codeLength = _byteReader.u4(); + code = _byteReader.bytes(codeLength); + final int exceptionTableLength = _byteReader.u2(); - public int getMethodIndex() { - return (enclosingMethodIndex); - } - } + for (int i = 0; i < exceptionTableLength; i++) { + exceptionPoolEntries.add(new ExceptionPoolEntry(_byteReader)); + } - public class SignatureEntry extends AttributePoolEntry{ + codeEntryAttributePool = new AttributePool(_byteReader, getName()); + } - public SignatureEntry(ByteReader _byteReader, int _nameIndex, int _length) { - super(_byteReader, _nameIndex, _length); - signatureIndex = _byteReader.u2(); - } + @Override + public AttributePool getAttributePool() { + return (codeEntryAttributePool); + } - private final int signatureIndex; + public LineNumberTableEntry getLineNumberTableEntry() { + return (codeEntryAttributePool.getLineNumberTableEntry()); + } - int getSignatureIndex() { - return (signatureIndex); - } - } + public int getMaxLocals() { + return (maxLocals); + } - public class RealLocalVariableTableEntry extends PoolEntry implements - LocalVariableTableEntry{ + public int getMaxStack() { + return (maxStack); + } - class RealLocalVariableInfo implements LocalVariableInfo{ - private final int descriptorIndex; + byte[] getCode() { + return code; + } + + public List getExceptionPoolEntries() { + return exceptionPoolEntries; + } + } - private final int usageLength; + class ConstantValueEntry extends AttributePoolEntry { + private final int index; + + ConstantValueEntry(ByteReader _byteReader, int _nameIndex, int _length) { + super(_byteReader, _nameIndex, _length); + index = _byteReader.u2(); + } - private final int variableNameIndex; + public int getIndex() { + return (index); + } + + } + + public class DeprecatedEntry extends AttributePoolEntry { + DeprecatedEntry(ByteReader _byteReader, int _nameIndex, int _length) { + super(_byteReader, _nameIndex, _length); + } + } - private final int start; + abstract class AttributePoolEntry { + final int length; - private final int variableIndex; + final int nameIndex; - public RealLocalVariableInfo(ByteReader _byteReader) { - start = _byteReader.u2(); - usageLength = _byteReader.u2(); - variableNameIndex = _byteReader.u2(); - descriptorIndex = _byteReader.u2(); - variableIndex = _byteReader.u2(); + AttributePoolEntry(ByteReader _byteReader, int _nameIndex, int _length) { + nameIndex = _nameIndex; + length = _length; } - public int getDescriptorIndex() { - return (descriptorIndex); + public AttributePool getAttributePool() { + return (null); } public int getLength() { - return (usageLength); + return (length); + } + + String getName() { + return (constantPool.getUTF8Entry(nameIndex).getUTF8()); } public int getNameIndex() { - return (variableNameIndex); + return (nameIndex); } + } - @Override - public int getStart() { - return (start); + abstract class PoolEntry extends AttributePoolEntry implements Iterable { + private final List pool = new ArrayList<>(); + + List getPool() { + return (pool); } - @Override - public int getVariableIndex() { - return (variableIndex); + PoolEntry(ByteReader _byteReader, int _nameIndex, int _length) { + super(_byteReader, _nameIndex, _length); } @Override - public String getVariableName() { - return (constantPool.getUTF8Entry(variableNameIndex).getUTF8()); + public Iterator iterator() { + return (pool.iterator()); } + } - @Override - public String getVariableDescriptor() { - return (constantPool.getUTF8Entry(descriptorIndex).getUTF8()); + public class ExceptionEntry extends PoolEntry { + ExceptionEntry(ByteReader _byteReader, int _nameIndex, int _length) { + super(_byteReader, _nameIndex, _length); + final int exceptionTableLength = _byteReader.u2(); + for (int i = 0; i < exceptionTableLength; i++) { + getPool().add(_byteReader.u2()); + } } + } - @Override - public int getEnd() { - return (start + usageLength); + class InnerClassesEntry extends PoolEntry { + class InnerClassInfo { + private final int innerAccess; + + private final int innerIndex; + + private final int innerNameIndex; + + private final int outerIndex; + + InnerClassInfo(ByteReader _byteReader) { + innerIndex = _byteReader.u2(); + outerIndex = _byteReader.u2(); + innerNameIndex = _byteReader.u2(); + innerAccess = _byteReader.u2(); + } + + public int getInnerAccess() { + return (innerAccess); + } + + public int getInnerIndex() { + return (innerIndex); + } + + public int getInnerNameIndex() { + return (innerNameIndex); + } + + public int getOuterIndex() { + return (outerIndex); + } } - @Override - public boolean isArray() { - return (getVariableDescriptor().startsWith("[")); + InnerClassesEntry(ByteReader _byteReader, int _nameIndex, int _length) { + super(_byteReader, _nameIndex, _length); + final int innerClassesTableLength = _byteReader.u2(); + for (int i = 0; i < innerClassesTableLength; i++) { + getPool().add(new InnerClassInfo(_byteReader)); + } } - } + } - public RealLocalVariableTableEntry(ByteReader _byteReader, int _nameIndex, int _length) { - super(_byteReader, _nameIndex, _length); - final int localVariableTableLength = _byteReader.u2(); - for (int i = 0; i < localVariableTableLength; i++) { - getPool().add(new RealLocalVariableInfo(_byteReader)); + public class LineNumberTableEntry extends PoolEntry { + + class StartLineNumberPair { + private final int lineNumber; + + private final int start; + + StartLineNumberPair(ByteReader _byteReader) { + start = _byteReader.u2(); + lineNumber = _byteReader.u2(); + } + + int getLineNumber() { + return (lineNumber); + } + + int getStart() { + return (start); + } } - } - public RealLocalVariableInfo getVariable(int _pc, int _index) { - RealLocalVariableInfo returnValue = null; - // System.out.println("pc = " + _pc + " index = " + _index); - for (final RealLocalVariableInfo 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; - break; - } + LineNumberTableEntry(ByteReader _byteReader, int _nameIndex, int _length) { + super(_byteReader, _nameIndex, _length); + final int lineNumberTableLength = _byteReader.u2(); + for (int i = 0; i < lineNumberTableLength; i++) { + getPool().add(new StartLineNumberPair(_byteReader)); + } } - // System.out.println("returning " + returnValue); - return (returnValue); - } + public int getSourceLineNumber(int _start, boolean _exact) { + final Iterator i = getPool().iterator(); + if (i.hasNext()) { + StartLineNumberPair from = i.next(); + while (i.hasNext()) { + final StartLineNumberPair to = i.next(); + if (_exact) { + if (_start == from.getStart()) { + return (from.getLineNumber()); + } + } else if ((_start >= from.getStart()) && (_start < to.getStart())) { + return (from.getLineNumber()); + } + from = to; + } + if (_exact) { + if (_start == from.getStart()) { + return (from.getLineNumber()); + } + } else if (_start >= from.getStart()) { + return (from.getLineNumber()); + } + } - public String getVariableName(int _pc, int _index) { - String returnValue = "unknown"; - final RealLocalVariableInfo localVariableInfo = (RealLocalVariableInfo) getVariable(_pc, _index); - if (localVariableInfo != null) { - returnValue = convert(constantPool.getUTF8Entry(localVariableInfo.getDescriptorIndex()).getUTF8(), constantPool - .getUTF8Entry(localVariableInfo.getNameIndex()).getUTF8()); + return (-1); } - // System.out.println("returning " + returnValue); - return (returnValue); - } - } + } - 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) { - argument = _byteReader.u2(); - } + class EnclosingMethodEntry extends AttributePoolEntry { - int argument;// u2; + EnclosingMethodEntry(ByteReader _byteReader, int _nameIndex, int _length) { + super(_byteReader, _nameIndex, _length); + enclosingClassIndex = _byteReader.u2(); + enclosingMethodIndex = _byteReader.u2(); } - public BootstrapMethod(ByteReader _byteReader) { - bootstrapMethodRef = _byteReader.u2(); - numBootstrapArguments = _byteReader.u2(); - bootstrapArguments = new BootstrapArgument[numBootstrapArguments]; - for (int i = 0; i < numBootstrapArguments; i++) { - bootstrapArguments[i] = new BootstrapArgument(_byteReader); - } + private final int enclosingClassIndex; + + public int getClassIndex() { + return (enclosingClassIndex); } - int bootstrapMethodRef; //u2 - - int numBootstrapArguments; //u2 + private final int enclosingMethodIndex; - BootstrapArgument bootstrapArguments[]; - } + public int getMethodIndex() { + return (enclosingMethodIndex); + } + } - BootstrapMethodsEntry(ByteReader _byteReader, int _nameIndex, int _length) { - super(_byteReader, _nameIndex, _length); - numBootstrapMethods = _byteReader.u2(); - bootstrapMethods = new BootstrapMethod[numBootstrapMethods]; - for (int i = 0; i < numBootstrapMethods; i++) { - bootstrapMethods[i] = new BootstrapMethod(_byteReader); + class SignatureEntry extends AttributePoolEntry { + + SignatureEntry(ByteReader _byteReader, int _nameIndex, int _length) { + super(_byteReader, _nameIndex, _length); + signatureIndex = _byteReader.u2(); } - } - private int numBootstrapMethods; + private final int signatureIndex; - BootstrapMethod bootstrapMethods[]; + int getSignatureIndex() { + return (signatureIndex); + } + } - int getNumBootstrapMethods() { - return (numBootstrapMethods); - } + public class RealLocalVariableTableEntry extends PoolEntry implements + LocalVariableTableEntry { - } + class RealLocalVariableInfo implements LocalVariableInfo { + private final int descriptorIndex; - public class OtherEntry extends AttributePoolEntry{ - private final byte[] bytes; + private final int usageLength; - public OtherEntry(ByteReader _byteReader, int _nameIndex, int _length) { - super(_byteReader, _nameIndex, _length); - bytes = _byteReader.bytes(_length); - } + private final int variableNameIndex; - public byte[] getBytes() { - return (bytes); - } + private final int start; - @Override - public String toString() { - return (new String(bytes)); - } + private final int variableIndex; - } + RealLocalVariableInfo(ByteReader _byteReader) { + start = _byteReader.u2(); + usageLength = _byteReader.u2(); + variableNameIndex = _byteReader.u2(); + descriptorIndex = _byteReader.u2(); + variableIndex = _byteReader.u2(); + } - class StackMapTableEntry extends AttributePoolEntry{ - private byte[] bytes; + int getDescriptorIndex() { + return (descriptorIndex); + } - StackMapTableEntry(ByteReader _byteReader, int _nameIndex, int _length) { - super(_byteReader, _nameIndex, _length); - bytes = _byteReader.bytes(_length); - } - - byte[] getBytes() { - return (bytes); - } + @Override + public int getLength() { + return (usageLength); + } - @Override - public String toString() { - return (new String(bytes)); - } - } + int getNameIndex() { + return (variableNameIndex); + } - public class LocalVariableTypeTableEntry extends AttributePoolEntry{ - private byte[] bytes; + @Override + public int getStart() { + return (start); + } - public LocalVariableTypeTableEntry(ByteReader _byteReader, int _nameIndex, int _length) { - super(_byteReader, _nameIndex, _length); - bytes = _byteReader.bytes(_length); - } + @Override + public int getVariableIndex() { + return (variableIndex); + } - public byte[] getBytes() { - return (bytes); - } + @Override + public String getVariableName() { + return (constantPool.getUTF8Entry(variableNameIndex).getUTF8()); + } - @Override - public String toString() { - return (new String(bytes)); - } - } + @Override + public String getVariableDescriptor() { + return (constantPool.getUTF8Entry(descriptorIndex).getUTF8()); + } - public class SourceFileEntry extends AttributePoolEntry{ - private final int sourceFileIndex; + @Override + public int getEnd() { + return (start + usageLength); + } - public SourceFileEntry(ByteReader _byteReader, int _nameIndex, int _length) { - super(_byteReader, _nameIndex, _length); - sourceFileIndex = _byteReader.u2(); - } + @Override + public boolean isArray() { + return (getVariableDescriptor().startsWith("[")); + } + } - public int getSourceFileIndex() { - return (sourceFileIndex); - } - - public String getSourceFileName() { - return (constantPool.getUTF8Entry(sourceFileIndex).getUTF8()); - } - } + RealLocalVariableTableEntry(ByteReader _byteReader, int _nameIndex, int _length) { + super(_byteReader, _nameIndex, _length); + final int localVariableTableLength = _byteReader.u2(); + for (int i = 0; i < localVariableTableLength; i++) { + getPool().add(new RealLocalVariableInfo(_byteReader)); + } + } - public class SyntheticEntry extends AttributePoolEntry{ - public SyntheticEntry(ByteReader _byteReader, int _nameIndex, int _length) { - super(_byteReader, _nameIndex, _length); - } - } - - public class RuntimeAnnotationsEntry extends PoolEntry{ - - public class AnnotationInfo { - private final int typeIndex; - - private final int elementValuePairCount; - - public class ElementValuePair{ - class Value { - Value(int _tag) { - tag = _tag; - } - - int tag; - - } - - public class PrimitiveValue extends Value{ - private final int typeNameIndex; - - private final int constNameIndex; - - public PrimitiveValue(int _tag, ByteReader _byteReader) { - super(_tag); - typeNameIndex = _byteReader.u2(); - //constNameIndex = _byteReader.u2(); - constNameIndex = 0; - } - - public int getConstNameIndex() { - return (constNameIndex); - } - - public int getTypeNameIndex() { - return (typeNameIndex); - } - } - - public class EnumValue extends Value{ - EnumValue(int _tag, ByteReader _byteReader) { - super(_tag); - } - } - - public class ArrayValue extends Value{ - ArrayValue(int _tag, ByteReader _byteReader) { - super(_tag); - } - } - - public class ClassValue extends Value{ - ClassValue(int _tag, ByteReader _byteReader) { - super(_tag); - } - } - - public class AnnotationValue extends Value{ - AnnotationValue(int _tag, ByteReader _byteReader) { - super(_tag); - } - } - - @SuppressWarnings("unused") - private final int elementNameIndex; - - @SuppressWarnings("unused") - private Value value; - - public ElementValuePair(ByteReader _byteReader) { - elementNameIndex = _byteReader.u2(); - final int tag = _byteReader.u1(); - - switch (tag) { - case SIGC_BYTE: - case SIGC_CHAR: - case SIGC_INT: - case SIGC_LONG: - case SIGC_DOUBLE: - case SIGC_FLOAT: - case SIGC_SHORT: - case SIGC_BOOLEAN: - case 's': // special for String - value = new PrimitiveValue(tag, _byteReader); - break; - case 'e': // special for Enum - value = new EnumValue(tag, _byteReader); - break; - case 'c': // special for class - value = new ClassValue(tag, _byteReader); - break; - case '@': // special for Annotation - value = new AnnotationValue(tag, _byteReader); - break; - case 'a': // special for array - value = new ArrayValue(tag, _byteReader); + @Override + public RealLocalVariableInfo getVariable(int _pc, int _index) { + RealLocalVariableInfo returnValue = null; + // System.out.println("pc = " + _pc + " index = " + _index); + for (final RealLocalVariableInfo 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; break; - } - } - } + } + } - private final ElementValuePair[] elementValuePairs; + // System.out.println("returning " + returnValue); + return (returnValue); + } - public AnnotationInfo(ByteReader _byteReader) { - typeIndex = _byteReader.u2(); - elementValuePairCount = _byteReader.u2(); - elementValuePairs = new ElementValuePair[elementValuePairCount]; - for (int i = 0; i < elementValuePairCount; i++) { - elementValuePairs[i] = new ElementValuePair(_byteReader); - } + public String getVariableName(int _pc, int _index) { + String returnValue = "unknown"; + final RealLocalVariableInfo localVariableInfo = getVariable(_pc, _index); + if (localVariableInfo != null) { + returnValue = convert(constantPool.getUTF8Entry(localVariableInfo.getDescriptorIndex()).getUTF8(), constantPool + .getUTF8Entry(localVariableInfo.getNameIndex()).getUTF8()); + } + // System.out.println("returning " + returnValue); + return (returnValue); } + } + + class BootstrapMethodsEntry extends AttributePoolEntry { + // http://docs.oracle.com/javase/specs/jvms/se7/html/jvms-4.html#jvms-4.7.21 + class BootstrapMethod { + class BootstrapArgument { + BootstrapArgument(ByteReader _byteReader) { + argument = _byteReader.u2(); + } + + final int argument;// u2; + } + + BootstrapMethod(ByteReader _byteReader) { + bootstrapMethodRef = _byteReader.u2(); + numBootstrapArguments = _byteReader.u2(); + bootstrapArguments = new BootstrapArgument[numBootstrapArguments]; + for (int i = 0; i < numBootstrapArguments; i++) { + bootstrapArguments[i] = new BootstrapArgument(_byteReader); + } + } - public int getTypeIndex() { - return (typeIndex); + final int bootstrapMethodRef; //u2 + + final int numBootstrapArguments; //u2 + + final BootstrapArgument[] bootstrapArguments; } - public String getTypeDescriptor() { - return (constantPool.getUTF8Entry(typeIndex).getUTF8()); + BootstrapMethodsEntry(ByteReader _byteReader, int _nameIndex, int _length) { + super(_byteReader, _nameIndex, _length); + numBootstrapMethods = _byteReader.u2(); + bootstrapMethods = new BootstrapMethod[numBootstrapMethods]; + for (int i = 0; i < numBootstrapMethods; i++) { + bootstrapMethods[i] = new BootstrapMethod(_byteReader); + } } - } - public RuntimeAnnotationsEntry(ByteReader _byteReader, int _nameIndex, int _length) { - super(_byteReader, _nameIndex, _length); - final int localVariableTableLength = _byteReader.u2(); - for (int i = 0; i < localVariableTableLength; i++) { - getPool().add(new AnnotationInfo(_byteReader)); + private final int numBootstrapMethods; + + final BootstrapMethod[] bootstrapMethods; + + int getNumBootstrapMethods() { + return (numBootstrapMethods); } - } - } + } - private CodeEntry codeEntry = null; + class OtherEntry extends AttributePoolEntry { + private final byte[] bytes; - private EnclosingMethodEntry enclosingMethodEntry = null; + OtherEntry(ByteReader _byteReader, int _nameIndex, int _length) { + super(_byteReader, _nameIndex, _length); + bytes = _byteReader.bytes(_length); + } + + public byte[] getBytes() { + return (bytes); + } - private DeprecatedEntry deprecatedEntry = null; + @Override + public String toString() { + return (new String(bytes)); + } - private ExceptionEntry exceptionEntry = null; + } - private LineNumberTableEntry lineNumberTableEntry = null; + class StackMapTableEntry extends AttributePoolEntry { + private final byte[] bytes; - private LocalVariableTableEntry localVariableTableEntry = null; + StackMapTableEntry(ByteReader _byteReader, int _nameIndex, int _length) { + super(_byteReader, _nameIndex, _length); + bytes = _byteReader.bytes(_length); + } - private RuntimeAnnotationsEntry runtimeVisibleAnnotationsEntry; + byte[] getBytes() { + return (bytes); + } - private RuntimeAnnotationsEntry runtimeInvisibleAnnotationsEntry; + @Override + public String toString() { + return (new String(bytes)); + } + } - private SourceFileEntry sourceFileEntry = null; + class LocalVariableTypeTableEntry extends AttributePoolEntry { + private final byte[] bytes; - private SyntheticEntry syntheticEntry = null; + LocalVariableTypeTableEntry(ByteReader _byteReader, int _nameIndex, int _length) { + super(_byteReader, _nameIndex, _length); + bytes = _byteReader.bytes(_length); + } - private BootstrapMethodsEntry bootstrapMethodsEntry = null; + public byte[] getBytes() { + return (bytes); + } - private final static String LOCALVARIABLETABLE_TAG = "LocalVariableTable"; + @Override + public String toString() { + return (new String(bytes)); + } + } + + public class SourceFileEntry extends AttributePoolEntry { + private final int sourceFileIndex; + + SourceFileEntry(ByteReader _byteReader, int _nameIndex, int _length) { + super(_byteReader, _nameIndex, _length); + sourceFileIndex = _byteReader.u2(); + } + + public int getSourceFileIndex() { + return (sourceFileIndex); + } + + public String getSourceFileName() { + return (constantPool.getUTF8Entry(sourceFileIndex).getUTF8()); + } + } + + public class SyntheticEntry extends AttributePoolEntry { + SyntheticEntry(ByteReader _byteReader, int _nameIndex, int _length) { + super(_byteReader, _nameIndex, _length); + } + } + + public class RuntimeAnnotationsEntry extends PoolEntry { + + public class AnnotationInfo { + private final int typeIndex; + +// private final int elementValuePairCount; +// +// public class ElementValuePair { +// class Value { +// Value(int _tag) { +// tag = _tag; +// } +// +// final int tag; +// +// } +// +// class PrimitiveValue extends Value { +// private final int typeNameIndex; +// +// private final int constNameIndex; +// +// PrimitiveValue(int _tag, ByteReader _byteReader) { +// super(_tag); +// typeNameIndex = _byteReader.u2(); +// //constNameIndex = _byteReader.u2(); +// constNameIndex = 0; +// } +// +// public int getConstNameIndex() { +// return (constNameIndex); +// } +// +// public int getTypeNameIndex() { +// return (typeNameIndex); +// } +// } +// +// class EnumValue extends Value { +// EnumValue(int _tag, ByteReader _byteReader) { +// super(_tag); +// } +// } +// +// class ArrayValue extends Value { +// ArrayValue(int _tag, ByteReader _byteReader) { +// super(_tag); +// } +// } +// +// class ClassValue extends Value { +// ClassValue(int _tag, ByteReader _byteReader) { +// super(_tag); +// } +// } +// +// class AnnotationValue extends Value { +// AnnotationValue(int _tag, ByteReader _byteReader) { +// super(_tag); +// } +// } +// +// @SuppressWarnings("unused") +// private final int elementNameIndex; +// +// @SuppressWarnings("unused") +// private Value value; +// +// ElementValuePair(ByteReader _byteReader) { +// elementNameIndex = _byteReader.u2(); +// final int tag = _byteReader.u1(); +// +// switch (tag) { +// case SIGC_BYTE: +// case SIGC_CHAR: +// case SIGC_INT: +// case SIGC_LONG: +// case SIGC_DOUBLE: +// case SIGC_FLOAT: +// case SIGC_SHORT: +// case SIGC_BOOLEAN: +// case 's': // special for String +// value = new PrimitiveValue(tag, _byteReader); +// break; +// case 'e': // special for Enum +// value = new EnumValue(tag, _byteReader); +// break; +// case 'c': // special for class +// value = new ClassValue(tag, _byteReader); +// break; +// case '@': // special for Annotation +// value = new AnnotationValue(tag, _byteReader); +// break; +// case 'a': // special for array +// value = new ArrayValue(tag, _byteReader); +// break; +// } +// } +// } +// private final ElementValuePair[] elementValuePairs; + + AnnotationInfo(ByteReader _byteReader) { + typeIndex = _byteReader.u2(); +// elementValuePairCount = _byteReader.u2(); +// elementValuePairs = new ElementValuePair[elementValuePairCount]; +// for (int i = 0; i < elementValuePairCount; i++) { +// elementValuePairs[i] = new ElementValuePair(_byteReader); +// } + } + + public int getTypeIndex() { + return (typeIndex); + } + + public String getTypeDescriptor() { + return (constantPool.getUTF8Entry(typeIndex).getUTF8()); + } + } + + RuntimeAnnotationsEntry(ByteReader _byteReader, int _nameIndex, int _length) { + super(_byteReader, _nameIndex, _length); + final int localVariableTableLength = _byteReader.u2(); + for (int i = 0; i < localVariableTableLength; i++) { + getPool().add(new AnnotationInfo(_byteReader)); + } + } + + } + + private CodeEntry codeEntry = null; + + private EnclosingMethodEntry enclosingMethodEntry = null; + + private DeprecatedEntry deprecatedEntry = null; + + private ExceptionEntry exceptionEntry = null; + + private LineNumberTableEntry lineNumberTableEntry = null; + + private LocalVariableTableEntry localVariableTableEntry = null; + + private RuntimeAnnotationsEntry runtimeVisibleAnnotationsEntry; + + private RuntimeAnnotationsEntry runtimeInvisibleAnnotationsEntry; + + private SourceFileEntry sourceFileEntry = null; + + private SyntheticEntry syntheticEntry = null; + + private BootstrapMethodsEntry bootstrapMethodsEntry = null; + + private final static String LOCALVARIABLETABLE_TAG = "LocalVariableTable"; + + private final static String CONSTANTVALUE_TAG = "ConstantValue"; + + private final static String LINENUMBERTABLE_TAG = "LineNumberTable"; - private final static String CONSTANTVALUE_TAG = "ConstantValue"; + private final static String SOURCEFILE_TAG = "SourceFile"; - private final static String LINENUMBERTABLE_TAG = "LineNumberTable"; + private final static String SYNTHETIC_TAG = "Synthetic"; - private final static String SOURCEFILE_TAG = "SourceFile"; + private final static String EXCEPTIONS_TAG = "Exceptions"; - private final static String SYNTHETIC_TAG = "Synthetic"; + private final static String INNERCLASSES_TAG = "InnerClasses"; - private final static String EXCEPTIONS_TAG = "Exceptions"; + private final static String DEPRECATED_TAG = "Deprecated"; - private final static String INNERCLASSES_TAG = "InnerClasses"; + private final static String CODE_TAG = "Code"; - private final static String DEPRECATED_TAG = "Deprecated"; + private final static String ENCLOSINGMETHOD_TAG = "EnclosingMethod"; - private final static String CODE_TAG = "Code"; + private final static String SIGNATURE_TAG = "Signature"; - private final static String ENCLOSINGMETHOD_TAG = "EnclosingMethod"; + private final static String RUNTIMEINVISIBLEANNOTATIONS_TAG = "RuntimeInvisibleAnnotations"; - private final static String SIGNATURE_TAG = "Signature"; + private final static String RUNTIMEVISIBLEANNOTATIONS_TAG = "RuntimeVisibleAnnotations"; - private final static String RUNTIMEINVISIBLEANNOTATIONS_TAG = "RuntimeInvisibleAnnotations"; + private final static String BOOTSTRAPMETHODS_TAG = "BootstrapMethods"; - private final static String RUNTIMEVISIBLEANNOTATIONS_TAG = "RuntimeVisibleAnnotations"; + private final static String STACKMAPTABLE_TAG = "StackMapTable"; - private final static String BOOTSTRAPMETHODS_TAG = "BootstrapMethods"; + private final static String LOCALVARIABLETYPETABLE_TAG = "LocalVariableTypeTable"; - private final static String STACKMAPTABLE_TAG = "StackMapTable"; + AttributePool(ByteReader _byteReader, String name) { + final int attributeCount = _byteReader.u2(); + AttributePoolEntry entry = null; + for (int i = 0; i < attributeCount; i++) { + final int attributeNameIndex = _byteReader.u2(); + final int length = _byteReader.u4(); + UTF8Entry utf8Entry = constantPool.getUTF8Entry(attributeNameIndex); + if (utf8Entry == null) { + throw new IllegalStateException("corrupted state reading attributes for " + name); + } + final String attributeName = utf8Entry.getUTF8(); + switch (attributeName) { + case LOCALVARIABLETABLE_TAG: + localVariableTableEntry = new RealLocalVariableTableEntry(_byteReader, attributeNameIndex, length); + entry = (AttributePoolEntry) localVariableTableEntry; + break; + case CONSTANTVALUE_TAG: + entry = new ConstantValueEntry(_byteReader, attributeNameIndex, length); + break; + case LINENUMBERTABLE_TAG: + lineNumberTableEntry = new LineNumberTableEntry(_byteReader, attributeNameIndex, length); + entry = lineNumberTableEntry; + break; + case SOURCEFILE_TAG: + sourceFileEntry = new SourceFileEntry(_byteReader, attributeNameIndex, length); + entry = sourceFileEntry; + break; + case SYNTHETIC_TAG: + syntheticEntry = new SyntheticEntry(_byteReader, attributeNameIndex, length); + entry = syntheticEntry; + break; + case EXCEPTIONS_TAG: + exceptionEntry = new ExceptionEntry(_byteReader, attributeNameIndex, length); + entry = exceptionEntry; + break; + case INNERCLASSES_TAG: + entry = new InnerClassesEntry(_byteReader, attributeNameIndex, length); + break; + case DEPRECATED_TAG: + deprecatedEntry = new DeprecatedEntry(_byteReader, attributeNameIndex, length); + entry = deprecatedEntry; + break; + case CODE_TAG: + codeEntry = new CodeEntry(_byteReader, attributeNameIndex, length); + entry = codeEntry; + break; + case ENCLOSINGMETHOD_TAG: + enclosingMethodEntry = new EnclosingMethodEntry(_byteReader, attributeNameIndex, length); + entry = enclosingMethodEntry; + break; + case SIGNATURE_TAG: + entry = new SignatureEntry(_byteReader, attributeNameIndex, length); + break; + case RUNTIMEINVISIBLEANNOTATIONS_TAG: + runtimeInvisibleAnnotationsEntry = new RuntimeAnnotationsEntry(_byteReader, attributeNameIndex, length); + entry = runtimeInvisibleAnnotationsEntry; + break; + case RUNTIMEVISIBLEANNOTATIONS_TAG: + runtimeVisibleAnnotationsEntry = new RuntimeAnnotationsEntry(_byteReader, attributeNameIndex, length); + entry = runtimeVisibleAnnotationsEntry; + break; + case BOOTSTRAPMETHODS_TAG: + bootstrapMethodsEntry = new BootstrapMethodsEntry(_byteReader, attributeNameIndex, length); + entry = bootstrapMethodsEntry; + // http://docs.oracle.com/javase/specs/jvms/se7/html/jvms-4.html#jvms-4.7.21 + break; + case STACKMAPTABLE_TAG: + // http://docs.oracle.com/javase/specs/jvms/se7/html/jvms-4.html#jvms-4.7.4 - private final static String LOCALVARIABLETYPETABLE_TAG = "LocalVariableTypeTable"; + entry = new StackMapTableEntry(_byteReader, attributeNameIndex, length); + break; + case LOCALVARIABLETYPETABLE_TAG: + // http://docs.oracle.com/javase/specs/jvms/se7/html/jvms-4.html#jvms-4.7.14 + entry = new LocalVariableTypeTableEntry(_byteReader, attributeNameIndex, length); + break; + default: + logger.warning("Found unexpected Attribute (name = " + attributeName + ')'); + entry = new OtherEntry(_byteReader, attributeNameIndex, length); + break; + } + attributePoolEntries.add(entry); - public AttributePool(ByteReader _byteReader, String name) { - final int attributeCount = _byteReader.u2(); - AttributePoolEntry entry = null; - for (int i = 0; i < attributeCount; i++) { - final int attributeNameIndex = _byteReader.u2(); - final int length = _byteReader.u4(); - UTF8Entry utf8Entry = constantPool.getUTF8Entry(attributeNameIndex); - if (utf8Entry == null) { - throw new IllegalStateException("corrupted state reading attributes for " + name); } - final String attributeName = utf8Entry.getUTF8(); - if (attributeName.equals(LOCALVARIABLETABLE_TAG)) { - localVariableTableEntry = new RealLocalVariableTableEntry(_byteReader, attributeNameIndex, length); - entry = (RealLocalVariableTableEntry) localVariableTableEntry; - } else if (attributeName.equals(CONSTANTVALUE_TAG)) { - entry = new ConstantValueEntry(_byteReader, attributeNameIndex, length); - } else if (attributeName.equals(LINENUMBERTABLE_TAG)) { - lineNumberTableEntry = new LineNumberTableEntry(_byteReader, attributeNameIndex, length); - entry = lineNumberTableEntry; - } else if (attributeName.equals(SOURCEFILE_TAG)) { - sourceFileEntry = new SourceFileEntry(_byteReader, attributeNameIndex, length); - entry = sourceFileEntry; - } else if (attributeName.equals(SYNTHETIC_TAG)) { - syntheticEntry = new SyntheticEntry(_byteReader, attributeNameIndex, length); - entry = syntheticEntry; - } else if (attributeName.equals(EXCEPTIONS_TAG)) { - exceptionEntry = new ExceptionEntry(_byteReader, attributeNameIndex, length); - entry = exceptionEntry; - } else if (attributeName.equals(INNERCLASSES_TAG)) { - entry = new InnerClassesEntry(_byteReader, attributeNameIndex, length); - } else if (attributeName.equals(DEPRECATED_TAG)) { - deprecatedEntry = new DeprecatedEntry(_byteReader, attributeNameIndex, length); - entry = deprecatedEntry; - } else if (attributeName.equals(CODE_TAG)) { - codeEntry = new CodeEntry(_byteReader, attributeNameIndex, length); - entry = codeEntry; - } else if (attributeName.equals(ENCLOSINGMETHOD_TAG)) { - enclosingMethodEntry = new EnclosingMethodEntry(_byteReader, attributeNameIndex, length); - entry = enclosingMethodEntry; - } else if (attributeName.equals(SIGNATURE_TAG)) { - entry = new SignatureEntry(_byteReader, attributeNameIndex, length); - } else if (attributeName.equals(RUNTIMEINVISIBLEANNOTATIONS_TAG)) { - runtimeInvisibleAnnotationsEntry = new RuntimeAnnotationsEntry(_byteReader, attributeNameIndex, length); - entry = runtimeInvisibleAnnotationsEntry; - } else if (attributeName.equals(RUNTIMEVISIBLEANNOTATIONS_TAG)) { - runtimeVisibleAnnotationsEntry = new RuntimeAnnotationsEntry(_byteReader, attributeNameIndex, length); - entry = runtimeVisibleAnnotationsEntry; - } else if (attributeName.equals(BOOTSTRAPMETHODS_TAG)) { - bootstrapMethodsEntry = new BootstrapMethodsEntry(_byteReader, attributeNameIndex, length); - entry = bootstrapMethodsEntry; - // http://docs.oracle.com/javase/specs/jvms/se7/html/jvms-4.html#jvms-4.7.21 - } else if (attributeName.equals(STACKMAPTABLE_TAG)) { - // http://docs.oracle.com/javase/specs/jvms/se7/html/jvms-4.html#jvms-4.7.4 + } - entry = new StackMapTableEntry(_byteReader, attributeNameIndex, length); - } else if (attributeName.equals(LOCALVARIABLETYPETABLE_TAG)) { - // http://docs.oracle.com/javase/specs/jvms/se7/html/jvms-4.html#jvms-4.7.14 - entry = new LocalVariableTypeTableEntry(_byteReader, attributeNameIndex, length); - } else { - logger.warning("Found unexpected Attribute (name = " + attributeName + ")"); - entry = new OtherEntry(_byteReader, attributeNameIndex, length); - } - attributePoolEntries.add(entry); + CodeEntry getCodeEntry() { + return (codeEntry); + } - } - } + public DeprecatedEntry getDeprecatedEntry() { + return (deprecatedEntry); + } - public CodeEntry getCodeEntry() { - return (codeEntry); - } + public ExceptionEntry getExceptionEntry() { + return (exceptionEntry); + } - public DeprecatedEntry getDeprecatedEntry() { - return (deprecatedEntry); - } + LineNumberTableEntry getLineNumberTableEntry() { + return (lineNumberTableEntry); + } - public ExceptionEntry getExceptionEntry() { - return (exceptionEntry); - } + public LocalVariableTableEntry getLocalVariableTableEntry() { + return (localVariableTableEntry); + } - public LineNumberTableEntry getLineNumberTableEntry() { - return (lineNumberTableEntry); - } + public SourceFileEntry getSourceFileEntry() { + return (sourceFileEntry); + } - public LocalVariableTableEntry getLocalVariableTableEntry() { - return (localVariableTableEntry); - } + public SyntheticEntry getSyntheticEntry() { + return (syntheticEntry); + } - public SourceFileEntry getSourceFileEntry() { - return (sourceFileEntry); - } + public RuntimeAnnotationsEntry getRuntimeInvisibleAnnotationsEntry() { + return (runtimeInvisibleAnnotationsEntry); + } - public SyntheticEntry getSyntheticEntry() { - return (syntheticEntry); - } + public RuntimeAnnotationsEntry getRuntimeVisibleAnnotationsEntry() { + return (runtimeVisibleAnnotationsEntry); + } - public RuntimeAnnotationsEntry getRuntimeInvisibleAnnotationsEntry() { - return (runtimeInvisibleAnnotationsEntry); - } + public RuntimeAnnotationsEntry getBootstrap() { + return (runtimeVisibleAnnotationsEntry); + } - public RuntimeAnnotationsEntry getRuntimeVisibleAnnotationsEntry() { - return (runtimeVisibleAnnotationsEntry); - } + } - public RuntimeAnnotationsEntry getBootstrap() { - return (runtimeVisibleAnnotationsEntry); - } + private static final ClassLoader classModelLoader = ClassModel.class.getClassLoader(); - } + public class ClassModelField { + private final int fieldAccessFlags; - private static ClassLoader classModelLoader = ClassModel.class.getClassLoader(); + final AttributePool fieldAttributePool; - public class ClassModelField { - private final int fieldAccessFlags; + private final int descriptorIndex; - AttributePool fieldAttributePool; + private final int index; - private final int descriptorIndex; + private final int nameIndex; + + ClassModelField(ByteReader _byteReader, int _index) { + index = _index; + fieldAccessFlags = _byteReader.u2(); + nameIndex = _byteReader.u2(); + descriptorIndex = _byteReader.u2(); + fieldAttributePool = new AttributePool(_byteReader, getName()); + } - private final int index; + public int getAccessFlags() { + return (fieldAccessFlags); + } - private final int nameIndex; + public AttributePool getAttributePool() { + return (fieldAttributePool); + } - public ClassModelField(ByteReader _byteReader, int _index) { - index = _index; - fieldAccessFlags = _byteReader.u2(); - nameIndex = _byteReader.u2(); - descriptorIndex = _byteReader.u2(); - fieldAttributePool = new AttributePool(_byteReader, getName()); - } + public String getDescriptor() { + return (getDescriptorUTF8Entry().getUTF8()); + } - public int getAccessFlags() { - return (fieldAccessFlags); - } + public int getDescriptorIndex() { + return (descriptorIndex); + } - public AttributePool getAttributePool() { - return (fieldAttributePool); - } + ConstantPool.UTF8Entry getDescriptorUTF8Entry() { + return (constantPool.getUTF8Entry(descriptorIndex)); + } - public String getDescriptor() { - return (getDescriptorUTF8Entry().getUTF8()); - } + public int getIndex() { + return (index); + } - public int getDescriptorIndex() { - return (descriptorIndex); - } + public String getName() { + return (getNameUTF8Entry().getUTF8()); + } - public ConstantPool.UTF8Entry getDescriptorUTF8Entry() { - return (constantPool.getUTF8Entry(descriptorIndex)); - } + public int getNameIndex() { + return (nameIndex); + } - public int getIndex() { - return (index); - } + ConstantPool.UTF8Entry getNameUTF8Entry() { + return (constantPool.getUTF8Entry(nameIndex)); + } - public String getName() { - return (getNameUTF8Entry().getUTF8()); - } + public Class getDeclaringClass() { + final String clazzName = getDescriptor().replaceAll("^L", "").replaceAll("/", ".").replaceAll(";$", ""); + try { + return (Class.forName(clazzName, true, classModelLoader)); + } catch (final ClassNotFoundException e) { + System.out.println("no class found for " + clazzName); + e.printStackTrace(); + return null; + } + } + } - public int getNameIndex() { - return (nameIndex); - } + public class ClassModelMethod { - public ConstantPool.UTF8Entry getNameUTF8Entry() { - return (constantPool.getUTF8Entry(nameIndex)); - } + private final int methodAccessFlags; - public Class getDeclaringClass() { - final String clazzName = getDescriptor().replaceAll("^L", "").replaceAll("/", ".").replaceAll(";$", ""); - try { - return (Class.forName(clazzName, true, classModelLoader)); - } catch (final ClassNotFoundException e) { - System.out.println("no class found for " + clazzName); - e.printStackTrace(); - return null; - } - } - } + private final AttributePool methodAttributePool; - public class ClassModelMethod { + private final int descriptorIndex; - private final int methodAccessFlags; + private final int index; - private final AttributePool methodAttributePool; + private final int nameIndex; - private final int descriptorIndex; + private final CodeEntry codeEntry; - private final int index; + ClassModelMethod(ByteReader _byteReader, int _index) { + index = _index; + methodAccessFlags = _byteReader.u2(); + nameIndex = _byteReader.u2(); + descriptorIndex = _byteReader.u2(); + methodAttributePool = new AttributePool(_byteReader, getName()); + codeEntry = methodAttributePool.getCodeEntry(); + } - private final int nameIndex; + @Override + public int hashCode() { + return index; + } - private final CodeEntry codeEntry; + @Override + public boolean equals(Object obj) { + return this == obj; + } - public ClassModelMethod(ByteReader _byteReader, int _index) { - index = _index; - methodAccessFlags = _byteReader.u2(); - nameIndex = _byteReader.u2(); - descriptorIndex = _byteReader.u2(); - methodAttributePool = new AttributePool(_byteReader, getName()); - codeEntry = methodAttributePool.getCodeEntry(); - } + public int getAccessFlags() { + return (methodAccessFlags); + } - public int getAccessFlags() { - return (methodAccessFlags); - } + public boolean isStatic() { + return (Access.STATIC.bitIsSet(methodAccessFlags)); + } - public boolean isStatic() { - return (Access.STATIC.bitIsSet(methodAccessFlags)); - } + AttributePool getAttributePool() { + return (methodAttributePool); + } - public AttributePool getAttributePool() { - return (methodAttributePool); - } + public AttributePool.CodeEntry getCodeEntry() { + return (methodAttributePool.getCodeEntry()); + } - public AttributePool.CodeEntry getCodeEntry() { - return (methodAttributePool.getCodeEntry()); - } + public String getDescriptor() { + return (getDescriptorUTF8Entry().getUTF8()); + } - public String getDescriptor() { - return (getDescriptorUTF8Entry().getUTF8()); - } + public int getDescriptorIndex() { + return (descriptorIndex); + } - public int getDescriptorIndex() { - return (descriptorIndex); - } + public ConstantPool.UTF8Entry getDescriptorUTF8Entry() { + return (constantPool.getUTF8Entry(descriptorIndex)); + } - public ConstantPool.UTF8Entry getDescriptorUTF8Entry() { - return (constantPool.getUTF8Entry(descriptorIndex)); - } + public int getIndex() { + return (index); + } - public int getIndex() { - return (index); - } + public String getName() { + return (getNameUTF8Entry().getUTF8()); + } - public String getName() { - return (getNameUTF8Entry().getUTF8()); - } + public int getNameIndex() { + return (nameIndex); + } - public int getNameIndex() { - return (nameIndex); - } + ConstantPool.UTF8Entry getNameUTF8Entry() { + return (constantPool.getUTF8Entry(nameIndex)); + } - public ConstantPool.UTF8Entry getNameUTF8Entry() { - return (constantPool.getUTF8Entry(nameIndex)); - } + public ConstantPool getConstantPool() { + return (constantPool); + } - public ConstantPool getConstantPool() { - return (constantPool); - } + public AttributePool.LineNumberTableEntry getLineNumberTableEntry() { + return (getAttributePool().codeEntry.codeEntryAttributePool.lineNumberTableEntry); + } - public AttributePool.LineNumberTableEntry getLineNumberTableEntry() { - return (getAttributePool().codeEntry.codeEntryAttributePool.lineNumberTableEntry); - } + public LocalVariableTableEntry getLocalVariableTableEntry() { + return (getAttributePool().codeEntry.codeEntryAttributePool.localVariableTableEntry); + } - public LocalVariableTableEntry getLocalVariableTableEntry() { - return (getAttributePool().codeEntry.codeEntryAttributePool.localVariableTableEntry); - } - - void setLocalVariableTableEntry(LocalVariableTableEntry _localVariableTableEntry) { - getAttributePool().codeEntry.codeEntryAttributePool.localVariableTableEntry = _localVariableTableEntry; - } + void setLocalVariableTableEntry(LocalVariableTableEntry _localVariableTableEntry) { + getAttributePool().codeEntry.codeEntryAttributePool.localVariableTableEntry = _localVariableTableEntry; + } - public LocalVariableInfo getLocalVariable(int _pc, int _index) { - return (getLocalVariableTableEntry().getVariable(_pc, _index)); - } + public LocalVariableInfo getLocalVariable(int _pc, int _index) { + return (getLocalVariableTableEntry().getVariable(_pc, _index)); + } - public byte[] getCode() { - return (codeEntry.getCode()); - } + public byte[] getCode() { + return (codeEntry.getCode()); + } - public ClassModel getClassModel() { - return (ClassModel.this); - } + public ClassModel getClassModel() { + return (ClassModel.this); + } - public String toString() { - return getClassModel().getClassWeAreModelling().getName() + "." + getName() + " " + getDescriptor(); - } + public String toString() { + return getClassModel().clazz.getName() + '.' + getName() + ' ' + getDescriptor(); + } - public ClassModel getOwnerClassModel() { - return ClassModel.this; - } - } - - public class ClassModelInterface { - private final int interfaceIndex; - - ClassModelInterface(ByteReader _byteReader) { - interfaceIndex = _byteReader.u2(); - } - - ConstantPool.ClassEntry getClassEntry() { - return (constantPool.getClassEntry(interfaceIndex)); - } - - 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 - */ - public 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")); - } - - void parse(InputStream _inputStream) throws ClassParseException { - - ByteReader byteReader = new ByteReader(_inputStream); - magic = byteReader.u4(); - minorVersion = byteReader.u2(); - majorVersion = byteReader.u2(); - constantPool = new ConstantPool(byteReader); - - accessFlags = byteReader.u2(); - thisClassConstantPoolIndex = byteReader.u2(); - superClassConstantPoolIndex = byteReader.u2(); - - final int interfaceCount = byteReader.u2(); - for (int i = 0; i < interfaceCount; i++) { - final ClassModelInterface iface = new ClassModelInterface(byteReader); - interfaces.add(iface); - } - - final int fieldCount = byteReader.u2(); - for (int i = 0; i < fieldCount; i++) { - final ClassModelField field = new ClassModelField(byteReader, i); - fields.add(field); - } - - final int methodPoolLength = byteReader.u2(); - for (int i = 0; i < methodPoolLength; i++) { - final ClassModelMethod method = new ClassModelMethod(byteReader, i); - methods.add(method); - } - - attributePool = new AttributePool(byteReader, Reflection.getSimpleName(getClassWeAreModelling())); - } - - public int getMagic() { - return (magic); - } - - public int getMajorVersion() { - return (majorVersion); - } - - public int getMinorVersion() { - return (minorVersion); - } - - public int getAccessFlags() { - return (accessFlags); - } - - public ConstantPool getConstantPool() { - return (constantPool); - } - - public int getThisClassConstantPoolIndex() { - return (thisClassConstantPoolIndex); - } - - public int getSuperClassConstantPoolIndex() { - return (superClassConstantPoolIndex); - } - - public AttributePool getAttributePool() { - return (attributePool); - } - - public ClassModelField getField(String _name, String _descriptor) { - for (final ClassModelField entry : fields) { - if (entry.getName().equals(_name) && entry.getDescriptor().equals(_descriptor)) { - return (entry); - } - } - return superClazz.getField(_name, _descriptor); - } - - public ClassModelField getField(String _name) { - for (final ClassModelField entry : fields) { - if (entry.getName().equals(_name)) { - return (entry); - } - } - return superClazz.getField(_name); - } - - public ClassModelMethod getMethod(String _name, String _descriptor) { - ClassModelMethod methodOrNull = getMethodOrNull(_name, _descriptor); - if (methodOrNull == null) - return superClazz != null ? superClazz.getMethod(_name, _descriptor) : (null); - return methodOrNull; - } - - private ClassModelMethod getMethodOrNull(String _name, String _descriptor) { - for (final ClassModelMethod entry : methods) { - if (entry.getName().equals(_name) && entry.getDescriptor().equals(_descriptor)) { - if (logger.isLoggable(Level.FINE)) { - logger.fine("Found " + clazz.getName() + "." + entry.getName() + " " + entry.getDescriptor() + " for " - + _name.replace('/', '.')); - } - return (entry); - } - } - return null; - } - - public List getFieldPoolEntries() { - return (fields); - } - - /** - * 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()) - * - * @return The Method or null if we fail to locate a given method. - */ - public ClassModelMethod getMethod(MethodEntry _methodEntry, boolean _isSpecial) { - final String entryClassNameInDotForm = _methodEntry.getClassEntry().getNameUTF8Entry().getUTF8().replace('/', '.'); - - // 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); - } - return superClazz.getMethod(_methodEntry, false); - } - - NameAndTypeEntry nameAndTypeEntry = _methodEntry.getNameAndTypeEntry(); - ClassModelMethod methodOrNull = getMethodOrNull(nameAndTypeEntry.getNameUTF8Entry().getUTF8(), nameAndTypeEntry + public ClassModel getOwnerClassModel() { + return ClassModel.this; + } + } + + class ClassModelInterface { + private final int interfaceIndex; + + ClassModelInterface(ByteReader _byteReader) { + interfaceIndex = _byteReader.u2(); + } + + ConstantPool.ClassEntry getClassEntry() { + return (constantPool.getClassEntry(interfaceIndex)); + } + + int getInterfaceIndex() { + return (interfaceIndex); + } + + } + + public final Class clazz; + + /** + * 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. + * + * @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 + * @see ByteReader + * @see Java 5 Class File Format + */ + private void parse(ClassLoader _classLoader, String _className) { + + parse(_classLoader.getResourceAsStream(_className.replace('.', '/') + ".class")); + } + + private void parse(InputStream _inputStream) { + + ByteReader byteReader = new ByteReader(_inputStream); + magic = byteReader.u4(); + minorVersion = byteReader.u2(); + majorVersion = byteReader.u2(); + constantPool = new ConstantPool(byteReader); + + accessFlags = byteReader.u2(); + thisClassConstantPoolIndex = byteReader.u2(); + superClassConstantPoolIndex = byteReader.u2(); + + final int interfaceCount = byteReader.u2(); + for (int i = 0; i < interfaceCount; i++) { + interfaces.add(new ClassModelInterface(byteReader)); + } + + final int fieldCount = byteReader.u2(); + for (int i = 0; i < fieldCount; i++) { + fields.add(new ClassModelField(byteReader, i)); + } + + final int methodPoolLength = byteReader.u2(); + for (int i = 0; i < methodPoolLength; i++) { + methods.add(new ClassModelMethod(byteReader, i)); + } + + attributePool = new AttributePool(byteReader, Reflection.getSimpleName(clazz)); + } + + public int getMagic() { + return (magic); + } + + public int getMajorVersion() { + return (majorVersion); + } + + public int getMinorVersion() { + return (minorVersion); + } + + public int getAccessFlags() { + return (accessFlags); + } + + public ConstantPool getConstantPool() { + return (constantPool); + } + + public int getThisClassConstantPoolIndex() { + return (thisClassConstantPoolIndex); + } + + public int getSuperClassConstantPoolIndex() { + return (superClassConstantPoolIndex); + } + + public AttributePool getAttributePool() { + return (attributePool); + } + + private ClassModelField getField(String _name, String _descriptor) { + ClassModel other = this; + while (true) { + for (final ClassModelField entry : other.fields) { + if (entry.getName().equals(_name) && entry.getDescriptor().equals(_descriptor)) { + return (entry); + } + } + other = other.superClazz; + } + } + + public ClassModelField getField(String _name) { + ClassModel other = this; + while (true) { + for (final ClassModelField entry : other.fields) { + if (entry.getName().equals(_name)) { + return (entry); + } + } + other = other.superClazz; + } + } + + public ClassModelMethod getMethod(String _name, String _descriptor) { + ClassModelMethod methodOrNull = getMethodOrNull(_name, _descriptor); + if (methodOrNull == null) + return superClazz != null ? superClazz.getMethod(_name, _descriptor) : (null); + else + return methodOrNull; + } + + private ClassModelMethod getMethodOrNull(String _name, String _descriptor) { + for (final ClassModelMethod entry : methods) { + if (entry.getName().equals(_name) && entry.getDescriptor().equals(_descriptor)) { +// if (logger.isLoggable(Level.FINE)) { +// logger.fine("Found " + clazz.getName() + '.' + entry.getName() + ' ' + entry.getDescriptor() + " for " +// + _name.replace('/', '.')); +// } + return (entry); + } + } + return null; + } + + + /** + * 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()) + * @return The Method or null if we fail to locate a given method. + */ + public ClassModelMethod getMethod(MethodEntry _methodEntry, boolean _isSpecial) { + final String entryClassNameInDotForm = _methodEntry.getClassEntry().getNameUTF8Entry().getUTF8().replace('/', '.'); + + // 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); +// } + return superClazz.getMethod(_methodEntry, false); + } + + NameAndTypeEntry nameAndTypeEntry = _methodEntry.getNameAndTypeEntry(); + ClassModelMethod methodOrNull = getMethodOrNull(nameAndTypeEntry.getNameUTF8Entry().getUTF8(), nameAndTypeEntry .getDescriptorUTF8Entry().getUTF8()); - if (methodOrNull == null) - return superClazz != null ? superClazz.getMethod(_methodEntry, false) : (null); - return methodOrNull; - } - - // private ValueCache methodModelCache = ValueCache.on(this::computeMethodModel); - private ValueCache methodModelCache = ValueCache - .on(new ThrowingValueComputer(){ - @Override public MethodModel compute(MethodKey key) throws AparapiException { - return computeMethodModel(key); - } - }); - - /** - * Create a MethodModel for a given method name and signature. - * - * @param _name - * @param _signature - * @return - * @throws AparapiException - */ - public MethodModel getMethodModel(String _name, String _signature) throws AparapiException { - if (CacheEnabler.areCachesEnabled()) - return methodModelCache.computeIfAbsent(MethodKey.of(_name, _signature)); - else { - final ClassModelMethod method = getMethod(_name, _signature); - return new MethodModel(method); - } - } - - private MethodModel computeMethodModel(MethodKey methodKey) throws AparapiException { - final ClassModelMethod method = getMethod(methodKey.getName(), methodKey.getSignature()); - return new MethodModel(method); - } - - // These fields use for accessor conversion - private final ArrayList structMembers = new ArrayList(); - - private final ArrayList structMemberOffsets = new ArrayList(); - - private final ArrayList structMemberTypes = new ArrayList(); - - private int totalStructSize = 0; - - public ArrayList getStructMembers() { - return structMembers; - } - - public ArrayList getStructMemberOffsets() { - return structMemberOffsets; - } - - public ArrayList getStructMemberTypes() { - return structMemberTypes; - } - - public int getTotalStructSize() { - return totalStructSize; - } - - public void setTotalStructSize(int x) { - totalStructSize = x; - } - - // private final ValueCache entrypointCache = ValueCache.on(this::computeBasicEntrypoint); - private final ValueCache entrypointCache = ValueCache - .on(new ThrowingValueComputer(){ - @Override public Entrypoint compute(EntrypointKey key) throws AparapiException { - return computeBasicEntrypoint(key); - } - }); - - Entrypoint getEntrypoint(String _entrypointName, String _descriptor, Object _k) throws AparapiException { - if (CacheEnabler.areCachesEnabled()) { - EntrypointKey key = EntrypointKey.of(_entrypointName, _descriptor); - long s = System.nanoTime(); - Entrypoint entrypointWithoutKernel = entrypointCache.computeIfAbsent(key); - long e = System.nanoTime() - s; - return entrypointWithoutKernel.cloneForKernel(_k); - } else { - final MethodModel method = getMethodModel(_entrypointName, _descriptor); - return new Entrypoint(this, method, _k); - } - } - - Entrypoint computeBasicEntrypoint(EntrypointKey entrypointKey) throws AparapiException { - final MethodModel method = getMethodModel(entrypointKey.getEntrypointName(), entrypointKey.getDescriptor()); - return new Entrypoint(this, method, null); - } - - public Class getClassWeAreModelling() { - return clazz; - } - - public Entrypoint getEntrypoint(String _entrypointName, Object _k) throws AparapiException { - return (getEntrypoint(_entrypointName, "()V", _k)); - } - - public Entrypoint getEntrypoint() throws AparapiException { - return (getEntrypoint("run", "()V", null)); - } - - public static void invalidateCaches() { - classModelCache.invalidate(); - } - - @Override public String toString() { - return "ClassModel of " + getClassWeAreModelling(); - } + if (methodOrNull == null) + return superClazz != null ? superClazz.getMethod(_methodEntry, false) : (null); + return methodOrNull; + } + + + /** + * 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()) + * @return The Method or null if we fail to locate a given method. + */ + public ClassModelMethod getMethod0(final MethodEntry _methodEntry, boolean _isSpecial) { + ClassModel other = this; + final NameAndTypeEntry meNT = _methodEntry.getNameAndTypeEntry(); + String meNT8 = meNT.getNameUTF8Entry().getUTF8(); + final String entryClassNameInDotForm = meNT8.replace('/', '.'); + while (true) { + + // Shortcut direct calls to supers to allow "foo() { super.foo() }" type stuff to work + if (_isSpecial && (other.superClazz != null) && other.superClazz.isSuperClass(entryClassNameInDotForm)) { +// if (other.logger.isLoggable(Level.FINE)) { +// other.logger.fine("going to look in super:" + other.superClazz.getClassWeAreModelling().getName() + " on behalf of " +// + entryClassNameInDotForm); +// } + _isSpecial = false; + other = other.superClazz; + continue; + } + + NameAndTypeEntry nameAndTypeEntry = meNT; + ClassModelMethod methodOrNull = other.getMethodOrNull(nameAndTypeEntry.getNameUTF8Entry().getUTF8(), nameAndTypeEntry + .getDescriptorUTF8Entry().getUTF8()); + if (methodOrNull == null) + return other.superClazz != null ? other.superClazz.getMethod(_methodEntry, false) : (null); + else + return methodOrNull; + } + } + + + private final ValueCache methodModelCache = ValueCache + .on(this::computeMethodModel); + + /** + * Create a MethodModel for a given method name and signature. + * + * @param _name + * @param _signature + * @return + * @throws AparapiException + */ + private MethodModel getMethodModel(String _name, String _signature) throws AparapiException { + if (CacheEnabler.areCachesEnabled()) + return methodModelCache.computeIfAbsent(MethodKey.of(_name, _signature)); + else { + final ClassModelMethod method = getMethod(_name, _signature); + return new MethodModel(method); + } + } + + private MethodModel computeMethodModel(MethodKey methodKey) throws AparapiException { + return new MethodModel(getMethod(methodKey.getName(), methodKey.getSignature())); + } + + // These fields use for accessor conversion + private final ArrayList structMembers = new ArrayList<>(); + + private final ArrayList structMemberOffsets = new ArrayList<>(); + + private final ArrayList structMemberTypes = new ArrayList<>(); + + private int totalStructSize = 0; + + public ArrayList getStructMembers() { + return structMembers; + } + + public ArrayList getStructMemberOffsets() { + return structMemberOffsets; + } + + public ArrayList getStructMemberTypes() { + return structMemberTypes; + } + + public int getTotalStructSize() { + return totalStructSize; + } + + public void setTotalStructSize(int x) { + totalStructSize = x; + } + + // private final ValueCache entrypointCache = ValueCache.on(this::computeBasicEntrypoint); + private final ValueCache entrypointCache = ValueCache + .on(this::computeBasicEntrypoint); + + private Entrypoint getEntrypoint(String _entrypointName, String _descriptor, Object _k) throws AparapiException { + if (CacheEnabler.areCachesEnabled()) { + EntrypointKey key = EntrypointKey.of(_entrypointName, _descriptor); + //long s = System.nanoTime(); + Entrypoint entrypointWithoutKernel = entrypointCache.computeIfAbsent(key); + //long e = System.nanoTime() - s; + return entrypointWithoutKernel.cloneForKernel(_k); + } else { + final MethodModel method = getMethodModel(_entrypointName, _descriptor); + return new Entrypoint(this, method, _k); + } + } + + private Entrypoint computeBasicEntrypoint(EntrypointKey entrypointKey) throws AparapiException { + return new Entrypoint(this, + getMethodModel(entrypointKey.getEntrypointName(), entrypointKey.getDescriptor()), + null); + } + + public Entrypoint getEntrypoint(String _entrypointName, Object _k) throws AparapiException { + return (getEntrypoint(_entrypointName, "()V", _k)); + } + + public Entrypoint getEntrypoint() throws AparapiException { + return (getEntrypoint("run", "()V", null)); + } + + public static void invalidateCaches() { + classModelCache.invalidate(); + } + + @Override + public String toString() { + return "ClassModel of " + clazz; + } } diff --git a/src/main/java/com/aparapi/internal/model/Entrypoint.java b/src/main/java/com/aparapi/internal/model/Entrypoint.java index 3a291b24..cfb95d2b 100644 --- a/src/main/java/com/aparapi/internal/model/Entrypoint.java +++ b/src/main/java/com/aparapi/internal/model/Entrypoint.java @@ -67,32 +67,32 @@ to national security controls as identified on the Commerce Control List (curren public class Entrypoint implements Cloneable { - private static Logger logger = Logger.getLogger(Config.getLoggerName()); + private static final Logger logger = Logger.getLogger(Config.getLoggerName()); - private final List referencedClassModelFields = new ArrayList(); + private final List referencedClassModelFields = new ArrayList<>(); - private final List referencedFields = new ArrayList(); + private final List referencedFields = new ArrayList<>(); - private ClassModel classModel; + private final ClassModel classModel; private Object kernelInstance = null; - private final Set referencedFieldNames = new LinkedHashSet(); + private final Set referencedFieldNames = new LinkedHashSet<>(); - private final Set arrayFieldAssignments = new LinkedHashSet(); + private final Set arrayFieldAssignments = new LinkedHashSet<>(); - private final Set arrayFieldAccesses = new LinkedHashSet(); + private final Set arrayFieldAccesses = new LinkedHashSet<>(); // Classes of object array members - private final HashMap objectArrayFieldsClasses = new HashMap(); + private final HashMap objectArrayFieldsClasses = new HashMap<>(); // Supporting classes of object array members like supers - private final HashMap allFieldsClasses = new HashMap(); + private final HashMap allFieldsClasses = new HashMap<>(); // Keep track of arrays whose length is taken via foo.length - private final Set arrayFieldArrayLengthUsed = new LinkedHashSet(); + private final Set arrayFieldArrayLengthUsed = new LinkedHashSet<>(); - private final List calledMethods = new ArrayList(); + private final List calledMethods = new ArrayList<>(); private final MethodModel methodModel; @@ -122,7 +122,7 @@ public boolean requiresByteAddressableStorePragma() { } /* Atomics are detected in Entrypoint */ - public void setRequiresAtomics32Pragma(boolean newVal) { + private void setRequiresAtomics32Pragma(boolean newVal) { usesAtomic32 = newVal; } @@ -150,7 +150,7 @@ public Map getObjectArrayFieldsClasses() { return objectArrayFieldsClasses; } - public static Field getFieldFromClassHierarchy(Class _clazz, String _name) throws AparapiException { + private static Field getFieldFromClassHierarchy(Class _clazz, String _name) throws ClassParseException { // look in self // if found, done @@ -232,7 +232,7 @@ public static Field getFieldFromClassHierarchy(Class _clazz, String _name) th * 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. */ - public ClassModel getOrUpdateAllClassAccesses(String className) throws AparapiException { + private ClassModel getOrUpdateAllClassAccesses(String className) throws AparapiException { ClassModel memberClassModel = allFieldsClasses.get(className); if (memberClassModel == null) { try { @@ -247,18 +247,18 @@ public ClassModel getOrUpdateAllClassAccesses(String className) throws AparapiEx ClassModel superModel = memberClassModel.getSuperClazz(); while (superModel != null) { // See if super is already added - final ClassModel oldSuper = allFieldsClasses.get(superModel.getClassWeAreModelling().getName()); + final ClassModel oldSuper = allFieldsClasses.get(superModel.clazz.getName()); if (oldSuper != null) { if (oldSuper != superModel) { memberClassModel.replaceSuperClazz(oldSuper); if (logger.isLoggable(Level.FINEST)) { - logger.finest("replaced super " + oldSuper.getClassWeAreModelling().getName() + " for " + className); + logger.finest("replaced super " + oldSuper.clazz.getName() + " for " + className); } } } else { - allFieldsClasses.put(superModel.getClassWeAreModelling().getName(), superModel); + allFieldsClasses.put(superModel.clazz.getName(), superModel); if (logger.isLoggable(Level.FINEST)) { - logger.finest("add new super " + superModel.getClassWeAreModelling().getName() + " for " + className); + logger.finest("add new super " + superModel.clazz.getName() + " for " + className); } } @@ -275,7 +275,7 @@ public ClassModel getOrUpdateAllClassAccesses(String className) throws AparapiEx return memberClassModel; } - public ClassModelMethod resolveAccessorCandidate(MethodCall _methodCall, MethodEntry _methodEntry) throws AparapiException { + private ClassModelMethod resolveAccessorCandidate(MethodCall _methodCall, MethodEntry _methodEntry) throws AparapiException { final String methodsActualClassName = (_methodEntry.getClassEntry().getNameUTF8Entry().getUTF8()).replace('/', '.'); if (_methodCall instanceof VirtualMethodCall) { @@ -303,7 +303,7 @@ public ClassModelMethod resolveAccessorCandidate(MethodCall _methodCall, MethodE * Update accessor structures when there is a direct access to an * obect array element's data members */ - public void updateObjectMemberFieldAccesses(String className, FieldEntry field) throws AparapiException { + private void updateObjectMemberFieldAccesses(String className, FieldEntry field) throws AparapiException { final String accessedFieldName = field.getNameAndTypeEntry().getNameUTF8Entry().getUTF8(); // Quickly bail if it is a ref @@ -317,7 +317,7 @@ public void updateObjectMemberFieldAccesses(String className, FieldEntry field) } final ClassModel memberClassModel = getOrUpdateAllClassAccesses(className); - final Class memberClass = memberClassModel.getClassWeAreModelling(); + final Class memberClass = memberClassModel.clazz; ClassModel superCandidate = null; // We may add this field if no superclass match @@ -326,11 +326,11 @@ public void updateObjectMemberFieldAccesses(String className, FieldEntry field) // No exact match, look for a superclass for (final ClassModel c : allFieldsClasses.values()) { if (logger.isLoggable(Level.FINEST)) { - logger.finest(" super: " + c.getClassWeAreModelling().getName() + " for " + className); + logger.finest(" super: " + c.clazz.getName() + " for " + className); } if (c.isSuperClass(memberClass)) { if (logger.isLoggable(Level.FINE)) { - logger.fine("selected super: " + c.getClassWeAreModelling().getName() + " for " + className); + logger.fine("selected super: " + c.clazz.getName() + " for " + className); } superCandidate = c; break; @@ -356,7 +356,7 @@ public void updateObjectMemberFieldAccesses(String className, FieldEntry field) if (!f.getClassEntry().getNameUTF8Entry().getUTF8().equals(field.getClassEntry().getNameUTF8Entry().getUTF8())) { // Look up in class hierarchy to ensure it is the same field - final Field superField = getFieldFromClassHierarchy(superCandidate.getClassWeAreModelling(), f + final Field superField = getFieldFromClassHierarchy(superCandidate.clazz, f .getNameAndTypeEntry().getNameUTF8Entry().getUTF8()); final Field classField = getFieldFromClassHierarchy(memberClass, f.getNameAndTypeEntry().getNameUTF8Entry() .getUTF8()); @@ -386,9 +386,9 @@ public void updateObjectMemberFieldAccesses(String className, FieldEntry field) if (!found) { structMemberSet.add(field); if (logger.isLoggable(Level.FINE)) { - logger.fine("Adding assigned field " + field.getNameAndTypeEntry().getNameUTF8Entry().getUTF8() + " type: " + logger.fine("Adding assigned field " + field.getNameAndTypeEntry().getNameUTF8Entry().getUTF8() + " type: " + field.getNameAndTypeEntry().getDescriptorUTF8Entry().getUTF8() + " to " - + memberClassModel.getClassWeAreModelling().getName()); + + memberClassModel.clazz.getName()); } } } @@ -397,7 +397,7 @@ public void updateObjectMemberFieldAccesses(String className, FieldEntry field) /* * Find a suitable call target in the kernel class, supers, object members or static calls */ - ClassModelMethod resolveCalledMethod(MethodCall methodCall, ClassModel classModel) throws AparapiException { + private 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); @@ -411,7 +411,7 @@ ClassModelMethod resolveCalledMethod(MethodCall methodCall, ClassModel classMode } } - ClassModelMethod m = classModel.getMethod(methodEntry, (methodCall instanceof I_INVOKESPECIAL) ? true : false); + ClassModelMethod m = classModel.getMethod(methodEntry, methodCall instanceof I_INVOKESPECIAL); // Did not find method in this class or supers. Look for data member object arrays if (m == null && !isMapped) { @@ -421,9 +421,9 @@ ClassModelMethod resolveCalledMethod(MethodCall methodCall, ClassModel classMode // Look for a intra-object call in a object member if (m == null && !isMapped) { for (ClassModel c : allFieldsClasses.values()) { - if (c.getClassWeAreModelling().getName() + if (c.clazz.getName() .equals(methodEntry.getClassEntry().getNameUTF8Entry().getUTF8().replace('/', '.'))) { - m = c.getMethod(methodEntry, (methodCall instanceof I_INVOKESPECIAL) ? true : false); + m = c.getMethod(methodEntry, methodCall instanceof I_INVOKESPECIAL); assert m != null; break; } @@ -442,7 +442,7 @@ ClassModelMethod resolveCalledMethod(MethodCall methodCall, ClassModel classMode m = otherClassModel.getMethod(methodEntry, false); } - if (logger.isLoggable(Level.INFO)) { + if (logger.isLoggable(Level.FINE)) { logger.fine("Selected method for: " + methodEntry + " is " + m); } @@ -454,7 +454,7 @@ public Entrypoint(ClassModel _classModel, MethodModel _methodModel, Object _k) t methodModel = _methodModel; kernelInstance = _k; - final Map methodMap = new LinkedHashMap(); + final Map methodMap = new LinkedHashMap<>(); boolean discovered = true; @@ -474,13 +474,14 @@ public Entrypoint(ClassModel _classModel, MethodModel _methodModel, Object _k) t } // Collect all methods called directly from kernel's run method + Set methodMapKeys = methodMap.keySet(); for (final MethodCall methodCall : methodModel.getMethodCalls()) { ClassModelMethod m = resolveCalledMethod(methodCall, classModel); - if ((m != null) && !methodMap.keySet().contains(m) && !noCL(m)) { + if ((m != null) && !methodMapKeys.contains(m) && !noCL(m)) { final MethodModel target = new MethodModel(m, this); methodMap.put(m, target); - methodModel.getCalledMethods().add(target); + methodModel.calledMethods.add(target); discovered = true; } } @@ -489,21 +490,21 @@ public Entrypoint(ClassModel _classModel, MethodModel _methodModel, Object _k) t // Walk the whole graph of called methods and add them to the methodMap while (discovered) { discovered = false; - for (final MethodModel mm : new ArrayList(methodMap.values())) { + for (final MethodModel mm : new ArrayList<>(methodMap.values())) { for (final MethodCall methodCall : mm.getMethodCalls()) { ClassModelMethod m = resolveCalledMethod(methodCall, classModel); if (m != null && !noCL(m)) { MethodModel target = null; - if (methodMap.keySet().contains(m)) { + if (methodMapKeys.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 // 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.FINE)) { + logger.fine("repositioning : " + m.getClassModel().clazz.getName() + ' ' + m.getName() + + ' ' + m.getDescriptor()); } } else { target = new MethodModel(m, this); @@ -511,23 +512,23 @@ public Entrypoint(ClassModel _classModel, MethodModel _methodModel, Object _k) t } methodMap.put(m, target); // Build graph of call targets to look for recursion - mm.getCalledMethods().add(target); + mm.calledMethods.add(target); } } } } - methodModel.checkForRecursion(new HashSet()); + methodModel.checkForRecursion(new LinkedHashSet<>()); calledMethods.addAll(methodMap.values()); Collections.reverse(calledMethods); - final List methods = new ArrayList(calledMethods); + final List methods = new ArrayList<>(calledMethods); // add method to the calledMethods so we can include in this list methods.add(methodModel); - final Set fieldAssignments = new HashSet(); + final Set fieldAssignments = new HashSet<>(); - final Set fieldAccesses = new HashSet(); + final Set fieldAccesses = new HashSet<>(); for (final MethodModel methodModel : methods) { @@ -606,7 +607,7 @@ public Entrypoint(ClassModel _classModel, MethodModel _methodModel, Object _k) t final String className = (signature.substring(2, signature.length() - 1)).replace('/', '.'); final ClassModel arrayFieldModel = getOrUpdateAllClassAccesses(className); if (arrayFieldModel != null) { - final Class memberClass = arrayFieldModel.getClassWeAreModelling(); + final Class memberClass = arrayFieldModel.clazz; final int modifiers = memberClass.getModifiers(); if (!Modifier.isFinal(modifiers)) { throw new ClassParseException(ClassParseException.TYPE.ACCESSEDOBJECTNONFINAL); @@ -635,8 +636,8 @@ public Entrypoint(ClassModel _classModel, MethodModel _methodModel, Object _k) t } else { final String className = (field.getClassEntry().getNameUTF8Entry().getUTF8()).replace('/', '.'); // Look for object data member access - if (!className.equals(getClassModel().getClassWeAreModelling().getName()) - && (getFieldFromClassHierarchy(getClassModel().getClassWeAreModelling(), accessedFieldName) == null)) { + if (!className.equals(getClassModel().clazz.getName()) + && (getFieldFromClassHierarchy(getClassModel().clazz, accessedFieldName) == null)) { updateObjectMemberFieldAccesses(className, field); } } @@ -650,8 +651,8 @@ public Entrypoint(ClassModel _classModel, MethodModel _methodModel, Object _k) t final String className = (field.getClassEntry().getNameUTF8Entry().getUTF8()).replace('/', '.'); // Look for object data member access - if (!className.equals(getClassModel().getClassWeAreModelling().getName()) - && (getFieldFromClassHierarchy(getClassModel().getClassWeAreModelling(), assignedFieldName) == null)) { + if (!className.equals(getClassModel().clazz.getName()) + && (getFieldFromClassHierarchy(getClassModel().clazz, assignedFieldName) == null)) { updateObjectMemberFieldAccesses(className, field); } else { @@ -701,12 +702,12 @@ else if (instruction instanceof I_INVOKEVIRTUAL) { for (final String referencedFieldName : referencedFieldNames) { try { - final Class clazz = classModel.getClassWeAreModelling(); + final Class clazz = classModel.clazz; final Field field = getFieldFromClassHierarchy(clazz, referencedFieldName); if (field != null) { referencedFields.add(field); final 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 (final SecurityException e) { @@ -725,8 +726,8 @@ else if (instruction instanceof I_INVOKEVIRTUAL) { ClassModel superModel = memberObjClass.getSuperClazz(); while (superModel != null) { if (logger.isLoggable(Level.FINEST)) { - logger.finest("adding = " + superModel.getClassWeAreModelling().getName() + " fields into " - + memberObjClass.getClassWeAreModelling().getName()); + logger.finest("adding = " + superModel.clazz.getName() + " fields into " + + memberObjClass.clazz.getName()); } memberObjClass.getStructMembers().addAll(superModel.getStructMembers()); superModel = superModel.getSuperClazz(); @@ -734,34 +735,31 @@ else if (instruction instanceof I_INVOKEVIRTUAL) { } // Sort fields of each class biggest->smallest - final Comparator fieldSizeComparator = new Comparator(){ - @Override public int compare(FieldEntry aa, FieldEntry bb) { - final String aType = aa.getNameAndTypeEntry().getDescriptorUTF8Entry().getUTF8(); - final String bType = bb.getNameAndTypeEntry().getDescriptorUTF8Entry().getUTF8(); + final Comparator fieldSizeComparator = (aa, bb) -> { + if (aa == bb) + return 0; + final String aType = aa.getNameAndTypeEntry().getDescriptorUTF8Entry().getUTF8(); + final String bType = bb.getNameAndTypeEntry().getDescriptorUTF8Entry().getUTF8(); - // Booleans get converted down to bytes - final int aSize = InstructionSet.TypeSpec.valueOf(aType.equals("Z") ? "B" : aType).getSize(); - final int bSize = InstructionSet.TypeSpec.valueOf(bType.equals("Z") ? "B" : bType).getSize(); + if (aType.equals(bType)) + return 0; - if (logger.isLoggable(Level.FINEST)) { - logger.finest("aType= " + aType + " aSize= " + aSize + " . . bType= " + bType + " bSize= " + bSize); - } + // Booleans get converted down to bytes + final int aSize = TypeSpec.valueOf(aType.equals("Z") ? "B" : aType).getSize(); + final int bSize = TypeSpec.valueOf(bType.equals("Z") ? "B" : bType).getSize(); - // Note this is sorting in reverse order so the biggest is first - if (aSize > bSize) { - return -1; - } else if (aSize == bSize) { - return 0; - } else { - return 1; - } - } +// 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 + return Integer.compare(bSize, aSize); }; for (final ClassModel c : objectArrayFieldsClasses.values()) { final ArrayList fields = c.getStructMembers(); if (fields.size() > 0) { - Collections.sort(fields, fieldSizeComparator); + fields.sort(fieldSizeComparator); // Now compute the total size for the struct int totalSize = 0; @@ -770,7 +768,7 @@ else if (instruction instanceof I_INVOKEVIRTUAL) { for (final FieldEntry f : fields) { // Record field offset for use while copying // Get field we will copy out of the kernel member object - final Field rfield = getFieldFromClassHierarchy(c.getClassWeAreModelling(), f.getNameAndTypeEntry() + final Field rfield = getFieldFromClassHierarchy(c.clazz, f.getNameAndTypeEntry() .getNameUTF8Entry().getUTF8()); c.getStructMemberOffsets().add(UnsafeWrapper.objectFieldOffset(rfield)); @@ -805,8 +803,7 @@ else if (instruction instanceof I_INVOKEVIRTUAL) { } private boolean noCL(ClassModelMethod m) { - boolean found = m.getClassModel().getNoCLMethods().contains(m.getName()); - return found; + return m.getClassModel().isNoCLMethod(m.getName()); } private FieldEntry getSimpleGetterField(MethodModel method) { @@ -859,18 +856,18 @@ public MethodModel getCallTarget(MethodEntry _methodEntry, boolean _isSpecial) { boolean isMapped = Kernel.isMappedMethod(_methodEntry); if (logger.isLoggable(Level.FINE) && (target == null)) { - logger.fine("Did not find call target: " + _methodEntry + " in " + getClassModel().getClassWeAreModelling().getName() + logger.fine("Did not find call target: " + _methodEntry + " in " + getClassModel().clazz.getName() + " isMapped=" + isMapped); } if (target == null) { // Look for member obj accessor calls + final String entryClassNameInDotForm = _methodEntry.getClassEntry().getNameUTF8Entry().getUTF8().replace('/', '.'); for (final ClassModel memberObjClass : objectArrayFieldsClasses.values()) { - final String entryClassNameInDotForm = _methodEntry.getClassEntry().getNameUTF8Entry().getUTF8().replace('/', '.'); - if (entryClassNameInDotForm.equals(memberObjClass.getClassWeAreModelling().getName())) { + if (entryClassNameInDotForm.equals(memberObjClass.clazz.getName())) { if (logger.isLoggable(Level.FINE)) { - logger.fine("Searching for call target: " + _methodEntry + " in " - + memberObjClass.getClassWeAreModelling().getName()); + logger.fine("Searching for call target: " + _methodEntry + " in " + + memberObjClass.clazz.getName()); } target = memberObjClass.getMethod(_methodEntry, false); @@ -893,15 +890,17 @@ public MethodModel getCallTarget(MethodEntry _methodEntry, boolean _isSpecial) { } // Search for static calls to other classes + String meNT = _methodEntry.getNameAndTypeEntry().getNameUTF8Entry().getUTF8(); + String deNT = _methodEntry.getNameAndTypeEntry().getDescriptorUTF8Entry().getUTF8(); for (MethodModel m : calledMethods) { if (logger.isLoggable(Level.FINE)) { logger.fine("Searching for call target: " + _methodEntry + " in " + m.getName()); } - if (m.getMethod().getName().equals(_methodEntry.getNameAndTypeEntry().getNameUTF8Entry().getUTF8()) - && m.getMethod().getDescriptor().equals(_methodEntry.getNameAndTypeEntry().getDescriptorUTF8Entry().getUTF8())) { + if (m.getMethod().getName().equals(meNT) + && m.getMethod().getDescriptor().equals(deNT)) { if (logger.isLoggable(Level.FINE)) { - logger.fine("Found " + m.getMethod().getClassModel().getClassWeAreModelling().getName() + "." - + m.getMethod().getName() + " " + m.getMethod().getDescriptor()); + logger.fine("Found " + m.getMethod().getClassModel().clazz.getName() + '.' + + m.getMethod().getName() + ' ' + m.getMethod().getDescriptor()); } return m; } diff --git a/src/main/java/com/aparapi/internal/model/EntrypointKey.java b/src/main/java/com/aparapi/internal/model/EntrypointKey.java index fe5530bc..95a726d7 100644 --- a/src/main/java/com/aparapi/internal/model/EntrypointKey.java +++ b/src/main/java/com/aparapi/internal/model/EntrypointKey.java @@ -20,9 +20,9 @@ public static EntrypointKey of(String entrypointName, String descriptor) { return new EntrypointKey(entrypointName, descriptor); } - private String descriptor; + private final String descriptor; - private String entrypointName; + private final String entrypointName; private EntrypointKey(String entrypointName, String descriptor) { this.entrypointName = entrypointName; @@ -46,7 +46,7 @@ String getEntrypointName() { } @Override public String toString() { - return "EntrypointKey [entrypointName=" + entrypointName + ", descriptor=" + descriptor + "]"; + return "EntrypointKey [entrypointName=" + entrypointName + ", descriptor=" + descriptor + ']'; } @Override public boolean equals(Object obj) { @@ -63,10 +63,7 @@ String getEntrypointName() { } else if (!descriptor.equals(other.descriptor)) return false; if (entrypointName == null) { - if (other.entrypointName != null) - return false; - } else if (!entrypointName.equals(other.entrypointName)) - return false; - return true; + return other.entrypointName == null; + } else return entrypointName.equals(other.entrypointName); } } diff --git a/src/main/java/com/aparapi/internal/model/Memoizer.java b/src/main/java/com/aparapi/internal/model/Memoizer.java index 60c8d152..012b3bdd 100644 --- a/src/main/java/com/aparapi/internal/model/Memoizer.java +++ b/src/main/java/com/aparapi/internal/model/Memoizer.java @@ -22,7 +22,7 @@ interface Optional { final class Some implements Optional{ private final E value; - static final Optional of(E value) { + static Optional of(E value) { return new Some<>(value); } @@ -65,7 +65,7 @@ private None() { } public interface Memoizer extends Supplier { - public final class Impl implements Memoizer{ + final class Impl implements Memoizer{ private final Supplier supplier; private final AtomicReference> valueRef = new AtomicReference<>(Optional.None. none()); diff --git a/src/main/java/com/aparapi/internal/model/MethodKey.java b/src/main/java/com/aparapi/internal/model/MethodKey.java index 28f5921d..c71aa5b7 100644 --- a/src/main/java/com/aparapi/internal/model/MethodKey.java +++ b/src/main/java/com/aparapi/internal/model/MethodKey.java @@ -25,7 +25,7 @@ static MethodKey of(String name, String signature) { private final String signature; @Override public String toString() { - return "MethodKey [name=" + getName() + ", signature=" + getSignature() + "]"; + return "MethodKey [name=" + getName() + ", signature=" + getSignature() + ']'; } @Override public int hashCode() { @@ -50,11 +50,8 @@ static MethodKey of(String name, String signature) { } else if (!getName().equals(other.getName())) return false; if (getSignature() == null) { - if (other.getSignature() != null) - return false; - } else if (!getSignature().equals(other.getSignature())) - return false; - return true; + return other.getSignature() == null; + } else return getSignature().equals(other.getSignature()); } private MethodKey(String name, String signature) { diff --git a/src/main/java/com/aparapi/internal/model/MethodModel.java b/src/main/java/com/aparapi/internal/model/MethodModel.java index 1766a13c..9e29dcee 100644 --- a/src/main/java/com/aparapi/internal/model/MethodModel.java +++ b/src/main/java/com/aparapi/internal/model/MethodModel.java @@ -69,7 +69,7 @@ to national security controls as identified on the Commerce Control List (curren public class MethodModel{ - private static Logger logger = Logger.getLogger(Config.getLoggerName()); + private static final Logger logger = Logger.getLogger(Config.getLoggerName()); private ExpressionList expressionList; @@ -126,13 +126,9 @@ public FieldEntry getAccessorVariableFieldEntry() { return accessorVariableFieldEntry; } - private final Set calledMethods = new HashSet(); + public final Set calledMethods = new HashSet<>(); - public Set getCalledMethods() { - return calledMethods; - } - - public void checkForRecursion(Set transitiveCalledMethods) throws AparapiException { + public void checkForRecursion(Set transitiveCalledMethods) throws AparapiException { if (transitiveCalledMethods.contains(this)) { throw new ClassParseException(ClassParseException.TYPE.RECURSION, getName()); @@ -142,9 +138,7 @@ public void checkForRecursion(Set transitiveCalledMethods) throws A transitiveCalledMethods.add(this); // For each callee, send him a copy of the call chain up to this method - final Iterator cmi = getCalledMethods().iterator(); - while (cmi.hasNext()) { - final MethodModel next = cmi.next(); + for (MethodModel next : calledMethods) { next.checkForRecursion(transitiveCalledMethods); } @@ -165,7 +159,7 @@ public void checkForRecursion(Set transitiveCalledMethods) throws A * require pragmas to be used in the OpenCL source * */ - public void setRequiredPragmas(Instruction instruction) { + private void setRequiredPragmas(Instruction instruction) { final boolean setDouble = instruction.getByteCode().usesDouble(); if (setDouble) { usesDoubles = true; @@ -202,8 +196,8 @@ public boolean requiresByteAddressableStorePragma() { * * @return Map the returned pc to Instruction map */ - public Map createListOfInstructions() throws ClassParseException { - final Map pcMap = new LinkedHashMap(); + private Map createListOfInstructions() throws ClassParseException { + final Map pcMap = new LinkedHashMap<>(); final byte[] code = method.getCode(); // We create a byteReader for reading the bytes from the code array @@ -312,7 +306,7 @@ public Map createListOfInstructions() throws ClassParseExc * * @see InstructionSet.Branch#getTarget() */ - public void buildBranchGraphs(Map pcMap) { + private void buildBranchGraphs(Map pcMap) { for (Instruction instruction = pcHead; instruction != null; instruction = instruction.getNextPC()) { if (instruction.isBranch()) { final Branch branch = instruction.asBranch(); @@ -334,7 +328,7 @@ public void buildBranchGraphs(Map pcMap) { * * */ - public void deoptimizeReverseBranches() { + private void deoptimizeReverseBranches() { for (Instruction instruction = pcHead; instruction != null; instruction = instruction.getNextPC()) { if (instruction.isBranch()) { @@ -441,7 +435,7 @@ public void deoptimizeReverseBranches() { * @param _instruction * @throws ClassParseException */ - public void txFormDups(ExpressionList _expressionList, final Instruction _instruction) throws ClassParseException { + private void txFormDups(ExpressionList _expressionList, final Instruction _instruction) throws ClassParseException { if (_instruction instanceof I_DUP) { Instruction e = _expressionList.getTail(); while (!e.producesStack()) { @@ -541,7 +535,7 @@ public void txFormDups(ExpressionList _expressionList, final Instruction _instru * @throws ClassParseException */ - void foldExpressions() throws ClassParseException { + private void foldExpressions() throws ClassParseException { // we also populate a second list of expressions held between headTail.head and headTail.tail @@ -602,7 +596,7 @@ void foldExpressions() throws ClassParseException { } } - InstructionTransformer[] transformers = new InstructionTransformer[] { + private final InstructionTransformer[] transformers = new InstructionTransformer[] { new InstructionTransformer("long hand post increment of field"){ @@ -932,7 +926,7 @@ void foldExpressions() throws ClassParseException { final AssignToLocalVariable assign = (AssignToLocalVariable) i.getNextExpr(); final InlineAssignInstruction inlineAssign = new InlineAssignInstruction(MethodModel.this, assign, cast); - _expressionList.replaceInclusive((Instruction) cast, (Instruction) assign, inlineAssign); + _expressionList.replaceInclusive(cast, (Instruction) assign, inlineAssign); return (inlineAssign); } @@ -1143,7 +1137,7 @@ void foldExpressions() throws ClassParseException { } }, - new InstructionTransformer("incline assign from constant (method call or logical expression)"){ + new InstructionTransformer("inline assign from constant (method call or logical expression)"){ /** *

              *                 A                                     A
@@ -1243,7 +1237,7 @@ void foldExpressions() throws ClassParseException {
 
    };
 
-   void applyTransformations(ExpressionList _expressionList, final Instruction _instruction, final Instruction _operandStart)
+   private void applyTransformations(ExpressionList _expressionList, final Instruction _instruction, final Instruction _operandStart)
          throws ClassParseException {
 
       if (logger.isLoggable(Level.FINE)) {
@@ -1263,10 +1257,10 @@ void applyTransformations(ExpressionList _expressionList, final Instruction _ins
             && (_operandStart.getNextExpr() instanceof AssignToLocalVariable)) {
          final Instruction assignFirst = _operandStart.getNextExpr();
          Instruction assign = assignFirst;
-         int count = 0;
+//         int count = 0;
          while ((assign != null) && (assign instanceof AssignToLocalVariable)) {
             assign = assign.getNextExpr();
-            count++;
+//            count++;
          }
          if (assign == null) {
             final Instruction newOne = new MultiAssignInstruction(this, _operandStart, assignFirst, assign);
@@ -1309,7 +1303,7 @@ void applyTransformations(ExpressionList _expressionList, final Instruction _ins
    /**
     * Determine if this method is a getter and record the accessed field if so
     */
-   void checkForGetter(Map pcMap) throws ClassParseException {
+   private void checkForGetter(Map pcMap) throws ClassParseException {
       final String methodName = getMethod().getName();
       String rawVarNameCandidate = null;
       boolean mightBeGetter = true;
@@ -1337,7 +1331,7 @@ void checkForGetter(Map pcMap) throws ClassParseException
                if ((instruction instanceof Return) && (expressionList.getHead() == expressionList.getTail())) {
                   instruction = instruction.getPrevPC();
                   if (instruction instanceof AccessInstanceField) {
-                     final FieldEntry field = ((AccessInstanceField) instruction).getConstantPoolFieldEntry();
+                     final FieldEntry field = ((FieldReference) instruction).getConstantPoolFieldEntry();
                      accessedFieldName = field.getNameAndTypeEntry().getNameUTF8Entry().getUTF8();
                      if (accessedFieldName.equals(varNameCandidateCamelCased)) {
 
@@ -1395,7 +1389,7 @@ private void setAccessorVariableFieldEntry(FieldEntry field) {
    /**
     * Determine if this method is a setter and record the accessed field if so
     */
-   void checkForSetter(Map pcMap) throws ClassParseException {
+   private void checkForSetter(Map pcMap) throws ClassParseException {
       final String methodName = getMethod().getName();
       if (methodName.startsWith("set")) {
          final String rawVarNameCandidate = methodName.substring(3);
@@ -1409,7 +1403,7 @@ void checkForSetter(Map pcMap) throws ClassParseException
          if ((instruction instanceof AssignToInstanceField) && (expressionList.getTail() instanceof Return) && (pcMap.size() == 4)) {
             final Instruction prev = instruction.getPrevPC();
             if (prev instanceof AccessLocalVariable) {
-               final FieldEntry field = ((AssignToInstanceField) instruction).getConstantPoolFieldEntry();
+               final FieldEntry field = ((FieldReference) instruction).getConstantPoolFieldEntry();
                accessedFieldName = field.getNameAndTypeEntry().getNameUTF8Entry().getUTF8();
                if (accessedFieldName.equals(varNameCandidateCamelCased)) {
 
@@ -1448,7 +1442,7 @@ void checkForSetter(Map pcMap) throws ClassParseException
    }
 
    // The entrypoint is used to make checks on object accessors
-   Entrypoint entrypoint = null;
+   private Entrypoint entrypoint = null;
 
    MethodModel(ClassModelMethod _method, Entrypoint _entrypoint) throws AparapiException {
       entrypoint = _entrypoint;
@@ -1461,13 +1455,13 @@ void checkForSetter(Map pcMap) throws ClassParseException
 
    public static class FakeLocalVariableTableEntry implements LocalVariableTableEntry{
 
-      class Var implements LocalVariableInfo{
+      static class Var implements LocalVariableInfo{
 
          int startPc = 0;
 
          int endPc = 0;
 
-         String name = null;
+         final String name;
 
          boolean arg;
 
@@ -1483,7 +1477,7 @@ class Var implements LocalVariableInfo{
                name = "arr_" + _slotIndex;
                descriptor = "/* arg */";
             } else {
-               name = _storeSpec.toString().toLowerCase() + "_" + _slotIndex;
+               name = _storeSpec.toString().toLowerCase() + '_' + _slotIndex;
                descriptor = _storeSpec.toString();
             }
          }
@@ -1493,11 +1487,16 @@ class Var implements LocalVariableInfo{
          }
 
          @Override public boolean equals(Object object) {
-            return (object instanceof Var && ((object == this) || ((Var) object).name.equals(name)));
+            return this==object || (object instanceof Var && ((Var) object).name.equals(name));
          }
 
-         public String toString() {
-            return (name + "[" + startPc + "-" + endPc + "]");
+          @Override
+          public int hashCode() {
+              return name.hashCode();
+          }
+
+          public String toString() {
+            return (name + '[' + startPc + '-' + endPc + ']');
          }
 
          @Override public boolean isArray() {
@@ -1529,9 +1528,9 @@ public String toString() {
          }
       }
 
-      List list = new ArrayList();
+      final List list = new ArrayList<>();
 
-      public FakeLocalVariableTableEntry(Map _pcMap, ClassModelMethod _method) {
+      FakeLocalVariableTableEntry(Map _pcMap, ClassModelMethod _method) {
          int numberOfSlots = _method.getCodeEntry().getMaxLocals();
 
          MethodDescription description = ClassModel.getMethodDescription(_method.getDescriptor());
@@ -1583,10 +1582,9 @@ public FakeLocalVariableTableEntry(Map _pcMap, ClassModelM
             vars[i].endPc = pc + instruction.getLength();
          }
 
-         Collections.sort(list, new Comparator(){
-            @Override public int compare(LocalVariableInfo o1, LocalVariableInfo o2) {
-               return o1.getStart() - o2.getStart();
-            }
+         list.sort((o1, o2) -> {
+             if (o1 == o2) return 0;
+             return Integer.compare(o2.getStart(), o1.getStart()); //o1.getStart() - o2.getStart();
          });
 
          if (Config.enableShowFakeLocalVariableTable) {
@@ -1601,18 +1599,18 @@ public FakeLocalVariableTableEntry(Map _pcMap, ClassModelM
       }
 
       @Override public LocalVariableInfo getVariable(int _pc, int _index) {
-         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())
-                  && _index == localVariableInfo.getVariableIndex()) {
-               returnValue = localVariableInfo;
-               break;
+             int start = localVariableInfo.getStart();
+             if (_pc >= start - 1 &&
+                 _pc <= (start + localVariableInfo.getLength()) &&
+                 _index == localVariableInfo.getVariableIndex()) {
+               return localVariableInfo;
             }
          }
-         return (returnValue);
+         return null;
       }
 
       @Override public Iterator iterator() {
@@ -1621,12 +1619,12 @@ public FakeLocalVariableTableEntry(Map _pcMap, ClassModelM
 
    }
 
-   private void init(ClassModelMethod _method) throws AparapiException {
-      try {
+   private void init(ClassModelMethod _method) throws ClassParseException {
+      //try {
          method = _method;
          expressionList = new ExpressionList(this);
          ClassModel owner = _method.getOwnerClassModel();
-         if (owner.getNoCLMethods().contains(method.getName())) {
+         if (owner.isNoCLMethod(method.getName())) {
              noCL = true;
          }
 
@@ -1650,10 +1648,12 @@ private void init(ClassModelMethod _method) throws AparapiException {
          if (localVariableTableEntry == null) {
             localVariableTableEntry = new FakeLocalVariableTableEntry(pcMap, method);
             method.setLocalVariableTableEntry(localVariableTableEntry);
-            logger.warning("Method "
-                  + method.getName()
-                  + method.getDescriptor()
-                  + " does not contain a LocalVariableTable entry (source not compiled with -g) codegen will attempt to create a synthetic table based on bytecode. This is experimental!!");
+
+            if (logger.isLoggable(Level.WARNING))
+                logger.warning("Method "
+                      + method.getName()
+                      + method.getDescriptor()
+                      + " does not contain a LocalVariableTable entry (source not compiled with -g) codegen will attempt to create a synthetic table based on bytecode. This is experimental!!");
          }
 
          // pass #2 build branch graph
@@ -1686,14 +1686,14 @@ private void init(ClassModelMethod _method) throws AparapiException {
          if (Config.instructionListener != null) {
             Config.instructionListener.showAndTell("end", expressionList.getHead(), null);
          }
-      } catch (final Throwable _t) {
-         if (_t instanceof ClassParseException) {
-            _t.printStackTrace();
-            throw (ClassParseException) _t;
-         }
-         throw new ClassParseException(_t);
-
-      }
+//      } catch (final Throwable _t) {
+//         if (_t instanceof ClassParseException) {
+//            _t.printStackTrace();
+//            throw (ClassParseException) _t;
+//         }
+//         throw new ClassParseException(_t);
+//
+//      }
    }
 
    public LocalVariableTableEntry getLocalVariableTableEntry() {
@@ -1716,19 +1716,19 @@ public String getSimpleName() {
     * @return the fully qualified name such as "com_amd_javalabs_opencl_demo_PaternityTest$SimpleKernel__actuallyDoIt"
     */
    public String getName() {
-      return (method.getClassModel().getMethod(method.getName(), method.getDescriptor()).getClassModel().getClassWeAreModelling()
+       return (method.getClassModel().getMethod(method.getName(), method.getDescriptor()).getClassModel().clazz
             .getName().replace('.', '_')
             + "__" + method.getName());
    }
 
    public String getReturnType() {
       final String returnType = method.getDescriptorUTF8Entry().getUTF8();
-      final int index = returnType.indexOf(")");
+      final int index = returnType.indexOf(')');
       return (returnType.substring(index + 1));
    }
 
    public List getMethodCalls() {
-      final List methodCalls = new ArrayList();
+      final List methodCalls = new ArrayList<>();
 
       for (Instruction i = getPCHead(); i != null; i = i.getNextPC()) {
          if (i instanceof MethodCall) {
diff --git a/src/main/java/com/aparapi/internal/model/ValueCache.java b/src/main/java/com/aparapi/internal/model/ValueCache.java
index e2568a46..397fc1a4 100644
--- a/src/main/java/com/aparapi/internal/model/ValueCache.java
+++ b/src/main/java/com/aparapi/internal/model/ValueCache.java
@@ -32,7 +32,7 @@ public interface ValueComputer extends ThrowingValueComputer ValueCache on(ThrowingValueComputer computer) {
-      return new ValueCache(computer);
+      return new ValueCache<>(computer);
    }
 
    private final ConcurrentMap> map = new ConcurrentHashMap<>();
diff --git a/src/main/java/com/aparapi/internal/opencl/OpenCLArgDescriptor.java b/src/main/java/com/aparapi/internal/opencl/OpenCLArgDescriptor.java
index 2c3349c9..7d30631c 100644
--- a/src/main/java/com/aparapi/internal/opencl/OpenCLArgDescriptor.java
+++ b/src/main/java/com/aparapi/internal/opencl/OpenCLArgDescriptor.java
@@ -99,7 +99,7 @@ public OpenCLArgDescriptor(String _name, long _bits) {
       }
 
       if ((bits & ARG_ARRAY_BIT) == ARG_ARRAY_BIT) {
-         argBuilder.append("*");
+         argBuilder.append('*');
       }
 
       argBuilder.append(name);
diff --git a/src/main/java/com/aparapi/internal/opencl/OpenCLKernel.java b/src/main/java/com/aparapi/internal/opencl/OpenCLKernel.java
index 3b1bba49..e733a0e9 100644
--- a/src/main/java/com/aparapi/internal/opencl/OpenCLKernel.java
+++ b/src/main/java/com/aparapi/internal/opencl/OpenCLKernel.java
@@ -56,7 +56,7 @@ private OpenCLKernel() {
     * @return
     */
    public static OpenCLKernel createKernel(OpenCLProgram _program, String _kernelName, List _args) {
-      final OpenCLArgDescriptor[] argArray = _args.toArray(new OpenCLArgDescriptor[0]);
+      final OpenCLArgDescriptor[] argArray = _args.toArray(new OpenCLArgDescriptor[_args.size()]);
       final OpenCLKernel oclk = new OpenCLKernel().createKernelJNI(_program, _kernelName, argArray);
       for (final OpenCLArgDescriptor arg : argArray) {
          arg.kernel = oclk;
diff --git a/src/main/java/com/aparapi/internal/opencl/OpenCLPlatform.java b/src/main/java/com/aparapi/internal/opencl/OpenCLPlatform.java
index 43f26969..3626760e 100644
--- a/src/main/java/com/aparapi/internal/opencl/OpenCLPlatform.java
+++ b/src/main/java/com/aparapi/internal/opencl/OpenCLPlatform.java
@@ -32,7 +32,7 @@ public class OpenCLPlatform extends OpenCLJNI{
 
    private final String name;
 
-   private final List devices = new ArrayList();
+   private final List devices = new ArrayList<>();
 
    private static List platforms;
 
@@ -73,7 +73,7 @@ public List getOpenCLPlatforms() {
          if (OpenCLLoader.isOpenCLAvailable()) {
             platforms = getPlatforms();
          } else {
-            return (Collections.EMPTY_LIST);
+            return (Collections.emptyList());
          }
       }
       return platforms;
diff --git a/src/main/java/com/aparapi/internal/opencl/OpenCLProgram.java b/src/main/java/com/aparapi/internal/opencl/OpenCLProgram.java
index 1f01246c..4d86c86b 100644
--- a/src/main/java/com/aparapi/internal/opencl/OpenCLProgram.java
+++ b/src/main/java/com/aparapi/internal/opencl/OpenCLProgram.java
@@ -40,9 +40,9 @@ public class OpenCLProgram extends OpenCLJNI{
    /**
     * FIXME Why are these not ConcurrentHashMaps or at least synchronized at a finer grain?
     */
-   private final Map instanceToMem = new HashMap();
+   private final Map instanceToMem = new HashMap<>();
 
-   private final Map addressToMem = new HashMap();
+   private final Map addressToMem = new HashMap<>();
 
    /**
     * Minimal constructor
diff --git a/src/main/java/com/aparapi/internal/reader/ByteBuffer.java b/src/main/java/com/aparapi/internal/reader/ByteBuffer.java
index a5dbb43f..39107cbf 100644
--- a/src/main/java/com/aparapi/internal/reader/ByteBuffer.java
+++ b/src/main/java/com/aparapi/internal/reader/ByteBuffer.java
@@ -68,7 +68,7 @@ to national security controls as identified on the Commerce Control List (curren
  * @author gfrost
  *
  */
-public class ByteBuffer{
+class ByteBuffer{
 
    private byte[] bytes;
 
@@ -233,7 +233,7 @@ String utf8(int _offset) {
       return (returnString);
    }
 
-   byte b(int _offset) {
+   private byte b(int _offset) {
       return bytes[_offset];
    }
 
diff --git a/src/main/java/com/aparapi/internal/tool/ABCCKernel.java b/src/main/java/com/aparapi/internal/tool/ABCCKernel.java
new file mode 100644
index 00000000..af7341ef
--- /dev/null
+++ b/src/main/java/com/aparapi/internal/tool/ABCCKernel.java
@@ -0,0 +1,65 @@
+package com.aparapi.internal.tool;
+
+import com.aparapi.Kernel;
+
+/** example kernel for testing and tutorial purposes */
+public class ABCCKernel extends Kernel {
+    public static final int FI = 0, GI = 1, HI = 2, YI = 3, FI2 = 4, FIGI = 5, GI2 = 6, YIFI = 7, YIGI = 8, FIHI = 9, GIHI = 10, HI2 = 11, YIHI = 12;
+    public static final int v = 13;
+    private static final int TC = 0, M = 1, W = 2;
+    private float[] T, p;
+    private float[] tcmw = new float[3];
+    private float[] result;
+    //public final int N;
+
+    public ABCCKernel(float[] t, float[] p) {
+        setExplicit(true);
+        this.T = t;
+        this.p = p;
+        this.result = new float[t.length * v];
+        put(this.T).put(this.p).put(result);
+    }
+
+    public void setNewTandP(float[] t, float[] p) {
+        this.T = t;
+        this.p = p;
+        this.result = new float[t.length * v];
+        put(this.T).put(this.p).put(result);
+    }
+
+    public void set_tcmw(float tc, float m, float w) {
+        this.tcmw = new float[]{tc, m, w};
+        put(this.tcmw);
+    }
+
+    @Override
+    public void run() {
+        int i = getGlobalId();
+        int j = i * v;
+        int fi = FI + j, gi = GI + j, hi = HI + j, yi = YI + j, fi2 = FI2 + j, figi = FIGI + j, gi2 = GI2 + j, yifi = YIFI + j, yigi = YIGI + j, fihi = FIHI + j, gihi = GIHI + j, hi2 = HI2 + j, yihi = YIHI + j;
+        float tc = tcmw[TC];
+        float w = tcmw[W];
+        float m = tcmw[M];
+
+        float[] r = this.result;
+
+        r[fi] = pow((tc - T[i]), m);
+        r[gi] = r[fi] * cos(w * log(tc - T[i])); //TODO check if this inner log is computed once and shared
+        r[hi] = r[fi] * sin(w * log(tc - T[i]));
+        r[yi] = p[i];
+        r[fi2] = r[fi] * r[fi];
+        r[figi] = r[fi] * r[gi];
+        r[gi2] = r[gi] * r[gi];
+        r[yifi] = r[yi] * r[fi];
+        r[yigi] = r[yi] * r[gi];
+        r[fihi] = r[fi] * r[hi];
+        r[gihi] = r[gi] * r[hi];
+        r[hi2] = r[hi] * r[hi];
+        r[yihi] = r[yi] * r[hi];
+    }
+
+    public float[] getResult() {
+        get(result);
+        return result;
+    }
+}
diff --git a/src/main/java/com/aparapi/internal/tool/InstructionHelper.java b/src/main/java/com/aparapi/internal/tool/InstructionHelper.java
index aedcd6cb..34ac86c0 100644
--- a/src/main/java/com/aparapi/internal/tool/InstructionHelper.java
+++ b/src/main/java/com/aparapi/internal/tool/InstructionHelper.java
@@ -43,24 +43,24 @@
 
 public class InstructionHelper{
 
-   public static class Table{
+   static class Table{
 
       final static String spaces = "                                                                                                                        ";
 
-      private final List cols = new ArrayList();
+      private final List cols = new ArrayList<>();
 
       private int size = 0;
 
       private int col = 0;
 
-      public static class Col{
-         private final List text = new ArrayList();
+      static class Col{
+         private final List text = new ArrayList<>();
 
          private int width;
 
          private String format = "%s";
 
-         public Col(String _format) {
+         Col(String _format) {
             format = _format;
          }
 
@@ -68,7 +68,7 @@ public Col() {
             this("%s");
          }
 
-         public void format(Object... args) {
+         void format(Object... args) {
             final String s = String.format(format, args);
 
             width = Math.max(s.length(), width);
@@ -79,7 +79,7 @@ public int size() {
             return (text.size());
          }
 
-         public String pad(String _s, int _width) {
+         static String pad(String _s, int _width) {
             final int length = _s.length();
             final int padWidth = _width - length;
             final String padded = _s + spaces.substring(0, padWidth);
@@ -87,24 +87,24 @@ public String pad(String _s, int _width) {
 
          }
 
-         public String get(int _i) {
+         String get(int _i) {
 
             return (pad(text.get(_i), width));
          }
 
-         public void header(String _header) {
+         void header(String _header) {
             text.add(_header);
             width = _header.length();
          }
       }
 
-      public Table(String... _formats) {
+      Table(String... _formats) {
          for (final String format : _formats) {
             cols.add(new Col(format));
          }
       }
 
-      public void data(Object... args) {
+      void data(Object... args) {
          cols.get(col++).format(args);
          if (col == cols.size()) {
             col = 0;
@@ -119,13 +119,13 @@ public void data(Object... args) {
             for (final Table.Col col : cols) {
                sb.append(col.get(i));
             }
-            sb.append("\n");
+            sb.append('\n');
          }
 
          return (sb.toString());
       }
 
-      public void header(String... _headers) {
+      void header(String... _headers) {
          for (int i = 0; i < _headers.length; i++) {
             cols.get(i).header(_headers[i]);
          }
@@ -137,11 +137,11 @@ public void header(String... _headers) {
    public static class StringWriter extends BlockWriter{
       private StringBuilder sb = null;
 
-      public StringWriter(StringBuilder _sb) {
+      StringWriter(StringBuilder _sb) {
          sb = _sb;
       }
 
-      public StringWriter() {
+      StringWriter() {
          sb = new StringBuilder();
       }
 
@@ -167,23 +167,20 @@ public static String write(MethodModel _methodModel) throws CodeGenException {
          // TODO Auto-generated method stub
       }
 
-      @Override public void writeMethodBody(MethodModel _methodModel) throws CodeGenException {
-         super.writeMethodBody(_methodModel);
-      }
    }
 
-   public static class BranchVector{
-      protected Instruction from;
+   static class BranchVector{
+      final Instruction from;
 
-      protected Instruction to;
+      final Instruction to;
 
-      protected Instruction start;
+      final Instruction start;
 
-      protected Instruction end;
+      final Instruction end;
 
       private boolean forward = false;
 
-      public BranchVector(Instruction _from, Instruction _to) {
+      BranchVector(Instruction _from, Instruction _to) {
          from = _from;
          to = _to;
          if (from.getThisPC() > to.getThisPC()) {
@@ -211,23 +208,23 @@ public Instruction getTo() {
          return (to);
       }
 
-      public Instruction getFrom() {
+      Instruction getFrom() {
          return (from);
       }
 
-      public int getStartPC() {
+      int getStartPC() {
          return (start.getThisPC());
       }
 
-      public int getEndPC() {
+      int getEndPC() {
          return (end.getThisPC());
       }
 
-      public Instruction getStart() {
+      Instruction getStart() {
          return (start);
       }
 
-      public Instruction getEnd() {
+      Instruction getEnd() {
          return (end);
       }
 
@@ -241,7 +238,7 @@ public Instruction getEnd() {
 
       }
 
-      public boolean isForward() {
+      boolean isForward() {
          return (forward);
       }
 
@@ -252,7 +249,7 @@ public boolean isForward() {
          return ("backward from " + getEnd() + " to " + getStart());
       }
 
-      public boolean isConditionalBranch() {
+      boolean isConditionalBranch() {
          return (getFrom().isBranch() && getFrom().asBranch().isConditional());
       }
 
@@ -260,19 +257,19 @@ public boolean isBackward() {
          return (!isForward());
       }
 
-      public static final String NONE = " ";
+      static final String NONE = " ";
 
-      public static final String THROUGH = "|";
+      static final String THROUGH = "|";
 
-      public static final String CONDITIONAL_START = "?";
+      static final String CONDITIONAL_START = "?";
 
-      public static final String UNCONDITIONAL_START = "-";
+      static final String UNCONDITIONAL_START = "-";
 
-      public static final String TOP_ARROW = "^";
+      static final String TOP_ARROW = "^";
 
-      public static final String BOTTOM_ARROW = "v";
+      static final String BOTTOM_ARROW = "v";
 
-      public String render(int _pc) {
+      String render(int _pc) {
          String returnString = NONE;
 
          if (isForward()) {
@@ -295,7 +292,7 @@ public String render(int _pc) {
          return returnString;
       }
 
-      public String render(int _startPC, int _thisPC) {
+      String render(int _startPC, int _thisPC) {
          String returnString = NONE;
          if (isForward()) {
             if (_startPC == getStartPC()) {
@@ -345,11 +342,11 @@ public static String getLabel(Instruction instruction, boolean showNumber, boole
             } else if (instruction instanceof MethodCall) {
                final MethodCall methodCall = (MethodCall) instruction;
                label.append(methodCall.getConstantPoolMethodEntry().getNameAndTypeEntry().getNameUTF8Entry().getUTF8());
-               label.append(" ");
+               label.append(' ');
                label.append(methodCall.getConstantPoolMethodEntry().getNameAndTypeEntry().getDescriptorUTF8Entry().getUTF8());
             } else if (instruction instanceof OperatorInstruction) {
                final OperatorInstruction operatorInstruction = (OperatorInstruction) instruction;
-               label.append(operatorInstruction.getOperator().getText() + "(" + byteCodeName + ")");
+               label.append(operatorInstruction.getOperator().getText()).append('(').append(byteCodeName).append(')');
             } else if (instruction instanceof FieldReference) {
                final FieldReference field = (FieldReference) instruction;
                label.append(field.getConstantPoolFieldEntry().getNameAndTypeEntry().getNameUTF8Entry().getUTF8());
@@ -376,7 +373,7 @@ public static String getLabel(Instruction instruction, boolean showNumber, boole
                }
 
                label.append(info == null ? "?" : info.getVariableName());
-               label.append("=");
+               label.append('=');
 
             } else if (instruction instanceof LocalVariableTableIndexAccessor) {
                final LocalVariableTableIndexAccessor localVariableAccessor = (LocalVariableTableIndexAccessor) instruction;
@@ -386,8 +383,8 @@ public static String getLabel(Instruction instruction, boolean showNumber, boole
             } else if (instruction instanceof I_IINC) {
 
                label.append(instruction.getByteCode());
-               label.append(" " + ((I_IINC) instruction).getDelta());
-               label.append(" " + ((I_IINC) instruction).getLocalVariableInfo().getVariableName());
+               label.append(' ').append(((I_IINC) instruction).getDelta());
+               label.append(' ').append(((I_IINC) instruction).getLocalVariableInfo().getVariableName());
             } else if (instruction instanceof CompositeInstruction) {
                label.append("composite ");
                label.append(instruction.getByteCode());
@@ -467,7 +464,7 @@ static String createView(MethodModel _methodModel, String _msg, Instruction _hea
             sb.append(branchInfo.render(root.getThisPC(), root.getStartPC()));
          }
          table.data(root.getStartPC(), root.getThisPC());
-         table.data(" " + label);
+         table.data(' ' + label);
          table.data(sb);
          table.data(_pcForwardBranchTargetCounts[root.getStartPC()]);
       }
@@ -477,7 +474,7 @@ static String createView(MethodModel _methodModel, String _msg, Instruction _hea
          sb.append(branchInfo.render(_tail.getThisPC(), _tail.getStartPC()));
       }
       table.data(_tail.getStartPC(), _tail.getThisPC());
-      table.data("[" + label + "]");
+      table.data('[' + label + ']');
       table.data(sb);
       table.data(_pcForwardBranchTargetCounts[_tail.getStartPC()]);
       return (_msg + "{\n" + table.toString() + "}\n");
@@ -505,16 +502,13 @@ static String getJavapView(MethodModel _methodModel) {
       return (table.toString());
    }
 
-   private static Comparator branchInfoComparator = new Comparator(){
-      @Override public int compare(BranchVector left, BranchVector right) {
-         final int value = left.getFrom().compareTo(right.getFrom());
-         return (value);
-      }
-
+   private static final Comparator branchInfoComparator = (left, right) -> {
+      final int value = left.getFrom().compareTo(right.getFrom());
+      return (value);
    };
 
-   static List getBranches(MethodModel _methodModel) {
-      final List branchVectors = new ArrayList();
+   private static List getBranches(MethodModel _methodModel) {
+      final List branchVectors = new ArrayList<>();
 
       for (Instruction instruction = _methodModel.getPCHead(); instruction != null; instruction = instruction.getNextPC()) {
          if (instruction.isBranch()) {
@@ -524,16 +518,16 @@ static List getBranches(MethodModel _methodModel) {
          }
       }
       // Sort the branch vectors.  The natural order is essentially by from address. Note that this is not the same as start address.. back edges would be the exceptions
-      Collections.sort(branchVectors, branchInfoComparator);
+      branchVectors.sort(branchInfoComparator);
 
       return (branchVectors);
    }
 
-   void edump(StringBuilder _sb, Instruction i, boolean clone) {
+   private static void edump(StringBuilder _sb, Instruction i, boolean clone) {
       final String label = InstructionHelper.getLabel(i, false, true, true);
 
       if (i instanceof CloneInstruction) {
-         edump(_sb, ((CloneInstruction) i).getReal(), true);
+         edump(_sb, i.getReal(), true);
       } else {
 
          if (i.producesStack()) {
@@ -543,20 +537,20 @@ void edump(StringBuilder _sb, Instruction i, boolean clone) {
          }
 
          if (clone) {
-            _sb.append("*");
+            _sb.append('*');
          } else {
-            _sb.append(" ");
+            _sb.append(' ');
          }
-         _sb.append(i.getThisPC() + ":" + label);
+         _sb.append(i.getThisPC()).append(':').append(label);
       }
 
    }
 
-   void fdump(int _depth, Instruction i, boolean clone) {
+   private static void fdump(int _depth, Instruction i, boolean clone) {
       final String label = i.getByteCode().getName();// InstructionHelper.getLabel(i, false, false, false);
 
       if (i instanceof CloneInstruction) {
-         fdump(_depth, ((CloneInstruction) i).getReal(), true);
+         fdump(_depth, i.getReal(), true);
       } else {
          if (_depth == 0) {
             if (i.producesStack()) {
@@ -590,11 +584,11 @@ void fdump(int _depth, Instruction i, boolean clone) {
       }
    }
 
-   void dump(String _indent, Instruction i, boolean clone) {
+   private static void dump(String _indent, Instruction i, boolean clone) {
       final String label = InstructionHelper.getLabel(i, true, false, false);
 
       if (i instanceof CloneInstruction) {
-         dump(_indent, ((CloneInstruction) i).getReal(), true);
+         dump(_indent, i.getReal(), true);
       } else {
          System.out.println(_indent + (clone ? "*" : " ") + label);
       }
diff --git a/src/main/java/com/aparapi/internal/tool/InstructionViewer.java b/src/main/java/com/aparapi/internal/tool/InstructionViewer.java
index ce83f795..fdcc2f1d 100644
--- a/src/main/java/com/aparapi/internal/tool/InstructionViewer.java
+++ b/src/main/java/com/aparapi/internal/tool/InstructionViewer.java
@@ -1,12 +1,12 @@
 /**
  * Copyright (c) 2016 - 2017 Syncleus, Inc.
- *
+ * 

* Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + *

+ * http://www.apache.org/licenses/LICENSE-2.0 + *

* Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -28,7 +28,6 @@ import java.awt.RenderingHints; import java.awt.Shape; import java.awt.Stroke; -import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; @@ -47,22 +46,7 @@ import java.util.List; import java.util.Map; -import javax.swing.JButton; -import javax.swing.JCheckBox; -import javax.swing.JComponent; -import javax.swing.JFrame; -import javax.swing.JLabel; -import javax.swing.JMenu; -import javax.swing.JMenuBar; -import javax.swing.JMenuItem; -import javax.swing.JPanel; -import javax.swing.JToggleButton; -import javax.swing.JToolBar; -import javax.swing.SpringLayout; -import javax.swing.UIManager; -import javax.swing.UnsupportedLookAndFeelException; -import javax.swing.event.ChangeEvent; -import javax.swing.event.ChangeListener; +import javax.swing.*; import com.aparapi.Config; import com.aparapi.internal.exception.AparapiException; @@ -76,1057 +60,1086 @@ import com.aparapi.internal.tool.InstructionViewer.Form.Template; import com.aparapi.internal.tool.InstructionViewer.Form.Toggle; -public class InstructionViewer implements Config.InstructionListener{ +public class InstructionViewer implements Config.InstructionListener { - public static abstract class Form { - public @interface OneOf { - String label(); + static abstract class Form { + public @interface OneOf { + String label(); - String[] options(); - } + String[] options(); + } - public interface Template{ - } + interface Template { + } - @Retention(RetentionPolicy.RUNTIME) public @interface List { - Class value(); + @Retention(RetentionPolicy.RUNTIME) + public @interface List { + Class value(); - } + } - @Retention(RetentionPolicy.RUNTIME) public @interface Toggle { - String label(); + @Retention(RetentionPolicy.RUNTIME) + @interface Toggle { + String label(); - String on(); + String on(); - String off(); - } + String off(); + } - @Retention(RetentionPolicy.RUNTIME) public @interface Check { - String label(); - } + @Retention(RetentionPolicy.RUNTIME) + @interface Check { + String label(); + } - public final static int INSET = 5; + final static int INSET = 5; - private final T template; + private final T template; - JPanel panel; + final JPanel panel; - private final SpringLayout layout = new SpringLayout(); + private final SpringLayout layout = new SpringLayout(); - void setBoolean(Field _field, boolean _value) { - try { - _field.setBoolean(template, _value); - } catch (final IllegalArgumentException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (final IllegalAccessException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - - boolean getBoolean(Field _field) { - try { - return (_field.getBoolean(template)); - } catch (final IllegalArgumentException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (final IllegalAccessException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - return (false); - } - - Object get(Field _field) { - try { - return (_field.get(template)); - } catch (final IllegalArgumentException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (final IllegalAccessException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - return (null); - } - - public Form(T _template) { - template = _template; - panel = new JPanel(layout); - JComponent last = panel; - final Map fieldToLabelMap = new LinkedHashMap(); - Field fieldWithWidestLabel = null; - int fieldWithWidestLabelWidth = 0; - - // we need to know the widest Label so create the labels in one pass - for (final Field field : template.getClass().getFields()) { - String labelString = null; - - final Check checkAnnotation = field.getAnnotation(Check.class); - if (checkAnnotation != null) { - labelString = checkAnnotation.label(); - } else { - final Toggle toggleAnnotation = field.getAnnotation(Toggle.class); - if (toggleAnnotation != null) { - labelString = toggleAnnotation.label(); - } + void setBoolean(Field _field, boolean _value) { + try { + _field.setBoolean(template, _value); + } catch (final IllegalArgumentException | IllegalAccessException e) { + // TODO Auto-generated catch block + e.printStackTrace(); } - if (labelString != null) { - final JLabel label = new JLabel(labelString); - panel.add(label); - - fieldToLabelMap.put(field, label); - if (labelString.length() > fieldWithWidestLabelWidth) { - fieldWithWidestLabel = field; - fieldWithWidestLabelWidth = labelString.length(); - } + } + + boolean getBoolean(Field _field) { + try { + return (_field.getBoolean(template)); + } catch (final IllegalArgumentException | IllegalAccessException e) { + // TODO Auto-generated catch block + e.printStackTrace(); } - } - - for (final Field field : fieldToLabelMap.keySet()) { - layout.putConstraint(SpringLayout.NORTH, fieldToLabelMap.get(field), INSET, (last == panel) ? SpringLayout.NORTH - : SpringLayout.SOUTH, last); - layout.putConstraint(SpringLayout.WEST, fieldToLabelMap.get(field), INSET, SpringLayout.WEST, panel); - JComponent newComponent = null; - - if (field.getType().isAssignableFrom(Boolean.TYPE)) { - final Field booleanField = field; - - final Toggle toggleAnnotation = field.getAnnotation(Toggle.class); - if (toggleAnnotation != null) { - final String toggleButtonOnLabel = toggleAnnotation.on(); - final String toggleButtonOffLabel = toggleAnnotation.off(); - final String toggleButtonLabel = getBoolean(field) ? toggleButtonOnLabel : toggleButtonOffLabel; - final JToggleButton toggleButton = new JToggleButton(toggleButtonLabel, getBoolean(field)); - toggleButton.addActionListener(new ActionListener(){ - @Override public void actionPerformed(ActionEvent _actionEvent) { - final JToggleButton toggleButton = ((JToggleButton) _actionEvent.getSource()); - // System.out.println("toggle toggle "+toggleButton); - if (toggleButton.getText().equals(toggleButtonOnLabel)) { - toggleButton.setText(toggleButtonOffLabel); - setBoolean(booleanField, false); - - } else { - toggleButton.setText(toggleButtonOnLabel); - setBoolean(booleanField, true); + return (false); + } - } - sync(); - - } - }); - newComponent = toggleButton; - } - final Check checkAnnotation = field.getAnnotation(Check.class); - if (checkAnnotation != null) { - final JCheckBox checkBox = new JCheckBox(); - checkBox.setSelected(getBoolean(field)); - - checkBox.addChangeListener(new ChangeListener(){ - - @Override public void stateChanged(ChangeEvent _changeEvent) { - - final JCheckBox checkBox = ((JCheckBox) _changeEvent.getSource()); - // System.out.println("check toggle "+checkBox); - setBoolean(booleanField, checkBox.isSelected()); - sync(); - - } - }); - newComponent = checkBox; - } + Object get(Field _field) { + try { + return (_field.get(template)); + } catch (final IllegalArgumentException | IllegalAccessException e) { + // TODO Auto-generated catch block + e.printStackTrace(); } - if (newComponent != null) { - panel.add(newComponent); - layout.putConstraint(SpringLayout.NORTH, newComponent, INSET, (last == panel) ? SpringLayout.NORTH - : SpringLayout.SOUTH, last); - layout.putConstraint(SpringLayout.WEST, newComponent, INSET, SpringLayout.EAST, - fieldToLabelMap.get(fieldWithWidestLabel)); - layout.putConstraint(SpringLayout.EAST, newComponent, INSET, SpringLayout.EAST, panel); + return (null); + } + + Form(T _template) { + template = _template; + panel = new JPanel(layout); + JComponent last = panel; + final Map fieldToLabelMap = new LinkedHashMap<>(); + Field fieldWithWidestLabel = null; + int fieldWithWidestLabelWidth = 0; + + // we need to know the widest Label so create the labels in one pass + for (final Field field : template.getClass().getFields()) { + String labelString = null; + + final Check checkAnnotation = field.getAnnotation(Check.class); + if (checkAnnotation != null) { + labelString = checkAnnotation.label(); + } else { + final Toggle toggleAnnotation = field.getAnnotation(Toggle.class); + if (toggleAnnotation != null) { + labelString = toggleAnnotation.label(); + } + } + if (labelString != null) { + final JLabel label = new JLabel(labelString); + panel.add(label); + + fieldToLabelMap.put(field, label); + if (labelString.length() > fieldWithWidestLabelWidth) { + fieldWithWidestLabel = field; + fieldWithWidestLabelWidth = labelString.length(); + } + } } - last = newComponent; - } - layout.layoutContainer(panel); + for (final Map.Entry fieldJLabelEntry : fieldToLabelMap.entrySet()) { + layout.putConstraint(SpringLayout.NORTH, fieldJLabelEntry.getValue(), INSET, (last == panel) ? SpringLayout.NORTH + : SpringLayout.SOUTH, last); + layout.putConstraint(SpringLayout.WEST, fieldJLabelEntry.getValue(), INSET, SpringLayout.WEST, panel); + JComponent newComponent = null; + + if (((Field) fieldJLabelEntry.getKey()).getType().isAssignableFrom(Boolean.TYPE)) { + final Field booleanField = fieldJLabelEntry.getKey(); + + final Toggle toggleAnnotation = (fieldJLabelEntry.getKey()).getAnnotation(Toggle.class); + if (toggleAnnotation != null) { + final String toggleButtonOnLabel = toggleAnnotation.on(); + final String toggleButtonOffLabel = toggleAnnotation.off(); + final String toggleButtonLabel = getBoolean(fieldJLabelEntry.getKey()) ? toggleButtonOnLabel : toggleButtonOffLabel; + final JToggleButton toggleButton = new JToggleButton(toggleButtonLabel, getBoolean(fieldJLabelEntry.getKey())); + toggleButton.addActionListener(_actionEvent -> { + final JToggleButton toggleButton1 = ((JToggleButton) _actionEvent.getSource()); + // System.out.println("toggle toggle "+toggleButton); + if (toggleButton1.getText().equals(toggleButtonOnLabel)) { + toggleButton1.setText(toggleButtonOffLabel); + setBoolean(booleanField, false); + + } else { + toggleButton1.setText(toggleButtonOnLabel); + setBoolean(booleanField, true); + + } + sync(); + + }); + newComponent = toggleButton; + } + final Check checkAnnotation = (fieldJLabelEntry.getKey()).getAnnotation(Check.class); + if (checkAnnotation != null) { + final JCheckBox checkBox = new JCheckBox(); + checkBox.setSelected(getBoolean(fieldJLabelEntry.getKey())); + + checkBox.addChangeListener(_changeEvent -> { + + final JCheckBox checkBox1 = ((JCheckBox) _changeEvent.getSource()); + // System.out.println("check toggle "+checkBox); + setBoolean(booleanField, checkBox1.isSelected()); + sync(); + + }); + newComponent = checkBox; + } + } + if (newComponent != null) { + panel.add(newComponent); + layout.putConstraint(SpringLayout.NORTH, newComponent, INSET, (last == panel) ? SpringLayout.NORTH + : SpringLayout.SOUTH, last); + layout.putConstraint(SpringLayout.WEST, newComponent, INSET, SpringLayout.EAST, + fieldToLabelMap.get(fieldWithWidestLabel)); + layout.putConstraint(SpringLayout.EAST, newComponent, INSET, SpringLayout.EAST, panel); + } + last = newComponent; + } - } + layout.layoutContainer(panel); - public abstract void sync(); + } - public Component getPanel() { - return (panel); - } - } + protected abstract void sync(); - public static final int VMARGIN = 2; + Component getPanel() { + return (panel); + } + } - public static final int HMARGIN = 2; + private static final int VMARGIN = 2; - public static final int HGAPROOT = 100; + private static final int HMARGIN = 2; - public static final int HGAP = 40; + public static final int HGAPROOT = 100; - public static final int VGAP = 20; + private static final int HGAP = 40; - public static final int ARROWGAP = 5; + private static final int VGAP = 20; - public static final int EDGEGAP = 20; + private static final int ARROWGAP = 5; - public static final int CURVEBOW = 20; + private static final int EDGEGAP = 20; - public static class Options implements Template{ + private static final int CURVEBOW = 20; - @Toggle(label = "Fold", on = "On", off = "Off") public boolean fold = true; + public static class Options implements Template { - @Check(label = "Fan Edges") public boolean edgeFan = true; + @Toggle(label = "Fold", on = "On", off = "Off") + final boolean fold = true; - @Check(label = "Curves") public boolean edgeCurve = false; + @Check(label = "Fan Edges") + final boolean edgeFan = true; - @Check(label = "PC") public boolean showPc = true; + @Check(label = "Curves") + final boolean edgeCurve = false; - @Check(label = "Bytecode Labels") public boolean verboseBytecodeLabels = false; + @Check(label = "PC") + final boolean showPc = true; - @Check(label = "Collapse All") public boolean collapseAll = false; + @Check(label = "Bytecode Labels") + final boolean verboseBytecodeLabels = false; - /* @Check(label = "Show expressions")*/public boolean showExpressions = false; + @Check(label = "Collapse All") + final boolean collapseAll = false; - } + /* @Check(label = "Show expressions")*/ final boolean showExpressions = false; - private static class XY{ - public XY(double _x, double _y) { - x = _x; - y = _y; - } + } - double x, y; - } + private static class XY { + XY(double _x, double _y) { + x = _x; + y = _y; + } - private static class View{ - AffineTransform offGraphicsTransform = new AffineTransform(); + final double x; + final double y; + } - private double scale = 1; + private static class View { + AffineTransform offGraphicsTransform = new AffineTransform(); - private double x; + private double scale = 1; - private double y; + private double x; - public double translatex(int _screenx) { - return ((_screenx - offGraphicsTransform.getTranslateX()) / offGraphicsTransform.getScaleX()); + private double y; - } + double translatex(int _screenx) { + return ((_screenx - offGraphicsTransform.getTranslateX()) / offGraphicsTransform.getScaleX()); - public double screenx() { - return ((offGraphicsTransform.getScaleX() * x) + offGraphicsTransform.getTranslateX()); - } + } - public double translatey(int _screeny) { - return ((_screeny - offGraphicsTransform.getTranslateY()) / offGraphicsTransform.getScaleY()); - } + double screenx() { + return ((offGraphicsTransform.getScaleX() * x) + offGraphicsTransform.getTranslateX()); + } - public double screeny() { - return ((offGraphicsTransform.getScaleY() * y) + offGraphicsTransform.getTranslateY()); - } - } + double translatey(int _screeny) { + return ((_screeny - offGraphicsTransform.getTranslateY()) / offGraphicsTransform.getScaleY()); + } - private final JPanel container; + double screeny() { + return ((offGraphicsTransform.getScaleY() * y) + offGraphicsTransform.getTranslateY()); + } + } - private BufferedImage offscreen; + private final JPanel container; - private Dimension offscreensize; + private BufferedImage offscreen; - private Graphics2D offgraphics; + private Dimension offscreensize; - public void dirty() { - dirty = true; + private Graphics2D offgraphics; - container.repaint(); - } + private void dirty() { + dirty = true; - private boolean dirty = false; + container.repaint(); + } - private final View view = new View(); + volatile private boolean dirty = false; - private XY dragStart = null; + private final View view = new View(); - public synchronized void draw(Graphics _g) { + private XY dragStart = null; - final Dimension containerSize = container.getSize(); - if (dirty || (offscreen == null) || (containerSize.width != offscreensize.width) + private synchronized void draw(Graphics _g) { + + final Dimension containerSize = container.getSize(); + if (dirty || (offscreen == null) || (containerSize.width != offscreensize.width) || (containerSize.height != offscreensize.height)) { - offscreensize = new Dimension(containerSize.width, containerSize.height); - offscreen = (BufferedImage) container.createImage(offscreensize.width, offscreensize.height); - - if (offgraphics != null) { - offgraphics.dispose(); - } - offgraphics = offscreen.createGraphics(); - - offgraphics.setFont(container.getFont()); - offgraphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); - offgraphics.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); - offgraphics.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); - // offgraphics.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE); - offgraphics.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON); - final AffineTransform offGraphicsTransform = new AffineTransform(); - offgraphics.setTransform(offGraphicsTransform); - offgraphics.setColor(container.getBackground()); - offgraphics.fillRect(0, 0, (offscreensize.width), (offscreensize.height)); - offGraphicsTransform.setToTranslation(view.screenx(), view.screeny()); - offGraphicsTransform.scale(view.scale, view.scale); - offgraphics.setTransform(offGraphicsTransform); - view.offGraphicsTransform = offGraphicsTransform; - dirty = false; - - } else { - offgraphics.setColor(container.getBackground()); - offgraphics.fillRect(0, 0, (offscreensize.width), (offscreensize.height)); - } - render(offgraphics); - _g.drawImage(offscreen, 0, 0, null); - - } - - public Component getContainer() { - return (container); - } - - public void text(Graphics2D _g, String _text, double _x, double _y) { - final FontMetrics fm = _g.getFontMetrics(); - _g.drawString(_text, (int) _x, (int) ((_y - fm.getAscent()) + fm.getHeight())); - - } + offscreensize = new Dimension(containerSize.width, containerSize.height); + offscreen = (BufferedImage) container.createImage(offscreensize.width, offscreensize.height); + + if (offgraphics != null) { + offgraphics.dispose(); + } + offgraphics = offscreen.createGraphics(); + + offgraphics.setFont(container.getFont()); + offgraphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); + offgraphics.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); + offgraphics.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); + // offgraphics.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE); + offgraphics.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON); + final AffineTransform offGraphicsTransform = new AffineTransform(); + offgraphics.setTransform(offGraphicsTransform); + offgraphics.setColor(container.getBackground()); + offgraphics.fillRect(0, 0, (offscreensize.width), (offscreensize.height)); + offGraphicsTransform.setToTranslation(view.screenx(), view.screeny()); + offGraphicsTransform.scale(view.scale, view.scale); + offgraphics.setTransform(offGraphicsTransform); + view.offGraphicsTransform = offGraphicsTransform; + dirty = false; + + } else { + offgraphics.setColor(container.getBackground()); + offgraphics.fillRect(0, 0, (offscreensize.width), (offscreensize.height)); + } + render(offgraphics); + _g.drawImage(offscreen, 0, 0, null); + + } + + private Component getContainer() { + return (container); + } + + private static void text(Graphics2D _g, String _text, double _x, double _y) { + final FontMetrics fm = _g.getFontMetrics(); + _g.drawString(_text, (int) _x, (int) ((_y - fm.getAscent()) + fm.getHeight())); - public void text(Graphics2D _g, Color _color, String _text, double _x, double _y) { - final Color color = _g.getColor(); - _g.setColor(_color); - text(_g, _text, _x, _y); - _g.setColor(color); + } - } + public static void text(Graphics2D _g, Color _color, String _text, double _x, double _y) { + final Color color = _g.getColor(); + _g.setColor(_color); + text(_g, _text, _x, _y); + _g.setColor(color); - public void line(Graphics2D _g, Stroke _stroke, double _x1, double _y1, double _x2, double _y2) { - final Stroke stroke = _g.getStroke(); - _g.setStroke(_stroke); - line(_g, _x1, _y1, _x2, _y2); - _g.setStroke(stroke); - } + } - public void stroke(Graphics2D _g, Stroke _stroke, Shape _rect) { - final Stroke stroke = _g.getStroke(); - _g.setStroke(_stroke); - draw(_g, _rect); - _g.setStroke(stroke); - } + private static void line(Graphics2D _g, Stroke _stroke, double _x1, double _y1, double _x2, double _y2) { + final Stroke stroke = _g.getStroke(); + _g.setStroke(_stroke); + line(_g, _x1, _y1, _x2, _y2); + _g.setStroke(stroke); + } - public void fill(Graphics2D _g, Color _color, Shape _rect) { - final Color color = _g.getColor(); - _g.setColor(_color); - fill(_g, _rect); - _g.setColor(color); - } + private static void stroke(Graphics2D _g, Stroke _stroke, Shape _rect) { + final Stroke stroke = _g.getStroke(); + _g.setStroke(_stroke); + draw(_g, _rect); + _g.setStroke(stroke); + } - public void fillStroke(Graphics2D _g, Color _fillColor, Color _strokeColor, Stroke _stroke, Shape _rect) { - final Color color = _g.getColor(); - _g.setColor(_fillColor); - fill(_g, _rect); - _g.setColor(_strokeColor); - stroke(_g, _stroke, _rect); - _g.setColor(color); - } + public static void fill(Graphics2D _g, Color _color, Shape _rect) { + final Color color = _g.getColor(); + _g.setColor(_color); + fill(_g, _rect); + _g.setColor(color); + } - public void line(Graphics2D _g, double _x1, double _y1, double _x2, double _y2) { - _g.drawLine((int) _x1, (int) _y1, (int) _x2, (int) _y2); - } + public static void fillStroke(Graphics2D _g, Color _fillColor, Color _strokeColor, Stroke _stroke, Shape _rect) { + final Color color = _g.getColor(); + _g.setColor(_fillColor); + fill(_g, _rect); + _g.setColor(_strokeColor); + stroke(_g, _stroke, _rect); + _g.setColor(color); + } - public void draw(Graphics2D _g, Shape _rectangle) { - _g.draw(_rectangle); - } + private static void line(Graphics2D _g, double _x1, double _y1, double _x2, double _y2) { + _g.drawLine((int) _x1, (int) _y1, (int) _x2, (int) _y2); + } - public void fill(Graphics2D _g, Shape _rectangle) { - _g.fill(_rectangle); - } + private static void draw(Graphics2D _g, Shape _rectangle) { + _g.draw(_rectangle); + } - public Options config = new Options(); + private static void fill(Graphics2D _g, Shape _rectangle) { + _g.fill(_rectangle); + } - final private Color unselectedColor = Color.WHITE; + private final Options config = new Options(); - final private Color selectedColor = Color.gray.brighter(); + final private Color unselectedColor = Color.WHITE; - private final Stroke thickStroke = new BasicStroke((float) 2.0); + final private Color selectedColor = Color.gray.brighter(); - private final Stroke thinStroke = new BasicStroke((float) 1.0); + private final Stroke thickStroke = new BasicStroke((float) 2.0); - private final Stroke outlineStroke = new BasicStroke((float) 0.5); + private final Stroke thinStroke = new BasicStroke((float) 1.0); - public Polygon arrowHeadOut = new Polygon(); - { - arrowHeadOut.addPoint(8, -4); - arrowHeadOut.addPoint(0, 0); - arrowHeadOut.addPoint(8, 4); - arrowHeadOut.addPoint(8, -4); - } + private final Stroke outlineStroke = new BasicStroke((float) 0.5); - Polygon arrowHeadIn = new Polygon(); - { - arrowHeadIn.addPoint(0, -4); - arrowHeadIn.addPoint(8, 0); - arrowHeadIn.addPoint(0, 4); - arrowHeadIn.addPoint(0, -4); - } + private final Polygon arrowHeadOut = new Polygon(); - public class InstructionView{ + { + arrowHeadOut.addPoint(8, -4); + arrowHeadOut.addPoint(0, 0); + arrowHeadOut.addPoint(8, 4); + arrowHeadOut.addPoint(8, -4); + } - private final Instruction instruction; + private final Polygon arrowHeadIn = new Polygon(); - private Shape shape; + { + arrowHeadIn.addPoint(0, -4); + arrowHeadIn.addPoint(8, 0); + arrowHeadIn.addPoint(0, 4); + arrowHeadIn.addPoint(0, -4); + } - public Instruction branchTarget; + static class InstructionView { - public Instruction collapsedBranchTarget; + private final Instruction instruction; - public String label; + private Shape shape; - public boolean dim; + public Instruction branchTarget; - public InstructionView(Instruction _instruction) { - instruction = _instruction; - } + public Instruction collapsedBranchTarget; - } + String label; - private final Map locationToInstructionViewMap = new HashMap(); + boolean dim; - InstructionView getInstructionView(Instruction _instruction) { + InstructionView(Instruction _instruction) { + instruction = _instruction; + } - InstructionView instructionView = locationToInstructionViewMap.get(_instruction); - if (instructionView == null) { - locationToInstructionViewMap.put(_instruction, instructionView = new InstructionView(_instruction)); + } - } - return (instructionView); - } + private final Map locationToInstructionViewMap = new HashMap<>(); - double foldPlace(Graphics2D _g, InstructionView _instructionView, double _x, double _y, boolean _dim) { - _instructionView.dim = _dim; - final FontMetrics fm = _g.getFontMetrics(); + private InstructionView getInstructionView(Instruction _instruction) { - _instructionView.label = InstructionHelper.getLabel(_instructionView.instruction, config.showPc, config.showExpressions, + InstructionView instructionView = locationToInstructionViewMap.computeIfAbsent(_instruction, InstructionView::new); + return (instructionView); + } + + private double foldPlace(Graphics2D _g, InstructionView _instructionView, double _x, double _y, boolean _dim) { + _instructionView.dim = _dim; + final FontMetrics fm = _g.getFontMetrics(); + + _instructionView.label = InstructionHelper.getLabel(_instructionView.instruction, config.showPc, config.showExpressions, config.verboseBytecodeLabels); - final int w = fm.stringWidth(_instructionView.label) + HMARGIN; - final int h = fm.getHeight() + VMARGIN; + final int w = fm.stringWidth(_instructionView.label) + HMARGIN; + final int h = fm.getHeight() + VMARGIN; - double y = _y; - final double x = _x + w + (_instructionView.instruction.getRootExpr() == _instructionView.instruction ? HGAP : HGAP); + double y = _y; + final double x = _x + w + (_instructionView.instruction.getRootExpr() == _instructionView.instruction ? HGAP : HGAP); - if (!config.collapseAll && !config.showExpressions) { + if (!config.collapseAll && !config.showExpressions) { - for (Instruction e = _instructionView.instruction.getFirstChild(); e != null; e = e.getNextExpr()) { + for (Instruction e = _instructionView.instruction.getFirstChild(); e != null; e = e.getNextExpr()) { - y = foldPlace(_g, getInstructionView(e), x, y, _dim); - if (e != _instructionView.instruction.getLastChild()) { - y += VGAP; + y = foldPlace(_g, getInstructionView(e), x, y, _dim); + if (e != _instructionView.instruction.getLastChild()) { + y += VGAP; + } } - } - - } - final double top = ((y + _y) / 2) - (h / 2); - _instructionView.shape = new Rectangle((int) _x, (int) top, w, h); - return (Math.max(_y, y)); - - } - - void foldRender(Graphics2D _g, InstructionView _instructionView) { - final Instruction instruction = _instructionView.instruction; - if (!config.collapseAll && !config.showExpressions) { - for (Instruction e = instruction.getFirstChild(); e != null; e = e.getNextExpr()) { - - foldRender(_g, getInstructionView(e)); - - } - } - if (_instructionView.dim) { - _g.setColor(unselectedColor); - } else { - _g.setColor(selectedColor); - } - _g.fill(_instructionView.shape); - _g.setColor(Color.black); - _g.setStroke(outlineStroke); - _g.draw(_instructionView.shape); - text(_g, _instructionView.label, _instructionView.shape.getBounds().getCenterX() - - (_instructionView.shape.getBounds().getWidth() / 2), _instructionView.shape.getBounds().getCenterY()); - if (!config.collapseAll && !config.showExpressions) { + } + final double top = ((y + _y) / 2.0) - (h / 2.0); + _instructionView.shape = new Rectangle((int) _x, (int) top, w, h); + return (Math.max(_y, y)); - if (config.edgeFan) { + } + private void foldRender(Graphics2D _g, InstructionView _instructionView) { + final Instruction instruction = _instructionView.instruction; + if (!config.collapseAll && !config.showExpressions) { for (Instruction e = instruction.getFirstChild(); e != null; e = e.getNextExpr()) { - final InstructionView iv = getInstructionView(e); - final double x1 = _instructionView.shape.getBounds().getMaxX() + ARROWGAP; - - final double y1 = _instructionView.shape.getBounds().getCenterY(); - final double x2 = iv.shape.getBounds().getMinX() - 5; - final double y2 = iv.shape.getBounds().getCenterY(); - - if (config.edgeCurve) { - _g.draw(new CubicCurve2D.Double(x1, y1, x1 + CURVEBOW, y1, x2 - CURVEBOW, y2, x2, y2)); - } else { - final double dx = (x1 - x2); - final double dy = (y1 - y2); - - final AffineTransform transform = _g.getTransform(); - final double hypot = Math.hypot(dy, dx); - final double angle = Math.atan2(dy, dx); - _g.translate(x2, y2); - _g.rotate(angle); - line(_g, thickStroke, 0, 0, hypot, 0); - _g.fillPolygon(arrowHeadOut); - _g.setTransform(transform); - } - } - } else { - - _g.setStroke(thickStroke); - if ((instruction.getFirstChild() != null) && (instruction.getFirstChild() != instruction.getLastChild())) { // >1 children - final InstructionView iv0 = getInstructionView(instruction.getFirstChild()); - final InstructionView ivn = getInstructionView(instruction.getLastChild()); - - final double midx = (_instructionView.shape.getBounds().getMaxX() + iv0.shape.getBounds().getMinX()) / 2; - line(_g, midx, iv0.shape.getBounds().getCenterY(), midx, ivn.shape.getBounds().getCenterY()); - line(_g, _instructionView.shape.getBounds().getMaxX() + ARROWGAP, _instructionView.shape.getBounds().getCenterY(), - midx, _instructionView.shape.getBounds().getCenterY()); - - for (Instruction e = instruction.getFirstChild(); e != null; e = e.getNextExpr()) { - final InstructionView iv = getInstructionView(e); - line(_g, midx, iv.shape.getBounds().getCenterY(), iv.shape.getBounds().getMinX() - ARROWGAP, iv.shape.getBounds() - .getCenterY()); - } - } else if (instruction.getFirstChild() != null) { // 1 child - final InstructionView iv = getInstructionView(instruction.getFirstChild()); - line(_g, _instructionView.shape.getBounds().getMaxX() + ARROWGAP, _instructionView.shape.getBounds().getCenterY(), - iv.shape.getBounds().getMinX() - ARROWGAP, iv.shape.getBounds().getCenterY()); + foldRender(_g, getInstructionView(e)); + } - } - } + } +// if (_instructionView.dim) { +// _g.setColor(unselectedColor); +// } else { +// _g.setColor(selectedColor); +// } + _g.setColor(hashColor(_instructionView.instruction.getByteCode().ordinal())); + _g.fill(_instructionView.shape); + _g.setColor(Color.white); + _g.setStroke(outlineStroke); + _g.draw(_instructionView.shape); + text(_g, _instructionView.label, _instructionView.shape.getBounds().getCenterX() + - (_instructionView.shape.getBounds().getWidth() / 2), _instructionView.shape.getBounds().getCenterY()); - } + if (!config.collapseAll && !config.showExpressions) { - double flatPlace(Graphics2D _g, InstructionView _instructionView, double _x, double _y) { - final FontMetrics fm = _g.getFontMetrics(); - final Instruction instruction = _instructionView.instruction; - _instructionView.label = InstructionHelper.getLabel(instruction, config.showPc, config.showExpressions, - config.verboseBytecodeLabels); + if (config.edgeFan) { - final int h = fm.getHeight() + 2; - final double top = (_y / 2) - (h / 2); - _instructionView.shape = new Rectangle((int) _x, (int) top, fm.stringWidth(_instructionView.label) + 2, h); - return (_y + h); - } - - void flatRender(Graphics2D _g, InstructionView _instructionView) { - _g.setColor(unselectedColor); - _g.fill(_instructionView.shape); - _g.setColor(Color.black); - stroke(_g, outlineStroke, _instructionView.shape); - text(_g, _instructionView.label, _instructionView.shape.getBounds().getCenterX() - - (_instructionView.shape.getBounds().getWidth() / 2), _instructionView.shape.getBounds().getCenterY()); - } - - ClassModel classModel = null; - - public InstructionViewer(Color _background, String _name) { - - try { - classModel = ClassModel.createClassModel(Class.forName(_name)); - } catch (final ClassParseException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (final ClassNotFoundException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - container = new JPanel(){ - /** - * - */ - private static final long serialVersionUID = 1L; - - @Override public void paintComponent(Graphics g) { - draw(g); - } - }; - container.setBackground(_background); - - final MouseAdapter mouseAdaptor = new MouseAdapter(){ - @Override public void mouseEntered(MouseEvent e) { - container.requestFocusInWindow(); - } - - @Override public void mouseDragged(MouseEvent e) { - // System.out.println("dragged"); - if (dragStart != null) { - view.x = view.translatex(e.getX()) - dragStart.x; - view.y = view.translatey(e.getY()) - dragStart.y; - dirty(); - } + for (Instruction e = instruction.getFirstChild(); e != null; e = e.getNextExpr()) { + final InstructionView iv = getInstructionView(e); + final double x1 = _instructionView.shape.getBounds().getMaxX() + ARROWGAP; - } + final double y1 = _instructionView.shape.getBounds().getCenterY(); + final double x2 = iv.shape.getBounds().getMinX() - 5; + final double y2 = iv.shape.getBounds().getCenterY(); - @Override public void mousePressed(MouseEvent e) { + if (config.edgeCurve) { + _g.draw(new CubicCurve2D.Double(x1, y1, x1 + CURVEBOW, y1, x2 - CURVEBOW, y2, x2, y2)); + } else { + final double dx = (x1 - x2); + final double dy = (y1 - y2); - if (e.getButton() == 1) { - dragStart = new XY(view.translatex(e.getX()), view.translatey(e.getY())); - dirty(); + final AffineTransform transform = _g.getTransform(); + final double hypot = Math.hypot(dy, dx); + final double angle = Math.atan2(dy, dx); + _g.translate(x2, y2); + _g.rotate(angle); + line(_g, thickStroke, 0, 0, hypot, 0); + _g.fillPolygon(arrowHeadOut); + _g.setTransform(transform); + } + } - } else if (e.getButton() == 3) { + } else { - if (select(view.translatex(e.getX()), view.translatey(e.getY()))) { - dirty(); - } + _g.setStroke(thickStroke); + if ((instruction.getFirstChild() != null) && (instruction.getFirstChild() != instruction.getLastChild())) { // >1 children + final InstructionView iv0 = getInstructionView(instruction.getFirstChild()); + final InstructionView ivn = getInstructionView(instruction.getLastChild()); + + final double midx = (_instructionView.shape.getBounds().getMaxX() + iv0.shape.getBounds().getMinX()) / 2; + line(_g, midx, iv0.shape.getBounds().getCenterY(), midx, ivn.shape.getBounds().getCenterY()); + line(_g, _instructionView.shape.getBounds().getMaxX() + ARROWGAP, _instructionView.shape.getBounds().getCenterY(), + midx, _instructionView.shape.getBounds().getCenterY()); + + for (Instruction e = instruction.getFirstChild(); e != null; e = e.getNextExpr()) { + final InstructionView iv = getInstructionView(e); + line(_g, midx, iv.shape.getBounds().getCenterY(), iv.shape.getBounds().getMinX() - ARROWGAP, iv.shape.getBounds() + .getCenterY()); + } + } else if (instruction.getFirstChild() != null) { // 1 child + final InstructionView iv = getInstructionView(instruction.getFirstChild()); + line(_g, _instructionView.shape.getBounds().getMaxX() + ARROWGAP, _instructionView.shape.getBounds().getCenterY(), + iv.shape.getBounds().getMinX() - ARROWGAP, iv.shape.getBounds().getCenterY()); + } } + } - } - - @Override public void mouseReleased(MouseEvent e) { - dragStart = null; - // container.repaint(); - } - - @Override public void mouseWheelMoved(MouseWheelEvent e) { - view.scale += e.getWheelRotation() / 10.0; - dirty(); - } - - }; - - final KeyAdapter keyAdaptor = new KeyAdapter(){ - @Override public void keyTyped(KeyEvent arg0) { - if ((arg0.getKeyChar() == '-') || (arg0.getKeyChar() == '+')) { - if (arg0.getKeyChar() == '-') { - view.scale -= .1; - } else { - view.scale += .1; - } - dirty(); + } + + private double flatPlace(Graphics2D _g, InstructionView _instructionView, double _x, double _y) { + final FontMetrics fm = _g.getFontMetrics(); + final Instruction instruction = _instructionView.instruction; + _instructionView.label = InstructionHelper.getLabel(instruction, config.showPc, config.showExpressions, + config.verboseBytecodeLabels); + + final int h = fm.getHeight() + 2; + final double top = (_y / 2) - (h / 2.0); + _instructionView.shape = new Rectangle((int) _x, (int) top, fm.stringWidth(_instructionView.label) + 2, h); + return (_y + h); + } + + private void flatRender(Graphics2D _g, InstructionView iv) { + //_g.setColor(unselectedColor); + _g.setColor(hashColor(iv.instruction.getByteCode().ordinal())); + _g.fill(iv.shape); + _g.setColor(Color.BLACK); + stroke(_g, outlineStroke, iv.shape); + text(_g, iv.label, iv.shape.getBounds().getCenterX() + - (iv.shape.getBounds().getWidth() / 2), iv.shape.getBounds().getCenterY()); + } + + private ClassModel classModel = null; + + public InstructionViewer(Color _background, String _name) { + + try { + classModel = ClassModel.createClassModel(_name != null ? Class.forName(_name) : ABCCKernel.class); + } catch (final ClassParseException | ClassNotFoundException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + container = new JPanel() { + /** + * + */ + private static final long serialVersionUID = 1L; + + @Override + public void paintComponent(Graphics g) { + draw(g); } + }; + container.setBackground(_background); - } - - }; - container.addMouseMotionListener(mouseAdaptor); - container.addMouseListener(mouseAdaptor); - container.addMouseWheelListener(mouseAdaptor); - container.addKeyListener(keyAdaptor); - container.repaint(); - - } - - public InstructionViewer() { - - final JFrame frame = new JFrame(); - - final Color background = Color.WHITE; - final JPanel panel = new JPanel(new BorderLayout()); - final JMenuBar menuBar = new JMenuBar(); - - final JMenu fileMenu = new JMenu("File"); - fileMenu.setMnemonic(KeyEvent.VK_F); - final ActionListener closeActionListener = new ActionListener(){ - @Override public void actionPerformed(ActionEvent arg0) { - System.exit(1); - } - - }; - final ActionListener nextActionListener = new ActionListener(){ - @Override public void actionPerformed(ActionEvent arg0) { - doorbell.ring(); - - } - - }; - final JMenuItem closeMenuItem = new JMenuItem("Close"); - closeMenuItem.setMnemonic(KeyEvent.VK_C); - closeMenuItem.addActionListener(closeActionListener); - fileMenu.add(closeMenuItem); - menuBar.add(fileMenu); - menuBar.setEnabled(true); - frame.setJMenuBar(menuBar); - - // http://java.sun.com/docs/books/tutorial/uiswing/components/toolbar.html - final JToolBar toolBar = new JToolBar(); - final JButton closeButton = new JButton("Close"); - closeButton.addActionListener(closeActionListener); - toolBar.add(closeButton); - - final JButton nextButton = new JButton("Next"); - nextButton.addActionListener(nextActionListener); - toolBar.add(nextButton); - - panel.add(BorderLayout.PAGE_START, toolBar); - - container = new JPanel(){ - /** - * - */ - private static final long serialVersionUID = 1L; - - @Override public void paintComponent(Graphics g) { - draw(g); - } - }; - container.setBackground(Color.WHITE); - - final MouseAdapter mouseAdaptor = new MouseAdapter(){ - @Override public void mouseEntered(MouseEvent e) { - container.requestFocusInWindow(); - } - - @Override public void mouseDragged(MouseEvent e) { - // System.out.println("dragged"); - if (dragStart != null) { - view.x = view.translatex(e.getX()) - dragStart.x; - view.y = view.translatey(e.getY()) - dragStart.y; - dirty(); + final MouseAdapter mouseAdaptor = new MouseAdapter() { + @Override + public void mouseEntered(MouseEvent e) { + container.requestFocusInWindow(); } - } + @Override + public void mouseDragged(MouseEvent e) { + // System.out.println("dragged"); + if (dragStart != null) { + view.x = view.translatex(e.getX()) - dragStart.x; + view.y = view.translatey(e.getY()) - dragStart.y; + dirty(); + } - @Override public void mousePressed(MouseEvent e) { + } - if (e.getButton() == 1) { - dragStart = new XY(view.translatex(e.getX()), view.translatey(e.getY())); - dirty(); + @Override + public void mousePressed(MouseEvent e) { - } else if (e.getButton() == 3) { + if (e.getButton() == 1) { + dragStart = new XY(view.translatex(e.getX()), view.translatey(e.getY())); + dirty(); - if (select(view.translatex(e.getX()), view.translatey(e.getY()))) { - dirty(); - } - } + } else if (e.getButton() == 3) { + + if (select(view.translatex(e.getX()), view.translatey(e.getY()))) { + dirty(); + } + } - } - - @Override public void mouseReleased(MouseEvent e) { - dragStart = null; - // container.repaint(); - } - - @Override public void mouseWheelMoved(MouseWheelEvent e) { - view.scale += e.getWheelRotation() / 10.0; - dirty(); - } - - }; - - final KeyAdapter keyAdaptor = new KeyAdapter(){ - @Override public void keyTyped(KeyEvent arg0) { - if ((arg0.getKeyChar() == '-') || (arg0.getKeyChar() == '+')) { - if (arg0.getKeyChar() == '-') { - view.scale -= .1; - } else { - view.scale += .1; - } - dirty(); } - } - - }; - container.addMouseMotionListener(mouseAdaptor); - container.addMouseListener(mouseAdaptor); - container.addMouseWheelListener(mouseAdaptor); - container.addKeyListener(keyAdaptor); - container.repaint(); - - panel.add(BorderLayout.CENTER, container); - - final JPanel controls = new JPanel(new BorderLayout()); - - final Form form = new Form(config){ - @Override public void sync() { - dirty(); - } - }; - controls.add(form.getPanel()); - - controls.setPreferredSize(new Dimension(200, 500)); - panel.add(BorderLayout.EAST, controls); - frame.setBackground(background); - frame.getContentPane().add(panel); - frame.setPreferredSize(new Dimension(1024, 1000)); - frame.pack(); - frame.setVisible(true); - - } - - public boolean select(double _x, double _y) { - for (Instruction l = first; l != null; l = l.getNextPC()) { - final InstructionView iv = getInstructionView(l); - if ((iv.shape != null) && iv.shape.contains(_x, _y)) { - - return (true); - } - } - return (false); - } - - public void render(Graphics2D _g) { - if (first != null) { - - if (config.fold) { - double y = 100; - final Instruction firstRoot = first.getRootExpr(); - final List instructionViews = new ArrayList(); - - Instruction lastInstruction = null; - for (Instruction instruction = firstRoot; instruction != null; instruction = instruction.getNextExpr()) { - final InstructionView iv = getInstructionView(instruction); - iv.dim = false; - y = foldPlace(_g, iv, 100, y, false) + VGAP; - instructionViews.add(iv); - lastInstruction = instruction; + @Override + public void mouseReleased(MouseEvent e) { + dragStart = null; + // container.repaint(); } - lastInstruction.getRootExpr(); - while (lastInstruction instanceof CompositeInstruction) { - lastInstruction = lastInstruction.getLastChild(); + + @Override + public void mouseWheelMoved(MouseWheelEvent e) { + view.scale += e.getWheelRotation() / 10.0; + dirty(); } - for (Instruction instruction = lastInstruction.getNextPC(); instruction != null; instruction = instruction.getNextPC()) { - final InstructionView iv = getInstructionView(instruction); - iv.dim = true; - y = foldPlace(_g, iv, 100, y, true) + VGAP; - instructionViews.add(iv); + }; + + final KeyAdapter keyAdaptor = new KeyAdapter() { + @Override + public void keyTyped(KeyEvent arg0) { + if ((arg0.getKeyChar() == '-') || (arg0.getKeyChar() == '+')) { + if (arg0.getKeyChar() == '-') { + view.scale -= .1; + } else { + view.scale += .1; + } + dirty(); + } } - _g.setColor(Color.black); + }; + container.addMouseMotionListener(mouseAdaptor); + container.addMouseListener(mouseAdaptor); + container.addMouseWheelListener(mouseAdaptor); + container.addKeyListener(keyAdaptor); + container.repaint(); + + } + + final JFrame frame = new JFrame(); + + public InstructionViewer() { - for (final InstructionView instructionView : instructionViews) { - if (instructionView.instruction.isBranch()) { - final Instruction rootFromInstruction = instructionView.instruction; - final Instruction rootToInstruction = instructionView.instruction.asBranch().getTarget(); - final InstructionView fromIv = getInstructionView(rootFromInstruction); - final InstructionView toIv = getInstructionView(rootToInstruction); - edge(_g, Color.BLACK, fromIv, toIv, null, null); - } - } - InstructionView last = null; - for (final InstructionView instructionView : instructionViews) { + final Color background = Color.BLACK; + final JPanel panel = new JPanel(new BorderLayout()); + final JMenuBar menuBar = new JMenuBar(); - foldRender(_g, instructionView); - if (last != null) { - line(_g, thickStroke, 120, last.shape.getBounds().getMaxY(), 120, instructionView.shape.getBounds().getMinY()); - } - foldRender(_g, instructionView); - last = instructionView; + final JMenu fileMenu = new JMenu("File"); + fileMenu.setMnemonic(KeyEvent.VK_F); + final ActionListener closeActionListener = arg0 -> System.exit(1); + final ActionListener nextActionListener = arg0 -> doorbell.ring(); + final JMenuItem closeMenuItem = new JMenuItem("Close"); + closeMenuItem.setMnemonic(KeyEvent.VK_C); + closeMenuItem.addActionListener(closeActionListener); + fileMenu.add(closeMenuItem); + menuBar.add(fileMenu); + menuBar.setEnabled(true); + frame.setJMenuBar(menuBar); + + // http://java.sun.com/docs/books/tutorial/uiswing/components/toolbar.html + final JToolBar toolBar = new JToolBar(); + final JButton closeButton = new JButton("Close"); + closeButton.addActionListener(closeActionListener); + toolBar.add(closeButton); + + final JButton nextButton = new JButton("Next"); + nextButton.addActionListener(nextActionListener); + toolBar.add(nextButton); + + panel.add(BorderLayout.NORTH, toolBar); + + container = new JPanel() { + /** + * + */ + private static final long serialVersionUID = 1L; + + @Override + public void paintComponent(Graphics g) { + draw(g); } + }; + container.setBackground(Color.BLACK); - } else { - double y = 100; - for (Instruction l = first; l != null; l = l.getNextPC()) { + final MouseAdapter mouseAdaptor = new MouseAdapter() { + @Override + public void mouseEntered(MouseEvent e) { + container.requestFocusInWindow(); + } - y = flatPlace(_g, getInstructionView(l), 100, y) + VGAP; + @Override + public void mouseDragged(MouseEvent e) { + // System.out.println("dragged"); + if (dragStart != null) { + view.x = view.translatex(e.getX()) - dragStart.x; + view.y = view.translatey(e.getY()) - dragStart.y; + dirty(); + } } - _g.setColor(Color.black); - for (Instruction l = first; l != null; l = l.getNextPC()) { - if (l.isBranch()) { - final Instruction rootFromInstruction = l; - final Instruction rootToInstruction = l.asBranch().getTarget(); - final InstructionView fromIv = getInstructionView(rootFromInstruction); - final InstructionView toIv = getInstructionView(rootToInstruction); + @Override + public void mousePressed(MouseEvent e) { + + if (e.getButton() == 1) { + dragStart = new XY(view.translatex(e.getX()), view.translatey(e.getY())); + dirty(); + + } else if (e.getButton() == 3) { + + if (select(view.translatex(e.getX()), view.translatey(e.getY()))) { + dirty(); + } + } - edge(_g, Color.BLACK, fromIv, toIv, null, null); - } + } + + @Override + public void mouseReleased(MouseEvent e) { + dragStart = null; + // container.repaint(); + } + @Override + public void mouseWheelMoved(MouseWheelEvent e) { + view.scale += e.getWheelRotation() / 10.0; + dirty(); } - InstructionView last = null; - for (Instruction l = first; l != null; l = l.getNextPC()) { - final InstructionView iv = getInstructionView(l); + }; + + final KeyAdapter keyAdaptor = new KeyAdapter() { + @Override + public void keyTyped(KeyEvent arg0) { + if ((arg0.getKeyChar() == '-') || (arg0.getKeyChar() == '+')) { + if (arg0.getKeyChar() == '-') { + view.scale -= .1; + } else { + view.scale += .1; + } + dirty(); + } - if (last != null) { - line(_g, thickStroke, 120, last.shape.getBounds().getMaxY(), 120, iv.shape.getBounds().getMinY()); - } - flatRender(_g, iv); - last = iv; } - } - } - } + }; + container.addMouseMotionListener(mouseAdaptor); + container.addMouseListener(mouseAdaptor); + container.addMouseWheelListener(mouseAdaptor); + container.addKeyListener(keyAdaptor); + container.repaint(); + + panel.add(BorderLayout.CENTER, container); - public void edge(Graphics2D _g, Color _color, InstructionView _branch, InstructionView _target, String _endLabel, - String _startLabel) { + final JPanel controls = new JPanel(new BorderLayout()); - final int delta = _target.instruction.getThisPC() - _branch.instruction.getThisPC(); - final int adjust = 7 + Math.abs(delta); - final double y1 = (int) _branch.shape.getBounds().getMaxY(); - if (_target.shape != null) { - _g.setStroke(thinStroke); - final Color old = _g.getColor(); - _g.setColor(_color); - final double y2 = (int) _target.shape.getBounds().getMinY(); - if (delta > 0) { + final Form form = new Form(config) { + @Override + public void sync() { + dirty(); + } + }; + //form.panel.setOpaque(false); - final double x1 = (int) _branch.shape.getBounds().getMinX() - EDGEGAP; - final double x2 = (int) _target.shape.getBounds().getMinX() - EDGEGAP; + controls.add(form.getPanel()); + controls.setBackground(background); + form.getPanel().setBackground(background); - _g.draw(new CubicCurve2D.Double(x1, y1, x1 - adjust, y1, x1 - adjust, y2, x2, y2)); + controls.setPreferredSize(new Dimension(200, 500)); - final AffineTransform transform = _g.getTransform(); - _g.translate(x2 - 5, y2); - _g.fillPolygon(arrowHeadIn); - _g.setTransform(transform); + panel.add(BorderLayout.EAST, controls); - } else { + frame.setBackground(background); + frame.getContentPane().setBackground(background); + frame.getContentPane().add(panel); + frame.setPreferredSize(new Dimension(1024, 1000)); + frame.pack(); + frame.setVisible(true); - final double x1 = (int) _branch.shape.getBounds().getMaxX() + EDGEGAP; - final double x2 = (int) _target.shape.getBounds().getMaxX() + EDGEGAP; + } - _g.draw(new CubicCurve2D.Double(x1, y1, Math.max(x1, x2) + adjust, y1, Math.max(x1, x2) + adjust, y2, x2, y2)); - final AffineTransform transform = _g.getTransform(); + private boolean select(double _x, double _y) { + for (Instruction l = first; l != null; l = l.getNextPC()) { + final InstructionView iv = getInstructionView(l); + if ((iv.shape != null) && iv.shape.contains(_x, _y)) { - _g.translate(x2 - 5, y2); - _g.fillPolygon(arrowHeadOut); - _g.setTransform(transform); + return (true); + } + } + return (false); + } + + private void render(Graphics2D _g) { + if (first != null) { + + if (config.fold) { + double y = 100; + final Instruction firstRoot = first.getRootExpr(); + final List instructionViews = new ArrayList<>(); + + Instruction lastInstruction = null; + for (Instruction instruction = firstRoot; instruction != null; instruction = instruction.getNextExpr()) { + final InstructionView iv = getInstructionView(instruction); + iv.dim = false; + y = foldPlace(_g, iv, 100, y, false) + VGAP; + instructionViews.add(iv); + lastInstruction = instruction; + } + lastInstruction.getRootExpr(); + while (lastInstruction instanceof CompositeInstruction) { + lastInstruction = lastInstruction.getLastChild(); + } + for (Instruction instruction = lastInstruction.getNextPC(); instruction != null; instruction = instruction.getNextPC()) { + + final InstructionView iv = getInstructionView(instruction); + iv.dim = true; + y = foldPlace(_g, iv, 100, y, true) + VGAP; + instructionViews.add(iv); + + } + + _g.setColor(Color.black); + + for (final InstructionView instructionView : instructionViews) { + if (instructionView.instruction.isBranch()) { + final Instruction rootFromInstruction = instructionView.instruction; + final Instruction rootToInstruction = instructionView.instruction.asBranch().getTarget(); + final InstructionView fromIv = getInstructionView(rootFromInstruction); + final InstructionView toIv = getInstructionView(rootToInstruction); + edge(_g, hashColor(instructionView.instruction.getByteCode().ordinal()), fromIv, toIv, null, null); + } + } + + InstructionView last = null; + + for (final InstructionView instructionView : instructionViews) { + + foldRender(_g, instructionView); + if (last != null) { + line(_g, thickStroke, 120, last.shape.getBounds().getMaxY(), 120, instructionView.shape.getBounds().getMinY()); + } + foldRender(_g, instructionView); + last = instructionView; + } - } - _g.setColor(old); - } - } + } else { + double y = 100; + for (Instruction l = first; l != null; l = l.getNextPC()) { - volatile Instruction first = null; + y = flatPlace(_g, getInstructionView(l), 100, y) + VGAP; - volatile Instruction current = null; + } - @Override public void showAndTell(String message, Instruction head, Instruction _instruction) { + _g.setColor(Color.black); + for (Instruction l = first; l != null; l = l.getNextPC()) { + if (l.isBranch()) { + final Instruction rootFromInstruction = l; + final Instruction rootToInstruction = l.asBranch().getTarget(); + final InstructionView fromIv = getInstructionView(rootFromInstruction); + final InstructionView toIv = getInstructionView(rootToInstruction); - if (first == null) { - first = head; - } - current = _instruction; - dirty(); - doorbell.snooze(); + edge(_g, hashColor(l.getByteCode().ordinal()), fromIv, toIv, null, null); + } - } + } - public static class DoorBell{ - volatile boolean notified = false; + InstructionView last = null; + for (Instruction l = first; l != null; l = l.getNextPC()) { + final InstructionView iv = getInstructionView(l); - public synchronized void snooze() { - while (!notified) { - try { - this.wait(); - } catch (final InterruptedException e) { - // TODO Auto-generated catch block - e.printStackTrace(); + if (last != null) { + line(_g, thickStroke, 120, last.shape.getBounds().getMaxY(), 120, iv.shape.getBounds().getMinY()); + } + flatRender(_g, iv); + last = iv; + } } - } - notified = false; - } + } - public synchronized void ring() { - notified = true; - notify(); - } + } - } + static Color hashColor(int h) { + return Color.getHSBColor(h/10f, 0.5f, 0.5f); + } - public static DoorBell doorbell = new DoorBell(); + private void edge(Graphics2D G, Color _color, InstructionView _branch, InstructionView _target, String _endLabel, + String _startLabel) { - public static void main(String[] _args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, - UnsupportedLookAndFeelException, AparapiException { + final int delta = _target.instruction.getThisPC() - _branch.instruction.getThisPC(); + final int adjust = 7 + Math.abs(delta); + final double y1 = (int) _branch.shape.getBounds().getMaxY(); + if (_target.shape != null) { + G.setStroke(thinStroke); + final Color old = G.getColor(); + G.setColor(_color); + final double y2 = (int) _target.shape.getBounds().getMinY(); + if (delta > 0) { - UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); + final double x1 = (int) _branch.shape.getBounds().getMinX() - EDGEGAP; + final double x2 = (int) _target.shape.getBounds().getMinX() - EDGEGAP; - final JFrame frame = new JFrame(); - frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + G.draw(new CubicCurve2D.Double(x1, y1, x1 - adjust, y1, x1 - adjust, y2, x2, y2)); - final Color background = Color.WHITE; - final JPanel panel = new JPanel(new BorderLayout()); - final JMenuBar menuBar = new JMenuBar(); + final AffineTransform transform = G.getTransform(); + G.translate(x2 - 5, y2); + G.fillPolygon(arrowHeadIn); + char[] lbl = _startLabel.toCharArray(); + G.drawChars(lbl, 0, lbl.length, 0, 0); + G.setTransform(transform); - final JMenu fileMenu = new JMenu("File"); - fileMenu.setMnemonic(KeyEvent.VK_F); - final ActionListener closeActionListener = new ActionListener(){ - @Override public void actionPerformed(ActionEvent arg0) { - System.exit(1); - } + } else { - }; - final ActionListener nextActionListener = new ActionListener(){ - @Override public void actionPerformed(ActionEvent arg0) { - doorbell.ring(); + final double x1 = (int) _branch.shape.getBounds().getMaxX() + EDGEGAP; + final double x2 = (int) _target.shape.getBounds().getMaxX() + EDGEGAP; - } + G.draw(new CubicCurve2D.Double(x1, y1, Math.max(x1, x2) + adjust, y1, Math.max(x1, x2) + adjust, y2, x2, y2)); + final AffineTransform transform = G.getTransform(); - }; - final JMenuItem closeMenuItem = new JMenuItem("Close"); - closeMenuItem.setMnemonic(KeyEvent.VK_C); - closeMenuItem.addActionListener(closeActionListener); - fileMenu.add(closeMenuItem); - menuBar.add(fileMenu); - menuBar.setEnabled(true); - frame.setJMenuBar(menuBar); + G.translate(x2 - 5, y2); + G.fillPolygon(arrowHeadOut); + G.setTransform(transform); - final InstructionViewer instructionViewer = new InstructionViewer(background, _args[0]); + } + G.setColor(old); + } + } + + private volatile Instruction first = null; - Config.instructionListener = instructionViewer; - // http://java.sun.com/docs/books/tutorial/uiswing/components/toolbar.html - final JToolBar toolBar = new JToolBar(); - final JButton closeButton = new JButton("Close"); - closeButton.addActionListener(closeActionListener); - toolBar.add(closeButton); + private volatile Instruction current = null; - final JButton nextButton = new JButton("Next"); - nextButton.addActionListener(nextActionListener); - toolBar.add(nextButton); + @Override + public void showAndTell(String message, Instruction head, Instruction _instruction) { - panel.add(BorderLayout.PAGE_START, toolBar); + if (first == null) { + first = head; + } + current = _instruction; + dirty(); + doorbell.snooze(); - panel.add(BorderLayout.CENTER, instructionViewer.getContainer()); + } - final JPanel controls = new JPanel(new BorderLayout()); + static class DoorBell { + private volatile boolean notified = false; - final Form form = new Form(instructionViewer.config){ - @Override public void sync() { - instructionViewer.dirty(); - } - }; - controls.add(form.getPanel()); + synchronized void snooze() { + while (!notified) { + try { + this.wait(); + } catch (final InterruptedException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + notified = false; + } + + synchronized void ring() { + notified = true; + notify(); + } + + } + + private static final DoorBell doorbell = new DoorBell(); + + public static void main(String[] _args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, + UnsupportedLookAndFeelException { + + UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); + + final JFrame frame = new JFrame(); + frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); + + final Color background = Color.BLACK; + final JPanel panel = new JPanel(new BorderLayout()); + final JMenuBar menuBar = new JMenuBar(); + + final JMenu fileMenu = new JMenu("File"); + fileMenu.setMnemonic(KeyEvent.VK_F); + final ActionListener closeActionListener = arg0 -> System.exit(1); + final ActionListener nextActionListener = arg0 -> doorbell.ring(); + final JMenuItem closeMenuItem = new JMenuItem("Close"); + closeMenuItem.setMnemonic(KeyEvent.VK_C); + closeMenuItem.addActionListener(closeActionListener); + fileMenu.add(closeMenuItem); + menuBar.add(fileMenu); + menuBar.setEnabled(true); + frame.setJMenuBar(menuBar); + + final InstructionViewer instructionViewer = new InstructionViewer(background, _args.length > 0 ? _args[0] : null); + + Config.instructionListener = instructionViewer; + // http://java.sun.com/docs/books/tutorial/uiswing/components/toolbar.html + final JToolBar toolBar = new JToolBar(); +// final JButton closeButton = new JButton("Close"); +// closeButton.addActionListener(closeActionListener); +// toolBar.add(closeButton); + + final Thread[] runThread = {null}; + final JToggleButton runButton = new JToggleButton("Run"); + runButton.addActionListener((x) -> { + synchronized (instructionViewer) { + if (runButton.isSelected()) { + runThread[0] = new Thread(() -> { + while (runThread[0] != null) { + nextActionListener.actionPerformed(null); + try { + Thread.sleep(100); + } catch (InterruptedException e) { + + } + } + }); + runThread[0].start(); + } else { + runThread[0] = null; + } + } + }); + toolBar.add(runButton); - controls.setPreferredSize(new Dimension(200, 500)); - panel.add(BorderLayout.EAST, controls); - frame.setBackground(background); - frame.getContentPane().add(panel); - frame.setPreferredSize(new Dimension(800, 1000)); - frame.pack(); - frame.setVisible(true); - (new Thread(new Runnable(){ + final JButton nextButton = new JButton("Step"); + nextButton.addActionListener(nextActionListener); + toolBar.add(nextButton); - @Override public void run() { + panel.add(BorderLayout.PAGE_START, toolBar); + panel.add(BorderLayout.CENTER, instructionViewer.getContainer()); + + final JPanel controls = new JPanel(new BorderLayout()); + + final Form form = new Form(instructionViewer.config) { + @Override + public void sync() { + instructionViewer.dirty(); + } + }; + controls.add(form.getPanel()); + + controls.setPreferredSize(new Dimension(200, 500)); + panel.add(BorderLayout.EAST, controls); + frame.setBackground(background); + controls.setBackground(background); + form.getPanel().setBackground(background); + frame.setContentPane(panel); + frame.setPreferredSize(new Dimension(800, 1000)); + frame.pack(); + frame.setVisible(true); + + (new Thread(() -> { + + SwingUtilities.invokeLater(() -> { + runButton.setSelected(true); + runButton.getActionListeners()[0].actionPerformed(null); //auto-start + }); Entrypoint entrypoint; try { - entrypoint = instructionViewer.classModel.getEntrypoint(); - final MethodModel method = entrypoint.getMethodModel(); + entrypoint = instructionViewer.classModel.getEntrypoint(); + final MethodModel method = entrypoint.getMethodModel(); } catch (final AparapiException e) { - // TODO Auto-generated catch block - e.printStackTrace(); + // TODO Auto-generated catch block + e.printStackTrace(); } - } - - })).start(); + })).start(); - } + } } diff --git a/src/main/java/com/aparapi/internal/util/OpenCLUtil.java b/src/main/java/com/aparapi/internal/util/OpenCLUtil.java index 91933f68..f623c60f 100644 --- a/src/main/java/com/aparapi/internal/util/OpenCLUtil.java +++ b/src/main/java/com/aparapi/internal/util/OpenCLUtil.java @@ -22,7 +22,7 @@ /** * This utility class encapsulates the necessary actions required to query underlying OpenCL information */ -public class OpenCLUtil{ +class OpenCLUtil{ /** * Retrieve a list of available OpenCL Platforms diff --git a/src/main/java/com/aparapi/internal/util/UnsafeWrapper.java b/src/main/java/com/aparapi/internal/util/UnsafeWrapper.java index b39543fe..0c554be8 100644 --- a/src/main/java/com/aparapi/internal/util/UnsafeWrapper.java +++ b/src/main/java/com/aparapi/internal/util/UnsafeWrapper.java @@ -129,22 +129,7 @@ public class UnsafeWrapper{ putLongMethod = uc.getDeclaredMethod("putLong", Object.class, long.class, long.class); putByteMethod = uc.getDeclaredMethod("putByte", Object.class, long.class, byte.class); compareAndSwapIntMethod = uc.getDeclaredMethod("compareAndSwapInt", Object.class, long.class, int.class, int.class); - } catch (final SecurityException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (final NoSuchFieldException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (final IllegalArgumentException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (final IllegalAccessException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (final ClassNotFoundException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (final NoSuchMethodException e) { + } catch (final SecurityException | NoSuchMethodException | ClassNotFoundException | IllegalAccessException | IllegalArgumentException | NoSuchFieldException e) { // TODO Auto-generated catch block e.printStackTrace(); } @@ -164,13 +149,7 @@ public static int atomicAdd(int[] _arr, int _index, int _delta) { if ((Boolean) compareAndSwapIntMethod.invoke(unsafe, _arr, rawIndex, current, next)) { return current; } - } catch (final IllegalArgumentException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (final IllegalAccessException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (final InvocationTargetException e) { + } catch (final IllegalArgumentException | InvocationTargetException | IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } @@ -182,13 +161,7 @@ public static int arrayBaseOffset(Class _arrayClass) { try { offset = (Integer) (arrayBaseOffsetMethod.invoke(unsafe, _arrayClass)); - } catch (final IllegalArgumentException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (final IllegalAccessException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (final InvocationTargetException e) { + } catch (final IllegalArgumentException | InvocationTargetException | IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } @@ -200,34 +173,22 @@ public static int arrayIndexScale(Class _arrayClass) { int scale = 0; try { scale = (Integer) (arrayIndexScaleMethod.invoke(unsafe, _arrayClass)); - } catch (final IllegalArgumentException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (final IllegalAccessException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (final InvocationTargetException e) { + } catch (final IllegalArgumentException | InvocationTargetException | IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } return scale; } - private static int intArrayBase = arrayBaseOffset(int[].class); + private static final int intArrayBase = arrayBaseOffset(int[].class); - private static int intArrayScale = arrayIndexScale(int[].class); + private static final int intArrayScale = arrayIndexScale(int[].class); public static Object getObject(Object _object, long _offset) { Object object = null; try { object = getObjectMethod.invoke(unsafe, _object, _offset); - } catch (final IllegalArgumentException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (final IllegalAccessException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (final InvocationTargetException e) { + } catch (final IllegalArgumentException | InvocationTargetException | IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } @@ -238,13 +199,7 @@ public static int getInt(Object _object, long _offset) { int value = 0; try { value = (Integer) getIntMethod.invoke(unsafe, _object, _offset); - } catch (final IllegalArgumentException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (final IllegalAccessException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (final InvocationTargetException e) { + } catch (final IllegalArgumentException | InvocationTargetException | IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } @@ -255,13 +210,7 @@ public static float getFloat(Object _object, long _offset) { float value = 0; try { value = (Float) getFloatMethod.invoke(unsafe, _object, _offset); - } catch (final IllegalArgumentException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (final IllegalAccessException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (final InvocationTargetException e) { + } catch (final IllegalArgumentException | InvocationTargetException | IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } @@ -272,13 +221,7 @@ public static byte getByte(Object _object, long _offset) { byte value = 0; try { value = (Byte) getByteMethod.invoke(unsafe, _object, _offset); - } catch (final IllegalArgumentException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (final IllegalAccessException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (final InvocationTargetException e) { + } catch (final IllegalArgumentException | InvocationTargetException | IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } @@ -289,13 +232,7 @@ public static boolean getBoolean(Object _object, long _offset) { boolean value = false; try { value = (Boolean) getBooleanMethod.invoke(unsafe, _object, _offset); - } catch (final IllegalArgumentException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (final IllegalAccessException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (final InvocationTargetException e) { + } catch (final IllegalArgumentException | InvocationTargetException | IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } @@ -306,13 +243,7 @@ public static long getLong(Object _object, long _offset) { long value = 0; try { value = (Long) getLongMethod.invoke(unsafe, _object, _offset); - } catch (final IllegalArgumentException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (final IllegalAccessException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (final InvocationTargetException e) { + } catch (final IllegalArgumentException | InvocationTargetException | IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } @@ -322,13 +253,7 @@ public static long getLong(Object _object, long _offset) { public static void putBoolean(Object _object, long _offset, boolean _boolean) { try { putBooleanMethod.invoke(unsafe, _object, _offset, _boolean); - } catch (final IllegalArgumentException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (final IllegalAccessException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (final InvocationTargetException e) { + } catch (final IllegalArgumentException | InvocationTargetException | IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } @@ -337,13 +262,7 @@ public static void putBoolean(Object _object, long _offset, boolean _boolean) { public static void putFloat(Object _object, long _offset, float _float) { try { putFloatMethod.invoke(unsafe, _object, _offset, _float); - } catch (final IllegalArgumentException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (final IllegalAccessException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (final InvocationTargetException e) { + } catch (final IllegalArgumentException | InvocationTargetException | IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } @@ -352,13 +271,7 @@ public static void putFloat(Object _object, long _offset, float _float) { public static void putInt(Object _object, long _offset, int _int) { try { putIntMethod.invoke(unsafe, _object, _offset, _int); - } catch (final IllegalArgumentException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (final IllegalAccessException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (final InvocationTargetException e) { + } catch (final IllegalArgumentException | InvocationTargetException | IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } @@ -367,13 +280,7 @@ public static void putInt(Object _object, long _offset, int _int) { public static void putDouble(Object _object, long _offset, double _double) { try { putDoubleMethod.invoke(unsafe, _object, _offset, _double); - } catch (final IllegalArgumentException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (final IllegalAccessException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (final InvocationTargetException e) { + } catch (final IllegalArgumentException | InvocationTargetException | IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } @@ -382,13 +289,7 @@ public static void putDouble(Object _object, long _offset, double _double) { public static void putByte(Object _object, long _offset, byte _byte) { try { putByteMethod.invoke(unsafe, _object, _offset, _byte); - } catch (final IllegalArgumentException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (final IllegalAccessException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (final InvocationTargetException e) { + } catch (final IllegalArgumentException | InvocationTargetException | IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } @@ -397,29 +298,17 @@ public static void putByte(Object _object, long _offset, byte _byte) { public static void putLong(Object _object, long _offset, long _long) { try { putLongMethod.invoke(unsafe, _object, _offset, _long); - } catch (final IllegalArgumentException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (final IllegalAccessException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (final InvocationTargetException e) { + } catch (final IllegalArgumentException | InvocationTargetException | IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static long objectFieldOffset(Field _field) { - long offset = 0l; + long offset = 0L; try { offset = (Long) objectFieldOffsetMethod.invoke(unsafe, _field); - } catch (final IllegalArgumentException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (final IllegalAccessException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (final InvocationTargetException e) { + } catch (final IllegalArgumentException | InvocationTargetException | IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } diff --git a/src/main/java/com/aparapi/internal/writer/BlockWriter.java b/src/main/java/com/aparapi/internal/writer/BlockWriter.java index 0712ffc4..55974a7e 100644 --- a/src/main/java/com/aparapi/internal/writer/BlockWriter.java +++ b/src/main/java/com/aparapi/internal/writer/BlockWriter.java @@ -55,14 +55,11 @@ to national security controls as identified on the Commerce Control List (curren import com.aparapi.*; import com.aparapi.internal.exception.*; import com.aparapi.internal.instruction.*; -import com.aparapi.internal.instruction.BranchSet.LogicalExpressionNode; -import com.aparapi.internal.instruction.InstructionSet.AccessInstanceField; import com.aparapi.internal.instruction.BranchSet.*; import com.aparapi.internal.instruction.InstructionSet.*; import com.aparapi.internal.model.ClassModel.ConstantPool.*; import com.aparapi.internal.model.ClassModel.*; import com.aparapi.internal.model.*; -import com.aparapi.internal.model.ClassModel.ConstantPool.NameAndTypeEntry; import java.util.*; @@ -76,35 +73,35 @@ to national security controls as identified on the Commerce Control List (curren public abstract class BlockWriter{ - public final static String arrayLengthMangleSuffix = "__javaArrayLength"; + final static String arrayLengthMangleSuffix = "__javaArrayLength"; - public final static String arrayDimMangleSuffix = "__javaArrayDimension"; + final static String arrayDimMangleSuffix = "__javaArrayDimension"; - public abstract void write(String _string); + protected abstract void write(String _string); - public void writeln(String _string) { + void writeln(String _string) { write(_string); newLine(); } - public int indent = 0; + private int indent = 0; - public void in() { + void in() { indent++; } - public void out() { + void out() { indent--; } - public void newLine() { + void newLine() { write("\n"); for (int i = 0; i < indent; i++) { write(" "); } } - public void writeConditionalBranch16(ConditionalBranch16 _branch16, boolean _invert) throws CodeGenException { + private void writeConditionalBranch16(ConditionalBranch16 _branch16, boolean _invert) throws CodeGenException { if (_branch16 instanceof If) { final If iff = (If) _branch16; @@ -160,7 +157,7 @@ public void writeConditionalBranch16(ConditionalBranch16 _branch16, boolean _inv } } - public void writeComposite(CompositeInstruction instruction) throws CodeGenException { + private void writeComposite(CompositeInstruction instruction) throws CodeGenException { if (instruction instanceof CompositeArbitraryScopeInstruction) { newLine(); @@ -283,13 +280,13 @@ public void writeComposite(CompositeInstruction instruction) throws CodeGenExcep Instruction blockEnd = instruction.getLastChild(); writeBlock(blockStart, blockEnd); write("while("); - writeConditional(((CompositeInstruction) instruction).getBranchSet(), true); + writeConditional(instruction.getBranchSet(), true); write(");"); newLine(); } } - public void writeSequence(Instruction _first, Instruction _last) throws CodeGenException { + private void writeSequence(Instruction _first, Instruction _last) throws CodeGenException { for (Instruction instruction = _first; instruction != _last; instruction = instruction.getNextExpr()) { if (instruction instanceof CompositeInstruction) { @@ -304,7 +301,7 @@ public void writeSequence(Instruction _first, Instruction _last) throws CodeGenE } - protected void writeGetterBlock(FieldEntry accessorVariableFieldEntry) { + private void writeGetterBlock(FieldEntry accessorVariableFieldEntry) { write("{"); in(); newLine(); @@ -317,7 +314,7 @@ protected void writeGetterBlock(FieldEntry accessorVariableFieldEntry) { write("}"); } - public void writeBlock(Instruction _first, Instruction _last) throws CodeGenException { + private void writeBlock(Instruction _first, Instruction _last) throws CodeGenException { write("{"); in(); writeSequence(_first, _last); @@ -327,18 +324,18 @@ public void writeBlock(Instruction _first, Instruction _last) throws CodeGenExce write("}"); } - public Instruction writeConditional(BranchSet _branchSet) throws CodeGenException { + private Instruction writeConditional(BranchSet _branchSet) throws CodeGenException { return (writeConditional(_branchSet, false)); } - public Instruction writeConditional(BranchSet _branchSet, boolean _invert) throws CodeGenException { + private Instruction writeConditional(BranchSet _branchSet, boolean _invert) throws CodeGenException { final LogicalExpressionNode logicalExpression = _branchSet.getLogicalExpression(); write(_invert ? logicalExpression : logicalExpression.cloneInverted()); return (_branchSet.getLast().getNextExpr()); } - public void write(LogicalExpressionNode _node) throws CodeGenException { + private void write(LogicalExpressionNode _node) throws CodeGenException { if (_node instanceof SimpleLogicalExpressionNode) { final SimpleLogicalExpressionNode sn = (SimpleLogicalExpressionNode) _node; @@ -366,15 +363,15 @@ public void write(LogicalExpressionNode _node) throws CodeGenException { } } - public String convertType(String _typeDesc, boolean useClassModel, boolean isLocal) { + String convertType(String _typeDesc, boolean useClassModel, boolean isLocal) { return (_typeDesc); } - public String convertCast(String _cast) { + private String convertCast(String _cast) { // Strip parens off cast //System.out.println("cast = " + _cast); final String raw = convertType(_cast.substring(1, _cast.length() - 1), false, false); - return ("(" + raw + ")"); + return ('(' + raw + ')'); } public void writeInstruction(Instruction _instruction) throws CodeGenException { @@ -479,7 +476,7 @@ public void writeInstruction(Instruction _instruction) throws CodeGenException { dim++; } - NameAndTypeEntry nameAndTypeEntry = ((AccessField) load).getConstantPoolFieldEntry().getNameAndTypeEntry(); + NameAndTypeEntry nameAndTypeEntry = ((FieldReference) load).getConstantPoolFieldEntry().getNameAndTypeEntry(); if (isMultiDimensionalArray(nameAndTypeEntry)) { String arrayName = nameAndTypeEntry.getNameUTF8Entry().getUTF8(); write(" * this->" + arrayName + arrayDimMangleSuffix + dim); @@ -497,7 +494,7 @@ public void writeInstruction(Instruction _instruction) throws CodeGenException { if (accessField instanceof AccessInstanceField) { Instruction accessInstanceField = ((AccessInstanceField) accessField).getInstance(); if (accessInstanceField instanceof CloneInstruction) { - accessInstanceField = ((CloneInstruction) accessInstanceField).getReal(); + accessInstanceField = accessInstanceField.getReal(); } if (!(accessInstanceField instanceof I_ALOAD_0)) { writeInstruction(accessInstanceField); @@ -520,7 +517,7 @@ public void writeInstruction(Instruction _instruction) throws CodeGenException { load = load.getFirstChild(); dim++; } - NameAndTypeEntry nameAndTypeEntry = ((AccessInstanceField) load).getConstantPoolFieldEntry().getNameAndTypeEntry(); + NameAndTypeEntry nameAndTypeEntry = ((FieldReference) load).getConstantPoolFieldEntry().getNameAndTypeEntry(); final String arrayName = nameAndTypeEntry.getNameUTF8Entry().getUTF8(); String dimSuffix = isMultiDimensionalArray(nameAndTypeEntry) ? Integer.toString(dim) : ""; write("this->" + arrayName + arrayLengthMangleSuffix + dimSuffix); @@ -608,7 +605,7 @@ public void writeInstruction(Instruction _instruction) throws CodeGenException { writeInstruction(binaryInstruction.getLhs()); - write(" " + binaryInstruction.getOperator().getText() + " "); + write(' ' + binaryInstruction.getOperator().getText() + ' '); writeInstruction(binaryInstruction.getRhs()); if (needsParenthesis) { @@ -672,7 +669,7 @@ public void writeInstruction(Instruction _instruction) throws CodeGenException { AssignToLocalVariable from = (AssignToLocalVariable) multiAssignInstruction.getFrom(); final AssignToLocalVariable last = (AssignToLocalVariable) multiAssignInstruction.getTo(); final Instruction common = multiAssignInstruction.getCommon(); - final Stack stack = new Stack(); + final Stack stack = new Stack<>(); while (from != last) { stack.push(from); @@ -756,7 +753,7 @@ public void writeInstruction(Instruction _instruction) throws CodeGenException { } - private boolean isNeedParenthesis(Instruction instruction){ + private static boolean isNeedParenthesis(Instruction instruction){ final Instruction parent = instruction.getParentExpr(); boolean needsParenthesis = true; @@ -797,7 +794,7 @@ private boolean isObjectArray(final AccessArrayElement arrayLoadInstruction) { return isObjectArray(accessInstanceField.getConstantPoolFieldEntry().getNameAndTypeEntry()); } - private AccessField getUltimateInstanceFieldAccess(final AccessArrayElement arrayLoadInstruction) { + private static AccessField getUltimateInstanceFieldAccess(final AccessArrayElement arrayLoadInstruction) { Instruction load = arrayLoadInstruction.getArrayRef(); while (load instanceof I_AALOAD) { load = load.getFirstChild(); @@ -806,9 +803,8 @@ private AccessField getUltimateInstanceFieldAccess(final AccessArrayElement arra return (AccessField) load; } - public void writeMethod(MethodCall _methodCall, MethodEntry _methodEntry) throws CodeGenException { - boolean noCL = _methodEntry.getOwnerClassModel().getNoCLMethods() - .contains(_methodEntry.getNameAndTypeEntry().getNameUTF8Entry().getUTF8()); + void writeMethod(MethodCall _methodCall, MethodEntry _methodEntry) throws CodeGenException { + boolean noCL = _methodEntry.getOwnerClassModel().isNoCLMethod(_methodEntry.getNameAndTypeEntry().getNameUTF8Entry().getUTF8()); if (noCL) { return; } @@ -836,7 +832,7 @@ public void writeMethod(MethodCall _methodCall, MethodEntry _methodEntry) throws } - public void writeThisRef() { + void writeThisRef() { write("this."); } diff --git a/src/main/java/com/aparapi/internal/writer/KernelWriter.java b/src/main/java/com/aparapi/internal/writer/KernelWriter.java index 8099c591..d73d0395 100644 --- a/src/main/java/com/aparapi/internal/writer/KernelWriter.java +++ b/src/main/java/com/aparapi/internal/writer/KernelWriter.java @@ -66,688 +66,709 @@ to national security controls as identified on the Commerce Control List (curren import java.util.*; -public abstract class KernelWriter extends BlockWriter{ +public abstract class KernelWriter extends BlockWriter { - private final String cvtBooleanToChar = "char "; + private static final String cvtBooleanToChar = "char "; - private final String cvtBooleanArrayToCharStar = "char* "; + private static final String cvtBooleanArrayToCharStar = "char* "; - private final String cvtBooleanArrayToChar = "char "; + private static final String cvtBooleanArrayToChar = "char "; - private final String cvtByteToChar = "char "; + private static final String cvtByteToChar = "char "; - private final String cvtByteArrayToCharStar = "char* "; + private static final String cvtByteArrayToCharStar = "char* "; - private final String cvtByteArrayToChar = "char "; + private static final String cvtByteArrayToChar = "char "; - private final String cvtCharToShort = "unsigned short "; + private static final String cvtCharToShort = "unsigned short "; - private final String cvtCharArrayToShortStar = "unsigned short* "; + private static final String cvtCharArrayToShortStar = "unsigned short* "; - private final String cvtCharArrayToShort = "unsigned short "; + private static final String cvtCharArrayToShort = "unsigned short "; - private final String cvtIntArrayToIntStar = "int* "; + private static final String cvtIntArrayToIntStar = "int* "; - private final String cvtIntArrayToInt = "int "; + private static final String cvtIntArrayToInt = "int "; - private final String cvtFloatArrayToFloatStar = "float* "; + private static final String cvtFloatArrayToFloatStar = "float* "; - private final String cvtFloatArrayToFloat = "float "; + private static final String cvtFloatArrayToFloat = "float "; - private final String cvtDoubleArrayToDoubleStar = "double* "; + private static final String cvtDoubleArrayToDoubleStar = "double* "; - private final String cvtDoubleArrayToDouble = "double "; - - private final String cvtLongArrayToLongStar = "long* "; - - private final String cvtLongArrayToLong = "long "; - - private final String cvtShortArrayToShortStar = "short* "; + private static final String cvtDoubleArrayToDouble = "double "; - private final String cvtShortArrayToShort = "short "; - - /** When declaring a __private struct pointer field, we always omit the "__private" qualifier. This is because the NVidia OpenCL compiler, at time of writing - * erroneously complains about explicitly qualifying pointers with __private ("error: field may not be qualified with an address space"). - */ - private static final boolean IMPLICIT_PRIVATE_FIELDS = true; + private static final String cvtLongArrayToLongStar = "long* "; - // private static Logger logger = Logger.getLogger(Config.getLoggerName()); + private static final String cvtLongArrayToLong = "long "; + + private static final String cvtShortArrayToShortStar = "short* "; + + private static final String cvtShortArrayToShort = "short "; + + /** When declaring a __private struct pointer field, we always omit the "__private" qualifier. This is because the NVidia OpenCL compiler, at time of writing + * erroneously complains about explicitly qualifying pointers with __private ("error: field may not be qualified with an address space"). + */ + private static final boolean IMPLICIT_PRIVATE_FIELDS = true; + + // private static Logger logger = Logger.getLogger(Config.getLoggerName()); + + private Entrypoint entryPoint = null; + + private final static Map javaToCLIdentifierMap = new HashMap() {{ + put("getGlobalId()I", "get_global_id(0)"); + put("getGlobalId(I)I", "get_global_id"); // no parenthesis if we are conveying args + put("getGlobalX()I", "get_global_id(0)"); + put("getGlobalY()I", "get_global_id(1)"); + put("getGlobalZ()I", "get_global_id(2)"); + + put("getGlobalSize()I", "get_global_size(0)"); + put("getGlobalSize(I)I", "get_global_size"); // no parenthesis if we are conveying args + put("getGlobalWidth()I", "get_global_size(0)"); + put("getGlobalHeight()I", "get_global_size(1)"); + put("getGlobalDepth()I", "get_global_size(2)"); + + put("getLocalId()I", "get_local_id(0)"); + put("getLocalId(I)I", "get_local_id"); // no parenthesis if we are conveying args + put("getLocalX()I", "get_local_id(0)"); + put("getLocalY()I", "get_local_id(1)"); + put("getLocalZ()I", "get_local_id(2)"); + + put("getLocalSize()I", "get_local_size(0)"); + put("getLocalSize(I)I", "get_local_size"); // no parenthesis if we are conveying args + put("getLocalWidth()I", "get_local_size(0)"); + put("getLocalHeight()I", "get_local_size(1)"); + put("getLocalDepth()I", "get_local_size(2)"); + + put("getNumGroups()I", "get_num_groups(0)"); + put("getNumGroups(I)I", "get_num_groups"); // no parenthesis if we are conveying args + put("getNumGroupsX()I", "get_num_groups(0)"); + put("getNumGroupsY()I", "get_num_groups(1)"); + put("getNumGroupsZ()I", "get_num_groups(2)"); + + put("getGroupId()I", "get_group_id(0)"); + put("getGroupId(I)I", "get_group_id"); // no parenthesis if we are conveying args + put("getGroupX()I", "get_group_id(0)"); + put("getGroupY()I", "get_group_id(1)"); + put("getGroupZ()I", "get_group_id(2)"); + + put("getPassId()I", "get_pass_id(this)"); + + put("localBarrier()V", "barrier(CLK_LOCAL_MEM_FENCE)"); + + put("globalBarrier()V", "barrier(CLK_GLOBAL_MEM_FENCE)"); + + }}; + + /** + * These three convert functions are here to perform + * any type conversion that may be required between + * Java and OpenCL. + * + * @param _typeDesc + * String in the Java JNI notation, [I, etc + * @return Suitably converted string, "char*", etc + */ + @Override + public String convertType(String _typeDesc, boolean useClassModel, boolean isLocal) { + switch (_typeDesc) { + case "Z": + case "boolean": + return (cvtBooleanToChar); + case "[Z": + case "boolean[]": + return isLocal ? (cvtBooleanArrayToChar) : (cvtBooleanArrayToCharStar); + case "B": + case "byte": + return (cvtByteToChar); + case "[B": + case "byte[]": + return isLocal ? (cvtByteArrayToChar) : (cvtByteArrayToCharStar); + case "C": + case "char": + return (cvtCharToShort); + case "[C": + case "char[]": + return isLocal ? (cvtCharArrayToShort) : (cvtCharArrayToShortStar); + case "[I": + case "int[]": + return isLocal ? (cvtIntArrayToInt) : (cvtIntArrayToIntStar); + case "[F": + case "float[]": + return isLocal ? (cvtFloatArrayToFloat) : (cvtFloatArrayToFloatStar); + case "[D": + case "double[]": + return isLocal ? (cvtDoubleArrayToDouble) : (cvtDoubleArrayToDoubleStar); + case "[J": + case "long[]": + return isLocal ? (cvtLongArrayToLong) : (cvtLongArrayToLongStar); + case "[S": + case "short[]": + return isLocal ? (cvtShortArrayToShort) : (cvtShortArrayToShortStar); + } + // if we get this far, we haven't matched anything yet + if (useClassModel) { + return (ClassModel.convert(_typeDesc, "", true)); + } else { + return _typeDesc; + } + } + + @Override + public void writeMethod(MethodCall _methodCall, MethodEntry _methodEntry) throws CodeGenException { + final int argc = _methodEntry.getStackConsumeCount(); + + NameAndTypeEntry entry = _methodEntry.getNameAndTypeEntry(); + final String methodName = entry.getNameUTF8Entry().getUTF8(); + final String methodSignature = entry.getDescriptorUTF8Entry().getUTF8(); + + final String barrierAndGetterMappings = javaToCLIdentifierMap.get(methodName + methodSignature); + + if (barrierAndGetterMappings != null) { + // this is one of the OpenCL barrier or size getter methods + // write the mapping and exit + if (argc > 0) { + write(barrierAndGetterMappings); + write("("); + for (int arg = 0; arg < argc; arg++) { + if ((arg != 0)) { + write(", "); + } + writeInstruction(_methodCall.getArg(arg)); + } + write(")"); + } else { + write(barrierAndGetterMappings); + } + } else { + final boolean isSpecial = _methodCall instanceof I_INVOKESPECIAL; + MethodModel m = entryPoint.getCallTarget(_methodEntry, isSpecial); - private Entrypoint entryPoint = null; - - public final static Map javaToCLIdentifierMap = new HashMap(); - { - javaToCLIdentifierMap.put("getGlobalId()I", "get_global_id(0)"); - javaToCLIdentifierMap.put("getGlobalId(I)I", "get_global_id"); // no parenthesis if we are conveying args - javaToCLIdentifierMap.put("getGlobalX()I", "get_global_id(0)"); - javaToCLIdentifierMap.put("getGlobalY()I", "get_global_id(1)"); - javaToCLIdentifierMap.put("getGlobalZ()I", "get_global_id(2)"); - - javaToCLIdentifierMap.put("getGlobalSize()I", "get_global_size(0)"); - javaToCLIdentifierMap.put("getGlobalSize(I)I", "get_global_size"); // no parenthesis if we are conveying args - javaToCLIdentifierMap.put("getGlobalWidth()I", "get_global_size(0)"); - javaToCLIdentifierMap.put("getGlobalHeight()I", "get_global_size(1)"); - javaToCLIdentifierMap.put("getGlobalDepth()I", "get_global_size(2)"); - - javaToCLIdentifierMap.put("getLocalId()I", "get_local_id(0)"); - javaToCLIdentifierMap.put("getLocalId(I)I", "get_local_id"); // no parenthesis if we are conveying args - javaToCLIdentifierMap.put("getLocalX()I", "get_local_id(0)"); - javaToCLIdentifierMap.put("getLocalY()I", "get_local_id(1)"); - javaToCLIdentifierMap.put("getLocalZ()I", "get_local_id(2)"); - - javaToCLIdentifierMap.put("getLocalSize()I", "get_local_size(0)"); - javaToCLIdentifierMap.put("getLocalSize(I)I", "get_local_size"); // no parenthesis if we are conveying args - javaToCLIdentifierMap.put("getLocalWidth()I", "get_local_size(0)"); - javaToCLIdentifierMap.put("getLocalHeight()I", "get_local_size(1)"); - javaToCLIdentifierMap.put("getLocalDepth()I", "get_local_size(2)"); - - javaToCLIdentifierMap.put("getNumGroups()I", "get_num_groups(0)"); - javaToCLIdentifierMap.put("getNumGroups(I)I", "get_num_groups"); // no parenthesis if we are conveying args - javaToCLIdentifierMap.put("getNumGroupsX()I", "get_num_groups(0)"); - javaToCLIdentifierMap.put("getNumGroupsY()I", "get_num_groups(1)"); - javaToCLIdentifierMap.put("getNumGroupsZ()I", "get_num_groups(2)"); - - javaToCLIdentifierMap.put("getGroupId()I", "get_group_id(0)"); - javaToCLIdentifierMap.put("getGroupId(I)I", "get_group_id"); // no parenthesis if we are conveying args - javaToCLIdentifierMap.put("getGroupX()I", "get_group_id(0)"); - javaToCLIdentifierMap.put("getGroupY()I", "get_group_id(1)"); - javaToCLIdentifierMap.put("getGroupZ()I", "get_group_id(2)"); - - javaToCLIdentifierMap.put("getPassId()I", "get_pass_id(this)"); - - javaToCLIdentifierMap.put("localBarrier()V", "barrier(CLK_LOCAL_MEM_FENCE)"); - - javaToCLIdentifierMap.put("globalBarrier()V", "barrier(CLK_GLOBAL_MEM_FENCE)"); - } - - /** - * These three convert functions are here to perform - * any type conversion that may be required between - * Java and OpenCL. - * - * @param _typeDesc - * String in the Java JNI notation, [I, etc - * @return Suitably converted string, "char*", etc - */ - @Override public String convertType(String _typeDesc, boolean useClassModel, boolean isLocal) { - if (_typeDesc.equals("Z") || _typeDesc.equals("boolean")) { - return (cvtBooleanToChar); - } else if (_typeDesc.equals("[Z") || _typeDesc.equals("boolean[]")) { - return isLocal ? (cvtBooleanArrayToChar) : (cvtBooleanArrayToCharStar); - } else if (_typeDesc.equals("B") || _typeDesc.equals("byte")) { - return (cvtByteToChar); - } else if (_typeDesc.equals("[B") || _typeDesc.equals("byte[]")) { - return isLocal ? (cvtByteArrayToChar) : (cvtByteArrayToCharStar); - } else if (_typeDesc.equals("C") || _typeDesc.equals("char")) { - return (cvtCharToShort); - } else if (_typeDesc.equals("[C") || _typeDesc.equals("char[]")) { - return isLocal ? (cvtCharArrayToShort) : (cvtCharArrayToShortStar); - } else if (_typeDesc.equals("[I") || _typeDesc.equals("int[]")) { - return isLocal ? (cvtIntArrayToInt) : (cvtIntArrayToIntStar); - } else if (_typeDesc.equals("[F") || _typeDesc.equals("float[]")) { - return isLocal ? (cvtFloatArrayToFloat) : (cvtFloatArrayToFloatStar); - } else if (_typeDesc.equals("[D") || _typeDesc.equals("double[]")) { - return isLocal ? (cvtDoubleArrayToDouble) : (cvtDoubleArrayToDoubleStar); - } else if (_typeDesc.equals("[J") || _typeDesc.equals("long[]")) { - return isLocal ? (cvtLongArrayToLong) : (cvtLongArrayToLongStar); - } else if (_typeDesc.equals("[S") || _typeDesc.equals("short[]")) { - return isLocal ? (cvtShortArrayToShort) : (cvtShortArrayToShortStar); - } - // if we get this far, we haven't matched anything yet - if (useClassModel) { - return (ClassModel.convert(_typeDesc, "", true)); - } else { - return _typeDesc; - } - } - - @Override public void writeMethod(MethodCall _methodCall, MethodEntry _methodEntry) throws CodeGenException { - final int argc = _methodEntry.getStackConsumeCount(); - - final String methodName = _methodEntry.getNameAndTypeEntry().getNameUTF8Entry().getUTF8(); - final String methodSignature = _methodEntry.getNameAndTypeEntry().getDescriptorUTF8Entry().getUTF8(); - - final String barrierAndGetterMappings = javaToCLIdentifierMap.get(methodName + methodSignature); - - if (barrierAndGetterMappings != null) { - // this is one of the OpenCL barrier or size getter methods - // write the mapping and exit - if (argc > 0) { - write(barrierAndGetterMappings); - write("("); - for (int arg = 0; arg < argc; arg++) { - if ((arg != 0)) { - write(", "); - } - writeInstruction(_methodCall.getArg(arg)); + FieldEntry getterField = null; + if (m != null && m.isGetter()) { + getterField = m.getAccessorVariableFieldEntry(); } - write(")"); - } else { - write(barrierAndGetterMappings); - } - } else { - final boolean isSpecial = _methodCall instanceof I_INVOKESPECIAL; - MethodModel m = entryPoint.getCallTarget(_methodEntry, isSpecial); - - FieldEntry getterField = null; - if (m != null && m.isGetter()) { - getterField = m.getAccessorVariableFieldEntry(); - } - if (getterField != null && isThis(_methodCall.getArg(0))) { - String fieldName = getterField.getNameAndTypeEntry().getNameUTF8Entry().getUTF8(); - write("this->"); - write(fieldName); - return; - } - boolean noCL = _methodEntry.getOwnerClassModel().getNoCLMethods() - .contains(_methodEntry.getNameAndTypeEntry().getNameUTF8Entry().getUTF8()); - if (noCL) { - return; - } - final String intrinsicMapping = Kernel.getMappedMethodName(_methodEntry); - // System.out.println("getMappedMethodName for " + methodName + " returned " + mapping); - boolean isIntrinsic = false; - - if (intrinsicMapping == null) { - assert entryPoint != null : "entryPoint should not be null"; - boolean isMapped = Kernel.isMappedMethod(_methodEntry); - - if (m != null) { - write(m.getName()); - } else { - // Must be a library call like rsqrt - assert isMapped : _methodEntry + " should be mapped method!"; - write(methodName); - isIntrinsic = true; + if (getterField != null && isThis(_methodCall.getArg(0))) { + String fieldName = getterField.getNameAndTypeEntry().getNameUTF8Entry().getUTF8(); + write("this->"); + write(fieldName); + return; + } + boolean noCL = _methodEntry.getOwnerClassModel().isNoCLMethod( + entry.getNameUTF8Entry().getUTF8()); + if (noCL) { + return; } - } else { - write(intrinsicMapping); - } - - write("("); - - if ((intrinsicMapping == null) && (_methodCall instanceof VirtualMethodCall) && (!isIntrinsic)) { - - final Instruction i = ((VirtualMethodCall) _methodCall).getInstanceReference(); - - if (i instanceof I_ALOAD_0) { - write("this"); - } else if (i instanceof AccessArrayElement) { - final AccessArrayElement arrayAccess = (AccessArrayElement) ((VirtualMethodCall) _methodCall).getInstanceReference(); - final Instruction refAccess = arrayAccess.getArrayRef(); - //assert refAccess instanceof I_GETFIELD : "ref should come from getfield"; - final String fieldName = ((AccessField) refAccess).getConstantPoolFieldEntry().getNameAndTypeEntry() - .getNameUTF8Entry().getUTF8(); - write(" &(this->" + fieldName); - write("["); - writeInstruction(arrayAccess.getArrayIndex()); - write("])"); + final String intrinsicMapping = Kernel.getMappedMethodName(_methodEntry); + // System.out.println("getMappedMethodName for " + methodName + " returned " + mapping); + boolean isIntrinsic = false; + + if (intrinsicMapping == null) { + assert entryPoint != null : "entryPoint should not be null"; + boolean isMapped = Kernel.isMappedMethod(_methodEntry); + + if (m != null) { + write(m.getName()); + } else { + // Must be a library call like rsqrt + assert isMapped : _methodEntry + " should be mapped method!"; + write(methodName); + isIntrinsic = true; + } } else { - assert false : "unhandled call from: " + i; + write(intrinsicMapping); + } + + write("("); + + if ((intrinsicMapping == null) && (_methodCall instanceof VirtualMethodCall) && (!isIntrinsic)) { + + final Instruction i = ((VirtualMethodCall) _methodCall).getInstanceReference(); + + if (i instanceof I_ALOAD_0) { + write("this"); + } else if (i instanceof AccessArrayElement) { + final AccessArrayElement arrayAccess = (AccessArrayElement) ((VirtualMethodCall) _methodCall).getInstanceReference(); + final Instruction refAccess = arrayAccess.getArrayRef(); + //assert refAccess instanceof I_GETFIELD : "ref should come from getfield"; + final String fieldName = ((FieldReference) refAccess).getConstantPoolFieldEntry().getNameAndTypeEntry() + .getNameUTF8Entry().getUTF8(); + write(" &(this->" + fieldName); + write("["); + writeInstruction(arrayAccess.getArrayIndex()); + write("])"); + } else { + assert false : "unhandled call from: " + i; + } } - } - for (int arg = 0; arg < argc; arg++) { - if (((intrinsicMapping == null) && (_methodCall instanceof VirtualMethodCall) && (!isIntrinsic)) || (arg != 0)) { - write(", "); + for (int arg = 0; arg < argc; arg++) { + if (((intrinsicMapping == null) && (_methodCall instanceof VirtualMethodCall) && (!isIntrinsic)) || (arg != 0)) { + write(", "); + } + writeInstruction(_methodCall.getArg(arg)); } - writeInstruction(_methodCall.getArg(arg)); - } - write(")"); - } - } + write(")"); + } + } - private boolean isThis(Instruction instruction) { - return instruction instanceof I_ALOAD_0; - } + private static boolean isThis(Instruction instruction) { + return instruction instanceof I_ALOAD_0; + } - public void writePragma(String _name, boolean _enable) { - write("#pragma OPENCL EXTENSION " + _name + " : " + (_enable ? "en" : "dis") + "able"); - newLine(); - } + private void writePragma(String _name, boolean _enable) { + write("#pragma OPENCL EXTENSION " + _name + " : " + (_enable ? "en" : "dis") + "able"); + newLine(); + } - public final static String __local = "__local"; + private final static String __local = "__local"; - public final static String __global = "__global"; + private final static String __global = "__global"; - public final static String __constant = "__constant"; + private final static String __constant = "__constant"; - public final static String __private = "__private"; + private final static String __private = "__private"; - public final static String LOCAL_ANNOTATION_NAME = "L" + com.aparapi.Kernel.Local.class.getName().replace('.', '/') + ";"; + private final static String LOCAL_ANNOTATION_NAME = 'L' + com.aparapi.Kernel.Local.class.getName().replace('.', '/') + ';'; - public final static String CONSTANT_ANNOTATION_NAME = "L" + com.aparapi.Kernel.Constant.class.getName().replace('.', '/') - + ";"; + private final static String CONSTANT_ANNOTATION_NAME = 'L' + com.aparapi.Kernel.Constant.class.getName().replace('.', '/') + + ';'; - @Override public void write(Entrypoint _entryPoint) throws CodeGenException { - final List thisStruct = new ArrayList(); - final List argLines = new ArrayList(); - final List assigns = new ArrayList(); + @Override + public void write(Entrypoint _entryPoint) throws CodeGenException { + final List thisStruct = new ArrayList<>(); + final List argLines = new ArrayList<>(); + final List assigns = new ArrayList<>(); - entryPoint = _entryPoint; + entryPoint = _entryPoint; - for (final ClassModelField field : _entryPoint.getReferencedClassModelFields()) { - // Field field = _entryPoint.getClassModel().getField(f.getName()); - final StringBuilder thisStructLine = new StringBuilder(); - final StringBuilder argLine = new StringBuilder(); - final StringBuilder assignLine = new StringBuilder(); + final StringBuilder thisStructLine = new StringBuilder(); + final StringBuilder argLine = new StringBuilder(); + final StringBuilder assignLine = new StringBuilder(); - String signature = field.getDescriptor(); + for (final ClassModelField field : _entryPoint.getReferencedClassModelFields()) { + // Field field = _entryPoint.getClassModel().getField(f.getName()); + thisStructLine.setLength(0); + argLine.setLength(0); + assignLine.setLength(0); - boolean isPointer = false; + String signature = field.getDescriptor(); - int numDimensions = 0; + boolean isPointer = false; - // check the suffix + int numDimensions = 0; - String type = field.getName().endsWith(Kernel.LOCAL_SUFFIX) ? __local - : (field.getName().endsWith(Kernel.CONSTANT_SUFFIX) ? __constant : __global); - Integer privateMemorySize = null; - try { - privateMemorySize = _entryPoint.getClassModel().getPrivateMemorySize(field.getName()); - } catch (ClassParseException e) { - throw new CodeGenException(e); - } + // check the suffix - if (privateMemorySize != null) { - type = __private; - } - final RuntimeAnnotationsEntry visibleAnnotations = field.getAttributePool().getRuntimeVisibleAnnotationsEntry(); + String type = field.getName().endsWith(Kernel.LOCAL_SUFFIX) ? __local + : (field.getName().endsWith(Kernel.CONSTANT_SUFFIX) ? __constant : __global); + Integer privateMemorySize = null; + try { + privateMemorySize = _entryPoint.getClassModel().getPrivateMemorySize(field.getName()); + } catch (ClassParseException e) { + throw new CodeGenException(e); + } - if (visibleAnnotations != null) { - for (final AnnotationInfo ai : visibleAnnotations) { - final String typeDescriptor = ai.getTypeDescriptor(); - if (typeDescriptor.equals(LOCAL_ANNOTATION_NAME)) { - type = __local; - } else if (typeDescriptor.equals(CONSTANT_ANNOTATION_NAME)) { - type = __constant; - } + if (privateMemorySize != null) { + type = __private; } - } - - String argType = (__private.equals(type)) ? __constant : type; - - //if we have a an array we want to mark the object as a pointer - //if we have a multiple dimensional array we want to remember the number of dimensions - while (signature.startsWith("[")) { - if (isPointer == false) { - argLine.append(argType + " "); - if (!(type.equals(__private) && IMPLICIT_PRIVATE_FIELDS)) { - thisStructLine.append(type + " "); - } + final RuntimeAnnotationsEntry visibleAnnotations = field.getAttributePool().getRuntimeVisibleAnnotationsEntry(); + + if (visibleAnnotations != null) { + for (final AnnotationInfo ai : visibleAnnotations) { + final String typeDescriptor = ai.getTypeDescriptor(); + if (typeDescriptor.equals(LOCAL_ANNOTATION_NAME)) { + type = __local; + } else if (typeDescriptor.equals(CONSTANT_ANNOTATION_NAME)) { + type = __constant; + } + } } - isPointer = true; - numDimensions++; - signature = signature.substring(1); - } - - // If it is a converted array of objects, emit the struct param - String className = null; - if (signature.startsWith("L")) { - // Turn Lcom/codegen/javalabs/opencl/demo/DummyOOA; into com_amd_javalabs_opencl_demo_DummyOOA for example - className = (signature.substring(1, signature.length() - 1)).replace('/', '_'); - // if (logger.isLoggable(Level.FINE)) { - // logger.fine("Examining object parameter: " + signature + " new: " + className); - // } - argLine.append(className); - thisStructLine.append(className); - } else { - argLine.append(convertType(ClassModel.typeName(signature.charAt(0)), false, false)); - thisStructLine.append(convertType(ClassModel.typeName(signature.charAt(0)), false, false)); - } - - argLine.append(" "); - thisStructLine.append(" "); - - if (isPointer) { - argLine.append("*"); - if (privateMemorySize == null) { - thisStructLine.append("*"); + + String argType = (__private.equals(type)) ? __constant : type; + + //if we have a an array we want to mark the object as a pointer + //if we have a multiple dimensional array we want to remember the number of dimensions + while (signature.startsWith("[")) { + if (isPointer == false) { + argLine.append(argType).append(' '); + if (!(type.equals(__private) && IMPLICIT_PRIVATE_FIELDS)) { + thisStructLine.append(type).append(' '); + } + } + isPointer = true; + numDimensions++; + signature = signature.substring(1); } - } - - if (privateMemorySize == null) { - assignLine.append("this->"); - assignLine.append(field.getName()); - assignLine.append(" = "); - assignLine.append(field.getName()); - } - - argLine.append(field.getName()); - thisStructLine.append(field.getName()); - if (privateMemorySize == null) { - assigns.add(assignLine.toString()); - } - argLines.add(argLine.toString()); - if (privateMemorySize != null) { - thisStructLine.append("[").append(privateMemorySize).append("]"); - } - thisStruct.add(thisStructLine.toString()); - - // Add int field into "this" struct for supporting java arraylength op - // named like foo__javaArrayLength - if (isPointer && _entryPoint.getArrayFieldArrayLengthUsed().contains(field.getName()) || isPointer && numDimensions > 1) { - - for (int i = 0; i < numDimensions; i++) { - final StringBuilder lenStructLine = new StringBuilder(); - final StringBuilder lenArgLine = new StringBuilder(); - final StringBuilder lenAssignLine = new StringBuilder(); - - String suffix = numDimensions == 1 ? "" : Integer.toString(i); - String lenName = field.getName() + BlockWriter.arrayLengthMangleSuffix + suffix; - - lenStructLine.append("int " + lenName); - - lenAssignLine.append("this->"); - lenAssignLine.append(lenName); - lenAssignLine.append(" = "); - lenAssignLine.append(lenName); - - lenArgLine.append("int " + lenName); - - assigns.add(lenAssignLine.toString()); - argLines.add(lenArgLine.toString()); - thisStruct.add(lenStructLine.toString()); - - if (numDimensions > 1) { - final StringBuilder dimStructLine = new StringBuilder(); - final StringBuilder dimArgLine = new StringBuilder(); - final StringBuilder dimAssignLine = new StringBuilder(); - String dimName = field.getName() + BlockWriter.arrayDimMangleSuffix + suffix; - - dimStructLine.append("int " + dimName); - - dimAssignLine.append("this->"); - dimAssignLine.append(dimName); - dimAssignLine.append(" = "); - dimAssignLine.append(dimName); - - dimArgLine.append("int " + dimName); - - assigns.add(dimAssignLine.toString()); - argLines.add(dimArgLine.toString()); - thisStruct.add(dimStructLine.toString()); - } + + // If it is a converted array of objects, emit the struct param + String className = null; + if (signature.startsWith("L")) { + // Turn Lcom/codegen/javalabs/opencl/demo/DummyOOA; into com_amd_javalabs_opencl_demo_DummyOOA for example + className = (signature.substring(1, signature.length() - 1)).replace('/', '_'); + // if (logger.isLoggable(Level.FINE)) { + // logger.fine("Examining object parameter: " + signature + " new: " + className); + // } + argLine.append(className); + thisStructLine.append(className); + } else { + argLine.append(convertType(ClassModel.typeName(signature.charAt(0)), false, false)); + thisStructLine.append(convertType(ClassModel.typeName(signature.charAt(0)), false, false)); } - } - } - - if (Config.enableByteWrites || _entryPoint.requiresByteAddressableStorePragma()) { - // Starting with OpenCL 1.1 (which is as far back as we support) - // this feature is part of the core, so we no longer need this pragma - if (false) { - writePragma("cl_khr_byte_addressable_store", true); - newLine(); - } - } - - boolean usesAtomics = false; - if (Config.enableAtomic32 || _entryPoint.requiresAtomic32Pragma()) { - usesAtomics = true; - writePragma("cl_khr_global_int32_base_atomics", true); - writePragma("cl_khr_global_int32_extended_atomics", true); - writePragma("cl_khr_local_int32_base_atomics", true); - writePragma("cl_khr_local_int32_extended_atomics", true); - } - - if (Config.enableAtomic64 || _entryPoint.requiresAtomic64Pragma()) { - usesAtomics = true; - writePragma("cl_khr_int64_base_atomics", true); - writePragma("cl_khr_int64_extended_atomics", true); - } - - if (usesAtomics) { - write("int atomicAdd(__global int *_arr, int _index, int _delta){"); - in(); - { - newLine(); - write("return atomic_add(&_arr[_index], _delta);"); - out(); - newLine(); - } - write("}"); - - newLine(); - } - - if (Config.enableDoubles || _entryPoint.requiresDoublePragma()) { - writePragma("cl_khr_fp64", true); - newLine(); - } - - // Emit structs for oop transformation accessors - for (final ClassModel cm : _entryPoint.getObjectArrayFieldsClasses().values()) { - final ArrayList fieldSet = cm.getStructMembers(); - if (fieldSet.size() > 0) { - final String mangledClassName = cm.getClassWeAreModelling().getName().replace('.', '_'); - newLine(); - write("typedef struct " + mangledClassName + "_s{"); - in(); - newLine(); - int totalSize = 0; - int alignTo = 0; + argLine.append(' '); + thisStructLine.append(' '); - final Iterator it = fieldSet.iterator(); - while (it.hasNext()) { - final FieldEntry field = it.next(); - final String fType = field.getNameAndTypeEntry().getDescriptorUTF8Entry().getUTF8(); - final int fSize = InstructionSet.TypeSpec.valueOf(fType.equals("Z") ? "B" : fType).getSize(); + if (isPointer) { + argLine.append('*'); + if (privateMemorySize == null) { + thisStructLine.append('*'); + } + } - if (fSize > alignTo) { - alignTo = fSize; - } - totalSize += fSize; + if (privateMemorySize == null) { + assignLine.append("this->"); + assignLine.append(field.getName()); + assignLine.append(" = "); + assignLine.append(field.getName()); + } - final String cType = convertType(field.getNameAndTypeEntry().getDescriptorUTF8Entry().getUTF8(), true, false); - assert cType != null : "could not find type for " + field.getNameAndTypeEntry().getDescriptorUTF8Entry().getUTF8(); - writeln(cType + " " + field.getNameAndTypeEntry().getNameUTF8Entry().getUTF8() + ";"); + argLine.append(field.getName()); + thisStructLine.append(field.getName()); + if (privateMemorySize == null) { + assigns.add(assignLine.toString()); } + argLines.add(argLine.toString()); + if (privateMemorySize != null) { + thisStructLine.append('[').append(privateMemorySize).append(']'); + } + thisStruct.add(thisStructLine.toString()); - // compute total size for OpenCL buffer - int totalStructSize = 0; - if ((totalSize % alignTo) == 0) { - totalStructSize = totalSize; - } else { - // Pad up if necessary - totalStructSize = ((totalSize / alignTo) + 1) * alignTo; + // Add int field into "this" struct for supporting java arraylength op + // named like foo__javaArrayLength + if (isPointer && _entryPoint.getArrayFieldArrayLengthUsed().contains(field.getName()) || isPointer && numDimensions > 1) { + + for (int i = 0; i < numDimensions; i++) { + final StringBuilder lenStructLine = new StringBuilder(); + final StringBuilder lenArgLine = new StringBuilder(); + final StringBuilder lenAssignLine = new StringBuilder(); + + String suffix = numDimensions == 1 ? "" : Integer.toString(i); + String lenName = field.getName() + BlockWriter.arrayLengthMangleSuffix + suffix; + + lenStructLine.append("int ").append(lenName); + + lenAssignLine.append("this->"); + lenAssignLine.append(lenName); + lenAssignLine.append(" = "); + lenAssignLine.append(lenName); + + lenArgLine.append("int ").append(lenName); + + assigns.add(lenAssignLine.toString()); + argLines.add(lenArgLine.toString()); + thisStruct.add(lenStructLine.toString()); + + if (numDimensions > 1) { + final StringBuilder dimStructLine = new StringBuilder(); + final StringBuilder dimArgLine = new StringBuilder(); + final StringBuilder dimAssignLine = new StringBuilder(); + String dimName = field.getName() + BlockWriter.arrayDimMangleSuffix + suffix; + + dimStructLine.append("int ").append(dimName); + + dimAssignLine.append("this->"); + dimAssignLine.append(dimName); + dimAssignLine.append(" = "); + dimAssignLine.append(dimName); + + dimArgLine.append("int ").append(dimName); + + assigns.add(dimAssignLine.toString()); + argLines.add(dimArgLine.toString()); + thisStruct.add(dimStructLine.toString()); + } + } } - if (totalStructSize > alignTo) { - while (totalSize < totalStructSize) { - // structBuffer.put((byte)-1); - writeln("char _pad_" + totalSize + ";"); - totalSize++; - } + } + + if (Config.enableByteWrites || _entryPoint.requiresByteAddressableStorePragma()) { + // Starting with OpenCL 1.1 (which is as far back as we support) + // this feature is part of the core, so we no longer need this pragma + if (false) { + writePragma("cl_khr_byte_addressable_store", true); + newLine(); + } + } + + boolean usesAtomics = false; + if (Config.enableAtomic32 || _entryPoint.requiresAtomic32Pragma()) { + usesAtomics = true; + writePragma("cl_khr_global_int32_base_atomics", true); + writePragma("cl_khr_global_int32_extended_atomics", true); + writePragma("cl_khr_local_int32_base_atomics", true); + writePragma("cl_khr_local_int32_extended_atomics", true); + } + + if (Config.enableAtomic64 || _entryPoint.requiresAtomic64Pragma()) { + usesAtomics = true; + writePragma("cl_khr_int64_base_atomics", true); + writePragma("cl_khr_int64_extended_atomics", true); + } + + if (usesAtomics) { + write("int atomicAdd(__global int *_arr, int _index, int _delta){"); + in(); + { + newLine(); + write("return atomic_add(&_arr[_index], _delta);"); + out(); + newLine(); } + write("}"); - out(); newLine(); - write("} " + mangledClassName + ";"); + } + + if (Config.enableDoubles || _entryPoint.requiresDoublePragma()) { + writePragma("cl_khr_fp64", true); newLine(); - } - } - - write("typedef struct This_s{"); - - in(); - newLine(); - for (final String line : thisStruct) { - write(line); - writeln(";"); - } - write("int passid"); - out(); - writeln(";"); - // out(); - // newLine(); - write("}This;"); - newLine(); - write("int get_pass_id(This *this){"); - in(); - { - newLine(); - write("return this->passid;"); - out(); - newLine(); - } - write("}"); - newLine(); - - for (final MethodModel mm : _entryPoint.getCalledMethods()) { - // write declaration :) - if (mm.isPrivateMemoryGetter()) { - continue; - } - - final String returnType = mm.getReturnType(); - // Arrays always map to __private or__global arrays - if (returnType.startsWith("[")) { - write(" __global "); - } - write(convertType(returnType, true, false)); - - write(mm.getName() + "("); - - if (!mm.getMethod().isStatic()) { - if ((mm.getMethod().getClassModel() == _entryPoint.getClassModel()) - || mm.getMethod().getClassModel().isSuperClass(_entryPoint.getClassModel().getClassWeAreModelling())) { - write("This *this"); - } else { - // Call to an object member or superclass of member - for (final ClassModel c : _entryPoint.getObjectArrayFieldsClasses().values()) { - if (mm.getMethod().getClassModel() == c) { - write("__global " + mm.getMethod().getClassModel().getClassWeAreModelling().getName().replace('.', '_') - + " *this"); - break; - } else if (mm.getMethod().getClassModel().isSuperClass(c.getClassWeAreModelling())) { - write("__global " + c.getClassWeAreModelling().getName().replace('.', '_') + " *this"); - break; - } - } + } + + // Emit structs for oop transformation accessors + for (final ClassModel cm : _entryPoint.getObjectArrayFieldsClasses().values()) { + final ArrayList fieldSet = cm.getStructMembers(); + if (fieldSet.size() > 0) { + final String mangledClassName = cm.clazz.getName().replace('.', '_'); + newLine(); + write("typedef struct " + mangledClassName + "_s{"); + in(); + newLine(); + + int totalSize = 0; + int alignTo = 0; + + for (FieldEntry field : fieldSet) { + final String fType = field.getNameAndTypeEntry().getDescriptorUTF8Entry().getUTF8(); + final int fSize = TypeSpec.valueOf(fType.equals("Z") ? "B" : fType).getSize(); + + if (fSize > alignTo) { + alignTo = fSize; + } + totalSize += fSize; + + final String cType = convertType(field.getNameAndTypeEntry().getDescriptorUTF8Entry().getUTF8(), true, false); + assert cType != null : "could not find type for " + field.getNameAndTypeEntry().getDescriptorUTF8Entry().getUTF8(); + writeln(cType + ' ' + field.getNameAndTypeEntry().getNameUTF8Entry().getUTF8() + ';'); + } + + // compute total size for OpenCL buffer + int totalStructSize = 0; + if ((totalSize % alignTo) == 0) { + totalStructSize = totalSize; + } else { + // Pad up if necessary + totalStructSize = ((totalSize / alignTo) + 1) * alignTo; + } + if (totalStructSize > alignTo) { + while (totalSize < totalStructSize) { + // structBuffer.put((byte)-1); + writeln("char _pad_" + totalSize + ';'); + totalSize++; + } + } + + out(); + newLine(); + write("} " + mangledClassName + ';'); + newLine(); + } + } + + write("typedef struct This_s{"); + + in(); + newLine(); + for (final String line : thisStruct) { + write(line); + writeln(";"); + } + write("int passid"); + out(); + writeln(";"); + // out(); + // newLine(); + write("}This;"); + newLine(); + write("int get_pass_id(This *this){"); + in(); + { + newLine(); + write("return this->passid;"); + out(); + newLine(); + } + write("}"); + newLine(); + + for (final MethodModel mm : _entryPoint.getCalledMethods()) { + // write declaration :) + if (mm.isPrivateMemoryGetter()) { + continue; } - } - boolean alreadyHasFirstArg = !mm.getMethod().isStatic(); + final String returnType = mm.getReturnType(); + // Arrays always map to __private or__global arrays + if (returnType.startsWith("[")) { + write(" __global "); + } + write(convertType(returnType, true, false)); + + write(mm.getName() + '('); + + if (!mm.getMethod().isStatic()) { + if ((mm.getMethod().getClassModel() == _entryPoint.getClassModel()) + || mm.getMethod().getClassModel().isSuperClass(_entryPoint.getClassModel().clazz)) { + write("This *this"); + } else { + // Call to an object member or superclass of member + for (final ClassModel c : _entryPoint.getObjectArrayFieldsClasses().values()) { + if (mm.getMethod().getClassModel() == c) { + write("__global " + mm.getMethod().getClassModel().clazz.getName().replace('.', '_') + + " *this"); + break; + } else if (mm.getMethod().getClassModel().isSuperClass(c.clazz)) { + write("__global " + c.clazz.getName().replace('.', '_') + " *this"); + break; + } + } + } + } - final LocalVariableTableEntry lvte = mm.getLocalVariableTableEntry(); - for (final LocalVariableInfo lvi : lvte) { - if ((lvi.getStart() == 0) && ((lvi.getVariableIndex() != 0) || mm.getMethod().isStatic())) { // full scope but skip this - final String descriptor = lvi.getVariableDescriptor(); - if (alreadyHasFirstArg) { - write(", "); - } + boolean alreadyHasFirstArg = !mm.getMethod().isStatic(); - if (descriptor.startsWith("[") && !lvi.getVariableName().endsWith(PRIVATE_SUFFIX)) { - write(" __global "); - } + final LocalVariableTableEntry lvte = mm.getLocalVariableTableEntry(); + for (final LocalVariableInfo lvi : lvte) { + if ((lvi.getStart() == 0) && ((lvi.getVariableIndex() != 0) || mm.getMethod().isStatic())) { // full scope but skip this + final String descriptor = lvi.getVariableDescriptor(); + if (alreadyHasFirstArg) { + write(", "); + } - write(convertType(descriptor, true, false)); - write(lvi.getVariableName()); - alreadyHasFirstArg = true; + if (descriptor.startsWith("[") && !lvi.getVariableName().endsWith(PRIVATE_SUFFIX)) { + write(" __global "); + } + + write(convertType(descriptor, true, false)); + write(lvi.getVariableName()); + alreadyHasFirstArg = true; + } } - } - write(")"); - writeMethodBody(mm); - newLine(); - } + write(")"); + writeMethodBody(mm); + newLine(); + } - write("__kernel void " + _entryPoint.getMethodModel().getSimpleName() + "("); + write("__kernel void " + _entryPoint.getMethodModel().getSimpleName() + '('); - in(); - boolean first = true; - for (final String line : argLines) { + in(); + boolean first = true; + for (final String line : argLines) { - if (first) { + if (first) { + first = false; + } else { + write(", "); + } + + newLine(); + write(line); + } + + if (first) { first = false; - } else { + } else { write(", "); - } - - newLine(); - write(line); - } - - if (first) { - first = false; - } else { - write(", "); - } - newLine(); - write("int passid"); - out(); - newLine(); - write("){"); - in(); - newLine(); - writeln("This thisStruct;"); - writeln("This* this=&thisStruct;"); - for (final String line : assigns) { - write(line); - writeln(";"); - } - write("this->passid = passid"); - writeln(";"); - - writeMethodBody(_entryPoint.getMethodModel()); - out(); - newLine(); - writeln("}"); - out(); - } - - @Override public void writeThisRef() { - write("this->"); - } - - @Override public void writeInstruction(Instruction _instruction) throws CodeGenException { - if ((_instruction instanceof I_IUSHR) || (_instruction instanceof I_LUSHR)) { - final BinaryOperator binaryInstruction = (BinaryOperator) _instruction; - final 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; - } - if (needsParenthesis) { - write("("); - } - - if (binaryInstruction instanceof I_IUSHR) { - write("((unsigned int)"); - } else { - write("((unsigned long)"); - } - writeInstruction(binaryInstruction.getLhs()); - write(")"); - write(" >> "); - writeInstruction(binaryInstruction.getRhs()); - - if (needsParenthesis) { + } + newLine(); + write("int passid"); + out(); + newLine(); + write("){"); + in(); + newLine(); + writeln("This thisStruct;"); + writeln("This* this=&thisStruct;"); + for (final String line : assigns) { + write(line); + writeln(";"); + } + write("this->passid = passid"); + writeln(";"); + + writeMethodBody(_entryPoint.getMethodModel()); + out(); + newLine(); + writeln("}"); + out(); + } + + @Override + public void writeThisRef() { + write("this->"); + } + + @Override + public void writeInstruction(Instruction _instruction) throws CodeGenException { + if ((_instruction instanceof I_IUSHR) || (_instruction instanceof I_LUSHR)) { + final BinaryOperator binaryInstruction = (BinaryOperator) _instruction; + final 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; + } + if (needsParenthesis) { + write("("); + } + + if (binaryInstruction instanceof I_IUSHR) { + write("((unsigned int)"); + } else { + write("((unsigned long)"); + } + writeInstruction(binaryInstruction.getLhs()); write(")"); - } - } else { - super.writeInstruction(_instruction); - } - } - - public static String writeToString(Entrypoint _entrypoint) throws CodeGenException { - final StringBuilder openCLStringBuilder = new StringBuilder(); - final KernelWriter openCLWriter = new KernelWriter(){ - @Override public void write(String _string) { - openCLStringBuilder.append(_string); - } - }; - try { - openCLWriter.write(_entrypoint); - } catch (final CodeGenException codeGenException) { - throw codeGenException; - }/* catch (final Throwable t) { - throw new CodeGenException(t); - }*/ - - return (openCLStringBuilder.toString()); - } + write(" >> "); + writeInstruction(binaryInstruction.getRhs()); + + if (needsParenthesis) { + write(")"); + } + } else { + super.writeInstruction(_instruction); + } + } + + public static String writeToString(Entrypoint _entrypoint) throws CodeGenException { + final StringBuilder openCLStringBuilder = new StringBuilder(); + final KernelWriter openCLWriter = new KernelWriter() { + @Override + public void write(String _string) { + openCLStringBuilder.append(_string); + } + }; + //try { + openCLWriter.write(_entrypoint); +// } catch (final CodeGenException codeGenException) { +// throw codeGenException; +// }/* catch (final Throwable t) { +// throw new CodeGenException(t); +// }*/ + + return (openCLStringBuilder.toString()); + } } diff --git a/src/main/java/com/aparapi/opencl/OpenCL.java b/src/main/java/com/aparapi/opencl/OpenCL.java index dd21a278..e31b1f7b 100644 --- a/src/main/java/com/aparapi/opencl/OpenCL.java +++ b/src/main/java/com/aparapi/opencl/OpenCL.java @@ -24,105 +24,116 @@ public interface OpenCL { - public static final String CL_KHR_FP64 = "cl_khr_fp64"; + String CL_KHR_FP64 = "cl_khr_fp64"; - public static final String CL_KHR_SELECT_FPROUNDING_MODE = "cl_khr_select_fprounding_mode"; + String CL_KHR_SELECT_FPROUNDING_MODE = "cl_khr_select_fprounding_mode"; - public static final String CL_KHR_GLOBAL_INT32_BASE_ATOMICS = "cl_khr_global_int32_base_atomics"; + String CL_KHR_GLOBAL_INT32_BASE_ATOMICS = "cl_khr_global_int32_base_atomics"; - public static final String CL_KHR_GLOBAL_INT32_EXTENDED_ATOMICS = "cl_khr_global_int32_extended_atomics"; + String CL_KHR_GLOBAL_INT32_EXTENDED_ATOMICS = "cl_khr_global_int32_extended_atomics"; - public static final String CL_KHR_LOCAL_INT32_BASE_ATOMICS = "cl_khr_local_int32_base_atomics"; + String CL_KHR_LOCAL_INT32_BASE_ATOMICS = "cl_khr_local_int32_base_atomics"; - public static final String CL_KHR_LOCAL_INT32_EXTENDED_ATOMICS = "cl_khr_local_int32_extended_atomics"; + String CL_KHR_LOCAL_INT32_EXTENDED_ATOMICS = "cl_khr_local_int32_extended_atomics"; - public static final String CL_KHR_INT64_BASE_ATOMICS = "cl_khr_int64_base_atomics"; + String CL_KHR_INT64_BASE_ATOMICS = "cl_khr_int64_base_atomics"; - public static final String CL_KHR_INT64_EXTENDED_ATOMICS = "cl_khr_int64_extended_atomics"; + String CL_KHR_INT64_EXTENDED_ATOMICS = "cl_khr_int64_extended_atomics"; - public static final String CL_KHR_3D_IMAGE_WRITES = "cl_khr_3d_image_writes"; + String CL_KHR_3D_IMAGE_WRITES = "cl_khr_3d_image_writes"; - public static final String CL_KHR_BYTE_ADDRESSABLE_SUPPORT = "cl_khr_byte_addressable_store"; + String CL_KHR_BYTE_ADDRESSABLE_SUPPORT = "cl_khr_byte_addressable_store"; - public static final String CL_KHR_FP16 = "cl_khr_fp16"; + String CL_KHR_FP16 = "cl_khr_fp16"; - public static final String CL_KHR_GL_SHARING = "cl_khr_gl_sharing"; + String CL_KHR_GL_SHARING = "cl_khr_gl_sharing"; - @Target(ElementType.PARAMETER) @Retention(RetentionPolicy.RUNTIME) public @interface Put { + @Target(ElementType.PARAMETER) @Retention(RetentionPolicy.RUNTIME) + @interface Put { } - @Target(ElementType.PARAMETER) @Retention(RetentionPolicy.RUNTIME) public @interface Get { + @Target(ElementType.PARAMETER) @Retention(RetentionPolicy.RUNTIME) + @interface Get { } - @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) public @interface Source { + @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) + @interface Source { String value(); } - @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) public @interface Resource { + @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) + @interface Resource { String value(); } - @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface Kernel { + @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) + @interface Kernel { String value(); } - @Target(ElementType.PARAMETER) @Retention(RetentionPolicy.RUNTIME) public @interface Arg { + @Target(ElementType.PARAMETER) @Retention(RetentionPolicy.RUNTIME) + @interface Arg { String value(); } - @Target(ElementType.PARAMETER) @Retention(RetentionPolicy.RUNTIME) public @interface GlobalReadWrite { + @Target(ElementType.PARAMETER) @Retention(RetentionPolicy.RUNTIME) + @interface GlobalReadWrite { String value(); } - @Target(ElementType.PARAMETER) @Retention(RetentionPolicy.RUNTIME) public @interface GlobalReadOnly { + @Target(ElementType.PARAMETER) @Retention(RetentionPolicy.RUNTIME) + @interface GlobalReadOnly { String value(); } - @Target(ElementType.PARAMETER) @Retention(RetentionPolicy.RUNTIME) public @interface GlobalWriteOnly { + @Target(ElementType.PARAMETER) @Retention(RetentionPolicy.RUNTIME) + @interface GlobalWriteOnly { String value(); } - @Target(ElementType.PARAMETER) @Retention(RetentionPolicy.RUNTIME) public @interface Local { + @Target(ElementType.PARAMETER) @Retention(RetentionPolicy.RUNTIME) + @interface Local { String value(); } - @Target(ElementType.PARAMETER) @Retention(RetentionPolicy.RUNTIME) public @interface Constant { + @Target(ElementType.PARAMETER) @Retention(RetentionPolicy.RUNTIME) + @interface Constant { String value(); } - public T put(float[] array); + T put(float[] array); - public T put(int[] array); + T put(int[] array); - public T put(short[] array); + T put(short[] array); - public T put(byte[] array); + T put(byte[] array); - public T put(char[] array); + T put(char[] array); - public T put(boolean[] array); + T put(boolean[] array); - public T put(double[] array); + T put(double[] array); - public T get(float[] array); + T get(float[] array); - public T get(int[] array); + T get(int[] array); - public T get(short[] array); + T get(short[] array); - public T get(char[] array); + T get(char[] array); - public T get(boolean[] array); + T get(boolean[] array); - public T get(double[] array); + T get(double[] array); - public T get(byte[] array); + T get(byte[] array); - public T begin(); + T begin(); - public T end(); + T end(); - public T dispose(); + T dispose(); - public List getProfileInfo(); + List getProfileInfo(); } diff --git a/src/main/java/com/aparapi/opencl/OpenCLAdapter.java b/src/main/java/com/aparapi/opencl/OpenCLAdapter.java index 95bb104f..da2d6b1d 100644 --- a/src/main/java/com/aparapi/opencl/OpenCLAdapter.java +++ b/src/main/java/com/aparapi/opencl/OpenCLAdapter.java @@ -21,76 +21,94 @@ public class OpenCLAdapter implements OpenCL{ + @Override @SuppressWarnings("unchecked") public T put(byte[] array) { return ((T) this); } + @Override @SuppressWarnings("unchecked") public T get(byte[] array) { return ((T) this); } + @Override @SuppressWarnings("unchecked") public T put(float[] array) { return ((T) this); } + @Override @SuppressWarnings("unchecked") public T put(int[] array) { return ((T) this); } + @Override @SuppressWarnings("unchecked") public T put(short[] array) { return ((T) this); } + @Override @SuppressWarnings("unchecked") public T put(char[] array) { return ((T) this); } + @Override @SuppressWarnings("unchecked") public T put(boolean[] array) { return ((T) this); } + @Override @SuppressWarnings("unchecked") public T put(double[] array) { return ((T) this); } + @Override @SuppressWarnings("unchecked") public T get(float[] array) { return ((T) this); } + @Override @SuppressWarnings("unchecked") public T get(int[] array) { return ((T) this); } + @Override @SuppressWarnings("unchecked") public T get(short[] array) { return ((T) this); } + @Override @SuppressWarnings("unchecked") public T get(char[] array) { return ((T) this); } + @Override @SuppressWarnings("unchecked") public T get(boolean[] array) { return ((T) this); } + @Override @SuppressWarnings("unchecked") public T get(double[] array) { return ((T) this); } + @Override @SuppressWarnings("unchecked") public T begin() { return ((T) this); } + @Override @SuppressWarnings("unchecked") public T end() { return ((T) this); } + @Override @SuppressWarnings("unchecked") public T dispose() { return ((T) this); } + @Override public List getProfileInfo(){ - return(new ArrayList()); + return(new ArrayList<>()); } } diff --git a/src/main/java/com/aparapi/util/swing/MultiPassKernelSwingWorker.java b/src/main/java/com/aparapi/util/swing/MultiPassKernelSwingWorker.java index d9d51c94..e5618639 100644 --- a/src/main/java/com/aparapi/util/swing/MultiPassKernelSwingWorker.java +++ b/src/main/java/com/aparapi/util/swing/MultiPassKernelSwingWorker.java @@ -13,87 +13,98 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.aparapi.util.swing; - -import com.aparapi.Kernel; -import com.aparapi.internal.kernel.KernelRunner; - -import javax.swing.*; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; - -/** - * Implementation of SwingWorker to assist in progress tracking and cancellation of multi-pass {@link Kernel}s. - */ -public abstract class MultiPassKernelSwingWorker extends SwingWorker{ - - public static final int DEFAULT_POLL_INTERVAL = 50; - - private Kernel kernel; - private Timer timer; - - protected MultiPassKernelSwingWorker(Kernel kernel) { - this.kernel = kernel; - } - - /** Utility method which just invokes {@link Kernel#cancelMultiPass()} on the executing kernel. */ - public void cancelExecution() { - kernel.cancelMultiPass(); - } - - /** This method must invoke one of the {@code kernel}'s execute() methods. */ - protected abstract void executeKernel(Kernel kernel); - - /** This method, which is always invoked on the swing event dispatch thread, should be used to update any components (such as a {@link javax.swing.JProgressBar}) so - * as to reflect the progress of the multi-pass Kernel being executed. - * - * @param passId The passId for the Kernel's current pass, or one of the constant fields returnable by {@link KernelRunner#getCurrentPass()}. - */ - protected abstract void updatePassId(int passId); - - /** Executes the {@link #kernel} via {@link #executeKernel(Kernel)}, whilst also managing progress updates for the kernel's passId. */ - @Override - protected final Void doInBackground() throws Exception { - try { - setUpExecution(); - executeKernel(kernel); - return null; - } - finally { - cleanUpExecution(); - } - } - - private void setUpExecution() { - ActionListener listener = new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - updatePassId(); - } - }; - timer = new Timer(getPollIntervalMillis(), listener); - timer.setCoalesce(false); - timer.start(); - } - - private void cleanUpExecution() { - timer.stop(); - timer = null; - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - updatePassId(KernelRunner.PASS_ID_COMPLETED_EXECUTION); - } - }); - } - - private void updatePassId() { - int progress = kernel.getCurrentPass(); - updatePassId(progress); - } - - /** The interval at which the Kernel's current passId is polled. Unless overridden, returns {@link #DEFAULT_POLL_INTERVAL}. */ - protected int getPollIntervalMillis() { - return DEFAULT_POLL_INTERVAL; - } -} +///** +// * Copyright (c) 2016 - 2017 Syncleus, Inc. +// * +// * Licensed under the Apache License, Version 2.0 (the "License"); +// * you may not use this file except in compliance with the License. +// * You may obtain a copy of the License at +// * +// * http://www.apache.org/licenses/LICENSE-2.0 +// * +// * Unless required by applicable law or agreed to in writing, software +// * distributed under the License is distributed on an "AS IS" BASIS, +// * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// * See the License for the specific language governing permissions and +// * limitations under the License. +// */ +//package com.aparapi.util.swing; +// +//import com.aparapi.Kernel; +//import com.aparapi.internal.kernel.KernelRunner; +// +//import javax.swing.*; +//import java.awt.event.ActionEvent; +//import java.awt.event.ActionListener; +// +///** +// * Implementation of SwingWorker to assist in progress tracking and cancellation of multi-pass {@link Kernel}s. +// */ +//public abstract class MultiPassKernelSwingWorker extends SwingWorker{ +// +// public static final int DEFAULT_POLL_INTERVAL = 50; +// +// private Kernel kernel; +// private Timer timer; +// +// protected MultiPassKernelSwingWorker(Kernel kernel) { +// this.kernel = kernel; +// } +// +// +// /** This method must invoke one of the {@code kernel}'s execute() methods. */ +// protected abstract void executeKernel(Kernel kernel); +// +// /** This method, which is always invoked on the swing event dispatch thread, should be used to update any components (such as a {@link javax.swing.JProgressBar}) so +// * as to reflect the progress of the multi-pass Kernel being executed. +// * +// * @param passId The passId for the Kernel's current pass, or one of the constant fields returnable by {@link KernelRunner#getCurrentPass()}. +// */ +// protected abstract void updatePassId(int passId); +// +// /** Executes the {@link #kernel} via {@link #executeKernel(Kernel)}, whilst also managing progress updates for the kernel's passId. */ +// @Override +// protected final Void doInBackground() throws Exception { +// try { +// setUpExecution(); +// executeKernel(kernel); +// return null; +// } +// finally { +// cleanUpExecution(); +// } +// } +// +// private void setUpExecution() { +// ActionListener listener = new ActionListener() { +// @Override +// public void actionPerformed(ActionEvent e) { +// updatePassId(); +// } +// }; +// timer = new Timer(getPollIntervalMillis(), listener); +// timer.setCoalesce(false); +// timer.start(); +// } +// +// private void cleanUpExecution() { +// timer.stop(); +// timer = null; +// SwingUtilities.invokeLater(new Runnable() { +// @Override +// public void run() { +// updatePassId(KernelRunner.PASS_ID_COMPLETED_EXECUTION); +// } +// }); +// } +// +// private void updatePassId() { +// int progress = kernel.getCurrentPass(); +// updatePassId(progress); +// } +// +// /** The interval at which the Kernel's current passId is polled. Unless overridden, returns {@link #DEFAULT_POLL_INTERVAL}. */ +// protected int getPollIntervalMillis() { +// return DEFAULT_POLL_INTERVAL; +// } +//} diff --git a/src/test/java/com/aparapi/ConvolutionLargeTest.java b/src/test/java/com/aparapi/ConvolutionLargeTest.java index 291941cf..cefd66d3 100644 --- a/src/test/java/com/aparapi/ConvolutionLargeTest.java +++ b/src/test/java/com/aparapi/ConvolutionLargeTest.java @@ -18,7 +18,6 @@ import java.text.MessageFormat; import java.util.concurrent.TimeUnit; -import com.aparapi.Kernel; import com.aparapi.internal.model.CacheEnabler; import com.aparapi.internal.model.Supplier; import org.junit.Test; @@ -62,21 +61,13 @@ public void testConvolutionLarge() { @Override public Supplier getSupplier() { - return new Supplier() { - @Override - public ImageConvolution get() { - return convolution; - } - }; + return () -> convolution; } @Override public Consumer getDisposer() { - return new Consumer() { - @Override - public void accept(ImageConvolution k) { - // Do nothing - } + return k -> { + // Do nothing }; } @@ -93,22 +84,12 @@ public String getName() { testWithSupplier(new ImageConvolutionCreationContext() { @Override public Supplier getSupplier() { - return new Supplier() { - @Override - public ImageConvolution get() { - return new ImageConvolution(); - } - }; + return ImageConvolution::new; } @Override public Consumer getDisposer() { - return new Consumer() { - @Override - public void accept(ImageConvolution k) { - k.dispose(); - } - }; + return Kernel::dispose; } @Override @@ -160,7 +141,7 @@ private long doTest(String name, int seconds, ImageConvolutionCreationContext im long totalTime = 0; Supplier imageConvolutionSupplier = imageConvolutionCreationContext.getSupplier(); Consumer disposer = imageConvolutionCreationContext.getDisposer(); - System.out.print("\tTesting " + name + "[" + imageConvolutionCreationContext.getName() + "] (" + seconds + " seconds) "); + System.out.print("\tTesting " + name + '[' + imageConvolutionCreationContext.getName() + "] (" + seconds + " seconds) "); int calls = 0; long initialTime = System.nanoTime(); long maxElapsedNs = TimeUnit.SECONDS.toNanos(seconds); diff --git a/src/test/java/com/aparapi/codegen/CodeGenJUnitBase.java b/src/test/java/com/aparapi/codegen/CodeGenJUnitBase.java index 0fee2c06..aab20234 100644 --- a/src/test/java/com/aparapi/codegen/CodeGenJUnitBase.java +++ b/src/test/java/com/aparapi/codegen/CodeGenJUnitBase.java @@ -54,6 +54,7 @@ to national security controls as identified on the Commerce Control List (curren import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; import java.util.Arrays; @@ -116,7 +117,7 @@ protected void test(Class _class, Class _expected assertEquals(_class.getSimpleName(), Arrays.toString(expectedOpenCL), actual); } } else { - assertTrue("Expected exception " + _expectedExceptionType + " Instead we got {\n" + actual + "\n}", false); + fail("Expected exception " + _expectedExceptionType + " Instead we got {\n" + actual + "\n}"); } } catch (AssertionError e) { diff --git a/src/test/java/com/aparapi/codegen/CreateJUnitTest.java b/src/test/java/com/aparapi/codegen/CreateJUnitTest.java index 070ce8bc..035e2d18 100644 --- a/src/test/java/com/aparapi/codegen/CreateJUnitTest.java +++ b/src/test/java/com/aparapi/codegen/CreateJUnitTest.java @@ -72,7 +72,7 @@ public void test() throws ClassNotFoundException, FileNotFoundException, IOExcep File testDir = new File(sourceDir, testPackageName.replace(".", "/")); System.out.println(testDir.getCanonicalPath()); - List classNames = new ArrayList(); + List classNames = new ArrayList<>(); for (File sourceFile : testDir.listFiles(new FilenameFilter() { @Override @@ -91,7 +91,7 @@ public boolean accept(File dir, String name) { for (String className : classNames) { - Source source = new Source(Class.forName(testPackageName + "." + className), sourceDir); + Source source = new Source(Class.forName(testPackageName + '.' + className), sourceDir); final String testName = className + "Test"; @@ -104,7 +104,7 @@ public boolean accept(File dir, String name) { sb.append(doc); sb.append("\n */\n"); } - sb.append("public class " + testName + " extends com.codegen.CodeGenJUnitBase{\n"); + sb.append("public class ").append(testName).append(" extends com.codegen.CodeGenJUnitBase{\n"); appendExpectedOpenCL(source, sb); appendExpectedExceptions(source, sb); appendTest(testPackageName, testName, "", sb); @@ -122,8 +122,8 @@ public boolean accept(File dir, String name) { } private static void appendTest(String testPackageName, String className, String suffix, StringBuilder sb) { - sb.append(" @Test public void " + className + suffix + "(){\n"); - sb.append(" test(" + testPackageName + "." + className + ".class, expectedException, expectedOpenCL);\n"); + sb.append(" @Test public void ").append(className).append(suffix).append("(){\n"); + sb.append(" test(").append(testPackageName).append('.').append(className).append(".class, expectedException, expectedOpenCL);\n"); sb.append(" }\n"); } @@ -132,7 +132,7 @@ private static void appendExpectedExceptions(Source source, StringBuilder sb) { if (exceptions.length() > 0) { sb.append(" private static final Class expectedException = "); - sb.append("com.codegen.internal.exception." + exceptions + ".class"); + sb.append("com.codegen.internal.exception.").append(exceptions).append(".class"); sb.append(";\n"); } else { sb.append(" private static final Class expectedException = null;\n"); @@ -146,7 +146,7 @@ private static void appendExpectedOpenCL(Source source, StringBuilder sb) { for (List opencl : source.getOpenCL()) { sb.append(" \"\"\n"); for (String line : opencl) { - sb.append(" +\"" + line + "\\n\"\n"); + sb.append(" +\"").append(line).append("\\n\"\n"); } sb.append(" ,\n"); } diff --git a/src/test/java/com/aparapi/codegen/Diff.java b/src/test/java/com/aparapi/codegen/Diff.java index 5a48f633..ce3db81c 100644 --- a/src/test/java/com/aparapi/codegen/Diff.java +++ b/src/test/java/com/aparapi/codegen/Diff.java @@ -69,7 +69,7 @@ static int[] hash(String[] lines) { static void costDiag(List[][] flags, int x, int y) { if (x == 0 || y == 0 || flags[x - 1][y - 1] == null) { if (x < (flags.length - 2) && y < (flags[0].length - 2)) { - flags[x][y] = new ArrayList(); + flags[x][y] = new ArrayList<>(); flags[x][y].add(new Point(x, y)); } } else { @@ -117,22 +117,22 @@ public void extend(int _lhsTo, int _rhsTo) { public String toString(String[] _lhs, String[] _rhs) { StringBuilder sb = new StringBuilder(); - sb.append(type).append("\n"); + sb.append(type).append('\n'); switch (type) { case SAME: for (int i = lhsFrom; i <= lhsTo; i++) { - sb.append(" ==" + _lhs[i]).append("\n"); + sb.append(" ==").append(_lhs[i]).append('\n'); } break; case LEFT: for (int i = lhsFrom; i <= lhsTo; i++) { - sb.append(" <" + _lhs[i]).append("\n"); + sb.append(" <").append(_lhs[i]).append('\n'); } break; case RIGHT: for (int i = rhsFrom; i <= rhsTo; i++) { - sb.append(" >" + _rhs[i]).append("\n"); + sb.append(" >").append(_rhs[i]).append('\n'); } break; } @@ -141,7 +141,7 @@ public String toString(String[] _lhs, String[] _rhs) { } - List blocks = new ArrayList(); + List blocks = new ArrayList<>(); private String[] rhs; @@ -179,7 +179,7 @@ public String[] getRhs() { public String toString() { StringBuilder sb = new StringBuilder(); for (Block block : blocks) { - sb.append(block.toString(lhs, rhs)).append("\n"); + sb.append(block.toString(lhs, rhs)).append('\n'); } return (sb.toString()); } diff --git a/src/test/java/com/aparapi/codegen/Source.java b/src/test/java/com/aparapi/codegen/Source.java index c5b44d13..78e36ff7 100644 --- a/src/test/java/com/aparapi/codegen/Source.java +++ b/src/test/java/com/aparapi/codegen/Source.java @@ -55,7 +55,6 @@ to national security controls as identified on the Commerce Control List (curren import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; -import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; @@ -87,19 +86,19 @@ enum STATE { Source.STATE state = STATE.NONE; - List all = new ArrayList(); + List all = new ArrayList<>(); - List> opencl = new ArrayList>(); + List> opencl = new ArrayList<>(); - List doc = new ArrayList(); + List doc = new ArrayList<>(); - List java = new ArrayList(); + List java = new ArrayList<>(); - List exceptions = new ArrayList(); + List exceptions = new ArrayList<>(); public Source(Class _clazz, File _rootDir) { clazz = _clazz; - String srcName = clazz.getPackage().getName().replace(".", "/") + "/" + clazz + ".java"; + String srcName = clazz.getPackage().getName().replace(".", "/") + '/' + clazz + ".java"; file = new File(_rootDir, srcName); try { BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file))); @@ -113,7 +112,7 @@ public Source(Class _clazz, File _rootDir) { case JAVA: if (trimmedLine.equals(OpenCLStart)) { state = STATE.OPENCL; - openclSection = new ArrayList(); + openclSection = new ArrayList<>(); opencl.add(openclSection); } else if (trimmedLine.startsWith(ThrowsStart) && trimmedLine.endsWith(ThrowsEnd)) { @@ -141,9 +140,6 @@ public Source(Class _clazz, File _rootDir) { } } - } catch (FileNotFoundException e) { - // TODO Auto-generated catch block - e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); @@ -151,12 +147,15 @@ public Source(Class _clazz, File _rootDir) { } - private String listToString(List list) { - StringBuilder stringBuilder = new StringBuilder(); - for (String line : list) { - stringBuilder.append(line).append("\n"); - } - return (stringBuilder.toString().trim()); + private static String listToString(List list) { + StringBuilder sb = new StringBuilder(); + for (int i = 0, listSize = list.size(); i < listSize; i++) { + String line = list.get(i); + sb.append(line); + if (i < listSize-1) + sb.append('\n'); + } + return sb.toString(); } public String getOpenCLString(int _index) { diff --git a/src/test/java/com/aparapi/codegen/SwingDiff.java b/src/test/java/com/aparapi/codegen/SwingDiff.java index 0b431359..92b5d8a5 100644 --- a/src/test/java/com/aparapi/codegen/SwingDiff.java +++ b/src/test/java/com/aparapi/codegen/SwingDiff.java @@ -99,9 +99,9 @@ public SwingDiff(Diff.DiffResult result) { // Create and add the style final Style rootStyle = sc.addStyle("Root", null); rootStyle.addAttribute(StyleConstants.Foreground, Color.black); - rootStyle.addAttribute(StyleConstants.FontSize, new Integer(12)); + rootStyle.addAttribute(StyleConstants.FontSize, 12); rootStyle.addAttribute(StyleConstants.FontFamily, "serif"); - rootStyle.addAttribute(StyleConstants.Bold, new Boolean(false)); + rootStyle.addAttribute(StyleConstants.Bold, Boolean.FALSE); final Style heading1Style = sc.addStyle("Heading1", rootStyle); heading1Style.addAttribute(StyleConstants.Foreground, Color.blue); @@ -134,19 +134,7 @@ public SwingDiff(Diff.DiffResult result) { frame.getContentPane().add(panel); frame.pack(); frame.setVisible(true); - } catch (ClassNotFoundException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (InstantiationException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IllegalAccessException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (UnsupportedLookAndFeelException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (BadLocationException e) { + } catch (ClassNotFoundException | BadLocationException | UnsupportedLookAndFeelException | IllegalAccessException | InstantiationException e) { // TODO Auto-generated catch block e.printStackTrace(); } @@ -166,7 +154,7 @@ public static void main(String[] args) { private static String arrayToString(String[] array) { StringBuilder stringBuilder = new StringBuilder(); for (String line : array) { - stringBuilder.append(line).append("\n"); + stringBuilder.append(line).append('\n'); } return (stringBuilder.toString().trim()); } @@ -175,15 +163,12 @@ private static String[] getFileContents(String string) { String[] content = null; try { BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(string))); - List lines = new ArrayList(); + List lines = new ArrayList<>(); for (String line = reader.readLine(); line != null; line = reader.readLine()) { lines.add(line); } reader.close(); - content = lines.toArray(new String[0]); - } catch (FileNotFoundException e) { - // TODO Auto-generated catch block - e.printStackTrace(); + content = lines.toArray(new String[lines.size()]); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); @@ -198,13 +183,10 @@ private static String getFileContent(String string) { BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(string))); StringBuilder sb = new StringBuilder(); for (String line = reader.readLine(); line != null; line = reader.readLine()) { - sb.append(line).append("\n"); + sb.append(line).append('\n'); } reader.close(); content = sb.toString(); - } catch (FileNotFoundException e) { - // TODO Auto-generated catch block - e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); diff --git a/src/test/java/com/aparapi/codegen/test/Access2DIntArrayTest.java b/src/test/java/com/aparapi/codegen/test/Access2DIntArrayTest.java index 4cc93f54..3b8cb04e 100644 --- a/src/test/java/com/aparapi/codegen/test/Access2DIntArrayTest.java +++ b/src/test/java/com/aparapi/codegen/test/Access2DIntArrayTest.java @@ -50,7 +50,7 @@ public class Access2DIntArrayTest extends com.aparapi.codegen.CodeGenJUnitBase { " return;\n" + " }\n" + "}\n" + - "\n"}; + '\n'}; private static final Class expectedException = null; @Test diff --git a/src/test/java/com/aparapi/codegen/test/AccessBooleanArrayTest.java b/src/test/java/com/aparapi/codegen/test/AccessBooleanArrayTest.java index 3c385b0b..d1142ac9 100644 --- a/src/test/java/com/aparapi/codegen/test/AccessBooleanArrayTest.java +++ b/src/test/java/com/aparapi/codegen/test/AccessBooleanArrayTest.java @@ -44,7 +44,7 @@ public class AccessBooleanArrayTest extends com.aparapi.codegen.CodeGenJUnitBase " return;\n" + " }\n" + "}\n" + - "\n"}; + '\n'}; private static final Class expectedException = null; @Test diff --git a/src/test/java/com/aparapi/codegen/test/AccessByteArrayTest.java b/src/test/java/com/aparapi/codegen/test/AccessByteArrayTest.java index be92c00d..5b74c714 100644 --- a/src/test/java/com/aparapi/codegen/test/AccessByteArrayTest.java +++ b/src/test/java/com/aparapi/codegen/test/AccessByteArrayTest.java @@ -40,7 +40,7 @@ public class AccessByteArrayTest extends com.aparapi.codegen.CodeGenJUnitBase { " return;\n" + " }\n" + "}\n" + - "\n"}; + '\n'}; private static final Class expectedException = null; @Test diff --git a/src/test/java/com/aparapi/codegen/test/AccessDoubleArrayTest.java b/src/test/java/com/aparapi/codegen/test/AccessDoubleArrayTest.java index 8c43a995..1e329c83 100644 --- a/src/test/java/com/aparapi/codegen/test/AccessDoubleArrayTest.java +++ b/src/test/java/com/aparapi/codegen/test/AccessDoubleArrayTest.java @@ -19,7 +19,7 @@ public class AccessDoubleArrayTest extends com.aparapi.codegen.CodeGenJUnitBase { private static final String[] expectedOpenCL = {"#pragma OPENCL EXTENSION cl_khr_fp64 : enable\n" + - "\n" + + '\n' + "typedef struct This_s{\n" + " __global double *doubles;\n" + " int passid;\n" + @@ -42,7 +42,7 @@ public class AccessDoubleArrayTest extends com.aparapi.codegen.CodeGenJUnitBase " return;\n" + " }\n" + "}\n" + - "\n"}; + '\n'}; private static final Class expectedException = null; @Test diff --git a/src/test/java/com/aparapi/codegen/test/AccessFloatArrayTest.java b/src/test/java/com/aparapi/codegen/test/AccessFloatArrayTest.java index c6cadebc..85d81298 100644 --- a/src/test/java/com/aparapi/codegen/test/AccessFloatArrayTest.java +++ b/src/test/java/com/aparapi/codegen/test/AccessFloatArrayTest.java @@ -40,7 +40,7 @@ public class AccessFloatArrayTest extends com.aparapi.codegen.CodeGenJUnitBase { " return;\n" + " }\n" + "}\n" + - "\n"}; + '\n'}; private static final Class expectedException = null; @Test diff --git a/src/test/java/com/aparapi/codegen/test/AccessIntArrayTest.java b/src/test/java/com/aparapi/codegen/test/AccessIntArrayTest.java index 5d405c12..439be278 100644 --- a/src/test/java/com/aparapi/codegen/test/AccessIntArrayTest.java +++ b/src/test/java/com/aparapi/codegen/test/AccessIntArrayTest.java @@ -40,7 +40,7 @@ public class AccessIntArrayTest extends com.aparapi.codegen.CodeGenJUnitBase { " return;\n" + " }\n" + "}\n" + - "\n"}; + '\n'}; private static final Class expectedException = null; @Test diff --git a/src/test/java/com/aparapi/codegen/test/AccessLongArrayTest.java b/src/test/java/com/aparapi/codegen/test/AccessLongArrayTest.java index c8846eda..b07f5ae3 100644 --- a/src/test/java/com/aparapi/codegen/test/AccessLongArrayTest.java +++ b/src/test/java/com/aparapi/codegen/test/AccessLongArrayTest.java @@ -40,7 +40,7 @@ public class AccessLongArrayTest extends com.aparapi.codegen.CodeGenJUnitBase { " return;\n" + " }\n" + "}\n" + - "\n"}; + '\n'}; private static final Class expectedException = null; @Test diff --git a/src/test/java/com/aparapi/codegen/test/AccessNested2DIntArrayTest.java b/src/test/java/com/aparapi/codegen/test/AccessNested2DIntArrayTest.java index e3336f37..371a5f85 100644 --- a/src/test/java/com/aparapi/codegen/test/AccessNested2DIntArrayTest.java +++ b/src/test/java/com/aparapi/codegen/test/AccessNested2DIntArrayTest.java @@ -53,7 +53,7 @@ public class AccessNested2DIntArrayTest extends com.aparapi.codegen.CodeGenJUnit " return;\n" + " }\n" + "}\n" + - "\n"}; + '\n'}; private static final Class expectedException = null; @Test diff --git a/src/test/java/com/aparapi/codegen/test/AccessShortArrayTest.java b/src/test/java/com/aparapi/codegen/test/AccessShortArrayTest.java index 323ed934..4c39d6c5 100644 --- a/src/test/java/com/aparapi/codegen/test/AccessShortArrayTest.java +++ b/src/test/java/com/aparapi/codegen/test/AccessShortArrayTest.java @@ -40,7 +40,7 @@ public class AccessShortArrayTest extends com.aparapi.codegen.CodeGenJUnitBase { " return;\n" + " }\n" + "}\n" + - "\n"}; + '\n'}; private static final Class expectedException = null; @Test diff --git a/src/test/java/com/aparapi/codegen/test/AndOrAndPrecedenceTest.java b/src/test/java/com/aparapi/codegen/test/AndOrAndPrecedenceTest.java index 2103e27b..b8176fdf 100644 --- a/src/test/java/com/aparapi/codegen/test/AndOrAndPrecedenceTest.java +++ b/src/test/java/com/aparapi/codegen/test/AndOrAndPrecedenceTest.java @@ -41,7 +41,7 @@ public class AndOrAndPrecedenceTest extends com.aparapi.codegen.CodeGenJUnitBase " }\n" + " return;\n" + " }\n" + -"}"}; + '}'}; private static final Class expectedException = null; @Test diff --git a/src/test/java/com/aparapi/codegen/test/AndOrPrecedence2Test.java b/src/test/java/com/aparapi/codegen/test/AndOrPrecedence2Test.java index bee966f1..b6514d27 100644 --- a/src/test/java/com/aparapi/codegen/test/AndOrPrecedence2Test.java +++ b/src/test/java/com/aparapi/codegen/test/AndOrPrecedence2Test.java @@ -41,7 +41,7 @@ public class AndOrPrecedence2Test extends com.aparapi.codegen.CodeGenJUnitBase { " }\n" + " return;\n" + " }\n" + -"}"}; + '}'}; private static final Class expectedException = null; @Test diff --git a/src/test/java/com/aparapi/codegen/test/AndOrPrecedenceTest.java b/src/test/java/com/aparapi/codegen/test/AndOrPrecedenceTest.java index 9d36028f..6cd9cad8 100644 --- a/src/test/java/com/aparapi/codegen/test/AndOrPrecedenceTest.java +++ b/src/test/java/com/aparapi/codegen/test/AndOrPrecedenceTest.java @@ -40,7 +40,7 @@ public class AndOrPrecedenceTest extends com.aparapi.codegen.CodeGenJUnitBase { " }\n" + " return;\n" + " }\n" + -"}"}; + '}'}; private static final Class expectedException = null; diff --git a/src/test/java/com/aparapi/codegen/test/ArbitraryScope2Test.java b/src/test/java/com/aparapi/codegen/test/ArbitraryScope2Test.java index 212f2018..71b321b9 100644 --- a/src/test/java/com/aparapi/codegen/test/ArbitraryScope2Test.java +++ b/src/test/java/com/aparapi/codegen/test/ArbitraryScope2Test.java @@ -27,7 +27,7 @@ public class ArbitraryScope2Test extends com.aparapi.codegen.CodeGenJUnitBase { " int get_pass_id(This *this){\n" + " return this->passid;\n" + " }\n" + -"\n" + + '\n' + " __kernel void run(\n" + " int width,\n" + " float scale,\n" + diff --git a/src/test/java/com/aparapi/codegen/test/ArbitraryScopeSimpleTest.java b/src/test/java/com/aparapi/codegen/test/ArbitraryScopeSimpleTest.java index af73ce36..ad64e790 100644 --- a/src/test/java/com/aparapi/codegen/test/ArbitraryScopeSimpleTest.java +++ b/src/test/java/com/aparapi/codegen/test/ArbitraryScopeSimpleTest.java @@ -20,13 +20,13 @@ public class ArbitraryScopeSimpleTest extends com.aparapi.codegen.CodeGenJUnitBase { private static final String[] expectedOpenCL = { "typedef struct This_s{\n" + -"\n" + + '\n' + " int passid;\n" + " }This;\n" + " int get_pass_id(This *this){\n" + " return this->passid;\n" + " }\n" + -"\n" + + '\n' + " __kernel void run(\n" + " int passid\n" + " ){\n" + diff --git a/src/test/java/com/aparapi/codegen/test/ArbitraryScopeTest.java b/src/test/java/com/aparapi/codegen/test/ArbitraryScopeTest.java index 367d9720..ef1252ae 100644 --- a/src/test/java/com/aparapi/codegen/test/ArbitraryScopeTest.java +++ b/src/test/java/com/aparapi/codegen/test/ArbitraryScopeTest.java @@ -25,13 +25,13 @@ public class ArbitraryScopeTest extends com.aparapi.codegen.CodeGenJUnitBase { + " int width;\n" + " float scale;\n" + " int maxIterations;\n" - + "\n" + + '\n' + " int passid;\n" + " }This;\n" + " int get_pass_id(This *this){\n" + " return this->passid;\n" + " }\n" - + "\n" + + '\n' + " __kernel void run(\n" + " int width,\n" + " float scale,\n" @@ -74,7 +74,7 @@ public class ArbitraryScopeTest extends com.aparapi.codegen.CodeGenJUnitBase { + " return;\n" + " }\n" + " }\n" - + " "}; + + ' '}; private static final Class expectedException = null; @Ignore diff --git a/src/test/java/com/aparapi/codegen/test/ArrayTortureIssue35Test.java b/src/test/java/com/aparapi/codegen/test/ArrayTortureIssue35Test.java index 3eb48358..5b3fa3bf 100644 --- a/src/test/java/com/aparapi/codegen/test/ArrayTortureIssue35Test.java +++ b/src/test/java/com/aparapi/codegen/test/ArrayTortureIssue35Test.java @@ -27,7 +27,7 @@ public class ArrayTortureIssue35Test extends com.aparapi.codegen.CodeGenJUnitBas " int get_pass_id(This *this){\n" + " return this->passid;\n" + " }\n" + -"\n" + + '\n' + " __kernel void run(\n" + " __global int *a,\n" + " __global int *b,\n" + diff --git a/src/test/java/com/aparapi/codegen/test/AssignAndPassAsParameterTest.java b/src/test/java/com/aparapi/codegen/test/AssignAndPassAsParameterTest.java index 2a18a958..50db46c4 100644 --- a/src/test/java/com/aparapi/codegen/test/AssignAndPassAsParameterTest.java +++ b/src/test/java/com/aparapi/codegen/test/AssignAndPassAsParameterTest.java @@ -28,7 +28,7 @@ public class AssignAndPassAsParameterTest extends com.aparapi.codegen.CodeGenJUn + " int get_pass_id(This *this){\n" + " return this->passid;\n" + " }\n" - + "\n" + + '\n' + " int com_aparapi_codegen_test_AssignAndPassAsParameter__actuallyDoIt(This *this, int a){\n" + " return(1);\n" + " }\n" @@ -47,8 +47,8 @@ public class AssignAndPassAsParameterTest extends com.aparapi.codegen.CodeGenJUn + " return;\n" + " }\n" + " }\n" - + "\n" - + " "}; + + '\n' + + ' '}; private static final Class expectedException = null; @Test diff --git a/src/test/java/com/aparapi/codegen/test/Atomic32PragmaTest.java b/src/test/java/com/aparapi/codegen/test/Atomic32PragmaTest.java index 070d39a1..7de85856 100644 --- a/src/test/java/com/aparapi/codegen/test/Atomic32PragmaTest.java +++ b/src/test/java/com/aparapi/codegen/test/Atomic32PragmaTest.java @@ -33,7 +33,7 @@ public class Atomic32PragmaTest extends com.aparapi.codegen.CodeGenJUnitBase { " int get_pass_id(This *this){\n" + " return this->passid;\n" + " }\n" + -"\n" + + '\n' + " __kernel void run(\n" + " __global int *values,\n" + " int passid\n" + @@ -47,7 +47,7 @@ public class Atomic32PragmaTest extends com.aparapi.codegen.CodeGenJUnitBase { " return;\n" + " }\n" + " }\n" + -" "}; + ' '}; private static final Class expectedException = null; @Test diff --git a/src/test/java/com/aparapi/codegen/test/BooleanToggleTest.java b/src/test/java/com/aparapi/codegen/test/BooleanToggleTest.java index bf2b3cec..d9c24e7f 100644 --- a/src/test/java/com/aparapi/codegen/test/BooleanToggleTest.java +++ b/src/test/java/com/aparapi/codegen/test/BooleanToggleTest.java @@ -36,7 +36,7 @@ public class BooleanToggleTest extends com.aparapi.codegen.CodeGenJUnitBase { " pass = (pass==0)?1:0;\n" + " return;\n" + " }\n" + -"}"}; + '}'}; private static final Class expectedException = null; @Test diff --git a/src/test/java/com/aparapi/codegen/test/ByteParamsSimpleTest.java b/src/test/java/com/aparapi/codegen/test/ByteParamsSimpleTest.java index b6d6a93f..6ebdeaea 100644 --- a/src/test/java/com/aparapi/codegen/test/ByteParamsSimpleTest.java +++ b/src/test/java/com/aparapi/codegen/test/ByteParamsSimpleTest.java @@ -41,7 +41,7 @@ public class ByteParamsSimpleTest extends com.aparapi.codegen.CodeGenJUnitBase { " return;\n" + " }\n" + " }\n" + -" "}; + ' '}; private static final Class expectedException = null; @Test diff --git a/src/test/java/com/aparapi/codegen/test/ByteParamsTest.java b/src/test/java/com/aparapi/codegen/test/ByteParamsTest.java index 33e04fa6..0e3cd4a5 100644 --- a/src/test/java/com/aparapi/codegen/test/ByteParamsTest.java +++ b/src/test/java/com/aparapi/codegen/test/ByteParamsTest.java @@ -21,13 +21,13 @@ public class ByteParamsTest extends com.aparapi.codegen.CodeGenJUnitBase { private static final String[] expectedOpenCL = { "typedef struct This_s{\n" - + "\n" + + '\n' + " int passid;\n" + " }This;\n" + " int get_pass_id(This *this){\n" + " return this->passid;\n" + " }\n" - + "\n" + + '\n' + " char com_aparapi_codegen_test_ByteParams__addEmUp2(This *this, char x, char y){\n" + " return((char )(x + y));\n" + " }\n" @@ -44,7 +44,7 @@ public class ByteParamsTest extends com.aparapi.codegen.CodeGenJUnitBase { + " return;\n" + " }\n" + " }\n" - + " "}; + + ' '}; private static final Class expectedException = null; @Test diff --git a/src/test/java/com/aparapi/codegen/test/CallGetPassId.java b/src/test/java/com/aparapi/codegen/test/CallGetPassId.java index 4eababb9..fb05dda8 100644 --- a/src/test/java/com/aparapi/codegen/test/CallGetPassId.java +++ b/src/test/java/com/aparapi/codegen/test/CallGetPassId.java @@ -18,6 +18,7 @@ import com.aparapi.Kernel; public class CallGetPassId extends Kernel { + @Override public void run() { int thePassId = getPassId(); } diff --git a/src/test/java/com/aparapi/codegen/test/CallObject.java b/src/test/java/com/aparapi/codegen/test/CallObject.java index 13a5553f..50d12454 100644 --- a/src/test/java/com/aparapi/codegen/test/CallObject.java +++ b/src/test/java/com/aparapi/codegen/test/CallObject.java @@ -23,6 +23,7 @@ public class CallObject extends Kernel { ; int out[] = new int[2]; + @Override public void run() { out[0] = dummy.foo(); } diff --git a/src/test/java/com/aparapi/codegen/test/CallObjectStatic.java b/src/test/java/com/aparapi/codegen/test/CallObjectStatic.java index 2f135007..a33ff3b1 100644 --- a/src/test/java/com/aparapi/codegen/test/CallObjectStatic.java +++ b/src/test/java/com/aparapi/codegen/test/CallObjectStatic.java @@ -22,6 +22,7 @@ public class CallObjectStatic extends Kernel { ; + @Override public void run() { out[0] = Dummy.foo(); } diff --git a/src/test/java/com/aparapi/codegen/test/CallObjectStaticTest.java b/src/test/java/com/aparapi/codegen/test/CallObjectStaticTest.java index 7f964d40..a0d5579f 100644 --- a/src/test/java/com/aparapi/codegen/test/CallObjectStaticTest.java +++ b/src/test/java/com/aparapi/codegen/test/CallObjectStaticTest.java @@ -41,7 +41,7 @@ public class CallObjectStaticTest extends com.aparapi.codegen.CodeGenJUnitBase { " return;\n" + " }\n" + " }\n" + -" "}; + ' '}; private static final Class expectedException = null; @Test diff --git a/src/test/java/com/aparapi/codegen/test/CallRunSuper.java b/src/test/java/com/aparapi/codegen/test/CallRunSuper.java index 9ed326d0..64531613 100644 --- a/src/test/java/com/aparapi/codegen/test/CallRunSuper.java +++ b/src/test/java/com/aparapi/codegen/test/CallRunSuper.java @@ -27,6 +27,7 @@ public void run() { } public class CallRunSuper extends CallRunSuperBase { + @Override public void run() { super.run(); out[1] = 3; diff --git a/src/test/java/com/aparapi/codegen/test/CallRunSuperTest.java b/src/test/java/com/aparapi/codegen/test/CallRunSuperTest.java index 9b7f87f3..5bb8f42c 100644 --- a/src/test/java/com/aparapi/codegen/test/CallRunSuperTest.java +++ b/src/test/java/com/aparapi/codegen/test/CallRunSuperTest.java @@ -25,7 +25,7 @@ public class CallRunSuperTest extends com.aparapi.codegen.CodeGenJUnitBase { " int get_pass_id(This *this){\n" + " return this->passid;\n" + " }\n" + -"\n" + + '\n' + " void com_aparapi_codegen_test_CallRunSuperBase__run(This *this){\n" + " this->out[0] = 2;\n" + " return;\n" + @@ -44,7 +44,7 @@ public class CallRunSuperTest extends com.aparapi.codegen.CodeGenJUnitBase { " return;\n" + " }\n" + " }\n" + -" "}; + ' '}; private static final Class expectedException = null; @Test diff --git a/src/test/java/com/aparapi/codegen/test/CallStaticInAnotherClass.java b/src/test/java/com/aparapi/codegen/test/CallStaticInAnotherClass.java index d6666f05..cdad19a6 100644 --- a/src/test/java/com/aparapi/codegen/test/CallStaticInAnotherClass.java +++ b/src/test/java/com/aparapi/codegen/test/CallStaticInAnotherClass.java @@ -31,6 +31,7 @@ public int doodoo() { return AnotherClass.foo(); } + @Override public void run() { out[0] = AnotherClass.foo() + doodoo(); } diff --git a/src/test/java/com/aparapi/codegen/test/CallStaticInAnotherClassTest.java b/src/test/java/com/aparapi/codegen/test/CallStaticInAnotherClassTest.java index e6913639..9fc25af8 100644 --- a/src/test/java/com/aparapi/codegen/test/CallStaticInAnotherClassTest.java +++ b/src/test/java/com/aparapi/codegen/test/CallStaticInAnotherClassTest.java @@ -45,8 +45,8 @@ public class CallStaticInAnotherClassTest extends com.aparapi.codegen.CodeGenJUn " return;\n" + " }\n" + " }\n" + -"\n" + -" "}; + '\n' + + ' '}; private static final Class expectedException = null; @Test diff --git a/src/test/java/com/aparapi/codegen/test/CallSuper.java b/src/test/java/com/aparapi/codegen/test/CallSuper.java index 5e3913bf..5252dd12 100644 --- a/src/test/java/com/aparapi/codegen/test/CallSuper.java +++ b/src/test/java/com/aparapi/codegen/test/CallSuper.java @@ -26,10 +26,12 @@ int foo(int n) { public class CallSuper extends CallSuperBase { int out[] = new int[1]; + @Override public void run() { out[0] = foo(2); } + @Override int foo(int n) { return 1 + super.foo(n); } diff --git a/src/test/java/com/aparapi/codegen/test/CallSuperTest.java b/src/test/java/com/aparapi/codegen/test/CallSuperTest.java index 8736e709..f635ae3f 100644 --- a/src/test/java/com/aparapi/codegen/test/CallSuperTest.java +++ b/src/test/java/com/aparapi/codegen/test/CallSuperTest.java @@ -26,7 +26,7 @@ public class CallSuperTest extends com.aparapi.codegen.CodeGenJUnitBase { " int get_pass_id(This *this){\n" + " return this->passid;\n" + " }\n" + -"\n" + + '\n' + " int com_aparapi_codegen_test_CallSuperBase__foo(This *this, int n){\n" + " return((n * 2));\n" + " }\n" + @@ -46,7 +46,7 @@ public class CallSuperTest extends com.aparapi.codegen.CodeGenJUnitBase { " return;\n" + " }\n" + " }\n" + -" "}; + ' '}; private static final Class expectedException = null; @Test diff --git a/src/test/java/com/aparapi/codegen/test/CallTwiceTest.java b/src/test/java/com/aparapi/codegen/test/CallTwiceTest.java index c4ac2aae..1a330e0e 100644 --- a/src/test/java/com/aparapi/codegen/test/CallTwiceTest.java +++ b/src/test/java/com/aparapi/codegen/test/CallTwiceTest.java @@ -42,7 +42,7 @@ public class CallTwiceTest extends com.aparapi.codegen.CodeGenJUnitBase { " return;\n" + " }\n" + " }\n" + -" "}; + ' '}; private static final Class expectedException = null; @Test diff --git a/src/test/java/com/aparapi/codegen/test/CharArrayFieldTest.java b/src/test/java/com/aparapi/codegen/test/CharArrayFieldTest.java index 816e32f2..8236b2bb 100644 --- a/src/test/java/com/aparapi/codegen/test/CharArrayFieldTest.java +++ b/src/test/java/com/aparapi/codegen/test/CharArrayFieldTest.java @@ -39,7 +39,7 @@ public class CharArrayFieldTest extends com.aparapi.codegen.CodeGenJUnitBase { " return;\n" + " }\n" + " }\n" + -" "}; + ' '}; private static final Class expectedException = null; @Test diff --git a/src/test/java/com/aparapi/codegen/test/CharAsParameterTest.java b/src/test/java/com/aparapi/codegen/test/CharAsParameterTest.java index af722887..bc52f595 100644 --- a/src/test/java/com/aparapi/codegen/test/CharAsParameterTest.java +++ b/src/test/java/com/aparapi/codegen/test/CharAsParameterTest.java @@ -41,7 +41,7 @@ public class CharAsParameterTest extends com.aparapi.codegen.CodeGenJUnitBase { " return;\n" + " }\n" + " }\n" + -" "}; + ' '}; private static final Class expectedException = null; @Test diff --git a/src/test/java/com/aparapi/codegen/test/CharTypeTest.java b/src/test/java/com/aparapi/codegen/test/CharTypeTest.java index aff15a14..74dbc49a 100644 --- a/src/test/java/com/aparapi/codegen/test/CharTypeTest.java +++ b/src/test/java/com/aparapi/codegen/test/CharTypeTest.java @@ -40,7 +40,7 @@ public class CharTypeTest extends com.aparapi.codegen.CodeGenJUnitBase { " return;\n" + " }\n" + " }\n" + -" "}; + ' '}; private static final Class expectedException = null; @Test diff --git a/src/test/java/com/aparapi/codegen/test/ClassHasStaticFieldAccessTest.java b/src/test/java/com/aparapi/codegen/test/ClassHasStaticFieldAccessTest.java index b2ba54c3..b793d63b 100644 --- a/src/test/java/com/aparapi/codegen/test/ClassHasStaticFieldAccessTest.java +++ b/src/test/java/com/aparapi/codegen/test/ClassHasStaticFieldAccessTest.java @@ -46,8 +46,8 @@ public class ClassHasStaticFieldAccessTest extends com.aparapi.codegen.CodeGenJU " return;\n" + " }\n" + " }\n" + -"\n" + -" "}; + '\n' + + ' '}; private static final Class expectedException = null; @Test diff --git a/src/test/java/com/aparapi/codegen/test/ClassHasStaticMethodSimpleTest.java b/src/test/java/com/aparapi/codegen/test/ClassHasStaticMethodSimpleTest.java index 897e43d9..287ad120 100644 --- a/src/test/java/com/aparapi/codegen/test/ClassHasStaticMethodSimpleTest.java +++ b/src/test/java/com/aparapi/codegen/test/ClassHasStaticMethodSimpleTest.java @@ -39,7 +39,7 @@ public class ClassHasStaticMethodSimpleTest extends com.aparapi.codegen.CodeGenJ " return;\n" + " }\n" + " }\n" + -" "}; + ' '}; private static final Class expectedException = null; @Test diff --git a/src/test/java/com/aparapi/codegen/test/ClassHasStaticMethodTest.java b/src/test/java/com/aparapi/codegen/test/ClassHasStaticMethodTest.java index 7e4eba05..9da7ed09 100644 --- a/src/test/java/com/aparapi/codegen/test/ClassHasStaticMethodTest.java +++ b/src/test/java/com/aparapi/codegen/test/ClassHasStaticMethodTest.java @@ -49,7 +49,7 @@ public class ClassHasStaticMethodTest extends com.aparapi.codegen.CodeGenJUnitBa " return;\n" + " }\n" + " }\n" + -" "}; + ' '}; private static final Class expectedException = null; @Test diff --git a/src/test/java/com/aparapi/codegen/test/CompositeArbitraryScopeTest.java b/src/test/java/com/aparapi/codegen/test/CompositeArbitraryScopeTest.java index 95b91e90..301c4a43 100644 --- a/src/test/java/com/aparapi/codegen/test/CompositeArbitraryScopeTest.java +++ b/src/test/java/com/aparapi/codegen/test/CompositeArbitraryScopeTest.java @@ -20,13 +20,13 @@ public class CompositeArbitraryScopeTest extends com.aparapi.codegen.CodeGenJUnitBase { private static final String[] expectedOpenCL = { "typedef struct This_s{\n" + -"\n" + + '\n' + " int passid;\n" + " }This;\n" + " int get_pass_id(This *this){\n" + " return this->passid;\n" + " }\n" + -"\n" + + '\n' + " void com_aparapi_codegen_test_CompositeArbitraryScope__t5(This *this){\n" + " int gid = get_global_id(0);\n" + " int numRemaining = 1;\n" + @@ -113,7 +113,7 @@ public class CompositeArbitraryScopeTest extends com.aparapi.codegen.CodeGenJUni " return;\n" + " }\n" + " }\n" + -" "}; + ' '}; private static final Class expectedException = null; @Test diff --git a/src/test/java/com/aparapi/codegen/test/ConstantAssignInExpressionTest.java b/src/test/java/com/aparapi/codegen/test/ConstantAssignInExpressionTest.java index 895ff4d0..68a51cdd 100644 --- a/src/test/java/com/aparapi/codegen/test/ConstantAssignInExpressionTest.java +++ b/src/test/java/com/aparapi/codegen/test/ConstantAssignInExpressionTest.java @@ -20,13 +20,13 @@ public class ConstantAssignInExpressionTest extends com.aparapi.codegen.CodeGenJUnitBase { private static final String[] expectedOpenCL = { "typedef struct This_s{\n" + -"\n" + + '\n' + " int passid;\n" + " }This;\n" + " int get_pass_id(This *this){\n" + " return this->passid;\n" + " }\n" + -"\n" + + '\n' + " void com_aparapi_codegen_test_ConstantAssignInExpression__func(This *this, int _arg){\n" + " return;\n" + " }\n" + @@ -42,7 +42,7 @@ public class ConstantAssignInExpressionTest extends com.aparapi.codegen.CodeGenJ " return;\n" + " }\n" + " }\n" + -" "}; + ' '}; private static final Class expectedException = null; @Test diff --git a/src/test/java/com/aparapi/codegen/test/ContinueTest.java b/src/test/java/com/aparapi/codegen/test/ContinueTest.java index da4aae41..854833ce 100644 --- a/src/test/java/com/aparapi/codegen/test/ContinueTest.java +++ b/src/test/java/com/aparapi/codegen/test/ContinueTest.java @@ -20,13 +20,13 @@ public class ContinueTest extends com.aparapi.codegen.CodeGenJUnitBase { private static final String[] expectedOpenCL = { "typedef struct This_s{\n" + -"\n" + + '\n' + " int passid;\n" + " }This;\n" + " int get_pass_id(This *this){\n" + " return this->passid;\n" + " }\n" + -"\n" + + '\n' + " __kernel void run(\n" + " int passid\n" + " ){\n" + @@ -44,7 +44,7 @@ public class ContinueTest extends com.aparapi.codegen.CodeGenJUnitBase { " return;\n" + " }\n" + " }\n" + -" "}; + ' '}; private static final Class expectedException = null; @Test diff --git a/src/test/java/com/aparapi/codegen/test/DirectRecursion.java b/src/test/java/com/aparapi/codegen/test/DirectRecursion.java index 76153fab..cdfcd56c 100644 --- a/src/test/java/com/aparapi/codegen/test/DirectRecursion.java +++ b/src/test/java/com/aparapi/codegen/test/DirectRecursion.java @@ -21,6 +21,7 @@ public class DirectRecursion extends Kernel { int intout[] = new int[1]; + @Override public void run() { intout[0] = fact(10); @SuppressWarnings("unused") boolean pass = false; diff --git a/src/test/java/com/aparapi/codegen/test/DoWhileTest.java b/src/test/java/com/aparapi/codegen/test/DoWhileTest.java index 88198b4b..c5430222 100644 --- a/src/test/java/com/aparapi/codegen/test/DoWhileTest.java +++ b/src/test/java/com/aparapi/codegen/test/DoWhileTest.java @@ -20,13 +20,13 @@ public class DoWhileTest extends com.aparapi.codegen.CodeGenJUnitBase { private static final String[] expectedOpenCL = { "typedef struct This_s{\n" + -"\n" + + '\n' + " int passid;\n" + " }This;\n" + " int get_pass_id(This *this){\n" + " return this->passid;\n" + " }\n" + -"\n" + + '\n' + " __kernel void run(\n" + " int passid\n" + " ){\n" + @@ -43,7 +43,7 @@ public class DoWhileTest extends com.aparapi.codegen.CodeGenJUnitBase { " return;\n" + " }\n" + " }\n" + -" "}; + ' '}; private static final Class expectedException = null; @Test diff --git a/src/test/java/com/aparapi/codegen/test/DremTest.java b/src/test/java/com/aparapi/codegen/test/DremTest.java index 4ec391ca..c704bed5 100644 --- a/src/test/java/com/aparapi/codegen/test/DremTest.java +++ b/src/test/java/com/aparapi/codegen/test/DremTest.java @@ -20,7 +20,7 @@ public class DremTest extends com.aparapi.codegen.CodeGenJUnitBase { private static final String[] expectedOpenCL = { "#pragma OPENCL EXTENSION cl_khr_fp64 : enable\n" + -"\n" + + '\n' + " typedef struct This_s{\n" + " __global double *out;\n" + " double m;\n" + @@ -47,8 +47,8 @@ public class DremTest extends com.aparapi.codegen.CodeGenJUnitBase { " return;\n" + " }\n" + " }\n" + -"\n" + -" "}; + '\n' + + ' '}; private static final Class expectedException = null; @Test diff --git a/src/test/java/com/aparapi/codegen/test/EarlyReturnTest.java b/src/test/java/com/aparapi/codegen/test/EarlyReturnTest.java index 9168956e..ea878bbf 100644 --- a/src/test/java/com/aparapi/codegen/test/EarlyReturnTest.java +++ b/src/test/java/com/aparapi/codegen/test/EarlyReturnTest.java @@ -41,7 +41,7 @@ public class EarlyReturnTest extends com.aparapi.codegen.CodeGenJUnitBase { " return;\n" + " }\n" + " }\n" + -" "}; + ' '}; private static final Class expectedException = null; @Test diff --git a/src/test/java/com/aparapi/codegen/test/EmptyWhileWithIncTest.java b/src/test/java/com/aparapi/codegen/test/EmptyWhileWithIncTest.java index 039b3214..190f591d 100644 --- a/src/test/java/com/aparapi/codegen/test/EmptyWhileWithIncTest.java +++ b/src/test/java/com/aparapi/codegen/test/EmptyWhileWithIncTest.java @@ -36,7 +36,7 @@ public class EmptyWhileWithIncTest extends com.aparapi.codegen.CodeGenJUnitBase " return;\n" + " }\n" + " }\n" + -" "}; + ' '}; private static final Class expectedException = null; @Test diff --git a/src/test/java/com/aparapi/codegen/test/EntrypointRecursion.java b/src/test/java/com/aparapi/codegen/test/EntrypointRecursion.java index 52c6e548..22d321ee 100644 --- a/src/test/java/com/aparapi/codegen/test/EntrypointRecursion.java +++ b/src/test/java/com/aparapi/codegen/test/EntrypointRecursion.java @@ -21,6 +21,7 @@ public class EntrypointRecursion extends Kernel { int[] values = new int[128]; + @Override public void run() { int id = getGlobalId(); diff --git a/src/test/java/com/aparapi/codegen/test/ExTest.java b/src/test/java/com/aparapi/codegen/test/ExTest.java index 051eca92..b543f64c 100644 --- a/src/test/java/com/aparapi/codegen/test/ExTest.java +++ b/src/test/java/com/aparapi/codegen/test/ExTest.java @@ -25,7 +25,7 @@ public class ExTest extends com.aparapi.codegen.CodeGenJUnitBase { " int get_pass_id(This *this){\n" + " return this->passid;\n" + " }\n" + -"\n" + + '\n' + " __kernel void run(\n" + " int passid\n" + " ){\n" + @@ -42,7 +42,7 @@ public class ExTest extends com.aparapi.codegen.CodeGenJUnitBase { " return;\n" + " }\n" + " }\n" + -" "}; + ' '}; private static final Class expectedException = null; @Test diff --git a/src/test/java/com/aparapi/codegen/test/FirstAssignInExpression2Test.java b/src/test/java/com/aparapi/codegen/test/FirstAssignInExpression2Test.java index 53274d4f..5e55acd3 100644 --- a/src/test/java/com/aparapi/codegen/test/FirstAssignInExpression2Test.java +++ b/src/test/java/com/aparapi/codegen/test/FirstAssignInExpression2Test.java @@ -22,7 +22,7 @@ public class FirstAssignInExpression2Test extends com.aparapi.codegen.CodeGenJUn private static final String[] expectedOpenCL = { "typedef struct This_s{\n" - + "\n" + + '\n' + " int passid;\n" + " }This;\n" + " int get_pass_id(This *this){\n" @@ -48,7 +48,7 @@ public class FirstAssignInExpression2Test extends com.aparapi.codegen.CodeGenJUn + " return;\n" + " }\n" + " }\n" - + " "}; + + ' '}; private static final Class expectedException = null; @Ignore diff --git a/src/test/java/com/aparapi/codegen/test/FirstAssignInExpressionTest.java b/src/test/java/com/aparapi/codegen/test/FirstAssignInExpressionTest.java index 0bf52228..acd2d1eb 100644 --- a/src/test/java/com/aparapi/codegen/test/FirstAssignInExpressionTest.java +++ b/src/test/java/com/aparapi/codegen/test/FirstAssignInExpressionTest.java @@ -21,13 +21,13 @@ public class FirstAssignInExpressionTest extends com.aparapi.codegen.CodeGenJUnitBase { private static final String[] expectedOpenCL = { "typedef struct This_s{\n" + -"\n" + + '\n' + " int passid;\n" + " }This;\n" + " int get_pass_id(This *this){\n" + " return this->passid;\n" + " }\n" + -"\n" + + '\n' + " void func(This *this, int _arg){\n" + " return;\n" + " }\n" + @@ -43,7 +43,7 @@ public class FirstAssignInExpressionTest extends com.aparapi.codegen.CodeGenJUni " return;\n" + " }\n" + " }\n" + -" "}; + ' '}; private static final Class expectedException = null; @Ignore diff --git a/src/test/java/com/aparapi/codegen/test/FloatParamsSimpleTest.java b/src/test/java/com/aparapi/codegen/test/FloatParamsSimpleTest.java index f47a4ce0..2a618fe5 100644 --- a/src/test/java/com/aparapi/codegen/test/FloatParamsSimpleTest.java +++ b/src/test/java/com/aparapi/codegen/test/FloatParamsSimpleTest.java @@ -20,13 +20,13 @@ public class FloatParamsSimpleTest extends com.aparapi.codegen.CodeGenJUnitBase { private static final String[] expectedOpenCL = { "typedef struct This_s{\n" + -"\n" + + '\n' + " int passid;\n" + " }This;\n" + " int get_pass_id(This *this){\n" + " return this->passid;\n" + " }\n" + -"\n" + + '\n' + " void com_aparapi_codegen_test_FloatParamsSimple__floatParams(This *this, float y){\n" + " return;\n" + " }\n" + @@ -41,7 +41,7 @@ public class FloatParamsSimpleTest extends com.aparapi.codegen.CodeGenJUnitBase " return;\n" + " }\n" + " }\n" + -" "}; + ' '}; private static final Class expectedException = null; @Test diff --git a/src/test/java/com/aparapi/codegen/test/FloatParamsTest.java b/src/test/java/com/aparapi/codegen/test/FloatParamsTest.java index ecb8189f..44146e1c 100644 --- a/src/test/java/com/aparapi/codegen/test/FloatParamsTest.java +++ b/src/test/java/com/aparapi/codegen/test/FloatParamsTest.java @@ -20,13 +20,13 @@ public class FloatParamsTest extends com.aparapi.codegen.CodeGenJUnitBase { private static final String[] expectedOpenCL = { "typedef struct This_s{\n" + -"\n" + + '\n' + " int passid;\n" + " }This;\n" + " int get_pass_id(This *this){\n" + " return this->passid;\n" + " }\n" + -"\n" + + '\n' + " int com_aparapi_codegen_test_FloatParams__addEmUp(This *this, float y, float z){\n" + " return(((int)y + (int)z));\n" + " }\n" + @@ -43,7 +43,7 @@ public class FloatParamsTest extends com.aparapi.codegen.CodeGenJUnitBase { " return;\n" + " }\n" + " }\n" + -" "}; + ' '}; private static final Class expectedException = null; @Test diff --git a/src/test/java/com/aparapi/codegen/test/ForAndMandelNoInitializeTest.java b/src/test/java/com/aparapi/codegen/test/ForAndMandelNoInitializeTest.java index f78d08b6..ca2ac712 100644 --- a/src/test/java/com/aparapi/codegen/test/ForAndMandelNoInitializeTest.java +++ b/src/test/java/com/aparapi/codegen/test/ForAndMandelNoInitializeTest.java @@ -28,7 +28,7 @@ public class ForAndMandelNoInitializeTest extends com.aparapi.codegen.CodeGenJUn " int get_pass_id(This *this){\n" + " return this->passid;\n" + " }\n" + -"\n" + + '\n' + " __kernel void run(\n" + " int width,\n" + " float scale,\n" + @@ -65,7 +65,7 @@ public class ForAndMandelNoInitializeTest extends com.aparapi.codegen.CodeGenJUn " return;\n" + " }\n" + " }\n" + -" "}; + ' '}; private static final Class expectedException = null; @Test diff --git a/src/test/java/com/aparapi/codegen/test/ForAndMandelTest.java b/src/test/java/com/aparapi/codegen/test/ForAndMandelTest.java index d2b055cb..f98a62d8 100644 --- a/src/test/java/com/aparapi/codegen/test/ForAndMandelTest.java +++ b/src/test/java/com/aparapi/codegen/test/ForAndMandelTest.java @@ -28,7 +28,7 @@ public class ForAndMandelTest extends com.aparapi.codegen.CodeGenJUnitBase { " int get_pass_id(This *this){\n" + " return this->passid;\n" + " }\n" + -"\n" + + '\n' + " __kernel void run(\n" + " int width,\n" + " float scale,\n" + @@ -64,7 +64,7 @@ public class ForAndMandelTest extends com.aparapi.codegen.CodeGenJUnitBase { " return;\n" + " }\n" + " }\n" + -" "}; + ' '}; private static final Class expectedException = null; @Test diff --git a/src/test/java/com/aparapi/codegen/test/ForAndTest.java b/src/test/java/com/aparapi/codegen/test/ForAndTest.java index 786225dd..10b6cf7f 100644 --- a/src/test/java/com/aparapi/codegen/test/ForAndTest.java +++ b/src/test/java/com/aparapi/codegen/test/ForAndTest.java @@ -20,13 +20,13 @@ public class ForAndTest extends com.aparapi.codegen.CodeGenJUnitBase { private static final String[] expectedOpenCL = { "typedef struct This_s{\n" + -"\n" + + '\n' + " int passid;\n" + " }This;\n" + " int get_pass_id(This *this){\n" + " return this->passid;\n" + " }\n" + -"\n" + + '\n' + " __kernel void run(\n" + " int passid\n" + " ){\n" + @@ -41,7 +41,7 @@ public class ForAndTest extends com.aparapi.codegen.CodeGenJUnitBase { " return;\n" + " }\n" + " }\n" + -" "}; + ' '}; private static final Class expectedException = null; @Test diff --git a/src/test/java/com/aparapi/codegen/test/ForAsFirstTest.java b/src/test/java/com/aparapi/codegen/test/ForAsFirstTest.java index df54814c..b0d32cd4 100644 --- a/src/test/java/com/aparapi/codegen/test/ForAsFirstTest.java +++ b/src/test/java/com/aparapi/codegen/test/ForAsFirstTest.java @@ -20,13 +20,13 @@ public class ForAsFirstTest extends com.aparapi.codegen.CodeGenJUnitBase { private static final String[] expectedOpenCL = { "typedef struct This_s{\n" + -"\n" + + '\n' + " int passid;\n" + " }This;\n" + " int get_pass_id(This *this){\n" + " return this->passid;\n" + " }\n" + -"\n" + + '\n' + " __kernel void run(\n" + " int passid\n" + " ){\n" + @@ -39,7 +39,7 @@ public class ForAsFirstTest extends com.aparapi.codegen.CodeGenJUnitBase { " return;\n" + " }\n" + " }\n" + -" "}; + ' '}; private static final Class expectedException = null; @Test diff --git a/src/test/java/com/aparapi/codegen/test/ForBooleanToggleTest.java b/src/test/java/com/aparapi/codegen/test/ForBooleanToggleTest.java index fd3491ba..bb50133b 100644 --- a/src/test/java/com/aparapi/codegen/test/ForBooleanToggleTest.java +++ b/src/test/java/com/aparapi/codegen/test/ForBooleanToggleTest.java @@ -20,13 +20,13 @@ public class ForBooleanToggleTest extends com.aparapi.codegen.CodeGenJUnitBase { private static final String[] expectedOpenCL = { "typedef struct This_s{\n" + -"\n" + + '\n' + " int passid;\n" + " }This;\n" + " int get_pass_id(This *this){\n" + " return this->passid;\n" + " }\n" + -"\n" + + '\n' + " __kernel void run(\n" + " int passid\n" + " ){\n" + @@ -41,7 +41,7 @@ public class ForBooleanToggleTest extends com.aparapi.codegen.CodeGenJUnitBase { " return;\n" + " }\n" + " }\n" + -" "}; + ' '}; private static final Class expectedException = null; @Test diff --git a/src/test/java/com/aparapi/codegen/test/ForIfMandelTest.java b/src/test/java/com/aparapi/codegen/test/ForIfMandelTest.java index 933895c9..da9b38e3 100644 --- a/src/test/java/com/aparapi/codegen/test/ForIfMandelTest.java +++ b/src/test/java/com/aparapi/codegen/test/ForIfMandelTest.java @@ -28,7 +28,7 @@ public class ForIfMandelTest extends com.aparapi.codegen.CodeGenJUnitBase { " int get_pass_id(This *this){\n" + " return this->passid;\n" + " }\n" + -"\n" + + '\n' + " __kernel void run(\n" + " int width,\n" + " float scale,\n" + @@ -68,7 +68,7 @@ public class ForIfMandelTest extends com.aparapi.codegen.CodeGenJUnitBase { " return;\n" + " }\n" + " }\n" + -" "}; + ' '}; private static final Class expectedException = null; @Test diff --git a/src/test/java/com/aparapi/codegen/test/ForIfTest.java b/src/test/java/com/aparapi/codegen/test/ForIfTest.java index a0d95778..5b025f2a 100644 --- a/src/test/java/com/aparapi/codegen/test/ForIfTest.java +++ b/src/test/java/com/aparapi/codegen/test/ForIfTest.java @@ -20,13 +20,13 @@ public class ForIfTest extends com.aparapi.codegen.CodeGenJUnitBase { private static final String[] expectedOpenCL = { "typedef struct This_s{\n" + -"\n" + + '\n' + " int passid;\n" + " }This;\n" + " int get_pass_id(This *this){\n" + " return this->passid;\n" + " }\n" + -"\n" + + '\n' + " __kernel void run(\n" + " int passid\n" + " ){\n" + @@ -43,7 +43,7 @@ public class ForIfTest extends com.aparapi.codegen.CodeGenJUnitBase { " return;\n" + " }\n" + " }\n" + -" "}; + ' '}; private static final Class expectedException = null; @Test diff --git a/src/test/java/com/aparapi/codegen/test/ForTest.java b/src/test/java/com/aparapi/codegen/test/ForTest.java index c9a26974..98aa3dde 100644 --- a/src/test/java/com/aparapi/codegen/test/ForTest.java +++ b/src/test/java/com/aparapi/codegen/test/ForTest.java @@ -39,7 +39,7 @@ public class ForTest extends com.aparapi.codegen.CodeGenJUnitBase { " return;\n" + " }\n" + " }\n" + -" "}; + ' '}; private static final Class expectedException = null; @Test diff --git a/src/test/java/com/aparapi/codegen/test/FremTest.java b/src/test/java/com/aparapi/codegen/test/FremTest.java index 95389efb..ee15f23d 100644 --- a/src/test/java/com/aparapi/codegen/test/FremTest.java +++ b/src/test/java/com/aparapi/codegen/test/FremTest.java @@ -45,7 +45,7 @@ public class FremTest extends com.aparapi.codegen.CodeGenJUnitBase { " return;\n" + " }\n" + " }\n" + -" "}; + ' '}; private static final Class expectedException = null; @Test diff --git a/src/test/java/com/aparapi/codegen/test/FusedMultiplyAdd.java b/src/test/java/com/aparapi/codegen/test/FusedMultiplyAdd.java index ca1da6ac..a1d6c83d 100644 --- a/src/test/java/com/aparapi/codegen/test/FusedMultiplyAdd.java +++ b/src/test/java/com/aparapi/codegen/test/FusedMultiplyAdd.java @@ -18,6 +18,7 @@ import com.aparapi.Kernel; public class FusedMultiplyAdd extends Kernel { + @Override public void run() { double d1 = 123.0, d2 = 0.456, d3 = 789.0; float f1 = 123.0f, f2 = 0.456f, f3 = 789.0f; diff --git a/src/test/java/com/aparapi/codegen/test/FusedMultiplyAddTest.java b/src/test/java/com/aparapi/codegen/test/FusedMultiplyAddTest.java index d4c79f08..0a587325 100644 --- a/src/test/java/com/aparapi/codegen/test/FusedMultiplyAddTest.java +++ b/src/test/java/com/aparapi/codegen/test/FusedMultiplyAddTest.java @@ -44,7 +44,7 @@ public class FusedMultiplyAddTest extends com.aparapi.codegen.CodeGenJUnitBase { " }\n" + " return;\n" + " }\n" + - "}"}; + '}'}; private static final Class expectedException = null; @Test diff --git a/src/test/java/com/aparapi/codegen/test/IEEERemainderDouble.java b/src/test/java/com/aparapi/codegen/test/IEEERemainderDouble.java index 734c62fe..fa8fee5a 100644 --- a/src/test/java/com/aparapi/codegen/test/IEEERemainderDouble.java +++ b/src/test/java/com/aparapi/codegen/test/IEEERemainderDouble.java @@ -22,6 +22,7 @@ public class IEEERemainderDouble extends Kernel { double m; double n; + @Override public void run() { out[0] = IEEEremainder(m, n); } diff --git a/src/test/java/com/aparapi/codegen/test/IEEERemainderDoubleTest.java b/src/test/java/com/aparapi/codegen/test/IEEERemainderDoubleTest.java index 8edaf00d..f7737855 100644 --- a/src/test/java/com/aparapi/codegen/test/IEEERemainderDoubleTest.java +++ b/src/test/java/com/aparapi/codegen/test/IEEERemainderDoubleTest.java @@ -20,7 +20,7 @@ public class IEEERemainderDoubleTest extends com.aparapi.codegen.CodeGenJUnitBase { private static final String[] expectedOpenCL = { "#pragma OPENCL EXTENSION cl_khr_fp64 : enable\n" + -"\n" + + '\n' + " typedef struct This_s{\n" + " __global double *out;\n" + " double m;\n" + @@ -47,8 +47,8 @@ public class IEEERemainderDoubleTest extends com.aparapi.codegen.CodeGenJUnitBas " return;\n" + " }\n" + " }\n" + -"\n" + -" "}; + '\n' + + ' '}; private static final Class expectedException = null; @Test diff --git a/src/test/java/com/aparapi/codegen/test/IEEERemainderFloat.java b/src/test/java/com/aparapi/codegen/test/IEEERemainderFloat.java index ac1c6864..d7b8543c 100644 --- a/src/test/java/com/aparapi/codegen/test/IEEERemainderFloat.java +++ b/src/test/java/com/aparapi/codegen/test/IEEERemainderFloat.java @@ -22,6 +22,7 @@ public class IEEERemainderFloat extends Kernel { float m; float n; + @Override public void run() { out[0] = IEEEremainder(m, n); } diff --git a/src/test/java/com/aparapi/codegen/test/IEEERemainderFloatTest.java b/src/test/java/com/aparapi/codegen/test/IEEERemainderFloatTest.java index c591f4fa..f7695ae9 100644 --- a/src/test/java/com/aparapi/codegen/test/IEEERemainderFloatTest.java +++ b/src/test/java/com/aparapi/codegen/test/IEEERemainderFloatTest.java @@ -45,8 +45,8 @@ public class IEEERemainderFloatTest extends com.aparapi.codegen.CodeGenJUnitBase " return;\n" + " }\n" + " }\n" + -"\n" + -" "}; + '\n' + + ' '}; private static final Class expectedException = null; @Test diff --git a/src/test/java/com/aparapi/codegen/test/IfAndAndAndTest.java b/src/test/java/com/aparapi/codegen/test/IfAndAndAndTest.java index 4a567536..369194cf 100644 --- a/src/test/java/com/aparapi/codegen/test/IfAndAndAndTest.java +++ b/src/test/java/com/aparapi/codegen/test/IfAndAndAndTest.java @@ -21,13 +21,13 @@ public class IfAndAndAndTest extends com.aparapi.codegen.CodeGenJUnitBase { private static final String[] expectedOpenCL = { "typedef struct This_s{\n" - + "\n" + + '\n' + " int passid;\n" + " }This;\n" + " int get_pass_id(This *this){\n" + " return this->passid;\n" + " }\n" - + "\n" + + '\n' + " __kernel void run(\n" + " int passid\n" + " ){\n" @@ -43,7 +43,7 @@ public class IfAndAndAndTest extends com.aparapi.codegen.CodeGenJUnitBase { + " return;\n" + " }\n" + " }\n" - + " "}; + + ' '}; private static final Class expectedException = null; @Test diff --git a/src/test/java/com/aparapi/codegen/test/IfAndAndTest.java b/src/test/java/com/aparapi/codegen/test/IfAndAndTest.java index ddac28ce..72268848 100644 --- a/src/test/java/com/aparapi/codegen/test/IfAndAndTest.java +++ b/src/test/java/com/aparapi/codegen/test/IfAndAndTest.java @@ -21,13 +21,13 @@ public class IfAndAndTest extends com.aparapi.codegen.CodeGenJUnitBase { private static final String[] expectedOpenCL = { "typedef struct This_s{\n" - + "\n" + + '\n' + " int passid;\n" + " }This;\n" + " int get_pass_id(This *this){\n" + " return this->passid;\n" + " }\n" - + "\n" + + '\n' + " __kernel void run(\n" + " int passid\n" + " ){\n" @@ -43,7 +43,7 @@ public class IfAndAndTest extends com.aparapi.codegen.CodeGenJUnitBase { + " return;\n" + " }\n" + " }\n" - + " "}; + + ' '}; private static final Class expectedException = null; @Test diff --git a/src/test/java/com/aparapi/codegen/test/IfAndOrAndTest.java b/src/test/java/com/aparapi/codegen/test/IfAndOrAndTest.java index 8e91650a..e95ea691 100644 --- a/src/test/java/com/aparapi/codegen/test/IfAndOrAndTest.java +++ b/src/test/java/com/aparapi/codegen/test/IfAndOrAndTest.java @@ -21,13 +21,13 @@ public class IfAndOrAndTest extends com.aparapi.codegen.CodeGenJUnitBase { private static final String[] expectedOpenCL = { "typedef struct This_s{\n" - + "\n" + + '\n' + " int passid;\n" + " }This;\n" + " int get_pass_id(This *this){\n" + " return this->passid;\n" + " }\n" - + "\n" + + '\n' + " __kernel void run(\n" + " int passid\n" + " ){\n" @@ -43,7 +43,7 @@ public class IfAndOrAndTest extends com.aparapi.codegen.CodeGenJUnitBase { + " return;\n" + " }\n" + " }\n" - + " "}; + + ' '}; private static final Class expectedException = null; diff --git a/src/test/java/com/aparapi/codegen/test/IfAndTest.java b/src/test/java/com/aparapi/codegen/test/IfAndTest.java index d469c0fa..d78c6275 100644 --- a/src/test/java/com/aparapi/codegen/test/IfAndTest.java +++ b/src/test/java/com/aparapi/codegen/test/IfAndTest.java @@ -21,13 +21,13 @@ public class IfAndTest extends com.aparapi.codegen.CodeGenJUnitBase { private static final String[] expectedOpenCL = { "typedef struct This_s{\n" - + "\n" + + '\n' + " int passid;\n" + " }This;\n" + " int get_pass_id(This *this){\n" + " return this->passid;\n" + " }\n" - + "\n" + + '\n' + " __kernel void run(\n" + " int passid\n" + " ){\n" @@ -43,7 +43,7 @@ public class IfAndTest extends com.aparapi.codegen.CodeGenJUnitBase { + " return;\n" + " }\n" + " }\n" - + " "}; + + ' '}; private static final Class expectedException = null; @Test diff --git a/src/test/java/com/aparapi/codegen/test/IfBooleanAndAndAndTest.java b/src/test/java/com/aparapi/codegen/test/IfBooleanAndAndAndTest.java index aa642c0e..976d1c1c 100644 --- a/src/test/java/com/aparapi/codegen/test/IfBooleanAndAndAndTest.java +++ b/src/test/java/com/aparapi/codegen/test/IfBooleanAndAndAndTest.java @@ -21,13 +21,13 @@ public class IfBooleanAndAndAndTest extends com.aparapi.codegen.CodeGenJUnitBase private static final String[] expectedOpenCL = { "typedef struct This_s{\n" - + "\n" + + '\n' + " int passid;\n" + " }This;\n" + " int get_pass_id(This *this){\n" + " return this->passid;\n" + " }\n" - + "\n" + + '\n' + " __kernel void run(\n" + " int passid\n" + " ){\n" @@ -46,7 +46,7 @@ public class IfBooleanAndAndAndTest extends com.aparapi.codegen.CodeGenJUnitBase + " return;\n" + " }\n" + " }\n" - + " "}; + + ' '}; private static final Class expectedException = null; @Test diff --git a/src/test/java/com/aparapi/codegen/test/IfBooleanAndAndOrTest.java b/src/test/java/com/aparapi/codegen/test/IfBooleanAndAndOrTest.java index c637d4ff..dbf385ed 100644 --- a/src/test/java/com/aparapi/codegen/test/IfBooleanAndAndOrTest.java +++ b/src/test/java/com/aparapi/codegen/test/IfBooleanAndAndOrTest.java @@ -21,13 +21,13 @@ public class IfBooleanAndAndOrTest extends com.aparapi.codegen.CodeGenJUnitBase private static final String[] expectedOpenCL = { "typedef struct This_s{\n" - + "\n" + + '\n' + " int passid;\n" + " }This;\n" + " int get_pass_id(This *this){\n" + " return this->passid;\n" + " }\n" - + "\n" + + '\n' + " __kernel void run(\n" + " int passid\n" + " ){\n" @@ -46,7 +46,7 @@ public class IfBooleanAndAndOrTest extends com.aparapi.codegen.CodeGenJUnitBase + " return;\n" + " }\n" + " }\n" - + " "}; + + ' '}; private static final Class expectedException = null; @Test diff --git a/src/test/java/com/aparapi/codegen/test/IfBooleanAndOrAndTest.java b/src/test/java/com/aparapi/codegen/test/IfBooleanAndOrAndTest.java index 5655f680..f196af2c 100644 --- a/src/test/java/com/aparapi/codegen/test/IfBooleanAndOrAndTest.java +++ b/src/test/java/com/aparapi/codegen/test/IfBooleanAndOrAndTest.java @@ -21,13 +21,13 @@ public class IfBooleanAndOrAndTest extends com.aparapi.codegen.CodeGenJUnitBase private static final String[] expectedOpenCL = { "typedef struct This_s{\n" - + "\n" + + '\n' + " int passid;\n" + " }This;\n" + " int get_pass_id(This *this){\n" + " return this->passid;\n" + " }\n" - + "\n" + + '\n' + " __kernel void run(\n" + " int passid\n" + " ){\n" @@ -46,7 +46,7 @@ public class IfBooleanAndOrAndTest extends com.aparapi.codegen.CodeGenJUnitBase + " return;\n" + " }\n" + " }\n" - + " "}; + + ' '}; private static final Class expectedException = null; @Test diff --git a/src/test/java/com/aparapi/codegen/test/IfBooleanAndOrOrTest.java b/src/test/java/com/aparapi/codegen/test/IfBooleanAndOrOrTest.java index 17531120..3caed0fb 100644 --- a/src/test/java/com/aparapi/codegen/test/IfBooleanAndOrOrTest.java +++ b/src/test/java/com/aparapi/codegen/test/IfBooleanAndOrOrTest.java @@ -21,13 +21,13 @@ public class IfBooleanAndOrOrTest extends com.aparapi.codegen.CodeGenJUnitBase { private static final String[] expectedOpenCL = { "typedef struct This_s{\n" - + "\n" + + '\n' + " int passid;\n" + " }This;\n" + " int get_pass_id(This *this){\n" + " return this->passid;\n" + " }\n" - + "\n" + + '\n' + " __kernel void run(\n" + " int passid\n" + " ){\n" @@ -46,7 +46,7 @@ public class IfBooleanAndOrOrTest extends com.aparapi.codegen.CodeGenJUnitBase { + " return;\n" + " }\n" + " }\n" - + " "}; + + ' '}; private static final Class expectedException = null; @Test diff --git a/src/test/java/com/aparapi/codegen/test/IfBooleanOrAndAndTest.java b/src/test/java/com/aparapi/codegen/test/IfBooleanOrAndAndTest.java index 7e625618..11d31d5f 100644 --- a/src/test/java/com/aparapi/codegen/test/IfBooleanOrAndAndTest.java +++ b/src/test/java/com/aparapi/codegen/test/IfBooleanOrAndAndTest.java @@ -21,13 +21,13 @@ public class IfBooleanOrAndAndTest extends com.aparapi.codegen.CodeGenJUnitBase private static final String[] expectedOpenCL = { "typedef struct This_s{\n" - + "\n" + + '\n' + " int passid;\n" + " }This;\n" + " int get_pass_id(This *this){\n" + " return this->passid;\n" + " }\n" - + "\n" + + '\n' + " __kernel void run(\n" + " int passid\n" + " ){\n" @@ -46,7 +46,7 @@ public class IfBooleanOrAndAndTest extends com.aparapi.codegen.CodeGenJUnitBase + " return;\n" + " }\n" + " }\n" - + " "}; + + ' '}; private static final Class expectedException = null; @Test diff --git a/src/test/java/com/aparapi/codegen/test/IfBooleanOrAndOrTest.java b/src/test/java/com/aparapi/codegen/test/IfBooleanOrAndOrTest.java index 966e2517..5ddb837c 100644 --- a/src/test/java/com/aparapi/codegen/test/IfBooleanOrAndOrTest.java +++ b/src/test/java/com/aparapi/codegen/test/IfBooleanOrAndOrTest.java @@ -21,13 +21,13 @@ public class IfBooleanOrAndOrTest extends com.aparapi.codegen.CodeGenJUnitBase { private static final String[] expectedOpenCL = { "typedef struct This_s{\n" - + "\n" + + '\n' + " int passid;\n" + " }This;\n" + " int get_pass_id(This *this){\n" + " return this->passid;\n" + " }\n" - + "\n" + + '\n' + " __kernel void run(\n" + " int passid\n" + " ){\n" @@ -46,7 +46,7 @@ public class IfBooleanOrAndOrTest extends com.aparapi.codegen.CodeGenJUnitBase { + " return;\n" + " }\n" + " }\n" - + " "}; + + ' '}; private static final Class expectedException = null; @Test diff --git a/src/test/java/com/aparapi/codegen/test/IfBooleanOrOrAndTest.java b/src/test/java/com/aparapi/codegen/test/IfBooleanOrOrAndTest.java index d2229770..3dfad893 100644 --- a/src/test/java/com/aparapi/codegen/test/IfBooleanOrOrAndTest.java +++ b/src/test/java/com/aparapi/codegen/test/IfBooleanOrOrAndTest.java @@ -21,13 +21,13 @@ public class IfBooleanOrOrAndTest extends com.aparapi.codegen.CodeGenJUnitBase { private static final String[] expectedOpenCL = { "typedef struct This_s{\n" - + "\n" + + '\n' + " int passid;\n" + " }This;\n" + " int get_pass_id(This *this){\n" + " return this->passid;\n" + " }\n" - + "\n" + + '\n' + " __kernel void run(\n" + " int passid\n" + " ){\n" @@ -46,7 +46,7 @@ public class IfBooleanOrOrAndTest extends com.aparapi.codegen.CodeGenJUnitBase { + " return;\n" + " }\n" + " }\n" - + " "}; + + ' '}; private static final Class expectedException = null; @Test diff --git a/src/test/java/com/aparapi/codegen/test/IfBooleanOrOrOrTest.java b/src/test/java/com/aparapi/codegen/test/IfBooleanOrOrOrTest.java index 62bec0cd..bc8532b3 100644 --- a/src/test/java/com/aparapi/codegen/test/IfBooleanOrOrOrTest.java +++ b/src/test/java/com/aparapi/codegen/test/IfBooleanOrOrOrTest.java @@ -21,13 +21,13 @@ public class IfBooleanOrOrOrTest extends com.aparapi.codegen.CodeGenJUnitBase { private static final String[] expectedOpenCL = { "typedef struct This_s{\n" - + "\n" + + '\n' + " int passid;\n" + " }This;\n" + " int get_pass_id(This *this){\n" + " return this->passid;\n" + " }\n" - + "\n" + + '\n' + " __kernel void run(\n" + " int passid\n" + " ){\n" @@ -46,7 +46,7 @@ public class IfBooleanOrOrOrTest extends com.aparapi.codegen.CodeGenJUnitBase { + " return;\n" + " }\n" + " }\n" - + " "}; + + ' '}; private static final Class expectedException = null; @Test diff --git a/src/test/java/com/aparapi/codegen/test/IfElseAndAndAndTest.java b/src/test/java/com/aparapi/codegen/test/IfElseAndAndAndTest.java index 9c54bbaf..b441f1b3 100644 --- a/src/test/java/com/aparapi/codegen/test/IfElseAndAndAndTest.java +++ b/src/test/java/com/aparapi/codegen/test/IfElseAndAndAndTest.java @@ -21,13 +21,13 @@ public class IfElseAndAndAndTest extends com.aparapi.codegen.CodeGenJUnitBase { private static final String[] expectedOpenCL = { "typedef struct This_s{\n" - + "\n" + + '\n' + " int passid;\n" + " }This;\n" + " int get_pass_id(This *this){\n" + " return this->passid;\n" + " }\n" - + "\n" + + '\n' + " __kernel void run(\n" + " int passid\n" + " ){\n" @@ -45,7 +45,7 @@ public class IfElseAndAndAndTest extends com.aparapi.codegen.CodeGenJUnitBase { + " return;\n" + " }\n" + " }\n" - + " "}; + + ' '}; private static final Class expectedException = null; @Test diff --git a/src/test/java/com/aparapi/codegen/test/IfElseAndTest.java b/src/test/java/com/aparapi/codegen/test/IfElseAndTest.java index 70bb5db8..dbf82108 100644 --- a/src/test/java/com/aparapi/codegen/test/IfElseAndTest.java +++ b/src/test/java/com/aparapi/codegen/test/IfElseAndTest.java @@ -21,13 +21,13 @@ public class IfElseAndTest extends com.aparapi.codegen.CodeGenJUnitBase { private static final String[] expectedOpenCL = { "typedef struct This_s{\n" - + "\n" + + '\n' + " int passid;\n" + " }This;\n" + " int get_pass_id(This *this){\n" + " return this->passid;\n" + " }\n" - + "\n" + + '\n' + " __kernel void run(\n" + " int passid\n" + " ){\n" @@ -45,7 +45,7 @@ public class IfElseAndTest extends com.aparapi.codegen.CodeGenJUnitBase { + " return;\n" + " }\n" + " }\n" - + " "}; + + ' '}; private static final Class expectedException = null; @Test diff --git a/src/test/java/com/aparapi/codegen/test/IfElseIfElseIfElseTest.java b/src/test/java/com/aparapi/codegen/test/IfElseIfElseIfElseTest.java index ab4ad638..5fbfbfa2 100644 --- a/src/test/java/com/aparapi/codegen/test/IfElseIfElseIfElseTest.java +++ b/src/test/java/com/aparapi/codegen/test/IfElseIfElseIfElseTest.java @@ -22,12 +22,12 @@ public class IfElseIfElseIfElseTest extends com.aparapi.codegen.CodeGenJUnitBase private static final String[] expectedOpenCL = { "typedef struct This_s{\n" + " int passid;\n" - + "\n" + + '\n' + " }This;\n" + " int get_pass_id(This *this){\n" + " return this->passid;\n" + " }\n" - + "\n" + + '\n' + " __kernel void run(\n" + " int passid\n" + " ){\n" @@ -54,7 +54,7 @@ public class IfElseIfElseIfElseTest extends com.aparapi.codegen.CodeGenJUnitBase + " return;\n" + " }\n" + " }\n" - + " "}; + + ' '}; private static final Class expectedException = null; @Test diff --git a/src/test/java/com/aparapi/codegen/test/IfElseNot__OrOr_And_Test.java b/src/test/java/com/aparapi/codegen/test/IfElseNot__OrOr_And_Test.java index 778de595..c3db1212 100644 --- a/src/test/java/com/aparapi/codegen/test/IfElseNot__OrOr_And_Test.java +++ b/src/test/java/com/aparapi/codegen/test/IfElseNot__OrOr_And_Test.java @@ -21,13 +21,13 @@ public class IfElseNot__OrOr_And_Test extends com.aparapi.codegen.CodeGenJUnitBa private static final String[] expectedOpenCL = { "typedef struct This_s{\n" - + "\n" + + '\n' + " int passid;\n" + " }This;\n" + " int get_pass_id(This *this){\n" + " return this->passid;\n" + " }\n" - + "\n" + + '\n' + " __kernel void run(\n" + " int passid\n" + " ){\n" @@ -45,7 +45,7 @@ public class IfElseNot__OrOr_And_Test extends com.aparapi.codegen.CodeGenJUnitBa + " return;\n" + " }\n" + " }\n" - + " "}; + + ' '}; private static final Class expectedException = null; @Test diff --git a/src/test/java/com/aparapi/codegen/test/IfElseOrOrAndTest.java b/src/test/java/com/aparapi/codegen/test/IfElseOrOrAndTest.java index 1c3ccfcb..46c50cd9 100644 --- a/src/test/java/com/aparapi/codegen/test/IfElseOrOrAndTest.java +++ b/src/test/java/com/aparapi/codegen/test/IfElseOrOrAndTest.java @@ -21,13 +21,13 @@ public class IfElseOrOrAndTest extends com.aparapi.codegen.CodeGenJUnitBase { private static final String[] expectedOpenCL = { "typedef struct This_s{\n" - + "\n" + + '\n' + " int passid;\n" + " }This;\n" + " int get_pass_id(This *this){\n" + " return this->passid;\n" + " }\n" - + "\n" + + '\n' + " __kernel void run(\n" + " int passid\n" + " ){\n" @@ -45,7 +45,7 @@ public class IfElseOrOrAndTest extends com.aparapi.codegen.CodeGenJUnitBase { + " return;\n" + " }\n" + " }\n" - + " "}; + + ' '}; private static final Class expectedException = null; @Test diff --git a/src/test/java/com/aparapi/codegen/test/IfElseOrOrOrTest.java b/src/test/java/com/aparapi/codegen/test/IfElseOrOrOrTest.java index b0b9b5c0..8804537c 100644 --- a/src/test/java/com/aparapi/codegen/test/IfElseOrOrOrTest.java +++ b/src/test/java/com/aparapi/codegen/test/IfElseOrOrOrTest.java @@ -21,13 +21,13 @@ public class IfElseOrOrOrTest extends com.aparapi.codegen.CodeGenJUnitBase { private static final String[] expectedOpenCL = { "typedef struct This_s{\n" - + "\n" + + '\n' + " int passid;\n" + " }This;\n" + " int get_pass_id(This *this){\n" + " return this->passid;\n" + " }\n" - + "\n" + + '\n' + " __kernel void run(\n" + " int passid\n" + " ){\n" @@ -45,7 +45,7 @@ public class IfElseOrOrOrTest extends com.aparapi.codegen.CodeGenJUnitBase { + " return;\n" + " }\n" + " }\n" - + " "}; + + ' '}; private static final Class expectedException = null; @Test diff --git a/src/test/java/com/aparapi/codegen/test/IfElseTest.java b/src/test/java/com/aparapi/codegen/test/IfElseTest.java index 1c19bce7..83843a7f 100644 --- a/src/test/java/com/aparapi/codegen/test/IfElseTest.java +++ b/src/test/java/com/aparapi/codegen/test/IfElseTest.java @@ -21,13 +21,13 @@ public class IfElseTest extends com.aparapi.codegen.CodeGenJUnitBase { private static final String[] expectedOpenCL = { "typedef struct This_s{\n" - + "\n" + + '\n' + " int passid;\n" + " }This;\n" + " int get_pass_id(This *this){\n" + " return this->passid;\n" + " }\n" - + "\n" + + '\n' + " __kernel void run(\n" + " int passid\n" + " ){\n" @@ -45,7 +45,7 @@ public class IfElseTest extends com.aparapi.codegen.CodeGenJUnitBase { + " return;\n" + " }\n" + " }\n" - + " "}; + + ' '}; private static final Class expectedException = null; diff --git a/src/test/java/com/aparapi/codegen/test/IfElse_And_Or_AndTest.java b/src/test/java/com/aparapi/codegen/test/IfElse_And_Or_AndTest.java index 60130a6e..41822a26 100644 --- a/src/test/java/com/aparapi/codegen/test/IfElse_And_Or_AndTest.java +++ b/src/test/java/com/aparapi/codegen/test/IfElse_And_Or_AndTest.java @@ -21,13 +21,13 @@ public class IfElse_And_Or_AndTest extends com.aparapi.codegen.CodeGenJUnitBase private static final String[] expectedOpenCL = { "typedef struct This_s{\n" - + "\n" + + '\n' + " int passid;\n" + " }This;\n" + " int get_pass_id(This *this){\n" + " return this->passid;\n" + " }\n" - + "\n" + + '\n' + " __kernel void run(\n" + " int passid\n" + " ){\n" @@ -46,7 +46,7 @@ public class IfElse_And_Or_AndTest extends com.aparapi.codegen.CodeGenJUnitBase + " return;\n" + " }\n" + " }\n" - + " "}; + + ' '}; private static final Class expectedException = null; @Test diff --git a/src/test/java/com/aparapi/codegen/test/IfElse_OrOr_AndTest.java b/src/test/java/com/aparapi/codegen/test/IfElse_OrOr_AndTest.java index 8dbcb21a..1c004ed9 100644 --- a/src/test/java/com/aparapi/codegen/test/IfElse_OrOr_AndTest.java +++ b/src/test/java/com/aparapi/codegen/test/IfElse_OrOr_AndTest.java @@ -21,13 +21,13 @@ public class IfElse_OrOr_AndTest extends com.aparapi.codegen.CodeGenJUnitBase { private static final String[] expectedOpenCL = { "typedef struct This_s{\n" - + "\n" + + '\n' + " int passid;\n" + " }This;\n" + " int get_pass_id(This *this){\n" + " return this->passid;\n" + " }\n" - + "\n" + + '\n' + " __kernel void run(\n" + " int passid\n" + " ){\n" @@ -45,7 +45,7 @@ public class IfElse_OrOr_AndTest extends com.aparapi.codegen.CodeGenJUnitBase { + " return;\n" + " }\n" + " }\n" - + " "}; + + ' '}; private static final Class expectedException = null; @Test diff --git a/src/test/java/com/aparapi/codegen/test/IfElse_Or_And_OrTest.java b/src/test/java/com/aparapi/codegen/test/IfElse_Or_And_OrTest.java index 66ab19fa..5e4694ed 100644 --- a/src/test/java/com/aparapi/codegen/test/IfElse_Or_And_OrTest.java +++ b/src/test/java/com/aparapi/codegen/test/IfElse_Or_And_OrTest.java @@ -21,13 +21,13 @@ public class IfElse_Or_And_OrTest extends com.aparapi.codegen.CodeGenJUnitBase { private static final String[] expectedOpenCL = { "typedef struct This_s{\n" - + "\n" + + '\n' + " int passid;\n" + " }This;\n" + " int get_pass_id(This *this){\n" + " return this->passid;\n" + " }\n" - + "\n" + + '\n' + " __kernel void run(\n" + " int passid\n" + " ){\n" @@ -46,7 +46,7 @@ public class IfElse_Or_And_OrTest extends com.aparapi.codegen.CodeGenJUnitBase { + " return;\n" + " }\n" + " }\n" - + " "}; + + ' '}; private static final Class expectedException = null; @Test diff --git a/src/test/java/com/aparapi/codegen/test/IfOrAndOrTest.java b/src/test/java/com/aparapi/codegen/test/IfOrAndOrTest.java index b2852ab3..e730d2d8 100644 --- a/src/test/java/com/aparapi/codegen/test/IfOrAndOrTest.java +++ b/src/test/java/com/aparapi/codegen/test/IfOrAndOrTest.java @@ -21,13 +21,13 @@ public class IfOrAndOrTest extends com.aparapi.codegen.CodeGenJUnitBase { private static final String[] expectedOpenCL = { "typedef struct This_s{\n" - + "\n" + + '\n' + " int passid;\n" + " }This;\n" + " int get_pass_id(This *this){\n" + " return this->passid;\n" + " }\n" - + "\n" + + '\n' + " __kernel void run(\n" + " int passid\n" + " ){\n" @@ -43,7 +43,7 @@ public class IfOrAndOrTest extends com.aparapi.codegen.CodeGenJUnitBase { + " return;\n" + " }\n" + " }\n" - + " "}; + + ' '}; private static final Class expectedException = null; @Test diff --git a/src/test/java/com/aparapi/codegen/test/IfOrOrAndTest.java b/src/test/java/com/aparapi/codegen/test/IfOrOrAndTest.java index c50ca18f..fa845286 100644 --- a/src/test/java/com/aparapi/codegen/test/IfOrOrAndTest.java +++ b/src/test/java/com/aparapi/codegen/test/IfOrOrAndTest.java @@ -21,13 +21,13 @@ public class IfOrOrAndTest extends com.aparapi.codegen.CodeGenJUnitBase { private static final String[] expectedOpenCL = { "typedef struct This_s{\n" - + "\n" + + '\n' + " int passid;\n" + " }This;\n" + " int get_pass_id(This *this){\n" + " return this->passid;\n" + " }\n" - + "\n" + + '\n' + " __kernel void run(\n" + " int passid\n" + " ){\n" @@ -43,7 +43,7 @@ public class IfOrOrAndTest extends com.aparapi.codegen.CodeGenJUnitBase { + " return;\n" + " }\n" + " }\n" - + " "}; + + ' '}; private static final Class expectedException = null; @Test diff --git a/src/test/java/com/aparapi/codegen/test/IfOrOrOrTest.java b/src/test/java/com/aparapi/codegen/test/IfOrOrOrTest.java index 4dc25d0d..b2d5bc32 100644 --- a/src/test/java/com/aparapi/codegen/test/IfOrOrOrTest.java +++ b/src/test/java/com/aparapi/codegen/test/IfOrOrOrTest.java @@ -21,13 +21,13 @@ public class IfOrOrOrTest extends com.aparapi.codegen.CodeGenJUnitBase { private static final String[] expectedOpenCL = { "typedef struct This_s{\n" - + "\n" + + '\n' + " int passid;\n" + " }This;\n" + " int get_pass_id(This *this){\n" + " return this->passid;\n" + " }\n" - + "\n" + + '\n' + " __kernel void run(\n" + " int passid\n" + " ){\n" @@ -43,7 +43,7 @@ public class IfOrOrOrTest extends com.aparapi.codegen.CodeGenJUnitBase { + " return;\n" + " }\n" + " }\n" - + " "}; + + ' '}; private static final Class expectedException = null; @Test diff --git a/src/test/java/com/aparapi/codegen/test/IfOrOrTest.java b/src/test/java/com/aparapi/codegen/test/IfOrOrTest.java index d9ad783d..0e1eb0d7 100644 --- a/src/test/java/com/aparapi/codegen/test/IfOrOrTest.java +++ b/src/test/java/com/aparapi/codegen/test/IfOrOrTest.java @@ -21,13 +21,13 @@ public class IfOrOrTest extends com.aparapi.codegen.CodeGenJUnitBase { private static final String[] expectedOpenCL = { "typedef struct This_s{\n" - + "\n" + + '\n' + " int passid;\n" + " }This;\n" + " int get_pass_id(This *this){\n" + " return this->passid;\n" + " }\n" - + "\n" + + '\n' + " __kernel void run(\n" + " int passid\n" + " ){\n" @@ -43,7 +43,7 @@ public class IfOrOrTest extends com.aparapi.codegen.CodeGenJUnitBase { + " return;\n" + " }\n" + " }\n" - + " "}; + + ' '}; private static final Class expectedException = null; diff --git a/src/test/java/com/aparapi/codegen/test/IfOrTest.java b/src/test/java/com/aparapi/codegen/test/IfOrTest.java index a5ba4611..a0a7cf7b 100644 --- a/src/test/java/com/aparapi/codegen/test/IfOrTest.java +++ b/src/test/java/com/aparapi/codegen/test/IfOrTest.java @@ -21,13 +21,13 @@ public class IfOrTest extends com.aparapi.codegen.CodeGenJUnitBase { private static final String[] expectedOpenCL = { "typedef struct This_s{\n" - + "\n" + + '\n' + " int passid;\n" + " }This;\n" + " int get_pass_id(This *this){\n" + " return this->passid;\n" + " }\n" - + "\n" + + '\n' + " __kernel void run(\n" + " int passid\n" + " ){\n" @@ -43,7 +43,7 @@ public class IfOrTest extends com.aparapi.codegen.CodeGenJUnitBase { + " return;\n" + " }\n" + " }\n" - + " "}; + + ' '}; private static final Class expectedException = null; @Test diff --git a/src/test/java/com/aparapi/codegen/test/IfTest.java b/src/test/java/com/aparapi/codegen/test/IfTest.java index b9d30e1b..cd40ec0d 100644 --- a/src/test/java/com/aparapi/codegen/test/IfTest.java +++ b/src/test/java/com/aparapi/codegen/test/IfTest.java @@ -20,13 +20,13 @@ public class IfTest extends com.aparapi.codegen.CodeGenJUnitBase { private static final String[] expectedOpenCL = { "typedef struct This_s{\n" + -"\n" + + '\n' + " int passid;\n" + " }This;\n" + " int get_pass_id(This *this){\n" + " return this->passid;\n" + " }\n" + -"\n" + + '\n' + " __kernel void run(\n" + " int passid\n" + " ){\n" + @@ -42,7 +42,7 @@ public class IfTest extends com.aparapi.codegen.CodeGenJUnitBase { " return;\n" + " }\n" + " }\n" + -" "}; + ' '}; private static final Class expectedException = null; @Test diff --git a/src/test/java/com/aparapi/codegen/test/If_IfElseIfElseElse_ElseTest.java b/src/test/java/com/aparapi/codegen/test/If_IfElseIfElseElse_ElseTest.java index aa343693..a2490686 100644 --- a/src/test/java/com/aparapi/codegen/test/If_IfElseIfElseElse_ElseTest.java +++ b/src/test/java/com/aparapi/codegen/test/If_IfElseIfElseElse_ElseTest.java @@ -20,13 +20,13 @@ public class If_IfElseIfElseElse_ElseTest extends com.aparapi.codegen.CodeGenJUnitBase { private static final String[] expectedOpenCL = { "typedef struct This_s{\n" + -"\n" + + '\n' + " int passid;\n" + " }This;\n" + " int get_pass_id(This *this){\n" + " return this->passid;\n" + " }\n" + -"\n" + + '\n' + " __kernel void run(\n" + " int passid\n" + " ){\n" + @@ -54,7 +54,7 @@ public class If_IfElseIfElseElse_ElseTest extends com.aparapi.codegen.CodeGenJUn " return;\n" + " }\n" + " }\n" + -" "}; + ' '}; private static final Class expectedException = null; @Test diff --git a/src/test/java/com/aparapi/codegen/test/If_IfElse_ElseTest.java b/src/test/java/com/aparapi/codegen/test/If_IfElse_ElseTest.java index 19ecd703..7727094d 100644 --- a/src/test/java/com/aparapi/codegen/test/If_IfElse_ElseTest.java +++ b/src/test/java/com/aparapi/codegen/test/If_IfElse_ElseTest.java @@ -20,13 +20,13 @@ public class If_IfElse_ElseTest extends com.aparapi.codegen.CodeGenJUnitBase { private static final String[] expectedOpenCL = { "typedef struct This_s{\n" + -"\n" + + '\n' + " int passid;\n" + " }This;\n" + " int get_pass_id(This *this){\n" + " return this->passid;\n" + " }\n" + -"\n" + + '\n' + " __kernel void run(\n" + " int passid\n" + " ){\n" + @@ -49,7 +49,7 @@ public class If_IfElse_ElseTest extends com.aparapi.codegen.CodeGenJUnitBase { " return;\n" + " }\n" + " }\n" + -" "}; + ' '}; private static final Class expectedException = null; @Test diff --git a/src/test/java/com/aparapi/codegen/test/If_IfElse_Else_IfElse_Test.java b/src/test/java/com/aparapi/codegen/test/If_IfElse_Else_IfElse_Test.java index babace06..f69dcbb0 100644 --- a/src/test/java/com/aparapi/codegen/test/If_IfElse_Else_IfElse_Test.java +++ b/src/test/java/com/aparapi/codegen/test/If_IfElse_Else_IfElse_Test.java @@ -20,13 +20,13 @@ public class If_IfElse_Else_IfElse_Test extends com.aparapi.codegen.CodeGenJUnitBase { private static final String[] expectedOpenCL = { "typedef struct This_s{\n" + -"\n" + + '\n' + " int passid;\n" + " }This;\n" + " int get_pass_id(This *this){\n" + " return this->passid;\n" + " }\n" + -"\n" + + '\n' + " __kernel void run(\n" + " int passid\n" + " ){\n" + @@ -57,7 +57,7 @@ public class If_IfElse_Else_IfElse_Test extends com.aparapi.codegen.CodeGenJUnit " return;\n" + " }\n" + " }\n" + -" "}; + ' '}; private static final Class expectedException = null; @Test diff --git a/src/test/java/com/aparapi/codegen/test/If_If_Else2Test.java b/src/test/java/com/aparapi/codegen/test/If_If_Else2Test.java index 5ddc53c5..2a0c2995 100644 --- a/src/test/java/com/aparapi/codegen/test/If_If_Else2Test.java +++ b/src/test/java/com/aparapi/codegen/test/If_If_Else2Test.java @@ -20,13 +20,13 @@ public class If_If_Else2Test extends com.aparapi.codegen.CodeGenJUnitBase { private static final String[] expectedOpenCL = { "typedef struct This_s{\n" + -"\n" + + '\n' + " int passid;\n" + " }This;\n" + " int get_pass_id(This *this){\n" + " return this->passid;\n" + " }\n" + -"\n" + + '\n' + " __kernel void run(\n" + " int passid\n" + " ){\n" + @@ -45,7 +45,7 @@ public class If_If_Else2Test extends com.aparapi.codegen.CodeGenJUnitBase { " return;\n" + " }\n" + " }\n" + -" "}; + ' '}; private static final Class expectedException = null; @Test diff --git a/src/test/java/com/aparapi/codegen/test/If_If_ElseTest.java b/src/test/java/com/aparapi/codegen/test/If_If_ElseTest.java index 872814b2..c30e53f9 100644 --- a/src/test/java/com/aparapi/codegen/test/If_If_ElseTest.java +++ b/src/test/java/com/aparapi/codegen/test/If_If_ElseTest.java @@ -20,13 +20,13 @@ public class If_If_ElseTest extends com.aparapi.codegen.CodeGenJUnitBase { private static final String[] expectedOpenCL = { "typedef struct This_s{\n" + -"\n" + + '\n' + " int passid;\n" + " }This;\n" + " int get_pass_id(This *this){\n" + " return this->passid;\n" + " }\n" + -"\n" + + '\n' + " __kernel void run(\n" + " int passid\n" + " ){\n" + @@ -47,7 +47,7 @@ public class If_If_ElseTest extends com.aparapi.codegen.CodeGenJUnitBase { " return;\n" + " }\n" + " }\n" + -" "}; + ' '}; private static final Class expectedException = null; @Test diff --git a/src/test/java/com/aparapi/codegen/test/If_If_Else_If_Test.java b/src/test/java/com/aparapi/codegen/test/If_If_Else_If_Test.java index 147c20b7..5c66af3b 100644 --- a/src/test/java/com/aparapi/codegen/test/If_If_Else_If_Test.java +++ b/src/test/java/com/aparapi/codegen/test/If_If_Else_If_Test.java @@ -20,13 +20,13 @@ public class If_If_Else_If_Test extends com.aparapi.codegen.CodeGenJUnitBase { private static final String[] expectedOpenCL = { "typedef struct This_s{\n" + -"\n" + + '\n' + " int passid;\n" + " }This;\n" + " int get_pass_id(This *this){\n" + " return this->passid;\n" + " }\n" + -"\n" + + '\n' + " __kernel void run(\n" + " int passid\n" + " ){\n" + @@ -49,7 +49,7 @@ public class If_If_Else_If_Test extends com.aparapi.codegen.CodeGenJUnitBase { " return;\n" + " }\n" + " }\n" + -" "}; + ' '}; private static final Class expectedException = null; @Test diff --git a/src/test/java/com/aparapi/codegen/test/If_OrOr_AndTest.java b/src/test/java/com/aparapi/codegen/test/If_OrOr_AndTest.java index 24191f4e..715bf95d 100644 --- a/src/test/java/com/aparapi/codegen/test/If_OrOr_AndTest.java +++ b/src/test/java/com/aparapi/codegen/test/If_OrOr_AndTest.java @@ -20,13 +20,13 @@ public class If_OrOr_AndTest extends com.aparapi.codegen.CodeGenJUnitBase { private static final String[] expectedOpenCL = { "typedef struct This_s{\n" + -"\n" + + '\n' + " int passid;\n" + " }This;\n" + " int get_pass_id(This *this){\n" + " return this->passid;\n" + " }\n" + -"\n" + + '\n' + " __kernel void run(\n" + " int passid\n" + " ){\n" + @@ -42,7 +42,7 @@ public class If_OrOr_AndTest extends com.aparapi.codegen.CodeGenJUnitBase { " return;\n" + " }\n" + " }\n" + -" "}; + ' '}; private static final Class expectedException = null; @Test diff --git a/src/test/java/com/aparapi/codegen/test/If_While_ElseTest.java b/src/test/java/com/aparapi/codegen/test/If_While_ElseTest.java index 96d53946..d6033d4a 100644 --- a/src/test/java/com/aparapi/codegen/test/If_While_ElseTest.java +++ b/src/test/java/com/aparapi/codegen/test/If_While_ElseTest.java @@ -20,13 +20,13 @@ public class If_While_ElseTest extends com.aparapi.codegen.CodeGenJUnitBase { private static final String[] expectedOpenCL = { "typedef struct This_s{\n" + -"\n" + + '\n' + " int passid;\n" + " }This;\n" + " int get_pass_id(This *this){\n" + " return this->passid;\n" + " }\n" + -"\n" + + '\n' + " __kernel void run(\n" + " int passid\n" + " ){\n" + @@ -44,7 +44,7 @@ public class If_While_ElseTest extends com.aparapi.codegen.CodeGenJUnitBase { " return;\n" + " }\n" + " }\n" + -" "}; + ' '}; private static final Class expectedException = null; @Test diff --git a/src/test/java/com/aparapi/codegen/test/If_While_Else_WhileTest.java b/src/test/java/com/aparapi/codegen/test/If_While_Else_WhileTest.java index e9f42e99..5522322c 100644 --- a/src/test/java/com/aparapi/codegen/test/If_While_Else_WhileTest.java +++ b/src/test/java/com/aparapi/codegen/test/If_While_Else_WhileTest.java @@ -20,13 +20,13 @@ public class If_While_Else_WhileTest extends com.aparapi.codegen.CodeGenJUnitBase { private static final String[] expectedOpenCL = { "typedef struct This_s{\n" + -"\n" + + '\n' + " int passid;\n" + " }This;\n" + " int get_pass_id(This *this){\n" + " return this->passid;\n" + " }\n" + -"\n" + + '\n' + " __kernel void run(\n" + " int passid\n" + " ){\n" + @@ -45,7 +45,7 @@ public class If_While_Else_WhileTest extends com.aparapi.codegen.CodeGenJUnitBas " return;\n" + " }\n" + " }\n" + -" "}; + ' '}; private static final Class expectedException = null; @Test diff --git a/src/test/java/com/aparapi/codegen/test/ImplementsInterface.java b/src/test/java/com/aparapi/codegen/test/ImplementsInterface.java index 4041970c..a25171e6 100644 --- a/src/test/java/com/aparapi/codegen/test/ImplementsInterface.java +++ b/src/test/java/com/aparapi/codegen/test/ImplementsInterface.java @@ -26,10 +26,12 @@ public class ImplementsInterface extends Kernel implements IFoo { int ival = 3; + @Override public int bar(int n) { return n + ival; } + @Override public void run() { out[0] = bar(1); @SuppressWarnings("unused") boolean pass = false; diff --git a/src/test/java/com/aparapi/codegen/test/ImplementsInterfaceTest.java b/src/test/java/com/aparapi/codegen/test/ImplementsInterfaceTest.java index 7d9e5fbb..ebd91c30 100644 --- a/src/test/java/com/aparapi/codegen/test/ImplementsInterfaceTest.java +++ b/src/test/java/com/aparapi/codegen/test/ImplementsInterfaceTest.java @@ -27,7 +27,7 @@ public class ImplementsInterfaceTest extends com.aparapi.codegen.CodeGenJUnitBas " int get_pass_id(This *this){\n" + " return this->passid;\n" + " }\n" + -"\n" + + '\n' + " int com_aparapi_codegen_test_ImplementsInterface__bar(This *this, int n){\n" + " return((n + this->ival));\n" + " }\n" + @@ -47,7 +47,7 @@ public class ImplementsInterfaceTest extends com.aparapi.codegen.CodeGenJUnitBas " return;\n" + " }\n" + " }\n" + -" "}; + ' '}; private static final Class expectedException = null; @Test diff --git a/src/test/java/com/aparapi/codegen/test/IncArrayArgContentTest.java b/src/test/java/com/aparapi/codegen/test/IncArrayArgContentTest.java index 253a7c4a..12f8c79a 100644 --- a/src/test/java/com/aparapi/codegen/test/IncArrayArgContentTest.java +++ b/src/test/java/com/aparapi/codegen/test/IncArrayArgContentTest.java @@ -26,7 +26,7 @@ public class IncArrayArgContentTest extends com.aparapi.codegen.CodeGenJUnitBase " int get_pass_id(This *this){\n" + " return this->passid;\n" + " }\n" + -"\n" + + '\n' + " void com_aparapi_codegen_test_IncArrayArgContent__incit(This *this, __global int* arr){\n" + " arr[0] = arr[0] + 1;\n" + " return;\n" + @@ -44,7 +44,7 @@ public class IncArrayArgContentTest extends com.aparapi.codegen.CodeGenJUnitBase " return;\n" + " }\n" + " }\n" + -" "}; + ' '}; private static final Class expectedException = null; @Test diff --git a/src/test/java/com/aparapi/codegen/test/IndirectRecursion.java b/src/test/java/com/aparapi/codegen/test/IndirectRecursion.java index 4e5ef7a4..3cf4b68c 100644 --- a/src/test/java/com/aparapi/codegen/test/IndirectRecursion.java +++ b/src/test/java/com/aparapi/codegen/test/IndirectRecursion.java @@ -21,6 +21,7 @@ public class IndirectRecursion extends Kernel { int intout[] = new int[1]; + @Override public void run() { intout[0] = foo(10); @SuppressWarnings("unused") boolean pass = false; diff --git a/src/test/java/com/aparapi/codegen/test/Interface.java b/src/test/java/com/aparapi/codegen/test/Interface.java index ca1da431..df6fddb4 100644 --- a/src/test/java/com/aparapi/codegen/test/Interface.java +++ b/src/test/java/com/aparapi/codegen/test/Interface.java @@ -28,7 +28,8 @@ public interface Operator { public double operate(double d); } - public class SimpleAdder implements Operator { + public static class SimpleAdder implements Operator { + @Override public double operate(double d) { return d + 1.0; } diff --git a/src/test/java/com/aparapi/codegen/test/LongCompare.java b/src/test/java/com/aparapi/codegen/test/LongCompare.java index 68bb343d..30bf5e67 100644 --- a/src/test/java/com/aparapi/codegen/test/LongCompare.java +++ b/src/test/java/com/aparapi/codegen/test/LongCompare.java @@ -18,6 +18,7 @@ import com.aparapi.Kernel; public class LongCompare extends Kernel { + @Override public void run() { long n1 = 1; long n2 = 2; diff --git a/src/test/java/com/aparapi/codegen/test/LongCompareTest.java b/src/test/java/com/aparapi/codegen/test/LongCompareTest.java index 558ea2d3..bb4cf931 100644 --- a/src/test/java/com/aparapi/codegen/test/LongCompareTest.java +++ b/src/test/java/com/aparapi/codegen/test/LongCompareTest.java @@ -20,13 +20,13 @@ public class LongCompareTest extends com.aparapi.codegen.CodeGenJUnitBase { private static final String[] expectedOpenCL = { "typedef struct This_s{\n" + -"\n" + + '\n' + " int passid;\n" + " }This;\n" + " int get_pass_id(This *this){\n" + " return this->passid;\n" + " }\n" + -"\n" + + '\n' + " __kernel void run(\n" + " int passid\n" + " ){\n" + @@ -43,8 +43,8 @@ public class LongCompareTest extends com.aparapi.codegen.CodeGenJUnitBase { " return;\n" + " }\n" + " }\n" + -"\n" + -" "}; + '\n' + + ' '}; private static final Class expectedException = null; @Test diff --git a/src/test/java/com/aparapi/codegen/test/LongComparesTest.java b/src/test/java/com/aparapi/codegen/test/LongComparesTest.java index 6dfd649d..1095fca1 100644 --- a/src/test/java/com/aparapi/codegen/test/LongComparesTest.java +++ b/src/test/java/com/aparapi/codegen/test/LongComparesTest.java @@ -41,7 +41,7 @@ public class LongComparesTest extends com.aparapi.codegen.CodeGenJUnitBase { " return;\n" + " }\n" + " }\n" + -" "}; + ' '}; private static final Class expectedException = null; @Test diff --git a/src/test/java/com/aparapi/codegen/test/LoopsTest.java b/src/test/java/com/aparapi/codegen/test/LoopsTest.java index 31deb6f6..60d86fa9 100644 --- a/src/test/java/com/aparapi/codegen/test/LoopsTest.java +++ b/src/test/java/com/aparapi/codegen/test/LoopsTest.java @@ -42,7 +42,7 @@ public class LoopsTest extends com.aparapi.codegen.CodeGenJUnitBase { " return;\n" + " }\n" + " }\n" + -" "}; + ' '}; private static final Class expectedException = null; @Test diff --git a/src/test/java/com/aparapi/codegen/test/MathAbs.java b/src/test/java/com/aparapi/codegen/test/MathAbs.java index ca11d573..9afb50bc 100644 --- a/src/test/java/com/aparapi/codegen/test/MathAbs.java +++ b/src/test/java/com/aparapi/codegen/test/MathAbs.java @@ -18,6 +18,7 @@ import com.aparapi.Kernel; public class MathAbs extends Kernel { + @Override public void run() { double d = -1.0; float f = -1.0f; diff --git a/src/test/java/com/aparapi/codegen/test/MathAbsTest.java b/src/test/java/com/aparapi/codegen/test/MathAbsTest.java index 836e079b..a5699742 100644 --- a/src/test/java/com/aparapi/codegen/test/MathAbsTest.java +++ b/src/test/java/com/aparapi/codegen/test/MathAbsTest.java @@ -20,15 +20,15 @@ public class MathAbsTest extends com.aparapi.codegen.CodeGenJUnitBase { private static final String[] expectedOpenCL = { "#pragma OPENCL EXTENSION cl_khr_fp64 : enable\n" + -"\n" + + '\n' + " typedef struct This_s{\n" + -"\n" + + '\n' + " int passid;\n" + " }This;\n" + " int get_pass_id(This *this){\n" + " return this->passid;\n" + " }\n" + -"\n" + + '\n' + " __kernel void run(\n" + " int passid\n" + " ){\n" + @@ -47,7 +47,7 @@ public class MathAbsTest extends com.aparapi.codegen.CodeGenJUnitBase { " return;\n" + " }\n" + " }\n" + -" "}; + ' '}; private static final Class expectedException = null; @Test diff --git a/src/test/java/com/aparapi/codegen/test/MathDegRad.java b/src/test/java/com/aparapi/codegen/test/MathDegRad.java index 676c8753..0a92cfa7 100644 --- a/src/test/java/com/aparapi/codegen/test/MathDegRad.java +++ b/src/test/java/com/aparapi/codegen/test/MathDegRad.java @@ -18,6 +18,7 @@ import com.aparapi.Kernel; public class MathDegRad extends Kernel { + @Override public void run() { double d = -1.0; float f = -1.0f; diff --git a/src/test/java/com/aparapi/codegen/test/MathDegRadTest.java b/src/test/java/com/aparapi/codegen/test/MathDegRadTest.java index 79db96b7..9b4844f7 100644 --- a/src/test/java/com/aparapi/codegen/test/MathDegRadTest.java +++ b/src/test/java/com/aparapi/codegen/test/MathDegRadTest.java @@ -20,15 +20,15 @@ public class MathDegRadTest extends com.aparapi.codegen.CodeGenJUnitBase { private static final String[] expectedOpenCL = { "#pragma OPENCL EXTENSION cl_khr_fp64 : enable\n" + -"\n" + + '\n' + " typedef struct This_s{\n" + -"\n" + + '\n' + " int passid;\n" + " }This;\n" + " int get_pass_id(This *this){\n" + " return this->passid;\n" + " }\n" + -"\n" + + '\n' + " __kernel void run(\n" + " int passid\n" + " ){\n" + @@ -45,7 +45,7 @@ public class MathDegRadTest extends com.aparapi.codegen.CodeGenJUnitBase { " return;\n" + " }\n" + " }\n" + -" "}; + ' '}; private static final Class expectedException = null; @Test diff --git a/src/test/java/com/aparapi/codegen/test/MathFallThru.java b/src/test/java/com/aparapi/codegen/test/MathFallThru.java index 76a2dd89..e2e53cea 100644 --- a/src/test/java/com/aparapi/codegen/test/MathFallThru.java +++ b/src/test/java/com/aparapi/codegen/test/MathFallThru.java @@ -22,6 +22,7 @@ public class MathFallThru extends Kernel { long longout[] = new long[3]; int intout[] = new int[3]; + @Override public void run() { float f1 = 1.0f; double d1 = 1.0; diff --git a/src/test/java/com/aparapi/codegen/test/MathFallThruTest.java b/src/test/java/com/aparapi/codegen/test/MathFallThruTest.java index 0c7f2893..8ab7aa6e 100644 --- a/src/test/java/com/aparapi/codegen/test/MathFallThruTest.java +++ b/src/test/java/com/aparapi/codegen/test/MathFallThruTest.java @@ -20,7 +20,7 @@ public class MathFallThruTest extends com.aparapi.codegen.CodeGenJUnitBase { private static final String[] expectedOpenCL = { "#pragma OPENCL EXTENSION cl_khr_fp64 : enable\n" + -"\n" + + '\n' + " typedef struct This_s{\n" + " __global long *longout;\n" + " __global int *intout;\n" + @@ -29,7 +29,7 @@ public class MathFallThruTest extends com.aparapi.codegen.CodeGenJUnitBase { " int get_pass_id(This *this){\n" + " return this->passid;\n" + " }\n" + -"\n" + + '\n' + " __kernel void run(\n" + " __global long *longout,\n" + " __global int *intout,\n" + @@ -53,8 +53,8 @@ public class MathFallThruTest extends com.aparapi.codegen.CodeGenJUnitBase { " return;\n" + " }\n" + " }\n" + -"\n" + -" "}; + '\n' + + ' '}; private static final Class expectedException = null; @Test diff --git a/src/test/java/com/aparapi/codegen/test/MathMax.java b/src/test/java/com/aparapi/codegen/test/MathMax.java index 9faf762c..9b685d70 100644 --- a/src/test/java/com/aparapi/codegen/test/MathMax.java +++ b/src/test/java/com/aparapi/codegen/test/MathMax.java @@ -18,6 +18,7 @@ import com.aparapi.Kernel; public class MathMax extends Kernel { + @Override public void run() { double d1 = -1.0, d2 = 1.0; float f1 = -1.0f, f2 = 1.0f; diff --git a/src/test/java/com/aparapi/codegen/test/MathMaxTest.java b/src/test/java/com/aparapi/codegen/test/MathMaxTest.java index 5a276be4..c3c0e681 100644 --- a/src/test/java/com/aparapi/codegen/test/MathMaxTest.java +++ b/src/test/java/com/aparapi/codegen/test/MathMaxTest.java @@ -20,15 +20,15 @@ public class MathMaxTest extends com.aparapi.codegen.CodeGenJUnitBase { private static final String[] expectedOpenCL = { "#pragma OPENCL EXTENSION cl_khr_fp64 : enable\n" + -"\n" + + '\n' + " typedef struct This_s{\n" + -"\n" + + '\n' + " int passid;\n" + " }This;\n" + " int get_pass_id(This *this){\n" + " return this->passid;\n" + " }\n" + -"\n" + + '\n' + " __kernel void run(\n" + " int passid\n" + " ){\n" + @@ -51,8 +51,8 @@ public class MathMaxTest extends com.aparapi.codegen.CodeGenJUnitBase { " return;\n" + " }\n" + " }\n" + -"\n" + -" "}; + '\n' + + ' '}; private static final Class expectedException = null; @Test diff --git a/src/test/java/com/aparapi/codegen/test/MathMin.java b/src/test/java/com/aparapi/codegen/test/MathMin.java index fc16404f..476a3570 100644 --- a/src/test/java/com/aparapi/codegen/test/MathMin.java +++ b/src/test/java/com/aparapi/codegen/test/MathMin.java @@ -18,6 +18,7 @@ import com.aparapi.Kernel; public class MathMin extends Kernel { + @Override public void run() { double d1 = -1.0, d2 = 1.0; float f1 = -1.0f, f2 = 1.0f; diff --git a/src/test/java/com/aparapi/codegen/test/MathMinTest.java b/src/test/java/com/aparapi/codegen/test/MathMinTest.java index 72823b7b..bb5869d8 100644 --- a/src/test/java/com/aparapi/codegen/test/MathMinTest.java +++ b/src/test/java/com/aparapi/codegen/test/MathMinTest.java @@ -20,15 +20,15 @@ public class MathMinTest extends com.aparapi.codegen.CodeGenJUnitBase { private static final String[] expectedOpenCL = { "#pragma OPENCL EXTENSION cl_khr_fp64 : enable\n" + -"\n" + + '\n' + " typedef struct This_s{\n" + -"\n" + + '\n' + " int passid;\n" + " }This;\n" + " int get_pass_id(This *this){\n" + " return this->passid;\n" + " }\n" + -"\n" + + '\n' + " __kernel void run(\n" + " int passid\n" + " ){\n" + @@ -51,8 +51,8 @@ public class MathMinTest extends com.aparapi.codegen.CodeGenJUnitBase { " return;\n" + " }\n" + " }\n" + -"\n" + -" "}; + '\n' + + ' '}; private static final Class expectedException = null; @Test diff --git a/src/test/java/com/aparapi/codegen/test/MathRemainder.java b/src/test/java/com/aparapi/codegen/test/MathRemainder.java index eb377bdb..ef94f391 100644 --- a/src/test/java/com/aparapi/codegen/test/MathRemainder.java +++ b/src/test/java/com/aparapi/codegen/test/MathRemainder.java @@ -18,6 +18,7 @@ import com.aparapi.Kernel; public class MathRemainder extends Kernel { + @Override public void run() { double d1 = 7.0, d2 = 2.0; float f1 = 7.0f, f2 = 2.0f; diff --git a/src/test/java/com/aparapi/codegen/test/MathRemainderTest.java b/src/test/java/com/aparapi/codegen/test/MathRemainderTest.java index 97bb42c1..02909797 100644 --- a/src/test/java/com/aparapi/codegen/test/MathRemainderTest.java +++ b/src/test/java/com/aparapi/codegen/test/MathRemainderTest.java @@ -20,15 +20,15 @@ public class MathRemainderTest extends com.aparapi.codegen.CodeGenJUnitBase { private static final String[] expectedOpenCL = { "#pragma OPENCL EXTENSION cl_khr_fp64 : enable\n" + -"\n" + + '\n' + " typedef struct This_s{\n" + -"\n" + + '\n' + " int passid;\n" + " }This;\n" + " int get_pass_id(This *this){\n" + " return this->passid;\n" + " }\n" + -"\n" + + '\n' + " __kernel void run(\n" + " int passid\n" + " ){\n" + @@ -47,7 +47,7 @@ public class MathRemainderTest extends com.aparapi.codegen.CodeGenJUnitBase { " return;\n" + " }\n" + " }\n" + -" "}; + ' '}; private static final Class expectedException = null; @Test diff --git a/src/test/java/com/aparapi/codegen/test/MultiContinueTest.java b/src/test/java/com/aparapi/codegen/test/MultiContinueTest.java index ba6db517..f3ca1b9c 100644 --- a/src/test/java/com/aparapi/codegen/test/MultiContinueTest.java +++ b/src/test/java/com/aparapi/codegen/test/MultiContinueTest.java @@ -20,13 +20,13 @@ public class MultiContinueTest extends com.aparapi.codegen.CodeGenJUnitBase { private static final String[] expectedOpenCL = { "typedef struct This_s{\n" + -"\n" + + '\n' + " int passid;\n" + " }This;\n" + " int get_pass_id(This *this){\n" + " return this->passid;\n" + " }\n" + -"\n" + + '\n' + " __kernel void run(\n" + " int passid\n" + " ){\n" + @@ -53,7 +53,7 @@ public class MultiContinueTest extends com.aparapi.codegen.CodeGenJUnitBase { " return;\n" + " }\n" + " }\n" + -" "}; + ' '}; private static final Class expectedException = null; @Test diff --git a/src/test/java/com/aparapi/codegen/test/MultipleAssignExprTest.java b/src/test/java/com/aparapi/codegen/test/MultipleAssignExprTest.java index 19ef61aa..791b23d9 100644 --- a/src/test/java/com/aparapi/codegen/test/MultipleAssignExprTest.java +++ b/src/test/java/com/aparapi/codegen/test/MultipleAssignExprTest.java @@ -20,13 +20,13 @@ public class MultipleAssignExprTest extends com.aparapi.codegen.CodeGenJUnitBase { private static final String[] expectedOpenCL = { "typedef struct This_s{\n" + -"\n" + + '\n' + " int passid;\n" + " }This;\n" + " int get_pass_id(This *this){\n" + " return this->passid;\n" + " }\n" + -"\n" + + '\n' + " int com_aparapi_codegen_test_MultipleAssignExpr__sum(This *this, int lhs, int rhs){\n" + " return((lhs + rhs));\n" + " }\n" + @@ -44,7 +44,7 @@ public class MultipleAssignExprTest extends com.aparapi.codegen.CodeGenJUnitBase " return;\n" + " }\n" + " }\n" + -" "}; + ' '}; private static final Class expectedException = null; @Test diff --git a/src/test/java/com/aparapi/codegen/test/MultipleAssignTest.java b/src/test/java/com/aparapi/codegen/test/MultipleAssignTest.java index 1d26c90f..2b667ee5 100644 --- a/src/test/java/com/aparapi/codegen/test/MultipleAssignTest.java +++ b/src/test/java/com/aparapi/codegen/test/MultipleAssignTest.java @@ -20,13 +20,13 @@ public class MultipleAssignTest extends com.aparapi.codegen.CodeGenJUnitBase { private static final String[] expectedOpenCL = { "typedef struct This_s{\n" + -"\n" + + '\n' + " int passid;\n" + " }This;\n" + " int get_pass_id(This *this){\n" + " return this->passid;\n" + " }\n" + -"\n" + + '\n' + " __kernel void run(\n" + " int passid\n" + " ){\n" + @@ -41,7 +41,7 @@ public class MultipleAssignTest extends com.aparapi.codegen.CodeGenJUnitBase { " return;\n" + " }\n" + " }\n" + -" "}; + ' '}; private static final Class expectedException = null; @Test diff --git a/src/test/java/com/aparapi/codegen/test/NaNTest.java b/src/test/java/com/aparapi/codegen/test/NaNTest.java index a3f71b83..48104ad9 100644 --- a/src/test/java/com/aparapi/codegen/test/NaNTest.java +++ b/src/test/java/com/aparapi/codegen/test/NaNTest.java @@ -20,15 +20,15 @@ public class NaNTest extends com.aparapi.codegen.CodeGenJUnitBase { private static final String[] expectedOpenCL = { "#pragma OPENCL EXTENSION cl_khr_fp64 : enable\n" + -"\n" + + '\n' + " typedef struct This_s{\n" + -"\n" + + '\n' + " int passid;\n" + " }This;\n" + " int get_pass_id(This *this){\n" + " return this->passid;\n" + " }\n" + -"\n" + + '\n' + " __kernel void run(\n" + " int passid\n" + " ){\n" + @@ -40,7 +40,7 @@ public class NaNTest extends com.aparapi.codegen.CodeGenJUnitBase { " return;\n" + " }\n" + " }\n" + -" "}; + ' '}; private static final Class expectedException = null; @Test diff --git a/src/test/java/com/aparapi/codegen/test/NewLocalArrayTest.java b/src/test/java/com/aparapi/codegen/test/NewLocalArrayTest.java index f316a8a3..cd18cfe2 100644 --- a/src/test/java/com/aparapi/codegen/test/NewLocalArrayTest.java +++ b/src/test/java/com/aparapi/codegen/test/NewLocalArrayTest.java @@ -20,13 +20,13 @@ public class NewLocalArrayTest extends com.aparapi.codegen.CodeGenJUnitBase { private static final String[] expectedOpenCL = { "typedef struct This_s{\n" + -"\n" + + '\n' + " int passid;\n" + " }This;\n" + " int get_pass_id(This *this){\n" + " return this->passid;\n" + " }\n" + -"\n" + + '\n' + " __kernel void run(\n" + " int passid\n" + " ){\n" + @@ -42,7 +42,7 @@ public class NewLocalArrayTest extends com.aparapi.codegen.CodeGenJUnitBase { " return;\n" + " }\n" + " }\n" + -" "}; + ' '}; private static final Class expectedException = null; @Test diff --git a/src/test/java/com/aparapi/codegen/test/NonNullCheckTest.java b/src/test/java/com/aparapi/codegen/test/NonNullCheckTest.java index 835806fa..40ae1d6a 100644 --- a/src/test/java/com/aparapi/codegen/test/NonNullCheckTest.java +++ b/src/test/java/com/aparapi/codegen/test/NonNullCheckTest.java @@ -28,7 +28,7 @@ public class NonNullCheckTest extends com.aparapi.codegen.CodeGenJUnitBase { + " int get_pass_id(This *this){\n" + " return this->passid;\n" + " }\n" - + "\n" + + '\n' + " __kernel void run(\n" + " __global int *ints,\n" + " int passid\n" @@ -44,7 +44,7 @@ public class NonNullCheckTest extends com.aparapi.codegen.CodeGenJUnitBase { + " return;\n" + " }\n" + " }\n" - + " "}; + + ' '}; private static final Class expectedException = null; @Ignore diff --git a/src/test/java/com/aparapi/codegen/test/NullCheckTest.java b/src/test/java/com/aparapi/codegen/test/NullCheckTest.java index d3335fac..f8adb6c1 100644 --- a/src/test/java/com/aparapi/codegen/test/NullCheckTest.java +++ b/src/test/java/com/aparapi/codegen/test/NullCheckTest.java @@ -26,7 +26,7 @@ public class NullCheckTest extends com.aparapi.codegen.CodeGenJUnitBase { " int get_pass_id(This *this){\n" + " return this->passid;\n" + " }\n" + -"\n" + + '\n' + " __kernel void run(\n" + " __global int *ints,\n" + " int passid\n" + @@ -43,7 +43,7 @@ public class NullCheckTest extends com.aparapi.codegen.CodeGenJUnitBase { " return;\n" + " }\n" + " }\n" + -" "}; + ' '}; private static final Class expectedException = null; @Test diff --git a/src/test/java/com/aparapi/codegen/test/ObjectArrayCallHierarchy.java b/src/test/java/com/aparapi/codegen/test/ObjectArrayCallHierarchy.java index 5de756a1..5e445cb2 100644 --- a/src/test/java/com/aparapi/codegen/test/ObjectArrayCallHierarchy.java +++ b/src/test/java/com/aparapi/codegen/test/ObjectArrayCallHierarchy.java @@ -37,6 +37,7 @@ public int bar(int x) { return -x; } + @Override public void run() { int myId = getGlobalId(); dummy[myId].intField = bar(2) + dummy[myId].funnyGet(); diff --git a/src/test/java/com/aparapi/codegen/test/ObjectArrayCommonSuper.java b/src/test/java/com/aparapi/codegen/test/ObjectArrayCommonSuper.java index 9871090f..1893201f 100644 --- a/src/test/java/com/aparapi/codegen/test/ObjectArrayCommonSuper.java +++ b/src/test/java/com/aparapi/codegen/test/ObjectArrayCommonSuper.java @@ -34,6 +34,7 @@ public ObjectArrayCommonSuper() { ; + @Override public void run() { int myId = getGlobalId(); db[myId].intField = db[myId].getIntField() + db[myId].getBrosInt(); diff --git a/src/test/java/com/aparapi/codegen/test/ObjectArrayMemberAccess.java b/src/test/java/com/aparapi/codegen/test/ObjectArrayMemberAccess.java index 75765b76..2d182090 100644 --- a/src/test/java/com/aparapi/codegen/test/ObjectArrayMemberAccess.java +++ b/src/test/java/com/aparapi/codegen/test/ObjectArrayMemberAccess.java @@ -43,6 +43,7 @@ public int bar(int x) { return -x; } + @Override public void run() { int myId = getGlobalId(); dummy[myId].mem = dummy[myId].mem + 2; diff --git a/src/test/java/com/aparapi/codegen/test/ObjectArrayMemberAccessTest.java b/src/test/java/com/aparapi/codegen/test/ObjectArrayMemberAccessTest.java index c37c1dd0..b33552d6 100644 --- a/src/test/java/com/aparapi/codegen/test/ObjectArrayMemberAccessTest.java +++ b/src/test/java/com/aparapi/codegen/test/ObjectArrayMemberAccessTest.java @@ -22,9 +22,9 @@ public class ObjectArrayMemberAccessTest extends com.aparapi.codegen.CodeGenJUni "typedef struct com_aparapi_codegen_test_ObjectArrayMemberAccess$DummyOOA_s{\n" + " int mem;\n" + " float floatField;\n" + -"\n" + + '\n' + " } com_aparapi_codegen_test_ObjectArrayMemberAccess$DummyOOA;\n" + -"\n" + + '\n' + " typedef struct This_s{\n" + " __global com_aparapi_codegen_test_ObjectArrayMemberAccess$DummyOOA *dummy;\n" + " int passid;\n" + @@ -32,7 +32,7 @@ public class ObjectArrayMemberAccessTest extends com.aparapi.codegen.CodeGenJUni " int get_pass_id(This *this){\n" + " return this->passid;\n" + " }\n" + -"\n" + + '\n' + " __kernel void run(\n" + " __global com_aparapi_codegen_test_ObjectArrayMemberAccess$DummyOOA *dummy,\n" + " int passid\n" + @@ -48,7 +48,7 @@ public class ObjectArrayMemberAccessTest extends com.aparapi.codegen.CodeGenJUni " return;\n" + " }\n" + " }\n" + -" "}; + ' '}; private static final Class expectedException = null; @Test diff --git a/src/test/java/com/aparapi/codegen/test/ObjectArrayMemberBadGetter.java b/src/test/java/com/aparapi/codegen/test/ObjectArrayMemberBadGetter.java index 6eccfed5..502546c6 100644 --- a/src/test/java/com/aparapi/codegen/test/ObjectArrayMemberBadGetter.java +++ b/src/test/java/com/aparapi/codegen/test/ObjectArrayMemberBadGetter.java @@ -30,12 +30,13 @@ public ObjectArrayMemberBadGetter() { dummy[0] = new DummyOOA(); } + @Override public void run() { int myId = getGlobalId(); dummy[myId].setFloatField(dummy[myId].getFloatField() + (float) 2.0); } - final class DummyOOA { + static final class DummyOOA { int mem; float floatField; diff --git a/src/test/java/com/aparapi/codegen/test/ObjectArrayMemberBadSetter.java b/src/test/java/com/aparapi/codegen/test/ObjectArrayMemberBadSetter.java index 8893df32..322be9e2 100644 --- a/src/test/java/com/aparapi/codegen/test/ObjectArrayMemberBadSetter.java +++ b/src/test/java/com/aparapi/codegen/test/ObjectArrayMemberBadSetter.java @@ -30,12 +30,13 @@ public ObjectArrayMemberBadSetter() { dummy[0] = new DummyOOA(); } + @Override public void run() { int myId = getGlobalId(); dummy[myId].setFloatField(dummy[myId].getFloatField() + (float) 2.0); } - final class DummyOOA { + static final class DummyOOA { int mem; float floatField; diff --git a/src/test/java/com/aparapi/codegen/test/ObjectArrayMemberCall.java b/src/test/java/com/aparapi/codegen/test/ObjectArrayMemberCall.java index 28eb3709..e0225641 100644 --- a/src/test/java/com/aparapi/codegen/test/ObjectArrayMemberCall.java +++ b/src/test/java/com/aparapi/codegen/test/ObjectArrayMemberCall.java @@ -43,6 +43,7 @@ public int bar(int x) { return -x; } + @Override public void run() { int myId = getGlobalId(); dummy[myId].mem = dummy[myId].addEmUp(dummy[myId].mem, 2); diff --git a/src/test/java/com/aparapi/codegen/test/ObjectArrayMemberCallTest.java b/src/test/java/com/aparapi/codegen/test/ObjectArrayMemberCallTest.java index 65bde86d..1fcdaa6e 100644 --- a/src/test/java/com/aparapi/codegen/test/ObjectArrayMemberCallTest.java +++ b/src/test/java/com/aparapi/codegen/test/ObjectArrayMemberCallTest.java @@ -58,7 +58,7 @@ public class ObjectArrayMemberCallTest extends com.aparapi.codegen.CodeGenJUnitB + " int tmp2 = com_aparapi_codegen_test_ObjectArrayMemberCall$DummyOOA__addEmUpPlusOne( &(this->dummy[myId]), 2, tmp);\n" + " return;\n" + " }\n" - + "}"}; + + '}'}; private static final Class expectedException = null; @Test diff --git a/src/test/java/com/aparapi/codegen/test/ObjectArrayMemberGetterSetter.java b/src/test/java/com/aparapi/codegen/test/ObjectArrayMemberGetterSetter.java index f0f6d76b..c85e32e6 100644 --- a/src/test/java/com/aparapi/codegen/test/ObjectArrayMemberGetterSetter.java +++ b/src/test/java/com/aparapi/codegen/test/ObjectArrayMemberGetterSetter.java @@ -111,6 +111,7 @@ public int bar(int x) { return -x; } + @Override public void run() { int myId = getGlobalId(); diff --git a/src/test/java/com/aparapi/codegen/test/ObjectArrayMemberGetterSetterTest.java b/src/test/java/com/aparapi/codegen/test/ObjectArrayMemberGetterSetterTest.java index 554829d9..c998d31b 100644 --- a/src/test/java/com/aparapi/codegen/test/ObjectArrayMemberGetterSetterTest.java +++ b/src/test/java/com/aparapi/codegen/test/ObjectArrayMemberGetterSetterTest.java @@ -34,7 +34,7 @@ public class ObjectArrayMemberGetterSetterTest extends com.aparapi.codegen.CodeG + " char _pad_23;\n" + " \n" + "} com_aparapi_codegen_test_DummyOOA;\n" - + "\n" + + '\n' + "typedef struct com_aparapi_codegen_test_TheOtherOne_s{\n" + " int mem;\n" + " \n" @@ -116,7 +116,7 @@ public class ObjectArrayMemberGetterSetterTest extends com.aparapi.codegen.CodeG + " this->out[myId] = com_aparapi_codegen_test_ObjectArrayMemberGetterSetter__getSomething(this);\n" + " return;\n" + " }\n" - + "}"}; + + '}'}; private static final Class expectedException = null; @Test diff --git a/src/test/java/com/aparapi/codegen/test/ObjectArrayMemberHierarchy.java b/src/test/java/com/aparapi/codegen/test/ObjectArrayMemberHierarchy.java index a7a5354c..431143b0 100644 --- a/src/test/java/com/aparapi/codegen/test/ObjectArrayMemberHierarchy.java +++ b/src/test/java/com/aparapi/codegen/test/ObjectArrayMemberHierarchy.java @@ -42,6 +42,7 @@ public int bar(int x) { return -x; } + @Override public void run() { int myId = getGlobalId(); dummy[myId].intField = dummy[myId].getIntField() + 2 + getSomething(); diff --git a/src/test/java/com/aparapi/codegen/test/ObjectArrayMemberHierarchyTest.java b/src/test/java/com/aparapi/codegen/test/ObjectArrayMemberHierarchyTest.java index 375ed62b..f7265bb4 100644 --- a/src/test/java/com/aparapi/codegen/test/ObjectArrayMemberHierarchyTest.java +++ b/src/test/java/com/aparapi/codegen/test/ObjectArrayMemberHierarchyTest.java @@ -59,7 +59,7 @@ public class ObjectArrayMemberHierarchyTest extends com.aparapi.codegen.CodeGenJ + " com_aparapi_codegen_test_ObjectArrayMemberHierarchy$DummyOOA__setFloatField( &(this->dummy[myId]), (this->dummy[myId].floatField + 2.0f));\n" + " return;\n" + " }\n" - + "}"}; + + '}'}; private static final Class expectedException = null; @Test diff --git a/src/test/java/com/aparapi/codegen/test/ObjectArrayMemberNotFinal.java b/src/test/java/com/aparapi/codegen/test/ObjectArrayMemberNotFinal.java index 4fa0f874..9c677ff9 100644 --- a/src/test/java/com/aparapi/codegen/test/ObjectArrayMemberNotFinal.java +++ b/src/test/java/com/aparapi/codegen/test/ObjectArrayMemberNotFinal.java @@ -92,6 +92,7 @@ public int bar(int x) { return -x; } + @Override public void run() { int myId = getGlobalId(); diff --git a/src/test/java/com/aparapi/codegen/test/ObjectRefCopy.java b/src/test/java/com/aparapi/codegen/test/ObjectRefCopy.java index 34353bf6..3a260e23 100644 --- a/src/test/java/com/aparapi/codegen/test/ObjectRefCopy.java +++ b/src/test/java/com/aparapi/codegen/test/ObjectRefCopy.java @@ -24,6 +24,7 @@ public class ObjectRefCopy extends Kernel { ; DummyOOA dummy[] = new DummyOOA[size]; + @Override public void run() { int myId = getGlobalId(); dummy[myId] = dummy[myId + 1]; diff --git a/src/test/java/com/aparapi/codegen/test/ObjectRefCopyTest.java b/src/test/java/com/aparapi/codegen/test/ObjectRefCopyTest.java index a5cff184..0e188eb5 100644 --- a/src/test/java/com/aparapi/codegen/test/ObjectRefCopyTest.java +++ b/src/test/java/com/aparapi/codegen/test/ObjectRefCopyTest.java @@ -15,8 +15,6 @@ */ package com.aparapi.codegen.test; -import com.aparapi.internal.exception.ClassParseException; -import org.junit.Ignore; import org.junit.Test; public class ObjectRefCopyTest extends com.aparapi.codegen.CodeGenJUnitBase { @@ -41,7 +39,7 @@ public class ObjectRefCopyTest extends com.aparapi.codegen.CodeGenJUnitBase { + " this->dummy[myId] = this->dummy[(myId + 1)];\n" + " return;\n" + " }\n" - + "}" + + '}' }; private static final Class expectedException = null; diff --git a/src/test/java/com/aparapi/codegen/test/ObjectWithinObject.java b/src/test/java/com/aparapi/codegen/test/ObjectWithinObject.java index c288456b..4b80de5b 100644 --- a/src/test/java/com/aparapi/codegen/test/ObjectWithinObject.java +++ b/src/test/java/com/aparapi/codegen/test/ObjectWithinObject.java @@ -21,9 +21,9 @@ public class ObjectWithinObject extends Kernel { final int size = 8; - ; DummyOOA dummy[] = new DummyOOA[size]; + @Override public void run() { int myId = getGlobalId(); dummy[myId].mem = dummy[myId].next.mem + 4; diff --git a/src/test/java/com/aparapi/codegen/test/OrAndOrPrecedenceTest.java b/src/test/java/com/aparapi/codegen/test/OrAndOrPrecedenceTest.java index 8649bded..7424982e 100644 --- a/src/test/java/com/aparapi/codegen/test/OrAndOrPrecedenceTest.java +++ b/src/test/java/com/aparapi/codegen/test/OrAndOrPrecedenceTest.java @@ -20,13 +20,13 @@ public class OrAndOrPrecedenceTest extends com.aparapi.codegen.CodeGenJUnitBase { private static final String[] expectedOpenCL = { "typedef struct This_s{\n" + -"\n" + + '\n' + " int passid;\n" + " }This;\n" + " int get_pass_id(This *this){\n" + " return this->passid;\n" + " }\n" + -"\n" + + '\n' + " __kernel void run(\n" + " int passid\n" + " ){\n" + @@ -45,7 +45,7 @@ public class OrAndOrPrecedenceTest extends com.aparapi.codegen.CodeGenJUnitBase " return;\n" + " }\n" + " }\n" + -" "}; + ' '}; private static final Class expectedException = null; diff --git a/src/test/java/com/aparapi/codegen/test/OverloadMethod.java b/src/test/java/com/aparapi/codegen/test/OverloadMethod.java index c54ca0f1..ebba7a2e 100644 --- a/src/test/java/com/aparapi/codegen/test/OverloadMethod.java +++ b/src/test/java/com/aparapi/codegen/test/OverloadMethod.java @@ -20,6 +20,7 @@ public class OverloadMethod extends Kernel { int out[] = new int[1]; + @Override public void run() { out[0] = foo(2) + foo(2, 3); } diff --git a/src/test/java/com/aparapi/codegen/test/OverloadMethodTest.java b/src/test/java/com/aparapi/codegen/test/OverloadMethodTest.java index d6d73e72..d5246992 100644 --- a/src/test/java/com/aparapi/codegen/test/OverloadMethodTest.java +++ b/src/test/java/com/aparapi/codegen/test/OverloadMethodTest.java @@ -45,7 +45,7 @@ public class OverloadMethodTest extends com.aparapi.codegen.CodeGenJUnitBase { " return;\n" + " }\n" + " }\n" + -" "}; + ' '}; private static final Class expectedException = null; diff --git a/src/test/java/com/aparapi/codegen/test/OverriddenKernelField.java b/src/test/java/com/aparapi/codegen/test/OverriddenKernelField.java index f43a3453..ff3dfba9 100644 --- a/src/test/java/com/aparapi/codegen/test/OverriddenKernelField.java +++ b/src/test/java/com/aparapi/codegen/test/OverriddenKernelField.java @@ -25,6 +25,7 @@ int foo(int n) { return out[0]; } + @Override public void run() { out[0] = foo(3); } @@ -33,10 +34,12 @@ public void run() { public class OverriddenKernelField extends OverriddenKernelFieldParent { int out[] = new int[1]; + @Override public void run() { out[0] = foo(2); } + @Override int foo(int n) { return super.foo(n + 1); } diff --git a/src/test/java/com/aparapi/codegen/test/OverriddenKernelFieldTest.java b/src/test/java/com/aparapi/codegen/test/OverriddenKernelFieldTest.java index 84821cdf..6cce2629 100644 --- a/src/test/java/com/aparapi/codegen/test/OverriddenKernelFieldTest.java +++ b/src/test/java/com/aparapi/codegen/test/OverriddenKernelFieldTest.java @@ -46,7 +46,7 @@ public class OverriddenKernelFieldTest extends com.aparapi.codegen.CodeGenJUnitB " return;\n" + " }\n" + " }\n" + -" "}; + ' '}; private static final Class expectedException = null; diff --git a/src/test/java/com/aparapi/codegen/test/PlayPenTest.java b/src/test/java/com/aparapi/codegen/test/PlayPenTest.java index 01c2387a..d780a8bf 100644 --- a/src/test/java/com/aparapi/codegen/test/PlayPenTest.java +++ b/src/test/java/com/aparapi/codegen/test/PlayPenTest.java @@ -21,13 +21,13 @@ public class PlayPenTest extends com.aparapi.codegen.CodeGenJUnitBase { private static final String[] expectedOpenCL = { "typedef struct This_s{\n" - + "\n" + + '\n' + " int passid;\n" + " }This;\n" + " int get_pass_id(This *this){\n" + " return this->passid;\n" + " }\n" - + "\n" + + '\n' + " __kernel void run(\n" + " int passid\n" + " ){\n" @@ -55,7 +55,7 @@ public class PlayPenTest extends com.aparapi.codegen.CodeGenJUnitBase { + " return;\n" + " }\n" + " }\n" - + " "}; + + ' '}; private static final Class expectedException = null; @Test diff --git a/src/test/java/com/aparapi/codegen/test/PostDecArrayItemTest.java b/src/test/java/com/aparapi/codegen/test/PostDecArrayItemTest.java index 438f715a..fcbdcfb0 100644 --- a/src/test/java/com/aparapi/codegen/test/PostDecArrayItemTest.java +++ b/src/test/java/com/aparapi/codegen/test/PostDecArrayItemTest.java @@ -28,7 +28,7 @@ public class PostDecArrayItemTest extends com.aparapi.codegen.CodeGenJUnitBase { + " int get_pass_id(This *this){\n" + " return this->passid;\n" + " }\n" - + "\n" + + '\n' + " __kernel void run(\n" + " __global int *values,\n" + " __global int *results,\n" @@ -45,7 +45,7 @@ public class PostDecArrayItemTest extends com.aparapi.codegen.CodeGenJUnitBase { + " return;\n" + " }\n" + " }\n" - + " "}; + + ' '}; private static final Class expectedException = null; @Test diff --git a/src/test/java/com/aparapi/codegen/test/PostDecByteTest.java b/src/test/java/com/aparapi/codegen/test/PostDecByteTest.java index c15acdc1..2250dc6f 100644 --- a/src/test/java/com/aparapi/codegen/test/PostDecByteTest.java +++ b/src/test/java/com/aparapi/codegen/test/PostDecByteTest.java @@ -26,7 +26,7 @@ public class PostDecByteTest extends com.aparapi.codegen.CodeGenJUnitBase { + " int get_pass_id(This *this){\n" + " return this->passid;\n" + " }\n" - + "\n" + + '\n' + " char com_aparapi_codegen_test_PostDecByte__incByte(This *this, char a){\n" + " return(a++);\n" + " }\n" @@ -42,7 +42,7 @@ public class PostDecByteTest extends com.aparapi.codegen.CodeGenJUnitBase { + " return;\n" + " }\n" + " }\n" - + " "}; + + ' '}; private static final Class expectedException = null; @Test diff --git a/src/test/java/com/aparapi/codegen/test/PostDecLocalTest.java b/src/test/java/com/aparapi/codegen/test/PostDecLocalTest.java index 632822b2..a18bc8e2 100644 --- a/src/test/java/com/aparapi/codegen/test/PostDecLocalTest.java +++ b/src/test/java/com/aparapi/codegen/test/PostDecLocalTest.java @@ -21,13 +21,13 @@ public class PostDecLocalTest extends com.aparapi.codegen.CodeGenJUnitBase { private static final String[] expectedOpenCL = { "typedef struct This_s{\n" - + "\n" + + '\n' + " int passid;\n" + " }This;\n" + " int get_pass_id(This *this){\n" + " return this->passid;\n" + " }\n" - + "\n" + + '\n' + " __kernel void run(\n" + " int passid\n" + " ){\n" @@ -43,7 +43,7 @@ public class PostDecLocalTest extends com.aparapi.codegen.CodeGenJUnitBase { + " return;\n" + " }\n" + " }\n" - + " "}; + + ' '}; private static final Class expectedException = null; @Test diff --git a/src/test/java/com/aparapi/codegen/test/PostDecPostIncTest.java b/src/test/java/com/aparapi/codegen/test/PostDecPostIncTest.java index 817f162d..9b95e19e 100644 --- a/src/test/java/com/aparapi/codegen/test/PostDecPostIncTest.java +++ b/src/test/java/com/aparapi/codegen/test/PostDecPostIncTest.java @@ -21,13 +21,13 @@ public class PostDecPostIncTest extends com.aparapi.codegen.CodeGenJUnitBase { private static final String[] expectedOpenCL = { "typedef struct This_s{\n" - + "\n" + + '\n' + " int passid;\n" + " }This;\n" + " int get_pass_id(This *this){\n" + " return this->passid;\n" + " }\n" - + "\n" + + '\n' + " __kernel void run(\n" + " int passid\n" + " ){\n" @@ -41,7 +41,7 @@ public class PostDecPostIncTest extends com.aparapi.codegen.CodeGenJUnitBase { + " return;\n" + " }\n" + " }\n" - + " "}; + + ' '}; private static final Class expectedException = null; @Test diff --git a/src/test/java/com/aparapi/codegen/test/PostIncArrayIndexAndElementTest.java b/src/test/java/com/aparapi/codegen/test/PostIncArrayIndexAndElementTest.java index 71da203b..1fd48823 100644 --- a/src/test/java/com/aparapi/codegen/test/PostIncArrayIndexAndElementTest.java +++ b/src/test/java/com/aparapi/codegen/test/PostIncArrayIndexAndElementTest.java @@ -27,7 +27,7 @@ public class PostIncArrayIndexAndElementTest extends com.aparapi.codegen.CodeGen + " int get_pass_id(This *this){\n" + " return this->passid;\n" + " }\n" - + "\n" + + '\n' + " __kernel void run(\n" + " __global int *array,\n" + " int passid\n" @@ -42,7 +42,7 @@ public class PostIncArrayIndexAndElementTest extends com.aparapi.codegen.CodeGen + " return;\n" + " }\n" + " }\n" - + " "}; + + ' '}; private static final Class expectedException = null; @Test diff --git a/src/test/java/com/aparapi/codegen/test/PostIncArrayItemAsParameterTest.java b/src/test/java/com/aparapi/codegen/test/PostIncArrayItemAsParameterTest.java index a5791b49..33bd9bb5 100644 --- a/src/test/java/com/aparapi/codegen/test/PostIncArrayItemAsParameterTest.java +++ b/src/test/java/com/aparapi/codegen/test/PostIncArrayItemAsParameterTest.java @@ -28,7 +28,7 @@ public class PostIncArrayItemAsParameterTest extends com.aparapi.codegen.CodeGen + " int get_pass_id(This *this){\n" + " return this->passid;\n" + " }\n" - + "\n" + + '\n' + " int com_aparapi_codegen_test_PostIncArrayItemAsParameter__actuallyDoIt(This *this, int a){\n" + " return(1);\n" + " }\n" @@ -47,7 +47,7 @@ public class PostIncArrayItemAsParameterTest extends com.aparapi.codegen.CodeGen + " return;\n" + " }\n" + " }\n" - + " "}; + + ' '}; private static final Class expectedException = null; @Test diff --git a/src/test/java/com/aparapi/codegen/test/PostIncArrayItemFieldIndexTest.java b/src/test/java/com/aparapi/codegen/test/PostIncArrayItemFieldIndexTest.java index 8d441f76..3973188a 100644 --- a/src/test/java/com/aparapi/codegen/test/PostIncArrayItemFieldIndexTest.java +++ b/src/test/java/com/aparapi/codegen/test/PostIncArrayItemFieldIndexTest.java @@ -29,7 +29,7 @@ public class PostIncArrayItemFieldIndexTest extends com.aparapi.codegen.CodeGenJ + " int get_pass_id(This *this){\n" + " return this->passid;\n" + " }\n" - + "\n" + + '\n' + " __kernel void run(\n" + " __global int *values,\n" + " int a,\n" @@ -47,7 +47,7 @@ public class PostIncArrayItemFieldIndexTest extends com.aparapi.codegen.CodeGenJ + " return;\n" + " }\n" + " }\n" - + " "}; + + ' '}; private static final Class expectedException = null; @Test diff --git a/src/test/java/com/aparapi/codegen/test/PostIncArrayItemTest.java b/src/test/java/com/aparapi/codegen/test/PostIncArrayItemTest.java index e232d257..6c9fe7b0 100644 --- a/src/test/java/com/aparapi/codegen/test/PostIncArrayItemTest.java +++ b/src/test/java/com/aparapi/codegen/test/PostIncArrayItemTest.java @@ -28,7 +28,7 @@ public class PostIncArrayItemTest extends com.aparapi.codegen.CodeGenJUnitBase { + " int get_pass_id(This *this){\n" + " return this->passid;\n" + " }\n" - + "\n" + + '\n' + " __kernel void run(\n" + " __global int *values,\n" + " __global int *results,\n" @@ -45,7 +45,7 @@ public class PostIncArrayItemTest extends com.aparapi.codegen.CodeGenJUnitBase { + " return;\n" + " }\n" + " }\n" - + " "}; + + ' '}; private static final Class expectedException = null; @Test diff --git a/src/test/java/com/aparapi/codegen/test/PostIncByteTest.java b/src/test/java/com/aparapi/codegen/test/PostIncByteTest.java index 28a36a41..05739d86 100644 --- a/src/test/java/com/aparapi/codegen/test/PostIncByteTest.java +++ b/src/test/java/com/aparapi/codegen/test/PostIncByteTest.java @@ -21,13 +21,13 @@ public class PostIncByteTest extends com.aparapi.codegen.CodeGenJUnitBase { private static final String[] expectedOpenCL = { "typedef struct This_s{\n" - + "\n" + + '\n' + " int passid;\n" + " }This;\n" + " int get_pass_id(This *this){\n" + " return this->passid;\n" + " }\n" - + "\n" + + '\n' + " char com_aparapi_codegen_test_PostIncByte__incByte(This *this, char a){\n" + " return(a++);\n" + " }\n" @@ -43,7 +43,7 @@ public class PostIncByteTest extends com.aparapi.codegen.CodeGenJUnitBase { + " return;\n" + " }\n" + " }\n" - + " "}; + + ' '}; private static final Class expectedException = null; @Test diff --git a/src/test/java/com/aparapi/codegen/test/PostIncIntTest.java b/src/test/java/com/aparapi/codegen/test/PostIncIntTest.java index 43e698ab..b1e5355e 100644 --- a/src/test/java/com/aparapi/codegen/test/PostIncIntTest.java +++ b/src/test/java/com/aparapi/codegen/test/PostIncIntTest.java @@ -21,13 +21,13 @@ public class PostIncIntTest extends com.aparapi.codegen.CodeGenJUnitBase { private static final String[] expectedOpenCL = { "typedef struct This_s{\n" - + "\n" + + '\n' + " int passid;\n" + " }This;\n" + " int get_pass_id(This *this){\n" + " return this->passid;\n" + " }\n" - + "\n" + + '\n' + " int com_aparapi_codegen_test_PostIncInt__foo(This *this, int a){\n" + " return(a);\n" + " }\n" @@ -43,7 +43,7 @@ public class PostIncIntTest extends com.aparapi.codegen.CodeGenJUnitBase { + " return;\n" + " }\n" + " }\n" - + " "}; + + ' '}; private static final Class expectedException = null; @Test diff --git a/src/test/java/com/aparapi/codegen/test/PostIncLocalStandaloneTest.java b/src/test/java/com/aparapi/codegen/test/PostIncLocalStandaloneTest.java index 63fef466..f7a1b2bf 100644 --- a/src/test/java/com/aparapi/codegen/test/PostIncLocalStandaloneTest.java +++ b/src/test/java/com/aparapi/codegen/test/PostIncLocalStandaloneTest.java @@ -21,13 +21,13 @@ public class PostIncLocalStandaloneTest extends com.aparapi.codegen.CodeGenJUnit private static final String[] expectedOpenCL = { "typedef struct This_s{\n" - + "\n" + + '\n' + " int passid;\n" + " }This;\n" + " int get_pass_id(This *this){\n" + " return this->passid;\n" + " }\n" - + "\n" + + '\n' + " __kernel void run(\n" + " int passid\n" + " ){\n" @@ -40,7 +40,7 @@ public class PostIncLocalStandaloneTest extends com.aparapi.codegen.CodeGenJUnit + " return;\n" + " }\n" + " }\n" - + " "}; + + ' '}; private static final Class expectedException = null; @Test diff --git a/src/test/java/com/aparapi/codegen/test/PostIncLocalTest.java b/src/test/java/com/aparapi/codegen/test/PostIncLocalTest.java index 338d1656..ef906e77 100644 --- a/src/test/java/com/aparapi/codegen/test/PostIncLocalTest.java +++ b/src/test/java/com/aparapi/codegen/test/PostIncLocalTest.java @@ -21,13 +21,13 @@ public class PostIncLocalTest extends com.aparapi.codegen.CodeGenJUnitBase { private static final String[] expectedOpenCL = { "typedef struct This_s{\n" - + "\n" + + '\n' + " int passid;\n" + " }This;\n" + " int get_pass_id(This *this){\n" + " return this->passid;\n" + " }\n" - + "\n" + + '\n' + " __kernel void run(\n" + " int passid\n" + " ){\n" @@ -43,7 +43,7 @@ public class PostIncLocalTest extends com.aparapi.codegen.CodeGenJUnitBase { + " return;\n" + " }\n" + " }\n" - + " "}; + + ' '}; private static final Class expectedException = null; @Test diff --git a/src/test/java/com/aparapi/codegen/test/PostIncLocalTwiceTest.java b/src/test/java/com/aparapi/codegen/test/PostIncLocalTwiceTest.java index 1795f527..c98553be 100644 --- a/src/test/java/com/aparapi/codegen/test/PostIncLocalTwiceTest.java +++ b/src/test/java/com/aparapi/codegen/test/PostIncLocalTwiceTest.java @@ -21,13 +21,13 @@ public class PostIncLocalTwiceTest extends com.aparapi.codegen.CodeGenJUnitBase private static final String[] expectedOpenCL = { "typedef struct This_s{\n" - + "\n" + + '\n' + " int passid;\n" + " }This;\n" + " int get_pass_id(This *this){\n" + " return this->passid;\n" + " }\n" - + "\n" + + '\n' + " __kernel void run(\n" + " int passid\n" + " ){\n" @@ -43,7 +43,7 @@ public class PostIncLocalTwiceTest extends com.aparapi.codegen.CodeGenJUnitBase + " return;\n" + " }\n" + " }\n" - + " "}; + + ' '}; private static final Class expectedException = null; diff --git a/src/test/java/com/aparapi/codegen/test/PreDecArrayIndexAndElementTest.java b/src/test/java/com/aparapi/codegen/test/PreDecArrayIndexAndElementTest.java index 9a160fac..1f5c86aa 100644 --- a/src/test/java/com/aparapi/codegen/test/PreDecArrayIndexAndElementTest.java +++ b/src/test/java/com/aparapi/codegen/test/PreDecArrayIndexAndElementTest.java @@ -27,7 +27,7 @@ public class PreDecArrayIndexAndElementTest extends com.aparapi.codegen.CodeGenJ + " int get_pass_id(This *this){\n" + " return this->passid;\n" + " }\n" - + "\n" + + '\n' + " __kernel void run(\n" + " __global int *array,\n" + " int passid\n" @@ -42,7 +42,7 @@ public class PreDecArrayIndexAndElementTest extends com.aparapi.codegen.CodeGenJ + " return;\n" + " }\n" + " }\n" - + " "}; + + ' '}; private static final Class expectedException = null; @Test diff --git a/src/test/java/com/aparapi/codegen/test/PreDecArrayItemTest.java b/src/test/java/com/aparapi/codegen/test/PreDecArrayItemTest.java index f5093e2e..5b5f5dc3 100644 --- a/src/test/java/com/aparapi/codegen/test/PreDecArrayItemTest.java +++ b/src/test/java/com/aparapi/codegen/test/PreDecArrayItemTest.java @@ -28,7 +28,7 @@ public class PreDecArrayItemTest extends com.aparapi.codegen.CodeGenJUnitBase { + " int get_pass_id(This *this){\n" + " return this->passid;\n" + " }\n" - + "\n" + + '\n' + " __kernel void run(\n" + " __global int *values,\n" + " __global int *results,\n" @@ -45,8 +45,8 @@ public class PreDecArrayItemTest extends com.aparapi.codegen.CodeGenJUnitBase { + " return;\n" + " }\n" + " }\n" - + "\n" - + " "}; + + '\n' + + ' '}; private static final Class expectedException = null; @Test diff --git a/src/test/java/com/aparapi/codegen/test/PreDecPostIncTest.java b/src/test/java/com/aparapi/codegen/test/PreDecPostIncTest.java index 34f7b11c..6de0b591 100644 --- a/src/test/java/com/aparapi/codegen/test/PreDecPostIncTest.java +++ b/src/test/java/com/aparapi/codegen/test/PreDecPostIncTest.java @@ -21,13 +21,13 @@ public class PreDecPostIncTest extends com.aparapi.codegen.CodeGenJUnitBase { private static final String[] expectedOpenCL = { "typedef struct This_s{\n" - + "\n" + + '\n' + " int passid;\n" + " }This;\n" + " int get_pass_id(This *this){\n" + " return this->passid;\n" + " }\n" - + "\n" + + '\n' + " __kernel void run(\n" + " int passid\n" + " ){\n" @@ -42,7 +42,7 @@ public class PreDecPostIncTest extends com.aparapi.codegen.CodeGenJUnitBase { + " return;\n" + " }\n" + " }\n" - + " "}; + + ' '}; private static final Class expectedException = null; @Test diff --git a/src/test/java/com/aparapi/codegen/test/PreIncArrayIndexAndElementTest.java b/src/test/java/com/aparapi/codegen/test/PreIncArrayIndexAndElementTest.java index 25184eea..2050146d 100644 --- a/src/test/java/com/aparapi/codegen/test/PreIncArrayIndexAndElementTest.java +++ b/src/test/java/com/aparapi/codegen/test/PreIncArrayIndexAndElementTest.java @@ -27,7 +27,7 @@ public class PreIncArrayIndexAndElementTest extends com.aparapi.codegen.CodeGenJ + " int get_pass_id(This *this){\n" + " return this->passid;\n" + " }\n" - + "\n" + + '\n' + " __kernel void run(\n" + " __global int *array,\n" + " int passid\n" @@ -42,7 +42,7 @@ public class PreIncArrayIndexAndElementTest extends com.aparapi.codegen.CodeGenJ + " return;\n" + " }\n" + " }\n" - + " "}; + + ' '}; private static final Class expectedException = null; @Test diff --git a/src/test/java/com/aparapi/codegen/test/PreIncArrayItemTest.java b/src/test/java/com/aparapi/codegen/test/PreIncArrayItemTest.java index 7833f74d..ca7d2f80 100644 --- a/src/test/java/com/aparapi/codegen/test/PreIncArrayItemTest.java +++ b/src/test/java/com/aparapi/codegen/test/PreIncArrayItemTest.java @@ -28,7 +28,7 @@ public class PreIncArrayItemTest extends com.aparapi.codegen.CodeGenJUnitBase { + " int get_pass_id(This *this){\n" + " return this->passid;\n" + " }\n" - + "\n" + + '\n' + " __kernel void run(\n" + " __global int *values,\n" + " __global int *results,\n" @@ -45,8 +45,8 @@ public class PreIncArrayItemTest extends com.aparapi.codegen.CodeGenJUnitBase { + " return;\n" + " }\n" + " }\n" - + "\n" - + " "}; + + '\n' + + ' '}; private static final Class expectedException = null; @Test diff --git a/src/test/java/com/aparapi/codegen/test/PreIncByteTest.java b/src/test/java/com/aparapi/codegen/test/PreIncByteTest.java index f9a079e1..a8b69998 100644 --- a/src/test/java/com/aparapi/codegen/test/PreIncByteTest.java +++ b/src/test/java/com/aparapi/codegen/test/PreIncByteTest.java @@ -42,7 +42,7 @@ public class PreIncByteTest extends com.aparapi.codegen.CodeGenJUnitBase { + " return;\n" + " }\n" + " }\n" - + " "}; + + ' '}; private static final Class expectedException = null; @Test diff --git a/src/test/java/com/aparapi/codegen/test/PreIncIntTest.java b/src/test/java/com/aparapi/codegen/test/PreIncIntTest.java index 1aec2683..5fd8eeb7 100644 --- a/src/test/java/com/aparapi/codegen/test/PreIncIntTest.java +++ b/src/test/java/com/aparapi/codegen/test/PreIncIntTest.java @@ -21,13 +21,13 @@ public class PreIncIntTest extends com.aparapi.codegen.CodeGenJUnitBase { private static final String[] expectedOpenCL = { "typedef struct This_s{\n" - + "\n" + + '\n' + " int passid;\n" + " }This;\n" + " int get_pass_id(This *this){\n" + " return this->passid;\n" + " }\n" - + "\n" + + '\n' + " int com_aparapi_codegen_test_PreIncInt__preIncInt(This *this, int a){\n" + " return(a);\n" + " }\n" @@ -43,7 +43,7 @@ public class PreIncIntTest extends com.aparapi.codegen.CodeGenJUnitBase { + " return;\n" + " }\n" + " }\n" - + " "}; + + ' '}; private static final Class expectedException = null; diff --git a/src/test/java/com/aparapi/codegen/test/PreIncLocalStandaloneTest.java b/src/test/java/com/aparapi/codegen/test/PreIncLocalStandaloneTest.java index bee32521..9ea0eddb 100644 --- a/src/test/java/com/aparapi/codegen/test/PreIncLocalStandaloneTest.java +++ b/src/test/java/com/aparapi/codegen/test/PreIncLocalStandaloneTest.java @@ -21,13 +21,13 @@ public class PreIncLocalStandaloneTest extends com.aparapi.codegen.CodeGenJUnitB private static final String[] expectedOpenCL = { "typedef struct This_s{\n" - + "\n" + + '\n' + " int passid;\n" + " }This;\n" + " int get_pass_id(This *this){\n" + " return this->passid;\n" + " }\n" - + "\n" + + '\n' + " __kernel void run(\n" + " int passid\n" + " ){\n" @@ -40,7 +40,7 @@ public class PreIncLocalStandaloneTest extends com.aparapi.codegen.CodeGenJUnitB + " return;\n" + " }\n" + " }\n" - + " "}; + + ' '}; private static final Class expectedException = null; @Test diff --git a/src/test/java/com/aparapi/codegen/test/PreIncLocalTest.java b/src/test/java/com/aparapi/codegen/test/PreIncLocalTest.java index 4ebbe805..a07cb5d2 100644 --- a/src/test/java/com/aparapi/codegen/test/PreIncLocalTest.java +++ b/src/test/java/com/aparapi/codegen/test/PreIncLocalTest.java @@ -21,13 +21,13 @@ public class PreIncLocalTest extends com.aparapi.codegen.CodeGenJUnitBase { private static final String[] expectedOpenCL = { "typedef struct This_s{\n" - + "\n" + + '\n' + " int passid;\n" + " }This;\n" + " int get_pass_id(This *this){\n" + " return this->passid;\n" + " }\n" - + "\n" + + '\n' + " __kernel void run(\n" + " int passid\n" + " ){\n" @@ -44,7 +44,7 @@ public class PreIncLocalTest extends com.aparapi.codegen.CodeGenJUnitBase { + " return;\n" + " }\n" + " }\n" - + " "}; + + ' '}; private static final Class expectedException = null; @Test diff --git a/src/test/java/com/aparapi/codegen/test/PreIncLocalTwiceTest.java b/src/test/java/com/aparapi/codegen/test/PreIncLocalTwiceTest.java index f542541a..51f4de85 100644 --- a/src/test/java/com/aparapi/codegen/test/PreIncLocalTwiceTest.java +++ b/src/test/java/com/aparapi/codegen/test/PreIncLocalTwiceTest.java @@ -21,13 +21,13 @@ public class PreIncLocalTwiceTest extends com.aparapi.codegen.CodeGenJUnitBase { private static final String[] expectedOpenCL = { "typedef struct This_s{\n" - + "\n" + + '\n' + " int passid;\n" + " }This;\n" + " int get_pass_id(This *this){\n" + " return this->passid;\n" + " }\n" - + "\n" + + '\n' + " __kernel void run(\n" + " int passid\n" + " ){\n" @@ -44,7 +44,7 @@ public class PreIncLocalTwiceTest extends com.aparapi.codegen.CodeGenJUnitBase { + " return;\n" + " }\n" + " }\n" - + " "}; + + ' '}; private static final Class expectedException = null; @Test diff --git a/src/test/java/com/aparapi/codegen/test/ReturnBooleanVarArrayTest.java b/src/test/java/com/aparapi/codegen/test/ReturnBooleanVarArrayTest.java index 46f45c4b..54e4dea8 100644 --- a/src/test/java/com/aparapi/codegen/test/ReturnBooleanVarArrayTest.java +++ b/src/test/java/com/aparapi/codegen/test/ReturnBooleanVarArrayTest.java @@ -40,7 +40,7 @@ public class ReturnBooleanVarArrayTest extends com.aparapi.codegen.CodeGenJUnitB + " com_aparapi_codegen_test_ReturnBooleanVarArray__returnBooleanVarArray(this);\n" + " return;\n" + " }\n" - + "}" + + '}' }; private static final Class expectedException = null; diff --git a/src/test/java/com/aparapi/codegen/test/ReturnByteArrayVarTest.java b/src/test/java/com/aparapi/codegen/test/ReturnByteArrayVarTest.java index 49cf10aa..f4fe3753 100644 --- a/src/test/java/com/aparapi/codegen/test/ReturnByteArrayVarTest.java +++ b/src/test/java/com/aparapi/codegen/test/ReturnByteArrayVarTest.java @@ -40,7 +40,7 @@ public class ReturnByteArrayVarTest extends com.aparapi.codegen.CodeGenJUnitBase + " com_aparapi_codegen_test_ReturnByteArrayVar__returnByteArrayVar(this);\n" + " return;\n" + " }\n" - + "}" + + '}' }; private static final Class expectedException = null; diff --git a/src/test/java/com/aparapi/codegen/test/ReturnDoubleArrayVarTest.java b/src/test/java/com/aparapi/codegen/test/ReturnDoubleArrayVarTest.java index 330b735d..e4dc01cb 100644 --- a/src/test/java/com/aparapi/codegen/test/ReturnDoubleArrayVarTest.java +++ b/src/test/java/com/aparapi/codegen/test/ReturnDoubleArrayVarTest.java @@ -40,7 +40,7 @@ public class ReturnDoubleArrayVarTest extends com.aparapi.codegen.CodeGenJUnitBa + " com_aparapi_codegen_test_ReturnDoubleArrayVar__returnDoubleArrayVar(this);\n" + " return;\n" + " }\n" - + "}" + + '}' }; private static final Class expectedException = null; diff --git a/src/test/java/com/aparapi/codegen/test/ReturnFloatArrayVarTest.java b/src/test/java/com/aparapi/codegen/test/ReturnFloatArrayVarTest.java index 6fe511ff..ca5bc31d 100644 --- a/src/test/java/com/aparapi/codegen/test/ReturnFloatArrayVarTest.java +++ b/src/test/java/com/aparapi/codegen/test/ReturnFloatArrayVarTest.java @@ -40,7 +40,7 @@ public class ReturnFloatArrayVarTest extends com.aparapi.codegen.CodeGenJUnitBas + " com_aparapi_codegen_test_ReturnFloatArrayVar__returnFloatArrayVar(this);\n" + " return;\n" + " }\n" - + "}" + + '}' }; private static final Class expectedException = null; diff --git a/src/test/java/com/aparapi/codegen/test/ReturnIntArrayVarTest.java b/src/test/java/com/aparapi/codegen/test/ReturnIntArrayVarTest.java index f891df6a..2d146db9 100644 --- a/src/test/java/com/aparapi/codegen/test/ReturnIntArrayVarTest.java +++ b/src/test/java/com/aparapi/codegen/test/ReturnIntArrayVarTest.java @@ -40,7 +40,7 @@ public class ReturnIntArrayVarTest extends com.aparapi.codegen.CodeGenJUnitBase + " com_aparapi_codegen_test_ReturnIntArrayVar__returnIntArrayVar(this);\n" + " return;\n" + " }\n" - + "}" + + '}' }; private static final Class expectedException = null; diff --git a/src/test/java/com/aparapi/codegen/test/ReturnLongArrayVarTest.java b/src/test/java/com/aparapi/codegen/test/ReturnLongArrayVarTest.java index 66e77425..8ac445c1 100644 --- a/src/test/java/com/aparapi/codegen/test/ReturnLongArrayVarTest.java +++ b/src/test/java/com/aparapi/codegen/test/ReturnLongArrayVarTest.java @@ -40,7 +40,7 @@ public class ReturnLongArrayVarTest extends com.aparapi.codegen.CodeGenJUnitBase + " com_aparapi_codegen_test_ReturnLongArrayVar__returnLongArrayVar(this);\n" + " return;\n" + " }\n" - + "}" + + '}' }; private static final Class expectedException = null; diff --git a/src/test/java/com/aparapi/codegen/test/ReturnPostIncIntTest.java b/src/test/java/com/aparapi/codegen/test/ReturnPostIncIntTest.java index 83b7b562..0c40d678 100644 --- a/src/test/java/com/aparapi/codegen/test/ReturnPostIncIntTest.java +++ b/src/test/java/com/aparapi/codegen/test/ReturnPostIncIntTest.java @@ -40,7 +40,7 @@ public class ReturnPostIncIntTest extends com.aparapi.codegen.CodeGenJUnitBase { + " return;\n" + " }\n" + " }\n" - + " "}; + + ' '}; private static final Class expectedException = null; @Test diff --git a/src/test/java/com/aparapi/codegen/test/ReturnPreIncIntTest.java b/src/test/java/com/aparapi/codegen/test/ReturnPreIncIntTest.java index 952b2a61..40cc2b96 100644 --- a/src/test/java/com/aparapi/codegen/test/ReturnPreIncIntTest.java +++ b/src/test/java/com/aparapi/codegen/test/ReturnPreIncIntTest.java @@ -41,7 +41,7 @@ public class ReturnPreIncIntTest extends com.aparapi.codegen.CodeGenJUnitBase { + " return;\n" + " }\n" + " }\n" - + " "}; + + ' '}; private static final Class expectedException = null; @Test diff --git a/src/test/java/com/aparapi/codegen/test/ReturnShortArrayVarTest.java b/src/test/java/com/aparapi/codegen/test/ReturnShortArrayVarTest.java index b703e37b..2c3dba09 100644 --- a/src/test/java/com/aparapi/codegen/test/ReturnShortArrayVarTest.java +++ b/src/test/java/com/aparapi/codegen/test/ReturnShortArrayVarTest.java @@ -41,7 +41,7 @@ public class ReturnShortArrayVarTest extends com.aparapi.codegen.CodeGenJUnitBas + " com_aparapi_codegen_test_ReturnShortArrayVar__returnShortArrayVar(this);\n" + " return;\n" + " }\n" - + "}" + + '}' }; private static final Class expectedException = null; diff --git a/src/test/java/com/aparapi/codegen/test/RightShifts.java b/src/test/java/com/aparapi/codegen/test/RightShifts.java index 2a5c1558..f64a20b1 100644 --- a/src/test/java/com/aparapi/codegen/test/RightShifts.java +++ b/src/test/java/com/aparapi/codegen/test/RightShifts.java @@ -23,6 +23,7 @@ public class RightShifts extends Kernel { int i1, i2; + @Override public void run() { iout[1] = i1 >> i2; iout[2] = i1 >>> i2; diff --git a/src/test/java/com/aparapi/codegen/test/RightShiftsTest.java b/src/test/java/com/aparapi/codegen/test/RightShiftsTest.java index d48ffb0a..67ed42e4 100644 --- a/src/test/java/com/aparapi/codegen/test/RightShiftsTest.java +++ b/src/test/java/com/aparapi/codegen/test/RightShiftsTest.java @@ -29,7 +29,7 @@ public class RightShiftsTest extends com.aparapi.codegen.CodeGenJUnitBase { + " int get_pass_id(This *this){\n" + " return this->passid;\n" + " }\n" - + "\n" + + '\n' + " __kernel void run(\n" + " __global int *iout,\n" + " int i1,\n" @@ -48,8 +48,8 @@ public class RightShiftsTest extends com.aparapi.codegen.CodeGenJUnitBase { + " return;\n" + " }\n" + " }\n" - + "\n" - + " "}; + + '\n' + + ' '}; private static final Class expectedException = null; @Test diff --git a/src/test/java/com/aparapi/codegen/test/SequenceTest.java b/src/test/java/com/aparapi/codegen/test/SequenceTest.java index 8efd40a1..9598a266 100644 --- a/src/test/java/com/aparapi/codegen/test/SequenceTest.java +++ b/src/test/java/com/aparapi/codegen/test/SequenceTest.java @@ -37,7 +37,7 @@ public class SequenceTest extends com.aparapi.codegen.CodeGenJUnitBase { + " return;\n" + " }\n" + " }\n" - + " "}; + + ' '}; private static final Class expectedException = null; @Test diff --git a/src/test/java/com/aparapi/codegen/test/StaticMethodCall.java b/src/test/java/com/aparapi/codegen/test/StaticMethodCall.java index 2b069e19..2ed85a86 100644 --- a/src/test/java/com/aparapi/codegen/test/StaticMethodCall.java +++ b/src/test/java/com/aparapi/codegen/test/StaticMethodCall.java @@ -24,6 +24,7 @@ public static int add(int i, int j) { return i + j; } + @Override public void run() { out[0] = add(1, 2); } diff --git a/src/test/java/com/aparapi/codegen/test/StaticMethodCallTest.java b/src/test/java/com/aparapi/codegen/test/StaticMethodCallTest.java index 50cff4c8..4b0f1812 100644 --- a/src/test/java/com/aparapi/codegen/test/StaticMethodCallTest.java +++ b/src/test/java/com/aparapi/codegen/test/StaticMethodCallTest.java @@ -43,8 +43,8 @@ public class StaticMethodCallTest extends com.aparapi.codegen.CodeGenJUnitBase { + " return;\n" + " }\n" + " }\n" - + "\n" - + " "}; + + '\n' + + ' '}; private static final Class expectedException = null; @Test diff --git a/src/test/java/com/aparapi/codegen/test/TernaryAndOrTest.java b/src/test/java/com/aparapi/codegen/test/TernaryAndOrTest.java index 886e4a79..32bc8dd1 100644 --- a/src/test/java/com/aparapi/codegen/test/TernaryAndOrTest.java +++ b/src/test/java/com/aparapi/codegen/test/TernaryAndOrTest.java @@ -40,7 +40,7 @@ public class TernaryAndOrTest extends com.aparapi.codegen.CodeGenJUnitBase { + " return;\n" + " }\n" + " }\n" - + " "}; + + ' '}; private static final Class expectedException = null; @Test diff --git a/src/test/java/com/aparapi/codegen/test/TernaryAndTest.java b/src/test/java/com/aparapi/codegen/test/TernaryAndTest.java index e240822a..e6f2312b 100644 --- a/src/test/java/com/aparapi/codegen/test/TernaryAndTest.java +++ b/src/test/java/com/aparapi/codegen/test/TernaryAndTest.java @@ -26,7 +26,7 @@ public class TernaryAndTest extends com.aparapi.codegen.CodeGenJUnitBase { + " int get_pass_id(This *this){\n" + " return this->passid;\n" + " }\n" - + "\n" + + '\n' + " float com_aparapi_codegen_test_TernaryAnd__random(This *this){\n" + " return(0.1f);\n" + " }\n" @@ -41,7 +41,7 @@ public class TernaryAndTest extends com.aparapi.codegen.CodeGenJUnitBase { + " return;\n" + " }\n" + " }\n" - + " "}; + + ' '}; private static final Class expectedException = null; @Test diff --git a/src/test/java/com/aparapi/codegen/test/TernaryNestedTest.java b/src/test/java/com/aparapi/codegen/test/TernaryNestedTest.java index e766849a..3bc78a55 100644 --- a/src/test/java/com/aparapi/codegen/test/TernaryNestedTest.java +++ b/src/test/java/com/aparapi/codegen/test/TernaryNestedTest.java @@ -39,7 +39,7 @@ public class TernaryNestedTest extends com.aparapi.codegen.CodeGenJUnitBase { + " int count = (a!=0)?((b!=0)?1:2):((c!=0)?3:4);\n" + " return;\n" + " }\n" - + "}"}; + + '}'}; private static final Class expectedException = null; @Test diff --git a/src/test/java/com/aparapi/codegen/test/TernaryOrTest.java b/src/test/java/com/aparapi/codegen/test/TernaryOrTest.java index 32ea3fa8..ca2b07c8 100644 --- a/src/test/java/com/aparapi/codegen/test/TernaryOrTest.java +++ b/src/test/java/com/aparapi/codegen/test/TernaryOrTest.java @@ -21,13 +21,13 @@ public class TernaryOrTest extends com.aparapi.codegen.CodeGenJUnitBase { private static final String[] expectedOpenCL = { "typedef struct This_s{\n" - + "\n" + + '\n' + " int passid;\n" + " }This;\n" + " int get_pass_id(This *this){\n" + " return this->passid;\n" + " }\n" - + "\n" + + '\n' + " float com_aparapi_codegen_test_TernaryOr__random(This *this){\n" + " return(0.1f);\n" + " }\n" @@ -42,7 +42,7 @@ public class TernaryOrTest extends com.aparapi.codegen.CodeGenJUnitBase { + " return;\n" + " }\n" + " }\n" - + " "}; + + ' '}; private static final Class expectedException = null; @Test diff --git a/src/test/java/com/aparapi/codegen/test/TernaryTest.java b/src/test/java/com/aparapi/codegen/test/TernaryTest.java index 5c584c4c..06cb48a9 100644 --- a/src/test/java/com/aparapi/codegen/test/TernaryTest.java +++ b/src/test/java/com/aparapi/codegen/test/TernaryTest.java @@ -41,7 +41,7 @@ public class TernaryTest extends com.aparapi.codegen.CodeGenJUnitBase { + " return;\n" + " }\n" + " }\n" - + " "}; + + ' '}; private static final Class expectedException = null; @Test diff --git a/src/test/java/com/aparapi/codegen/test/TwoForLoops.java b/src/test/java/com/aparapi/codegen/test/TwoForLoops.java index 10977d55..040c7357 100644 --- a/src/test/java/com/aparapi/codegen/test/TwoForLoops.java +++ b/src/test/java/com/aparapi/codegen/test/TwoForLoops.java @@ -21,6 +21,7 @@ public class TwoForLoops extends Kernel { final int size = 100; int a[] = new int[size]; + @Override public void run() { for (int i = 0; i < size; i++) { a[i] = i; diff --git a/src/test/java/com/aparapi/codegen/test/TwoForLoopsTest.java b/src/test/java/com/aparapi/codegen/test/TwoForLoopsTest.java index ad2ef527..ae49e15b 100644 --- a/src/test/java/com/aparapi/codegen/test/TwoForLoopsTest.java +++ b/src/test/java/com/aparapi/codegen/test/TwoForLoopsTest.java @@ -27,7 +27,7 @@ public class TwoForLoopsTest extends com.aparapi.codegen.CodeGenJUnitBase { + " int get_pass_id(This *this){\n" + " return this->passid;\n" + " }\n" - + "\n" + + '\n' + " __kernel void run(\n" + " __global int *a,\n" + " int passid\n" @@ -47,7 +47,7 @@ public class TwoForLoopsTest extends com.aparapi.codegen.CodeGenJUnitBase { + " return;\n" + " }\n" + " }\n" - + " "}; + + ' '}; private static final Class expectedException = null; @Test diff --git a/src/test/java/com/aparapi/codegen/test/UnrelatedIfElsesWithCommonEndByteTest.java b/src/test/java/com/aparapi/codegen/test/UnrelatedIfElsesWithCommonEndByteTest.java index 4c326e9a..5a7e5f50 100644 --- a/src/test/java/com/aparapi/codegen/test/UnrelatedIfElsesWithCommonEndByteTest.java +++ b/src/test/java/com/aparapi/codegen/test/UnrelatedIfElsesWithCommonEndByteTest.java @@ -21,13 +21,13 @@ public class UnrelatedIfElsesWithCommonEndByteTest extends com.aparapi.codegen.C private static final String[] expectedOpenCL = { "typedef struct This_s{\n" - + "\n" + + '\n' + " int passid;\n" + " }This;\n" + " int get_pass_id(This *this){\n" + " return this->passid;\n" + " }\n" - + "\n" + + '\n' + " __kernel void run(\n" + " int passid\n" + " ){\n" @@ -54,7 +54,7 @@ public class UnrelatedIfElsesWithCommonEndByteTest extends com.aparapi.codegen.C + " return;\n" + " }\n" + " }\n" - + " "}; + + ' '}; private static final Class expectedException = null; @Test diff --git a/src/test/java/com/aparapi/codegen/test/UnrelatedIfsWithCommonEndByteTest.java b/src/test/java/com/aparapi/codegen/test/UnrelatedIfsWithCommonEndByteTest.java index 1c0741ca..4de05f2e 100644 --- a/src/test/java/com/aparapi/codegen/test/UnrelatedIfsWithCommonEndByteTest.java +++ b/src/test/java/com/aparapi/codegen/test/UnrelatedIfsWithCommonEndByteTest.java @@ -21,13 +21,13 @@ public class UnrelatedIfsWithCommonEndByteTest extends com.aparapi.codegen.CodeG private static final String[] expectedOpenCL = { "typedef struct This_s{\n" - + "\n" + + '\n' + " int passid;\n" + " }This;\n" + " int get_pass_id(This *this){\n" + " return this->passid;\n" + " }\n" - + "\n" + + '\n' + " __kernel void run(\n" + " int passid\n" + " ){\n" @@ -52,7 +52,7 @@ public class UnrelatedIfsWithCommonEndByteTest extends com.aparapi.codegen.CodeG + " return;\n" + " }\n" + " }\n" - + " "}; + + ' '}; private static final Class expectedException = null; @Test diff --git a/src/test/java/com/aparapi/codegen/test/UnrelatedNestedIfElsesTest.java b/src/test/java/com/aparapi/codegen/test/UnrelatedNestedIfElsesTest.java index 7b8c0233..f03fd3dd 100644 --- a/src/test/java/com/aparapi/codegen/test/UnrelatedNestedIfElsesTest.java +++ b/src/test/java/com/aparapi/codegen/test/UnrelatedNestedIfElsesTest.java @@ -21,13 +21,13 @@ public class UnrelatedNestedIfElsesTest extends com.aparapi.codegen.CodeGenJUnit private static final String[] expectedOpenCL = { "typedef struct This_s{\n" - + "\n" + + '\n' + " int passid;\n" + " }This;\n" + " int get_pass_id(This *this){\n" + " return this->passid;\n" + " }\n" - + "\n" + + '\n' + " __kernel void run(\n" + " int passid\n" + " ){\n" @@ -55,7 +55,7 @@ public class UnrelatedNestedIfElsesTest extends com.aparapi.codegen.CodeGenJUnit + " return;\n" + " }\n" + " }\n" - + " "}; + + ' '}; private static final Class expectedException = null; @Test diff --git a/src/test/java/com/aparapi/codegen/test/UseObject.java b/src/test/java/com/aparapi/codegen/test/UseObject.java index 8979c148..7fee9da7 100644 --- a/src/test/java/com/aparapi/codegen/test/UseObject.java +++ b/src/test/java/com/aparapi/codegen/test/UseObject.java @@ -24,12 +24,13 @@ public class UseObject extends Kernel { int out[] = new int[2]; int plainInt = -1; + @Override public void run() { out[0] = dummy.n; out[1] = plainInt; } - class Dummy { + static class Dummy { public int n; } diff --git a/src/test/java/com/aparapi/codegen/test/UseObjectArrayLength.java b/src/test/java/com/aparapi/codegen/test/UseObjectArrayLength.java index 84d0faf9..37792419 100644 --- a/src/test/java/com/aparapi/codegen/test/UseObjectArrayLength.java +++ b/src/test/java/com/aparapi/codegen/test/UseObjectArrayLength.java @@ -23,11 +23,12 @@ public class UseObjectArrayLength extends Kernel { ; Dummy dummy[] = new Dummy[10]; + @Override public void run() { out[0] = dummy.length; } - final class Dummy { + static final class Dummy { public int n; } } diff --git a/src/test/java/com/aparapi/codegen/test/UseObjectArrayLengthTest.java b/src/test/java/com/aparapi/codegen/test/UseObjectArrayLengthTest.java index fb3ef906..4b89c987 100644 --- a/src/test/java/com/aparapi/codegen/test/UseObjectArrayLengthTest.java +++ b/src/test/java/com/aparapi/codegen/test/UseObjectArrayLengthTest.java @@ -29,7 +29,7 @@ public class UseObjectArrayLengthTest extends com.aparapi.codegen.CodeGenJUnitBa + " int get_pass_id(This *this){\n" + " return this->passid;\n" + " }\n" - + "\n" + + '\n' + " __kernel void run(\n" + " __global int *out,\n" + " __global com_aparapi_codegen_test_UseObjectArrayLength$Dummy *dummy,\n" @@ -47,7 +47,7 @@ public class UseObjectArrayLengthTest extends com.aparapi.codegen.CodeGenJUnitBa + " return;\n" + " }\n" + " }\n" - + " "}; + + ' '}; private static final Class expectedException = null; @Test diff --git a/src/test/java/com/aparapi/codegen/test/UsesArrayLength.java b/src/test/java/com/aparapi/codegen/test/UsesArrayLength.java index 255581eb..491a9e40 100644 --- a/src/test/java/com/aparapi/codegen/test/UsesArrayLength.java +++ b/src/test/java/com/aparapi/codegen/test/UsesArrayLength.java @@ -38,6 +38,7 @@ boolean actuallyDoIt(int index) { return (results.length - x > 0); } + @Override public void run() { int myId = 0; diff --git a/src/test/java/com/aparapi/codegen/test/UsesArrayLengthTest.java b/src/test/java/com/aparapi/codegen/test/UsesArrayLengthTest.java index 2491a18f..1f99082b 100644 --- a/src/test/java/com/aparapi/codegen/test/UsesArrayLengthTest.java +++ b/src/test/java/com/aparapi/codegen/test/UsesArrayLengthTest.java @@ -60,7 +60,7 @@ public class UsesArrayLengthTest extends com.aparapi.codegen.CodeGenJUnitBase { + " this->results2[myId] = (this->results[myId]==0)?1:0;\n" + " return;\n" + " }\n" - + "}"}; + + '}'}; private static final Class expectedException = null; @Test diff --git a/src/test/java/com/aparapi/codegen/test/WhileAndMandelTest.java b/src/test/java/com/aparapi/codegen/test/WhileAndMandelTest.java index 0597edc9..d2e560bf 100644 --- a/src/test/java/com/aparapi/codegen/test/WhileAndMandelTest.java +++ b/src/test/java/com/aparapi/codegen/test/WhileAndMandelTest.java @@ -24,13 +24,13 @@ public class WhileAndMandelTest extends com.aparapi.codegen.CodeGenJUnitBase { + " int width;\n" + " float scale;\n" + " int maxIterations;\n" - + "\n" + + '\n' + " int passid;\n" + " }This;\n" + " int get_pass_id(This *this){\n" + " return this->passid;\n" + " }\n" - + "\n" + + '\n' + " __kernel void run(\n" + " int width,\n" + " float scale,\n" @@ -67,7 +67,7 @@ public class WhileAndMandelTest extends com.aparapi.codegen.CodeGenJUnitBase { + " return;\n" + " }\n" + " }\n" - + " "}; + + ' '}; private static final Class expectedException = null; @Test diff --git a/src/test/java/com/aparapi/codegen/test/WhileEmptyLoopTest.java b/src/test/java/com/aparapi/codegen/test/WhileEmptyLoopTest.java index 4b24601e..6dd9a2c8 100644 --- a/src/test/java/com/aparapi/codegen/test/WhileEmptyLoopTest.java +++ b/src/test/java/com/aparapi/codegen/test/WhileEmptyLoopTest.java @@ -21,13 +21,13 @@ public class WhileEmptyLoopTest extends com.aparapi.codegen.CodeGenJUnitBase { private static final String[] expectedOpenCL = { "typedef struct This_s{\n" - + "\n" + + '\n' + " int passid;\n" + " }This;\n" + " int get_pass_id(This *this){\n" + " return this->passid;\n" + " }\n" - + "\n" + + '\n' + " __kernel void run(\n" + " int passid\n" + " ){\n" @@ -39,7 +39,7 @@ public class WhileEmptyLoopTest extends com.aparapi.codegen.CodeGenJUnitBase { + " return;\n" + " }\n" + " }\n" - + " "}; + + ' '}; private static final Class expectedException = null; @Test diff --git a/src/test/java/com/aparapi/codegen/test/WhileFloatCompoundTest.java b/src/test/java/com/aparapi/codegen/test/WhileFloatCompoundTest.java index 86c07f4e..1630fb47 100644 --- a/src/test/java/com/aparapi/codegen/test/WhileFloatCompoundTest.java +++ b/src/test/java/com/aparapi/codegen/test/WhileFloatCompoundTest.java @@ -46,7 +46,7 @@ public class WhileFloatCompoundTest extends com.aparapi.codegen.CodeGenJUnitBase + " return;\n" + " }\n" + " }\n" - + " "}; + + ' '}; private static final Class expectedException = null; @Test diff --git a/src/test/java/com/aparapi/codegen/test/WhileIfElseTest.java b/src/test/java/com/aparapi/codegen/test/WhileIfElseTest.java index d99c8b96..1b769b1b 100644 --- a/src/test/java/com/aparapi/codegen/test/WhileIfElseTest.java +++ b/src/test/java/com/aparapi/codegen/test/WhileIfElseTest.java @@ -47,7 +47,7 @@ public class WhileIfElseTest extends com.aparapi.codegen.CodeGenJUnitBase { + " return;\n" + " }\n" + " }\n" - + " "}; + + ' '}; private static final Class expectedException = null; @Test diff --git a/src/test/java/com/aparapi/codegen/test/WhileIfTest.java b/src/test/java/com/aparapi/codegen/test/WhileIfTest.java index c837c0ab..3e900d52 100644 --- a/src/test/java/com/aparapi/codegen/test/WhileIfTest.java +++ b/src/test/java/com/aparapi/codegen/test/WhileIfTest.java @@ -45,7 +45,7 @@ public class WhileIfTest extends com.aparapi.codegen.CodeGenJUnitBase { + " return;\n" + " }\n" + " }\n" - + " "}; + + ' '}; private static final Class expectedException = null; @Test diff --git a/src/test/java/com/aparapi/codegen/test/WhileTest.java b/src/test/java/com/aparapi/codegen/test/WhileTest.java index b1105096..5be46824 100644 --- a/src/test/java/com/aparapi/codegen/test/WhileTest.java +++ b/src/test/java/com/aparapi/codegen/test/WhileTest.java @@ -21,13 +21,13 @@ public class WhileTest extends com.aparapi.codegen.CodeGenJUnitBase { private static final String[] expectedOpenCL = { "typedef struct This_s{\n" - + "\n" + + '\n' + " int passid;\n" + " }This;\n" + " int get_pass_id(This *this){\n" + " return this->passid;\n" + " }\n" - + "\n" + + '\n' + " __kernel void run(\n" + " int passid\n" + " ){\n" @@ -43,7 +43,7 @@ public class WhileTest extends com.aparapi.codegen.CodeGenJUnitBase { + " return;\n" + " }\n" + " }\n" - + " "}; + + ' '}; private static final Class expectedException = null; @Test diff --git a/src/test/java/com/aparapi/codegen/test/WhileWithoutMutatorTest.java b/src/test/java/com/aparapi/codegen/test/WhileWithoutMutatorTest.java index 8c259a92..6b53ab60 100644 --- a/src/test/java/com/aparapi/codegen/test/WhileWithoutMutatorTest.java +++ b/src/test/java/com/aparapi/codegen/test/WhileWithoutMutatorTest.java @@ -26,7 +26,7 @@ public class WhileWithoutMutatorTest extends com.aparapi.codegen.CodeGenJUnitBas + " int get_pass_id(This *this){\n" + " return this->passid;\n" + " }\n" - + "\n" + + '\n' + " __kernel void run(\n" + " int passid\n" + " ){\n" @@ -39,7 +39,7 @@ public class WhileWithoutMutatorTest extends com.aparapi.codegen.CodeGenJUnitBas + " return;\n" + " }\n" + " }\n" - + " "}; + + ' '}; private static final Class expectedException = null; @Test diff --git a/src/test/java/com/aparapi/codegen/test/While_If_IfElseElseTest.java b/src/test/java/com/aparapi/codegen/test/While_If_IfElseElseTest.java index 5c566b85..4abb750c 100644 --- a/src/test/java/com/aparapi/codegen/test/While_If_IfElseElseTest.java +++ b/src/test/java/com/aparapi/codegen/test/While_If_IfElseElseTest.java @@ -59,7 +59,7 @@ public class While_If_IfElseElseTest extends com.aparapi.codegen.CodeGenJUnitBas + " g = g;\n" + " }\n" + " }\n" - + "\n" + + '\n' + " if (h==h && i==i){\n" + " if (j==j){\n" + " k = k;\n" @@ -81,7 +81,7 @@ public class While_If_IfElseElseTest extends com.aparapi.codegen.CodeGenJUnitBas + " return;\n" + " }\n" + " }\n" - + " "}; + + ' '}; private static final Class expectedException = null; @Test diff --git a/src/test/java/com/aparapi/codegen/test/WideIncTest.java b/src/test/java/com/aparapi/codegen/test/WideIncTest.java index e9828e76..5f485a46 100644 --- a/src/test/java/com/aparapi/codegen/test/WideIncTest.java +++ b/src/test/java/com/aparapi/codegen/test/WideIncTest.java @@ -38,7 +38,7 @@ public class WideIncTest extends com.aparapi.codegen.CodeGenJUnitBase { + " return;\n" + " }\n" + " }\n" - + " "}; + + ' '}; private static final Class expectedException = null; @Test diff --git a/src/test/java/com/aparapi/codegen/test/WideLoadTest.java b/src/test/java/com/aparapi/codegen/test/WideLoadTest.java index c839493f..6655d768 100644 --- a/src/test/java/com/aparapi/codegen/test/WideLoadTest.java +++ b/src/test/java/com/aparapi/codegen/test/WideLoadTest.java @@ -294,7 +294,7 @@ public class WideLoadTest extends com.aparapi.codegen.CodeGenJUnitBase { + " return;\n" + " }\n" + " }\n" - + " "}; + + ' '}; private static final Class expectedException = null; @Test diff --git a/src/test/java/com/aparapi/runtime/ArrayTest.java b/src/test/java/com/aparapi/runtime/ArrayTest.java index a21af6e2..9cb9d757 100644 --- a/src/test/java/com/aparapi/runtime/ArrayTest.java +++ b/src/test/java/com/aparapi/runtime/ArrayTest.java @@ -19,8 +19,8 @@ import com.aparapi.Kernel; import java.util.Arrays; -import org.junit.Test; +import org.junit.Test; public class ArrayTest { @Test @@ -65,7 +65,7 @@ public void run() { void validate() { for (int j = 0; j < SIZE; j++) { - int[] expected = new int[SIZE]; + int[] expected = new int[SIZE]; for (int i = 0; i < SIZE; i++) { expected[i] = i + j; } @@ -80,3 +80,72 @@ public void test() { } } } +//public class ArrayTest { +// +// /** test all sizes to ensure that all the possible divisors (even or not) +// * for the available # of threads/cores are tested */ +// @Test public void test_n() { +// for (int size = 2; size < 33; size++) +// new VectorKernel(size).test(); +// } +// +// @Test public void test_1() { +// new VectorKernel(1).test(); +// } +// @Test public void test_2() { +// new VectorKernel(2).test(); +// } +// +// public static class VectorKernel extends Kernel { +// private final int SIZE; +// +// final int[][] target; +// +// public VectorKernel(int size) { +// this.SIZE = size; +// this.target = new int[SIZE][SIZE]; +// for (int i = 0; i < SIZE; ++i) { +// int[] ints = new int[SIZE]; +// Arrays.fill(ints, 99); +// +// target[i] = ints; +// } +// } +// +// private void fillArray(int[] ints_$private$, int id) { +// for (int i = 0; i < SIZE; i++) { +// ints_$private$[i] = i + id; +// } +// } +// +// @Override +// public void run() { +// int id = getGlobalId(); +// +// int[] ints = new int[SIZE]; +// +// fillArray(ints, id); +// +// for (int i = 0; i < SIZE; i++) { +// target[id][i] = ints[i]; +// } +// } +// +// void validate() { +// int[] expected = new int[SIZE]; +// for (int j = 0; j < SIZE; j++) { +// +// for (int i = 0; i < SIZE; i++) { +// expected[i] = i + j; +// } +// +// assertArrayEquals("size=" + SIZE + "\ttarget["+j+ ']', expected, target[j]); +// } +// } +// +// public void test() { +// execute(SIZE); +// validate(); +// } +// } +//} diff --git a/src/test/java/com/aparapi/runtime/BufferTransferTest.java b/src/test/java/com/aparapi/runtime/BufferTransferTest.java index 0a11e44c..44328be9 100644 --- a/src/test/java/com/aparapi/runtime/BufferTransferTest.java +++ b/src/test/java/com/aparapi/runtime/BufferTransferTest.java @@ -26,7 +26,6 @@ import java.util.Arrays; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; import static org.junit.Assume.assumeTrue; public class BufferTransferTest { @@ -52,6 +51,7 @@ public void inOutOnce() { kernel.out = new int[SIZE]; Util.fill(kernel.in, new Util.Filler() { + @Override public void fill(int[] array, int index) { array[index] = index; } @@ -73,6 +73,7 @@ public void auto() { kernel.result = new int[SIZE]; Util.zero(kernel.result); Util.fill(kernel.values, new Util.Filler() { + @Override public void fill(int[] array, int index) { array[index] = index; } @@ -122,6 +123,7 @@ public void explicit() { kernel.result = new int[SIZE]; Util.zero(kernel.result); Util.fill(kernel.values, new Util.Filler() { + @Override public void fill(int[] array, int index) { array[index] = index; } @@ -216,7 +218,7 @@ public void run() { } - private class TestKernel extends Kernel { + private static class TestKernel extends Kernel { int[] simStep = new int[1]; int[] neuronOutputs = new int[3]; diff --git a/src/test/java/com/aparapi/runtime/CallStaticFromAnonymousKernelTest.java b/src/test/java/com/aparapi/runtime/CallStaticFromAnonymousKernelTest.java index 6e1aeb2e..8f862d89 100644 --- a/src/test/java/com/aparapi/runtime/CallStaticFromAnonymousKernelTest.java +++ b/src/test/java/com/aparapi/runtime/CallStaticFromAnonymousKernelTest.java @@ -16,9 +16,9 @@ package com.aparapi.runtime; import com.aparapi.Kernel; -import com.aparapi.device.Device; import org.junit.Test; +import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; public class CallStaticFromAnonymousKernelTest { @@ -62,7 +62,7 @@ public void run() { kernel.execute(size); for (int i = 0; i < size; i++) { - assertTrue("results == fooBar", results[i] == (fooBar(values[i]) + AnotherClass.foo(i))); + assertEquals(results[i], (fooBar(values[i]) + AnotherClass.foo(i))); } } diff --git a/src/test/java/com/aparapi/runtime/ExplicitBoolean.java b/src/test/java/com/aparapi/runtime/ExplicitBoolean.java index 66261623..62c01ce9 100644 --- a/src/test/java/com/aparapi/runtime/ExplicitBoolean.java +++ b/src/test/java/com/aparapi/runtime/ExplicitBoolean.java @@ -59,7 +59,7 @@ public void test() { System.out.println(k1.getTargetDevice().getShortDescription()); } - class ExplicitBooleanTestKernel extends Kernel { + static class ExplicitBooleanTestKernel extends Kernel { public boolean[] input, output; int size; // Number of work items. int iterations; // Number of times to execute kernel. diff --git a/src/test/java/com/aparapi/runtime/Issue102Test.java b/src/test/java/com/aparapi/runtime/Issue102Test.java index b3892d93..f25b9552 100644 --- a/src/test/java/com/aparapi/runtime/Issue102Test.java +++ b/src/test/java/com/aparapi/runtime/Issue102Test.java @@ -18,6 +18,7 @@ import com.aparapi.Kernel; import org.junit.Test; +import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; @@ -50,8 +51,8 @@ public void run() { void validate() { for (int i = 0; i < SIZE; i++) { - System.out.println(target[i] + " ... " + objects[i].getValue()); - assertTrue("target == objects", target[i] == objects[i].getValue()); + //System.out.println(target[i] + " ... " + objects[i].getValue()); + assertEquals(target[i], objects[i].getValue()); } } diff --git a/src/test/java/com/aparapi/runtime/Issue103Test.java b/src/test/java/com/aparapi/runtime/Issue103Test.java index 5b4a6fe5..4efb2f52 100644 --- a/src/test/java/com/aparapi/runtime/Issue103Test.java +++ b/src/test/java/com/aparapi/runtime/Issue103Test.java @@ -22,17 +22,17 @@ public class Issue103Test { + @Test public void test() { - Issue103Kernel b = new Issue103Kernel(); - b.test(); + new Issue103Kernel().test(); } public static class Issue103Kernel extends Kernel { static final int size = 32; - static int[] source = new int[size]; - static int[] target = new int[size]; + /* static */ int[] source = new int[size]; + /* static */ int[] target = new int[size]; public Issue103Kernel() { for (int i = 0; i < size; ++i) { diff --git a/src/test/java/com/aparapi/runtime/Issue55Test.java b/src/test/java/com/aparapi/runtime/Issue55Test.java index c2e9a268..277aab8e 100644 --- a/src/test/java/com/aparapi/runtime/Issue55Test.java +++ b/src/test/java/com/aparapi/runtime/Issue55Test.java @@ -59,8 +59,8 @@ public static void tearDownClass() { @Test public void testUseJtpOnly() { KernelManager.setKernelManager(KernelManagers.JTP_ONLY); - - Device device = KernelManager.instance().getDefaultPreferences().getPreferredDevice(testKernel); + + Device device = KernelManager.instance().defaultPreferences.getPreferredDevice(testKernel); assertThat(device.getType(), is(Device.TYPE.JTP)); } @@ -69,7 +69,7 @@ public void testUseJtpOnly() { public void testUseSequentialOnly() { KernelManager.setKernelManager(KernelManagers.SEQUENTIAL_ONLY); - Device device = KernelManager.instance().getDefaultPreferences().getPreferredDevice(testKernel); + Device device = KernelManager.instance().defaultPreferences.getPreferredDevice(testKernel); assertThat(device.getType(), is(Device.TYPE.SEQ)); } diff --git a/src/test/java/com/aparapi/runtime/Issue68Test.java b/src/test/java/com/aparapi/runtime/Issue68Test.java index fbc9e0dc..56d2c4ea 100644 --- a/src/test/java/com/aparapi/runtime/Issue68Test.java +++ b/src/test/java/com/aparapi/runtime/Issue68Test.java @@ -40,7 +40,7 @@ private int getModulus() { } // Runnable for calculating the column transforms in parallel - private class ColumnTableFNTRunnable extends Kernel { + private static class ColumnTableFNTRunnable extends Kernel { private final int stride; private final int length; private final boolean isInverse; diff --git a/src/test/java/com/aparapi/runtime/Issue69Test.java b/src/test/java/com/aparapi/runtime/Issue69Test.java index d33243cb..85c7e2e3 100644 --- a/src/test/java/com/aparapi/runtime/Issue69Test.java +++ b/src/test/java/com/aparapi/runtime/Issue69Test.java @@ -20,6 +20,8 @@ import org.junit.Assert; import org.junit.Test; +import static org.junit.Assert.fail; + public class Issue69Test { @Test @@ -36,7 +38,7 @@ public void run() { System.out.printf("%3d free = %10d\n", loop, Runtime.getRuntime().freeMemory()); kernel.execute(Range.create(512, 64), 1); for (int i = 0; i < globalArray.length; ++i) { - Assert.assertEquals("Wrong", i, globalArray[i]); + Assert.assertEquals(i, globalArray[i]); } } for (int loop = 0; loop < 100; loop++) { @@ -44,7 +46,7 @@ public void run() { System.out.printf("%3d free = %10d\n", loop, Runtime.getRuntime().freeMemory()); kernel.execute(Range.create(512, 64), 2); for (int i = 0; i < globalArray.length; ++i) { - Assert.assertEquals("Wrong", i, globalArray[i]); + Assert.assertEquals(i, globalArray[i]); } } } diff --git a/src/test/java/com/aparapi/runtime/MultithreadTest.java b/src/test/java/com/aparapi/runtime/MultithreadTest.java new file mode 100644 index 00000000..0629858f --- /dev/null +++ b/src/test/java/com/aparapi/runtime/MultithreadTest.java @@ -0,0 +1,154 @@ +/** + * Copyright (c) 2016 - 2017 Syncleus, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.aparapi.runtime; + +import com.aparapi.Kernel; +import com.aparapi.Range; +import com.aparapi.internal.tool.ABCCKernel; +import org.junit.Test; + +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; + + +public class MultithreadTest { + static float[] t = new float[]{416667f, 416668f, 416669f, 416670f, 416671f, 416672f, 416673f, 416674f, 416675f, 416676f, 416677f, 416678f, 416679f, 416680f, 416681f, 416682f, 416683f, 416684f, 416685f, 416686f, 416687f, 416688f, 416689f, 416690f, 416691f, 416692f, 416693f, 416694f, 416695f, 416696f, 416697f, 416698f, 416699f, 416700f, 416701f, 416702f, 416703f, 416704f, 416705f, 416706f, 416707f, 416708f, 416709f, 416710f, 416711f, 416712f, 416713f, 416714f, 416715f, 416716f, 416717f, 416718f, 416719f, 416720f, 416721f, 416722f, 416723f, 416724f, 416725f, 416726f, 416727f, 416728f, 416729f, 416730f, 416731f, 416732f, 416733f, 416734f, 416735f, 416736f, 416737f, 416738f, 416739f, 416740f, 416741f, 416742f, 416743f, 416744f, 416745f, 416746f, 416747f, 416748f, 416749f, 416750f, 416751f, 416752f, 416753f, 416754f, 416755f, 416756f, 416757f, 416758f, 416759f, 416760f, 416761f, 416762f, 416763f, 416764f, 416765f, 416766f, 416767f, 416768f, 416769f, 416770f, 416771f, 416772f, 416773f, 416774f, 416775f, 416776f, 416777f, 416778f, 416779f, 416780f, 416781f, 416782f, 416783f, 416784f, 416785f, 416786f, 416787f, 416788f, 416789f, 416790f, 416791f, 416792f, 416793f, 416794f, 416795f, 416796f, 416797f, 416798f, 416799f, 416800f, 416801f, 416802f, 416803f, 416804f, 416805f, 416806f, 416807f, 416808f, 416809f, 416810f, 416811f, 416812f, 416813f, 416814f, 416815f, 416816f, 416817f, 416818f, 416819f, 416820f, 416821f, 416822f, 416823f, 416824f, 416825f, 416826f, 416827f, 416828f, 416829f, 416830f, 416831f, 416832f, 416833f, 416834f, 416835f, 416836f, 416837f, 416838f, 416839f, 416840f, 416841f, 416842f, 416843f, 416844f, 416845f, 416846f, 416847f, 416848f, 416849f, 416850f, 416851f, 416852f, 416853f, 416854f, 416855f, 416856f, 416857f, 416858f, 416859f, 416860f, 416861f, 416862f, 416863f, 416864f, 416865f, 416866f}; + static float[] p = new float[]{2034.91f, 2042.03f, 2044.13f, 2063.15f, 2060.7f, 2056.29f, 2057.51f, 2058.18f, 2047.97f, 2001.26f, 2008.72f, 1999.9f, 1981.21f, 1933.88f, 1923.55f, 1939.44f, 1929.48f, 1893.06f, 1910.54f, 1930.46f, 1940.75f, 1929.77f, 1914.37f, 1872.92f, 1831.74f, 1857.52f, 1832.32f, 1830.06f, 1785.75f, 1784.81f, 1796.98f, 1809.07f, 1791.85f, 1768.04f, 1754.01f, 1741.92f, 1765.34f, 1785.87f, 1807.05f, 1797.9f, 1813.57f, 1758.5f, 1775.85f, 1768.07f, 1725.15f, 1716.43f, 1731.33f, 1761.02f, 1760.95f, 1742.41f, 1734.22f, 1731.33f, 1711.96f, 1710.56f, 1663.85f, 1656.57f, 1616.43f, 1611.78f, 1669.43f, 1651.7f, 1662.17f, 1707.62f, 1698.16f, 1669.59f, 1623.32f, 1622.89f, 1648.25f, 1685.88f, 1670.64f, 1694f, 1722.13f, 1706.31f, 1705.01f, 1735.95f, 1743.88f, 1775.36f, 1818.09f, 1812.17f, 1813.04f, 1775.78f, 1756.78f, 1756.94f, 1764.34f, 1812.26f, 1794.48f, 1802.72f, 1865.28f, 1863.09f, 1843.68f, 1893.35f, 1882.88f, 1915.17f, 1934.48f, 1912f, 1907.62f, 1910.38f, 1881.93f, 1914.18f, 1933.92f, 1952.46f, 1974.38f, 1954.74f, 1958.4f, 1956.65f, 1993.21f, 2000.73f, 2019.83f, 2045.57f, 2047.59f, 2002.27f, 2030.48f, 2037.54f, 2043.64f, 2069.43f, 2043.62f, 1992.19f, 2011.31f, 1964.96f, 1992.72f, 1985.37f, 2038.22f, 2018.29f, 2041.33f, 2053.25f, 2086.2f, 2079.23f, 2061.43f, 2060.43f, 2047.58f, 2027.91f, 2004.27f, 2042.32f, 2022.79f, 1999.28f, 1995.37f, 1989.62f, 1945.19f, 1961.19f, 1968.31f, 1971.8f, 1968.05f, 1980.25f, 2009.48f, 2026.87f, 2022.79f, 2023.39f, 2041.25f, 2021.78f, 2022.01f, 2026.15f, 2030.88f, 2041.01f, 2141.41f, 2190.04f, 2248.67f, 2221.63f, 2270.04f, 2259.56f, 2249.08f, 2280.56f, 2284.33f, 2348.77f, 2364.71f, 2438.89f, 2436.04f, 2370.25f, 2411.94f, 2341.18f, 2330.4f, 2377.23f, 2400.77f, 2372f, 2373.93f, 2324.76f, 2355f, 2328.78f, 2369.15f, 2392.48f, 2376.29f, 2359.96f, 2340.38f, 2339.7f, 2304.06f, 2286.95f, 2258.27f, 2268.42f, 2266.97f, 2317.76f, 2295.68f, 2299.64f, 2323.04f, 2340.8f, 2332.45f, 2316.51f, 2351.41f, 2362.82f, 2378.29f, 2404.29f, 2410.59f, 2443.15f}; + + @Test + public void test1() throws InterruptedException { + test(1, 1); + test(1, 2); + } + @Test + public void test4() throws InterruptedException { + test(4, 1); + test(4, 2); + } + @Test + public void test7() throws InterruptedException { + test(7, 1); + } + @Test + public void test9() throws InterruptedException { + test(9, 1); + } + +// @Test +// public void testN() throws InterruptedException { +// int granularity = 3; +// for (int t = 2; t< Math.max(granularity,Runtime.getRuntime().availableProcessors())+ granularity; t+= granularity) { +//// test(t, t/2); +// test(t, t); +//// test(t, t*2); +//// test(t, t*2+1); //odd +// } +// } + + static void test(int THREADS, int KERNELS) throws InterruptedException { + + final int E = (KERNELS * 8); //10000; + + final List kernels = new ArrayList(KERNELS); + for (int i = 0; i < KERNELS; i++) { + kernels.add( new ABCCKernel(t, p) ); + } + + final ExecutorService f = Executors.newFixedThreadPool( + THREADS + ); + + // repeat until we eventually crash + final AtomicInteger next = new AtomicInteger(0); + + for (int i = 0; i< E; i++) { + f.execute(() -> + kernels.get(next.getAndIncrement() % KERNELS).execute(Range.create(t.length))); + } + + f.shutdown(); + f.awaitTermination(1, TimeUnit.MINUTES); + + for (Kernel k : kernels) + k.dispose(); + } + +// static class ABCCKernel extends Kernel { +// public static final int FI = 0, GI = 1, HI = 2, YI = 3, FI2 = 4, FIGI = 5, GI2 = 6, YIFI = 7, YIGI = 8, FIHI = 9, GIHI = 10, HI2 = 11, YIHI = 12; +// public static final int v = 13; +// private static final int TC = 0, M = 1, W = 2; +// private float[] T, p; +// private float[] tcmw = new float[3]; +// private float[] result; +// //public final int N; +// +// public ABCCKernel(float[] t, float[] p) { +// setExplicit(true); +// this.T = t; +// this.p = p; +// this.result = new float[t.length * v]; +// put(this.T).put(this.p).put(result); +// } +// +// public void setNewTandP(float[] t, float[] p) { +// this.T = t; +// this.p = p; +// this.result = new float[t.length * v]; +// put(this.T).put(this.p).put(result); +// } +// +// public void set_tcmw(float tc, float m, float w) { +// this.tcmw = new float[]{tc, m, w}; +// put(this.tcmw); +// } +// +// @Override +// public void run() { +// int i = getGlobalId(); +// int j = i * v; +// int fi = FI + j, gi = GI + j, hi = HI + j, yi = YI + j, fi2 = FI2 + j, figi = FIGI + j, gi2 = GI2 + j, yifi = YIFI + j, yigi = YIGI + j, fihi = FIHI + j, gihi = GIHI + j, hi2 = HI2 + j, yihi = YIHI + j; +// float tc = tcmw[TC]; +// float w = tcmw[W]; +// float m = tcmw[M]; +// +// float[] r = this.result; +// +// r[fi] = pow((tc - T[i]), m); +// r[gi] = r[fi] * cos(w * log(tc - T[i])); //TODO check if this inner log is computed once and shared +// r[hi] = r[fi] * sin(w * log(tc - T[i])); +// r[yi] = p[i]; +// r[fi2] = r[fi] * r[fi]; +// r[figi] = r[fi] * r[gi]; +// r[gi2] = r[gi] * r[gi]; +// r[yifi] = r[yi] * r[fi]; +// r[yigi] = r[yi] * r[gi]; +// r[fihi] = r[fi] * r[hi]; +// r[gihi] = r[gi] * r[hi]; +// r[hi2] = r[hi] * r[hi]; +// r[yihi] = r[yi] * r[hi]; +// } +// +// public float[] getResult() { +// get(result); +// return result; +// } +// } + +} diff --git a/src/test/java/com/aparapi/runtime/Test12x4_4x2.java b/src/test/java/com/aparapi/runtime/Test12x4_4x2.java index a1a72032..a30bda3f 100644 --- a/src/test/java/com/aparapi/runtime/Test12x4_4x2.java +++ b/src/test/java/com/aparapi/runtime/Test12x4_4x2.java @@ -505,11 +505,11 @@ public void run() { show = true; } if (show) { - System.out.println("derived =>" + globalThreadId + " " + threadId + " " + x + "," + y + " " + lx + "," + ly + " " - + w + "," + h); - System.out.println("data =>" + test[globalThreadId][0] + " " + test[globalThreadId][1] + " " - + test[globalThreadId][2] + "," + test[globalThreadId][3] + " " + test[globalThreadId][4] + "," - + test[globalThreadId][5] + " " + w + "," + h); + System.out.println("derived =>" + globalThreadId + ' ' + threadId + ' ' + x + ',' + y + ' ' + lx + ',' + ly + ' ' + + w + ',' + h); + System.out.println("data =>" + test[globalThreadId][0] + ' ' + test[globalThreadId][1] + ' ' + + test[globalThreadId][2] + ',' + test[globalThreadId][3] + ' ' + test[globalThreadId][4] + ',' + + test[globalThreadId][5] + ' ' + w + ',' + h); } } } diff --git a/src/test/java/com/aparapi/runtime/UseStaticArrayTest.java b/src/test/java/com/aparapi/runtime/UseStaticArrayTest.java index 44e2a822..e3f7a54b 100644 --- a/src/test/java/com/aparapi/runtime/UseStaticArrayTest.java +++ b/src/test/java/com/aparapi/runtime/UseStaticArrayTest.java @@ -16,11 +16,9 @@ package com.aparapi.runtime; import com.aparapi.Kernel; -import com.aparapi.device.Device; import org.junit.Test; import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertTrue; public class UseStaticArrayTest { @Test