Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,15 @@
import static org.objectweb.asm.Opcodes.*;

import datadog.instrument.classinject.ClassInjector;
import datadog.instrument.glue.ObjectStoreGlue;
import datadog.instrument.testing.TestAgent;
import java.io.IOException;
import java.lang.instrument.ClassFileTransformer;
import java.lang.instrument.Instrumentation;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.security.ProtectionDomain;
Expand Down Expand Up @@ -48,19 +50,20 @@ final class DispatchBenchmarkSupport {

private DispatchBenchmarkSupport() {}

static synchronized void install(String variant) throws Exception {
static synchronized String install(String variant) throws Exception {
String dispatchClass =
variant.equals("direct") ? DIRECT_DISPATCH : BOOT_PREFIX + "ObjectStoreDispatch_" + variant;
if (installed != null) {
if (!installed.equals(variant)) {
throw new IllegalStateException("Use a separate JMH fork for each variant");
}
return;
return dispatchClass;
}
Instrumentation inst = TestAgent.getInstrumentation();
ClassInjector.enableClassInjection(inst);
injectDirectStore();
String dispatchClass = DIRECT_DISPATCH;
Class<?> bridge = ClassInjector.injectBootClass(BRIDGE.replace('/', '.'), relocateBridge());
if (!variant.equals("direct")) {
Class<?> bridge = ClassInjector.injectBootClass(BRIDGE.replace('/', '.'), relocateBridge());
Map<String, MethodHandle> targets = new HashMap<>();
MethodHandles.Lookup lookup = MethodHandles.lookup();
for (Method method : GlobalObjectStore.class.getDeclaredMethods()) {
Expand All @@ -69,13 +72,105 @@ static synchronized void install(String variant) throws Exception {
}
}
bridge.getMethod("initialize", Map.class).invoke(null, targets);
dispatchClass = BOOT_PREFIX + "ObjectStoreDispatch_" + variant;
ClassInjector.injectBootClass(
dispatchClass.replace('/', '.'), dispatcher(variant, dispatchClass));
}
inst.addTransformer(new SelectDispatch(dispatchClass), true);
inst.retransformClasses(ObjectStore.class);
installed = variant;
return dispatchClass;
}

static int removeStaleEntries() throws Exception {
// Direct dispatch uses the relocated bootstrap store; other variants bind to the local store.
if (installed.equals("direct")) {
return (Integer)
Class.forName(BRIDGE.replace('/', '.')).getMethod("removeStaleEntries").invoke(null);
}
return ObjectStore.removeStaleEntries();
}

static void populateKeys(String storage, String dispatchClass, Object[]... groups)
throws Exception {
Constructor<?> constructor = null;
switch (storage) {
case "uninjected":
break;
case "injected":
case "weakFallback":
String name = BOOT_PREFIX + "DispatchBenchmarkKey_" + storage;
constructor =
ClassInjector.injectBootClass(
name.replace('/', '.'),
generateKey(name, storage.equals("injected"), dispatchClass))
.getConstructor();
break;
default:
throw new IllegalArgumentException(storage);
}
for (Object[] keys : groups) {
for (int i = 0; i < keys.length; i++) {
keys[i] = constructor == null ? new Object() : constructor.newInstance();
}
}
}

/** Models a field-injected key with either a field or a weak fallback for the requested store. */
private static byte[] generateKey(String name, boolean injected, String dispatchClass) {
ClassWriter cw = new ClassWriter(0);
cw.visit(
V1_8,
ACC_PUBLIC | ACC_FINAL,
name,
null,
"java/lang/Object",
new String[] {ObjectStoreGlue.KEY_ID.replace('.', '/')});
if (injected) {
cw.visitField(ACC_PRIVATE, "value", "Ljava/lang/Object;", null, null).visitEnd();
}
MethodVisitor mv = cw.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null);
mv.visitCode();
mv.visitVarInsn(ALOAD, 0);
mv.visitMethodInsn(INVOKESPECIAL, "java/lang/Object", "<init>", "()V", false);
mv.visitInsn(RETURN);
mv.visitMaxs(1, 1);
mv.visitEnd();

mv = cw.visitMethod(ACC_PUBLIC, "$get$__dd_instrument$", "(I)Ljava/lang/Object;", null, null);
mv.visitCode();
mv.visitVarInsn(ALOAD, 0);
if (injected) {
mv.visitFieldInsn(GETFIELD, name, "value", "Ljava/lang/Object;");
} else {
mv.visitVarInsn(ILOAD, 1);
mv.visitMethodInsn(
INVOKESTATIC, dispatchClass, "weakGet", "(Ljava/lang/Object;I)Ljava/lang/Object;", false);
}
mv.visitInsn(ARETURN);
mv.visitMaxs(2, 2);
mv.visitEnd();

mv = cw.visitMethod(ACC_PUBLIC, "$put$__dd_instrument$", "(ILjava/lang/Object;)V", null, null);
mv.visitCode();
mv.visitVarInsn(ALOAD, 0);
if (injected) {
mv.visitVarInsn(ALOAD, 2);
mv.visitFieldInsn(PUTFIELD, name, "value", "Ljava/lang/Object;");
} else {
mv.visitVarInsn(ILOAD, 1);
mv.visitVarInsn(ALOAD, 2);
mv.visitMethodInsn(
INVOKESTATIC,
dispatchClass,
"weakPut",
"(Ljava/lang/Object;ILjava/lang/Object;)V",
false);
}
mv.visitInsn(RETURN);
mv.visitMaxs(3, 3);
mv.visitEnd();
cw.visitEnd();
return cw.toByteArray();
}

// Keep the measured baseline independent of the production bootstrap dispatcher.
Expand Down Expand Up @@ -104,16 +199,17 @@ private static void injectDirectStore() throws Exception {

private static byte[] relocateBridge() throws IOException {
ClassWriter writer = new ClassWriter(0);
Map<String, String> renames = new HashMap<>();
renames.put(Type.getInternalName(DispatchBridge.class), BRIDGE);
renames.put(LOCAL_GLOBAL_STORE, BOOT_GLOBAL_STORE);
new ClassReader(DispatchBridge.class.getName())
.accept(
new ClassRemapper(
writer,
new SimpleRemapper(ASM9, Type.getInternalName(DispatchBridge.class), BRIDGE)),
0);
.accept(new ClassRemapper(writer, new SimpleRemapper(ASM9, renames)), 0);
return writer.toByteArray();
}

private static byte[] dispatcher(String variant, String dispatchClass) throws IOException {
boolean shared = variant.equals("indyShared");
boolean indy = variant.equals("indy") || shared;
ClassWriter writer = new ClassWriter(0);
Handle bootstrap =
new Handle(
Expand All @@ -138,6 +234,8 @@ public MethodVisitor visitMethod(
String descriptor,
String signature,
String[] exceptions) {
String weakFallback =
name.equals("get") ? "weakGet" : name.equals("put") ? "weakPut" : null;
return new MethodVisitor(
ASM9, super.visitMethod(access, name, descriptor, signature, exceptions)) {
@Override
Expand All @@ -148,7 +246,11 @@ public void visitMethodInsn(
String descriptor,
boolean isInterface) {
if (opcode == INVOKESTATIC && BOOT_GLOBAL_STORE.equals(owner)) {
if (variant.equals("indy")) {
if (shared && weakFallback != null) {
// Keep indy only in weakGet/weakPut; normal accessors call them.
super.visitMethodInsn(
INVOKESTATIC, dispatchClass, weakFallback, descriptor, false);
} else if (indy) {
visitInvokeDynamicInsn(name, descriptor, bootstrap);
} else {
super.visitMethodInsn(
Expand Down Expand Up @@ -210,7 +312,7 @@ public void visitEnd() {}
},
remapper),
0);
} else if (!variant.equals("indy")) {
} else if (!indy) {
throw new IllegalArgumentException(variant);
}
writer.visitEnd();
Expand Down Expand Up @@ -238,7 +340,27 @@ public byte[] transform(
ClassReader reader = new ClassReader(bytecode);
ClassWriter writer = new ClassWriter(reader, 0);
reader.accept(
new ClassRemapper(writer, new SimpleRemapper(ASM9, LOCAL_GLOBAL_STORE, dispatchClass)),
new ClassVisitor(ASM9, writer) {
@Override
public MethodVisitor visitMethod(
int access, String name, String descriptor, String signature, String[] exceptions) {
MethodVisitor mv = super.visitMethod(access, name, descriptor, signature, exceptions);
// Only instance operations use dispatch; static cleanup stays on the global store.
if ((access & ACC_STATIC) != 0) {
return mv;
}
return new MethodVisitor(ASM9, mv) {
@Override
public void visitMethodInsn(
int opcode, String owner, String name, String descriptor, boolean isInterface) {
if (opcode == INVOKESTATIC && LOCAL_GLOBAL_STORE.equals(owner)) {
owner = dispatchClass;
}
super.visitMethodInsn(opcode, owner, name, descriptor, isInterface);
}
};
}
},
0);
return writer.toByteArray();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,18 @@
import java.util.Collections;
import java.util.Map;

/** Template copied to the bootstrap loader before either bridge is linked. */
/** Bootstrap template for benchmark fallback linkage and direct-store cleanup. */
@SuppressWarnings("unused") // Called reflectively or from generated benchmark bytecode.
public final class DispatchBridge {
private static Map<String, MethodHandle> targets = Collections.emptyMap();

private DispatchBridge() {}

/** Sweeps the relocated store used by the direct benchmark baseline. */
public static int removeStaleEntries() {
return GlobalObjectStore.removeStaleEntries();
}

public static void initialize(Map<String, MethodHandle> handles) {
targets = handles;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,13 @@
import java.util.function.Function;

/** Its fields and methods are copied into the generated final-handle dispatcher. */
@SuppressWarnings("unused") // Methods are copied into generated benchmark bytecode.
final class FinalHandleFallback {
private static final MethodHandle GET = DispatchBridge.target("get");
private static final MethodHandle PUT = DispatchBridge.target("put");
private static final MethodHandle GET_OR_PUT = DispatchBridge.target("getOrPut");
private static final MethodHandle GET_OR_COMPUTE = DispatchBridge.target("getOrCompute");
private static final MethodHandle REMOVE = DispatchBridge.target("remove");
private static final MethodHandle CLEAN = DispatchBridge.target("removeStaleEntries");

private FinalHandleFallback() {}

Expand All @@ -40,8 +40,4 @@ public static Object getOrCompute(Object key, int storeId, Function<Object, Obje
public static Object remove(Object key, int storeId) throws Throwable {
return (Object) REMOVE.invokeExact(key, storeId);
}

public static int removeStaleEntries() throws Throwable {
return (int) CLEAN.invokeExact();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,10 @@
import org.openjdk.jmh.annotations.Threads;
import org.openjdk.jmh.annotations.Warmup;

/** Runs with the testing jar supplied through -javaagent, including in each JMH fork. */
/**
* Compares dispatch alternatives across key storage paths. Runs with the testing jar supplied
* through -javaagent, including in each JMH fork.
*/
@State(Scope.Thread)
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(NANOSECONDS)
Expand All @@ -38,9 +41,12 @@ public class ObjectStoreDispatchBenchmark {
private static final String KEY_TYPE = "benchmark.Dispatch.Key";
private static final String VALUE_TYPE = "benchmark.Dispatch.Value";

@Param({"direct", "finalHandle", "indy"})
@Param({"direct", "finalHandle", "indy", "indyShared"})
public String dispatch;

@Param({"uninjected", "injected", "weakFallback"})
public String storage;

private final Object[] keys = new Object[KEY_COUNT];
private final Object[] absentKeys = new Object[KEY_COUNT];
private final Object value = new Object();
Expand All @@ -50,33 +56,41 @@ public class ObjectStoreDispatchBenchmark {

@Setup
public void setup() throws Exception {
DispatchBenchmarkSupport.install(dispatch);
String dispatchClass = DispatchBenchmarkSupport.install(dispatch);
DispatchBenchmarkSupport.populateKeys(storage, dispatchClass, keys, absentKeys);
store = ObjectStore.of(KEY_TYPE, VALUE_TYPE);
for (int i = 0; i < KEY_COUNT; i++) {
keys[i] = new Object();
absentKeys[i] = new Object();
store.put(keys[i], value);
}
verifyFallback();
verifyDispatch();
}

private void verifyFallback() {
Object key = new Object();
private void verifyDispatch() throws Exception {
verifyOperations(new Object());
verifyOperations(absentKeys[0]);
if (store.get(keys[0]) != value) {
throw new AssertionError("Stored value missing: " + dispatch + "/" + storage);
}
int remaining = DispatchBenchmarkSupport.removeStaleEntries();
if (!storage.equals("injected") && remaining < KEY_COUNT) {
throw new AssertionError("Cleanup missed live entries: " + dispatch + "/" + storage);
}
int storeId = ObjectStoreIds.objectStoreId(KEY_TYPE, VALUE_TYPE);
Object expectedGlobalValue =
!dispatch.equals("direct") && !storage.equals("injected") ? value : null;
if (GlobalObjectStore.get(keys[0], storeId) != expectedGlobalValue) {
throw new AssertionError("Unexpected global storage: " + dispatch + "/" + storage);
}
}

private void verifyOperations(Object key) {
if (store.get(key) != null
|| store.getOrPut(key, value) != value
|| store.getOrCompute(key, factory) != value
|| store.remove(key) != value
|| store.getOrCompute(key, factory) != value
|| store.remove(key) != value) {
throw new AssertionError("Global fallback failed: " + dispatch);
}
ObjectStore.removeStaleEntries();
int storeId = ObjectStoreIds.objectStoreId(KEY_TYPE, VALUE_TYPE);
if (!dispatch.equals("direct") && GlobalObjectStore.get(keys[0], storeId) != value) {
throw new AssertionError("Bridge did not use the original global store");
}
if (dispatch.equals("direct") && GlobalObjectStore.get(keys[0], storeId) != null) {
throw new AssertionError("Direct baseline did not use the bootstrap global store");
throw new AssertionError("Dispatch operations failed: " + dispatch + "/" + storage);
}
}

Expand Down
Loading