1 /*
   2  * Copyright (c) 1998, 2024, 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 #include "precompiled.hpp"
  26 #include "classfile/symbolTable.hpp"
  27 #include "compiler/compilerDirectives.hpp"
  28 #include "compiler/compilerOracle.hpp"
  29 #include "compiler/methodMatcher.hpp"
  30 #include "jvm.h"
  31 #include "memory/allocation.inline.hpp"
  32 #include "memory/oopFactory.hpp"
  33 #include "memory/resourceArea.hpp"
  34 #include "oops/klass.hpp"
  35 #include "oops/method.inline.hpp"
  36 #include "oops/symbol.hpp"
  37 #include "opto/phasetype.hpp"
  38 #include "opto/traceAutoVectorizationTag.hpp"
  39 #include "runtime/globals_extension.hpp"
  40 #include "runtime/handles.inline.hpp"
  41 #include "runtime/jniHandles.hpp"
  42 #include "runtime/os.hpp"
  43 #include "utilities/parseInteger.hpp"
  44 
  45 static const char* optiontype_names[] = {
  46 #define enum_of_types(type, name) name,
  47         OPTION_TYPES(enum_of_types)
  48 #undef enum_of_types
  49 };
  50 
  51 const char* optiontype2name(enum OptionType type) {
  52   return optiontype_names[static_cast<int>(type)];
  53 }
  54 
  55 static enum OptionType option_types[] = {
  56 #define enum_of_options(option, name, ctype) OptionType::ctype,
  57         COMPILECOMMAND_OPTIONS(enum_of_options)
  58 #undef enum_of_options
  59 };
  60 
  61 enum OptionType option2type(enum CompileCommand option) {
  62   return option_types[static_cast<int>(option)];
  63 }
  64 
  65 static const char* option_names[] = {
  66 #define enum_of_options(option, name, ctype) name,
  67         COMPILECOMMAND_OPTIONS(enum_of_options)
  68 #undef enum_of_options
  69 };
  70 
  71 const char* option2name(enum CompileCommand option) {
  72   return option_names[static_cast<int>(option)];
  73 }
  74 
  75 /* Methods to map real type names to OptionType */
  76 template<typename T>
  77 static OptionType get_type_for() {
  78   return OptionType::Unknown;
  79 };
  80 
  81 template<> OptionType get_type_for<intx>() {
  82   return OptionType::Intx;
  83 }
  84 
  85 template<> OptionType get_type_for<uintx>() {
  86   return OptionType::Uintx;
  87 }
  88 
  89 template<> OptionType get_type_for<bool>() {
  90   return OptionType::Bool;
  91 }
  92 
  93 template<> OptionType get_type_for<ccstr>() {
  94   return OptionType::Ccstr;
  95 }
  96 
  97 template<> OptionType get_type_for<double>() {
  98   return OptionType::Double;
  99 }
 100 
 101 class MethodMatcher;
 102 class TypedMethodOptionMatcher;
 103 
 104 static TypedMethodOptionMatcher* option_list = nullptr;
 105 static bool any_set = false;
 106 static bool print_final_memstat_report = false;
 107 
 108 // A filter for quick lookup if an option is set
 109 static bool option_filter[static_cast<int>(CompileCommand::Unknown) + 1] = { 0 };
 110 
 111 void command_set_in_filter(enum CompileCommand option) {
 112   assert(option != CompileCommand::Unknown, "sanity");
 113   assert(option2type(option) != OptionType::Unknown, "sanity");
 114 
 115   if ((option != CompileCommand::DontInline) &&
 116       (option != CompileCommand::Inline) &&
 117       (option != CompileCommand::Log)) {
 118     any_set = true;
 119   }
 120   option_filter[static_cast<int>(option)] = true;
 121 }
 122 
 123 bool has_command(enum CompileCommand option) {
 124   return option_filter[static_cast<int>(option)];
 125 }
 126 
 127 class TypedMethodOptionMatcher : public MethodMatcher {
 128  private:
 129   TypedMethodOptionMatcher* _next;
 130   enum CompileCommand _option;
 131  public:
 132 
 133   union {
 134     bool bool_value;
 135     intx intx_value;
 136     uintx uintx_value;
 137     double double_value;
 138     ccstr ccstr_value;
 139   } _u;
 140 
 141   TypedMethodOptionMatcher() : MethodMatcher(),
 142     _next(nullptr),
 143     _option(CompileCommand::Unknown) {
 144       memset(&_u, 0, sizeof(_u));
 145   }
 146 
 147   ~TypedMethodOptionMatcher();
 148   static TypedMethodOptionMatcher* parse_method_pattern(char*& line, char* errorbuf, const int buf_size);
 149   TypedMethodOptionMatcher* match(const methodHandle &method, enum CompileCommand option);
 150 
 151   void init(enum CompileCommand option, TypedMethodOptionMatcher* next) {
 152     _next = next;
 153     _option = option;
 154   }
 155 
 156   void init_matcher(Symbol* class_name, Mode class_mode,
 157                     Symbol* method_name, Mode method_mode,
 158                     Symbol* signature) {
 159     MethodMatcher::init(class_name, class_mode, method_name, method_mode, signature);
 160   }
 161 
 162   void set_next(TypedMethodOptionMatcher* next) {_next = next; }
 163   TypedMethodOptionMatcher* next() { return _next; }
 164   enum CompileCommand option() { return _option; }
 165   template<typename T> T value();
 166   template<typename T> void set_value(T value);
 167   void print();
 168   void print_all();
 169   TypedMethodOptionMatcher* clone();
 170 };
 171 
 172 // A few templated accessors instead of a full template class.
 173 template<> intx TypedMethodOptionMatcher::value<intx>() {
 174   return _u.intx_value;
 175 }
 176 
 177 template<> uintx TypedMethodOptionMatcher::value<uintx>() {
 178   return _u.uintx_value;
 179 }
 180 
 181 template<> bool TypedMethodOptionMatcher::value<bool>() {
 182   return _u.bool_value;
 183 }
 184 
 185 template<> double TypedMethodOptionMatcher::value<double>() {
 186   return _u.double_value;
 187 }
 188 
 189 template<> ccstr TypedMethodOptionMatcher::value<ccstr>() {
 190   return _u.ccstr_value;
 191 }
 192 
 193 template<> void TypedMethodOptionMatcher::set_value(intx value) {
 194   _u.intx_value = value;
 195 }
 196 
 197 template<> void TypedMethodOptionMatcher::set_value(uintx value) {
 198   _u.uintx_value = value;
 199 }
 200 
 201 template<> void TypedMethodOptionMatcher::set_value(double value) {
 202   _u.double_value = value;
 203 }
 204 
 205 template<> void TypedMethodOptionMatcher::set_value(bool value) {
 206   _u.bool_value = value;
 207 }
 208 
 209 template<> void TypedMethodOptionMatcher::set_value(ccstr value) {
 210   _u.ccstr_value = (ccstr)os::strdup_check_oom(value);
 211 }
 212 
 213 void TypedMethodOptionMatcher::print() {
 214   ttyLocker ttyl;
 215   print_base(tty);
 216   const char* name = option2name(_option);
 217   enum OptionType type = option2type(_option);
 218   switch (type) {
 219     case OptionType::Intx:
 220     tty->print_cr(" intx %s = " INTX_FORMAT, name, value<intx>());
 221     break;
 222     case OptionType::Uintx:
 223     tty->print_cr(" uintx %s = " UINTX_FORMAT, name, value<uintx>());
 224     break;
 225     case OptionType::Bool:
 226     tty->print_cr(" bool %s = %s", name, value<bool>() ? "true" : "false");
 227     break;
 228     case OptionType::Double:
 229     tty->print_cr(" double %s = %f", name, value<double>());
 230     break;
 231     case OptionType::Ccstr:
 232     case OptionType::Ccstrlist:
 233     tty->print_cr(" const char* %s = '%s'", name, value<ccstr>());
 234     break;
 235   default:
 236     ShouldNotReachHere();
 237   }
 238 }
 239 
 240 void TypedMethodOptionMatcher::print_all() {
 241    print();
 242    if (_next != nullptr) {
 243      tty->print(" ");
 244      _next->print_all();
 245    }
 246  }
 247 
 248 TypedMethodOptionMatcher* TypedMethodOptionMatcher::clone() {
 249   TypedMethodOptionMatcher* m = new TypedMethodOptionMatcher();
 250   m->_class_mode = _class_mode;
 251   m->_class_name = _class_name;
 252   m->_method_mode = _method_mode;
 253   m->_method_name = _method_name;
 254   m->_signature = _signature;
 255   // Need to ref count the symbols
 256   if (_class_name != nullptr) {
 257     _class_name->increment_refcount();
 258   }
 259   if (_method_name != nullptr) {
 260     _method_name->increment_refcount();
 261   }
 262   if (_signature != nullptr) {
 263     _signature->increment_refcount();
 264   }
 265   return m;
 266 }
 267 
 268 TypedMethodOptionMatcher::~TypedMethodOptionMatcher() {
 269   enum OptionType type = option2type(_option);
 270   if (type == OptionType::Ccstr || type == OptionType::Ccstrlist) {
 271     ccstr v = value<ccstr>();
 272     os::free((void*)v);
 273   }
 274 }
 275 
 276 TypedMethodOptionMatcher* TypedMethodOptionMatcher::parse_method_pattern(char*& line, char* errorbuf, const int buf_size) {
 277   assert(*errorbuf == '\0', "Dont call here with error_msg already set");
 278   const char* error_msg = nullptr;
 279   TypedMethodOptionMatcher* tom = new TypedMethodOptionMatcher();
 280   MethodMatcher::parse_method_pattern(line, error_msg, tom);
 281   if (error_msg != nullptr) {
 282     jio_snprintf(errorbuf, buf_size, error_msg);
 283     delete tom;
 284     return nullptr;
 285   }
 286   return tom;
 287 }
 288 
 289 TypedMethodOptionMatcher* TypedMethodOptionMatcher::match(const methodHandle& method, enum CompileCommand option) {
 290   TypedMethodOptionMatcher* current = this;
 291   while (current != nullptr) {
 292     if (current->_option == option) {
 293       if (current->matches(method)) {
 294         return current;
 295       }
 296     }
 297     current = current->next();
 298   }
 299   return nullptr;
 300 }
 301 
 302 template<typename T>
 303 static void register_command(TypedMethodOptionMatcher* matcher,
 304                              enum CompileCommand option,
 305                              T value) {
 306   assert(matcher != option_list, "No circular lists please");
 307   if (option == CompileCommand::Log && !LogCompilation) {
 308     tty->print_cr("Warning:  +LogCompilation must be enabled in order for individual methods to be logged with ");
 309     tty->print_cr("          CompileCommand=log,<method pattern>");
 310   }
 311   assert(CompilerOracle::option_matches_type(option, value), "Value must match option type");
 312 
 313   if (option == CompileCommand::Blackhole && !UnlockExperimentalVMOptions) {
 314     warning("Blackhole compile option is experimental and must be enabled via -XX:+UnlockExperimentalVMOptions");
 315     // Delete matcher as we don't keep it
 316     delete matcher;
 317     return;
 318   }
 319 
 320   matcher->init(option, option_list);
 321   matcher->set_value<T>(value);
 322   option_list = matcher;
 323   command_set_in_filter(option);
 324 
 325   if (!CompilerOracle::be_quiet()) {
 326     // Print out the successful registration of a compile command
 327     ttyLocker ttyl;
 328     tty->print("CompileCommand: %s ", option2name(option));
 329     matcher->print();
 330   }
 331 
 332   return;
 333 }
 334 
 335 template<typename T>
 336 bool CompilerOracle::has_option_value(const methodHandle& method, enum CompileCommand option, T& value) {
 337   assert(option_matches_type(option, value), "Value must match option type");
 338   if (!has_command(option)) {
 339     return false;
 340   }
 341   if (option_list != nullptr) {
 342     TypedMethodOptionMatcher* m = option_list->match(method, option);
 343     if (m != nullptr) {
 344       value = m->value<T>();
 345       return true;
 346     }
 347   }
 348   return false;
 349 }
 350 
 351 static bool resolve_inlining_predicate(enum CompileCommand option, const methodHandle& method) {
 352   assert(option == CompileCommand::Inline || option == CompileCommand::DontInline, "Sanity");
 353   bool v1 = false;
 354   bool v2 = false;
 355   bool has_inline = CompilerOracle::has_option_value(method, CompileCommand::Inline, v1);
 356   bool has_dnotinline = CompilerOracle::has_option_value(method, CompileCommand::DontInline, v2);
 357   if (has_inline && has_dnotinline) {
 358     if (v1 && v2) {
 359       // Conflict options detected
 360       // Find the last one for that method and return the predicate accordingly
 361       // option_list lists options in reverse order. So the first option we find is the last which was specified.
 362       enum CompileCommand last_one = CompileCommand::Unknown;
 363       TypedMethodOptionMatcher* current = option_list;
 364       while (current != nullptr) {
 365         last_one = current->option();
 366         if (last_one == CompileCommand::Inline || last_one == CompileCommand::DontInline) {
 367           if (current->matches(method)) {
 368             return last_one == option;
 369           }
 370         }
 371         current = current->next();
 372       }
 373       ShouldNotReachHere();
 374       return false;
 375     } else {
 376       // No conflicts
 377       return option == CompileCommand::Inline ? v1 : v2;
 378     }
 379   } else {
 380     if (option == CompileCommand::Inline) {
 381       return has_inline ? v1 : false;
 382     } else {
 383       return has_dnotinline ? v2 : false;
 384     }
 385   }
 386 }
 387 
 388 static bool check_predicate(enum CompileCommand option, const methodHandle& method) {
 389   // Special handling for Inline and DontInline since conflict options may be specified
 390   if (option == CompileCommand::Inline || option == CompileCommand::DontInline) {
 391     return resolve_inlining_predicate(option, method);
 392   }
 393 
 394   bool value = false;
 395   if (CompilerOracle::has_option_value(method, option, value)) {
 396     return value;
 397   }
 398   return false;
 399 }
 400 
 401 bool CompilerOracle::has_any_command_set() {
 402   return any_set;
 403 }
 404 
 405 // Explicit instantiation for all OptionTypes supported.
 406 template bool CompilerOracle::has_option_value<intx>(const methodHandle& method, enum CompileCommand option, intx& value);
 407 template bool CompilerOracle::has_option_value<uintx>(const methodHandle& method, enum CompileCommand option, uintx& value);
 408 template bool CompilerOracle::has_option_value<bool>(const methodHandle& method, enum CompileCommand option, bool& value);
 409 template bool CompilerOracle::has_option_value<ccstr>(const methodHandle& method, enum CompileCommand option, ccstr& value);
 410 template bool CompilerOracle::has_option_value<double>(const methodHandle& method, enum CompileCommand option, double& value);
 411 
 412 template<typename T>
 413 bool CompilerOracle::option_matches_type(enum CompileCommand option, T& value) {
 414   enum OptionType option_type = option2type(option);
 415   if (option_type == OptionType::Unknown) {
 416     return false; // Can't query options with type Unknown.
 417   }
 418   if (option_type == OptionType::Ccstrlist) {
 419     option_type = OptionType::Ccstr; // CCstrList type options are stored as Ccstr
 420   }
 421   return (get_type_for<T>() == option_type);
 422 }
 423 
 424 template bool CompilerOracle::option_matches_type<intx>(enum CompileCommand option, intx& value);
 425 template bool CompilerOracle::option_matches_type<uintx>(enum CompileCommand option, uintx& value);
 426 template bool CompilerOracle::option_matches_type<bool>(enum CompileCommand option, bool& value);
 427 template bool CompilerOracle::option_matches_type<ccstr>(enum CompileCommand option, ccstr& value);
 428 template bool CompilerOracle::option_matches_type<double>(enum CompileCommand option, double& value);
 429 
 430 bool CompilerOracle::has_option(const methodHandle& method, enum CompileCommand option) {
 431   bool value = false;
 432   has_option_value(method, option, value);
 433   return value;
 434 }
 435 
 436 bool CompilerOracle::should_exclude(const methodHandle& method) {
 437   if (check_predicate(CompileCommand::Exclude, method)) {
 438     return true;
 439   }
 440   if (has_command(CompileCommand::CompileOnly)) {
 441     return !check_predicate(CompileCommand::CompileOnly, method);
 442   }
 443   return false;
 444 }
 445 
 446 bool CompilerOracle::should_inline(const methodHandle& method) {
 447   return (check_predicate(CompileCommand::Inline, method));
 448 }
 449 
 450 bool CompilerOracle::should_not_inline(const methodHandle& method) {
 451   return check_predicate(CompileCommand::DontInline, method) || check_predicate(CompileCommand::Exclude, method);
 452 }
 453 
 454 bool CompilerOracle::should_print(const methodHandle& method) {
 455   return check_predicate(CompileCommand::Print, method);
 456 }
 457 
 458 bool CompilerOracle::should_print_methods() {
 459   return has_command(CompileCommand::Print);
 460 }
 461 
 462 // Tells whether there are any methods to collect memory statistics for
 463 bool CompilerOracle::should_collect_memstat() {
 464   return has_command(CompileCommand::MemStat) || has_command(CompileCommand::MemLimit);
 465 }
 466 
 467 bool CompilerOracle::should_print_final_memstat_report() {
 468   return print_final_memstat_report;
 469 }
 470 
 471 bool CompilerOracle::should_log(const methodHandle& method) {
 472   if (!LogCompilation) return false;
 473   if (!has_command(CompileCommand::Log)) {
 474     return true;  // by default, log all
 475   }
 476   return (check_predicate(CompileCommand::Log, method));
 477 }
 478 
 479 bool CompilerOracle::should_break_at(const methodHandle& method) {
 480   return check_predicate(CompileCommand::Break, method);
 481 }
 482 
 483 void CompilerOracle::tag_blackhole_if_possible(const methodHandle& method) {
 484   if (!check_predicate(CompileCommand::Blackhole, method)) {
 485     return;
 486   }
 487   guarantee(UnlockExperimentalVMOptions, "Checked during initial parsing");
 488   if (method->result_type() != T_VOID) {
 489     warning("Blackhole compile option only works for methods with void type: %s",
 490             method->name_and_sig_as_C_string());
 491     return;
 492   }
 493   if (!method->is_empty_method()) {
 494     warning("Blackhole compile option only works for empty methods: %s",
 495             method->name_and_sig_as_C_string());
 496     return;
 497   }
 498   if (!method->is_static()) {
 499     warning("Blackhole compile option only works for static methods: %s",
 500             method->name_and_sig_as_C_string());
 501     return;
 502   }
 503   if (method->intrinsic_id() == vmIntrinsics::_blackhole) {
 504     return;
 505   }
 506   if (method->intrinsic_id() != vmIntrinsics::_none) {
 507     warning("Blackhole compile option only works for methods that do not have intrinsic set: %s, %s",
 508             method->name_and_sig_as_C_string(), vmIntrinsics::name_at(method->intrinsic_id()));
 509     return;
 510   }
 511   method->set_intrinsic_id(vmIntrinsics::_blackhole);
 512 }
 513 
 514 static enum CompileCommand match_option_name(const char* line, int* bytes_read, char* errorbuf, int bufsize) {
 515   assert(ARRAY_SIZE(option_names) == static_cast<int>(CompileCommand::Count), "option_names size mismatch");
 516 
 517   *bytes_read = 0;
 518   char option_buf[256];
 519   int matches = sscanf(line, "%255[a-zA-Z0-9]%n", option_buf, bytes_read);
 520   if (matches > 0 && strcasecmp(option_buf, "unknown") != 0) {
 521     for (uint i = 0; i < ARRAY_SIZE(option_names); i++) {
 522       if (strcasecmp(option_buf, option_names[i]) == 0) {
 523         return static_cast<enum CompileCommand>(i);
 524       }
 525     }
 526   }
 527   jio_snprintf(errorbuf, bufsize, "Unrecognized option '%s'", option_buf);
 528   return CompileCommand::Unknown;
 529 }
 530 
 531 // match exactly and don't mess with errorbuf
 532 enum CompileCommand CompilerOracle::parse_option_name(const char* line) {
 533   for (uint i = 0; i < ARRAY_SIZE(option_names); i++) {
 534     if (strcasecmp(line, option_names[i]) == 0) {
 535       return static_cast<enum CompileCommand>(i);
 536     }
 537   }
 538   return CompileCommand::Unknown;
 539 }
 540 
 541 enum OptionType CompilerOracle::parse_option_type(const char* type_str) {
 542   for (uint i = 0; i < ARRAY_SIZE(optiontype_names); i++) {
 543     if (strcasecmp(type_str, optiontype_names[i]) == 0) {
 544       return static_cast<enum OptionType>(i);
 545     }
 546   }
 547   return OptionType::Unknown;
 548 }
 549 
 550 void print_tip() { // CMH Update info
 551   tty->cr();
 552   tty->print_cr("Usage: '-XX:CompileCommand=<option>,<method pattern>' - to set boolean option to true");
 553   tty->print_cr("Usage: '-XX:CompileCommand=<option>,<method pattern>,<value>'");
 554   tty->print_cr("Use:   '-XX:CompileCommand=help' for more information and to list all option.");
 555   tty->cr();
 556 }
 557 
 558 void print_option(enum CompileCommand option, const char* name, enum OptionType type) {
 559   if (type != OptionType::Unknown) {
 560     tty->print_cr("    %s (%s)", name, optiontype2name(type));
 561   }
 562 }
 563 
 564 void print_commands() {
 565   tty->cr();
 566   tty->print_cr("All available options:");
 567 #define enum_of_options(option, name, ctype) print_option(CompileCommand::option, name, OptionType::ctype);
 568   COMPILECOMMAND_OPTIONS(enum_of_options)
 569 #undef enum_of_options
 570   tty->cr();
 571 }
 572 
 573 static void usage() {
 574   tty->cr();
 575   tty->print_cr("The CompileCommand option enables the user of the JVM to control specific");
 576   tty->print_cr("behavior of the dynamic compilers.");
 577   tty->cr();
 578   tty->print_cr("Compile commands has this general form:");
 579   tty->print_cr("-XX:CompileCommand=<option><method pattern><value>");
 580   tty->print_cr("    Sets <option> to the specified value for methods matching <method pattern>");
 581   tty->print_cr("    All options are typed");
 582   tty->cr();
 583   tty->print_cr("-XX:CompileCommand=<option><method pattern>");
 584   tty->print_cr("    Sets <option> to true for methods matching <method pattern>");
 585   tty->print_cr("    Only applies to boolean options.");
 586   tty->cr();
 587   tty->print_cr("-XX:CompileCommand=quiet");
 588   tty->print_cr("    Silence the compile command output");
 589   tty->cr();
 590   tty->print_cr("-XX:CompileCommand=help");
 591   tty->print_cr("    Prints this help text");
 592   tty->cr();
 593   print_commands();
 594   tty->cr();
 595     tty->print_cr("Method patterns has the format:");
 596   tty->print_cr("  package/Class.method()");
 597   tty->cr();
 598   tty->print_cr("For backward compatibility this form is also allowed:");
 599   tty->print_cr("  package.Class::method()");
 600   tty->cr();
 601   tty->print_cr("The signature can be separated by an optional whitespace or comma:");
 602   tty->print_cr("  package/Class.method ()");
 603   tty->cr();
 604   tty->print_cr("The class and method identifier can be used together with leading or");
 605   tty->print_cr("trailing *'s for wildcard matching:");
 606   tty->print_cr("  *ackage/Clas*.*etho*()");
 607   tty->cr();
 608   tty->print_cr("It is possible to use more than one CompileCommand on the command line:");
 609   tty->print_cr("  -XX:CompileCommand=exclude,java/*.* -XX:CompileCommand=log,java*.*");
 610   tty->cr();
 611   tty->print_cr("The CompileCommands can be loaded from a file with the flag");
 612   tty->print_cr("-XX:CompileCommandFile=<file> or be added to the file '.hotspot_compiler'");
 613   tty->print_cr("Use the same format in the file as the argument to the CompileCommand flag.");
 614   tty->print_cr("Add one command on each line.");
 615   tty->print_cr("  exclude java/*.*");
 616   tty->print_cr("  option java/*.* ReplayInline");
 617   tty->cr();
 618   tty->print_cr("The following commands have conflicting behavior: 'exclude', 'inline', 'dontinline',");
 619   tty->print_cr("and 'compileonly'. There is no priority of commands. Applying (a subset of) these");
 620   tty->print_cr("commands to the same method results in undefined behavior.");
 621   tty->cr();
 622 };
 623 
 624 int skip_whitespace(char* &line) {
 625   // Skip any leading spaces
 626   int whitespace_read = 0;
 627   sscanf(line, "%*[ \t]%n", &whitespace_read);
 628   line += whitespace_read;
 629   return whitespace_read;
 630 }
 631 
 632 void skip_comma(char* &line) {
 633   // Skip any leading spaces
 634   if (*line == ',') {
 635     line++;
 636   }
 637 }
 638 
 639 static bool parseMemLimit(const char* line, intx& value, int& bytes_read, char* errorbuf, const int buf_size) {
 640   // Format:
 641   // "<memory size>['~' <suboption>]"
 642   // <memory size> can have units, e.g. M
 643   // <suboption> one of "crash" "stop", if omitted, "stop" is implied.
 644   //
 645   // Examples:
 646   // -XX:CompileCommand='memlimit,*.*,20m'
 647   // -XX:CompileCommand='memlimit,*.*,20m~stop'
 648   // -XX:CompileCommand='memlimit,Option::toString,1m~crash'
 649   //
 650   // The resulting intx carries the size and whether we are to stop or crash:
 651   // - neg. value means crash
 652   // - pos. value (default) means stop
 653   size_t s = 0;
 654   char* end;
 655   if (!parse_integer<size_t>(line, &end, &s)) {
 656     jio_snprintf(errorbuf, buf_size, "MemLimit: invalid value");
 657     return false;
 658   }
 659   bytes_read = (int)(end - line);
 660 
 661   intx v = (intx)s;
 662   if ((*end) != '\0') {
 663     if (strncasecmp(end, "~crash", 6) == 0) {
 664       v = -v;
 665       bytes_read += 6;
 666     } else if (strncasecmp(end, "~stop", 5) == 0) {
 667       // ok, this is the default
 668       bytes_read += 5;
 669     } else {
 670       jio_snprintf(errorbuf, buf_size, "MemLimit: invalid option");
 671       return false;
 672     }
 673   }
 674   value = v;
 675   return true;
 676 }
 677 
 678 static bool parseMemStat(const char* line, uintx& value, int& bytes_read, char* errorbuf, const int buf_size) {
 679 
 680 #define IF_ENUM_STRING(S, CMD)                \
 681   if (strncasecmp(line, S, strlen(S)) == 0) { \
 682     bytes_read += (int)strlen(S);             \
 683     CMD                                       \
 684     return true;                              \
 685   }
 686 
 687   IF_ENUM_STRING("collect", {
 688     value = (uintx)MemStatAction::collect;
 689   });
 690   IF_ENUM_STRING("print", {
 691     value = (uintx)MemStatAction::print;
 692     print_final_memstat_report = true;
 693   });
 694 #undef IF_ENUM_STRING
 695 
 696   jio_snprintf(errorbuf, buf_size, "MemStat: invalid option");
 697 
 698   return false;
 699 }
 700 
 701 static void scan_value(enum OptionType type, char* line, int& total_bytes_read,
 702         TypedMethodOptionMatcher* matcher, enum CompileCommand option, char* errorbuf, const int buf_size) {
 703   int bytes_read = 0;
 704   const char* ccname = option2name(option);
 705   const char* type_str = optiontype2name(type);
 706   int skipped = skip_whitespace(line);
 707   total_bytes_read += skipped;
 708   if (type == OptionType::Intx) {
 709     intx value;
 710     bool success = false;
 711     if (option == CompileCommand::MemLimit) {
 712       // Special parsing for MemLimit
 713       success = parseMemLimit(line, value, bytes_read, errorbuf, buf_size);
 714     } else {
 715       // Is it a raw number?
 716       success = sscanf(line, "" INTX_FORMAT "%n", &value, &bytes_read) == 1;
 717     }
 718     if (success) {
 719       total_bytes_read += bytes_read;
 720       line += bytes_read;
 721       register_command(matcher, option, value);
 722       return;
 723     } else {
 724       jio_snprintf(errorbuf, buf_size, "Value cannot be read for option '%s' of type '%s'", ccname, type_str);
 725     }
 726   } else if (type == OptionType::Uintx) {
 727     uintx value;
 728     bool success = false;
 729     if (option == CompileCommand::MemStat) {
 730       // Special parsing for MemStat
 731       success = parseMemStat(line, value, bytes_read, errorbuf, buf_size);
 732     } else {
 733       // parse as raw number
 734       success = sscanf(line, "" UINTX_FORMAT "%n", &value, &bytes_read) == 1;
 735     }
 736     if (success) {
 737       total_bytes_read += bytes_read;
 738       line += bytes_read;
 739       register_command(matcher, option, value);
 740     } else {
 741       jio_snprintf(errorbuf, buf_size, "Value cannot be read for option '%s' of type '%s'", ccname, type_str);
 742     }
 743   } else if (type == OptionType::Ccstr) {
 744     ResourceMark rm;
 745     char* value = NEW_RESOURCE_ARRAY(char, strlen(line) + 1);
 746     if (sscanf(line, "%255[_a-zA-Z0-9]%n", value, &bytes_read) == 1) {
 747       total_bytes_read += bytes_read;
 748       line += bytes_read;
 749       register_command(matcher, option, (ccstr) value);
 750       return;
 751     } else {
 752       jio_snprintf(errorbuf, buf_size, "Value cannot be read for option '%s' of type '%s'", ccname, type_str);
 753     }
 754   } else if (type == OptionType::Ccstrlist) {
 755     // Accumulates several strings into one. The internal type is ccstr.
 756     ResourceMark rm;
 757     char* value = NEW_RESOURCE_ARRAY(char, strlen(line) + 1);
 758     char* next_value = value;
 759     if (sscanf(line, "%255[_a-zA-Z0-9+\\-]%n", next_value, &bytes_read) == 1) {
 760       total_bytes_read += bytes_read;
 761       line += bytes_read;
 762       next_value += bytes_read + 1;
 763       char* end_value = next_value - 1;
 764       while (sscanf(line, "%*[ \t]%255[_a-zA-Z0-9+\\-]%n", next_value, &bytes_read) == 1) {
 765         total_bytes_read += bytes_read;
 766         line += bytes_read;
 767         *end_value = ' '; // override '\0'
 768         next_value += bytes_read;
 769         end_value = next_value-1;
 770       }
 771 
 772       if (option == CompileCommand::ControlIntrinsic || option == CompileCommand::DisableIntrinsic) {
 773         ControlIntrinsicValidator validator(value, (option == CompileCommand::DisableIntrinsic));
 774 
 775         if (!validator.is_valid()) {
 776           jio_snprintf(errorbuf, buf_size, "Unrecognized intrinsic detected in %s: %s", option2name(option), validator.what());
 777         }
 778       }
 779 #if !defined(PRODUCT) && defined(COMPILER2)
 780       else if (option == CompileCommand::TraceAutoVectorization) {
 781         TraceAutoVectorizationTagValidator validator(value, true);
 782 
 783         if (!validator.is_valid()) {
 784           jio_snprintf(errorbuf, buf_size, "Unrecognized tag name in %s: %s", option2name(option), validator.what());
 785         }
 786       } else if (option == CompileCommand::PrintIdealPhase) {
 787         PhaseNameValidator validator(value);
 788 
 789         if (!validator.is_valid()) {
 790           jio_snprintf(errorbuf, buf_size, "Unrecognized phase name in %s: %s", option2name(option), validator.what());
 791         }
 792       } else if (option == CompileCommand::TestOptionList) {
 793         // all values are ok
 794       }
 795 #endif
 796       else {
 797         assert(false, "Ccstrlist type option missing validator");
 798       }
 799 
 800       register_command(matcher, option, (ccstr) value);
 801       return;
 802     } else {
 803       jio_snprintf(errorbuf, buf_size, "Value cannot be read for option '%s' of type '%s'", ccname, type_str);
 804     }
 805   } else if (type == OptionType::Bool) {
 806     char value[256];
 807     if (*line == '\0') {
 808       // Short version of a CompileCommand sets a boolean Option to true
 809       // -XXCompileCommand=<Option>,<method pattern>
 810       register_command(matcher, option, true);
 811       return;
 812     }
 813     if (sscanf(line, "%255[a-zA-Z]%n", value, &bytes_read) == 1) {
 814       if (strcasecmp(value, "true") == 0) {
 815         total_bytes_read += bytes_read;
 816         line += bytes_read;
 817         register_command(matcher, option, true);
 818         return;
 819       } else if (strcasecmp(value, "false") == 0) {
 820         total_bytes_read += bytes_read;
 821         line += bytes_read;
 822         register_command(matcher, option, false);
 823         return;
 824       } else {
 825         jio_snprintf(errorbuf, buf_size, "Value cannot be read for option '%s' of type '%s'", ccname, type_str);
 826       }
 827     } else {
 828       jio_snprintf(errorbuf, buf_size, "Value cannot be read for option '%s' of type '%s'", ccname, type_str);
 829     }
 830   } else if (type == OptionType::Double) {
 831     char buffer[2][256];
 832     // Decimal separator '.' has been replaced with ' ' or '/' earlier,
 833     // so read integer and fraction part of double value separately.
 834     if (sscanf(line, "%255[0-9]%*[ /\t]%255[0-9]%n", buffer[0], buffer[1], &bytes_read) == 2) {
 835       char value[512] = "";
 836       jio_snprintf(value, sizeof(value), "%s.%s", buffer[0], buffer[1]);
 837       total_bytes_read += bytes_read;
 838       line += bytes_read;
 839       register_command(matcher, option, atof(value));
 840       return;
 841     } else {
 842       jio_snprintf(errorbuf, buf_size, "Value cannot be read for option '%s' of type '%s'", ccname, type_str);
 843     }
 844   } else {
 845     jio_snprintf(errorbuf, buf_size, "Type '%s' not supported ", type_str);
 846   }
 847 }
 848 
 849 // Scan next option and value in line, return MethodMatcher object on success, nullptr on failure.
 850 // On failure, error_msg contains description for the first error.
 851 // For future extensions: set error_msg on first error.
 852 static void scan_option_and_value(enum OptionType type, char* line, int& total_bytes_read,
 853                                 TypedMethodOptionMatcher* matcher,
 854                                 char* errorbuf, const int buf_size) {
 855   total_bytes_read = 0;
 856   int bytes_read = 0;
 857   char option_buf[256];
 858 
 859   // Read option name.
 860   if (sscanf(line, "%*[ \t]%255[a-zA-Z0-9]%n", option_buf, &bytes_read) == 1) {
 861     line += bytes_read;
 862     total_bytes_read += bytes_read;
 863     int bytes_read2 = 0;
 864     total_bytes_read += skip_whitespace(line);
 865     enum CompileCommand option = match_option_name(option_buf, &bytes_read2, errorbuf, buf_size);
 866     if (option == CompileCommand::Unknown) {
 867       assert(*errorbuf != '\0', "error must have been set");
 868       return;
 869     }
 870     enum OptionType optiontype = option2type(option);
 871     if (option2type(option) != type) {
 872       const char* optiontype_name = optiontype2name(optiontype);
 873       const char* type_name = optiontype2name(type);
 874       jio_snprintf(errorbuf, buf_size, "Option '%s' with type '%s' doesn't match supplied type '%s'", option_buf, optiontype_name, type_name);
 875       return;
 876     }
 877     scan_value(type, line, total_bytes_read, matcher, option, errorbuf, buf_size);
 878   } else {
 879     const char* type_str = optiontype2name(type);
 880     jio_snprintf(errorbuf, buf_size, "Option name for type '%s' should be alphanumeric ", type_str);
 881   }
 882   return;
 883 }
 884 
 885 void CompilerOracle::print_parse_error(char* error_msg, char* original_line) {
 886   assert(*error_msg != '\0', "Must have error_message");
 887   ttyLocker ttyl;
 888   tty->print_cr("CompileCommand: An error occurred during parsing");
 889   tty->print_cr("Error: %s", error_msg);
 890   tty->print_cr("Line: '%s'", original_line);
 891   print_tip();
 892 }
 893 
 894 class LineCopy : StackObj {
 895   const char* _copy;
 896 public:
 897     LineCopy(char* line) {
 898       _copy = os::strdup(line, mtInternal);
 899     }
 900     ~LineCopy() {
 901       os::free((void*)_copy);
 902     }
 903     char* get() {
 904       return (char*)_copy;
 905     }
 906 };
 907 
 908 bool CompilerOracle::parse_from_line(char* line) {
 909   if ((line[0] == '\0') || (line[0] == '#')) {
 910     return true;
 911   }
 912 
 913   LineCopy original(line);
 914   int bytes_read;
 915   char error_buf[1024] = {0};
 916 
 917   enum CompileCommand option = match_option_name(line, &bytes_read, error_buf, sizeof(error_buf));
 918   line += bytes_read;
 919   ResourceMark rm;
 920 
 921   if (option == CompileCommand::Unknown) {
 922     print_parse_error(error_buf, original.get());
 923     return false;
 924   }
 925 
 926   if (option == CompileCommand::Quiet) {
 927     _quiet = true;
 928     return true;
 929   }
 930 
 931   if (option == CompileCommand::Help) {
 932     usage();
 933     return true;
 934   }
 935 
 936   if (option == CompileCommand::Option) {
 937     // Look for trailing options.
 938     //
 939     // Two types of trailing options are
 940     // supported:
 941     //
 942     // (1) CompileCommand=option,Klass::method,option
 943     // (2) CompileCommand=option,Klass::method,type,option,value
 944     //
 945     // Type (1) is used to enable a boolean option for a method.
 946     //
 947     // Type (2) is used to support options with a value. Values can have the
 948     // the following types: intx, uintx, bool, ccstr, ccstrlist, and double.
 949 
 950     char option_type[256]; // stores option for Type (1) and type of Type (2)
 951     skip_comma(line);
 952     TypedMethodOptionMatcher* archetype = TypedMethodOptionMatcher::parse_method_pattern(line, error_buf, sizeof(error_buf));
 953     if (archetype == nullptr) {
 954       print_parse_error(error_buf, original.get());
 955       return false;
 956     }
 957 
 958     skip_whitespace(line);
 959 
 960     // This is unnecessarily complex. Should retire multi-option lines and skip while loop
 961     while (sscanf(line, "%255[a-zA-Z0-9]%n", option_type, &bytes_read) == 1) {
 962       line += bytes_read;
 963 
 964       // typed_matcher is used as a blueprint for each option, deleted at the end
 965       TypedMethodOptionMatcher* typed_matcher = archetype->clone();
 966       enum OptionType type = parse_option_type(option_type);
 967       if (type != OptionType::Unknown) {
 968         // Type (2) option: parse option name and value.
 969         scan_option_and_value(type, line, bytes_read, typed_matcher, error_buf, sizeof(error_buf));
 970         if (*error_buf != '\0') {
 971           print_parse_error(error_buf, original.get());
 972           return false;
 973         }
 974         line += bytes_read;
 975       } else {
 976         // Type (1) option - option_type contains the option name -> bool value = true is implied
 977         int bytes_read;
 978         enum CompileCommand option = match_option_name(option_type, &bytes_read, error_buf, sizeof(error_buf));
 979         if (option == CompileCommand::Unknown) {
 980           print_parse_error(error_buf, original.get());
 981           return false;
 982         }
 983         if (option2type(option) == OptionType::Bool) {
 984           register_command(typed_matcher, option, true);
 985         } else {
 986           jio_snprintf(error_buf, sizeof(error_buf), "  Missing type '%s' before option '%s'",
 987                        optiontype2name(option2type(option)), option2name(option));
 988           print_parse_error(error_buf, original.get());
 989           return false;
 990         }
 991       }
 992       assert(typed_matcher != nullptr, "sanity");
 993       assert(*error_buf == '\0', "No error here");
 994       skip_whitespace(line);
 995     } // while(
 996     delete archetype;
 997   } else {  // not an OptionCommand
 998     // Command has the following form:
 999     // CompileCommand=<option>,<method pattern><value>
1000     // CompileCommand=<option>,<method pattern>     (implies option is bool and value is true)
1001     assert(*error_buf == '\0', "Don't call here with error_buf already set");
1002     enum OptionType type = option2type(option);
1003     int bytes_read = 0;
1004     skip_comma(line);
1005     TypedMethodOptionMatcher* matcher = TypedMethodOptionMatcher::parse_method_pattern(line, error_buf, sizeof(error_buf));
1006     if (matcher == nullptr) {
1007       print_parse_error(error_buf, original.get());
1008       return false;
1009     }
1010     skip_whitespace(line);
1011     if (*line == '\0') {
1012       if (option2type(option) == OptionType::Bool) {
1013         // if this is a bool option this implies true
1014         register_command(matcher, option, true);
1015         return true;
1016       } else if (option == CompileCommand::MemStat) {
1017         // MemStat default action is to collect data but to not print
1018         register_command(matcher, option, (uintx)MemStatAction::collect);
1019         return true;
1020       } else {
1021         jio_snprintf(error_buf, sizeof(error_buf), "  Option '%s' is not followed by a value", option2name(option));
1022         print_parse_error(error_buf, original.get());
1023         return false;
1024       }
1025     }
1026     scan_value(type, line, bytes_read, matcher, option, error_buf, sizeof(error_buf));
1027     if (*error_buf != '\0') {
1028       print_parse_error(error_buf, original.get());
1029       return false;
1030     }
1031     assert(matcher != nullptr, "consistency");
1032   }
1033   return true;
1034 }
1035 
1036 static const char* default_cc_file = ".hotspot_compiler";
1037 
1038 static const char* cc_file() {
1039 #ifdef ASSERT
1040   if (CompileCommandFile == nullptr)
1041     return default_cc_file;
1042 #endif
1043   return CompileCommandFile;
1044 }
1045 
1046 bool CompilerOracle::has_command_file() {
1047   return cc_file() != nullptr;
1048 }
1049 
1050 bool CompilerOracle::_quiet = false;
1051 
1052 bool CompilerOracle::parse_from_file() {
1053   assert(has_command_file(), "command file must be specified");
1054   FILE* stream = os::fopen(cc_file(), "rt");
1055   if (stream == nullptr) {
1056     return true;
1057   }
1058 
1059   char token[1024];
1060   int  pos = 0;
1061   int  c = getc(stream);
1062   bool success = true;
1063   while(c != EOF && pos < (int)(sizeof(token)-1)) {
1064     if (c == '\n') {
1065       token[pos++] = '\0';
1066       if (!parse_from_line(token)) {
1067         success = false;
1068       }
1069       pos = 0;
1070     } else {
1071       token[pos++] = c;
1072     }
1073     c = getc(stream);
1074   }
1075   token[pos++] = '\0';
1076   if (!parse_from_line(token)) {
1077     success = false;
1078   }
1079   fclose(stream);
1080   return success;
1081 }
1082 
1083 bool CompilerOracle::parse_from_string(const char* str, bool (*parse_line)(char*)) {
1084   char token[1024];
1085   int  pos = 0;
1086   const char* sp = str;
1087   int  c = *sp++;
1088   bool success = true;
1089   while (c != '\0' && pos < (int)(sizeof(token)-1)) {
1090     if (c == '\n') {
1091       token[pos++] = '\0';
1092       if (!parse_line(token)) {
1093         success = false;
1094       }
1095       pos = 0;
1096     } else {
1097       token[pos++] = c;
1098     }
1099     c = *sp++;
1100   }
1101   token[pos++] = '\0';
1102   if (!parse_line(token)) {
1103     success = false;
1104   }
1105   return success;
1106 }
1107 
1108 bool compilerOracle_init() {
1109   bool success = true;
1110   if (!CompilerOracle::parse_from_string(CompileCommand, CompilerOracle::parse_from_line)) {
1111     success = false;
1112   }
1113   if (!CompilerOracle::parse_from_string(CompileOnly, CompilerOracle::parse_compile_only)) {
1114     success = false;
1115   }
1116   if (CompilerOracle::has_command_file()) {
1117     if (!CompilerOracle::parse_from_file()) {
1118       success = false;
1119     }
1120   } else {
1121     struct stat buf;
1122     if (os::stat(default_cc_file, &buf) == 0) {
1123       warning("%s file is present but has been ignored.  "
1124               "Run with -XX:CompileCommandFile=%s to load the file.",
1125               default_cc_file, default_cc_file);
1126     }
1127   }
1128   if (has_command(CompileCommand::Print)) {
1129     if (PrintAssembly) {
1130       warning("CompileCommand and/or %s file contains 'print' commands, but PrintAssembly is also enabled", default_cc_file);
1131     }
1132   }
1133   return success;
1134 }
1135 
1136 bool CompilerOracle::parse_compile_only(char* line) {
1137   if (line[0] == '\0') {
1138     return true;
1139   }
1140   ResourceMark rm;
1141   char error_buf[1024] = {0};
1142   LineCopy original(line);
1143   char* method_pattern;
1144   do {
1145     if (line[0] == '\0') {
1146       break;
1147     }
1148     method_pattern = strtok_r(line, ",", &line);
1149     if (method_pattern != nullptr) {
1150       TypedMethodOptionMatcher* matcher = TypedMethodOptionMatcher::parse_method_pattern(method_pattern, error_buf, sizeof(error_buf));
1151       if (matcher != nullptr) {
1152         register_command(matcher, CompileCommand::CompileOnly, true);
1153         continue;
1154       }
1155     }
1156     ttyLocker ttyl;
1157     tty->print_cr("CompileOnly: An error occurred during parsing");
1158     if (*error_buf != '\0') {
1159       tty->print_cr("Error: %s", error_buf);
1160     }
1161     tty->print_cr("Line: '%s'", original.get());
1162     return false;
1163   } while (method_pattern != nullptr && line != nullptr);
1164   return true;
1165 }
1166 
1167 enum CompileCommand CompilerOracle::string_to_option(const char* name) {
1168   int bytes_read = 0;
1169   char errorbuf[1024] = {0};
1170   return match_option_name(name, &bytes_read, errorbuf, sizeof(errorbuf));
1171 }