2 * Copyright (c) 2019 PANTHEON.tech, s.r.o. and others. All rights reserved.
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6 * and is available at http://www.eclipse.org/legal/epl-v10.html
8 package org.opendaylight.mdsal.binding.dom.codec.impl;
10 import static com.google.common.base.Verify.verify;
11 import static com.google.common.base.Verify.verifyNotNull;
12 import static java.util.Objects.requireNonNull;
13 import static org.opendaylight.mdsal.binding.dom.codec.impl.ByteBuddyUtils.THIS;
14 import static org.opendaylight.mdsal.binding.dom.codec.impl.ByteBuddyUtils.getField;
15 import static org.opendaylight.mdsal.binding.dom.codec.impl.ByteBuddyUtils.invokeMethod;
16 import static org.opendaylight.mdsal.binding.dom.codec.impl.ByteBuddyUtils.putField;
18 import com.google.common.base.MoreObjects.ToStringHelper;
19 import com.google.common.base.Supplier;
20 import com.google.common.collect.ImmutableMap;
21 import com.google.common.collect.Maps;
22 import java.lang.reflect.Method;
23 import java.util.ArrayList;
24 import java.util.Arrays;
25 import java.util.Comparator;
26 import java.util.List;
28 import java.util.Map.Entry;
29 import java.util.Objects;
30 import java.util.Optional;
31 import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
32 import net.bytebuddy.ByteBuddy;
33 import net.bytebuddy.description.field.FieldDescription;
34 import net.bytebuddy.description.method.MethodDescription;
35 import net.bytebuddy.description.type.TypeDefinition;
36 import net.bytebuddy.description.type.TypeDescription;
37 import net.bytebuddy.description.type.TypeDescription.Generic;
38 import net.bytebuddy.dynamic.DynamicType.Builder;
39 import net.bytebuddy.dynamic.scaffold.InstrumentedType;
40 import net.bytebuddy.implementation.Implementation;
41 import net.bytebuddy.implementation.Implementation.Context;
42 import net.bytebuddy.implementation.bytecode.Addition;
43 import net.bytebuddy.implementation.bytecode.ByteCodeAppender;
44 import net.bytebuddy.implementation.bytecode.Multiplication;
45 import net.bytebuddy.implementation.bytecode.StackManipulation;
46 import net.bytebuddy.implementation.bytecode.assign.TypeCasting;
47 import net.bytebuddy.implementation.bytecode.constant.ClassConstant;
48 import net.bytebuddy.implementation.bytecode.constant.IntegerConstant;
49 import net.bytebuddy.implementation.bytecode.constant.TextConstant;
50 import net.bytebuddy.implementation.bytecode.member.MethodReturn;
51 import net.bytebuddy.implementation.bytecode.member.MethodVariableAccess;
52 import net.bytebuddy.jar.asm.Label;
53 import net.bytebuddy.jar.asm.MethodVisitor;
54 import net.bytebuddy.jar.asm.Opcodes;
55 import org.eclipse.jdt.annotation.NonNull;
56 import org.eclipse.jdt.annotation.Nullable;
57 import org.opendaylight.mdsal.binding.dom.codec.loader.CodecClassLoader;
58 import org.opendaylight.mdsal.binding.dom.codec.loader.CodecClassLoader.ClassGenerator;
59 import org.opendaylight.mdsal.binding.dom.codec.loader.CodecClassLoader.GeneratorResult;
60 import org.opendaylight.yangtools.yang.binding.DataObject;
61 import org.slf4j.Logger;
62 import org.slf4j.LoggerFactory;
65 * Private support for generating {@link CodecDataObject} and {@link AugmentableCodecDataObject} specializations.
68 * Code generation here is probably more involved than usual mainly due to the fact we *really* want to express the
69 * strong connection between a generated class and BindingCodecContext in terms of a true constant, which boils down to
70 * {@code private static final NodeContextSupplier NCS}. Having such constants provides significant boost to JITs
71 * ability to optimize code -- especially with inlining and constant propagation.
74 * The accessor mapping performance is critical due to users typically not taking care of storing the results acquired
75 * by an invocation, assuming the accessors are backed by a normal field -- which of course is not true, as the results
76 * are lazily computed.
79 * The design is such that for a particular structure like:
87 * we end up generating a class with the following layout:
89 * public final class Foo$$$codecImpl extends CodecDataObject implements Foo {
90 * private static final AtomicRefereceFieldUpdater<Foo$$$codecImpl, Object> getBar$$$A;
91 * private volatile Object getBar;
93 * public Foo$$$codecImpl(NormalizedNodeContainer data) {
97 * public Bar getBar() {
98 * return (Bar) codecMember(getBar$$$A, "bar");
104 * This strategy minimizes the bytecode footprint and follows the generally good idea of keeping common logic in a
105 * single place in a maintainable form. The glue code is extremely light (~6 instructions), which is beneficial on both
106 * sides of invocation:
107 * - generated method can readily be inlined into the caller
108 * - it forms a call site into which codeMember() can be inlined with AtomicReferenceFieldUpdater being constant
111 * The second point is important here, as it allows the invocation logic around AtomicRefereceFieldUpdater to completely
112 * disappear, becoming synonymous with operations of a volatile field.
115 * Furthermore there are distinct {@code codecMember} methods, each of which supports a different invocation style:
117 * <li>with {@code String}, which ends up looking up a {@link ValueNodeCodecContext}</li>
118 * <li>with {@code Class}, which ends up looking up a {@link DataContainerCodecContext}</li>
119 * <li>with {@code NodeContextSupplier}, which performs a direct load</li>
121 * The third mode of operation requires that the object being implemented is not defined in a {@code grouping}, because
122 * it welds the object to a particular namespace -- hence it trades namespace mobility for access speed.
125 * The sticky point here is the NodeContextSupplier, as it is a heap object which cannot normally be looked up from the
126 * static context in which the static class initializer operates -- so we need perform some sort of a trick here.
127 * Eventhough ByteBuddy provides facilities for bridging references to type fields, those facilities operate on volatile
128 * fields -- hence they do not quite work for us.
131 * Another alternative, which we used in Javassist-generated DataObjectSerializers, is to muck with the static field
132 * using reflection -- which works, but requires redefinition of Field.modifiers, which is something Java 9 complains
133 * about quite noisily.
136 * We take a different approach here, which takes advantage of the fact we are in control of both code generation (here)
137 * and class loading (in {@link CodecClassLoader}). The process is performed in four steps:
139 * <li>During code generation, the context fields are pointed towards {@link CodecDataObjectBridge#resolve(String)} and
140 * {@link CodecDataObjectBridge#resolveKey(String)} methods, which are public and static, hence perfectly usable
141 * in the context of a class initializer.</li>
142 * <li>During class loading of generated byte code, the original instance of the generator is called to wrap the actual
143 * class loading operation. At this point the generator installs itself as the current generator for this thread via
144 * {@link CodecDataObjectBridge#setup(CodecDataObjectGenerator)} and allows the class to be loaded.
145 * <li>After the class has been loaded, but before the call returns, we will force the class to initialize, at which
146 * point the static invocations will be redirect to {@link #resolve(String)} and {@link #resolveKey(String)}
147 * methods, thus initializing the fields to the intended constants.</li>
148 * <li>Before returning from the class loading call, the generator will detach itself via
149 * {@link CodecDataObjectBridge#tearDown(CodecDataObjectGenerator)}.</li>
153 * This strategy works due to close cooperation with the target ClassLoader, as the entire code generation and loading
154 * block runs with the class loading lock for this FQCN and the reference is not leaked until the process completes.
156 abstract class CodecDataObjectGenerator<T extends CodecDataObject<?>> implements ClassGenerator<T> {
157 // Not reusable defintion: we can inline NodeContextSuppliers without a problem
158 static final class Fixed<T extends CodecDataObject<?>> extends CodecDataObjectGenerator<T> {
159 private final ImmutableMap<Method, NodeContextSupplier> properties;
161 private Fixed(final Builder<?> template, final ImmutableMap<Method, NodeContextSupplier> properties,
162 final @Nullable Method keyMethod) {
163 super(template, keyMethod);
164 this.properties = requireNonNull(properties);
168 Builder<T> generateGetters(final Builder<T> builder) {
169 Builder<T> tmp = builder;
170 for (Method method : properties.keySet()) {
171 LOG.trace("Generating for fixed method {}", method);
172 final String methodName = method.getName();
173 final TypeDescription retType = TypeDescription.ForLoadedType.of(method.getReturnType());
174 tmp = tmp.defineMethod(methodName, retType, PUB_FINAL).intercept(
175 new SupplierGetterMethodImplementation(methodName, retType));
181 ArrayList<Method> getterMethods() {
182 return new ArrayList<>(properties.keySet());
186 public Class<T> customizeLoading(final @NonNull Supplier<Class<T>> loader) {
187 final Fixed<?> prev = CodecDataObjectBridge.setup(this);
189 final Class<T> result = loader.get();
192 * This a bit of magic to support NodeContextSupplier constants. These constants need to be resolved
193 * while we have the information needed to find them -- that information is being held in this instance
194 * and we leak it to a thread-local variable held by CodecDataObjectBridge.
196 * By default the JVM will defer class initialization to first use, which unfortunately is too late for
197 * us, and hence we need to force class to initialize.
200 Class.forName(result.getName(), true, result.getClassLoader());
201 } catch (ClassNotFoundException e) {
202 throw new LinkageError("Failed to find newly-defined " + result, e);
207 CodecDataObjectBridge.tearDown(prev);
211 @NonNull NodeContextSupplier resolve(final @NonNull String methodName) {
212 final Optional<Entry<Method, NodeContextSupplier>> found = properties.entrySet().stream()
213 .filter(entry -> methodName.equals(entry.getKey().getName())).findAny();
214 verify(found.isPresent(), "Failed to find property for %s in %s", methodName, this);
215 return verifyNotNull(found.get().getValue());
219 // Reusable definition: we have to rely on context lookups
220 private static final class Reusable<T extends CodecDataObject<?>> extends CodecDataObjectGenerator<T> {
221 private final ImmutableMap<Method, ValueNodeCodecContext> simpleProperties;
222 private final Map<Method, Class<?>> daoProperties;
224 private Reusable(final Builder<?> template,
225 final ImmutableMap<Method, ValueNodeCodecContext> simpleProperties,
226 final Map<Method, Class<?>> daoProperties, final @Nullable Method keyMethod) {
227 super(template, keyMethod);
228 this.simpleProperties = requireNonNull(simpleProperties);
229 this.daoProperties = requireNonNull(daoProperties);
233 Builder<T> generateGetters(final Builder<T> builder) {
234 Builder<T> tmp = builder;
235 for (Entry<Method, ValueNodeCodecContext> entry : simpleProperties.entrySet()) {
236 final Method method = entry.getKey();
237 LOG.trace("Generating for simple method {}", method);
238 final String methodName = method.getName();
239 final TypeDescription retType = TypeDescription.ForLoadedType.of(method.getReturnType());
240 tmp = tmp.defineMethod(methodName, retType, PUB_FINAL).intercept(
241 new SimpleGetterMethodImplementation(methodName, retType,
242 entry.getValue().getSchema().getQName().getLocalName()));
244 for (Entry<Method, Class<?>> entry : daoProperties.entrySet()) {
245 final Method method = entry.getKey();
246 LOG.trace("Generating for structured method {}", method);
247 final String methodName = method.getName();
248 final TypeDescription retType = TypeDescription.ForLoadedType.of(method.getReturnType());
249 tmp = tmp.defineMethod(methodName, retType, PUB_FINAL).intercept(
250 new StructuredGetterMethodImplementation(methodName, retType, entry.getValue()));
257 ArrayList<Method> getterMethods() {
258 final ArrayList<Method> ret = new ArrayList<>(simpleProperties.size() + daoProperties.size());
259 ret.addAll(simpleProperties.keySet());
260 ret.addAll(daoProperties.keySet());
265 private static final Logger LOG = LoggerFactory.getLogger(CodecDataObjectGenerator.class);
266 private static final Generic BB_BOOLEAN = TypeDefinition.Sort.describe(boolean.class);
267 private static final Generic BB_DATAOBJECT = TypeDefinition.Sort.describe(DataObject.class);
268 private static final Generic BB_HELPER = TypeDefinition.Sort.describe(ToStringHelper.class);
269 private static final Generic BB_INT = TypeDefinition.Sort.describe(int.class);
270 private static final Comparator<Method> METHOD_BY_ALPHABET = Comparator.comparing(Method::getName);
272 private static final StackManipulation ARRAYS_EQUALS = invokeMethod(Arrays.class, "equals",
273 byte[].class, byte[].class);
274 private static final StackManipulation OBJECTS_EQUALS = invokeMethod(Objects.class, "equals",
275 Object.class, Object.class);
276 private static final StackManipulation HELPER_ADD = invokeMethod(ToStringHelper.class, "add",
277 String.class, Object.class);
279 private static final StackManipulation FIRST_ARG_REF = MethodVariableAccess.REFERENCE.loadFrom(1);
281 private static final int PROT_FINAL = Opcodes.ACC_PROTECTED | Opcodes.ACC_FINAL | Opcodes.ACC_SYNTHETIC;
282 private static final int PUB_FINAL = Opcodes.ACC_PUBLIC | Opcodes.ACC_FINAL | Opcodes.ACC_SYNTHETIC;
284 private static final Builder<?> CDO;
285 private static final Builder<?> ACDO;
288 final ByteBuddy bb = new ByteBuddy();
289 CDO = bb.subclass(CodecDataObject.class).visit(ByteBuddyUtils.computeFrames());
290 ACDO = bb.subclass(AugmentableCodecDataObject.class).visit(ByteBuddyUtils.computeFrames());
293 private final Builder<?> template;
294 private final Method keyMethod;
296 private CodecDataObjectGenerator(final Builder<?> template, final @Nullable Method keyMethod) {
297 this.template = requireNonNull(template);
298 this.keyMethod = keyMethod;
301 static <D extends DataObject, T extends CodecDataObject<T>> Class<T> generate(final CodecClassLoader loader,
302 final Class<D> bindingInterface, final ImmutableMap<Method, ValueNodeCodecContext> simpleProperties,
303 final Map<Method, Class<?>> daoProperties, final Method keyMethod) {
304 return loader.generateClass(bindingInterface, "codecImpl",
305 new Reusable<>(CDO, simpleProperties, daoProperties, keyMethod));
308 static <D extends DataObject, T extends CodecDataObject<T>> Class<T> generateAugmentable(
309 final CodecClassLoader loader, final Class<D> bindingInterface,
310 final ImmutableMap<Method, ValueNodeCodecContext> simpleProperties,
311 final Map<Method, Class<?>> daoProperties, final Method keyMethod) {
312 return loader.generateClass(bindingInterface, "codecImpl",
313 new Reusable<>(ACDO, simpleProperties, daoProperties, keyMethod));
317 public final GeneratorResult<T> generateClass(final CodecClassLoader loeader, final String fqcn,
318 final Class<?> bindingInterface) {
319 LOG.trace("Generating class {}", fqcn);
321 @SuppressWarnings("unchecked")
322 Builder<T> builder = (Builder<T>) template.name(fqcn).implement(bindingInterface);
324 builder = generateGetters(builder);
326 if (keyMethod != null) {
327 LOG.trace("Generating for key {}", keyMethod);
328 final String methodName = keyMethod.getName();
329 final TypeDescription retType = TypeDescription.ForLoadedType.of(keyMethod.getReturnType());
330 builder = builder.defineMethod(methodName, retType, PUB_FINAL).intercept(
331 new KeyMethodImplementation(methodName, retType));
334 // Index all property methods, turning them into "getFoo()" invocations, retaining order. We will be using
335 // those invocations in each of the three methods. Note that we do not glue the invocations to 'this', as we
336 // will be invoking them on 'other' in codecEquals()
337 final ArrayList<Method> properties = getterMethods();
338 // Make sure properties are alpha-sorted
339 properties.sort(METHOD_BY_ALPHABET);
340 final ImmutableMap<StackManipulation, Method> methods = Maps.uniqueIndex(properties,
341 ByteBuddyUtils::invokeMethod);
344 return GeneratorResult.of(builder
345 // codecHashCode() ...
346 .defineMethod("codecHashCode", BB_INT, PROT_FINAL)
347 .intercept(new Implementation.Simple(new CodecHashCode(methods)))
348 // ... codecEquals() ...
349 .defineMethod("codecEquals", BB_BOOLEAN, PROT_FINAL).withParameter(BB_DATAOBJECT)
350 .intercept(codecEquals(methods))
351 // ... and codecFillToString() ...
352 .defineMethod("codecFillToString", BB_HELPER, PROT_FINAL).withParameter(BB_HELPER)
353 .intercept(codecFillToString(methods))
358 abstract Builder<T> generateGetters(Builder<T> builder);
360 abstract ArrayList<Method> getterMethods();
362 private static Implementation codecEquals(final ImmutableMap<StackManipulation, Method> properties) {
363 // Label for 'return false;'
364 final Label falseLabel = new Label();
365 // Condition for 'if (!...)'
366 final StackManipulation ifFalse = ByteBuddyUtils.ifEq(falseLabel);
368 final List<StackManipulation> manipulations = new ArrayList<>(properties.size() * 6 + 5);
369 for (Entry<StackManipulation, Method> entry : properties.entrySet()) {
370 // if (!java.util.(Objects|Arrays).equals(getFoo(), other.getFoo())) {
373 manipulations.add(THIS);
374 manipulations.add(entry.getKey());
375 manipulations.add(FIRST_ARG_REF);
376 manipulations.add(entry.getKey());
377 manipulations.add(entry.getValue().getReturnType().isArray() ? ARRAYS_EQUALS : OBJECTS_EQUALS);
378 manipulations.add(ifFalse);
382 manipulations.add(IntegerConstant.ONE);
383 manipulations.add(MethodReturn.INTEGER);
385 manipulations.add(ByteBuddyUtils.markLabel(falseLabel));
386 manipulations.add(IntegerConstant.ZERO);
387 manipulations.add(MethodReturn.INTEGER);
389 return new Implementation.Simple(manipulations.toArray(new StackManipulation[0]));
392 private static Implementation codecFillToString(final ImmutableMap<StackManipulation, Method> properties) {
393 final List<StackManipulation> manipulations = new ArrayList<>(properties.size() * 4 + 2);
394 // push 'return helper' to stack...
395 manipulations.add(FIRST_ARG_REF);
396 for (Entry<StackManipulation, Method> entry : properties.entrySet()) {
397 // .add("getFoo", getFoo())
398 manipulations.add(new TextConstant(entry.getValue().getName()));
399 manipulations.add(THIS);
400 manipulations.add(entry.getKey());
401 manipulations.add(HELPER_ADD);
403 // ... execute 'return helper'
404 manipulations.add(MethodReturn.REFERENCE);
406 return new Implementation.Simple(manipulations.toArray(new StackManipulation[0]));
409 private abstract static class AbstractMethodImplementation implements Implementation {
410 private static final Generic BB_ARFU = TypeDefinition.Sort.describe(AtomicReferenceFieldUpdater.class);
411 private static final Generic BB_OBJECT = TypeDefinition.Sort.describe(Object.class);
412 private static final StackManipulation OBJECT_CLASS = ClassConstant.of(TypeDescription.OBJECT);
413 private static final StackManipulation ARFU_NEWUPDATER = invokeMethod(AtomicReferenceFieldUpdater.class,
414 "newUpdater", Class.class, Class.class, String.class);
416 static final int PRIV_CONST = Opcodes.ACC_PRIVATE | Opcodes.ACC_STATIC | Opcodes.ACC_FINAL
417 | Opcodes.ACC_SYNTHETIC;
418 private static final int PRIV_VOLATILE = Opcodes.ACC_PRIVATE | Opcodes.ACC_VOLATILE | Opcodes.ACC_SYNTHETIC;
420 final TypeDescription retType;
422 final String methodName;
424 final String arfuName;
426 AbstractMethodImplementation(final String methodName, final TypeDescription retType) {
427 this.methodName = requireNonNull(methodName);
428 this.retType = requireNonNull(retType);
429 this.arfuName = methodName + "$$$A";
433 public InstrumentedType prepare(final InstrumentedType instrumentedType) {
434 final InstrumentedType tmp = instrumentedType
435 // private static final AtomicReferenceFieldUpdater<This, Object> getFoo$$$A;
436 .withField(new FieldDescription.Token(arfuName, PRIV_CONST, BB_ARFU))
437 // private volatile Object getFoo;
438 .withField(new FieldDescription.Token(methodName, PRIV_VOLATILE, BB_OBJECT));
440 return tmp.withInitializer(new ByteCodeAppender.Simple(
441 // getFoo$$$A = AtomicReferenceFieldUpdater.newUpdater(This.class, Object.class, "getFoo");
442 ClassConstant.of(tmp),
444 new TextConstant(methodName),
446 putField(tmp, arfuName)));
450 private static final class KeyMethodImplementation extends AbstractMethodImplementation {
451 private static final StackManipulation CODEC_KEY = invokeMethod(CodecDataObject.class,
452 "codecKey", AtomicReferenceFieldUpdater.class);
454 KeyMethodImplementation(final String methodName, final TypeDescription retType) {
455 super(methodName, retType);
459 public ByteCodeAppender appender(final Target implementationTarget) {
460 final TypeDescription instrumentedType = implementationTarget.getInstrumentedType();
461 return new ByteCodeAppender.Simple(
462 // return (FooType) codecKey(getFoo$$$A);
464 getField(instrumentedType, arfuName),
466 TypeCasting.to(retType),
467 MethodReturn.REFERENCE);
471 private static final class SimpleGetterMethodImplementation extends AbstractMethodImplementation {
472 private static final StackManipulation CODEC_MEMBER = invokeMethod(CodecDataObject.class,
473 "codecMember", AtomicReferenceFieldUpdater.class, String.class);
475 private final String localName;
477 SimpleGetterMethodImplementation(final String methodName, final TypeDescription retType,
478 final String localName) {
479 super(methodName, retType);
480 this.localName = requireNonNull(localName);
484 public ByteCodeAppender appender(final Target implementationTarget) {
485 final TypeDescription instrumentedType = implementationTarget.getInstrumentedType();
486 return new ByteCodeAppender.Simple(
487 // return (FooType) codecMember(getFoo$$$A, "foo");
489 getField(instrumentedType, arfuName),
490 new TextConstant(localName),
492 TypeCasting.to(retType),
493 MethodReturn.REFERENCE);
497 private static final class StructuredGetterMethodImplementation extends AbstractMethodImplementation {
498 private static final StackManipulation CODEC_MEMBER = invokeMethod(CodecDataObject.class,
499 "codecMember", AtomicReferenceFieldUpdater.class, Class.class);
501 private final Class<?> bindingClass;
503 StructuredGetterMethodImplementation(final String methodName, final TypeDescription retType,
504 final Class<?> bindingClass) {
505 super(methodName, retType);
506 this.bindingClass = requireNonNull(bindingClass);
510 public ByteCodeAppender appender(final Target implementationTarget) {
511 final TypeDescription instrumentedType = implementationTarget.getInstrumentedType();
512 return new ByteCodeAppender.Simple(
513 // return (FooType) codecMember(getFoo$$$A, FooType.class);
515 getField(instrumentedType, arfuName),
516 ClassConstant.of(TypeDefinition.Sort.describe(bindingClass).asErasure()),
518 TypeCasting.to(retType),
519 MethodReturn.REFERENCE);
523 private static final class SupplierGetterMethodImplementation extends AbstractMethodImplementation {
524 private static final StackManipulation CODEC_MEMBER = invokeMethod(CodecDataObject.class,
525 "codecMember", AtomicReferenceFieldUpdater.class, NodeContextSupplier.class);
526 private static final StackManipulation BRIDGE_RESOLVE = invokeMethod(CodecDataObjectBridge.class,
527 "resolve", String.class);
528 private static final Generic BB_NCS = TypeDefinition.Sort.describe(NodeContextSupplier.class);
531 private final String contextName;
533 SupplierGetterMethodImplementation(final String methodName, final TypeDescription retType) {
534 super(methodName, retType);
535 contextName = methodName + "$$$C";
539 public InstrumentedType prepare(final InstrumentedType instrumentedType) {
540 final InstrumentedType tmp = super.prepare(instrumentedType)
541 // private static final NodeContextSupplier getFoo$$$C;
542 .withField(new FieldDescription.Token(contextName, PRIV_CONST, BB_NCS));
544 return tmp.withInitializer(new ByteCodeAppender.Simple(
545 // getFoo$$$C = CodecDataObjectBridge.resolve("getFoo");
546 new TextConstant(methodName),
548 putField(tmp, contextName)));
552 public ByteCodeAppender appender(final Target implementationTarget) {
553 final TypeDescription instrumentedType = implementationTarget.getInstrumentedType();
554 return new ByteCodeAppender.Simple(
555 // return (FooType) codecMember(getFoo$$$A, getFoo$$$C);
557 getField(instrumentedType, arfuName),
558 getField(instrumentedType, contextName),
560 TypeCasting.to(retType),
561 MethodReturn.REFERENCE);
565 private static final class CodecHashCode implements ByteCodeAppender {
566 private static final StackManipulation THIRTY_ONE = IntegerConstant.forValue(31);
567 private static final StackManipulation LOAD_RESULT = MethodVariableAccess.INTEGER.loadFrom(1);
568 private static final StackManipulation STORE_RESULT = MethodVariableAccess.INTEGER.storeAt(1);
569 private static final StackManipulation ARRAYS_HASHCODE = invokeMethod(Arrays.class, "hashCode", byte[].class);
570 private static final StackManipulation OBJECTS_HASHCODE = invokeMethod(Objects.class, "hashCode", Object.class);
572 private final ImmutableMap<StackManipulation, Method> properties;
574 CodecHashCode(final ImmutableMap<StackManipulation, Method> properties) {
575 this.properties = requireNonNull(properties);
579 public Size apply(final MethodVisitor methodVisitor, final Context implementationContext,
580 final MethodDescription instrumentedMethod) {
581 final List<StackManipulation> manipulations = new ArrayList<>(properties.size() * 8 + 4);
583 manipulations.add(IntegerConstant.ONE);
584 manipulations.add(STORE_RESULT);
586 for (Entry<StackManipulation, Method> entry : properties.entrySet()) {
587 // result = 31 * result + java.util.(Objects,Arrays).hashCode(getFoo());
588 manipulations.add(THIRTY_ONE);
589 manipulations.add(LOAD_RESULT);
590 manipulations.add(Multiplication.INTEGER);
591 manipulations.add(THIS);
592 manipulations.add(entry.getKey());
593 manipulations.add(entry.getValue().getReturnType().isArray() ? ARRAYS_HASHCODE : OBJECTS_HASHCODE);
594 manipulations.add(Addition.INTEGER);
595 manipulations.add(STORE_RESULT);
598 manipulations.add(LOAD_RESULT);
599 manipulations.add(MethodReturn.INTEGER);
601 StackManipulation.Size operandStackSize = new StackManipulation.Compound(manipulations)
602 .apply(methodVisitor, implementationContext);
603 return new Size(operandStackSize.getMaximalSize(), instrumentedMethod.getStackSize() + 1);