1 /*
   2  * Copyright (c) 2012, 2019, 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 
  24 
  25 package org.graalvm.compiler.hotspot.stubs;
  26 
  27 import static java.util.Collections.singletonList;
  28 import static org.graalvm.compiler.core.GraalCompiler.emitFrontEnd;
  29 import static org.graalvm.compiler.core.common.GraalOptions.GeneratePIC;
  30 import static org.graalvm.compiler.debug.DebugContext.DEFAULT_LOG_STREAM;
  31 import static org.graalvm.compiler.debug.DebugOptions.DebugStubsAndSnippets;
  32 import static org.graalvm.compiler.hotspot.HotSpotHostBackend.UNCOMMON_TRAP_HANDLER;
  33 import static org.graalvm.util.CollectionsUtil.allMatch;
  34 
  35 import java.util.ListIterator;
  36 import java.util.concurrent.atomic.AtomicInteger;
  37 
  38 import jdk.internal.vm.compiler.collections.EconomicSet;
  39 import org.graalvm.compiler.code.CompilationResult;
  40 import org.graalvm.compiler.core.common.CompilationIdentifier;
  41 import org.graalvm.compiler.core.common.GraalOptions;
  42 import org.graalvm.compiler.core.target.Backend;
  43 import org.graalvm.compiler.debug.DebugContext;
  44 import org.graalvm.compiler.debug.DebugContext.Description;
  45 import org.graalvm.compiler.hotspot.HotSpotCompiledCodeBuilder;
  46 import org.graalvm.compiler.hotspot.HotSpotForeignCallLinkage;
  47 import org.graalvm.compiler.hotspot.meta.HotSpotProviders;
  48 import org.graalvm.compiler.hotspot.nodes.StubStartNode;
  49 import org.graalvm.compiler.lir.asm.CompilationResultBuilderFactory;
  50 import org.graalvm.compiler.lir.phases.LIRPhase;
  51 import org.graalvm.compiler.lir.phases.LIRSuites;
  52 import org.graalvm.compiler.lir.phases.PostAllocationOptimizationPhase.PostAllocationOptimizationContext;
  53 import org.graalvm.compiler.lir.profiling.MoveProfilingPhase;
  54 import org.graalvm.compiler.nodes.StructuredGraph;
  55 import org.graalvm.compiler.options.OptionValues;
  56 import org.graalvm.compiler.phases.OptimisticOptimizations;
  57 import org.graalvm.compiler.phases.PhaseSuite;
  58 import org.graalvm.compiler.phases.tiers.Suites;
  59 import org.graalvm.compiler.printer.GraalDebugHandlersFactory;
  60 
  61 import jdk.vm.ci.code.CodeCacheProvider;
  62 import jdk.vm.ci.code.InstalledCode;
  63 import jdk.vm.ci.code.Register;
  64 import jdk.vm.ci.code.RegisterConfig;
  65 import jdk.vm.ci.code.site.Call;
  66 import jdk.vm.ci.code.site.ConstantReference;
  67 import jdk.vm.ci.code.site.DataPatch;
  68 import jdk.vm.ci.code.site.Infopoint;
  69 import jdk.vm.ci.hotspot.HotSpotCompiledCode;
  70 import jdk.vm.ci.hotspot.HotSpotMetaspaceConstant;
  71 import jdk.vm.ci.meta.DefaultProfilingInfo;
  72 import jdk.vm.ci.meta.ResolvedJavaMethod;
  73 import jdk.vm.ci.meta.TriState;
  74 
  75 //JaCoCo Exclude
  76 
  77 /**
  78  * Base class for implementing some low level code providing the out-of-line slow path for a snippet
  79  * and/or a callee saved call to a HotSpot C/C++ runtime function or even a another compiled Java
  80  * method.
  81  */
  82 public abstract class Stub {
  83 
  84     /**
  85      * The linkage information for a call to this stub from compiled code.
  86      */
  87     protected final HotSpotForeignCallLinkage linkage;
  88 
  89     /**
  90      * The code installed for the stub.
  91      */
  92     protected InstalledCode code;
  93 
  94     /**
  95      * The registers destroyed by this stub (from the caller's perspective).
  96      */
  97     private EconomicSet<Register> destroyedCallerRegisters;
  98 
  99     private static boolean checkRegisterSetEquivalency(EconomicSet<Register> a, EconomicSet<Register> b) {
 100         if (a == b) {
 101             return true;
 102         }
 103         if (a.size() != b.size()) {
 104             return false;
 105         }
 106         return allMatch(a, e -> b.contains(e));
 107     }
 108 
 109     public void initDestroyedCallerRegisters(EconomicSet<Register> registers) {
 110         assert registers != null;
 111         assert destroyedCallerRegisters == null || checkRegisterSetEquivalency(registers, destroyedCallerRegisters) : "cannot redefine";
 112         destroyedCallerRegisters = registers;
 113     }
 114 
 115     /**
 116      * Gets the registers destroyed by this stub from a caller's perspective. These are the
 117      * temporaries of this stub and must thus be caller saved by a callers of this stub.
 118      */
 119     public EconomicSet<Register> getDestroyedCallerRegisters() {
 120         assert destroyedCallerRegisters != null : "not yet initialized";
 121         return destroyedCallerRegisters;
 122     }
 123 
 124     public boolean shouldSaveRegistersAroundCalls() {
 125         return linkage.getEffect() == HotSpotForeignCallLinkage.RegisterEffect.COMPUTES_REGISTERS_KILLED;
 126     }
 127 
 128     protected final OptionValues options;
 129     protected final HotSpotProviders providers;
 130 
 131     /**
 132      * Creates a new stub.
 133      *
 134      * @param linkage linkage details for a call to the stub
 135      */
 136     public Stub(OptionValues options, HotSpotProviders providers, HotSpotForeignCallLinkage linkage) {
 137         this.linkage = linkage;
 138         this.options = new OptionValues(options, GraalOptions.TraceInlining, GraalOptions.TraceInliningForStubsAndSnippets.getValue(options));
 139         this.providers = providers;
 140     }
 141 
 142     /**
 143      * Gets the linkage for a call to this stub from compiled code.
 144      */
 145     public HotSpotForeignCallLinkage getLinkage() {
 146         return linkage;
 147     }
 148 
 149     public RegisterConfig getRegisterConfig() {
 150         return null;
 151     }
 152 
 153     /**
 154      * Gets the graph that from which the code for this stub will be compiled.
 155      *
 156      * @param compilationId unique compilation id for the stub
 157      */
 158     protected abstract StructuredGraph getGraph(DebugContext debug, CompilationIdentifier compilationId);
 159 
 160     @Override
 161     public String toString() {
 162         return "Stub<" + linkage.getDescriptor() + ">";
 163     }
 164 
 165     /**
 166      * Gets the method the stub's code will be associated with once installed. This may be null.
 167      */
 168     protected abstract ResolvedJavaMethod getInstalledCodeOwner();
 169 
 170     /**
 171      * Gets a context object for the debug scope created when producing the code for this stub.
 172      */
 173     protected abstract Object debugScopeContext();
 174 
 175     private static final AtomicInteger nextStubId = new AtomicInteger();
 176 
 177     private DebugContext openDebugContext(DebugContext outer) {
 178         if (DebugStubsAndSnippets.getValue(options)) {
 179             Description description = new Description(linkage, "Stub_" + nextStubId.incrementAndGet());
 180             return DebugContext.create(options, description, outer.getGlobalMetrics(), DEFAULT_LOG_STREAM, singletonList(new GraalDebugHandlersFactory(providers.getSnippetReflection())));
 181         }
 182         return DebugContext.disabled(options);
 183     }
 184 
 185     /**
 186      * Gets the code for this stub, compiling it first if necessary.
 187      */
 188     @SuppressWarnings("try")
 189     public synchronized InstalledCode getCode(final Backend backend) {
 190         if (code == null) {
 191             try (DebugContext debug = openDebugContext(DebugContext.forCurrentThread())) {
 192                 try (DebugContext.Scope d = debug.scope("CompilingStub", providers.getCodeCache(), debugScopeContext())) {
 193                     CodeCacheProvider codeCache = providers.getCodeCache();
 194                     CompilationResult compResult = buildCompilationResult(debug, backend);
 195                     try (DebugContext.Scope s = debug.scope("CodeInstall", compResult);
 196                                     DebugContext.Activation a = debug.activate()) {
 197                         assert destroyedCallerRegisters != null;
 198                         // Add a GeneratePIC check here later, we don't want to install
 199                         // code if we don't have a corresponding VM global symbol.
 200                         HotSpotCompiledCode compiledCode = HotSpotCompiledCodeBuilder.createCompiledCode(codeCache, null, null, compResult, options);
 201                         code = codeCache.installCode(null, compiledCode, null, null, false);
 202                     } catch (Throwable e) {
 203                         throw debug.handle(e);
 204                     }
 205                 } catch (Throwable e) {
 206                     throw debug.handle(e);
 207                 }
 208                 assert code != null : "error installing stub " + this;
 209             }
 210         }
 211 
 212         return code;
 213     }
 214 
 215     @SuppressWarnings("try")
 216     private CompilationResult buildCompilationResult(DebugContext debug, final Backend backend) {
 217         CompilationIdentifier compilationId = getStubCompilationId();
 218         final StructuredGraph graph = getGraph(debug, compilationId);
 219         CompilationResult compResult = new CompilationResult(compilationId, toString(), GeneratePIC.getValue(options));
 220 
 221         // Stubs cannot be recompiled so they cannot be compiled with assumptions
 222         assert graph.getAssumptions() == null;
 223 
 224         if (!(graph.start() instanceof StubStartNode)) {
 225             StubStartNode newStart = graph.add(new StubStartNode(Stub.this));
 226             newStart.setStateAfter(graph.start().stateAfter());
 227             graph.replaceFixed(graph.start(), newStart);
 228         }
 229 
 230         try (DebugContext.Scope s0 = debug.scope("StubCompilation", graph, providers.getCodeCache())) {
 231             Suites suites = createSuites();
 232             emitFrontEnd(providers, backend, graph, providers.getSuites().getDefaultGraphBuilderSuite(), OptimisticOptimizations.ALL, DefaultProfilingInfo.get(TriState.UNKNOWN), suites);
 233             LIRSuites lirSuites = createLIRSuites();
 234             backend.emitBackEnd(graph, Stub.this, getInstalledCodeOwner(), compResult, CompilationResultBuilderFactory.Default, getRegisterConfig(), lirSuites);
 235             assert checkStubInvariants(compResult);
 236         } catch (Throwable e) {
 237             throw debug.handle(e);
 238         }
 239         return compResult;
 240     }
 241 
 242     /**
 243      * Gets a {@link CompilationResult} that can be used for code generation. Required for AOT.
 244      */
 245     @SuppressWarnings("try")
 246     public CompilationResult getCompilationResult(DebugContext debug, final Backend backend) {
 247         try (DebugContext.Scope d = debug.scope("CompilingStub", providers.getCodeCache(), debugScopeContext())) {
 248             return buildCompilationResult(debug, backend);
 249         } catch (Throwable e) {
 250             throw debug.handle(e);
 251         }
 252     }
 253 
 254     public CompilationIdentifier getStubCompilationId() {
 255         return new StubCompilationIdentifier(this);
 256     }
 257 
 258     /**
 259      * Checks the conditions a compilation must satisfy to be installed as a RuntimeStub.
 260      */
 261     private boolean checkStubInvariants(CompilationResult compResult) {
 262         assert compResult.getExceptionHandlers().isEmpty() : this;
 263 
 264         // Stubs cannot be recompiled so they cannot be compiled with
 265         // assumptions and there is no point in recording evol_method dependencies
 266         assert compResult.getAssumptions() == null : "stubs should not use assumptions: " + this;
 267 
 268         for (DataPatch data : compResult.getDataPatches()) {
 269             if (data.reference instanceof ConstantReference) {
 270                 ConstantReference ref = (ConstantReference) data.reference;
 271                 if (ref.getConstant() instanceof HotSpotMetaspaceConstant) {
 272                     HotSpotMetaspaceConstant c = (HotSpotMetaspaceConstant) ref.getConstant();
 273                     if (c.asResolvedJavaType() != null && c.asResolvedJavaType().getName().equals("[I")) {
 274                         // special handling for NewArrayStub
 275                         // embedding the type '[I' is safe, since it is never unloaded
 276                         continue;
 277                     }
 278                 }
 279             }
 280 
 281             assert !(data.reference instanceof ConstantReference) : this + " cannot have embedded object or metadata constant: " + data.reference;
 282         }
 283         for (Infopoint infopoint : compResult.getInfopoints()) {
 284             assert infopoint instanceof Call : this + " cannot have non-call infopoint: " + infopoint;
 285             Call call = (Call) infopoint;
 286             assert call.target instanceof HotSpotForeignCallLinkage : this + " cannot have non runtime call: " + call.target;
 287             HotSpotForeignCallLinkage callLinkage = (HotSpotForeignCallLinkage) call.target;
 288             assert !callLinkage.isCompiledStub() || callLinkage.getDescriptor().equals(UNCOMMON_TRAP_HANDLER) : this + " cannot call compiled stub " + callLinkage;
 289         }
 290         return true;
 291     }
 292 
 293     protected Suites createSuites() {
 294         Suites defaultSuites = providers.getSuites().getDefaultSuites(options);
 295         return new Suites(new PhaseSuite<>(), defaultSuites.getMidTier(), defaultSuites.getLowTier());
 296     }
 297 
 298     protected LIRSuites createLIRSuites() {
 299         LIRSuites lirSuites = new LIRSuites(providers.getSuites().getDefaultLIRSuites(options));
 300         ListIterator<LIRPhase<PostAllocationOptimizationContext>> moveProfiling = lirSuites.getPostAllocationOptimizationStage().findPhase(MoveProfilingPhase.class);
 301         if (moveProfiling != null) {
 302             moveProfiling.remove();
 303         }
 304         return lirSuites;
 305     }
 306 }