Do not inline NodeContextSuppliers
[mdsal.git] / binding / mdsal-binding-dom-codec / src / main / java / org / opendaylight / mdsal / binding / dom / codec / impl / CodecDataObjectGenerator.java
1 /*
2  * Copyright (c) 2019 PANTHEON.tech, s.r.o. and others.  All rights reserved.
3  *
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
7  */
8 package org.opendaylight.mdsal.binding.dom.codec.impl;
9
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;
17
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;
27 import java.util.Map;
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;
63
64 /**
65  * Private support for generating {@link CodecDataObject} and {@link AugmentableCodecDataObject} specializations.
66  *
67  * <p>
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.
72  *
73  * <p>
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.
77  *
78  * <p>
79  * The design is such that for a particular structure like:
80  * <pre>
81  *     container foo {
82  *         leaf bar {
83  *             type string;
84  *         }
85  *     }
86  * </pre>
87  * we end up generating a class with the following layout:
88  * <pre>
89  *     public final class Foo$$$codecImpl extends CodecDataObject implements Foo {
90  *         private static final AtomicRefereceFieldUpdater&lt;Foo$$$codecImpl, Object&gt; getBar$$$A;
91  *         private volatile Object getBar;
92  *
93  *         public Foo$$$codecImpl(NormalizedNodeContainer data) {
94  *             super(data);
95  *         }
96  *
97  *         public Bar getBar() {
98  *             return (Bar) codecMember(getBar$$$A, "bar");
99  *         }
100  *     }
101  * </pre>
102  *
103  * <p>
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
109  *
110  * <p>
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.
113  *
114  * <p>
115  * Furthermore there are distinct {@code codecMember} methods, each of which supports a different invocation style:
116  * <ul>
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>
120  * </ul>
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.
123  *
124  * <p>
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.
129  *
130  * <p>
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.
134  *
135  * <p>
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:
138  * <ul>
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>
150  * </ul>
151  *
152  * <p>
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.
155  */
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;
160
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);
165         }
166
167         @Override
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));
176             }
177             return tmp;
178         }
179
180         @Override
181         ArrayList<Method> getterMethods() {
182             return new ArrayList<>(properties.keySet());
183         }
184
185         @Override
186         public Class<T> customizeLoading(final @NonNull Supplier<Class<T>> loader) {
187             final Fixed<?> prev = CodecDataObjectBridge.setup(this);
188             try {
189                 final Class<T> result = loader.get();
190
191                 /*
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.
195                  *
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.
198                  */
199                 try {
200                     Class.forName(result.getName(), true, result.getClassLoader());
201                 } catch (ClassNotFoundException e) {
202                     throw new LinkageError("Failed to find newly-defined " + result, e);
203                 }
204
205                 return result;
206             } finally {
207                 CodecDataObjectBridge.tearDown(prev);
208             }
209         }
210
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());
216         }
217     }
218
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;
223
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);
230         }
231
232         @Override
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()));
243             }
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()));
251             }
252
253             return tmp;
254         }
255
256         @Override
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());
261             return ret;
262         }
263     }
264
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);
271
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);
278
279     private static final StackManipulation FIRST_ARG_REF = MethodVariableAccess.REFERENCE.loadFrom(1);
280
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;
283
284     private static final Builder<?> CDO;
285     private static final Builder<?> ACDO;
286
287     static {
288         final ByteBuddy bb = new ByteBuddy();
289         CDO = bb.subclass(CodecDataObject.class).visit(ByteBuddyUtils.computeFrames());
290         ACDO = bb.subclass(AugmentableCodecDataObject.class).visit(ByteBuddyUtils.computeFrames());
291     }
292
293     private final Builder<?> template;
294     private final Method keyMethod;
295
296     private CodecDataObjectGenerator(final Builder<?> template, final @Nullable Method keyMethod) {
297         this.template = requireNonNull(template);
298         this.keyMethod = keyMethod;
299     }
300
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));
306     }
307
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));
314     }
315
316     @Override
317     public final GeneratorResult<T> generateClass(final CodecClassLoader loeader, final String fqcn,
318             final Class<?> bindingInterface) {
319         LOG.trace("Generating class {}", fqcn);
320
321         @SuppressWarnings("unchecked")
322         Builder<T> builder = (Builder<T>) template.name(fqcn).implement(bindingInterface);
323
324         builder = generateGetters(builder);
325
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));
332         }
333
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);
342
343         // Final bits:
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))
354                 // ... and build it
355                 .make());
356     }
357
358     abstract Builder<T> generateGetters(Builder<T> builder);
359
360     abstract ArrayList<Method> getterMethods();
361
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);
367
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())) {
371             //     return false;
372             // }
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);
379         }
380
381         // return true;
382         manipulations.add(IntegerConstant.ONE);
383         manipulations.add(MethodReturn.INTEGER);
384         // L0: return false;
385         manipulations.add(ByteBuddyUtils.markLabel(falseLabel));
386         manipulations.add(IntegerConstant.ZERO);
387         manipulations.add(MethodReturn.INTEGER);
388
389         return new Implementation.Simple(manipulations.toArray(new StackManipulation[0]));
390     }
391
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);
402         }
403         // ... execute 'return helper'
404         manipulations.add(MethodReturn.REFERENCE);
405
406         return new Implementation.Simple(manipulations.toArray(new StackManipulation[0]));
407     }
408
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);
415
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;
419
420         final TypeDescription retType;
421         // getFoo
422         final String methodName;
423         // getFoo$$$A
424         final String arfuName;
425
426         AbstractMethodImplementation(final String methodName, final TypeDescription retType) {
427             this.methodName = requireNonNull(methodName);
428             this.retType = requireNonNull(retType);
429             this.arfuName = methodName + "$$$A";
430         }
431
432         @Override
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));
439
440             return tmp.withInitializer(new ByteCodeAppender.Simple(
441                 // getFoo$$$A = AtomicReferenceFieldUpdater.newUpdater(This.class, Object.class, "getFoo");
442                 ClassConstant.of(tmp),
443                 OBJECT_CLASS,
444                 new TextConstant(methodName),
445                 ARFU_NEWUPDATER,
446                 putField(tmp, arfuName)));
447         }
448     }
449
450     private static final class KeyMethodImplementation extends AbstractMethodImplementation {
451         private static final StackManipulation CODEC_KEY = invokeMethod(CodecDataObject.class,
452             "codecKey", AtomicReferenceFieldUpdater.class);
453
454         KeyMethodImplementation(final String methodName, final TypeDescription retType) {
455             super(methodName, retType);
456         }
457
458         @Override
459         public ByteCodeAppender appender(final Target implementationTarget) {
460             final TypeDescription instrumentedType = implementationTarget.getInstrumentedType();
461             return new ByteCodeAppender.Simple(
462                 // return (FooType) codecKey(getFoo$$$A);
463                 THIS,
464                 getField(instrumentedType, arfuName),
465                 CODEC_KEY,
466                 TypeCasting.to(retType),
467                 MethodReturn.REFERENCE);
468         }
469     }
470
471     private static final class SimpleGetterMethodImplementation extends AbstractMethodImplementation {
472         private static final StackManipulation CODEC_MEMBER = invokeMethod(CodecDataObject.class,
473             "codecMember", AtomicReferenceFieldUpdater.class, String.class);
474
475         private final String localName;
476
477         SimpleGetterMethodImplementation(final String methodName, final TypeDescription retType,
478                 final String localName) {
479             super(methodName, retType);
480             this.localName = requireNonNull(localName);
481         }
482
483         @Override
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");
488                 THIS,
489                 getField(instrumentedType, arfuName),
490                 new TextConstant(localName),
491                 CODEC_MEMBER,
492                 TypeCasting.to(retType),
493                 MethodReturn.REFERENCE);
494         }
495     }
496
497     private static final class StructuredGetterMethodImplementation extends AbstractMethodImplementation {
498         private static final StackManipulation CODEC_MEMBER = invokeMethod(CodecDataObject.class,
499             "codecMember", AtomicReferenceFieldUpdater.class, Class.class);
500
501         private final Class<?> bindingClass;
502
503         StructuredGetterMethodImplementation(final String methodName, final TypeDescription retType,
504                 final Class<?> bindingClass) {
505             super(methodName, retType);
506             this.bindingClass = requireNonNull(bindingClass);
507         }
508
509         @Override
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);
514                 THIS,
515                 getField(instrumentedType, arfuName),
516                 ClassConstant.of(TypeDefinition.Sort.describe(bindingClass).asErasure()),
517                 CODEC_MEMBER,
518                 TypeCasting.to(retType),
519                 MethodReturn.REFERENCE);
520         }
521     }
522
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);
529
530         // getFoo$$$C
531         private final String contextName;
532
533         SupplierGetterMethodImplementation(final String methodName, final TypeDescription retType) {
534             super(methodName, retType);
535             contextName = methodName + "$$$C";
536         }
537
538         @Override
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));
543
544             return tmp.withInitializer(new ByteCodeAppender.Simple(
545                 // getFoo$$$C = CodecDataObjectBridge.resolve("getFoo");
546                 new TextConstant(methodName),
547                 BRIDGE_RESOLVE,
548                 putField(tmp, contextName)));
549         }
550
551         @Override
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);
556                 THIS,
557                 getField(instrumentedType, arfuName),
558                 getField(instrumentedType, contextName),
559                 CODEC_MEMBER,
560                 TypeCasting.to(retType),
561                 MethodReturn.REFERENCE);
562         }
563     }
564
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);
571
572         private final ImmutableMap<StackManipulation, Method> properties;
573
574         CodecHashCode(final ImmutableMap<StackManipulation, Method> properties) {
575             this.properties = requireNonNull(properties);
576         }
577
578         @Override
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);
582             // int result = 1;
583             manipulations.add(IntegerConstant.ONE);
584             manipulations.add(STORE_RESULT);
585
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);
596             }
597             // return result;
598             manipulations.add(LOAD_RESULT);
599             manipulations.add(MethodReturn.INTEGER);
600
601             StackManipulation.Size operandStackSize = new StackManipulation.Compound(manipulations)
602                     .apply(methodVisitor, implementationContext);
603             return new Size(operandStackSize.getMaximalSize(), instrumentedMethod.getStackSize() + 1);
604         }
605     }
606 }