/*
 * Copyright (c) 2007 IBM Corporation.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     IBM Corporation - initial API and implementation
 */
package com.ibm.wala.ssa;

import com.ibm.wala.classLoader.CallSiteReference;
import com.ibm.wala.shrike.shrikeCT.BootstrapMethodsReader.BootstrapMethod;

/**
 * Used for representing the JVML invokedynamic instruction. When generated by the Java compiler for
 * compilation of Java lambdas / method references, the instruction components are:
 *
 * <ul>
 *   <li>the bootstrap method, which refers to {@link
 *       java.lang.invoke.LambdaMetafactory#metafactory(java.lang.invoke.MethodHandles.Lookup,
 *       String, java.lang.invoke.MethodType, java.lang.invoke.MethodType,
 *       java.lang.invoke.MethodHandle, java.lang.invoke.MethodType)},
 *   <li>the call site, which contains the static arguments passed to the bootstrap method (i.e.,
 *       the method signature for the corresponding functional interface method), and
 *   <li>the standard invoke instruction parameters, representing the dynamic arguments (captured
 *       local variables)
 * </ul>
 *
 * <p>The behavior of WALA for other uses of invokedynamic is currently unspecified (though it aims
 * to not crash for any valid use).
 */
public class SSAInvokeDynamicInstruction extends SSAInvokeInstruction {
  private final BootstrapMethod bootstrap;

  public SSAInvokeDynamicInstruction(
      int iindex,
      int result,
      int[] params,
      int exception,
      CallSiteReference site,
      BootstrapMethod bootstrap) {
    super(iindex, result, params, exception, site);
    this.bootstrap = bootstrap;
  }

  public SSAInvokeDynamicInstruction(
      int iindex, int[] params, int exception, CallSiteReference site, BootstrapMethod bootstrap) {
    super(iindex, params, exception, site);
    this.bootstrap = bootstrap;
  }

  @Override
  public SSAInstruction copyForSSA(SSAInstructionFactory insts, int[] defs, int[] uses) {
    return new SSAInvokeDynamicInstruction(
        iIndex(),
        defs == null || result == -1 ? result : defs[0],
        uses == null ? params : uses,
        defs == null ? exception : defs[result == -1 ? 0 : 1],
        site,
        bootstrap);
  }

  public BootstrapMethod getBootstrap() {
    return bootstrap;
  }

  /**
   * Mark the instruction as an invokedynamic. The String will also contain the invocation type of
   * the boostrap method
   *
   * @param symbolTable the symbol table
   * @return result of {@link SSAAbstractInvokeInstruction#toString(SymbolTable)} with
   *     "[invokedynamic] " pre-pended
   */
  @Override
  public String toString(SymbolTable symbolTable) {
    return "[invokedynamic] " + super.toString(symbolTable);
  }
}
