compile.cpp revision 196:d1605aabd0a1
1/*
2 * Copyright 1997-2008 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/_compile.cpp.incl"
27
28/// Support for intrinsics.
29
30// Return the index at which m must be inserted (or already exists).
31// The sort order is by the address of the ciMethod, with is_virtual as minor key.
32int Compile::intrinsic_insertion_index(ciMethod* m, bool is_virtual) {
33#ifdef ASSERT
34  for (int i = 1; i < _intrinsics->length(); i++) {
35    CallGenerator* cg1 = _intrinsics->at(i-1);
36    CallGenerator* cg2 = _intrinsics->at(i);
37    assert(cg1->method() != cg2->method()
38           ? cg1->method()     < cg2->method()
39           : cg1->is_virtual() < cg2->is_virtual(),
40           "compiler intrinsics list must stay sorted");
41  }
42#endif
43  // Binary search sorted list, in decreasing intervals [lo, hi].
44  int lo = 0, hi = _intrinsics->length()-1;
45  while (lo <= hi) {
46    int mid = (uint)(hi + lo) / 2;
47    ciMethod* mid_m = _intrinsics->at(mid)->method();
48    if (m < mid_m) {
49      hi = mid-1;
50    } else if (m > mid_m) {
51      lo = mid+1;
52    } else {
53      // look at minor sort key
54      bool mid_virt = _intrinsics->at(mid)->is_virtual();
55      if (is_virtual < mid_virt) {
56        hi = mid-1;
57      } else if (is_virtual > mid_virt) {
58        lo = mid+1;
59      } else {
60        return mid;  // exact match
61      }
62    }
63  }
64  return lo;  // inexact match
65}
66
67void Compile::register_intrinsic(CallGenerator* cg) {
68  if (_intrinsics == NULL) {
69    _intrinsics = new GrowableArray<CallGenerator*>(60);
70  }
71  // This code is stolen from ciObjectFactory::insert.
72  // Really, GrowableArray should have methods for
73  // insert_at, remove_at, and binary_search.
74  int len = _intrinsics->length();
75  int index = intrinsic_insertion_index(cg->method(), cg->is_virtual());
76  if (index == len) {
77    _intrinsics->append(cg);
78  } else {
79#ifdef ASSERT
80    CallGenerator* oldcg = _intrinsics->at(index);
81    assert(oldcg->method() != cg->method() || oldcg->is_virtual() != cg->is_virtual(), "don't register twice");
82#endif
83    _intrinsics->append(_intrinsics->at(len-1));
84    int pos;
85    for (pos = len-2; pos >= index; pos--) {
86      _intrinsics->at_put(pos+1,_intrinsics->at(pos));
87    }
88    _intrinsics->at_put(index, cg);
89  }
90  assert(find_intrinsic(cg->method(), cg->is_virtual()) == cg, "registration worked");
91}
92
93CallGenerator* Compile::find_intrinsic(ciMethod* m, bool is_virtual) {
94  assert(m->is_loaded(), "don't try this on unloaded methods");
95  if (_intrinsics != NULL) {
96    int index = intrinsic_insertion_index(m, is_virtual);
97    if (index < _intrinsics->length()
98        && _intrinsics->at(index)->method() == m
99        && _intrinsics->at(index)->is_virtual() == is_virtual) {
100      return _intrinsics->at(index);
101    }
102  }
103  // Lazily create intrinsics for intrinsic IDs well-known in the runtime.
104  if (m->intrinsic_id() != vmIntrinsics::_none) {
105    CallGenerator* cg = make_vm_intrinsic(m, is_virtual);
106    if (cg != NULL) {
107      // Save it for next time:
108      register_intrinsic(cg);
109      return cg;
110    } else {
111      gather_intrinsic_statistics(m->intrinsic_id(), is_virtual, _intrinsic_disabled);
112    }
113  }
114  return NULL;
115}
116
117// Compile:: register_library_intrinsics and make_vm_intrinsic are defined
118// in library_call.cpp.
119
120
121#ifndef PRODUCT
122// statistics gathering...
123
124juint  Compile::_intrinsic_hist_count[vmIntrinsics::ID_LIMIT] = {0};
125jubyte Compile::_intrinsic_hist_flags[vmIntrinsics::ID_LIMIT] = {0};
126
127bool Compile::gather_intrinsic_statistics(vmIntrinsics::ID id, bool is_virtual, int flags) {
128  assert(id > vmIntrinsics::_none && id < vmIntrinsics::ID_LIMIT, "oob");
129  int oflags = _intrinsic_hist_flags[id];
130  assert(flags != 0, "what happened?");
131  if (is_virtual) {
132    flags |= _intrinsic_virtual;
133  }
134  bool changed = (flags != oflags);
135  if ((flags & _intrinsic_worked) != 0) {
136    juint count = (_intrinsic_hist_count[id] += 1);
137    if (count == 1) {
138      changed = true;           // first time
139    }
140    // increment the overall count also:
141    _intrinsic_hist_count[vmIntrinsics::_none] += 1;
142  }
143  if (changed) {
144    if (((oflags ^ flags) & _intrinsic_virtual) != 0) {
145      // Something changed about the intrinsic's virtuality.
146      if ((flags & _intrinsic_virtual) != 0) {
147        // This is the first use of this intrinsic as a virtual call.
148        if (oflags != 0) {
149          // We already saw it as a non-virtual, so note both cases.
150          flags |= _intrinsic_both;
151        }
152      } else if ((oflags & _intrinsic_both) == 0) {
153        // This is the first use of this intrinsic as a non-virtual
154        flags |= _intrinsic_both;
155      }
156    }
157    _intrinsic_hist_flags[id] = (jubyte) (oflags | flags);
158  }
159  // update the overall flags also:
160  _intrinsic_hist_flags[vmIntrinsics::_none] |= (jubyte) flags;
161  return changed;
162}
163
164static char* format_flags(int flags, char* buf) {
165  buf[0] = 0;
166  if ((flags & Compile::_intrinsic_worked) != 0)    strcat(buf, ",worked");
167  if ((flags & Compile::_intrinsic_failed) != 0)    strcat(buf, ",failed");
168  if ((flags & Compile::_intrinsic_disabled) != 0)  strcat(buf, ",disabled");
169  if ((flags & Compile::_intrinsic_virtual) != 0)   strcat(buf, ",virtual");
170  if ((flags & Compile::_intrinsic_both) != 0)      strcat(buf, ",nonvirtual");
171  if (buf[0] == 0)  strcat(buf, ",");
172  assert(buf[0] == ',', "must be");
173  return &buf[1];
174}
175
176void Compile::print_intrinsic_statistics() {
177  char flagsbuf[100];
178  ttyLocker ttyl;
179  if (xtty != NULL)  xtty->head("statistics type='intrinsic'");
180  tty->print_cr("Compiler intrinsic usage:");
181  juint total = _intrinsic_hist_count[vmIntrinsics::_none];
182  if (total == 0)  total = 1;  // avoid div0 in case of no successes
183  #define PRINT_STAT_LINE(name, c, f) \
184    tty->print_cr("  %4d (%4.1f%%) %s (%s)", (int)(c), ((c) * 100.0) / total, name, f);
185  for (int index = 1 + (int)vmIntrinsics::_none; index < (int)vmIntrinsics::ID_LIMIT; index++) {
186    vmIntrinsics::ID id = (vmIntrinsics::ID) index;
187    int   flags = _intrinsic_hist_flags[id];
188    juint count = _intrinsic_hist_count[id];
189    if ((flags | count) != 0) {
190      PRINT_STAT_LINE(vmIntrinsics::name_at(id), count, format_flags(flags, flagsbuf));
191    }
192  }
193  PRINT_STAT_LINE("total", total, format_flags(_intrinsic_hist_flags[vmIntrinsics::_none], flagsbuf));
194  if (xtty != NULL)  xtty->tail("statistics");
195}
196
197void Compile::print_statistics() {
198  { ttyLocker ttyl;
199    if (xtty != NULL)  xtty->head("statistics type='opto'");
200    Parse::print_statistics();
201    PhaseCCP::print_statistics();
202    PhaseRegAlloc::print_statistics();
203    Scheduling::print_statistics();
204    PhasePeephole::print_statistics();
205    PhaseIdealLoop::print_statistics();
206    if (xtty != NULL)  xtty->tail("statistics");
207  }
208  if (_intrinsic_hist_flags[vmIntrinsics::_none] != 0) {
209    // put this under its own <statistics> element.
210    print_intrinsic_statistics();
211  }
212}
213#endif //PRODUCT
214
215// Support for bundling info
216Bundle* Compile::node_bundling(const Node *n) {
217  assert(valid_bundle_info(n), "oob");
218  return &_node_bundling_base[n->_idx];
219}
220
221bool Compile::valid_bundle_info(const Node *n) {
222  return (_node_bundling_limit > n->_idx);
223}
224
225
226// Identify all nodes that are reachable from below, useful.
227// Use breadth-first pass that records state in a Unique_Node_List,
228// recursive traversal is slower.
229void Compile::identify_useful_nodes(Unique_Node_List &useful) {
230  int estimated_worklist_size = unique();
231  useful.map( estimated_worklist_size, NULL );  // preallocate space
232
233  // Initialize worklist
234  if (root() != NULL)     { useful.push(root()); }
235  // If 'top' is cached, declare it useful to preserve cached node
236  if( cached_top_node() ) { useful.push(cached_top_node()); }
237
238  // Push all useful nodes onto the list, breadthfirst
239  for( uint next = 0; next < useful.size(); ++next ) {
240    assert( next < unique(), "Unique useful nodes < total nodes");
241    Node *n  = useful.at(next);
242    uint max = n->len();
243    for( uint i = 0; i < max; ++i ) {
244      Node *m = n->in(i);
245      if( m == NULL ) continue;
246      useful.push(m);
247    }
248  }
249}
250
251// Disconnect all useless nodes by disconnecting those at the boundary.
252void Compile::remove_useless_nodes(Unique_Node_List &useful) {
253  uint next = 0;
254  while( next < useful.size() ) {
255    Node *n = useful.at(next++);
256    // Use raw traversal of out edges since this code removes out edges
257    int max = n->outcnt();
258    for (int j = 0; j < max; ++j ) {
259      Node* child = n->raw_out(j);
260      if( ! useful.member(child) ) {
261        assert( !child->is_top() || child != top(),
262                "If top is cached in Compile object it is in useful list");
263        // Only need to remove this out-edge to the useless node
264        n->raw_del_out(j);
265        --j;
266        --max;
267      }
268    }
269    if (n->outcnt() == 1 && n->has_special_unique_user()) {
270      record_for_igvn( n->unique_out() );
271    }
272  }
273  debug_only(verify_graph_edges(true/*check for no_dead_code*/);)
274}
275
276//------------------------------frame_size_in_words-----------------------------
277// frame_slots in units of words
278int Compile::frame_size_in_words() const {
279  // shift is 0 in LP32 and 1 in LP64
280  const int shift = (LogBytesPerWord - LogBytesPerInt);
281  int words = _frame_slots >> shift;
282  assert( words << shift == _frame_slots, "frame size must be properly aligned in LP64" );
283  return words;
284}
285
286// ============================================================================
287//------------------------------CompileWrapper---------------------------------
288class CompileWrapper : public StackObj {
289  Compile *const _compile;
290 public:
291  CompileWrapper(Compile* compile);
292
293  ~CompileWrapper();
294};
295
296CompileWrapper::CompileWrapper(Compile* compile) : _compile(compile) {
297  // the Compile* pointer is stored in the current ciEnv:
298  ciEnv* env = compile->env();
299  assert(env == ciEnv::current(), "must already be a ciEnv active");
300  assert(env->compiler_data() == NULL, "compile already active?");
301  env->set_compiler_data(compile);
302  assert(compile == Compile::current(), "sanity");
303
304  compile->set_type_dict(NULL);
305  compile->set_type_hwm(NULL);
306  compile->set_type_last_size(0);
307  compile->set_last_tf(NULL, NULL);
308  compile->set_indexSet_arena(NULL);
309  compile->set_indexSet_free_block_list(NULL);
310  compile->init_type_arena();
311  Type::Initialize(compile);
312  _compile->set_scratch_buffer_blob(NULL);
313  _compile->begin_method();
314}
315CompileWrapper::~CompileWrapper() {
316  if (_compile->failing()) {
317    _compile->print_method("Failed");
318  }
319  _compile->end_method();
320  if (_compile->scratch_buffer_blob() != NULL)
321    BufferBlob::free(_compile->scratch_buffer_blob());
322  _compile->env()->set_compiler_data(NULL);
323}
324
325
326//----------------------------print_compile_messages---------------------------
327void Compile::print_compile_messages() {
328#ifndef PRODUCT
329  // Check if recompiling
330  if (_subsume_loads == false && PrintOpto) {
331    // Recompiling without allowing machine instructions to subsume loads
332    tty->print_cr("*********************************************************");
333    tty->print_cr("** Bailout: Recompile without subsuming loads          **");
334    tty->print_cr("*********************************************************");
335  }
336  if (_do_escape_analysis != DoEscapeAnalysis && PrintOpto) {
337    // Recompiling without escape analysis
338    tty->print_cr("*********************************************************");
339    tty->print_cr("** Bailout: Recompile without escape analysis          **");
340    tty->print_cr("*********************************************************");
341  }
342  if (env()->break_at_compile()) {
343    // Open the debugger when compiing this method.
344    tty->print("### Breaking when compiling: ");
345    method()->print_short_name();
346    tty->cr();
347    BREAKPOINT;
348  }
349
350  if( PrintOpto ) {
351    if (is_osr_compilation()) {
352      tty->print("[OSR]%3d", _compile_id);
353    } else {
354      tty->print("%3d", _compile_id);
355    }
356  }
357#endif
358}
359
360
361void Compile::init_scratch_buffer_blob() {
362  if( scratch_buffer_blob() != NULL )  return;
363
364  // Construct a temporary CodeBuffer to have it construct a BufferBlob
365  // Cache this BufferBlob for this compile.
366  ResourceMark rm;
367  int size = (MAX_inst_size + MAX_stubs_size + MAX_const_size);
368  BufferBlob* blob = BufferBlob::create("Compile::scratch_buffer", size);
369  // Record the buffer blob for next time.
370  set_scratch_buffer_blob(blob);
371  // Have we run out of code space?
372  if (scratch_buffer_blob() == NULL) {
373    // Let CompilerBroker disable further compilations.
374    record_failure("Not enough space for scratch buffer in CodeCache");
375    return;
376  }
377
378  // Initialize the relocation buffers
379  relocInfo* locs_buf = (relocInfo*) blob->instructions_end() - MAX_locs_size;
380  set_scratch_locs_memory(locs_buf);
381}
382
383
384//-----------------------scratch_emit_size-------------------------------------
385// Helper function that computes size by emitting code
386uint Compile::scratch_emit_size(const Node* n) {
387  // Emit into a trash buffer and count bytes emitted.
388  // This is a pretty expensive way to compute a size,
389  // but it works well enough if seldom used.
390  // All common fixed-size instructions are given a size
391  // method by the AD file.
392  // Note that the scratch buffer blob and locs memory are
393  // allocated at the beginning of the compile task, and
394  // may be shared by several calls to scratch_emit_size.
395  // The allocation of the scratch buffer blob is particularly
396  // expensive, since it has to grab the code cache lock.
397  BufferBlob* blob = this->scratch_buffer_blob();
398  assert(blob != NULL, "Initialize BufferBlob at start");
399  assert(blob->size() > MAX_inst_size, "sanity");
400  relocInfo* locs_buf = scratch_locs_memory();
401  address blob_begin = blob->instructions_begin();
402  address blob_end   = (address)locs_buf;
403  assert(blob->instructions_contains(blob_end), "sanity");
404  CodeBuffer buf(blob_begin, blob_end - blob_begin);
405  buf.initialize_consts_size(MAX_const_size);
406  buf.initialize_stubs_size(MAX_stubs_size);
407  assert(locs_buf != NULL, "sanity");
408  int lsize = MAX_locs_size / 2;
409  buf.insts()->initialize_shared_locs(&locs_buf[0],     lsize);
410  buf.stubs()->initialize_shared_locs(&locs_buf[lsize], lsize);
411  n->emit(buf, this->regalloc());
412  return buf.code_size();
413}
414
415
416// ============================================================================
417//------------------------------Compile standard-------------------------------
418debug_only( int Compile::_debug_idx = 100000; )
419
420// Compile a method.  entry_bci is -1 for normal compilations and indicates
421// the continuation bci for on stack replacement.
422
423
424Compile::Compile( ciEnv* ci_env, C2Compiler* compiler, ciMethod* target, int osr_bci, bool subsume_loads, bool do_escape_analysis )
425                : Phase(Compiler),
426                  _env(ci_env),
427                  _log(ci_env->log()),
428                  _compile_id(ci_env->compile_id()),
429                  _save_argument_registers(false),
430                  _stub_name(NULL),
431                  _stub_function(NULL),
432                  _stub_entry_point(NULL),
433                  _method(target),
434                  _entry_bci(osr_bci),
435                  _initial_gvn(NULL),
436                  _for_igvn(NULL),
437                  _warm_calls(NULL),
438                  _subsume_loads(subsume_loads),
439                  _do_escape_analysis(do_escape_analysis),
440                  _failure_reason(NULL),
441                  _code_buffer("Compile::Fill_buffer"),
442                  _orig_pc_slot(0),
443                  _orig_pc_slot_offset_in_bytes(0),
444                  _node_bundling_limit(0),
445                  _node_bundling_base(NULL),
446#ifndef PRODUCT
447                  _trace_opto_output(TraceOptoOutput || method()->has_option("TraceOptoOutput")),
448                  _printer(IdealGraphPrinter::printer()),
449#endif
450                  _congraph(NULL) {
451  C = this;
452
453  CompileWrapper cw(this);
454#ifndef PRODUCT
455  if (TimeCompiler2) {
456    tty->print(" ");
457    target->holder()->name()->print();
458    tty->print(".");
459    target->print_short_name();
460    tty->print("  ");
461  }
462  TraceTime t1("Total compilation time", &_t_totalCompilation, TimeCompiler, TimeCompiler2);
463  TraceTime t2(NULL, &_t_methodCompilation, TimeCompiler, false);
464  bool print_opto_assembly = PrintOptoAssembly || _method->has_option("PrintOptoAssembly");
465  if (!print_opto_assembly) {
466    bool print_assembly = (PrintAssembly || _method->should_print_assembly());
467    if (print_assembly && !Disassembler::can_decode()) {
468      tty->print_cr("PrintAssembly request changed to PrintOptoAssembly");
469      print_opto_assembly = true;
470    }
471  }
472  set_print_assembly(print_opto_assembly);
473#endif
474
475  if (ProfileTraps) {
476    // Make sure the method being compiled gets its own MDO,
477    // so we can at least track the decompile_count().
478    method()->build_method_data();
479  }
480
481  Init(::AliasLevel);
482
483
484  print_compile_messages();
485
486  if (UseOldInlining || PrintCompilation NOT_PRODUCT( || PrintOpto) )
487    _ilt = InlineTree::build_inline_tree_root();
488  else
489    _ilt = NULL;
490
491  // Even if NO memory addresses are used, MergeMem nodes must have at least 1 slice
492  assert(num_alias_types() >= AliasIdxRaw, "");
493
494#define MINIMUM_NODE_HASH  1023
495  // Node list that Iterative GVN will start with
496  Unique_Node_List for_igvn(comp_arena());
497  set_for_igvn(&for_igvn);
498
499  // GVN that will be run immediately on new nodes
500  uint estimated_size = method()->code_size()*4+64;
501  estimated_size = (estimated_size < MINIMUM_NODE_HASH ? MINIMUM_NODE_HASH : estimated_size);
502  PhaseGVN gvn(node_arena(), estimated_size);
503  set_initial_gvn(&gvn);
504
505  { // Scope for timing the parser
506    TracePhase t3("parse", &_t_parser, true);
507
508    // Put top into the hash table ASAP.
509    initial_gvn()->transform_no_reclaim(top());
510
511    // Set up tf(), start(), and find a CallGenerator.
512    CallGenerator* cg;
513    if (is_osr_compilation()) {
514      const TypeTuple *domain = StartOSRNode::osr_domain();
515      const TypeTuple *range = TypeTuple::make_range(method()->signature());
516      init_tf(TypeFunc::make(domain, range));
517      StartNode* s = new (this, 2) StartOSRNode(root(), domain);
518      initial_gvn()->set_type_bottom(s);
519      init_start(s);
520      cg = CallGenerator::for_osr(method(), entry_bci());
521    } else {
522      // Normal case.
523      init_tf(TypeFunc::make(method()));
524      StartNode* s = new (this, 2) StartNode(root(), tf()->domain());
525      initial_gvn()->set_type_bottom(s);
526      init_start(s);
527      float past_uses = method()->interpreter_invocation_count();
528      float expected_uses = past_uses;
529      cg = CallGenerator::for_inline(method(), expected_uses);
530    }
531    if (failing())  return;
532    if (cg == NULL) {
533      record_method_not_compilable_all_tiers("cannot parse method");
534      return;
535    }
536    JVMState* jvms = build_start_state(start(), tf());
537    if ((jvms = cg->generate(jvms)) == NULL) {
538      record_method_not_compilable("method parse failed");
539      return;
540    }
541    GraphKit kit(jvms);
542
543    if (!kit.stopped()) {
544      // Accept return values, and transfer control we know not where.
545      // This is done by a special, unique ReturnNode bound to root.
546      return_values(kit.jvms());
547    }
548
549    if (kit.has_exceptions()) {
550      // Any exceptions that escape from this call must be rethrown
551      // to whatever caller is dynamically above us on the stack.
552      // This is done by a special, unique RethrowNode bound to root.
553      rethrow_exceptions(kit.transfer_exceptions_into_jvms());
554    }
555
556    // Remove clutter produced by parsing.
557    if (!failing()) {
558      ResourceMark rm;
559      PhaseRemoveUseless pru(initial_gvn(), &for_igvn);
560    }
561  }
562
563  // Note:  Large methods are capped off in do_one_bytecode().
564  if (failing())  return;
565
566  // After parsing, node notes are no longer automagic.
567  // They must be propagated by register_new_node_with_optimizer(),
568  // clone(), or the like.
569  set_default_node_notes(NULL);
570
571  for (;;) {
572    int successes = Inline_Warm();
573    if (failing())  return;
574    if (successes == 0)  break;
575  }
576
577  // Drain the list.
578  Finish_Warm();
579#ifndef PRODUCT
580  if (_printer) {
581    _printer->print_inlining(this);
582  }
583#endif
584
585  if (failing())  return;
586  NOT_PRODUCT( verify_graph_edges(); )
587
588  // Perform escape analysis
589  if (_do_escape_analysis)
590    _congraph = new ConnectionGraph(this);
591  if (_congraph != NULL) {
592    NOT_PRODUCT( TracePhase t2("escapeAnalysis", &_t_escapeAnalysis, TimeCompiler); )
593    _congraph->compute_escape();
594    if (failing())  return;
595
596#ifndef PRODUCT
597    if (PrintEscapeAnalysis) {
598      _congraph->dump();
599    }
600#endif
601  }
602  // Now optimize
603  Optimize();
604  if (failing())  return;
605  NOT_PRODUCT( verify_graph_edges(); )
606
607#ifndef PRODUCT
608  if (PrintIdeal) {
609    ttyLocker ttyl;  // keep the following output all in one block
610    // This output goes directly to the tty, not the compiler log.
611    // To enable tools to match it up with the compilation activity,
612    // be sure to tag this tty output with the compile ID.
613    if (xtty != NULL) {
614      xtty->head("ideal compile_id='%d'%s", compile_id(),
615                 is_osr_compilation()    ? " compile_kind='osr'" :
616                 "");
617    }
618    root()->dump(9999);
619    if (xtty != NULL) {
620      xtty->tail("ideal");
621    }
622  }
623#endif
624
625  // Now that we know the size of all the monitors we can add a fixed slot
626  // for the original deopt pc.
627
628  _orig_pc_slot =  fixed_slots();
629  int next_slot = _orig_pc_slot + (sizeof(address) / VMRegImpl::stack_slot_size);
630  set_fixed_slots(next_slot);
631
632  // Now generate code
633  Code_Gen();
634  if (failing())  return;
635
636  // Check if we want to skip execution of all compiled code.
637  {
638#ifndef PRODUCT
639    if (OptoNoExecute) {
640      record_method_not_compilable("+OptoNoExecute");  // Flag as failed
641      return;
642    }
643    TracePhase t2("install_code", &_t_registerMethod, TimeCompiler);
644#endif
645
646    if (is_osr_compilation()) {
647      _code_offsets.set_value(CodeOffsets::Verified_Entry, 0);
648      _code_offsets.set_value(CodeOffsets::OSR_Entry, _first_block_size);
649    } else {
650      _code_offsets.set_value(CodeOffsets::Verified_Entry, _first_block_size);
651      _code_offsets.set_value(CodeOffsets::OSR_Entry, 0);
652    }
653
654    env()->register_method(_method, _entry_bci,
655                           &_code_offsets,
656                           _orig_pc_slot_offset_in_bytes,
657                           code_buffer(),
658                           frame_size_in_words(), _oop_map_set,
659                           &_handler_table, &_inc_table,
660                           compiler,
661                           env()->comp_level(),
662                           true, /*has_debug_info*/
663                           has_unsafe_access()
664                           );
665  }
666}
667
668//------------------------------Compile----------------------------------------
669// Compile a runtime stub
670Compile::Compile( ciEnv* ci_env,
671                  TypeFunc_generator generator,
672                  address stub_function,
673                  const char *stub_name,
674                  int is_fancy_jump,
675                  bool pass_tls,
676                  bool save_arg_registers,
677                  bool return_pc )
678  : Phase(Compiler),
679    _env(ci_env),
680    _log(ci_env->log()),
681    _compile_id(-1),
682    _save_argument_registers(save_arg_registers),
683    _method(NULL),
684    _stub_name(stub_name),
685    _stub_function(stub_function),
686    _stub_entry_point(NULL),
687    _entry_bci(InvocationEntryBci),
688    _initial_gvn(NULL),
689    _for_igvn(NULL),
690    _warm_calls(NULL),
691    _orig_pc_slot(0),
692    _orig_pc_slot_offset_in_bytes(0),
693    _subsume_loads(true),
694    _do_escape_analysis(false),
695    _failure_reason(NULL),
696    _code_buffer("Compile::Fill_buffer"),
697    _node_bundling_limit(0),
698    _node_bundling_base(NULL),
699#ifndef PRODUCT
700    _trace_opto_output(TraceOptoOutput),
701    _printer(NULL),
702#endif
703    _congraph(NULL) {
704  C = this;
705
706#ifndef PRODUCT
707  TraceTime t1(NULL, &_t_totalCompilation, TimeCompiler, false);
708  TraceTime t2(NULL, &_t_stubCompilation, TimeCompiler, false);
709  set_print_assembly(PrintFrameConverterAssembly);
710#endif
711  CompileWrapper cw(this);
712  Init(/*AliasLevel=*/ 0);
713  init_tf((*generator)());
714
715  {
716    // The following is a dummy for the sake of GraphKit::gen_stub
717    Unique_Node_List for_igvn(comp_arena());
718    set_for_igvn(&for_igvn);  // not used, but some GraphKit guys push on this
719    PhaseGVN gvn(Thread::current()->resource_area(),255);
720    set_initial_gvn(&gvn);    // not significant, but GraphKit guys use it pervasively
721    gvn.transform_no_reclaim(top());
722
723    GraphKit kit;
724    kit.gen_stub(stub_function, stub_name, is_fancy_jump, pass_tls, return_pc);
725  }
726
727  NOT_PRODUCT( verify_graph_edges(); )
728  Code_Gen();
729  if (failing())  return;
730
731
732  // Entry point will be accessed using compile->stub_entry_point();
733  if (code_buffer() == NULL) {
734    Matcher::soft_match_failure();
735  } else {
736    if (PrintAssembly && (WizardMode || Verbose))
737      tty->print_cr("### Stub::%s", stub_name);
738
739    if (!failing()) {
740      assert(_fixed_slots == 0, "no fixed slots used for runtime stubs");
741
742      // Make the NMethod
743      // For now we mark the frame as never safe for profile stackwalking
744      RuntimeStub *rs = RuntimeStub::new_runtime_stub(stub_name,
745                                                      code_buffer(),
746                                                      CodeOffsets::frame_never_safe,
747                                                      // _code_offsets.value(CodeOffsets::Frame_Complete),
748                                                      frame_size_in_words(),
749                                                      _oop_map_set,
750                                                      save_arg_registers);
751      assert(rs != NULL && rs->is_runtime_stub(), "sanity check");
752
753      _stub_entry_point = rs->entry_point();
754    }
755  }
756}
757
758#ifndef PRODUCT
759void print_opto_verbose_signature( const TypeFunc *j_sig, const char *stub_name ) {
760  if(PrintOpto && Verbose) {
761    tty->print("%s   ", stub_name); j_sig->print_flattened(); tty->cr();
762  }
763}
764#endif
765
766void Compile::print_codes() {
767}
768
769//------------------------------Init-------------------------------------------
770// Prepare for a single compilation
771void Compile::Init(int aliaslevel) {
772  _unique  = 0;
773  _regalloc = NULL;
774
775  _tf      = NULL;  // filled in later
776  _top     = NULL;  // cached later
777  _matcher = NULL;  // filled in later
778  _cfg     = NULL;  // filled in later
779
780  set_24_bit_selection_and_mode(Use24BitFP, false);
781
782  _node_note_array = NULL;
783  _default_node_notes = NULL;
784
785  _immutable_memory = NULL; // filled in at first inquiry
786
787  // Globally visible Nodes
788  // First set TOP to NULL to give safe behavior during creation of RootNode
789  set_cached_top_node(NULL);
790  set_root(new (this, 3) RootNode());
791  // Now that you have a Root to point to, create the real TOP
792  set_cached_top_node( new (this, 1) ConNode(Type::TOP) );
793  set_recent_alloc(NULL, NULL);
794
795  // Create Debug Information Recorder to record scopes, oopmaps, etc.
796  env()->set_oop_recorder(new OopRecorder(comp_arena()));
797  env()->set_debug_info(new DebugInformationRecorder(env()->oop_recorder()));
798  env()->set_dependencies(new Dependencies(env()));
799
800  _fixed_slots = 0;
801  set_has_split_ifs(false);
802  set_has_loops(has_method() && method()->has_loops()); // first approximation
803  _deopt_happens = true;  // start out assuming the worst
804  _trap_can_recompile = false;  // no traps emitted yet
805  _major_progress = true; // start out assuming good things will happen
806  set_has_unsafe_access(false);
807  Copy::zero_to_bytes(_trap_hist, sizeof(_trap_hist));
808  set_decompile_count(0);
809
810  // Compilation level related initialization
811  if (env()->comp_level() == CompLevel_fast_compile) {
812    set_num_loop_opts(Tier1LoopOptsCount);
813    set_do_inlining(Tier1Inline != 0);
814    set_max_inline_size(Tier1MaxInlineSize);
815    set_freq_inline_size(Tier1FreqInlineSize);
816    set_do_scheduling(false);
817    set_do_count_invocations(Tier1CountInvocations);
818    set_do_method_data_update(Tier1UpdateMethodData);
819  } else {
820    assert(env()->comp_level() == CompLevel_full_optimization, "unknown comp level");
821    set_num_loop_opts(LoopOptsCount);
822    set_do_inlining(Inline);
823    set_max_inline_size(MaxInlineSize);
824    set_freq_inline_size(FreqInlineSize);
825    set_do_scheduling(OptoScheduling);
826    set_do_count_invocations(false);
827    set_do_method_data_update(false);
828  }
829
830  if (debug_info()->recording_non_safepoints()) {
831    set_node_note_array(new(comp_arena()) GrowableArray<Node_Notes*>
832                        (comp_arena(), 8, 0, NULL));
833    set_default_node_notes(Node_Notes::make(this));
834  }
835
836  // // -- Initialize types before each compile --
837  // // Update cached type information
838  // if( _method && _method->constants() )
839  //   Type::update_loaded_types(_method, _method->constants());
840
841  // Init alias_type map.
842  if (!_do_escape_analysis && aliaslevel == 3)
843    aliaslevel = 2;  // No unique types without escape analysis
844  _AliasLevel = aliaslevel;
845  const int grow_ats = 16;
846  _max_alias_types = grow_ats;
847  _alias_types   = NEW_ARENA_ARRAY(comp_arena(), AliasType*, grow_ats);
848  AliasType* ats = NEW_ARENA_ARRAY(comp_arena(), AliasType,  grow_ats);
849  Copy::zero_to_bytes(ats, sizeof(AliasType)*grow_ats);
850  {
851    for (int i = 0; i < grow_ats; i++)  _alias_types[i] = &ats[i];
852  }
853  // Initialize the first few types.
854  _alias_types[AliasIdxTop]->Init(AliasIdxTop, NULL);
855  _alias_types[AliasIdxBot]->Init(AliasIdxBot, TypePtr::BOTTOM);
856  _alias_types[AliasIdxRaw]->Init(AliasIdxRaw, TypeRawPtr::BOTTOM);
857  _num_alias_types = AliasIdxRaw+1;
858  // Zero out the alias type cache.
859  Copy::zero_to_bytes(_alias_cache, sizeof(_alias_cache));
860  // A NULL adr_type hits in the cache right away.  Preload the right answer.
861  probe_alias_cache(NULL)->_index = AliasIdxTop;
862
863  _intrinsics = NULL;
864  _macro_nodes = new GrowableArray<Node*>(comp_arena(), 8,  0, NULL);
865  register_library_intrinsics();
866}
867
868//---------------------------init_start----------------------------------------
869// Install the StartNode on this compile object.
870void Compile::init_start(StartNode* s) {
871  if (failing())
872    return; // already failing
873  assert(s == start(), "");
874}
875
876StartNode* Compile::start() const {
877  assert(!failing(), "");
878  for (DUIterator_Fast imax, i = root()->fast_outs(imax); i < imax; i++) {
879    Node* start = root()->fast_out(i);
880    if( start->is_Start() )
881      return start->as_Start();
882  }
883  ShouldNotReachHere();
884  return NULL;
885}
886
887//-------------------------------immutable_memory-------------------------------------
888// Access immutable memory
889Node* Compile::immutable_memory() {
890  if (_immutable_memory != NULL) {
891    return _immutable_memory;
892  }
893  StartNode* s = start();
894  for (DUIterator_Fast imax, i = s->fast_outs(imax); true; i++) {
895    Node *p = s->fast_out(i);
896    if (p != s && p->as_Proj()->_con == TypeFunc::Memory) {
897      _immutable_memory = p;
898      return _immutable_memory;
899    }
900  }
901  ShouldNotReachHere();
902  return NULL;
903}
904
905//----------------------set_cached_top_node------------------------------------
906// Install the cached top node, and make sure Node::is_top works correctly.
907void Compile::set_cached_top_node(Node* tn) {
908  if (tn != NULL)  verify_top(tn);
909  Node* old_top = _top;
910  _top = tn;
911  // Calling Node::setup_is_top allows the nodes the chance to adjust
912  // their _out arrays.
913  if (_top != NULL)     _top->setup_is_top();
914  if (old_top != NULL)  old_top->setup_is_top();
915  assert(_top == NULL || top()->is_top(), "");
916}
917
918#ifndef PRODUCT
919void Compile::verify_top(Node* tn) const {
920  if (tn != NULL) {
921    assert(tn->is_Con(), "top node must be a constant");
922    assert(((ConNode*)tn)->type() == Type::TOP, "top node must have correct type");
923    assert(tn->in(0) != NULL, "must have live top node");
924  }
925}
926#endif
927
928
929///-------------------Managing Per-Node Debug & Profile Info-------------------
930
931void Compile::grow_node_notes(GrowableArray<Node_Notes*>* arr, int grow_by) {
932  guarantee(arr != NULL, "");
933  int num_blocks = arr->length();
934  if (grow_by < num_blocks)  grow_by = num_blocks;
935  int num_notes = grow_by * _node_notes_block_size;
936  Node_Notes* notes = NEW_ARENA_ARRAY(node_arena(), Node_Notes, num_notes);
937  Copy::zero_to_bytes(notes, num_notes * sizeof(Node_Notes));
938  while (num_notes > 0) {
939    arr->append(notes);
940    notes     += _node_notes_block_size;
941    num_notes -= _node_notes_block_size;
942  }
943  assert(num_notes == 0, "exact multiple, please");
944}
945
946bool Compile::copy_node_notes_to(Node* dest, Node* source) {
947  if (source == NULL || dest == NULL)  return false;
948
949  if (dest->is_Con())
950    return false;               // Do not push debug info onto constants.
951
952#ifdef ASSERT
953  // Leave a bread crumb trail pointing to the original node:
954  if (dest != NULL && dest != source && dest->debug_orig() == NULL) {
955    dest->set_debug_orig(source);
956  }
957#endif
958
959  if (node_note_array() == NULL)
960    return false;               // Not collecting any notes now.
961
962  // This is a copy onto a pre-existing node, which may already have notes.
963  // If both nodes have notes, do not overwrite any pre-existing notes.
964  Node_Notes* source_notes = node_notes_at(source->_idx);
965  if (source_notes == NULL || source_notes->is_clear())  return false;
966  Node_Notes* dest_notes   = node_notes_at(dest->_idx);
967  if (dest_notes == NULL || dest_notes->is_clear()) {
968    return set_node_notes_at(dest->_idx, source_notes);
969  }
970
971  Node_Notes merged_notes = (*source_notes);
972  // The order of operations here ensures that dest notes will win...
973  merged_notes.update_from(dest_notes);
974  return set_node_notes_at(dest->_idx, &merged_notes);
975}
976
977
978//--------------------------allow_range_check_smearing-------------------------
979// Gating condition for coalescing similar range checks.
980// Sometimes we try 'speculatively' replacing a series of a range checks by a
981// single covering check that is at least as strong as any of them.
982// If the optimization succeeds, the simplified (strengthened) range check
983// will always succeed.  If it fails, we will deopt, and then give up
984// on the optimization.
985bool Compile::allow_range_check_smearing() const {
986  // If this method has already thrown a range-check,
987  // assume it was because we already tried range smearing
988  // and it failed.
989  uint already_trapped = trap_count(Deoptimization::Reason_range_check);
990  return !already_trapped;
991}
992
993
994//------------------------------flatten_alias_type-----------------------------
995const TypePtr *Compile::flatten_alias_type( const TypePtr *tj ) const {
996  int offset = tj->offset();
997  TypePtr::PTR ptr = tj->ptr();
998
999  // Process weird unsafe references.
1000  if (offset == Type::OffsetBot && (tj->isa_instptr() /*|| tj->isa_klassptr()*/)) {
1001    assert(InlineUnsafeOps, "indeterminate pointers come only from unsafe ops");
1002    tj = TypeOopPtr::BOTTOM;
1003    ptr = tj->ptr();
1004    offset = tj->offset();
1005  }
1006
1007  // Array pointers need some flattening
1008  const TypeAryPtr *ta = tj->isa_aryptr();
1009  if( ta && _AliasLevel >= 2 ) {
1010    // For arrays indexed by constant indices, we flatten the alias
1011    // space to include all of the array body.  Only the header, klass
1012    // and array length can be accessed un-aliased.
1013    if( offset != Type::OffsetBot ) {
1014      if( ta->const_oop() ) { // methodDataOop or methodOop
1015        offset = Type::OffsetBot;   // Flatten constant access into array body
1016        tj = ta = TypeAryPtr::make(ptr,ta->const_oop(),ta->ary(),ta->klass(),false,Type::OffsetBot, ta->instance_id());
1017      } else if( offset == arrayOopDesc::length_offset_in_bytes() ) {
1018        // range is OK as-is.
1019        tj = ta = TypeAryPtr::RANGE;
1020      } else if( offset == oopDesc::klass_offset_in_bytes() ) {
1021        tj = TypeInstPtr::KLASS; // all klass loads look alike
1022        ta = TypeAryPtr::RANGE; // generic ignored junk
1023        ptr = TypePtr::BotPTR;
1024      } else if( offset == oopDesc::mark_offset_in_bytes() ) {
1025        tj = TypeInstPtr::MARK;
1026        ta = TypeAryPtr::RANGE; // generic ignored junk
1027        ptr = TypePtr::BotPTR;
1028      } else {                  // Random constant offset into array body
1029        offset = Type::OffsetBot;   // Flatten constant access into array body
1030        tj = ta = TypeAryPtr::make(ptr,ta->ary(),ta->klass(),false,Type::OffsetBot, ta->instance_id());
1031      }
1032    }
1033    // Arrays of fixed size alias with arrays of unknown size.
1034    if (ta->size() != TypeInt::POS) {
1035      const TypeAry *tary = TypeAry::make(ta->elem(), TypeInt::POS);
1036      tj = ta = TypeAryPtr::make(ptr,ta->const_oop(),tary,ta->klass(),false,offset, ta->instance_id());
1037    }
1038    // Arrays of known objects become arrays of unknown objects.
1039    if (ta->elem()->isa_narrowoop() && ta->elem() != TypeNarrowOop::BOTTOM) {
1040      const TypeAry *tary = TypeAry::make(TypeNarrowOop::BOTTOM, ta->size());
1041      tj = ta = TypeAryPtr::make(ptr,ta->const_oop(),tary,NULL,false,offset, ta->instance_id());
1042    }
1043    if (ta->elem()->isa_oopptr() && ta->elem() != TypeInstPtr::BOTTOM) {
1044      const TypeAry *tary = TypeAry::make(TypeInstPtr::BOTTOM, ta->size());
1045      tj = ta = TypeAryPtr::make(ptr,ta->const_oop(),tary,NULL,false,offset, ta->instance_id());
1046    }
1047    // Arrays of bytes and of booleans both use 'bastore' and 'baload' so
1048    // cannot be distinguished by bytecode alone.
1049    if (ta->elem() == TypeInt::BOOL) {
1050      const TypeAry *tary = TypeAry::make(TypeInt::BYTE, ta->size());
1051      ciKlass* aklass = ciTypeArrayKlass::make(T_BYTE);
1052      tj = ta = TypeAryPtr::make(ptr,ta->const_oop(),tary,aklass,false,offset, ta->instance_id());
1053    }
1054    // During the 2nd round of IterGVN, NotNull castings are removed.
1055    // Make sure the Bottom and NotNull variants alias the same.
1056    // Also, make sure exact and non-exact variants alias the same.
1057    if( ptr == TypePtr::NotNull || ta->klass_is_exact() ) {
1058      if (ta->const_oop()) {
1059        tj = ta = TypeAryPtr::make(TypePtr::Constant,ta->const_oop(),ta->ary(),ta->klass(),false,offset);
1060      } else {
1061        tj = ta = TypeAryPtr::make(TypePtr::BotPTR,ta->ary(),ta->klass(),false,offset);
1062      }
1063    }
1064  }
1065
1066  // Oop pointers need some flattening
1067  const TypeInstPtr *to = tj->isa_instptr();
1068  if( to && _AliasLevel >= 2 && to != TypeOopPtr::BOTTOM ) {
1069    if( ptr == TypePtr::Constant ) {
1070      // No constant oop pointers (such as Strings); they alias with
1071      // unknown strings.
1072      tj = to = TypeInstPtr::make(TypePtr::BotPTR,to->klass(),false,0,offset);
1073    } else if( to->is_instance_field() ) {
1074      tj = to; // Keep NotNull and klass_is_exact for instance type
1075    } else if( ptr == TypePtr::NotNull || to->klass_is_exact() ) {
1076      // During the 2nd round of IterGVN, NotNull castings are removed.
1077      // Make sure the Bottom and NotNull variants alias the same.
1078      // Also, make sure exact and non-exact variants alias the same.
1079      tj = to = TypeInstPtr::make(TypePtr::BotPTR,to->klass(),false,0,offset, to->instance_id());
1080    }
1081    // Canonicalize the holder of this field
1082    ciInstanceKlass *k = to->klass()->as_instance_klass();
1083    if (offset >= 0 && offset < instanceOopDesc::base_offset_in_bytes()) {
1084      // First handle header references such as a LoadKlassNode, even if the
1085      // object's klass is unloaded at compile time (4965979).
1086      tj = to = TypeInstPtr::make(TypePtr::BotPTR, env()->Object_klass(), false, NULL, offset, to->instance_id());
1087    } else if (offset < 0 || offset >= k->size_helper() * wordSize) {
1088      to = NULL;
1089      tj = TypeOopPtr::BOTTOM;
1090      offset = tj->offset();
1091    } else {
1092      ciInstanceKlass *canonical_holder = k->get_canonical_holder(offset);
1093      if (!k->equals(canonical_holder) || tj->offset() != offset) {
1094        tj = to = TypeInstPtr::make(to->ptr(), canonical_holder, false, NULL, offset, to->instance_id());
1095      }
1096    }
1097  }
1098
1099  // Klass pointers to object array klasses need some flattening
1100  const TypeKlassPtr *tk = tj->isa_klassptr();
1101  if( tk ) {
1102    // If we are referencing a field within a Klass, we need
1103    // to assume the worst case of an Object.  Both exact and
1104    // inexact types must flatten to the same alias class.
1105    // Since the flattened result for a klass is defined to be
1106    // precisely java.lang.Object, use a constant ptr.
1107    if ( offset == Type::OffsetBot || (offset >= 0 && (size_t)offset < sizeof(Klass)) ) {
1108
1109      tj = tk = TypeKlassPtr::make(TypePtr::Constant,
1110                                   TypeKlassPtr::OBJECT->klass(),
1111                                   offset);
1112    }
1113
1114    ciKlass* klass = tk->klass();
1115    if( klass->is_obj_array_klass() ) {
1116      ciKlass* k = TypeAryPtr::OOPS->klass();
1117      if( !k || !k->is_loaded() )                  // Only fails for some -Xcomp runs
1118        k = TypeInstPtr::BOTTOM->klass();
1119      tj = tk = TypeKlassPtr::make( TypePtr::NotNull, k, offset );
1120    }
1121
1122    // Check for precise loads from the primary supertype array and force them
1123    // to the supertype cache alias index.  Check for generic array loads from
1124    // the primary supertype array and also force them to the supertype cache
1125    // alias index.  Since the same load can reach both, we need to merge
1126    // these 2 disparate memories into the same alias class.  Since the
1127    // primary supertype array is read-only, there's no chance of confusion
1128    // where we bypass an array load and an array store.
1129    uint off2 = offset - Klass::primary_supers_offset_in_bytes();
1130    if( offset == Type::OffsetBot ||
1131        off2 < Klass::primary_super_limit()*wordSize ) {
1132      offset = sizeof(oopDesc) +Klass::secondary_super_cache_offset_in_bytes();
1133      tj = tk = TypeKlassPtr::make( TypePtr::NotNull, tk->klass(), offset );
1134    }
1135  }
1136
1137  // Flatten all Raw pointers together.
1138  if (tj->base() == Type::RawPtr)
1139    tj = TypeRawPtr::BOTTOM;
1140
1141  if (tj->base() == Type::AnyPtr)
1142    tj = TypePtr::BOTTOM;      // An error, which the caller must check for.
1143
1144  // Flatten all to bottom for now
1145  switch( _AliasLevel ) {
1146  case 0:
1147    tj = TypePtr::BOTTOM;
1148    break;
1149  case 1:                       // Flatten to: oop, static, field or array
1150    switch (tj->base()) {
1151    //case Type::AryPtr: tj = TypeAryPtr::RANGE;    break;
1152    case Type::RawPtr:   tj = TypeRawPtr::BOTTOM;   break;
1153    case Type::AryPtr:   // do not distinguish arrays at all
1154    case Type::InstPtr:  tj = TypeInstPtr::BOTTOM;  break;
1155    case Type::KlassPtr: tj = TypeKlassPtr::OBJECT; break;
1156    case Type::AnyPtr:   tj = TypePtr::BOTTOM;      break;  // caller checks it
1157    default: ShouldNotReachHere();
1158    }
1159    break;
1160  case 2:                       // No collasping at level 2; keep all splits
1161  case 3:                       // No collasping at level 3; keep all splits
1162    break;
1163  default:
1164    Unimplemented();
1165  }
1166
1167  offset = tj->offset();
1168  assert( offset != Type::OffsetTop, "Offset has fallen from constant" );
1169
1170  assert( (offset != Type::OffsetBot && tj->base() != Type::AryPtr) ||
1171          (offset == Type::OffsetBot && tj->base() == Type::AryPtr) ||
1172          (offset == Type::OffsetBot && tj == TypeOopPtr::BOTTOM) ||
1173          (offset == Type::OffsetBot && tj == TypePtr::BOTTOM) ||
1174          (offset == oopDesc::mark_offset_in_bytes() && tj->base() == Type::AryPtr) ||
1175          (offset == oopDesc::klass_offset_in_bytes() && tj->base() == Type::AryPtr) ||
1176          (offset == arrayOopDesc::length_offset_in_bytes() && tj->base() == Type::AryPtr)  ,
1177          "For oops, klasses, raw offset must be constant; for arrays the offset is never known" );
1178  assert( tj->ptr() != TypePtr::TopPTR &&
1179          tj->ptr() != TypePtr::AnyNull &&
1180          tj->ptr() != TypePtr::Null, "No imprecise addresses" );
1181//    assert( tj->ptr() != TypePtr::Constant ||
1182//            tj->base() == Type::RawPtr ||
1183//            tj->base() == Type::KlassPtr, "No constant oop addresses" );
1184
1185  return tj;
1186}
1187
1188void Compile::AliasType::Init(int i, const TypePtr* at) {
1189  _index = i;
1190  _adr_type = at;
1191  _field = NULL;
1192  _is_rewritable = true; // default
1193  const TypeOopPtr *atoop = (at != NULL) ? at->isa_oopptr() : NULL;
1194  if (atoop != NULL && atoop->is_instance()) {
1195    const TypeOopPtr *gt = atoop->cast_to_instance(TypeOopPtr::UNKNOWN_INSTANCE);
1196    _general_index = Compile::current()->get_alias_index(gt);
1197  } else {
1198    _general_index = 0;
1199  }
1200}
1201
1202//---------------------------------print_on------------------------------------
1203#ifndef PRODUCT
1204void Compile::AliasType::print_on(outputStream* st) {
1205  if (index() < 10)
1206        st->print("@ <%d> ", index());
1207  else  st->print("@ <%d>",  index());
1208  st->print(is_rewritable() ? "   " : " RO");
1209  int offset = adr_type()->offset();
1210  if (offset == Type::OffsetBot)
1211        st->print(" +any");
1212  else  st->print(" +%-3d", offset);
1213  st->print(" in ");
1214  adr_type()->dump_on(st);
1215  const TypeOopPtr* tjp = adr_type()->isa_oopptr();
1216  if (field() != NULL && tjp) {
1217    if (tjp->klass()  != field()->holder() ||
1218        tjp->offset() != field()->offset_in_bytes()) {
1219      st->print(" != ");
1220      field()->print();
1221      st->print(" ***");
1222    }
1223  }
1224}
1225
1226void print_alias_types() {
1227  Compile* C = Compile::current();
1228  tty->print_cr("--- Alias types, AliasIdxBot .. %d", C->num_alias_types()-1);
1229  for (int idx = Compile::AliasIdxBot; idx < C->num_alias_types(); idx++) {
1230    C->alias_type(idx)->print_on(tty);
1231    tty->cr();
1232  }
1233}
1234#endif
1235
1236
1237//----------------------------probe_alias_cache--------------------------------
1238Compile::AliasCacheEntry* Compile::probe_alias_cache(const TypePtr* adr_type) {
1239  intptr_t key = (intptr_t) adr_type;
1240  key ^= key >> logAliasCacheSize;
1241  return &_alias_cache[key & right_n_bits(logAliasCacheSize)];
1242}
1243
1244
1245//-----------------------------grow_alias_types--------------------------------
1246void Compile::grow_alias_types() {
1247  const int old_ats  = _max_alias_types; // how many before?
1248  const int new_ats  = old_ats;          // how many more?
1249  const int grow_ats = old_ats+new_ats;  // how many now?
1250  _max_alias_types = grow_ats;
1251  _alias_types =  REALLOC_ARENA_ARRAY(comp_arena(), AliasType*, _alias_types, old_ats, grow_ats);
1252  AliasType* ats =    NEW_ARENA_ARRAY(comp_arena(), AliasType, new_ats);
1253  Copy::zero_to_bytes(ats, sizeof(AliasType)*new_ats);
1254  for (int i = 0; i < new_ats; i++)  _alias_types[old_ats+i] = &ats[i];
1255}
1256
1257
1258//--------------------------------find_alias_type------------------------------
1259Compile::AliasType* Compile::find_alias_type(const TypePtr* adr_type, bool no_create) {
1260  if (_AliasLevel == 0)
1261    return alias_type(AliasIdxBot);
1262
1263  AliasCacheEntry* ace = probe_alias_cache(adr_type);
1264  if (ace->_adr_type == adr_type) {
1265    return alias_type(ace->_index);
1266  }
1267
1268  // Handle special cases.
1269  if (adr_type == NULL)             return alias_type(AliasIdxTop);
1270  if (adr_type == TypePtr::BOTTOM)  return alias_type(AliasIdxBot);
1271
1272  // Do it the slow way.
1273  const TypePtr* flat = flatten_alias_type(adr_type);
1274
1275#ifdef ASSERT
1276  assert(flat == flatten_alias_type(flat), "idempotent");
1277  assert(flat != TypePtr::BOTTOM,     "cannot alias-analyze an untyped ptr");
1278  if (flat->isa_oopptr() && !flat->isa_klassptr()) {
1279    const TypeOopPtr* foop = flat->is_oopptr();
1280    const TypePtr* xoop = foop->cast_to_exactness(!foop->klass_is_exact())->is_ptr();
1281    assert(foop == flatten_alias_type(xoop), "exactness must not affect alias type");
1282  }
1283  assert(flat == flatten_alias_type(flat), "exact bit doesn't matter");
1284#endif
1285
1286  int idx = AliasIdxTop;
1287  for (int i = 0; i < num_alias_types(); i++) {
1288    if (alias_type(i)->adr_type() == flat) {
1289      idx = i;
1290      break;
1291    }
1292  }
1293
1294  if (idx == AliasIdxTop) {
1295    if (no_create)  return NULL;
1296    // Grow the array if necessary.
1297    if (_num_alias_types == _max_alias_types)  grow_alias_types();
1298    // Add a new alias type.
1299    idx = _num_alias_types++;
1300    _alias_types[idx]->Init(idx, flat);
1301    if (flat == TypeInstPtr::KLASS)  alias_type(idx)->set_rewritable(false);
1302    if (flat == TypeAryPtr::RANGE)   alias_type(idx)->set_rewritable(false);
1303    if (flat->isa_instptr()) {
1304      if (flat->offset() == java_lang_Class::klass_offset_in_bytes()
1305          && flat->is_instptr()->klass() == env()->Class_klass())
1306        alias_type(idx)->set_rewritable(false);
1307    }
1308    if (flat->isa_klassptr()) {
1309      if (flat->offset() == Klass::super_check_offset_offset_in_bytes() + (int)sizeof(oopDesc))
1310        alias_type(idx)->set_rewritable(false);
1311      if (flat->offset() == Klass::modifier_flags_offset_in_bytes() + (int)sizeof(oopDesc))
1312        alias_type(idx)->set_rewritable(false);
1313      if (flat->offset() == Klass::access_flags_offset_in_bytes() + (int)sizeof(oopDesc))
1314        alias_type(idx)->set_rewritable(false);
1315      if (flat->offset() == Klass::java_mirror_offset_in_bytes() + (int)sizeof(oopDesc))
1316        alias_type(idx)->set_rewritable(false);
1317    }
1318    // %%% (We would like to finalize JavaThread::threadObj_offset(),
1319    // but the base pointer type is not distinctive enough to identify
1320    // references into JavaThread.)
1321
1322    // Check for final instance fields.
1323    const TypeInstPtr* tinst = flat->isa_instptr();
1324    if (tinst && tinst->offset() >= instanceOopDesc::base_offset_in_bytes()) {
1325      ciInstanceKlass *k = tinst->klass()->as_instance_klass();
1326      ciField* field = k->get_field_by_offset(tinst->offset(), false);
1327      // Set field() and is_rewritable() attributes.
1328      if (field != NULL)  alias_type(idx)->set_field(field);
1329    }
1330    const TypeKlassPtr* tklass = flat->isa_klassptr();
1331    // Check for final static fields.
1332    if (tklass && tklass->klass()->is_instance_klass()) {
1333      ciInstanceKlass *k = tklass->klass()->as_instance_klass();
1334      ciField* field = k->get_field_by_offset(tklass->offset(), true);
1335      // Set field() and is_rewritable() attributes.
1336      if (field != NULL)   alias_type(idx)->set_field(field);
1337    }
1338  }
1339
1340  // Fill the cache for next time.
1341  ace->_adr_type = adr_type;
1342  ace->_index    = idx;
1343  assert(alias_type(adr_type) == alias_type(idx),  "type must be installed");
1344
1345  // Might as well try to fill the cache for the flattened version, too.
1346  AliasCacheEntry* face = probe_alias_cache(flat);
1347  if (face->_adr_type == NULL) {
1348    face->_adr_type = flat;
1349    face->_index    = idx;
1350    assert(alias_type(flat) == alias_type(idx), "flat type must work too");
1351  }
1352
1353  return alias_type(idx);
1354}
1355
1356
1357Compile::AliasType* Compile::alias_type(ciField* field) {
1358  const TypeOopPtr* t;
1359  if (field->is_static())
1360    t = TypeKlassPtr::make(field->holder());
1361  else
1362    t = TypeOopPtr::make_from_klass_raw(field->holder());
1363  AliasType* atp = alias_type(t->add_offset(field->offset_in_bytes()));
1364  assert(field->is_final() == !atp->is_rewritable(), "must get the rewritable bits correct");
1365  return atp;
1366}
1367
1368
1369//------------------------------have_alias_type--------------------------------
1370bool Compile::have_alias_type(const TypePtr* adr_type) {
1371  AliasCacheEntry* ace = probe_alias_cache(adr_type);
1372  if (ace->_adr_type == adr_type) {
1373    return true;
1374  }
1375
1376  // Handle special cases.
1377  if (adr_type == NULL)             return true;
1378  if (adr_type == TypePtr::BOTTOM)  return true;
1379
1380  return find_alias_type(adr_type, true) != NULL;
1381}
1382
1383//-----------------------------must_alias--------------------------------------
1384// True if all values of the given address type are in the given alias category.
1385bool Compile::must_alias(const TypePtr* adr_type, int alias_idx) {
1386  if (alias_idx == AliasIdxBot)         return true;  // the universal category
1387  if (adr_type == NULL)                 return true;  // NULL serves as TypePtr::TOP
1388  if (alias_idx == AliasIdxTop)         return false; // the empty category
1389  if (adr_type->base() == Type::AnyPtr) return false; // TypePtr::BOTTOM or its twins
1390
1391  // the only remaining possible overlap is identity
1392  int adr_idx = get_alias_index(adr_type);
1393  assert(adr_idx != AliasIdxBot && adr_idx != AliasIdxTop, "");
1394  assert(adr_idx == alias_idx ||
1395         (alias_type(alias_idx)->adr_type() != TypeOopPtr::BOTTOM
1396          && adr_type                       != TypeOopPtr::BOTTOM),
1397         "should not be testing for overlap with an unsafe pointer");
1398  return adr_idx == alias_idx;
1399}
1400
1401//------------------------------can_alias--------------------------------------
1402// True if any values of the given address type are in the given alias category.
1403bool Compile::can_alias(const TypePtr* adr_type, int alias_idx) {
1404  if (alias_idx == AliasIdxTop)         return false; // the empty category
1405  if (adr_type == NULL)                 return false; // NULL serves as TypePtr::TOP
1406  if (alias_idx == AliasIdxBot)         return true;  // the universal category
1407  if (adr_type->base() == Type::AnyPtr) return true;  // TypePtr::BOTTOM or its twins
1408
1409  // the only remaining possible overlap is identity
1410  int adr_idx = get_alias_index(adr_type);
1411  assert(adr_idx != AliasIdxBot && adr_idx != AliasIdxTop, "");
1412  return adr_idx == alias_idx;
1413}
1414
1415
1416
1417//---------------------------pop_warm_call-------------------------------------
1418WarmCallInfo* Compile::pop_warm_call() {
1419  WarmCallInfo* wci = _warm_calls;
1420  if (wci != NULL)  _warm_calls = wci->remove_from(wci);
1421  return wci;
1422}
1423
1424//----------------------------Inline_Warm--------------------------------------
1425int Compile::Inline_Warm() {
1426  // If there is room, try to inline some more warm call sites.
1427  // %%% Do a graph index compaction pass when we think we're out of space?
1428  if (!InlineWarmCalls)  return 0;
1429
1430  int calls_made_hot = 0;
1431  int room_to_grow   = NodeCountInliningCutoff - unique();
1432  int amount_to_grow = MIN2(room_to_grow, (int)NodeCountInliningStep);
1433  int amount_grown   = 0;
1434  WarmCallInfo* call;
1435  while (amount_to_grow > 0 && (call = pop_warm_call()) != NULL) {
1436    int est_size = (int)call->size();
1437    if (est_size > (room_to_grow - amount_grown)) {
1438      // This one won't fit anyway.  Get rid of it.
1439      call->make_cold();
1440      continue;
1441    }
1442    call->make_hot();
1443    calls_made_hot++;
1444    amount_grown   += est_size;
1445    amount_to_grow -= est_size;
1446  }
1447
1448  if (calls_made_hot > 0)  set_major_progress();
1449  return calls_made_hot;
1450}
1451
1452
1453//----------------------------Finish_Warm--------------------------------------
1454void Compile::Finish_Warm() {
1455  if (!InlineWarmCalls)  return;
1456  if (failing())  return;
1457  if (warm_calls() == NULL)  return;
1458
1459  // Clean up loose ends, if we are out of space for inlining.
1460  WarmCallInfo* call;
1461  while ((call = pop_warm_call()) != NULL) {
1462    call->make_cold();
1463  }
1464}
1465
1466
1467//------------------------------Optimize---------------------------------------
1468// Given a graph, optimize it.
1469void Compile::Optimize() {
1470  TracePhase t1("optimizer", &_t_optimizer, true);
1471
1472#ifndef PRODUCT
1473  if (env()->break_at_compile()) {
1474    BREAKPOINT;
1475  }
1476
1477#endif
1478
1479  ResourceMark rm;
1480  int          loop_opts_cnt;
1481
1482  NOT_PRODUCT( verify_graph_edges(); )
1483
1484  print_method("Start");
1485
1486 {
1487  // Iterative Global Value Numbering, including ideal transforms
1488  // Initialize IterGVN with types and values from parse-time GVN
1489  PhaseIterGVN igvn(initial_gvn());
1490  {
1491    NOT_PRODUCT( TracePhase t2("iterGVN", &_t_iterGVN, TimeCompiler); )
1492    igvn.optimize();
1493  }
1494
1495  print_method("Iter GVN 1", 2);
1496
1497  if (failing())  return;
1498
1499  // get rid of the connection graph since it's information is not
1500  // updated by optimizations
1501  _congraph = NULL;
1502
1503
1504  // Loop transforms on the ideal graph.  Range Check Elimination,
1505  // peeling, unrolling, etc.
1506
1507  // Set loop opts counter
1508  loop_opts_cnt = num_loop_opts();
1509  if((loop_opts_cnt > 0) && (has_loops() || has_split_ifs())) {
1510    {
1511      TracePhase t2("idealLoop", &_t_idealLoop, true);
1512      PhaseIdealLoop ideal_loop( igvn, NULL, true );
1513      loop_opts_cnt--;
1514      if (major_progress()) print_method("PhaseIdealLoop 1", 2);
1515      if (failing())  return;
1516    }
1517    // Loop opts pass if partial peeling occurred in previous pass
1518    if(PartialPeelLoop && major_progress() && (loop_opts_cnt > 0)) {
1519      TracePhase t3("idealLoop", &_t_idealLoop, true);
1520      PhaseIdealLoop ideal_loop( igvn, NULL, false );
1521      loop_opts_cnt--;
1522      if (major_progress()) print_method("PhaseIdealLoop 2", 2);
1523      if (failing())  return;
1524    }
1525    // Loop opts pass for loop-unrolling before CCP
1526    if(major_progress() && (loop_opts_cnt > 0)) {
1527      TracePhase t4("idealLoop", &_t_idealLoop, true);
1528      PhaseIdealLoop ideal_loop( igvn, NULL, false );
1529      loop_opts_cnt--;
1530      if (major_progress()) print_method("PhaseIdealLoop 3", 2);
1531    }
1532  }
1533  if (failing())  return;
1534
1535  // Conditional Constant Propagation;
1536  PhaseCCP ccp( &igvn );
1537  assert( true, "Break here to ccp.dump_nodes_and_types(_root,999,1)");
1538  {
1539    TracePhase t2("ccp", &_t_ccp, true);
1540    ccp.do_transform();
1541  }
1542  print_method("PhaseCPP 1", 2);
1543
1544  assert( true, "Break here to ccp.dump_old2new_map()");
1545
1546  // Iterative Global Value Numbering, including ideal transforms
1547  {
1548    NOT_PRODUCT( TracePhase t2("iterGVN2", &_t_iterGVN2, TimeCompiler); )
1549    igvn = ccp;
1550    igvn.optimize();
1551  }
1552
1553  print_method("Iter GVN 2", 2);
1554
1555  if (failing())  return;
1556
1557  // Loop transforms on the ideal graph.  Range Check Elimination,
1558  // peeling, unrolling, etc.
1559  if(loop_opts_cnt > 0) {
1560    debug_only( int cnt = 0; );
1561    while(major_progress() && (loop_opts_cnt > 0)) {
1562      TracePhase t2("idealLoop", &_t_idealLoop, true);
1563      assert( cnt++ < 40, "infinite cycle in loop optimization" );
1564      PhaseIdealLoop ideal_loop( igvn, NULL, true );
1565      loop_opts_cnt--;
1566      if (major_progress()) print_method("PhaseIdealLoop iterations", 2);
1567      if (failing())  return;
1568    }
1569  }
1570  {
1571    NOT_PRODUCT( TracePhase t2("macroExpand", &_t_macroExpand, TimeCompiler); )
1572    PhaseMacroExpand  mex(igvn);
1573    if (mex.expand_macro_nodes()) {
1574      assert(failing(), "must bail out w/ explicit message");
1575      return;
1576    }
1577  }
1578
1579 } // (End scope of igvn; run destructor if necessary for asserts.)
1580
1581  // A method with only infinite loops has no edges entering loops from root
1582  {
1583    NOT_PRODUCT( TracePhase t2("graphReshape", &_t_graphReshaping, TimeCompiler); )
1584    if (final_graph_reshaping()) {
1585      assert(failing(), "must bail out w/ explicit message");
1586      return;
1587    }
1588  }
1589
1590  print_method("Optimize finished", 2);
1591}
1592
1593
1594//------------------------------Code_Gen---------------------------------------
1595// Given a graph, generate code for it
1596void Compile::Code_Gen() {
1597  if (failing())  return;
1598
1599  // Perform instruction selection.  You might think we could reclaim Matcher
1600  // memory PDQ, but actually the Matcher is used in generating spill code.
1601  // Internals of the Matcher (including some VectorSets) must remain live
1602  // for awhile - thus I cannot reclaim Matcher memory lest a VectorSet usage
1603  // set a bit in reclaimed memory.
1604
1605  // In debug mode can dump m._nodes.dump() for mapping of ideal to machine
1606  // nodes.  Mapping is only valid at the root of each matched subtree.
1607  NOT_PRODUCT( verify_graph_edges(); )
1608
1609  Node_List proj_list;
1610  Matcher m(proj_list);
1611  _matcher = &m;
1612  {
1613    TracePhase t2("matcher", &_t_matcher, true);
1614    m.match();
1615  }
1616  // In debug mode can dump m._nodes.dump() for mapping of ideal to machine
1617  // nodes.  Mapping is only valid at the root of each matched subtree.
1618  NOT_PRODUCT( verify_graph_edges(); )
1619
1620  // If you have too many nodes, or if matching has failed, bail out
1621  check_node_count(0, "out of nodes matching instructions");
1622  if (failing())  return;
1623
1624  // Build a proper-looking CFG
1625  PhaseCFG cfg(node_arena(), root(), m);
1626  _cfg = &cfg;
1627  {
1628    NOT_PRODUCT( TracePhase t2("scheduler", &_t_scheduler, TimeCompiler); )
1629    cfg.Dominators();
1630    if (failing())  return;
1631
1632    NOT_PRODUCT( verify_graph_edges(); )
1633
1634    cfg.Estimate_Block_Frequency();
1635    cfg.GlobalCodeMotion(m,unique(),proj_list);
1636
1637    print_method("Global code motion", 2);
1638
1639    if (failing())  return;
1640    NOT_PRODUCT( verify_graph_edges(); )
1641
1642    debug_only( cfg.verify(); )
1643  }
1644  NOT_PRODUCT( verify_graph_edges(); )
1645
1646  PhaseChaitin regalloc(unique(),cfg,m);
1647  _regalloc = &regalloc;
1648  {
1649    TracePhase t2("regalloc", &_t_registerAllocation, true);
1650    // Perform any platform dependent preallocation actions.  This is used,
1651    // for example, to avoid taking an implicit null pointer exception
1652    // using the frame pointer on win95.
1653    _regalloc->pd_preallocate_hook();
1654
1655    // Perform register allocation.  After Chaitin, use-def chains are
1656    // no longer accurate (at spill code) and so must be ignored.
1657    // Node->LRG->reg mappings are still accurate.
1658    _regalloc->Register_Allocate();
1659
1660    // Bail out if the allocator builds too many nodes
1661    if (failing())  return;
1662  }
1663
1664  // Prior to register allocation we kept empty basic blocks in case the
1665  // the allocator needed a place to spill.  After register allocation we
1666  // are not adding any new instructions.  If any basic block is empty, we
1667  // can now safely remove it.
1668  {
1669    NOT_PRODUCT( TracePhase t2("removeEmpty", &_t_removeEmptyBlocks, TimeCompiler); )
1670    cfg.RemoveEmpty();
1671  }
1672
1673  // Perform any platform dependent postallocation verifications.
1674  debug_only( _regalloc->pd_postallocate_verify_hook(); )
1675
1676  // Apply peephole optimizations
1677  if( OptoPeephole ) {
1678    NOT_PRODUCT( TracePhase t2("peephole", &_t_peephole, TimeCompiler); )
1679    PhasePeephole peep( _regalloc, cfg);
1680    peep.do_transform();
1681  }
1682
1683  // Convert Nodes to instruction bits in a buffer
1684  {
1685    // %%%% workspace merge brought two timers together for one job
1686    TracePhase t2a("output", &_t_output, true);
1687    NOT_PRODUCT( TraceTime t2b(NULL, &_t_codeGeneration, TimeCompiler, false); )
1688    Output();
1689  }
1690
1691  print_method("End");
1692
1693  // He's dead, Jim.
1694  _cfg     = (PhaseCFG*)0xdeadbeef;
1695  _regalloc = (PhaseChaitin*)0xdeadbeef;
1696}
1697
1698
1699//------------------------------dump_asm---------------------------------------
1700// Dump formatted assembly
1701#ifndef PRODUCT
1702void Compile::dump_asm(int *pcs, uint pc_limit) {
1703  bool cut_short = false;
1704  tty->print_cr("#");
1705  tty->print("#  ");  _tf->dump();  tty->cr();
1706  tty->print_cr("#");
1707
1708  // For all blocks
1709  int pc = 0x0;                 // Program counter
1710  char starts_bundle = ' ';
1711  _regalloc->dump_frame();
1712
1713  Node *n = NULL;
1714  for( uint i=0; i<_cfg->_num_blocks; i++ ) {
1715    if (VMThread::should_terminate()) { cut_short = true; break; }
1716    Block *b = _cfg->_blocks[i];
1717    if (b->is_connector() && !Verbose) continue;
1718    n = b->_nodes[0];
1719    if (pcs && n->_idx < pc_limit)
1720      tty->print("%3.3x   ", pcs[n->_idx]);
1721    else
1722      tty->print("      ");
1723    b->dump_head( &_cfg->_bbs );
1724    if (b->is_connector()) {
1725      tty->print_cr("        # Empty connector block");
1726    } else if (b->num_preds() == 2 && b->pred(1)->is_CatchProj() && b->pred(1)->as_CatchProj()->_con == CatchProjNode::fall_through_index) {
1727      tty->print_cr("        # Block is sole successor of call");
1728    }
1729
1730    // For all instructions
1731    Node *delay = NULL;
1732    for( uint j = 0; j<b->_nodes.size(); j++ ) {
1733      if (VMThread::should_terminate()) { cut_short = true; break; }
1734      n = b->_nodes[j];
1735      if (valid_bundle_info(n)) {
1736        Bundle *bundle = node_bundling(n);
1737        if (bundle->used_in_unconditional_delay()) {
1738          delay = n;
1739          continue;
1740        }
1741        if (bundle->starts_bundle())
1742          starts_bundle = '+';
1743      }
1744
1745      if (WizardMode) n->dump();
1746
1747      if( !n->is_Region() &&    // Dont print in the Assembly
1748          !n->is_Phi() &&       // a few noisely useless nodes
1749          !n->is_Proj() &&
1750          !n->is_MachTemp() &&
1751          !n->is_Catch() &&     // Would be nice to print exception table targets
1752          !n->is_MergeMem() &&  // Not very interesting
1753          !n->is_top() &&       // Debug info table constants
1754          !(n->is_Con() && !n->is_Mach())// Debug info table constants
1755          ) {
1756        if (pcs && n->_idx < pc_limit)
1757          tty->print("%3.3x", pcs[n->_idx]);
1758        else
1759          tty->print("   ");
1760        tty->print(" %c ", starts_bundle);
1761        starts_bundle = ' ';
1762        tty->print("\t");
1763        n->format(_regalloc, tty);
1764        tty->cr();
1765      }
1766
1767      // If we have an instruction with a delay slot, and have seen a delay,
1768      // then back up and print it
1769      if (valid_bundle_info(n) && node_bundling(n)->use_unconditional_delay()) {
1770        assert(delay != NULL, "no unconditional delay instruction");
1771        if (WizardMode) delay->dump();
1772
1773        if (node_bundling(delay)->starts_bundle())
1774          starts_bundle = '+';
1775        if (pcs && n->_idx < pc_limit)
1776          tty->print("%3.3x", pcs[n->_idx]);
1777        else
1778          tty->print("   ");
1779        tty->print(" %c ", starts_bundle);
1780        starts_bundle = ' ';
1781        tty->print("\t");
1782        delay->format(_regalloc, tty);
1783        tty->print_cr("");
1784        delay = NULL;
1785      }
1786
1787      // Dump the exception table as well
1788      if( n->is_Catch() && (Verbose || WizardMode) ) {
1789        // Print the exception table for this offset
1790        _handler_table.print_subtable_for(pc);
1791      }
1792    }
1793
1794    if (pcs && n->_idx < pc_limit)
1795      tty->print_cr("%3.3x", pcs[n->_idx]);
1796    else
1797      tty->print_cr("");
1798
1799    assert(cut_short || delay == NULL, "no unconditional delay branch");
1800
1801  } // End of per-block dump
1802  tty->print_cr("");
1803
1804  if (cut_short)  tty->print_cr("*** disassembly is cut short ***");
1805}
1806#endif
1807
1808//------------------------------Final_Reshape_Counts---------------------------
1809// This class defines counters to help identify when a method
1810// may/must be executed using hardware with only 24-bit precision.
1811struct Final_Reshape_Counts : public StackObj {
1812  int  _call_count;             // count non-inlined 'common' calls
1813  int  _float_count;            // count float ops requiring 24-bit precision
1814  int  _double_count;           // count double ops requiring more precision
1815  int  _java_call_count;        // count non-inlined 'java' calls
1816  VectorSet _visited;           // Visitation flags
1817  Node_List _tests;             // Set of IfNodes & PCTableNodes
1818
1819  Final_Reshape_Counts() :
1820    _call_count(0), _float_count(0), _double_count(0), _java_call_count(0),
1821    _visited( Thread::current()->resource_area() ) { }
1822
1823  void inc_call_count  () { _call_count  ++; }
1824  void inc_float_count () { _float_count ++; }
1825  void inc_double_count() { _double_count++; }
1826  void inc_java_call_count() { _java_call_count++; }
1827
1828  int  get_call_count  () const { return _call_count  ; }
1829  int  get_float_count () const { return _float_count ; }
1830  int  get_double_count() const { return _double_count; }
1831  int  get_java_call_count() const { return _java_call_count; }
1832};
1833
1834static bool oop_offset_is_sane(const TypeInstPtr* tp) {
1835  ciInstanceKlass *k = tp->klass()->as_instance_klass();
1836  // Make sure the offset goes inside the instance layout.
1837  return k->contains_field_offset(tp->offset());
1838  // Note that OffsetBot and OffsetTop are very negative.
1839}
1840
1841//------------------------------final_graph_reshaping_impl----------------------
1842// Implement items 1-5 from final_graph_reshaping below.
1843static void final_graph_reshaping_impl( Node *n, Final_Reshape_Counts &fpu ) {
1844
1845  if ( n->outcnt() == 0 ) return; // dead node
1846  uint nop = n->Opcode();
1847
1848  // Check for 2-input instruction with "last use" on right input.
1849  // Swap to left input.  Implements item (2).
1850  if( n->req() == 3 &&          // two-input instruction
1851      n->in(1)->outcnt() > 1 && // left use is NOT a last use
1852      (!n->in(1)->is_Phi() || n->in(1)->in(2) != n) && // it is not data loop
1853      n->in(2)->outcnt() == 1 &&// right use IS a last use
1854      !n->in(2)->is_Con() ) {   // right use is not a constant
1855    // Check for commutative opcode
1856    switch( nop ) {
1857    case Op_AddI:  case Op_AddF:  case Op_AddD:  case Op_AddL:
1858    case Op_MaxI:  case Op_MinI:
1859    case Op_MulI:  case Op_MulF:  case Op_MulD:  case Op_MulL:
1860    case Op_AndL:  case Op_XorL:  case Op_OrL:
1861    case Op_AndI:  case Op_XorI:  case Op_OrI: {
1862      // Move "last use" input to left by swapping inputs
1863      n->swap_edges(1, 2);
1864      break;
1865    }
1866    default:
1867      break;
1868    }
1869  }
1870
1871  // Count FPU ops and common calls, implements item (3)
1872  switch( nop ) {
1873  // Count all float operations that may use FPU
1874  case Op_AddF:
1875  case Op_SubF:
1876  case Op_MulF:
1877  case Op_DivF:
1878  case Op_NegF:
1879  case Op_ModF:
1880  case Op_ConvI2F:
1881  case Op_ConF:
1882  case Op_CmpF:
1883  case Op_CmpF3:
1884  // case Op_ConvL2F: // longs are split into 32-bit halves
1885    fpu.inc_float_count();
1886    break;
1887
1888  case Op_ConvF2D:
1889  case Op_ConvD2F:
1890    fpu.inc_float_count();
1891    fpu.inc_double_count();
1892    break;
1893
1894  // Count all double operations that may use FPU
1895  case Op_AddD:
1896  case Op_SubD:
1897  case Op_MulD:
1898  case Op_DivD:
1899  case Op_NegD:
1900  case Op_ModD:
1901  case Op_ConvI2D:
1902  case Op_ConvD2I:
1903  // case Op_ConvL2D: // handled by leaf call
1904  // case Op_ConvD2L: // handled by leaf call
1905  case Op_ConD:
1906  case Op_CmpD:
1907  case Op_CmpD3:
1908    fpu.inc_double_count();
1909    break;
1910  case Op_Opaque1:              // Remove Opaque Nodes before matching
1911  case Op_Opaque2:              // Remove Opaque Nodes before matching
1912    n->subsume_by(n->in(1));
1913    break;
1914  case Op_CallStaticJava:
1915  case Op_CallJava:
1916  case Op_CallDynamicJava:
1917    fpu.inc_java_call_count(); // Count java call site;
1918  case Op_CallRuntime:
1919  case Op_CallLeaf:
1920  case Op_CallLeafNoFP: {
1921    assert( n->is_Call(), "" );
1922    CallNode *call = n->as_Call();
1923    // Count call sites where the FP mode bit would have to be flipped.
1924    // Do not count uncommon runtime calls:
1925    // uncommon_trap, _complete_monitor_locking, _complete_monitor_unlocking,
1926    // _new_Java, _new_typeArray, _new_objArray, _rethrow_Java, ...
1927    if( !call->is_CallStaticJava() || !call->as_CallStaticJava()->_name ) {
1928      fpu.inc_call_count();   // Count the call site
1929    } else {                  // See if uncommon argument is shared
1930      Node *n = call->in(TypeFunc::Parms);
1931      int nop = n->Opcode();
1932      // Clone shared simple arguments to uncommon calls, item (1).
1933      if( n->outcnt() > 1 &&
1934          !n->is_Proj() &&
1935          nop != Op_CreateEx &&
1936          nop != Op_CheckCastPP &&
1937          !n->is_Mem() ) {
1938        Node *x = n->clone();
1939        call->set_req( TypeFunc::Parms, x );
1940      }
1941    }
1942    break;
1943  }
1944
1945  case Op_StoreD:
1946  case Op_LoadD:
1947  case Op_LoadD_unaligned:
1948    fpu.inc_double_count();
1949    goto handle_mem;
1950  case Op_StoreF:
1951  case Op_LoadF:
1952    fpu.inc_float_count();
1953    goto handle_mem;
1954
1955  case Op_StoreB:
1956  case Op_StoreC:
1957  case Op_StoreCM:
1958  case Op_StorePConditional:
1959  case Op_StoreI:
1960  case Op_StoreL:
1961  case Op_StoreLConditional:
1962  case Op_CompareAndSwapI:
1963  case Op_CompareAndSwapL:
1964  case Op_CompareAndSwapP:
1965  case Op_CompareAndSwapN:
1966  case Op_StoreP:
1967  case Op_StoreN:
1968  case Op_LoadB:
1969  case Op_LoadC:
1970  case Op_LoadI:
1971  case Op_LoadKlass:
1972  case Op_LoadNKlass:
1973  case Op_LoadL:
1974  case Op_LoadL_unaligned:
1975  case Op_LoadPLocked:
1976  case Op_LoadLLocked:
1977  case Op_LoadP:
1978  case Op_LoadN:
1979  case Op_LoadRange:
1980  case Op_LoadS: {
1981  handle_mem:
1982#ifdef ASSERT
1983    if( VerifyOptoOopOffsets ) {
1984      assert( n->is_Mem(), "" );
1985      MemNode *mem  = (MemNode*)n;
1986      // Check to see if address types have grounded out somehow.
1987      const TypeInstPtr *tp = mem->in(MemNode::Address)->bottom_type()->isa_instptr();
1988      assert( !tp || oop_offset_is_sane(tp), "" );
1989    }
1990#endif
1991    break;
1992  }
1993
1994  case Op_AddP: {               // Assert sane base pointers
1995    Node *addp = n->in(AddPNode::Address);
1996    assert( !addp->is_AddP() ||
1997            addp->in(AddPNode::Base)->is_top() || // Top OK for allocation
1998            addp->in(AddPNode::Base) == n->in(AddPNode::Base),
1999            "Base pointers must match" );
2000#ifdef _LP64
2001    if (UseCompressedOops &&
2002        addp->Opcode() == Op_ConP &&
2003        addp == n->in(AddPNode::Base) &&
2004        n->in(AddPNode::Offset)->is_Con()) {
2005      // Use addressing with narrow klass to load with offset on x86.
2006      // On sparc loading 32-bits constant and decoding it have less
2007      // instructions (4) then load 64-bits constant (7).
2008      // Do this transformation here since IGVN will convert ConN back to ConP.
2009      const Type* t = addp->bottom_type();
2010      if (t->isa_oopptr()) {
2011        Node* nn = NULL;
2012
2013        // Look for existing ConN node of the same exact type.
2014        Compile* C = Compile::current();
2015        Node* r  = C->root();
2016        uint cnt = r->outcnt();
2017        for (uint i = 0; i < cnt; i++) {
2018          Node* m = r->raw_out(i);
2019          if (m!= NULL && m->Opcode() == Op_ConN &&
2020              m->bottom_type()->is_narrowoop()->make_oopptr() == t) {
2021            nn = m;
2022            break;
2023          }
2024        }
2025        if (nn != NULL) {
2026          // Decode a narrow oop to match address
2027          // [R12 + narrow_oop_reg<<3 + offset]
2028          nn = new (C,  2) DecodeNNode(nn, t);
2029          n->set_req(AddPNode::Base, nn);
2030          n->set_req(AddPNode::Address, nn);
2031          if (addp->outcnt() == 0) {
2032            addp->disconnect_inputs(NULL);
2033          }
2034        }
2035      }
2036    }
2037#endif
2038    break;
2039  }
2040
2041#ifdef _LP64
2042  case Op_CmpP:
2043    // Do this transformation here to preserve CmpPNode::sub() and
2044    // other TypePtr related Ideal optimizations (for example, ptr nullness).
2045    if( n->in(1)->is_DecodeN() ) {
2046      Compile* C = Compile::current();
2047      Node* in2 = NULL;
2048      if( n->in(2)->is_DecodeN() ) {
2049        in2 = n->in(2)->in(1);
2050      } else if ( n->in(2)->Opcode() == Op_ConP ) {
2051        const Type* t = n->in(2)->bottom_type();
2052        if (t == TypePtr::NULL_PTR) {
2053          Node *in1 = n->in(1);
2054          if (Matcher::clone_shift_expressions) {
2055            // x86, ARM and friends can handle 2 adds in addressing mode.
2056            // Decode a narrow oop and do implicit NULL check in address
2057            // [R12 + narrow_oop_reg<<3 + offset]
2058            in2 = ConNode::make(C, TypeNarrowOop::NULL_PTR);
2059          } else {
2060            // Don't replace CmpP(o ,null) if 'o' is used in AddP
2061            // to generate implicit NULL check on Sparc where
2062            // narrow oops can't be used in address.
2063            uint i = 0;
2064            for (; i < in1->outcnt(); i++) {
2065              if (in1->raw_out(i)->is_AddP())
2066                break;
2067            }
2068            if (i >= in1->outcnt()) {
2069              in2 = ConNode::make(C, TypeNarrowOop::NULL_PTR);
2070            }
2071          }
2072        } else if (t->isa_oopptr()) {
2073          in2 = ConNode::make(C, t->is_oopptr()->make_narrowoop());
2074        }
2075      }
2076      if( in2 != NULL ) {
2077        Node* cmpN = new (C, 3) CmpNNode(n->in(1)->in(1), in2);
2078        n->subsume_by( cmpN );
2079      }
2080    }
2081#endif
2082
2083  case Op_ModI:
2084    if (UseDivMod) {
2085      // Check if a%b and a/b both exist
2086      Node* d = n->find_similar(Op_DivI);
2087      if (d) {
2088        // Replace them with a fused divmod if supported
2089        Compile* C = Compile::current();
2090        if (Matcher::has_match_rule(Op_DivModI)) {
2091          DivModINode* divmod = DivModINode::make(C, n);
2092          d->subsume_by(divmod->div_proj());
2093          n->subsume_by(divmod->mod_proj());
2094        } else {
2095          // replace a%b with a-((a/b)*b)
2096          Node* mult = new (C, 3) MulINode(d, d->in(2));
2097          Node* sub  = new (C, 3) SubINode(d->in(1), mult);
2098          n->subsume_by( sub );
2099        }
2100      }
2101    }
2102    break;
2103
2104  case Op_ModL:
2105    if (UseDivMod) {
2106      // Check if a%b and a/b both exist
2107      Node* d = n->find_similar(Op_DivL);
2108      if (d) {
2109        // Replace them with a fused divmod if supported
2110        Compile* C = Compile::current();
2111        if (Matcher::has_match_rule(Op_DivModL)) {
2112          DivModLNode* divmod = DivModLNode::make(C, n);
2113          d->subsume_by(divmod->div_proj());
2114          n->subsume_by(divmod->mod_proj());
2115        } else {
2116          // replace a%b with a-((a/b)*b)
2117          Node* mult = new (C, 3) MulLNode(d, d->in(2));
2118          Node* sub  = new (C, 3) SubLNode(d->in(1), mult);
2119          n->subsume_by( sub );
2120        }
2121      }
2122    }
2123    break;
2124
2125  case Op_Load16B:
2126  case Op_Load8B:
2127  case Op_Load4B:
2128  case Op_Load8S:
2129  case Op_Load4S:
2130  case Op_Load2S:
2131  case Op_Load8C:
2132  case Op_Load4C:
2133  case Op_Load2C:
2134  case Op_Load4I:
2135  case Op_Load2I:
2136  case Op_Load2L:
2137  case Op_Load4F:
2138  case Op_Load2F:
2139  case Op_Load2D:
2140  case Op_Store16B:
2141  case Op_Store8B:
2142  case Op_Store4B:
2143  case Op_Store8C:
2144  case Op_Store4C:
2145  case Op_Store2C:
2146  case Op_Store4I:
2147  case Op_Store2I:
2148  case Op_Store2L:
2149  case Op_Store4F:
2150  case Op_Store2F:
2151  case Op_Store2D:
2152    break;
2153
2154  case Op_PackB:
2155  case Op_PackS:
2156  case Op_PackC:
2157  case Op_PackI:
2158  case Op_PackF:
2159  case Op_PackL:
2160  case Op_PackD:
2161    if (n->req()-1 > 2) {
2162      // Replace many operand PackNodes with a binary tree for matching
2163      PackNode* p = (PackNode*) n;
2164      Node* btp = p->binaryTreePack(Compile::current(), 1, n->req());
2165      n->subsume_by(btp);
2166    }
2167    break;
2168  default:
2169    assert( !n->is_Call(), "" );
2170    assert( !n->is_Mem(), "" );
2171    break;
2172  }
2173
2174  // Collect CFG split points
2175  if (n->is_MultiBranch())
2176    fpu._tests.push(n);
2177}
2178
2179//------------------------------final_graph_reshaping_walk---------------------
2180// Replacing Opaque nodes with their input in final_graph_reshaping_impl(),
2181// requires that the walk visits a node's inputs before visiting the node.
2182static void final_graph_reshaping_walk( Node_Stack &nstack, Node *root, Final_Reshape_Counts &fpu ) {
2183  fpu._visited.set(root->_idx); // first, mark node as visited
2184  uint cnt = root->req();
2185  Node *n = root;
2186  uint  i = 0;
2187  while (true) {
2188    if (i < cnt) {
2189      // Place all non-visited non-null inputs onto stack
2190      Node* m = n->in(i);
2191      ++i;
2192      if (m != NULL && !fpu._visited.test_set(m->_idx)) {
2193        cnt = m->req();
2194        nstack.push(n, i); // put on stack parent and next input's index
2195        n = m;
2196        i = 0;
2197      }
2198    } else {
2199      // Now do post-visit work
2200      final_graph_reshaping_impl( n, fpu );
2201      if (nstack.is_empty())
2202        break;             // finished
2203      n = nstack.node();   // Get node from stack
2204      cnt = n->req();
2205      i = nstack.index();
2206      nstack.pop();        // Shift to the next node on stack
2207    }
2208  }
2209}
2210
2211//------------------------------final_graph_reshaping--------------------------
2212// Final Graph Reshaping.
2213//
2214// (1) Clone simple inputs to uncommon calls, so they can be scheduled late
2215//     and not commoned up and forced early.  Must come after regular
2216//     optimizations to avoid GVN undoing the cloning.  Clone constant
2217//     inputs to Loop Phis; these will be split by the allocator anyways.
2218//     Remove Opaque nodes.
2219// (2) Move last-uses by commutative operations to the left input to encourage
2220//     Intel update-in-place two-address operations and better register usage
2221//     on RISCs.  Must come after regular optimizations to avoid GVN Ideal
2222//     calls canonicalizing them back.
2223// (3) Count the number of double-precision FP ops, single-precision FP ops
2224//     and call sites.  On Intel, we can get correct rounding either by
2225//     forcing singles to memory (requires extra stores and loads after each
2226//     FP bytecode) or we can set a rounding mode bit (requires setting and
2227//     clearing the mode bit around call sites).  The mode bit is only used
2228//     if the relative frequency of single FP ops to calls is low enough.
2229//     This is a key transform for SPEC mpeg_audio.
2230// (4) Detect infinite loops; blobs of code reachable from above but not
2231//     below.  Several of the Code_Gen algorithms fail on such code shapes,
2232//     so we simply bail out.  Happens a lot in ZKM.jar, but also happens
2233//     from time to time in other codes (such as -Xcomp finalizer loops, etc).
2234//     Detection is by looking for IfNodes where only 1 projection is
2235//     reachable from below or CatchNodes missing some targets.
2236// (5) Assert for insane oop offsets in debug mode.
2237
2238bool Compile::final_graph_reshaping() {
2239  // an infinite loop may have been eliminated by the optimizer,
2240  // in which case the graph will be empty.
2241  if (root()->req() == 1) {
2242    record_method_not_compilable("trivial infinite loop");
2243    return true;
2244  }
2245
2246  Final_Reshape_Counts fpu;
2247
2248  // Visit everybody reachable!
2249  // Allocate stack of size C->unique()/2 to avoid frequent realloc
2250  Node_Stack nstack(unique() >> 1);
2251  final_graph_reshaping_walk(nstack, root(), fpu);
2252
2253  // Check for unreachable (from below) code (i.e., infinite loops).
2254  for( uint i = 0; i < fpu._tests.size(); i++ ) {
2255    MultiBranchNode *n = fpu._tests[i]->as_MultiBranch();
2256    // Get number of CFG targets.
2257    // Note that PCTables include exception targets after calls.
2258    uint required_outcnt = n->required_outcnt();
2259    if (n->outcnt() != required_outcnt) {
2260      // Check for a few special cases.  Rethrow Nodes never take the
2261      // 'fall-thru' path, so expected kids is 1 less.
2262      if (n->is_PCTable() && n->in(0) && n->in(0)->in(0)) {
2263        if (n->in(0)->in(0)->is_Call()) {
2264          CallNode *call = n->in(0)->in(0)->as_Call();
2265          if (call->entry_point() == OptoRuntime::rethrow_stub()) {
2266            required_outcnt--;      // Rethrow always has 1 less kid
2267          } else if (call->req() > TypeFunc::Parms &&
2268                     call->is_CallDynamicJava()) {
2269            // Check for null receiver. In such case, the optimizer has
2270            // detected that the virtual call will always result in a null
2271            // pointer exception. The fall-through projection of this CatchNode
2272            // will not be populated.
2273            Node *arg0 = call->in(TypeFunc::Parms);
2274            if (arg0->is_Type() &&
2275                arg0->as_Type()->type()->higher_equal(TypePtr::NULL_PTR)) {
2276              required_outcnt--;
2277            }
2278          } else if (call->entry_point() == OptoRuntime::new_array_Java() &&
2279                     call->req() > TypeFunc::Parms+1 &&
2280                     call->is_CallStaticJava()) {
2281            // Check for negative array length. In such case, the optimizer has
2282            // detected that the allocation attempt will always result in an
2283            // exception. There is no fall-through projection of this CatchNode .
2284            Node *arg1 = call->in(TypeFunc::Parms+1);
2285            if (arg1->is_Type() &&
2286                arg1->as_Type()->type()->join(TypeInt::POS)->empty()) {
2287              required_outcnt--;
2288            }
2289          }
2290        }
2291      }
2292      // Recheck with a better notion of 'required_outcnt'
2293      if (n->outcnt() != required_outcnt) {
2294        record_method_not_compilable("malformed control flow");
2295        return true;            // Not all targets reachable!
2296      }
2297    }
2298    // Check that I actually visited all kids.  Unreached kids
2299    // must be infinite loops.
2300    for (DUIterator_Fast jmax, j = n->fast_outs(jmax); j < jmax; j++)
2301      if (!fpu._visited.test(n->fast_out(j)->_idx)) {
2302        record_method_not_compilable("infinite loop");
2303        return true;            // Found unvisited kid; must be unreach
2304      }
2305  }
2306
2307  // If original bytecodes contained a mixture of floats and doubles
2308  // check if the optimizer has made it homogenous, item (3).
2309  if( Use24BitFPMode && Use24BitFP &&
2310      fpu.get_float_count() > 32 &&
2311      fpu.get_double_count() == 0 &&
2312      (10 * fpu.get_call_count() < fpu.get_float_count()) ) {
2313    set_24_bit_selection_and_mode( false,  true );
2314  }
2315
2316  set_has_java_calls(fpu.get_java_call_count() > 0);
2317
2318  // No infinite loops, no reason to bail out.
2319  return false;
2320}
2321
2322//-----------------------------too_many_traps----------------------------------
2323// Report if there are too many traps at the current method and bci.
2324// Return true if there was a trap, and/or PerMethodTrapLimit is exceeded.
2325bool Compile::too_many_traps(ciMethod* method,
2326                             int bci,
2327                             Deoptimization::DeoptReason reason) {
2328  ciMethodData* md = method->method_data();
2329  if (md->is_empty()) {
2330    // Assume the trap has not occurred, or that it occurred only
2331    // because of a transient condition during start-up in the interpreter.
2332    return false;
2333  }
2334  if (md->has_trap_at(bci, reason) != 0) {
2335    // Assume PerBytecodeTrapLimit==0, for a more conservative heuristic.
2336    // Also, if there are multiple reasons, or if there is no per-BCI record,
2337    // assume the worst.
2338    if (log())
2339      log()->elem("observe trap='%s' count='%d'",
2340                  Deoptimization::trap_reason_name(reason),
2341                  md->trap_count(reason));
2342    return true;
2343  } else {
2344    // Ignore method/bci and see if there have been too many globally.
2345    return too_many_traps(reason, md);
2346  }
2347}
2348
2349// Less-accurate variant which does not require a method and bci.
2350bool Compile::too_many_traps(Deoptimization::DeoptReason reason,
2351                             ciMethodData* logmd) {
2352 if (trap_count(reason) >= (uint)PerMethodTrapLimit) {
2353    // Too many traps globally.
2354    // Note that we use cumulative trap_count, not just md->trap_count.
2355    if (log()) {
2356      int mcount = (logmd == NULL)? -1: (int)logmd->trap_count(reason);
2357      log()->elem("observe trap='%s' count='0' mcount='%d' ccount='%d'",
2358                  Deoptimization::trap_reason_name(reason),
2359                  mcount, trap_count(reason));
2360    }
2361    return true;
2362  } else {
2363    // The coast is clear.
2364    return false;
2365  }
2366}
2367
2368//--------------------------too_many_recompiles--------------------------------
2369// Report if there are too many recompiles at the current method and bci.
2370// Consults PerBytecodeRecompilationCutoff and PerMethodRecompilationCutoff.
2371// Is not eager to return true, since this will cause the compiler to use
2372// Action_none for a trap point, to avoid too many recompilations.
2373bool Compile::too_many_recompiles(ciMethod* method,
2374                                  int bci,
2375                                  Deoptimization::DeoptReason reason) {
2376  ciMethodData* md = method->method_data();
2377  if (md->is_empty()) {
2378    // Assume the trap has not occurred, or that it occurred only
2379    // because of a transient condition during start-up in the interpreter.
2380    return false;
2381  }
2382  // Pick a cutoff point well within PerBytecodeRecompilationCutoff.
2383  uint bc_cutoff = (uint) PerBytecodeRecompilationCutoff / 8;
2384  uint m_cutoff  = (uint) PerMethodRecompilationCutoff / 2 + 1;  // not zero
2385  Deoptimization::DeoptReason per_bc_reason
2386    = Deoptimization::reason_recorded_per_bytecode_if_any(reason);
2387  if ((per_bc_reason == Deoptimization::Reason_none
2388       || md->has_trap_at(bci, reason) != 0)
2389      // The trap frequency measure we care about is the recompile count:
2390      && md->trap_recompiled_at(bci)
2391      && md->overflow_recompile_count() >= bc_cutoff) {
2392    // Do not emit a trap here if it has already caused recompilations.
2393    // Also, if there are multiple reasons, or if there is no per-BCI record,
2394    // assume the worst.
2395    if (log())
2396      log()->elem("observe trap='%s recompiled' count='%d' recompiles2='%d'",
2397                  Deoptimization::trap_reason_name(reason),
2398                  md->trap_count(reason),
2399                  md->overflow_recompile_count());
2400    return true;
2401  } else if (trap_count(reason) != 0
2402             && decompile_count() >= m_cutoff) {
2403    // Too many recompiles globally, and we have seen this sort of trap.
2404    // Use cumulative decompile_count, not just md->decompile_count.
2405    if (log())
2406      log()->elem("observe trap='%s' count='%d' mcount='%d' decompiles='%d' mdecompiles='%d'",
2407                  Deoptimization::trap_reason_name(reason),
2408                  md->trap_count(reason), trap_count(reason),
2409                  md->decompile_count(), decompile_count());
2410    return true;
2411  } else {
2412    // The coast is clear.
2413    return false;
2414  }
2415}
2416
2417
2418#ifndef PRODUCT
2419//------------------------------verify_graph_edges---------------------------
2420// Walk the Graph and verify that there is a one-to-one correspondence
2421// between Use-Def edges and Def-Use edges in the graph.
2422void Compile::verify_graph_edges(bool no_dead_code) {
2423  if (VerifyGraphEdges) {
2424    ResourceArea *area = Thread::current()->resource_area();
2425    Unique_Node_List visited(area);
2426    // Call recursive graph walk to check edges
2427    _root->verify_edges(visited);
2428    if (no_dead_code) {
2429      // Now make sure that no visited node is used by an unvisited node.
2430      bool dead_nodes = 0;
2431      Unique_Node_List checked(area);
2432      while (visited.size() > 0) {
2433        Node* n = visited.pop();
2434        checked.push(n);
2435        for (uint i = 0; i < n->outcnt(); i++) {
2436          Node* use = n->raw_out(i);
2437          if (checked.member(use))  continue;  // already checked
2438          if (visited.member(use))  continue;  // already in the graph
2439          if (use->is_Con())        continue;  // a dead ConNode is OK
2440          // At this point, we have found a dead node which is DU-reachable.
2441          if (dead_nodes++ == 0)
2442            tty->print_cr("*** Dead nodes reachable via DU edges:");
2443          use->dump(2);
2444          tty->print_cr("---");
2445          checked.push(use);  // No repeats; pretend it is now checked.
2446        }
2447      }
2448      assert(dead_nodes == 0, "using nodes must be reachable from root");
2449    }
2450  }
2451}
2452#endif
2453
2454// The Compile object keeps track of failure reasons separately from the ciEnv.
2455// This is required because there is not quite a 1-1 relation between the
2456// ciEnv and its compilation task and the Compile object.  Note that one
2457// ciEnv might use two Compile objects, if C2Compiler::compile_method decides
2458// to backtrack and retry without subsuming loads.  Other than this backtracking
2459// behavior, the Compile's failure reason is quietly copied up to the ciEnv
2460// by the logic in C2Compiler.
2461void Compile::record_failure(const char* reason) {
2462  if (log() != NULL) {
2463    log()->elem("failure reason='%s' phase='compile'", reason);
2464  }
2465  if (_failure_reason == NULL) {
2466    // Record the first failure reason.
2467    _failure_reason = reason;
2468  }
2469  _root = NULL;  // flush the graph, too
2470}
2471
2472Compile::TracePhase::TracePhase(const char* name, elapsedTimer* accumulator, bool dolog)
2473  : TraceTime(NULL, accumulator, false NOT_PRODUCT( || TimeCompiler ), false)
2474{
2475  if (dolog) {
2476    C = Compile::current();
2477    _log = C->log();
2478  } else {
2479    C = NULL;
2480    _log = NULL;
2481  }
2482  if (_log != NULL) {
2483    _log->begin_head("phase name='%s' nodes='%d'", name, C->unique());
2484    _log->stamp();
2485    _log->end_head();
2486  }
2487}
2488
2489Compile::TracePhase::~TracePhase() {
2490  if (_log != NULL) {
2491    _log->done("phase nodes='%d'", C->unique());
2492  }
2493}
2494