1 /*
   2  * Copyright (c) 2016, 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 org.graalvm.compiler.hotspot;
  24 
  25 import static jdk.vm.ci.common.InitTimer.timer;
  26 
  27 import java.util.ArrayList;
  28 import java.util.Collections;
  29 import java.util.IdentityHashMap;
  30 import java.util.List;
  31 import java.util.stream.Collectors;
  32 
  33 import org.graalvm.compiler.debug.GraalError;
  34 import org.graalvm.compiler.options.Option;
  35 import org.graalvm.compiler.options.OptionType;
  36 import org.graalvm.compiler.options.OptionValue;
  37 import org.graalvm.compiler.phases.tiers.CompilerConfiguration;
  38 import org.graalvm.compiler.serviceprovider.GraalServices;
  39 
  40 import jdk.vm.ci.code.Architecture;
  41 import jdk.vm.ci.common.InitTimer;
  42 
  43 /**
  44  * A factory that creates the {@link CompilerConfiguration} the Graal compiler will use. Each
  45  * factory must have a unique {@link #name} and {@link #autoSelectionPriority}. The latter imposes a
  46  * total ordering between factories for the purpose of auto-selecting the factory to use.
  47  */
  48 public abstract class CompilerConfigurationFactory implements Comparable<CompilerConfigurationFactory> {
  49 
  50     static class Options {
  51         // @formatter:off
  52         @Option(help = "Names the Graal compiler configuration to use. If ommitted, the compiler configuration " +
  53                        "with the highest auto-selection priority is used. To see the set of available configurations, " +
  54                        "supply the value 'help' to this option.", type = OptionType.Expert)
  55         public static final OptionValue<String> CompilerConfiguration = new OptionValue<>(null);
  56         // @formatter:on
  57     }
  58 
  59     /**
  60      * The name of this factory. This must be unique across all factory instances and is used when
  61      * selecting a factory based on the value of {@link Options#CompilerConfiguration}.
  62      */
  63     private final String name;
  64 
  65     /**
  66      * The priority of this factory. This must be unique across all factory instances and is used
  67      * when selecting a factory when {@link Options#CompilerConfiguration} is omitted
  68      */
  69     private final int autoSelectionPriority;
  70 
  71     protected CompilerConfigurationFactory(String name, int autoSelectionPriority) {
  72         this.name = name;
  73         this.autoSelectionPriority = autoSelectionPriority;
  74         assert checkAndAddNewFactory(this);
  75     }
  76 
  77     public abstract CompilerConfiguration createCompilerConfiguration();
  78 
  79     /**
  80      * Collect the set of available {@linkplain HotSpotBackendFactory backends} for this compiler
  81      * configuration.
  82      */
  83     public BackendMap createBackendMap() {
  84         // default to backend with the same name as the compiler configuration
  85         return new DefaultBackendMap(name);
  86     }
  87 
  88     public interface BackendMap {
  89         HotSpotBackendFactory getBackendFactory(Architecture arch);
  90     }
  91 
  92     public static class DefaultBackendMap implements BackendMap {
  93 
  94         private final IdentityHashMap<Class<? extends Architecture>, HotSpotBackendFactory> backends = new IdentityHashMap<>();
  95 
  96         @SuppressWarnings("try")
  97         public DefaultBackendMap(String backendName) {
  98             try (InitTimer t = timer("HotSpotBackendFactory.register")) {
  99                 for (HotSpotBackendFactory backend : GraalServices.load(HotSpotBackendFactory.class)) {
 100                     if (backend.getName().equals(backendName)) {
 101                         Class<? extends Architecture> arch = backend.getArchitecture();
 102                         HotSpotBackendFactory oldEntry = backends.put(arch, backend);
 103                         assert oldEntry == null || oldEntry == backend : "duplicate Graal backend";
 104                     }
 105                 }
 106             }
 107         }
 108 
 109         @Override
 110         public final HotSpotBackendFactory getBackendFactory(Architecture arch) {
 111             return backends.get(arch.getClass());
 112         }
 113     }
 114 
 115     @Override
 116     public int compareTo(CompilerConfigurationFactory o) {
 117         if (autoSelectionPriority > o.autoSelectionPriority) {
 118             return -1;
 119         }
 120         if (autoSelectionPriority < o.autoSelectionPriority) {
 121             return 1;
 122         }
 123         assert this == o : "distinct compiler configurations cannot have the same auto selection priority";
 124         return 0;
 125     }
 126 
 127     @SuppressWarnings("all")
 128     private static boolean assertionsEnabled() {
 129         boolean assertionsEnabled = false;
 130         assert assertionsEnabled = true;
 131         return assertionsEnabled;
 132     }
 133 
 134     /**
 135      * List used to assert uniqueness of {@link #name} and {@link #autoSelectionPriority} across all
 136      * {@link CompilerConfigurationFactory} instances.
 137      */
 138     private static final List<CompilerConfigurationFactory> factories = assertionsEnabled() ? new ArrayList<>() : null;
 139 
 140     private static boolean checkAndAddNewFactory(CompilerConfigurationFactory factory) {
 141         for (CompilerConfigurationFactory other : factories) {
 142             assert !other.name.equals(factory.name) : factory.getClass().getName() + " cannot have the same selector as " + other.getClass().getName() + ": " + factory.name;
 143             assert other.autoSelectionPriority != factory.autoSelectionPriority : factory.getClass().getName() + " cannot have the same auto-selection priority as " + other.getClass().getName() +
 144                             ": " + factory.autoSelectionPriority;
 145         }
 146         factories.add(factory);
 147         return true;
 148     }
 149 
 150     /**
 151      * @return sorted list of {@link CompilerConfigurationFactory}s
 152      */
 153     private static List<CompilerConfigurationFactory> getAllCandidates() {
 154         List<CompilerConfigurationFactory> candidates = new ArrayList<>();
 155         for (CompilerConfigurationFactory candidate : GraalServices.load(CompilerConfigurationFactory.class)) {
 156             candidates.add(candidate);
 157         }
 158         Collections.sort(candidates);
 159         return candidates;
 160     }
 161 
 162     /**
 163      * Selects and instantiates a {@link CompilerConfigurationFactory}. The selection algorithm is
 164      * as follows: if {@code name} is non-null, then select the factory with the same name else if
 165      * {@link Options#CompilerConfiguration}{@code .getValue()} is non-null then select the factory
 166      * whose name matches the value else select the factory with the highest
 167      * {@link #autoSelectionPriority} value.
 168      *
 169      * @param name the name of the compiler configuration to select (optional)
 170      */
 171     @SuppressWarnings("try")
 172     public static CompilerConfigurationFactory selectFactory(String name) {
 173         CompilerConfigurationFactory factory = null;
 174         try (InitTimer t = timer("CompilerConfigurationFactory.selectFactory")) {
 175             String value = name == null ? Options.CompilerConfiguration.getValue() : name;
 176             if ("help".equals(value)) {
 177                 System.out.println("The available Graal compiler configurations are:");
 178                 for (CompilerConfigurationFactory candidate : getAllCandidates()) {
 179                     System.out.println("    " + candidate.name);
 180                 }
 181                 System.exit(0);
 182             } else if (value != null) {
 183                 for (CompilerConfigurationFactory candidate : GraalServices.load(CompilerConfigurationFactory.class)) {
 184                     if (candidate.name.equals(value)) {
 185                         factory = candidate;
 186                         break;
 187                     }
 188                 }
 189                 if (factory == null) {
 190                     throw new GraalError("Graal compiler configuration '%s' not found. Available configurations are: %s", value,
 191                                     getAllCandidates().stream().map(c -> c.name).collect(Collectors.joining(", ")));
 192                 }
 193             } else {
 194                 List<CompilerConfigurationFactory> candidates = getAllCandidates();
 195                 if (candidates.isEmpty()) {
 196                     throw new GraalError("No %s providers found", CompilerConfigurationFactory.class.getName());
 197                 }
 198                 factory = candidates.get(0);
 199             }
 200         }
 201         return factory;
 202     }
 203 }