1 /*
   2  * Copyright (c) 2012, 2018, 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     /**
 125      * Determines if this stub preserves all registers apart from those it
 126      * {@linkplain #getDestroyedCallerRegisters() destroys}.
 127      */
 128     public boolean preservesRegisters() {
 129         return true;
 130     }
 131 
 132     protected final OptionValues options;
 133     protected final HotSpotProviders providers;
 134 
 135     /**
 136      * Creates a new stub.
 137      *
 138      * @param linkage linkage details for a call to the stub
 139      */
 140     public Stub(OptionValues options, HotSpotProviders providers, HotSpotForeignCallLinkage linkage) {
 141         this.linkage = linkage;
 142         this.options = new OptionValues(options, GraalOptions.TraceInlining, GraalOptions.TraceInliningForStubsAndSnippets.getValue(options));
 143         this.providers = providers;
 144     }
 145 
 146     /**
 147      * Gets the linkage for a call to this stub from compiled code.
 148      */
 149     public HotSpotForeignCallLinkage getLinkage() {
 150         return linkage;
 151     }
 152 
 153     public RegisterConfig getRegisterConfig() {
 154         return null;
 155     }
 156 
 157     /**
 158      * Gets the graph that from which the code for this stub will be compiled.
 159      *
 160      * @param compilationId unique compilation id for the stub
 161      */
 162     protected abstract StructuredGraph getGraph(DebugContext debug, CompilationIdentifier compilationId);
 163 
 164     @Override
 165     public String toString() {
 166         return "Stub<" + linkage.getDescriptor() + ">";
 167     }
 168 
 169     /**
 170      * Gets the method the stub's code will be associated with once installed. This may be null.
 171      */
 172     protected abstract ResolvedJavaMethod getInstalledCodeOwner();
 173 
 174     /**
 175      * Gets a context object for the debug scope created when producing the code for this stub.
 176      */
 177     protected abstract Object debugScopeContext();
 178 
 179     private static final AtomicInteger nextStubId = new AtomicInteger();
 180 
 181     private DebugContext openDebugContext(DebugContext outer) {
 182         if (DebugStubsAndSnippets.getValue(options)) {
 183             Description description = new Description(linkage, "Stub_" + nextStubId.incrementAndGet());
 184             return DebugContext.create(options, description, outer.getGlobalMetrics(), DEFAULT_LOG_STREAM, singletonList(new GraalDebugHandlersFactory(providers.getSnippetReflection())));
 185         }
 186         return DebugContext.DISABLED;
 187     }
 188 
 189     /**
 190      * Gets the code for this stub, compiling it first if necessary.
 191      */
 192     @SuppressWarnings("try")
 193     public synchronized InstalledCode getCode(final Backend backend) {
 194         if (code == null) {
 195             try (DebugContext debug = openDebugContext(DebugContext.forCurrentThread())) {
 196                 try (DebugContext.Scope d = debug.scope("CompilingStub", providers.getCodeCache(), debugScopeContext())) {
 197                     CodeCacheProvider codeCache = providers.getCodeCache();
 198                     CompilationResult compResult = buildCompilationResult(debug, backend);
 199                     try (DebugContext.Scope s = debug.scope("CodeInstall", compResult);
 200                                     DebugContext.Activation a = debug.activate()) {
 201                         assert destroyedCallerRegisters != null;
 202                         // Add a GeneratePIC check here later, we don't want to install
 203                         // code if we don't have a corresponding VM global symbol.
 204                         HotSpotCompiledCode compiledCode = HotSpotCompiledCodeBuilder.createCompiledCode(codeCache, null, null, compResult, options);
 205                         code = codeCache.installCode(null, compiledCode, null, null, false);
 206                     } catch (Throwable e) {
 207                         throw debug.handle(e);
 208                     }
 209                 } catch (Throwable e) {
 210                     throw debug.handle(e);
 211                 }
 212                 assert code != null : "error installing stub " + this;
 213             }
 214         }
 215 
 216         return code;
 217     }
 218 
 219     @SuppressWarnings("try")
 220     private CompilationResult buildCompilationResult(DebugContext debug, final Backend backend) {
 221         CompilationIdentifier compilationId = getStubCompilationId();
 222         final StructuredGraph graph = getGraph(debug, compilationId);
 223         CompilationResult compResult = new CompilationResult(compilationId, toString(), GeneratePIC.getValue(options));
 224 
 225         // Stubs cannot be recompiled so they cannot be compiled with assumptions
 226         assert graph.getAssumptions() == null;
 227 
 228         if (!(graph.start() instanceof StubStartNode)) {
 229             StubStartNode newStart = graph.add(new StubStartNode(Stub.this));
 230             newStart.setStateAfter(graph.start().stateAfter());
 231             graph.replaceFixed(graph.start(), newStart);
 232         }
 233 
 234         try (DebugContext.Scope s0 = debug.scope("StubCompilation", graph, providers.getCodeCache())) {
 235             Suites suites = createSuites();
 236             emitFrontEnd(providers, backend, graph, providers.getSuites().getDefaultGraphBuilderSuite(), OptimisticOptimizations.ALL, DefaultProfilingInfo.get(TriState.UNKNOWN), suites);
 237             LIRSuites lirSuites = createLIRSuites();
 238             backend.emitBackEnd(graph, Stub.this, getInstalledCodeOwner(), compResult, CompilationResultBuilderFactory.Default, getRegisterConfig(), lirSuites);
 239             assert checkStubInvariants(compResult);
 240         } catch (Throwable e) {
 241             throw debug.handle(e);
 242         }
 243         return compResult;
 244     }
 245 
 246     /**
 247      * Gets a {@link CompilationResult} that can be used for code generation. Required for AOT.
 248      */
 249     @SuppressWarnings("try")
 250     public CompilationResult getCompilationResult(DebugContext debug, final Backend backend) {
 251         try (DebugContext.Scope d = debug.scope("CompilingStub", providers.getCodeCache(), debugScopeContext())) {
 252             return buildCompilationResult(debug, backend);
 253         } catch (Throwable e) {
 254             throw debug.handle(e);
 255         }
 256     }
 257 
 258     public CompilationIdentifier getStubCompilationId() {
 259         return new StubCompilationIdentifier(this);
 260     }
 261 
 262     /**
 263      * Checks the conditions a compilation must satisfy to be installed as a RuntimeStub.
 264      */
 265     private boolean checkStubInvariants(CompilationResult compResult) {
 266         assert compResult.getExceptionHandlers().isEmpty() : this;
 267 
 268         // Stubs cannot be recompiled so they cannot be compiled with
 269         // assumptions and there is no point in recording evol_method dependencies
 270         assert compResult.getAssumptions() == null : "stubs should not use assumptions: " + this;
 271 
 272         for (DataPatch data : compResult.getDataPatches()) {
 273             if (data.reference instanceof ConstantReference) {
 274                 ConstantReference ref = (ConstantReference) data.reference;
 275                 if (ref.getConstant() instanceof HotSpotMetaspaceConstant) {
 276                     HotSpotMetaspaceConstant c = (HotSpotMetaspaceConstant) ref.getConstant();
 277                     if (c.asResolvedJavaType() != null && c.asResolvedJavaType().getName().equals("[I")) {
 278                         // special handling for NewArrayStub
 279                         // embedding the type '[I' is safe, since it is never unloaded
 280                         continue;
 281                     }
 282                 }
 283             }
 284 
 285             assert !(data.reference instanceof ConstantReference) : this + " cannot have embedded object or metadata constant: " + data.reference;
 286         }
 287         for (Infopoint infopoint : compResult.getInfopoints()) {
 288             assert infopoint instanceof Call : this + " cannot have non-call infopoint: " + infopoint;
 289             Call call = (Call) infopoint;
 290             assert call.target instanceof HotSpotForeignCallLinkage : this + " cannot have non runtime call: " + call.target;
 291             HotSpotForeignCallLinkage callLinkage = (HotSpotForeignCallLinkage) call.target;
 292             assert !callLinkage.isCompiledStub() || callLinkage.getDescriptor().equals(UNCOMMON_TRAP_HANDLER) : this + " cannot call compiled stub " + callLinkage;
 293         }
 294         return true;
 295     }
 296 
 297     protected Suites createSuites() {
 298         Suites defaultSuites = providers.getSuites().getDefaultSuites(options);
 299         return new Suites(new PhaseSuite<>(), defaultSuites.getMidTier(), defaultSuites.getLowTier());
 300     }
 301 
 302     protected LIRSuites createLIRSuites() {
 303         LIRSuites lirSuites = new LIRSuites(providers.getSuites().getDefaultLIRSuites(options));
 304         ListIterator<LIRPhase<PostAllocationOptimizationContext>> moveProfiling = lirSuites.getPostAllocationOptimizationStage().findPhase(MoveProfilingPhase.class);
 305         if (moveProfiling != null) {
 306             moveProfiling.remove();
 307         }
 308         return lirSuites;
 309     }
 310 }
--- EOF ---