1 /*
   2  * Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  */
  23 package com.oracle.graal.hotspot.meta;
  24 
  25 import static com.oracle.graal.api.meta.MetaUtil.*;
  26 import static com.oracle.graal.graph.FieldIntrospection.*;
  27 import static com.oracle.graal.hotspot.HotSpotGraalRuntime.*;
  28 
  29 import java.lang.annotation.*;
  30 import java.lang.reflect.*;
  31 import java.util.*;
  32 import java.util.concurrent.*;
  33 
  34 import com.oracle.graal.api.code.*;
  35 import com.oracle.graal.api.meta.*;
  36 import com.oracle.graal.api.meta.ProfilingInfo.TriState;
  37 import com.oracle.graal.bytecode.*;
  38 import com.oracle.graal.hotspot.*;
  39 import com.oracle.graal.hotspot.debug.*;
  40 import com.oracle.graal.phases.*;
  41 
  42 /**
  43  * Implementation of {@link JavaMethod} for resolved HotSpot methods.
  44  */
  45 public final class HotSpotResolvedJavaMethod extends HotSpotMethod implements ResolvedJavaMethod {
  46 
  47     private static final long serialVersionUID = -5486975070147586588L;
  48 
  49     /**
  50      * Reference to metaspace Method object.
  51      */
  52     final long metaspaceMethod;
  53 
  54     private final HotSpotResolvedObjectType holder;
  55     private/* final */int codeSize;
  56     private/* final */int exceptionHandlerCount;
  57     private boolean callerSensitive;
  58     private boolean forceInline;
  59     private boolean dontInline;
  60     private boolean ignoredBySecurityStackWalk;
  61     private HotSpotSignature signature;
  62     private Boolean hasBalancedMonitors;
  63     private Map<Object, Object> compilerStorage;
  64     private HotSpotMethodData methodData;
  65     private byte[] code;
  66     private int compilationComplexity;
  67     private CompilationTask currentTask;
  68     private SpeculationLog speculationLog;
  69 
  70     HotSpotResolvedJavaMethod(HotSpotResolvedObjectType holder, long metaspaceMethod) {
  71         this.metaspaceMethod = metaspaceMethod;
  72         this.holder = holder;
  73         HotSpotGraalRuntime.getInstance().getCompilerToVM().initializeMethod(metaspaceMethod, this);
  74     }
  75 
  76     @Override
  77     public ResolvedJavaType getDeclaringClass() {
  78         return holder;
  79     }
  80 
  81     public long getMetaspaceMethod() {
  82         return metaspaceMethod;
  83     }
  84 
  85     /**
  86      * Gets the address of the C++ Method object for this method.
  87      */
  88     public Constant getMetaspaceMethodConstant() {
  89         return Constant.forIntegerKind(HotSpotGraalRuntime.getInstance().getTarget().wordKind, metaspaceMethod, this);
  90     }
  91 
  92     @Override
  93     public int getModifiers() {
  94         HotSpotVMConfig config = HotSpotGraalRuntime.getInstance().getConfig();
  95         return unsafe.getInt(metaspaceMethod + config.methodAccessFlagsOffset) & Modifier.methodModifiers();
  96     }
  97 
  98     @Override
  99     public boolean canBeStaticallyBound() {
 100         int modifiers = getModifiers();
 101         return (Modifier.isFinal(modifiers) || Modifier.isPrivate(modifiers) || Modifier.isStatic(modifiers)) && !Modifier.isAbstract(modifiers);
 102     }
 103 
 104     @Override
 105     public byte[] getCode() {
 106         if (codeSize == 0) {
 107             return null;
 108         }
 109         if (code == null) {
 110             code = HotSpotGraalRuntime.getInstance().getCompilerToVM().initializeBytecode(metaspaceMethod, new byte[codeSize]);
 111             assert code.length == codeSize : "expected: " + codeSize + ", actual: " + code.length;
 112         }
 113         return code;
 114     }
 115 
 116     @Override
 117     public int getCodeSize() {
 118         return codeSize;
 119     }
 120 
 121     @Override
 122     public ExceptionHandler[] getExceptionHandlers() {
 123         if (exceptionHandlerCount == 0) {
 124             return new ExceptionHandler[0];
 125         }
 126         ExceptionHandler[] handlers = new ExceptionHandler[exceptionHandlerCount];
 127         for (int i = 0; i < exceptionHandlerCount; i++) {
 128             handlers[i] = new ExceptionHandler(-1, -1, -1, -1, null);
 129         }
 130         return HotSpotGraalRuntime.getInstance().getCompilerToVM().initializeExceptionHandlers(metaspaceMethod, handlers);
 131     }
 132 
 133     /**
 134      * Returns true if this method has a CallerSensitive annotation.
 135      * 
 136      * @return true if CallerSensitive annotation present, false otherwise
 137      */
 138     public boolean isCallerSensitive() {
 139         return callerSensitive;
 140     }
 141 
 142     /**
 143      * Returns true if this method has a ForceInline annotation.
 144      * 
 145      * @return true if ForceInline annotation present, false otherwise
 146      */
 147     public boolean isForceInline() {
 148         return forceInline;
 149     }
 150 
 151     /**
 152      * Returns true if this method has a DontInline annotation.
 153      * 
 154      * @return true if DontInline annotation present, false otherwise
 155      */
 156     public boolean isDontInline() {
 157         return dontInline;
 158     }
 159 
 160     /**
 161      * Returns true if this method is one of the special methods that is ignored by security stack
 162      * walks.
 163      * 
 164      * @return true if special method ignored by security stack walks, false otherwise
 165      */
 166     public boolean ignoredBySecurityStackWalk() {
 167         return ignoredBySecurityStackWalk;
 168     }
 169 
 170     public boolean hasBalancedMonitors() {
 171         if (hasBalancedMonitors == null) {
 172             hasBalancedMonitors = HotSpotGraalRuntime.getInstance().getCompilerToVM().hasBalancedMonitors(metaspaceMethod);
 173         }
 174         return hasBalancedMonitors;
 175     }
 176 
 177     @Override
 178     public boolean isClassInitializer() {
 179         return "<clinit>".equals(name) && Modifier.isStatic(getModifiers());
 180     }
 181 
 182     @Override
 183     public boolean isConstructor() {
 184         return "<init>".equals(name) && !Modifier.isStatic(getModifiers());
 185     }
 186 
 187     @Override
 188     public int getMaxLocals() {
 189         HotSpotVMConfig config = HotSpotGraalRuntime.getInstance().getConfig();
 190         long metaspaceConstMethod = unsafe.getLong(metaspaceMethod + config.methodConstMethodOffset);
 191         return unsafe.getShort(metaspaceConstMethod + config.methodMaxLocalsOffset) & 0xFFFF;
 192     }
 193 
 194     @Override
 195     public int getMaxStackSize() {
 196         HotSpotVMConfig config = HotSpotGraalRuntime.getInstance().getConfig();
 197         long metaspaceConstMethod = unsafe.getLong(metaspaceMethod + config.methodConstMethodOffset);
 198         return config.extraStackEntries + (unsafe.getShort(metaspaceConstMethod + config.constMethodMaxStackOffset) & 0xFFFF);
 199     }
 200 
 201     @Override
 202     public StackTraceElement asStackTraceElement(int bci) {
 203         if (bci < 0 || bci >= codeSize) {
 204             // HotSpot code can only construct stack trace elements for valid bcis
 205             StackTraceElement ste = HotSpotGraalRuntime.getInstance().getCompilerToVM().getStackTraceElement(metaspaceMethod, 0);
 206             return new StackTraceElement(ste.getClassName(), ste.getMethodName(), ste.getFileName(), -1);
 207         }
 208         return HotSpotGraalRuntime.getInstance().getCompilerToVM().getStackTraceElement(metaspaceMethod, bci);
 209     }
 210 
 211     public ResolvedJavaMethod uniqueConcreteMethod() {
 212         HotSpotResolvedObjectType[] resultHolder = {null};
 213         long ucm = HotSpotGraalRuntime.getInstance().getCompilerToVM().getUniqueConcreteMethod(metaspaceMethod, resultHolder);
 214         if (ucm != 0L) {
 215             assert resultHolder[0] != null;
 216             return resultHolder[0].createMethod(ucm);
 217         }
 218         return null;
 219     }
 220 
 221     @Override
 222     public HotSpotSignature getSignature() {
 223         if (signature == null) {
 224             signature = new HotSpotSignature(HotSpotGraalRuntime.getInstance().getCompilerToVM().getSignature(metaspaceMethod));
 225         }
 226         return signature;
 227     }
 228 
 229     @Override
 230     public String toString() {
 231         return format("HotSpotMethod<%H.%n(%p)>", this);
 232     }
 233 
 234     public int getCompiledCodeSize() {
 235         return HotSpotGraalRuntime.getInstance().getCompilerToVM().getCompiledCodeSize(metaspaceMethod);
 236     }
 237 
 238     public int invocationCount() {
 239         return HotSpotGraalRuntime.getInstance().getCompilerToVM().getInvocationCount(metaspaceMethod);
 240     }
 241 
 242     @Override
 243     public int getCompilationComplexity() {
 244         if (compilationComplexity <= 0 && getCodeSize() > 0) {
 245             BytecodeStream s = new BytecodeStream(getCode());
 246             int result = 0;
 247             int currentBC;
 248             while ((currentBC = s.currentBC()) != Bytecodes.END) {
 249                 result += Bytecodes.compilationComplexity(currentBC);
 250                 s.next();
 251             }
 252             assert result > 0;
 253             compilationComplexity = result;
 254         }
 255         return compilationComplexity;
 256     }
 257 
 258     @Override
 259     public ProfilingInfo getProfilingInfo() {
 260         ProfilingInfo info;
 261 
 262         if (GraalOptions.UseProfilingInformation && methodData == null) {
 263             long metaspaceMethodData = unsafeReadWord(metaspaceMethod + HotSpotGraalRuntime.getInstance().getConfig().methodDataOffset);
 264             if (metaspaceMethodData != 0) {
 265                 methodData = new HotSpotMethodData(metaspaceMethodData);
 266             }
 267         }
 268 
 269         if (methodData == null || (!methodData.hasNormalData() && !methodData.hasExtraData())) {
 270             // Be optimistic and return false for exceptionSeen. A methodDataOop is allocated in
 271             // case of a deoptimization.
 272             info = DefaultProfilingInfo.get(TriState.FALSE);
 273         } else {
 274             info = new HotSpotProfilingInfo(methodData, codeSize);
 275         }
 276         return info;
 277     }
 278 
 279     @Override
 280     public void reprofile() {
 281         HotSpotGraalRuntime.getInstance().getCompilerToVM().reprofile(metaspaceMethod);
 282     }
 283 
 284     @Override
 285     public Map<Object, Object> getCompilerStorage() {
 286         if (compilerStorage == null) {
 287             compilerStorage = new ConcurrentHashMap<>();
 288         }
 289         return compilerStorage;
 290     }
 291 
 292     @Override
 293     public ConstantPool getConstantPool() {
 294         return ((HotSpotResolvedObjectType) getDeclaringClass()).constantPool();
 295     }
 296 
 297     @Override
 298     public Annotation[][] getParameterAnnotations() {
 299         if (isConstructor()) {
 300             Constructor javaConstructor = toJavaConstructor();
 301             return javaConstructor == null ? null : javaConstructor.getParameterAnnotations();
 302         }
 303         Method javaMethod = toJava();
 304         return javaMethod == null ? null : javaMethod.getParameterAnnotations();
 305     }
 306 
 307     @Override
 308     public <T extends Annotation> T getAnnotation(Class<T> annotationClass) {
 309         if (isConstructor()) {
 310             Constructor<?> javaConstructor = toJavaConstructor();
 311             return javaConstructor == null ? null : javaConstructor.getAnnotation(annotationClass);
 312         }
 313         Method javaMethod = toJava();
 314         return javaMethod == null ? null : javaMethod.getAnnotation(annotationClass);
 315     }
 316 
 317     @Override
 318     public Type[] getGenericParameterTypes() {
 319         if (isConstructor()) {
 320             Constructor javaConstructor = toJavaConstructor();
 321             return javaConstructor == null ? null : javaConstructor.getGenericParameterTypes();
 322         }
 323         Method javaMethod = toJava();
 324         return javaMethod == null ? null : javaMethod.getGenericParameterTypes();
 325     }
 326 
 327     public Class<?>[] signatureToTypes() {
 328         Signature sig = getSignature();
 329         int count = sig.getParameterCount(false);
 330         Class<?>[] result = new Class<?>[count];
 331         for (int i = 0; i < result.length; ++i) {
 332             result[i] = ((HotSpotResolvedJavaType) sig.getParameterType(i, holder).resolve(holder)).mirror();
 333         }
 334         return result;
 335     }
 336 
 337     private Method toJava() {
 338         try {
 339             return holder.mirror().getDeclaredMethod(name, signatureToTypes());
 340         } catch (NoSuchMethodException e) {
 341             return null;
 342         }
 343     }
 344 
 345     private Constructor toJavaConstructor() {
 346         try {
 347             return holder.mirror().getDeclaredConstructor(signatureToTypes());
 348         } catch (NoSuchMethodException e) {
 349             return null;
 350         }
 351     }
 352 
 353     @Override
 354     public boolean canBeInlined() {
 355         return HotSpotGraalRuntime.getInstance().getCompilerToVM().isMethodCompilable(metaspaceMethod);
 356     }
 357 
 358     @Override
 359     public LineNumberTable getLineNumberTable() {
 360         long[] values = HotSpotGraalRuntime.getInstance().getCompilerToVM().getLineNumberTable(this);
 361         assert values.length % 2 == 0;
 362         int[] bci = new int[values.length / 2];
 363         int[] line = new int[values.length / 2];
 364 
 365         for (int i = 0; i < values.length / 2; i++) {
 366             bci[i] = (int) values[i * 2];
 367             line[i] = (int) values[i * 2 + 1];
 368         }
 369 
 370         return new LineNumberTableImpl(line, bci);
 371     }
 372 
 373     @Override
 374     public LocalVariableTable getLocalVariableTable() {
 375         Local[] locals = HotSpotGraalRuntime.getInstance().getCompilerToVM().getLocalVariableTable(this);
 376         return new LocalVariableTableImpl(locals);
 377     }
 378 
 379     /**
 380      * Returns the offset of this method into the v-table. If the holder is not initialized, returns
 381      * -1
 382      * 
 383      * @return the offset of this method into the v-table
 384      */
 385     public int vtableEntryOffset() {
 386         if (!holder.isInitialized()) {
 387             return -1;
 388         }
 389         return HotSpotGraalRuntime.getInstance().getCompilerToVM().getVtableEntryOffset(metaspaceMethod);
 390     }
 391 
 392     public void setCurrentTask(CompilationTask task) {
 393         currentTask = task;
 394     }
 395 
 396     public CompilationTask currentTask() {
 397         return currentTask;
 398     }
 399 
 400     public SpeculationLog getSpeculationLog() {
 401         if (speculationLog == null) {
 402             speculationLog = new SpeculationLog();
 403         }
 404         return speculationLog;
 405     }
 406 
 407     public int intrinsicId() {
 408         HotSpotVMConfig config = HotSpotGraalRuntime.getInstance().getConfig();
 409         return unsafe.getByte(metaspaceMethod + config.methodIntrinsicIdOffset) & 0xff;
 410     }
 411 
 412     @Override
 413     public Constant invoke(Constant receiver, Constant[] arguments) {
 414         assert !isConstructor();
 415         Method javaMethod = toJava();
 416         javaMethod.setAccessible(true);
 417 
 418         Object[] objArguments = new Object[arguments.length];
 419         for (int i = 0; i < arguments.length; i++) {
 420             objArguments[i] = arguments[i].asBoxedValue();
 421         }
 422         Object objReceiver = receiver != null ? receiver.asObject() : null;
 423 
 424         try {
 425             Object objResult = javaMethod.invoke(objReceiver, objArguments);
 426             return javaMethod.getReturnType() == void.class ? null : Constant.forBoxed(getSignature().getReturnKind(), objResult);
 427 
 428         } catch (IllegalAccessException | InvocationTargetException ex) {
 429             throw new IllegalArgumentException(ex);
 430         }
 431     }
 432 
 433     @Override
 434     public Constant newInstance(Constant[] arguments) {
 435         assert isConstructor();
 436         Constructor javaConstructor = toJavaConstructor();
 437         javaConstructor.setAccessible(true);
 438 
 439         Object[] objArguments = new Object[arguments.length];
 440         for (int i = 0; i < arguments.length; i++) {
 441             objArguments[i] = arguments[i].asBoxedValue();
 442         }
 443 
 444         try {
 445             Object objResult = javaConstructor.newInstance(objArguments);
 446             assert objResult != null;
 447             return Constant.forObject(objResult);
 448 
 449         } catch (IllegalAccessException | InvocationTargetException | InstantiationException ex) {
 450             throw new IllegalArgumentException(ex);
 451         }
 452     }
 453 }