1 /*
   2  * Copyright 1998-2006 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
  20  * CA 95054 USA or visit www.sun.com if you need additional information or
  21  * have any questions.
  22  *
  23  */
  24 
  25 #include "incls/_precompiled.incl"
  26 #include "incls/_bytecodeInfo.cpp.incl"
  27 
  28 // These variables are declared in parse1.cpp
  29 extern int  explicit_null_checks_inserted;
  30 extern int  explicit_null_checks_elided;
  31 extern int  explicit_null_checks_inserted_old;
  32 extern int  explicit_null_checks_elided_old;
  33 extern int  nodes_created_old;
  34 extern int  nodes_created;
  35 extern int  methods_parsed_old;
  36 extern int  methods_parsed;
  37 extern int  methods_seen;
  38 extern int  methods_seen_old;
  39 
  40 
  41 //=============================================================================
  42 //------------------------------InlineTree-------------------------------------
  43 InlineTree::InlineTree( Compile* c, const InlineTree *caller_tree, ciMethod* callee, JVMState* caller_jvms, int caller_bci, float site_invoke_ratio )
  44 : C(c), _caller_jvms(caller_jvms),
  45   _caller_tree((InlineTree*)caller_tree),
  46   _method(callee), _site_invoke_ratio(site_invoke_ratio),
  47   _count_inline_bcs(method()->code_size()) {
  48   NOT_PRODUCT(_count_inlines = 0;)
  49   if (_caller_jvms != NULL) {
  50     // Keep a private copy of the caller_jvms:
  51     _caller_jvms = new (C) JVMState(caller_jvms->method(), caller_tree->caller_jvms());
  52     _caller_jvms->set_bci(caller_jvms->bci());
  53   }
  54   assert(_caller_jvms->same_calls_as(caller_jvms), "consistent JVMS");
  55   assert((caller_tree == NULL ? 0 : caller_tree->inline_depth() + 1) == inline_depth(), "correct (redundant) depth parameter");
  56   assert(caller_bci == this->caller_bci(), "correct (redundant) bci parameter");
  57   if (UseOldInlining) {
  58     // Update hierarchical counts, count_inline_bcs() and count_inlines()
  59     InlineTree *caller = (InlineTree *)caller_tree;
  60     for( ; caller != NULL; caller = ((InlineTree *)(caller->caller_tree())) ) {
  61       caller->_count_inline_bcs += count_inline_bcs();
  62       NOT_PRODUCT(caller->_count_inlines++;)
  63     }
  64   }
  65 }
  66 
  67 InlineTree::InlineTree(Compile* c, ciMethod* callee_method, JVMState* caller_jvms, float site_invoke_ratio)
  68 : C(c), _caller_jvms(caller_jvms), _caller_tree(NULL),
  69   _method(callee_method), _site_invoke_ratio(site_invoke_ratio),
  70   _count_inline_bcs(method()->code_size()) {
  71   NOT_PRODUCT(_count_inlines = 0;)
  72   assert(!UseOldInlining, "do not use for old stuff");
  73 }
  74 
  75 
  76 
  77 static void print_indent(int depth) {
  78   tty->print("      ");
  79   for (int i = depth; i != 0; --i) tty->print("  ");
  80 }
  81 
  82 static bool is_init_with_ea(ciMethod* callee_method,
  83                             ciMethod* caller_method, Compile* C) {
  84   // True when EA is ON and a java constructor is called or
  85   // a super constructor is called from an inlined java constructor.
  86   return DoEscapeAnalysis && EliminateAllocations &&
  87          ( callee_method->is_initializer() ||
  88            (caller_method->is_initializer() &&
  89             caller_method != C->method() &&
  90             caller_method->holder()->is_subclass_of(callee_method->holder()))
  91          );
  92 }
  93 
  94 // positive filter: should send be inlined?  returns NULL, if yes, or rejection msg
  95 const char* InlineTree::shouldInline(ciMethod* callee_method, ciMethod* caller_method, int caller_bci, ciCallProfile& profile, WarmCallInfo* wci_result) const {
  96   // Allows targeted inlining
  97   if(callee_method->should_inline()) {
  98     *wci_result = *(WarmCallInfo::always_hot());
  99     if (PrintInlining && Verbose) {
 100       print_indent(inline_depth());
 101       tty->print_cr("Inlined method is hot: ");
 102     }
 103     return NULL;
 104   }
 105 
 106   // positive filter: should send be inlined?  returns NULL (--> yes)
 107   // or rejection msg
 108   int max_size = C->max_inline_size();
 109   int size     = callee_method->code_size();
 110 
 111   // Check for too many throws (and not too huge)
 112   if(callee_method->interpreter_throwout_count() > InlineThrowCount &&
 113      size < InlineThrowMaxSize ) {
 114     wci_result->set_profit(wci_result->profit() * 100);
 115     if (PrintInlining && Verbose) {
 116       print_indent(inline_depth());
 117       tty->print_cr("Inlined method with many throws (throws=%d):", callee_method->interpreter_throwout_count());
 118     }
 119     return NULL;
 120   }
 121 
 122   if (!UseOldInlining) {
 123     return NULL;  // size and frequency are represented in a new way
 124   }
 125 
 126   int call_site_count  = method()->scale_count(profile.count());
 127   int invoke_count     = method()->interpreter_invocation_count();
 128   assert( invoke_count != 0, "Require invokation count greater than zero");
 129   int freq = call_site_count/invoke_count;
 130 
 131   // bump the max size if the call is frequent
 132   if ((freq >= InlineFrequencyRatio) ||
 133       (call_site_count >= InlineFrequencyCount) ||
 134       is_init_with_ea(callee_method, caller_method, C)) {
 135 
 136     max_size = C->freq_inline_size();
 137     if (size <= max_size && TraceFrequencyInlining) {
 138       print_indent(inline_depth());
 139       tty->print_cr("Inlined frequent method (freq=%d count=%d):", freq, call_site_count);
 140       print_indent(inline_depth());
 141       callee_method->print();
 142       tty->cr();
 143     }
 144   } else {
 145     // Not hot.  Check for medium-sized pre-existing nmethod at cold sites.
 146     if (callee_method->has_compiled_code() &&
 147         callee_method->instructions_size() > InlineSmallCode/4)
 148       return "already compiled into a medium method";
 149   }
 150   if (size > max_size) {
 151     if (max_size > C->max_inline_size())
 152       return "hot method too big";
 153     return "too big";
 154   }
 155   return NULL;
 156 }
 157 
 158 
 159 // negative filter: should send NOT be inlined?  returns NULL, ok to inline, or rejection msg
 160 const char* InlineTree::shouldNotInline(ciMethod *callee_method, ciMethod* caller_method, WarmCallInfo* wci_result) const {
 161   // negative filter: should send NOT be inlined?  returns NULL (--> inline) or rejection msg
 162   if (!UseOldInlining) {
 163     const char* fail = NULL;
 164     if (callee_method->is_abstract())               fail = "abstract method";
 165     // note: we allow ik->is_abstract()
 166     if (!callee_method->holder()->is_initialized()) fail = "method holder not initialized";
 167     if (callee_method->is_native())                 fail = "native method";
 168 
 169     if (fail) {
 170       *wci_result = *(WarmCallInfo::always_cold());
 171       return fail;
 172     }
 173 
 174     if (callee_method->has_unloaded_classes_in_signature()) {
 175       wci_result->set_profit(wci_result->profit() * 0.1);
 176     }
 177 
 178     // don't inline exception code unless the top method belongs to an
 179     // exception class
 180     if (callee_method->holder()->is_subclass_of(C->env()->Throwable_klass())) {
 181       ciMethod* top_method = caller_jvms() ? caller_jvms()->of_depth(1)->method() : method();
 182       if (!top_method->holder()->is_subclass_of(C->env()->Throwable_klass())) {
 183         wci_result->set_profit(wci_result->profit() * 0.1);
 184       }
 185     }
 186 
 187     if (callee_method->has_compiled_code() && callee_method->instructions_size() > InlineSmallCode) {
 188       wci_result->set_profit(wci_result->profit() * 0.1);
 189       // %%% adjust wci_result->size()?
 190     }
 191 
 192     return NULL;
 193   }
 194 
 195   // First check all inlining restrictions which are required for correctness
 196   if (callee_method->is_abstract())               return "abstract method";
 197   // note: we allow ik->is_abstract()
 198   if (!callee_method->holder()->is_initialized()) return "method holder not initialized";
 199   if (callee_method->is_native())                 return "native method";
 200   if (callee_method->has_unloaded_classes_in_signature()) return "unloaded signature classes";
 201 
 202   if (callee_method->should_inline()) {
 203     // ignore heuristic controls on inlining
 204     return NULL;
 205   }
 206 
 207   // Now perform checks which are heuristic
 208 
 209   if( callee_method->has_compiled_code() && callee_method->instructions_size() > InlineSmallCode )
 210     return "already compiled into a big method";
 211 
 212   // don't inline exception code unless the top method belongs to an
 213   // exception class
 214   if (caller_tree() != NULL &&
 215       callee_method->holder()->is_subclass_of(C->env()->Throwable_klass())) {
 216     const InlineTree *top = this;
 217     while (top->caller_tree() != NULL) top = top->caller_tree();
 218     ciInstanceKlass* k = top->method()->holder();
 219     if (!k->is_subclass_of(C->env()->Throwable_klass()))
 220       return "exception method";
 221   }
 222 
 223   // use frequency-based objections only for non-trivial methods
 224   if (callee_method->code_size() <= MaxTrivialSize) return NULL;
 225 
 226   // don't use counts with -Xcomp or CTW
 227   if (UseInterpreter && !CompileTheWorld) {
 228 
 229     if (!callee_method->has_compiled_code() &&
 230         !callee_method->was_executed_more_than(0)) {
 231       return "never executed";
 232     }
 233 
 234     if (is_init_with_ea(callee_method, caller_method, C)) {
 235 
 236       // Escape Analysis: inline all executed constructors
 237 
 238     } else if (!callee_method->was_executed_more_than(MIN2(MinInliningThreshold,
 239                                                            CompileThreshold >> 1))) {
 240       return "executed < MinInliningThreshold times";
 241     }
 242   }
 243 
 244   if (callee_method->should_not_inline()) {
 245     return "disallowed by CompilerOracle";
 246   }
 247 
 248   return NULL;
 249 }
 250 
 251 //-----------------------------try_to_inline-----------------------------------
 252 // return NULL if ok, reason for not inlining otherwise
 253 // Relocated from "InliningClosure::try_to_inline"
 254 const char* InlineTree::try_to_inline(ciMethod* callee_method, ciMethod* caller_method, int caller_bci, ciCallProfile& profile, WarmCallInfo* wci_result) {
 255 
 256   // Old algorithm had funny accumulating BC-size counters
 257   if (UseOldInlining && ClipInlining
 258       && (int)count_inline_bcs() >= DesiredMethodLimit) {
 259     return "size > DesiredMethodLimit";
 260   }
 261 
 262   const char *msg = NULL;
 263   if ((msg = shouldInline(callee_method, caller_method, caller_bci,
 264                           profile, wci_result)) != NULL) {
 265     return msg;
 266   }
 267   if ((msg = shouldNotInline(callee_method, caller_method,
 268                              wci_result)) != NULL) {
 269     return msg;
 270   }
 271 
 272   bool is_accessor = InlineAccessors && callee_method->is_accessor();
 273 
 274   // suppress a few checks for accessors and trivial methods
 275   if (!is_accessor && callee_method->code_size() > MaxTrivialSize) {
 276 
 277     // don't inline into giant methods
 278     if (C->unique() > (uint)NodeCountInliningCutoff) {
 279       return "NodeCountInliningCutoff";
 280     }
 281 
 282     if ((!UseInterpreter || CompileTheWorld) &&
 283         is_init_with_ea(callee_method, caller_method, C)) {
 284 
 285       // Escape Analysis stress testing when running Xcomp or CTW:
 286       // inline constructors even if they are not reached.
 287 
 288     } else if (profile.count() == 0) {
 289       // don't inline unreached call sites
 290       return "call site not reached";
 291     }
 292   }
 293 
 294   if (!C->do_inlining() && InlineAccessors && !is_accessor) {
 295     return "not an accessor";
 296   }
 297   if( inline_depth() > MaxInlineLevel ) {
 298     return "inlining too deep";
 299   }
 300   if( method() == callee_method &&
 301       inline_depth() > MaxRecursiveInlineLevel ) {
 302     return "recursively inlining too deep";
 303   }
 304 
 305   int size = callee_method->code_size();
 306 
 307   if (UseOldInlining && ClipInlining
 308       && (int)count_inline_bcs() + size >= DesiredMethodLimit) {
 309     return "size > DesiredMethodLimit";
 310   }
 311 
 312   // ok, inline this method
 313   return NULL;
 314 }
 315 
 316 //------------------------------pass_initial_checks----------------------------
 317 bool pass_initial_checks(ciMethod* caller_method, int caller_bci, ciMethod* callee_method) {
 318   ciInstanceKlass *callee_holder = callee_method ? callee_method->holder() : NULL;
 319   // Check if a callee_method was suggested
 320   if( callee_method == NULL )            return false;
 321   // Check if klass of callee_method is loaded
 322   if( !callee_holder->is_loaded() )      return false;
 323   if( !callee_holder->is_initialized() ) return false;
 324   if( !UseInterpreter || CompileTheWorld /* running Xcomp or CTW */ ) {
 325     // Checks that constant pool's call site has been visited
 326     // stricter than callee_holder->is_initialized()
 327     ciBytecodeStream iter(caller_method);
 328     iter.force_bci(caller_bci);
 329     int index = iter.get_index_big();
 330     if( !caller_method->is_klass_loaded(index, true) ) {
 331       return false;
 332     }
 333     // Try to do constant pool resolution if running Xcomp
 334     Bytecodes::Code call_bc = iter.cur_bc();
 335     if( !caller_method->check_call(index, call_bc == Bytecodes::_invokestatic) ) {
 336       return false;
 337     }
 338   }
 339   // We will attempt to see if a class/field/etc got properly loaded.  If it
 340   // did not, it may attempt to throw an exception during our probing.  Catch
 341   // and ignore such exceptions and do not attempt to compile the method.
 342   if( callee_method->should_exclude() )  return false;
 343 
 344   return true;
 345 }
 346 
 347 #ifndef PRODUCT
 348 //------------------------------print_inlining---------------------------------
 349 // Really, the failure_msg can be a success message also.
 350 void InlineTree::print_inlining(ciMethod *callee_method, int caller_bci, const char *failure_msg) const {
 351   print_indent(inline_depth());
 352   tty->print("@ %d  ", caller_bci);
 353   if( callee_method ) callee_method->print_short_name();
 354   else                tty->print(" callee not monotonic or profiled");
 355   tty->print("  %s", (failure_msg ? failure_msg : "inline"));
 356   if( Verbose && callee_method ) {
 357     const InlineTree *top = this;
 358     while( top->caller_tree() != NULL ) { top = top->caller_tree(); }
 359     tty->print("  bcs: %d+%d  invoked: %d", top->count_inline_bcs(), callee_method->code_size(), callee_method->interpreter_invocation_count());
 360   }
 361   tty->cr();
 362 }
 363 #endif
 364 
 365 //------------------------------ok_to_inline-----------------------------------
 366 WarmCallInfo* InlineTree::ok_to_inline(ciMethod* callee_method, JVMState* jvms, ciCallProfile& profile, WarmCallInfo* initial_wci) {
 367   assert(callee_method != NULL, "caller checks for optimized virtual!");
 368 #ifdef ASSERT
 369   // Make sure the incoming jvms has the same information content as me.
 370   // This means that we can eventually make this whole class AllStatic.
 371   if (jvms->caller() == NULL) {
 372     assert(_caller_jvms == NULL, "redundant instance state");
 373   } else {
 374     assert(_caller_jvms->same_calls_as(jvms->caller()), "redundant instance state");
 375   }
 376   assert(_method == jvms->method(), "redundant instance state");
 377 #endif
 378   const char *failure_msg   = NULL;
 379   int         caller_bci    = jvms->bci();
 380   ciMethod   *caller_method = jvms->method();
 381 
 382   if( !pass_initial_checks(caller_method, caller_bci, callee_method)) {
 383     if( PrintInlining ) {
 384       failure_msg = "failed_initial_checks";
 385       print_inlining( callee_method, caller_bci, failure_msg);
 386     }
 387     return NULL;
 388   }
 389 
 390   // Check if inlining policy says no.
 391   WarmCallInfo wci = *(initial_wci);
 392   failure_msg = try_to_inline(callee_method, caller_method, caller_bci, profile, &wci);
 393   if (failure_msg != NULL && C->log() != NULL) {
 394     C->log()->begin_elem("inline_fail reason='");
 395     C->log()->text("%s", failure_msg);
 396     C->log()->end_elem("'");
 397   }
 398 
 399 #ifndef PRODUCT
 400   if (UseOldInlining && InlineWarmCalls
 401       && (PrintOpto || PrintOptoInlining || PrintInlining)) {
 402     bool cold = wci.is_cold();
 403     bool hot  = !cold && wci.is_hot();
 404     bool old_cold = (failure_msg != NULL);
 405     if (old_cold != cold || (Verbose || WizardMode)) {
 406       tty->print("   OldInlining= %4s : %s\n           WCI=",
 407                  old_cold ? "cold" : "hot", failure_msg ? failure_msg : "OK");
 408       wci.print();
 409     }
 410   }
 411 #endif
 412   if (UseOldInlining) {
 413     if (failure_msg == NULL)
 414       wci = *(WarmCallInfo::always_hot());
 415     else
 416       wci = *(WarmCallInfo::always_cold());
 417   }
 418   if (!InlineWarmCalls) {
 419     if (!wci.is_cold() && !wci.is_hot()) {
 420       // Do not inline the warm calls.
 421       wci = *(WarmCallInfo::always_cold());
 422     }
 423   }
 424 
 425   if (!wci.is_cold()) {
 426     // In -UseOldInlining, the failure_msg may also be a success message.
 427     if (failure_msg == NULL)  failure_msg = "inline (hot)";
 428 
 429     // Inline!
 430     if( PrintInlining ) print_inlining( callee_method, caller_bci, failure_msg);
 431     if (UseOldInlining)
 432       build_inline_tree_for_callee(callee_method, jvms, caller_bci);
 433     if (InlineWarmCalls && !wci.is_hot())
 434       return new (C) WarmCallInfo(wci);  // copy to heap
 435     return WarmCallInfo::always_hot();
 436   }
 437 
 438   // Do not inline
 439   if (failure_msg == NULL)  failure_msg = "too cold to inline";
 440   if( PrintInlining ) print_inlining( callee_method, caller_bci, failure_msg);
 441   return NULL;
 442 }
 443 
 444 //------------------------------compute_callee_frequency-----------------------
 445 float InlineTree::compute_callee_frequency( int caller_bci ) const {
 446   int count  = method()->interpreter_call_site_count(caller_bci);
 447   int invcnt = method()->interpreter_invocation_count();
 448   float freq = (float)count/(float)invcnt;
 449   // Call-site count / interpreter invocation count, scaled recursively.
 450   // Always between 0.0 and 1.0.  Represents the percentage of the method's
 451   // total execution time used at this call site.
 452 
 453   return freq;
 454 }
 455 
 456 //------------------------------build_inline_tree_for_callee-------------------
 457 InlineTree *InlineTree::build_inline_tree_for_callee( ciMethod* callee_method, JVMState* caller_jvms, int caller_bci) {
 458   float recur_frequency = _site_invoke_ratio * compute_callee_frequency(caller_bci);
 459   // Attempt inlining.
 460   InlineTree* old_ilt = callee_at(caller_bci, callee_method);
 461   if (old_ilt != NULL) {
 462     return old_ilt;
 463   }
 464   InlineTree *ilt = new InlineTree( C, this, callee_method, caller_jvms, caller_bci, recur_frequency );
 465   _subtrees.append( ilt );
 466 
 467   NOT_PRODUCT( _count_inlines += 1; )
 468 
 469   return ilt;
 470 }
 471 
 472 
 473 //---------------------------------------callee_at-----------------------------
 474 InlineTree *InlineTree::callee_at(int bci, ciMethod* callee) const {
 475   for (int i = 0; i < _subtrees.length(); i++) {
 476     InlineTree* sub = _subtrees.at(i);
 477     if (sub->caller_bci() == bci && callee == sub->method()) {
 478       return sub;
 479     }
 480   }
 481   return NULL;
 482 }
 483 
 484 
 485 //------------------------------build_inline_tree_root-------------------------
 486 InlineTree *InlineTree::build_inline_tree_root() {
 487   Compile* C = Compile::current();
 488 
 489   // Root of inline tree
 490   InlineTree *ilt = new InlineTree(C, NULL, C->method(), NULL, -1, 1.0F);
 491 
 492   return ilt;
 493 }
 494 
 495 
 496 //-------------------------find_subtree_from_root-----------------------------
 497 // Given a jvms, which determines a call chain from the root method,
 498 // find the corresponding inline tree.
 499 // Note: This method will be removed or replaced as InlineTree goes away.
 500 InlineTree* InlineTree::find_subtree_from_root(InlineTree* root, JVMState* jvms, ciMethod* callee, bool create_if_not_found) {
 501   InlineTree* iltp = root;
 502   uint depth = jvms && jvms->has_method() ? jvms->depth() : 0;
 503   for (uint d = 1; d <= depth; d++) {
 504     JVMState* jvmsp  = jvms->of_depth(d);
 505     // Select the corresponding subtree for this bci.
 506     assert(jvmsp->method() == iltp->method(), "tree still in sync");
 507     ciMethod* d_callee = (d == depth) ? callee : jvms->of_depth(d+1)->method();
 508     InlineTree* sub = iltp->callee_at(jvmsp->bci(), d_callee);
 509     if (!sub) {
 510       if (create_if_not_found && d == depth) {
 511         return iltp->build_inline_tree_for_callee(d_callee, jvmsp, jvmsp->bci());
 512       }
 513       assert(sub != NULL, "should be a sub-ilt here");
 514       return NULL;
 515     }
 516     iltp = sub;
 517   }
 518   return iltp;
 519 }
 520 
 521 // ----------------------------------------------------------------------------
 522 #ifndef PRODUCT
 523 
 524 static void per_method_stats() {
 525   // Compute difference between this method's cumulative totals and old totals
 526   int explicit_null_checks_cur = explicit_null_checks_inserted - explicit_null_checks_inserted_old;
 527   int elided_null_checks_cur = explicit_null_checks_elided - explicit_null_checks_elided_old;
 528 
 529   // Print differences
 530   if( explicit_null_checks_cur )
 531     tty->print_cr("XXX Explicit NULL checks inserted: %d", explicit_null_checks_cur);
 532   if( elided_null_checks_cur )
 533     tty->print_cr("XXX Explicit NULL checks removed at parse time: %d", elided_null_checks_cur);
 534 
 535   // Store the current cumulative totals
 536   nodes_created_old = nodes_created;
 537   methods_parsed_old = methods_parsed;
 538   methods_seen_old = methods_seen;
 539   explicit_null_checks_inserted_old = explicit_null_checks_inserted;
 540   explicit_null_checks_elided_old = explicit_null_checks_elided;
 541 }
 542 
 543 #endif