Wed, 07 Feb 2018 13:00:31 +0800
#6578 On MIPS, add the end of the previous instruction to the implicit exception table when the node is a null check
Reviewed-by: fujie
Summary: the last instruction of the previous node (usually a instruction sequence) is the instruction which access memory on MIPS.
For example:
StoreB
NullCheck
=>
daddiu at,zero,1 ;wrong implicit exception dispatch position
sb at,18(s3) ;right implicit exception dispatch position
1 /*
2 * Copyright (c) 1998, 2014, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.
8 *
9 * This code is distributed in the hope that it will be useful, but WITHOUT
10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
12 * version 2 for more details (a copy is included in the LICENSE file that
13 * accompanied this code).
14 *
15 * You should have received a copy of the GNU General Public License version
16 * 2 along with this work; if not, write to the Free Software Foundation,
17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18 *
19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20 * or visit www.oracle.com if you need additional information or have any
21 * questions.
22 *
23 */
25 /*
26 * This file has been modified by Loongson Technology in 2015. These
27 * modifications are Copyright (c) 2015 Loongson Technology, and are made
28 * available on the same license terms set forth above.
29 */
31 #include "precompiled.hpp"
32 #include "asm/assembler.inline.hpp"
33 #include "code/compiledIC.hpp"
34 #include "code/debugInfo.hpp"
35 #include "code/debugInfoRec.hpp"
36 #include "compiler/compileBroker.hpp"
37 #include "compiler/oopMap.hpp"
38 #include "memory/allocation.inline.hpp"
39 #include "opto/callnode.hpp"
40 #include "opto/cfgnode.hpp"
41 #include "opto/locknode.hpp"
42 #include "opto/machnode.hpp"
43 #include "opto/output.hpp"
44 #include "opto/regalloc.hpp"
45 #include "opto/runtime.hpp"
46 #include "opto/subnode.hpp"
47 #include "opto/type.hpp"
48 #include "runtime/handles.inline.hpp"
49 #include "utilities/xmlstream.hpp"
51 #ifndef PRODUCT
52 #define DEBUG_ARG(x) , x
53 #else
54 #define DEBUG_ARG(x)
55 #endif
57 // Convert Nodes to instruction bits and pass off to the VM
58 void Compile::Output() {
59 // RootNode goes
60 assert( _cfg->get_root_block()->number_of_nodes() == 0, "" );
62 // The number of new nodes (mostly MachNop) is proportional to
63 // the number of java calls and inner loops which are aligned.
64 if ( C->check_node_count((NodeLimitFudgeFactor + C->java_calls()*3 +
65 C->inner_loops()*(OptoLoopAlignment-1)),
66 "out of nodes before code generation" ) ) {
67 return;
68 }
69 // Make sure I can find the Start Node
70 Block *entry = _cfg->get_block(1);
71 Block *broot = _cfg->get_root_block();
73 const StartNode *start = entry->head()->as_Start();
75 // Replace StartNode with prolog
76 MachPrologNode *prolog = new (this) MachPrologNode();
77 entry->map_node(prolog, 0);
78 _cfg->map_node_to_block(prolog, entry);
79 _cfg->unmap_node_from_block(start); // start is no longer in any block
81 // Virtual methods need an unverified entry point
83 if( is_osr_compilation() ) {
84 if( PoisonOSREntry ) {
85 // TODO: Should use a ShouldNotReachHereNode...
86 _cfg->insert( broot, 0, new (this) MachBreakpointNode() );
87 }
88 } else {
89 if( _method && !_method->flags().is_static() ) {
90 // Insert unvalidated entry point
91 _cfg->insert( broot, 0, new (this) MachUEPNode() );
92 }
94 }
97 // Break before main entry point
98 if( (_method && _method->break_at_execute())
99 #ifndef PRODUCT
100 ||(OptoBreakpoint && is_method_compilation())
101 ||(OptoBreakpointOSR && is_osr_compilation())
102 ||(OptoBreakpointC2R && !_method)
103 #endif
104 ) {
105 // checking for _method means that OptoBreakpoint does not apply to
106 // runtime stubs or frame converters
107 _cfg->insert( entry, 1, new (this) MachBreakpointNode() );
108 }
110 // Insert epilogs before every return
111 for (uint i = 0; i < _cfg->number_of_blocks(); i++) {
112 Block* block = _cfg->get_block(i);
113 if (!block->is_connector() && block->non_connector_successor(0) == _cfg->get_root_block()) { // Found a program exit point?
114 Node* m = block->end();
115 if (m->is_Mach() && m->as_Mach()->ideal_Opcode() != Op_Halt) {
116 MachEpilogNode* epilog = new (this) MachEpilogNode(m->as_Mach()->ideal_Opcode() == Op_Return);
117 block->add_inst(epilog);
118 _cfg->map_node_to_block(epilog, block);
119 }
120 }
121 }
123 # ifdef ENABLE_ZAP_DEAD_LOCALS
124 if (ZapDeadCompiledLocals) {
125 Insert_zap_nodes();
126 }
127 # endif
129 uint* blk_starts = NEW_RESOURCE_ARRAY(uint, _cfg->number_of_blocks() + 1);
130 blk_starts[0] = 0;
132 // Initialize code buffer and process short branches.
133 CodeBuffer* cb = init_buffer(blk_starts);
135 if (cb == NULL || failing()) {
136 return;
137 }
139 ScheduleAndBundle();
141 #ifndef PRODUCT
142 if (trace_opto_output()) {
143 tty->print("\n---- After ScheduleAndBundle ----\n");
144 for (uint i = 0; i < _cfg->number_of_blocks(); i++) {
145 tty->print("\nBB#%03d:\n", i);
146 Block* block = _cfg->get_block(i);
147 for (uint j = 0; j < block->number_of_nodes(); j++) {
148 Node* n = block->get_node(j);
149 OptoReg::Name reg = _regalloc->get_reg_first(n);
150 tty->print(" %-6s ", reg >= 0 && reg < REG_COUNT ? Matcher::regName[reg] : "");
151 n->dump();
152 }
153 }
154 }
155 #endif
157 if (failing()) {
158 return;
159 }
161 BuildOopMaps();
163 if (failing()) {
164 return;
165 }
167 fill_buffer(cb, blk_starts);
168 }
170 bool Compile::need_stack_bang(int frame_size_in_bytes) const {
171 // Determine if we need to generate a stack overflow check.
172 // Do it if the method is not a stub function and
173 // has java calls or has frame size > vm_page_size/8.
174 // The debug VM checks that deoptimization doesn't trigger an
175 // unexpected stack overflow (compiled method stack banging should
176 // guarantee it doesn't happen) so we always need the stack bang in
177 // a debug VM.
178 return (UseStackBanging && stub_function() == NULL &&
179 (has_java_calls() || frame_size_in_bytes > os::vm_page_size()>>3
180 DEBUG_ONLY(|| true)));
181 }
183 bool Compile::need_register_stack_bang() const {
184 // Determine if we need to generate a register stack overflow check.
185 // This is only used on architectures which have split register
186 // and memory stacks (ie. IA64).
187 // Bang if the method is not a stub function and has java calls
188 return (stub_function() == NULL && has_java_calls());
189 }
191 # ifdef ENABLE_ZAP_DEAD_LOCALS
194 // In order to catch compiler oop-map bugs, we have implemented
195 // a debugging mode called ZapDeadCompilerLocals.
196 // This mode causes the compiler to insert a call to a runtime routine,
197 // "zap_dead_locals", right before each place in compiled code
198 // that could potentially be a gc-point (i.e., a safepoint or oop map point).
199 // The runtime routine checks that locations mapped as oops are really
200 // oops, that locations mapped as values do not look like oops,
201 // and that locations mapped as dead are not used later
202 // (by zapping them to an invalid address).
204 int Compile::_CompiledZap_count = 0;
206 void Compile::Insert_zap_nodes() {
207 bool skip = false;
210 // Dink with static counts because code code without the extra
211 // runtime calls is MUCH faster for debugging purposes
213 if ( CompileZapFirst == 0 ) ; // nothing special
214 else if ( CompileZapFirst > CompiledZap_count() ) skip = true;
215 else if ( CompileZapFirst == CompiledZap_count() )
216 warning("starting zap compilation after skipping");
218 if ( CompileZapLast == -1 ) ; // nothing special
219 else if ( CompileZapLast < CompiledZap_count() ) skip = true;
220 else if ( CompileZapLast == CompiledZap_count() )
221 warning("about to compile last zap");
223 ++_CompiledZap_count; // counts skipped zaps, too
225 if ( skip ) return;
228 if ( _method == NULL )
229 return; // no safepoints/oopmaps emitted for calls in stubs,so we don't care
231 // Insert call to zap runtime stub before every node with an oop map
232 for( uint i=0; i<_cfg->number_of_blocks(); i++ ) {
233 Block *b = _cfg->get_block(i);
234 for ( uint j = 0; j < b->number_of_nodes(); ++j ) {
235 Node *n = b->get_node(j);
237 // Determining if we should insert a zap-a-lot node in output.
238 // We do that for all nodes that has oopmap info, except for calls
239 // to allocation. Calls to allocation passes in the old top-of-eden pointer
240 // and expect the C code to reset it. Hence, there can be no safepoints between
241 // the inlined-allocation and the call to new_Java, etc.
242 // We also cannot zap monitor calls, as they must hold the microlock
243 // during the call to Zap, which also wants to grab the microlock.
244 bool insert = n->is_MachSafePoint() && (n->as_MachSafePoint()->oop_map() != NULL);
245 if ( insert ) { // it is MachSafePoint
246 if ( !n->is_MachCall() ) {
247 insert = false;
248 } else if ( n->is_MachCall() ) {
249 MachCallNode* call = n->as_MachCall();
250 if (call->entry_point() == OptoRuntime::new_instance_Java() ||
251 call->entry_point() == OptoRuntime::new_array_Java() ||
252 call->entry_point() == OptoRuntime::multianewarray2_Java() ||
253 call->entry_point() == OptoRuntime::multianewarray3_Java() ||
254 call->entry_point() == OptoRuntime::multianewarray4_Java() ||
255 call->entry_point() == OptoRuntime::multianewarray5_Java() ||
256 call->entry_point() == OptoRuntime::slow_arraycopy_Java() ||
257 call->entry_point() == OptoRuntime::complete_monitor_locking_Java()
258 ) {
259 insert = false;
260 }
261 }
262 if (insert) {
263 Node *zap = call_zap_node(n->as_MachSafePoint(), i);
264 b->insert_node(zap, j);
265 _cfg->map_node_to_block(zap, b);
266 ++j;
267 }
268 }
269 }
270 }
271 }
274 Node* Compile::call_zap_node(MachSafePointNode* node_to_check, int block_no) {
275 const TypeFunc *tf = OptoRuntime::zap_dead_locals_Type();
276 CallStaticJavaNode* ideal_node =
277 new (this) CallStaticJavaNode( tf,
278 OptoRuntime::zap_dead_locals_stub(_method->flags().is_native()),
279 "call zap dead locals stub", 0, TypePtr::BOTTOM);
280 // We need to copy the OopMap from the site we're zapping at.
281 // We have to make a copy, because the zap site might not be
282 // a call site, and zap_dead is a call site.
283 OopMap* clone = node_to_check->oop_map()->deep_copy();
285 // Add the cloned OopMap to the zap node
286 ideal_node->set_oop_map(clone);
287 return _matcher->match_sfpt(ideal_node);
288 }
290 bool Compile::is_node_getting_a_safepoint( Node* n) {
291 // This code duplicates the logic prior to the call of add_safepoint
292 // below in this file.
293 if( n->is_MachSafePoint() ) return true;
294 return false;
295 }
297 # endif // ENABLE_ZAP_DEAD_LOCALS
299 // Compute the size of first NumberOfLoopInstrToAlign instructions at the top
300 // of a loop. When aligning a loop we need to provide enough instructions
301 // in cpu's fetch buffer to feed decoders. The loop alignment could be
302 // avoided if we have enough instructions in fetch buffer at the head of a loop.
303 // By default, the size is set to 999999 by Block's constructor so that
304 // a loop will be aligned if the size is not reset here.
305 //
306 // Note: Mach instructions could contain several HW instructions
307 // so the size is estimated only.
308 //
309 void Compile::compute_loop_first_inst_sizes() {
310 // The next condition is used to gate the loop alignment optimization.
311 // Don't aligned a loop if there are enough instructions at the head of a loop
312 // or alignment padding is larger then MaxLoopPad. By default, MaxLoopPad
313 // is equal to OptoLoopAlignment-1 except on new Intel cpus, where it is
314 // equal to 11 bytes which is the largest address NOP instruction.
315 if (MaxLoopPad < OptoLoopAlignment - 1) {
316 uint last_block = _cfg->number_of_blocks() - 1;
317 for (uint i = 1; i <= last_block; i++) {
318 Block* block = _cfg->get_block(i);
319 // Check the first loop's block which requires an alignment.
320 if (block->loop_alignment() > (uint)relocInfo::addr_unit()) {
321 uint sum_size = 0;
322 uint inst_cnt = NumberOfLoopInstrToAlign;
323 inst_cnt = block->compute_first_inst_size(sum_size, inst_cnt, _regalloc);
325 // Check subsequent fallthrough blocks if the loop's first
326 // block(s) does not have enough instructions.
327 Block *nb = block;
328 while(inst_cnt > 0 &&
329 i < last_block &&
330 !_cfg->get_block(i + 1)->has_loop_alignment() &&
331 !nb->has_successor(block)) {
332 i++;
333 nb = _cfg->get_block(i);
334 inst_cnt = nb->compute_first_inst_size(sum_size, inst_cnt, _regalloc);
335 } // while( inst_cnt > 0 && i < last_block )
337 block->set_first_inst_size(sum_size);
338 } // f( b->head()->is_Loop() )
339 } // for( i <= last_block )
340 } // if( MaxLoopPad < OptoLoopAlignment-1 )
341 }
343 // The architecture description provides short branch variants for some long
344 // branch instructions. Replace eligible long branches with short branches.
345 void Compile::shorten_branches(uint* blk_starts, int& code_size, int& reloc_size, int& stub_size) {
346 // Compute size of each block, method size, and relocation information size
347 uint nblocks = _cfg->number_of_blocks();
349 uint* jmp_offset = NEW_RESOURCE_ARRAY(uint,nblocks);
350 uint* jmp_size = NEW_RESOURCE_ARRAY(uint,nblocks);
351 int* jmp_nidx = NEW_RESOURCE_ARRAY(int ,nblocks);
353 // Collect worst case block paddings
354 int* block_worst_case_pad = NEW_RESOURCE_ARRAY(int, nblocks);
355 memset(block_worst_case_pad, 0, nblocks * sizeof(int));
357 DEBUG_ONLY( uint *jmp_target = NEW_RESOURCE_ARRAY(uint,nblocks); )
358 DEBUG_ONLY( uint *jmp_rule = NEW_RESOURCE_ARRAY(uint,nblocks); )
360 bool has_short_branch_candidate = false;
362 // Initialize the sizes to 0
363 code_size = 0; // Size in bytes of generated code
364 stub_size = 0; // Size in bytes of all stub entries
365 // Size in bytes of all relocation entries, including those in local stubs.
366 // Start with 2-bytes of reloc info for the unvalidated entry point
367 reloc_size = 1; // Number of relocation entries
369 // Make three passes. The first computes pessimistic blk_starts,
370 // relative jmp_offset and reloc_size information. The second performs
371 // short branch substitution using the pessimistic sizing. The
372 // third inserts nops where needed.
374 // Step one, perform a pessimistic sizing pass.
375 uint last_call_adr = max_uint;
376 uint last_avoid_back_to_back_adr = max_uint;
377 uint nop_size = (new (this) MachNopNode())->size(_regalloc);
378 for (uint i = 0; i < nblocks; i++) { // For all blocks
379 Block* block = _cfg->get_block(i);
381 // During short branch replacement, we store the relative (to blk_starts)
382 // offset of jump in jmp_offset, rather than the absolute offset of jump.
383 // This is so that we do not need to recompute sizes of all nodes when
384 // we compute correct blk_starts in our next sizing pass.
385 jmp_offset[i] = 0;
386 jmp_size[i] = 0;
387 jmp_nidx[i] = -1;
388 DEBUG_ONLY( jmp_target[i] = 0; )
389 DEBUG_ONLY( jmp_rule[i] = 0; )
391 // Sum all instruction sizes to compute block size
392 uint last_inst = block->number_of_nodes();
393 uint blk_size = 0;
394 for (uint j = 0; j < last_inst; j++) {
395 Node* nj = block->get_node(j);
396 // Handle machine instruction nodes
397 if (nj->is_Mach()) {
398 MachNode *mach = nj->as_Mach();
399 blk_size += (mach->alignment_required() - 1) * relocInfo::addr_unit(); // assume worst case padding
400 reloc_size += mach->reloc();
401 if (mach->is_MachCall()) {
402 // add size information for trampoline stub
403 // class CallStubImpl is platform-specific and defined in the *.ad files.
404 stub_size += CallStubImpl::size_call_trampoline();
405 reloc_size += CallStubImpl::reloc_call_trampoline();
407 MachCallNode *mcall = mach->as_MachCall();
408 // This destination address is NOT PC-relative
410 mcall->method_set((intptr_t)mcall->entry_point());
412 if (mcall->is_MachCallJava() && mcall->as_MachCallJava()->_method) {
413 stub_size += CompiledStaticCall::to_interp_stub_size();
414 reloc_size += CompiledStaticCall::reloc_to_interp_stub();
415 }
416 } else if (mach->is_MachSafePoint()) {
417 // If call/safepoint are adjacent, account for possible
418 // nop to disambiguate the two safepoints.
419 // ScheduleAndBundle() can rearrange nodes in a block,
420 // check for all offsets inside this block.
421 if (last_call_adr >= blk_starts[i]) {
422 blk_size += nop_size;
423 }
424 }
425 if (mach->avoid_back_to_back(MachNode::AVOID_BEFORE)) {
426 // Nop is inserted between "avoid back to back" instructions.
427 // ScheduleAndBundle() can rearrange nodes in a block,
428 // check for all offsets inside this block.
429 if (last_avoid_back_to_back_adr >= blk_starts[i]) {
430 blk_size += nop_size;
431 }
432 }
433 if (mach->may_be_short_branch()) {
434 if (!nj->is_MachBranch()) {
435 #ifndef PRODUCT
436 nj->dump(3);
437 #endif
438 Unimplemented();
439 }
440 assert(jmp_nidx[i] == -1, "block should have only one branch");
441 jmp_offset[i] = blk_size;
442 jmp_size[i] = nj->size(_regalloc);
443 jmp_nidx[i] = j;
444 has_short_branch_candidate = true;
445 }
446 }
447 blk_size += nj->size(_regalloc);
448 // Remember end of call offset
449 if (nj->is_MachCall() && !nj->is_MachCallLeaf()) {
450 last_call_adr = blk_starts[i]+blk_size;
451 }
452 // Remember end of avoid_back_to_back offset
453 if (nj->is_Mach() && nj->as_Mach()->avoid_back_to_back(MachNode::AVOID_AFTER)) {
454 last_avoid_back_to_back_adr = blk_starts[i]+blk_size;
455 }
456 }
458 // When the next block starts a loop, we may insert pad NOP
459 // instructions. Since we cannot know our future alignment,
460 // assume the worst.
461 if (i < nblocks - 1) {
462 Block* nb = _cfg->get_block(i + 1);
463 int max_loop_pad = nb->code_alignment()-relocInfo::addr_unit();
464 if (max_loop_pad > 0) {
465 assert(is_power_of_2(max_loop_pad+relocInfo::addr_unit()), "");
466 // Adjust last_call_adr and/or last_avoid_back_to_back_adr.
467 // If either is the last instruction in this block, bump by
468 // max_loop_pad in lock-step with blk_size, so sizing
469 // calculations in subsequent blocks still can conservatively
470 // detect that it may the last instruction in this block.
471 if (last_call_adr == blk_starts[i]+blk_size) {
472 last_call_adr += max_loop_pad;
473 }
474 if (last_avoid_back_to_back_adr == blk_starts[i]+blk_size) {
475 last_avoid_back_to_back_adr += max_loop_pad;
476 }
477 blk_size += max_loop_pad;
478 block_worst_case_pad[i + 1] = max_loop_pad;
479 }
480 }
482 // Save block size; update total method size
483 blk_starts[i+1] = blk_starts[i]+blk_size;
484 }
486 // Step two, replace eligible long jumps.
487 bool progress = true;
488 uint last_may_be_short_branch_adr = max_uint;
489 while (has_short_branch_candidate && progress) {
490 progress = false;
491 has_short_branch_candidate = false;
492 int adjust_block_start = 0;
493 for (uint i = 0; i < nblocks; i++) {
494 Block* block = _cfg->get_block(i);
495 int idx = jmp_nidx[i];
496 MachNode* mach = (idx == -1) ? NULL: block->get_node(idx)->as_Mach();
497 if (mach != NULL && mach->may_be_short_branch()) {
498 #ifdef ASSERT
499 assert(jmp_size[i] > 0 && mach->is_MachBranch(), "sanity");
500 int j;
501 // Find the branch; ignore trailing NOPs.
502 for (j = block->number_of_nodes()-1; j>=0; j--) {
503 Node* n = block->get_node(j);
504 if (!n->is_Mach() || n->as_Mach()->ideal_Opcode() != Op_Con)
505 break;
506 }
507 assert(j >= 0 && j == idx && block->get_node(j) == (Node*)mach, "sanity");
508 #endif
509 int br_size = jmp_size[i];
510 int br_offs = blk_starts[i] + jmp_offset[i];
512 // This requires the TRUE branch target be in succs[0]
513 uint bnum = block->non_connector_successor(0)->_pre_order;
514 int offset = blk_starts[bnum] - br_offs;
515 if (bnum > i) { // adjust following block's offset
516 offset -= adjust_block_start;
517 }
519 // This block can be a loop header, account for the padding
520 // in the previous block.
521 int block_padding = block_worst_case_pad[i];
522 assert(i == 0 || block_padding == 0 || br_offs >= block_padding, "Should have at least a padding on top");
523 // In the following code a nop could be inserted before
524 // the branch which will increase the backward distance.
525 bool needs_padding = ((uint)(br_offs - block_padding) == last_may_be_short_branch_adr);
526 assert(!needs_padding || jmp_offset[i] == 0, "padding only branches at the beginning of block");
528 if (needs_padding && offset <= 0)
529 offset -= nop_size;
531 if (_matcher->is_short_branch_offset(mach->rule(), br_size, offset)) {
532 // We've got a winner. Replace this branch.
533 MachNode* replacement = mach->as_MachBranch()->short_branch_version(this);
535 // Update the jmp_size.
536 int new_size = replacement->size(_regalloc);
537 int diff = br_size - new_size;
538 assert(diff >= (int)nop_size, "short_branch size should be smaller");
539 // Conservatively take into account padding between
540 // avoid_back_to_back branches. Previous branch could be
541 // converted into avoid_back_to_back branch during next
542 // rounds.
543 if (needs_padding && replacement->avoid_back_to_back(MachNode::AVOID_BEFORE)) {
544 jmp_offset[i] += nop_size;
545 diff -= nop_size;
546 }
547 adjust_block_start += diff;
548 block->map_node(replacement, idx);
549 mach->subsume_by(replacement, C);
550 mach = replacement;
551 progress = true;
553 jmp_size[i] = new_size;
554 DEBUG_ONLY( jmp_target[i] = bnum; );
555 DEBUG_ONLY( jmp_rule[i] = mach->rule(); );
556 } else {
557 // The jump distance is not short, try again during next iteration.
558 has_short_branch_candidate = true;
559 }
560 } // (mach->may_be_short_branch())
561 if (mach != NULL && (mach->may_be_short_branch() ||
562 mach->avoid_back_to_back(MachNode::AVOID_AFTER))) {
563 last_may_be_short_branch_adr = blk_starts[i] + jmp_offset[i] + jmp_size[i];
564 }
565 blk_starts[i+1] -= adjust_block_start;
566 }
567 }
569 #ifdef ASSERT
570 for (uint i = 0; i < nblocks; i++) { // For all blocks
571 if (jmp_target[i] != 0) {
572 int br_size = jmp_size[i];
573 int offset = blk_starts[jmp_target[i]]-(blk_starts[i] + jmp_offset[i]);
574 if (!_matcher->is_short_branch_offset(jmp_rule[i], br_size, offset)) {
575 tty->print_cr("target (%d) - jmp_offset(%d) = offset (%d), jump_size(%d), jmp_block B%d, target_block B%d", blk_starts[jmp_target[i]], blk_starts[i] + jmp_offset[i], offset, br_size, i, jmp_target[i]);
576 }
577 assert(_matcher->is_short_branch_offset(jmp_rule[i], br_size, offset), "Displacement too large for short jmp");
578 }
579 }
580 #endif
582 // Step 3, compute the offsets of all blocks, will be done in fill_buffer()
583 // after ScheduleAndBundle().
585 // ------------------
586 // Compute size for code buffer
587 code_size = blk_starts[nblocks];
589 // Relocation records
590 reloc_size += 1; // Relo entry for exception handler
592 // Adjust reloc_size to number of record of relocation info
593 // Min is 2 bytes, max is probably 6 or 8, with a tax up to 25% for
594 // a relocation index.
595 // The CodeBuffer will expand the locs array if this estimate is too low.
596 reloc_size *= 10 / sizeof(relocInfo);
597 }
599 //------------------------------FillLocArray-----------------------------------
600 // Create a bit of debug info and append it to the array. The mapping is from
601 // Java local or expression stack to constant, register or stack-slot. For
602 // doubles, insert 2 mappings and return 1 (to tell the caller that the next
603 // entry has been taken care of and caller should skip it).
604 static LocationValue *new_loc_value( PhaseRegAlloc *ra, OptoReg::Name regnum, Location::Type l_type ) {
605 // This should never have accepted Bad before
606 assert(OptoReg::is_valid(regnum), "location must be valid");
607 return (OptoReg::is_reg(regnum))
608 ? new LocationValue(Location::new_reg_loc(l_type, OptoReg::as_VMReg(regnum)) )
609 : new LocationValue(Location::new_stk_loc(l_type, ra->reg2offset(regnum)));
610 }
613 ObjectValue*
614 Compile::sv_for_node_id(GrowableArray<ScopeValue*> *objs, int id) {
615 for (int i = 0; i < objs->length(); i++) {
616 assert(objs->at(i)->is_object(), "corrupt object cache");
617 ObjectValue* sv = (ObjectValue*) objs->at(i);
618 if (sv->id() == id) {
619 return sv;
620 }
621 }
622 // Otherwise..
623 return NULL;
624 }
626 void Compile::set_sv_for_object_node(GrowableArray<ScopeValue*> *objs,
627 ObjectValue* sv ) {
628 assert(sv_for_node_id(objs, sv->id()) == NULL, "Precondition");
629 objs->append(sv);
630 }
633 void Compile::FillLocArray( int idx, MachSafePointNode* sfpt, Node *local,
634 GrowableArray<ScopeValue*> *array,
635 GrowableArray<ScopeValue*> *objs ) {
636 assert( local, "use _top instead of null" );
637 if (array->length() != idx) {
638 assert(array->length() == idx + 1, "Unexpected array count");
639 // Old functionality:
640 // return
641 // New functionality:
642 // Assert if the local is not top. In product mode let the new node
643 // override the old entry.
644 assert(local == top(), "LocArray collision");
645 if (local == top()) {
646 return;
647 }
648 array->pop();
649 }
650 const Type *t = local->bottom_type();
652 // Is it a safepoint scalar object node?
653 if (local->is_SafePointScalarObject()) {
654 SafePointScalarObjectNode* spobj = local->as_SafePointScalarObject();
656 ObjectValue* sv = Compile::sv_for_node_id(objs, spobj->_idx);
657 if (sv == NULL) {
658 ciKlass* cik = t->is_oopptr()->klass();
659 assert(cik->is_instance_klass() ||
660 cik->is_array_klass(), "Not supported allocation.");
661 sv = new ObjectValue(spobj->_idx,
662 new ConstantOopWriteValue(cik->java_mirror()->constant_encoding()));
663 Compile::set_sv_for_object_node(objs, sv);
665 uint first_ind = spobj->first_index(sfpt->jvms());
666 for (uint i = 0; i < spobj->n_fields(); i++) {
667 Node* fld_node = sfpt->in(first_ind+i);
668 (void)FillLocArray(sv->field_values()->length(), sfpt, fld_node, sv->field_values(), objs);
669 }
670 }
671 array->append(sv);
672 return;
673 }
675 // Grab the register number for the local
676 OptoReg::Name regnum = _regalloc->get_reg_first(local);
677 if( OptoReg::is_valid(regnum) ) {// Got a register/stack?
678 // Record the double as two float registers.
679 // The register mask for such a value always specifies two adjacent
680 // float registers, with the lower register number even.
681 // Normally, the allocation of high and low words to these registers
682 // is irrelevant, because nearly all operations on register pairs
683 // (e.g., StoreD) treat them as a single unit.
684 // Here, we assume in addition that the words in these two registers
685 // stored "naturally" (by operations like StoreD and double stores
686 // within the interpreter) such that the lower-numbered register
687 // is written to the lower memory address. This may seem like
688 // a machine dependency, but it is not--it is a requirement on
689 // the author of the <arch>.ad file to ensure that, for every
690 // even/odd double-register pair to which a double may be allocated,
691 // the word in the even single-register is stored to the first
692 // memory word. (Note that register numbers are completely
693 // arbitrary, and are not tied to any machine-level encodings.)
694 #ifdef _LP64
695 if( t->base() == Type::DoubleBot || t->base() == Type::DoubleCon ) {
696 array->append(new ConstantIntValue(0));
697 array->append(new_loc_value( _regalloc, regnum, Location::dbl ));
698 } else if ( t->base() == Type::Long ) {
699 array->append(new ConstantIntValue(0));
700 array->append(new_loc_value( _regalloc, regnum, Location::lng ));
701 } else if ( t->base() == Type::RawPtr ) {
702 // jsr/ret return address which must be restored into a the full
703 // width 64-bit stack slot.
704 array->append(new_loc_value( _regalloc, regnum, Location::lng ));
705 }
706 #else //_LP64
707 #ifdef SPARC
708 if (t->base() == Type::Long && OptoReg::is_reg(regnum)) {
709 // For SPARC we have to swap high and low words for
710 // long values stored in a single-register (g0-g7).
711 array->append(new_loc_value( _regalloc, regnum , Location::normal ));
712 array->append(new_loc_value( _regalloc, OptoReg::add(regnum,1), Location::normal ));
713 } else
714 #endif //SPARC
715 if( t->base() == Type::DoubleBot || t->base() == Type::DoubleCon || t->base() == Type::Long ) {
716 // Repack the double/long as two jints.
717 // The convention the interpreter uses is that the second local
718 // holds the first raw word of the native double representation.
719 // This is actually reasonable, since locals and stack arrays
720 // grow downwards in all implementations.
721 // (If, on some machine, the interpreter's Java locals or stack
722 // were to grow upwards, the embedded doubles would be word-swapped.)
723 array->append(new_loc_value( _regalloc, OptoReg::add(regnum,1), Location::normal ));
724 array->append(new_loc_value( _regalloc, regnum , Location::normal ));
725 }
726 #endif //_LP64
727 else if( (t->base() == Type::FloatBot || t->base() == Type::FloatCon) &&
728 OptoReg::is_reg(regnum) ) {
729 array->append(new_loc_value( _regalloc, regnum, Matcher::float_in_double()
730 ? Location::float_in_dbl : Location::normal ));
731 } else if( t->base() == Type::Int && OptoReg::is_reg(regnum) ) {
732 array->append(new_loc_value( _regalloc, regnum, Matcher::int_in_long
733 ? Location::int_in_long : Location::normal ));
734 } else if( t->base() == Type::NarrowOop ) {
735 array->append(new_loc_value( _regalloc, regnum, Location::narrowoop ));
736 } else {
737 array->append(new_loc_value( _regalloc, regnum, _regalloc->is_oop(local) ? Location::oop : Location::normal ));
738 }
739 return;
740 }
742 // No register. It must be constant data.
743 switch (t->base()) {
744 case Type::Half: // Second half of a double
745 ShouldNotReachHere(); // Caller should skip 2nd halves
746 break;
747 case Type::AnyPtr:
748 array->append(new ConstantOopWriteValue(NULL));
749 break;
750 case Type::AryPtr:
751 case Type::InstPtr: // fall through
752 array->append(new ConstantOopWriteValue(t->isa_oopptr()->const_oop()->constant_encoding()));
753 break;
754 case Type::NarrowOop:
755 if (t == TypeNarrowOop::NULL_PTR) {
756 array->append(new ConstantOopWriteValue(NULL));
757 } else {
758 array->append(new ConstantOopWriteValue(t->make_ptr()->isa_oopptr()->const_oop()->constant_encoding()));
759 }
760 break;
761 case Type::Int:
762 array->append(new ConstantIntValue(t->is_int()->get_con()));
763 break;
764 case Type::RawPtr:
765 // A return address (T_ADDRESS).
766 assert((intptr_t)t->is_ptr()->get_con() < (intptr_t)0x10000, "must be a valid BCI");
767 #ifdef _LP64
768 // Must be restored to the full-width 64-bit stack slot.
769 array->append(new ConstantLongValue(t->is_ptr()->get_con()));
770 #else
771 array->append(new ConstantIntValue(t->is_ptr()->get_con()));
772 #endif
773 break;
774 case Type::FloatCon: {
775 float f = t->is_float_constant()->getf();
776 array->append(new ConstantIntValue(jint_cast(f)));
777 break;
778 }
779 case Type::DoubleCon: {
780 jdouble d = t->is_double_constant()->getd();
781 #ifdef _LP64
782 array->append(new ConstantIntValue(0));
783 array->append(new ConstantDoubleValue(d));
784 #else
785 // Repack the double as two jints.
786 // The convention the interpreter uses is that the second local
787 // holds the first raw word of the native double representation.
788 // This is actually reasonable, since locals and stack arrays
789 // grow downwards in all implementations.
790 // (If, on some machine, the interpreter's Java locals or stack
791 // were to grow upwards, the embedded doubles would be word-swapped.)
792 jlong_accessor acc;
793 acc.long_value = jlong_cast(d);
794 array->append(new ConstantIntValue(acc.words[1]));
795 array->append(new ConstantIntValue(acc.words[0]));
796 #endif
797 break;
798 }
799 case Type::Long: {
800 jlong d = t->is_long()->get_con();
801 #ifdef _LP64
802 array->append(new ConstantIntValue(0));
803 array->append(new ConstantLongValue(d));
804 #else
805 // Repack the long as two jints.
806 // The convention the interpreter uses is that the second local
807 // holds the first raw word of the native double representation.
808 // This is actually reasonable, since locals and stack arrays
809 // grow downwards in all implementations.
810 // (If, on some machine, the interpreter's Java locals or stack
811 // were to grow upwards, the embedded doubles would be word-swapped.)
812 jlong_accessor acc;
813 acc.long_value = d;
814 array->append(new ConstantIntValue(acc.words[1]));
815 array->append(new ConstantIntValue(acc.words[0]));
816 #endif
817 break;
818 }
819 case Type::Top: // Add an illegal value here
820 array->append(new LocationValue(Location()));
821 break;
822 default:
823 ShouldNotReachHere();
824 break;
825 }
826 }
828 // Determine if this node starts a bundle
829 bool Compile::starts_bundle(const Node *n) const {
830 return (_node_bundling_limit > n->_idx &&
831 _node_bundling_base[n->_idx].starts_bundle());
832 }
834 //--------------------------Process_OopMap_Node--------------------------------
835 void Compile::Process_OopMap_Node(MachNode *mach, int current_offset) {
837 // Handle special safepoint nodes for synchronization
838 MachSafePointNode *sfn = mach->as_MachSafePoint();
839 MachCallNode *mcall;
841 #ifdef ENABLE_ZAP_DEAD_LOCALS
842 assert( is_node_getting_a_safepoint(mach), "logic does not match; false negative");
843 #endif
845 int safepoint_pc_offset = current_offset;
846 bool is_method_handle_invoke = false;
847 bool return_oop = false;
849 // Add the safepoint in the DebugInfoRecorder
850 if( !mach->is_MachCall() ) {
851 mcall = NULL;
852 #ifdef MIPS64
853 /*
854 2013/10/30 Jin: safepoint_pc_offset should point to tha last instruction in safePoint.
855 In X86 and sparc, their safePoints only contain one instruction.
856 However, we should add current_offset with the size of safePoint in MIPS.
857 0x2d6ff22c: lw s2, 0x14(s2)
858 last_pd->pc_offset()=308, pc_offset=304, bci=64
859 last_pd->pc_offset()=312, pc_offset=312, bci=64
860 /mnt/openjdk6/hotspot/src/share/vm/code/debugInfoRec.cpp, 289 , assert(last_pd->pc_offset() == pc_offset,"must be last pc")
862 ;; Safepoint:
863 ---> pc_offset=304
864 0x2d6ff230: lui at, 0x2b7a ; OopMap{s2=Oop s5=Oop t4=Oop off=308}
865 ;*goto
866 ; - java.util.Hashtable::get@64 (line 353)
867 ---> last_pd(308)
868 0x2d6ff234: lw at, 0xffffc100(at) ;*goto
869 ; - java.util.Hashtable::get@64 (line 353)
870 ; {poll}
871 0x2d6ff238: addiu s0, zero, 0x0
872 */
873 safepoint_pc_offset += sfn->size(_regalloc) - 4;
874 #endif
875 debug_info()->add_safepoint(safepoint_pc_offset, sfn->_oop_map);
876 } else {
877 mcall = mach->as_MachCall();
879 // Is the call a MethodHandle call?
880 if (mcall->is_MachCallJava()) {
881 if (mcall->as_MachCallJava()->_method_handle_invoke) {
882 assert(has_method_handle_invokes(), "must have been set during call generation");
883 is_method_handle_invoke = true;
884 }
885 }
887 // Check if a call returns an object.
888 if (mcall->returns_pointer()) {
889 return_oop = true;
890 }
891 safepoint_pc_offset += mcall->ret_addr_offset();
892 debug_info()->add_safepoint(safepoint_pc_offset, mcall->_oop_map);
893 }
895 // Loop over the JVMState list to add scope information
896 // Do not skip safepoints with a NULL method, they need monitor info
897 JVMState* youngest_jvms = sfn->jvms();
898 int max_depth = youngest_jvms->depth();
900 // Allocate the object pool for scalar-replaced objects -- the map from
901 // small-integer keys (which can be recorded in the local and ostack
902 // arrays) to descriptions of the object state.
903 GrowableArray<ScopeValue*> *objs = new GrowableArray<ScopeValue*>();
905 // Visit scopes from oldest to youngest.
906 for (int depth = 1; depth <= max_depth; depth++) {
907 JVMState* jvms = youngest_jvms->of_depth(depth);
908 int idx;
909 ciMethod* method = jvms->has_method() ? jvms->method() : NULL;
910 // Safepoints that do not have method() set only provide oop-map and monitor info
911 // to support GC; these do not support deoptimization.
912 int num_locs = (method == NULL) ? 0 : jvms->loc_size();
913 int num_exps = (method == NULL) ? 0 : jvms->stk_size();
914 int num_mon = jvms->nof_monitors();
915 assert(method == NULL || jvms->bci() < 0 || num_locs == method->max_locals(),
916 "JVMS local count must match that of the method");
918 // Add Local and Expression Stack Information
920 // Insert locals into the locarray
921 GrowableArray<ScopeValue*> *locarray = new GrowableArray<ScopeValue*>(num_locs);
922 for( idx = 0; idx < num_locs; idx++ ) {
923 FillLocArray( idx, sfn, sfn->local(jvms, idx), locarray, objs );
924 }
926 // Insert expression stack entries into the exparray
927 GrowableArray<ScopeValue*> *exparray = new GrowableArray<ScopeValue*>(num_exps);
928 for( idx = 0; idx < num_exps; idx++ ) {
929 FillLocArray( idx, sfn, sfn->stack(jvms, idx), exparray, objs );
930 }
932 // Add in mappings of the monitors
933 assert( !method ||
934 !method->is_synchronized() ||
935 method->is_native() ||
936 num_mon > 0 ||
937 !GenerateSynchronizationCode,
938 "monitors must always exist for synchronized methods");
940 // Build the growable array of ScopeValues for exp stack
941 GrowableArray<MonitorValue*> *monarray = new GrowableArray<MonitorValue*>(num_mon);
943 // Loop over monitors and insert into array
944 for (idx = 0; idx < num_mon; idx++) {
945 // Grab the node that defines this monitor
946 Node* box_node = sfn->monitor_box(jvms, idx);
947 Node* obj_node = sfn->monitor_obj(jvms, idx);
949 // Create ScopeValue for object
950 ScopeValue *scval = NULL;
952 if (obj_node->is_SafePointScalarObject()) {
953 SafePointScalarObjectNode* spobj = obj_node->as_SafePointScalarObject();
954 scval = Compile::sv_for_node_id(objs, spobj->_idx);
955 if (scval == NULL) {
956 const Type *t = spobj->bottom_type();
957 ciKlass* cik = t->is_oopptr()->klass();
958 assert(cik->is_instance_klass() ||
959 cik->is_array_klass(), "Not supported allocation.");
960 ObjectValue* sv = new ObjectValue(spobj->_idx,
961 new ConstantOopWriteValue(cik->java_mirror()->constant_encoding()));
962 Compile::set_sv_for_object_node(objs, sv);
964 uint first_ind = spobj->first_index(youngest_jvms);
965 for (uint i = 0; i < spobj->n_fields(); i++) {
966 Node* fld_node = sfn->in(first_ind+i);
967 (void)FillLocArray(sv->field_values()->length(), sfn, fld_node, sv->field_values(), objs);
968 }
969 scval = sv;
970 }
971 } else if (!obj_node->is_Con()) {
972 OptoReg::Name obj_reg = _regalloc->get_reg_first(obj_node);
973 if( obj_node->bottom_type()->base() == Type::NarrowOop ) {
974 scval = new_loc_value( _regalloc, obj_reg, Location::narrowoop );
975 } else {
976 scval = new_loc_value( _regalloc, obj_reg, Location::oop );
977 }
978 } else {
979 const TypePtr *tp = obj_node->get_ptr_type();
980 scval = new ConstantOopWriteValue(tp->is_oopptr()->const_oop()->constant_encoding());
981 }
983 OptoReg::Name box_reg = BoxLockNode::reg(box_node);
984 Location basic_lock = Location::new_stk_loc(Location::normal,_regalloc->reg2offset(box_reg));
985 bool eliminated = (box_node->is_BoxLock() && box_node->as_BoxLock()->is_eliminated());
986 monarray->append(new MonitorValue(scval, basic_lock, eliminated));
987 }
989 // We dump the object pool first, since deoptimization reads it in first.
990 debug_info()->dump_object_pool(objs);
992 // Build first class objects to pass to scope
993 DebugToken *locvals = debug_info()->create_scope_values(locarray);
994 DebugToken *expvals = debug_info()->create_scope_values(exparray);
995 DebugToken *monvals = debug_info()->create_monitor_values(monarray);
997 // Make method available for all Safepoints
998 ciMethod* scope_method = method ? method : _method;
999 // Describe the scope here
1000 assert(jvms->bci() >= InvocationEntryBci && jvms->bci() <= 0x10000, "must be a valid or entry BCI");
1001 assert(!jvms->should_reexecute() || depth == max_depth, "reexecute allowed only for the youngest");
1002 // Now we can describe the scope.
1003 debug_info()->describe_scope(safepoint_pc_offset, scope_method, jvms->bci(), jvms->should_reexecute(), is_method_handle_invoke, return_oop, locvals, expvals, monvals);
1004 } // End jvms loop
1006 // Mark the end of the scope set.
1007 debug_info()->end_safepoint(safepoint_pc_offset);
1008 }
1012 // A simplified version of Process_OopMap_Node, to handle non-safepoints.
1013 class NonSafepointEmitter {
1014 Compile* C;
1015 JVMState* _pending_jvms;
1016 int _pending_offset;
1018 void emit_non_safepoint();
1020 public:
1021 NonSafepointEmitter(Compile* compile) {
1022 this->C = compile;
1023 _pending_jvms = NULL;
1024 _pending_offset = 0;
1025 }
1027 void observe_instruction(Node* n, int pc_offset) {
1028 if (!C->debug_info()->recording_non_safepoints()) return;
1030 Node_Notes* nn = C->node_notes_at(n->_idx);
1031 if (nn == NULL || nn->jvms() == NULL) return;
1032 if (_pending_jvms != NULL &&
1033 _pending_jvms->same_calls_as(nn->jvms())) {
1034 // Repeated JVMS? Stretch it up here.
1035 _pending_offset = pc_offset;
1036 } else {
1037 if (_pending_jvms != NULL &&
1038 _pending_offset < pc_offset) {
1039 emit_non_safepoint();
1040 }
1041 _pending_jvms = NULL;
1042 if (pc_offset > C->debug_info()->last_pc_offset()) {
1043 // This is the only way _pending_jvms can become non-NULL:
1044 _pending_jvms = nn->jvms();
1045 _pending_offset = pc_offset;
1046 }
1047 }
1048 }
1050 // Stay out of the way of real safepoints:
1051 void observe_safepoint(JVMState* jvms, int pc_offset) {
1052 if (_pending_jvms != NULL &&
1053 !_pending_jvms->same_calls_as(jvms) &&
1054 _pending_offset < pc_offset) {
1055 emit_non_safepoint();
1056 }
1057 _pending_jvms = NULL;
1058 }
1060 void flush_at_end() {
1061 if (_pending_jvms != NULL) {
1062 emit_non_safepoint();
1063 }
1064 _pending_jvms = NULL;
1065 }
1066 };
1068 void NonSafepointEmitter::emit_non_safepoint() {
1069 JVMState* youngest_jvms = _pending_jvms;
1070 int pc_offset = _pending_offset;
1072 // Clear it now:
1073 _pending_jvms = NULL;
1075 DebugInformationRecorder* debug_info = C->debug_info();
1076 assert(debug_info->recording_non_safepoints(), "sanity");
1078 debug_info->add_non_safepoint(pc_offset);
1079 int max_depth = youngest_jvms->depth();
1081 // Visit scopes from oldest to youngest.
1082 for (int depth = 1; depth <= max_depth; depth++) {
1083 JVMState* jvms = youngest_jvms->of_depth(depth);
1084 ciMethod* method = jvms->has_method() ? jvms->method() : NULL;
1085 assert(!jvms->should_reexecute() || depth==max_depth, "reexecute allowed only for the youngest");
1086 debug_info->describe_scope(pc_offset, method, jvms->bci(), jvms->should_reexecute());
1087 }
1089 // Mark the end of the scope set.
1090 debug_info->end_non_safepoint(pc_offset);
1091 }
1093 //------------------------------init_buffer------------------------------------
1094 CodeBuffer* Compile::init_buffer(uint* blk_starts) {
1096 // Set the initially allocated size
1097 int code_req = initial_code_capacity;
1098 int locs_req = initial_locs_capacity;
1099 int stub_req = TraceJumps ? initial_stub_capacity * 10 : initial_stub_capacity;
1100 int const_req = initial_const_capacity;
1102 int pad_req = NativeCall::instruction_size;
1103 // The extra spacing after the code is necessary on some platforms.
1104 // Sometimes we need to patch in a jump after the last instruction,
1105 // if the nmethod has been deoptimized. (See 4932387, 4894843.)
1107 // Compute the byte offset where we can store the deopt pc.
1108 if (fixed_slots() != 0) {
1109 _orig_pc_slot_offset_in_bytes = _regalloc->reg2offset(OptoReg::stack2reg(_orig_pc_slot));
1110 }
1112 // Compute prolog code size
1113 _method_size = 0;
1114 _frame_slots = OptoReg::reg2stack(_matcher->_old_SP)+_regalloc->_framesize;
1115 #if defined(IA64) && !defined(AIX)
1116 if (save_argument_registers()) {
1117 // 4815101: this is a stub with implicit and unknown precision fp args.
1118 // The usual spill mechanism can only generate stfd's in this case, which
1119 // doesn't work if the fp reg to spill contains a single-precision denorm.
1120 // Instead, we hack around the normal spill mechanism using stfspill's and
1121 // ldffill's in the MachProlog and MachEpilog emit methods. We allocate
1122 // space here for the fp arg regs (f8-f15) we're going to thusly spill.
1123 //
1124 // If we ever implement 16-byte 'registers' == stack slots, we can
1125 // get rid of this hack and have SpillCopy generate stfspill/ldffill
1126 // instead of stfd/stfs/ldfd/ldfs.
1127 _frame_slots += 8*(16/BytesPerInt);
1128 }
1129 #endif
1130 assert(_frame_slots >= 0 && _frame_slots < 1000000, "sanity check");
1132 if (has_mach_constant_base_node()) {
1133 uint add_size = 0;
1134 // Fill the constant table.
1135 // Note: This must happen before shorten_branches.
1136 for (uint i = 0; i < _cfg->number_of_blocks(); i++) {
1137 Block* b = _cfg->get_block(i);
1139 for (uint j = 0; j < b->number_of_nodes(); j++) {
1140 Node* n = b->get_node(j);
1142 // If the node is a MachConstantNode evaluate the constant
1143 // value section.
1144 if (n->is_MachConstant()) {
1145 MachConstantNode* machcon = n->as_MachConstant();
1146 machcon->eval_constant(C);
1147 } else if (n->is_Mach()) {
1148 // On Power there are more nodes that issue constants.
1149 add_size += (n->as_Mach()->ins_num_consts() * 8);
1150 }
1151 }
1152 }
1154 // Calculate the offsets of the constants and the size of the
1155 // constant table (including the padding to the next section).
1156 constant_table().calculate_offsets_and_size();
1157 const_req = constant_table().size() + add_size;
1158 }
1160 // Initialize the space for the BufferBlob used to find and verify
1161 // instruction size in MachNode::emit_size()
1162 init_scratch_buffer_blob(const_req);
1163 if (failing()) return NULL; // Out of memory
1165 // Pre-compute the length of blocks and replace
1166 // long branches with short if machine supports it.
1167 shorten_branches(blk_starts, code_req, locs_req, stub_req);
1169 // nmethod and CodeBuffer count stubs & constants as part of method's code.
1170 // class HandlerImpl is platform-specific and defined in the *.ad files.
1171 int exception_handler_req = HandlerImpl::size_exception_handler() + MAX_stubs_size; // add marginal slop for handler
1172 int deopt_handler_req = HandlerImpl::size_deopt_handler() + MAX_stubs_size; // add marginal slop for handler
1173 stub_req += MAX_stubs_size; // ensure per-stub margin
1174 code_req += MAX_inst_size; // ensure per-instruction margin
1176 if (StressCodeBuffers)
1177 code_req = const_req = stub_req = exception_handler_req = deopt_handler_req = 0x10; // force expansion
1179 int total_req =
1180 const_req +
1181 code_req +
1182 pad_req +
1183 stub_req +
1184 exception_handler_req +
1185 deopt_handler_req; // deopt handler
1187 if (has_method_handle_invokes())
1188 total_req += deopt_handler_req; // deopt MH handler
1190 CodeBuffer* cb = code_buffer();
1191 cb->initialize(total_req, locs_req);
1193 // Have we run out of code space?
1194 if ((cb->blob() == NULL) || (!CompileBroker::should_compile_new_jobs())) {
1195 C->record_failure("CodeCache is full");
1196 return NULL;
1197 }
1198 // Configure the code buffer.
1199 cb->initialize_consts_size(const_req);
1200 cb->initialize_stubs_size(stub_req);
1201 cb->initialize_oop_recorder(env()->oop_recorder());
1203 // fill in the nop array for bundling computations
1204 MachNode *_nop_list[Bundle::_nop_count];
1205 Bundle::initialize_nops(_nop_list, this);
1207 return cb;
1208 }
1210 //------------------------------fill_buffer------------------------------------
1211 void Compile::fill_buffer(CodeBuffer* cb, uint* blk_starts) {
1212 // blk_starts[] contains offsets calculated during short branches processing,
1213 // offsets should not be increased during following steps.
1215 // Compute the size of first NumberOfLoopInstrToAlign instructions at head
1216 // of a loop. It is used to determine the padding for loop alignment.
1217 compute_loop_first_inst_sizes();
1219 // Create oopmap set.
1220 _oop_map_set = new OopMapSet();
1222 // !!!!! This preserves old handling of oopmaps for now
1223 debug_info()->set_oopmaps(_oop_map_set);
1225 uint nblocks = _cfg->number_of_blocks();
1226 // Count and start of implicit null check instructions
1227 uint inct_cnt = 0;
1228 uint *inct_starts = NEW_RESOURCE_ARRAY(uint, nblocks+1);
1230 // Count and start of calls
1231 uint *call_returns = NEW_RESOURCE_ARRAY(uint, nblocks+1);
1233 uint return_offset = 0;
1234 int nop_size = (new (this) MachNopNode())->size(_regalloc);
1236 int previous_offset = 0;
1237 int current_offset = 0;
1238 int last_call_offset = -1;
1239 int last_avoid_back_to_back_offset = -1;
1240 #ifdef ASSERT
1241 uint* jmp_target = NEW_RESOURCE_ARRAY(uint,nblocks);
1242 uint* jmp_offset = NEW_RESOURCE_ARRAY(uint,nblocks);
1243 uint* jmp_size = NEW_RESOURCE_ARRAY(uint,nblocks);
1244 uint* jmp_rule = NEW_RESOURCE_ARRAY(uint,nblocks);
1245 #endif
1247 // Create an array of unused labels, one for each basic block, if printing is enabled
1248 #ifndef PRODUCT
1249 int *node_offsets = NULL;
1250 uint node_offset_limit = unique();
1252 if (print_assembly())
1253 node_offsets = NEW_RESOURCE_ARRAY(int, node_offset_limit);
1254 #endif
1256 NonSafepointEmitter non_safepoints(this); // emit non-safepoints lazily
1258 // Emit the constant table.
1259 if (has_mach_constant_base_node()) {
1260 constant_table().emit(*cb);
1261 }
1263 // Create an array of labels, one for each basic block
1264 Label *blk_labels = NEW_RESOURCE_ARRAY(Label, nblocks+1);
1265 for (uint i=0; i <= nblocks; i++) {
1266 blk_labels[i].init();
1267 }
1269 // ------------------
1270 // Now fill in the code buffer
1271 Node *delay_slot = NULL;
1273 for (uint i = 0; i < nblocks; i++) {
1274 Block* block = _cfg->get_block(i);
1275 Node* head = block->head();
1277 // If this block needs to start aligned (i.e, can be reached other
1278 // than by falling-thru from the previous block), then force the
1279 // start of a new bundle.
1280 if (Pipeline::requires_bundling() && starts_bundle(head)) {
1281 cb->flush_bundle(true);
1282 }
1284 #ifdef ASSERT
1285 if (!block->is_connector()) {
1286 stringStream st;
1287 block->dump_head(_cfg, &st);
1288 MacroAssembler(cb).block_comment(st.as_string());
1289 }
1290 jmp_target[i] = 0;
1291 jmp_offset[i] = 0;
1292 jmp_size[i] = 0;
1293 jmp_rule[i] = 0;
1294 #endif
1295 int blk_offset = current_offset;
1297 // Define the label at the beginning of the basic block
1298 MacroAssembler(cb).bind(blk_labels[block->_pre_order]);
1300 uint last_inst = block->number_of_nodes();
1302 // Emit block normally, except for last instruction.
1303 // Emit means "dump code bits into code buffer".
1304 for (uint j = 0; j<last_inst; j++) {
1306 // Get the node
1307 Node* n = block->get_node(j);
1309 // See if delay slots are supported
1310 if (valid_bundle_info(n) &&
1311 node_bundling(n)->used_in_unconditional_delay()) {
1312 assert(delay_slot == NULL, "no use of delay slot node");
1313 assert(n->size(_regalloc) == Pipeline::instr_unit_size(), "delay slot instruction wrong size");
1315 delay_slot = n;
1316 continue;
1317 }
1319 // If this starts a new instruction group, then flush the current one
1320 // (but allow split bundles)
1321 if (Pipeline::requires_bundling() && starts_bundle(n))
1322 cb->flush_bundle(false);
1324 // The following logic is duplicated in the code ifdeffed for
1325 // ENABLE_ZAP_DEAD_LOCALS which appears above in this file. It
1326 // should be factored out. Or maybe dispersed to the nodes?
1328 // Special handling for SafePoint/Call Nodes
1329 bool is_mcall = false;
1330 if (n->is_Mach()) {
1331 MachNode *mach = n->as_Mach();
1332 is_mcall = n->is_MachCall();
1333 bool is_sfn = n->is_MachSafePoint();
1335 // If this requires all previous instructions be flushed, then do so
1336 if (is_sfn || is_mcall || mach->alignment_required() != 1) {
1337 cb->flush_bundle(true);
1338 current_offset = cb->insts_size();
1339 }
1341 // A padding may be needed again since a previous instruction
1342 // could be moved to delay slot.
1344 // align the instruction if necessary
1345 int padding = mach->compute_padding(current_offset);
1346 // Make sure safepoint node for polling is distinct from a call's
1347 // return by adding a nop if needed.
1348 if (is_sfn && !is_mcall && padding == 0 && current_offset == last_call_offset) {
1349 padding = nop_size;
1350 }
1351 if (padding == 0 && mach->avoid_back_to_back(MachNode::AVOID_BEFORE) &&
1352 current_offset == last_avoid_back_to_back_offset) {
1353 // Avoid back to back some instructions.
1354 padding = nop_size;
1355 }
1357 if(padding > 0) {
1358 assert((padding % nop_size) == 0, "padding is not a multiple of NOP size");
1359 int nops_cnt = padding / nop_size;
1360 MachNode *nop = new (this) MachNopNode(nops_cnt);
1361 block->insert_node(nop, j++);
1362 last_inst++;
1363 _cfg->map_node_to_block(nop, block);
1364 nop->emit(*cb, _regalloc);
1365 cb->flush_bundle(true);
1366 current_offset = cb->insts_size();
1367 }
1369 // Remember the start of the last call in a basic block
1370 if (is_mcall) {
1371 MachCallNode *mcall = mach->as_MachCall();
1373 // This destination address is NOT PC-relative
1374 mcall->method_set((intptr_t)mcall->entry_point());
1376 // Save the return address
1377 call_returns[block->_pre_order] = current_offset + mcall->ret_addr_offset();
1379 if (mcall->is_MachCallLeaf()) {
1380 is_mcall = false;
1381 is_sfn = false;
1382 }
1383 }
1385 // sfn will be valid whenever mcall is valid now because of inheritance
1386 if (is_sfn || is_mcall) {
1388 // Handle special safepoint nodes for synchronization
1389 if (!is_mcall) {
1390 MachSafePointNode *sfn = mach->as_MachSafePoint();
1391 // !!!!! Stubs only need an oopmap right now, so bail out
1392 if (sfn->jvms()->method() == NULL) {
1393 // Write the oopmap directly to the code blob??!!
1394 # ifdef ENABLE_ZAP_DEAD_LOCALS
1395 assert( !is_node_getting_a_safepoint(sfn), "logic does not match; false positive");
1396 # endif
1397 continue;
1398 }
1399 } // End synchronization
1401 non_safepoints.observe_safepoint(mach->as_MachSafePoint()->jvms(),
1402 current_offset);
1403 Process_OopMap_Node(mach, current_offset);
1404 } // End if safepoint
1406 // If this is a null check, then add the start of the previous instruction to the list
1407 else if( mach->is_MachNullCheck() ) {
1408 inct_starts[inct_cnt++] = previous_offset;
1409 }
1411 // If this is a branch, then fill in the label with the target BB's label
1412 else if (mach->is_MachBranch()) {
1413 // This requires the TRUE branch target be in succs[0]
1414 uint block_num = block->non_connector_successor(0)->_pre_order;
1416 // Try to replace long branch if delay slot is not used,
1417 // it is mostly for back branches since forward branch's
1418 // distance is not updated yet.
1419 bool delay_slot_is_used = valid_bundle_info(n) &&
1420 node_bundling(n)->use_unconditional_delay();
1421 if (!delay_slot_is_used && mach->may_be_short_branch()) {
1422 assert(delay_slot == NULL, "not expecting delay slot node");
1423 int br_size = n->size(_regalloc);
1424 int offset = blk_starts[block_num] - current_offset;
1425 if (block_num >= i) {
1426 // Current and following block's offset are not
1427 // finalized yet, adjust distance by the difference
1428 // between calculated and final offsets of current block.
1429 offset -= (blk_starts[i] - blk_offset);
1430 }
1431 // In the following code a nop could be inserted before
1432 // the branch which will increase the backward distance.
1433 bool needs_padding = (current_offset == last_avoid_back_to_back_offset);
1434 if (needs_padding && offset <= 0)
1435 offset -= nop_size;
1437 if (_matcher->is_short_branch_offset(mach->rule(), br_size, offset)) {
1438 // We've got a winner. Replace this branch.
1439 MachNode* replacement = mach->as_MachBranch()->short_branch_version(this);
1441 // Update the jmp_size.
1442 int new_size = replacement->size(_regalloc);
1443 assert((br_size - new_size) >= (int)nop_size, "short_branch size should be smaller");
1444 // Insert padding between avoid_back_to_back branches.
1445 if (needs_padding && replacement->avoid_back_to_back(MachNode::AVOID_BEFORE)) {
1446 MachNode *nop = new (this) MachNopNode();
1447 block->insert_node(nop, j++);
1448 _cfg->map_node_to_block(nop, block);
1449 last_inst++;
1450 nop->emit(*cb, _regalloc);
1451 cb->flush_bundle(true);
1452 current_offset = cb->insts_size();
1453 }
1454 #ifdef ASSERT
1455 jmp_target[i] = block_num;
1456 jmp_offset[i] = current_offset - blk_offset;
1457 jmp_size[i] = new_size;
1458 jmp_rule[i] = mach->rule();
1459 #endif
1460 block->map_node(replacement, j);
1461 mach->subsume_by(replacement, C);
1462 n = replacement;
1463 mach = replacement;
1464 }
1465 }
1466 mach->as_MachBranch()->label_set( &blk_labels[block_num], block_num );
1467 } else if (mach->ideal_Opcode() == Op_Jump) {
1468 for (uint h = 0; h < block->_num_succs; h++) {
1469 Block* succs_block = block->_succs[h];
1470 for (uint j = 1; j < succs_block->num_preds(); j++) {
1471 Node* jpn = succs_block->pred(j);
1472 if (jpn->is_JumpProj() && jpn->in(0) == mach) {
1473 uint block_num = succs_block->non_connector()->_pre_order;
1474 Label *blkLabel = &blk_labels[block_num];
1475 mach->add_case_label(jpn->as_JumpProj()->proj_no(), blkLabel);
1476 }
1477 }
1478 }
1479 }
1480 #ifdef ASSERT
1481 // Check that oop-store precedes the card-mark
1482 else if (mach->ideal_Opcode() == Op_StoreCM) {
1483 uint storeCM_idx = j;
1484 int count = 0;
1485 for (uint prec = mach->req(); prec < mach->len(); prec++) {
1486 Node *oop_store = mach->in(prec); // Precedence edge
1487 if (oop_store == NULL) continue;
1488 count++;
1489 uint i4;
1490 for (i4 = 0; i4 < last_inst; ++i4) {
1491 if (block->get_node(i4) == oop_store) {
1492 break;
1493 }
1494 }
1495 // Note: This test can provide a false failure if other precedence
1496 // edges have been added to the storeCMNode.
1497 assert(i4 == last_inst || i4 < storeCM_idx, "CM card-mark executes before oop-store");
1498 }
1499 assert(count > 0, "storeCM expects at least one precedence edge");
1500 }
1501 #endif
1502 else if (!n->is_Proj()) {
1503 // Remember the beginning of the previous instruction, in case
1504 // it's followed by a flag-kill and a null-check. Happens on
1505 // Intel all the time, with add-to-memory kind of opcodes.
1506 previous_offset = current_offset;
1507 }
1509 // Not an else-if!
1510 // If this is a trap based cmp then add its offset to the list.
1511 if (mach->is_TrapBasedCheckNode()) {
1512 inct_starts[inct_cnt++] = current_offset;
1513 }
1514 }
1516 // Verify that there is sufficient space remaining
1517 cb->insts()->maybe_expand_to_ensure_remaining(MAX_inst_size);
1518 if ((cb->blob() == NULL) || (!CompileBroker::should_compile_new_jobs())) {
1519 C->record_failure("CodeCache is full");
1520 return;
1521 }
1523 // Save the offset for the listing
1524 #ifndef PRODUCT
1525 if (node_offsets && n->_idx < node_offset_limit)
1526 node_offsets[n->_idx] = cb->insts_size();
1527 #endif
1529 // "Normal" instruction case
1530 DEBUG_ONLY( uint instr_offset = cb->insts_size(); )
1531 n->emit(*cb, _regalloc);
1532 current_offset = cb->insts_size();
1533 #ifdef MIPS64
1534 if (!n->is_Proj()) {
1535 // For MIPS, the first instruction of the previous node (usually a instruction sequence) sometime
1536 // is not the instruction which access memory. adjust is needed. previous_offset points to the
1537 // instruction which access memory. Instruction size is 4. cb->insts_size() and
1538 // cb->insts()->end() are the location of current instruction.
1539 int adjust = 4;
1540 NativeInstruction* inst = (NativeInstruction*) (cb->insts()->end() - 4);
1541 if (inst->is_sync()) {
1542 // a sync may be the last instruction, see store_B_immI_enc_sync
1543 adjust += 4;
1544 inst = (NativeInstruction*) (cb->insts()->end() - 8);
1545 }
1546 if (PatchContinuousLoad) {
1547 // if PatchContinuousLoad is true, a nop may be inserted after a load instruction and
1548 // the adjust would be 2 instructions.
1549 if (inst->is_nop()) {
1550 adjust += 4;
1551 }
1552 }
1553 previous_offset = current_offset - adjust;
1554 }
1555 #endif
1557 #ifdef ASSERT
1558 if (n->size(_regalloc) < (current_offset-instr_offset)) {
1559 n->dump();
1560 assert(false, "wrong size of mach node");
1561 }
1562 #endif
1563 non_safepoints.observe_instruction(n, current_offset);
1565 // mcall is last "call" that can be a safepoint
1566 // record it so we can see if a poll will directly follow it
1567 // in which case we'll need a pad to make the PcDesc sites unique
1568 // see 5010568. This can be slightly inaccurate but conservative
1569 // in the case that return address is not actually at current_offset.
1570 // This is a small price to pay.
1572 if (is_mcall) {
1573 last_call_offset = current_offset;
1574 }
1576 if (n->is_Mach() && n->as_Mach()->avoid_back_to_back(MachNode::AVOID_AFTER)) {
1577 // Avoid back to back some instructions.
1578 last_avoid_back_to_back_offset = current_offset;
1579 }
1581 // See if this instruction has a delay slot
1582 if (valid_bundle_info(n) && node_bundling(n)->use_unconditional_delay()) {
1583 assert(delay_slot != NULL, "expecting delay slot node");
1585 // Back up 1 instruction
1586 cb->set_insts_end(cb->insts_end() - Pipeline::instr_unit_size());
1588 // Save the offset for the listing
1589 #ifndef PRODUCT
1590 if (node_offsets && delay_slot->_idx < node_offset_limit)
1591 node_offsets[delay_slot->_idx] = cb->insts_size();
1592 #endif
1594 // Support a SafePoint in the delay slot
1595 if (delay_slot->is_MachSafePoint()) {
1596 MachNode *mach = delay_slot->as_Mach();
1597 // !!!!! Stubs only need an oopmap right now, so bail out
1598 if (!mach->is_MachCall() && mach->as_MachSafePoint()->jvms()->method() == NULL) {
1599 // Write the oopmap directly to the code blob??!!
1600 # ifdef ENABLE_ZAP_DEAD_LOCALS
1601 assert( !is_node_getting_a_safepoint(mach), "logic does not match; false positive");
1602 # endif
1603 delay_slot = NULL;
1604 continue;
1605 }
1607 int adjusted_offset = current_offset - Pipeline::instr_unit_size();
1608 non_safepoints.observe_safepoint(mach->as_MachSafePoint()->jvms(),
1609 adjusted_offset);
1610 // Generate an OopMap entry
1611 Process_OopMap_Node(mach, adjusted_offset);
1612 }
1614 // Insert the delay slot instruction
1615 delay_slot->emit(*cb, _regalloc);
1617 // Don't reuse it
1618 delay_slot = NULL;
1619 }
1621 } // End for all instructions in block
1623 // If the next block is the top of a loop, pad this block out to align
1624 // the loop top a little. Helps prevent pipe stalls at loop back branches.
1625 if (i < nblocks-1) {
1626 Block *nb = _cfg->get_block(i + 1);
1627 int padding = nb->alignment_padding(current_offset);
1628 if( padding > 0 ) {
1629 MachNode *nop = new (this) MachNopNode(padding / nop_size);
1630 block->insert_node(nop, block->number_of_nodes());
1631 _cfg->map_node_to_block(nop, block);
1632 nop->emit(*cb, _regalloc);
1633 current_offset = cb->insts_size();
1634 }
1635 }
1636 // Verify that the distance for generated before forward
1637 // short branches is still valid.
1638 guarantee((int)(blk_starts[i+1] - blk_starts[i]) >= (current_offset - blk_offset), "shouldn't increase block size");
1640 // Save new block start offset
1641 blk_starts[i] = blk_offset;
1642 } // End of for all blocks
1643 blk_starts[nblocks] = current_offset;
1645 non_safepoints.flush_at_end();
1647 // Offset too large?
1648 if (failing()) return;
1650 // Define a pseudo-label at the end of the code
1651 MacroAssembler(cb).bind( blk_labels[nblocks] );
1653 // Compute the size of the first block
1654 _first_block_size = blk_labels[1].loc_pos() - blk_labels[0].loc_pos();
1656 assert(cb->insts_size() < 500000, "method is unreasonably large");
1658 #ifdef ASSERT
1659 for (uint i = 0; i < nblocks; i++) { // For all blocks
1660 if (jmp_target[i] != 0) {
1661 int br_size = jmp_size[i];
1662 int offset = blk_starts[jmp_target[i]]-(blk_starts[i] + jmp_offset[i]);
1663 if (!_matcher->is_short_branch_offset(jmp_rule[i], br_size, offset)) {
1664 tty->print_cr("target (%d) - jmp_offset(%d) = offset (%d), jump_size(%d), jmp_block B%d, target_block B%d", blk_starts[jmp_target[i]], blk_starts[i] + jmp_offset[i], offset, br_size, i, jmp_target[i]);
1665 assert(false, "Displacement too large for short jmp");
1666 }
1667 }
1668 }
1669 #endif
1671 #ifndef PRODUCT
1672 // Information on the size of the method, without the extraneous code
1673 Scheduling::increment_method_size(cb->insts_size());
1674 #endif
1676 // ------------------
1677 // Fill in exception table entries.
1678 FillExceptionTables(inct_cnt, call_returns, inct_starts, blk_labels);
1680 // Only java methods have exception handlers and deopt handlers
1681 // class HandlerImpl is platform-specific and defined in the *.ad files.
1682 if (_method) {
1683 // Emit the exception handler code.
1684 _code_offsets.set_value(CodeOffsets::Exceptions, HandlerImpl::emit_exception_handler(*cb));
1685 // Emit the deopt handler code.
1686 _code_offsets.set_value(CodeOffsets::Deopt, HandlerImpl::emit_deopt_handler(*cb));
1688 // Emit the MethodHandle deopt handler code (if required).
1689 if (has_method_handle_invokes()) {
1690 // We can use the same code as for the normal deopt handler, we
1691 // just need a different entry point address.
1692 _code_offsets.set_value(CodeOffsets::DeoptMH, HandlerImpl::emit_deopt_handler(*cb));
1693 }
1694 }
1696 // One last check for failed CodeBuffer::expand:
1697 if ((cb->blob() == NULL) || (!CompileBroker::should_compile_new_jobs())) {
1698 C->record_failure("CodeCache is full");
1699 return;
1700 }
1702 #ifndef PRODUCT
1703 // Dump the assembly code, including basic-block numbers
1704 if (print_assembly()) {
1705 ttyLocker ttyl; // keep the following output all in one block
1706 if (!VMThread::should_terminate()) { // test this under the tty lock
1707 // This output goes directly to the tty, not the compiler log.
1708 // To enable tools to match it up with the compilation activity,
1709 // be sure to tag this tty output with the compile ID.
1710 if (xtty != NULL) {
1711 xtty->head("opto_assembly compile_id='%d'%s", compile_id(),
1712 is_osr_compilation() ? " compile_kind='osr'" :
1713 "");
1714 }
1715 if (method() != NULL) {
1716 method()->print_metadata();
1717 }
1718 dump_asm(node_offsets, node_offset_limit);
1719 if (xtty != NULL) {
1720 xtty->tail("opto_assembly");
1721 }
1722 }
1723 }
1724 #endif
1726 }
1728 void Compile::FillExceptionTables(uint cnt, uint *call_returns, uint *inct_starts, Label *blk_labels) {
1729 _inc_table.set_size(cnt);
1731 uint inct_cnt = 0;
1732 for (uint i = 0; i < _cfg->number_of_blocks(); i++) {
1733 Block* block = _cfg->get_block(i);
1734 Node *n = NULL;
1735 int j;
1737 // Find the branch; ignore trailing NOPs.
1738 for (j = block->number_of_nodes() - 1; j >= 0; j--) {
1739 n = block->get_node(j);
1740 if (!n->is_Mach() || n->as_Mach()->ideal_Opcode() != Op_Con) {
1741 break;
1742 }
1743 }
1745 // If we didn't find anything, continue
1746 if (j < 0) {
1747 continue;
1748 }
1750 // Compute ExceptionHandlerTable subtable entry and add it
1751 // (skip empty blocks)
1752 if (n->is_Catch()) {
1754 // Get the offset of the return from the call
1755 uint call_return = call_returns[block->_pre_order];
1756 #ifdef ASSERT
1757 assert( call_return > 0, "no call seen for this basic block" );
1758 while (block->get_node(--j)->is_MachProj()) ;
1759 assert(block->get_node(j)->is_MachCall(), "CatchProj must follow call");
1760 #endif
1761 // last instruction is a CatchNode, find it's CatchProjNodes
1762 int nof_succs = block->_num_succs;
1763 // allocate space
1764 GrowableArray<intptr_t> handler_bcis(nof_succs);
1765 GrowableArray<intptr_t> handler_pcos(nof_succs);
1766 // iterate through all successors
1767 for (int j = 0; j < nof_succs; j++) {
1768 Block* s = block->_succs[j];
1769 bool found_p = false;
1770 for (uint k = 1; k < s->num_preds(); k++) {
1771 Node* pk = s->pred(k);
1772 if (pk->is_CatchProj() && pk->in(0) == n) {
1773 const CatchProjNode* p = pk->as_CatchProj();
1774 found_p = true;
1775 // add the corresponding handler bci & pco information
1776 if (p->_con != CatchProjNode::fall_through_index) {
1777 // p leads to an exception handler (and is not fall through)
1778 assert(s == _cfg->get_block(s->_pre_order), "bad numbering");
1779 // no duplicates, please
1780 if (!handler_bcis.contains(p->handler_bci())) {
1781 uint block_num = s->non_connector()->_pre_order;
1782 handler_bcis.append(p->handler_bci());
1783 handler_pcos.append(blk_labels[block_num].loc_pos());
1784 }
1785 }
1786 }
1787 }
1788 assert(found_p, "no matching predecessor found");
1789 // Note: Due to empty block removal, one block may have
1790 // several CatchProj inputs, from the same Catch.
1791 }
1793 // Set the offset of the return from the call
1794 _handler_table.add_subtable(call_return, &handler_bcis, NULL, &handler_pcos);
1795 continue;
1796 }
1798 // Handle implicit null exception table updates
1799 if (n->is_MachNullCheck()) {
1800 uint block_num = block->non_connector_successor(0)->_pre_order;
1801 _inc_table.append(inct_starts[inct_cnt++], blk_labels[block_num].loc_pos());
1802 continue;
1803 }
1804 // Handle implicit exception table updates: trap instructions.
1805 if (n->is_Mach() && n->as_Mach()->is_TrapBasedCheckNode()) {
1806 uint block_num = block->non_connector_successor(0)->_pre_order;
1807 _inc_table.append(inct_starts[inct_cnt++], blk_labels[block_num].loc_pos());
1808 continue;
1809 }
1810 } // End of for all blocks fill in exception table entries
1811 }
1813 // Static Variables
1814 #ifndef PRODUCT
1815 uint Scheduling::_total_nop_size = 0;
1816 uint Scheduling::_total_method_size = 0;
1817 uint Scheduling::_total_branches = 0;
1818 uint Scheduling::_total_unconditional_delays = 0;
1819 uint Scheduling::_total_instructions_per_bundle[Pipeline::_max_instrs_per_cycle+1];
1820 #endif
1822 // Initializer for class Scheduling
1824 Scheduling::Scheduling(Arena *arena, Compile &compile)
1825 : _arena(arena),
1826 _cfg(compile.cfg()),
1827 _regalloc(compile.regalloc()),
1828 _reg_node(arena),
1829 _bundle_instr_count(0),
1830 _bundle_cycle_number(0),
1831 _scheduled(arena),
1832 _available(arena),
1833 _next_node(NULL),
1834 _bundle_use(0, 0, resource_count, &_bundle_use_elements[0]),
1835 _pinch_free_list(arena)
1836 #ifndef PRODUCT
1837 , _branches(0)
1838 , _unconditional_delays(0)
1839 #endif
1840 {
1841 // Create a MachNopNode
1842 _nop = new (&compile) MachNopNode();
1844 // Now that the nops are in the array, save the count
1845 // (but allow entries for the nops)
1846 _node_bundling_limit = compile.unique();
1847 uint node_max = _regalloc->node_regs_max_index();
1849 compile.set_node_bundling_limit(_node_bundling_limit);
1851 // This one is persistent within the Compile class
1852 _node_bundling_base = NEW_ARENA_ARRAY(compile.comp_arena(), Bundle, node_max);
1854 // Allocate space for fixed-size arrays
1855 _node_latency = NEW_ARENA_ARRAY(arena, unsigned short, node_max);
1856 _uses = NEW_ARENA_ARRAY(arena, short, node_max);
1857 _current_latency = NEW_ARENA_ARRAY(arena, unsigned short, node_max);
1859 // Clear the arrays
1860 memset(_node_bundling_base, 0, node_max * sizeof(Bundle));
1861 memset(_node_latency, 0, node_max * sizeof(unsigned short));
1862 memset(_uses, 0, node_max * sizeof(short));
1863 memset(_current_latency, 0, node_max * sizeof(unsigned short));
1865 // Clear the bundling information
1866 memcpy(_bundle_use_elements, Pipeline_Use::elaborated_elements, sizeof(Pipeline_Use::elaborated_elements));
1868 // Get the last node
1869 Block* block = _cfg->get_block(_cfg->number_of_blocks() - 1);
1871 _next_node = block->get_node(block->number_of_nodes() - 1);
1872 }
1874 #ifndef PRODUCT
1875 // Scheduling destructor
1876 Scheduling::~Scheduling() {
1877 _total_branches += _branches;
1878 _total_unconditional_delays += _unconditional_delays;
1879 }
1880 #endif
1882 // Step ahead "i" cycles
1883 void Scheduling::step(uint i) {
1885 Bundle *bundle = node_bundling(_next_node);
1886 bundle->set_starts_bundle();
1888 // Update the bundle record, but leave the flags information alone
1889 if (_bundle_instr_count > 0) {
1890 bundle->set_instr_count(_bundle_instr_count);
1891 bundle->set_resources_used(_bundle_use.resourcesUsed());
1892 }
1894 // Update the state information
1895 _bundle_instr_count = 0;
1896 _bundle_cycle_number += i;
1897 _bundle_use.step(i);
1898 }
1900 void Scheduling::step_and_clear() {
1901 Bundle *bundle = node_bundling(_next_node);
1902 bundle->set_starts_bundle();
1904 // Update the bundle record
1905 if (_bundle_instr_count > 0) {
1906 bundle->set_instr_count(_bundle_instr_count);
1907 bundle->set_resources_used(_bundle_use.resourcesUsed());
1909 _bundle_cycle_number += 1;
1910 }
1912 // Clear the bundling information
1913 _bundle_instr_count = 0;
1914 _bundle_use.reset();
1916 memcpy(_bundle_use_elements,
1917 Pipeline_Use::elaborated_elements,
1918 sizeof(Pipeline_Use::elaborated_elements));
1919 }
1921 // Perform instruction scheduling and bundling over the sequence of
1922 // instructions in backwards order.
1923 void Compile::ScheduleAndBundle() {
1925 // Don't optimize this if it isn't a method
1926 if (!_method)
1927 return;
1929 // Don't optimize this if scheduling is disabled
1930 if (!do_scheduling())
1931 return;
1933 // Scheduling code works only with pairs (8 bytes) maximum.
1934 if (max_vector_size() > 8)
1935 return;
1937 NOT_PRODUCT( TracePhase t2("isched", &_t_instrSched, TimeCompiler); )
1939 // Create a data structure for all the scheduling information
1940 Scheduling scheduling(Thread::current()->resource_area(), *this);
1942 // Walk backwards over each basic block, computing the needed alignment
1943 // Walk over all the basic blocks
1944 scheduling.DoScheduling();
1945 }
1947 // Compute the latency of all the instructions. This is fairly simple,
1948 // because we already have a legal ordering. Walk over the instructions
1949 // from first to last, and compute the latency of the instruction based
1950 // on the latency of the preceding instruction(s).
1951 void Scheduling::ComputeLocalLatenciesForward(const Block *bb) {
1952 #ifndef PRODUCT
1953 if (_cfg->C->trace_opto_output())
1954 tty->print("# -> ComputeLocalLatenciesForward\n");
1955 #endif
1957 // Walk over all the schedulable instructions
1958 for( uint j=_bb_start; j < _bb_end; j++ ) {
1960 // This is a kludge, forcing all latency calculations to start at 1.
1961 // Used to allow latency 0 to force an instruction to the beginning
1962 // of the bb
1963 uint latency = 1;
1964 Node *use = bb->get_node(j);
1965 uint nlen = use->len();
1967 // Walk over all the inputs
1968 for ( uint k=0; k < nlen; k++ ) {
1969 Node *def = use->in(k);
1970 if (!def)
1971 continue;
1973 uint l = _node_latency[def->_idx] + use->latency(k);
1974 if (latency < l)
1975 latency = l;
1976 }
1978 _node_latency[use->_idx] = latency;
1980 #ifndef PRODUCT
1981 if (_cfg->C->trace_opto_output()) {
1982 tty->print("# latency %4d: ", latency);
1983 use->dump();
1984 }
1985 #endif
1986 }
1988 #ifndef PRODUCT
1989 if (_cfg->C->trace_opto_output())
1990 tty->print("# <- ComputeLocalLatenciesForward\n");
1991 #endif
1993 } // end ComputeLocalLatenciesForward
1995 // See if this node fits into the present instruction bundle
1996 bool Scheduling::NodeFitsInBundle(Node *n) {
1997 uint n_idx = n->_idx;
1999 // If this is the unconditional delay instruction, then it fits
2000 if (n == _unconditional_delay_slot) {
2001 #ifndef PRODUCT
2002 if (_cfg->C->trace_opto_output())
2003 tty->print("# NodeFitsInBundle [%4d]: TRUE; is in unconditional delay slot\n", n->_idx);
2004 #endif
2005 return (true);
2006 }
2008 // If the node cannot be scheduled this cycle, skip it
2009 if (_current_latency[n_idx] > _bundle_cycle_number) {
2010 #ifndef PRODUCT
2011 if (_cfg->C->trace_opto_output())
2012 tty->print("# NodeFitsInBundle [%4d]: FALSE; latency %4d > %d\n",
2013 n->_idx, _current_latency[n_idx], _bundle_cycle_number);
2014 #endif
2015 return (false);
2016 }
2018 const Pipeline *node_pipeline = n->pipeline();
2020 uint instruction_count = node_pipeline->instructionCount();
2021 if (node_pipeline->mayHaveNoCode() && n->size(_regalloc) == 0)
2022 instruction_count = 0;
2023 else if (node_pipeline->hasBranchDelay() && !_unconditional_delay_slot)
2024 instruction_count++;
2026 if (_bundle_instr_count + instruction_count > Pipeline::_max_instrs_per_cycle) {
2027 #ifndef PRODUCT
2028 if (_cfg->C->trace_opto_output())
2029 tty->print("# NodeFitsInBundle [%4d]: FALSE; too many instructions: %d > %d\n",
2030 n->_idx, _bundle_instr_count + instruction_count, Pipeline::_max_instrs_per_cycle);
2031 #endif
2032 return (false);
2033 }
2035 // Don't allow non-machine nodes to be handled this way
2036 if (!n->is_Mach() && instruction_count == 0)
2037 return (false);
2039 // See if there is any overlap
2040 uint delay = _bundle_use.full_latency(0, node_pipeline->resourceUse());
2042 if (delay > 0) {
2043 #ifndef PRODUCT
2044 if (_cfg->C->trace_opto_output())
2045 tty->print("# NodeFitsInBundle [%4d]: FALSE; functional units overlap\n", n_idx);
2046 #endif
2047 return false;
2048 }
2050 #ifndef PRODUCT
2051 if (_cfg->C->trace_opto_output())
2052 tty->print("# NodeFitsInBundle [%4d]: TRUE\n", n_idx);
2053 #endif
2055 return true;
2056 }
2058 Node * Scheduling::ChooseNodeToBundle() {
2059 uint siz = _available.size();
2061 if (siz == 0) {
2063 #ifndef PRODUCT
2064 if (_cfg->C->trace_opto_output())
2065 tty->print("# ChooseNodeToBundle: NULL\n");
2066 #endif
2067 return (NULL);
2068 }
2070 // Fast path, if only 1 instruction in the bundle
2071 if (siz == 1) {
2072 #ifndef PRODUCT
2073 if (_cfg->C->trace_opto_output()) {
2074 tty->print("# ChooseNodeToBundle (only 1): ");
2075 _available[0]->dump();
2076 }
2077 #endif
2078 return (_available[0]);
2079 }
2081 // Don't bother, if the bundle is already full
2082 if (_bundle_instr_count < Pipeline::_max_instrs_per_cycle) {
2083 for ( uint i = 0; i < siz; i++ ) {
2084 Node *n = _available[i];
2086 // Skip projections, we'll handle them another way
2087 if (n->is_Proj())
2088 continue;
2090 // This presupposed that instructions are inserted into the
2091 // available list in a legality order; i.e. instructions that
2092 // must be inserted first are at the head of the list
2093 if (NodeFitsInBundle(n)) {
2094 #ifndef PRODUCT
2095 if (_cfg->C->trace_opto_output()) {
2096 tty->print("# ChooseNodeToBundle: ");
2097 n->dump();
2098 }
2099 #endif
2100 return (n);
2101 }
2102 }
2103 }
2105 // Nothing fits in this bundle, choose the highest priority
2106 #ifndef PRODUCT
2107 if (_cfg->C->trace_opto_output()) {
2108 tty->print("# ChooseNodeToBundle: ");
2109 _available[0]->dump();
2110 }
2111 #endif
2113 return _available[0];
2114 }
2116 void Scheduling::AddNodeToAvailableList(Node *n) {
2117 assert( !n->is_Proj(), "projections never directly made available" );
2118 #ifndef PRODUCT
2119 if (_cfg->C->trace_opto_output()) {
2120 tty->print("# AddNodeToAvailableList: ");
2121 n->dump();
2122 }
2123 #endif
2125 int latency = _current_latency[n->_idx];
2127 // Insert in latency order (insertion sort)
2128 uint i;
2129 for ( i=0; i < _available.size(); i++ )
2130 if (_current_latency[_available[i]->_idx] > latency)
2131 break;
2133 // Special Check for compares following branches
2134 if( n->is_Mach() && _scheduled.size() > 0 ) {
2135 int op = n->as_Mach()->ideal_Opcode();
2136 Node *last = _scheduled[0];
2137 if( last->is_MachIf() && last->in(1) == n &&
2138 ( op == Op_CmpI ||
2139 op == Op_CmpU ||
2140 op == Op_CmpP ||
2141 op == Op_CmpF ||
2142 op == Op_CmpD ||
2143 op == Op_CmpL ) ) {
2145 // Recalculate position, moving to front of same latency
2146 for ( i=0 ; i < _available.size(); i++ )
2147 if (_current_latency[_available[i]->_idx] >= latency)
2148 break;
2149 }
2150 }
2152 // Insert the node in the available list
2153 _available.insert(i, n);
2155 #ifndef PRODUCT
2156 if (_cfg->C->trace_opto_output())
2157 dump_available();
2158 #endif
2159 }
2161 void Scheduling::DecrementUseCounts(Node *n, const Block *bb) {
2162 for ( uint i=0; i < n->len(); i++ ) {
2163 Node *def = n->in(i);
2164 if (!def) continue;
2165 if( def->is_Proj() ) // If this is a machine projection, then
2166 def = def->in(0); // propagate usage thru to the base instruction
2168 if(_cfg->get_block_for_node(def) != bb) { // Ignore if not block-local
2169 continue;
2170 }
2172 // Compute the latency
2173 uint l = _bundle_cycle_number + n->latency(i);
2174 if (_current_latency[def->_idx] < l)
2175 _current_latency[def->_idx] = l;
2177 // If this does not have uses then schedule it
2178 if ((--_uses[def->_idx]) == 0)
2179 AddNodeToAvailableList(def);
2180 }
2181 }
2183 void Scheduling::AddNodeToBundle(Node *n, const Block *bb) {
2184 #ifndef PRODUCT
2185 if (_cfg->C->trace_opto_output()) {
2186 tty->print("# AddNodeToBundle: ");
2187 n->dump();
2188 }
2189 #endif
2191 // Remove this from the available list
2192 uint i;
2193 for (i = 0; i < _available.size(); i++)
2194 if (_available[i] == n)
2195 break;
2196 assert(i < _available.size(), "entry in _available list not found");
2197 _available.remove(i);
2199 // See if this fits in the current bundle
2200 const Pipeline *node_pipeline = n->pipeline();
2201 const Pipeline_Use& node_usage = node_pipeline->resourceUse();
2203 // Check for instructions to be placed in the delay slot. We
2204 // do this before we actually schedule the current instruction,
2205 // because the delay slot follows the current instruction.
2206 if (Pipeline::_branch_has_delay_slot &&
2207 node_pipeline->hasBranchDelay() &&
2208 !_unconditional_delay_slot) {
2210 uint siz = _available.size();
2212 // Conditional branches can support an instruction that
2213 // is unconditionally executed and not dependent by the
2214 // branch, OR a conditionally executed instruction if
2215 // the branch is taken. In practice, this means that
2216 // the first instruction at the branch target is
2217 // copied to the delay slot, and the branch goes to
2218 // the instruction after that at the branch target
2219 if ( n->is_MachBranch() ) {
2221 assert( !n->is_MachNullCheck(), "should not look for delay slot for Null Check" );
2222 assert( !n->is_Catch(), "should not look for delay slot for Catch" );
2224 #ifndef PRODUCT
2225 _branches++;
2226 #endif
2228 // At least 1 instruction is on the available list
2229 // that is not dependent on the branch
2230 for (uint i = 0; i < siz; i++) {
2231 Node *d = _available[i];
2232 const Pipeline *avail_pipeline = d->pipeline();
2234 // Don't allow safepoints in the branch shadow, that will
2235 // cause a number of difficulties
2236 if ( avail_pipeline->instructionCount() == 1 &&
2237 !avail_pipeline->hasMultipleBundles() &&
2238 !avail_pipeline->hasBranchDelay() &&
2239 Pipeline::instr_has_unit_size() &&
2240 d->size(_regalloc) == Pipeline::instr_unit_size() &&
2241 NodeFitsInBundle(d) &&
2242 !node_bundling(d)->used_in_delay()) {
2244 if (d->is_Mach() && !d->is_MachSafePoint()) {
2245 // A node that fits in the delay slot was found, so we need to
2246 // set the appropriate bits in the bundle pipeline information so
2247 // that it correctly indicates resource usage. Later, when we
2248 // attempt to add this instruction to the bundle, we will skip
2249 // setting the resource usage.
2250 _unconditional_delay_slot = d;
2251 node_bundling(n)->set_use_unconditional_delay();
2252 node_bundling(d)->set_used_in_unconditional_delay();
2253 _bundle_use.add_usage(avail_pipeline->resourceUse());
2254 _current_latency[d->_idx] = _bundle_cycle_number;
2255 _next_node = d;
2256 ++_bundle_instr_count;
2257 #ifndef PRODUCT
2258 _unconditional_delays++;
2259 #endif
2260 break;
2261 }
2262 }
2263 }
2264 }
2266 // No delay slot, add a nop to the usage
2267 if (!_unconditional_delay_slot) {
2268 // See if adding an instruction in the delay slot will overflow
2269 // the bundle.
2270 if (!NodeFitsInBundle(_nop)) {
2271 #ifndef PRODUCT
2272 if (_cfg->C->trace_opto_output())
2273 tty->print("# *** STEP(1 instruction for delay slot) ***\n");
2274 #endif
2275 step(1);
2276 }
2278 _bundle_use.add_usage(_nop->pipeline()->resourceUse());
2279 _next_node = _nop;
2280 ++_bundle_instr_count;
2281 }
2283 // See if the instruction in the delay slot requires a
2284 // step of the bundles
2285 if (!NodeFitsInBundle(n)) {
2286 #ifndef PRODUCT
2287 if (_cfg->C->trace_opto_output())
2288 tty->print("# *** STEP(branch won't fit) ***\n");
2289 #endif
2290 // Update the state information
2291 _bundle_instr_count = 0;
2292 _bundle_cycle_number += 1;
2293 _bundle_use.step(1);
2294 }
2295 }
2297 // Get the number of instructions
2298 uint instruction_count = node_pipeline->instructionCount();
2299 if (node_pipeline->mayHaveNoCode() && n->size(_regalloc) == 0)
2300 instruction_count = 0;
2302 // Compute the latency information
2303 uint delay = 0;
2305 if (instruction_count > 0 || !node_pipeline->mayHaveNoCode()) {
2306 int relative_latency = _current_latency[n->_idx] - _bundle_cycle_number;
2307 if (relative_latency < 0)
2308 relative_latency = 0;
2310 delay = _bundle_use.full_latency(relative_latency, node_usage);
2312 // Does not fit in this bundle, start a new one
2313 if (delay > 0) {
2314 step(delay);
2316 #ifndef PRODUCT
2317 if (_cfg->C->trace_opto_output())
2318 tty->print("# *** STEP(%d) ***\n", delay);
2319 #endif
2320 }
2321 }
2323 // If this was placed in the delay slot, ignore it
2324 if (n != _unconditional_delay_slot) {
2326 if (delay == 0) {
2327 if (node_pipeline->hasMultipleBundles()) {
2328 #ifndef PRODUCT
2329 if (_cfg->C->trace_opto_output())
2330 tty->print("# *** STEP(multiple instructions) ***\n");
2331 #endif
2332 step(1);
2333 }
2335 else if (instruction_count + _bundle_instr_count > Pipeline::_max_instrs_per_cycle) {
2336 #ifndef PRODUCT
2337 if (_cfg->C->trace_opto_output())
2338 tty->print("# *** STEP(%d >= %d instructions) ***\n",
2339 instruction_count + _bundle_instr_count,
2340 Pipeline::_max_instrs_per_cycle);
2341 #endif
2342 step(1);
2343 }
2344 }
2346 if (node_pipeline->hasBranchDelay() && !_unconditional_delay_slot)
2347 _bundle_instr_count++;
2349 // Set the node's latency
2350 _current_latency[n->_idx] = _bundle_cycle_number;
2352 // Now merge the functional unit information
2353 if (instruction_count > 0 || !node_pipeline->mayHaveNoCode())
2354 _bundle_use.add_usage(node_usage);
2356 // Increment the number of instructions in this bundle
2357 _bundle_instr_count += instruction_count;
2359 // Remember this node for later
2360 if (n->is_Mach())
2361 _next_node = n;
2362 }
2364 // It's possible to have a BoxLock in the graph and in the _bbs mapping but
2365 // not in the bb->_nodes array. This happens for debug-info-only BoxLocks.
2366 // 'Schedule' them (basically ignore in the schedule) but do not insert them
2367 // into the block. All other scheduled nodes get put in the schedule here.
2368 int op = n->Opcode();
2369 if( (op == Op_Node && n->req() == 0) || // anti-dependence node OR
2370 (op != Op_Node && // Not an unused antidepedence node and
2371 // not an unallocated boxlock
2372 (OptoReg::is_valid(_regalloc->get_reg_first(n)) || op != Op_BoxLock)) ) {
2374 // Push any trailing projections
2375 if( bb->get_node(bb->number_of_nodes()-1) != n ) {
2376 for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
2377 Node *foi = n->fast_out(i);
2378 if( foi->is_Proj() )
2379 _scheduled.push(foi);
2380 }
2381 }
2383 // Put the instruction in the schedule list
2384 _scheduled.push(n);
2385 }
2387 #ifndef PRODUCT
2388 if (_cfg->C->trace_opto_output())
2389 dump_available();
2390 #endif
2392 // Walk all the definitions, decrementing use counts, and
2393 // if a definition has a 0 use count, place it in the available list.
2394 DecrementUseCounts(n,bb);
2395 }
2397 // This method sets the use count within a basic block. We will ignore all
2398 // uses outside the current basic block. As we are doing a backwards walk,
2399 // any node we reach that has a use count of 0 may be scheduled. This also
2400 // avoids the problem of cyclic references from phi nodes, as long as phi
2401 // nodes are at the front of the basic block. This method also initializes
2402 // the available list to the set of instructions that have no uses within this
2403 // basic block.
2404 void Scheduling::ComputeUseCount(const Block *bb) {
2405 #ifndef PRODUCT
2406 if (_cfg->C->trace_opto_output())
2407 tty->print("# -> ComputeUseCount\n");
2408 #endif
2410 // Clear the list of available and scheduled instructions, just in case
2411 _available.clear();
2412 _scheduled.clear();
2414 // No delay slot specified
2415 _unconditional_delay_slot = NULL;
2417 #ifdef ASSERT
2418 for( uint i=0; i < bb->number_of_nodes(); i++ )
2419 assert( _uses[bb->get_node(i)->_idx] == 0, "_use array not clean" );
2420 #endif
2422 // Force the _uses count to never go to zero for unscheduable pieces
2423 // of the block
2424 for( uint k = 0; k < _bb_start; k++ )
2425 _uses[bb->get_node(k)->_idx] = 1;
2426 for( uint l = _bb_end; l < bb->number_of_nodes(); l++ )
2427 _uses[bb->get_node(l)->_idx] = 1;
2429 // Iterate backwards over the instructions in the block. Don't count the
2430 // branch projections at end or the block header instructions.
2431 for( uint j = _bb_end-1; j >= _bb_start; j-- ) {
2432 Node *n = bb->get_node(j);
2433 if( n->is_Proj() ) continue; // Projections handled another way
2435 // Account for all uses
2436 for ( uint k = 0; k < n->len(); k++ ) {
2437 Node *inp = n->in(k);
2438 if (!inp) continue;
2439 assert(inp != n, "no cycles allowed" );
2440 if (_cfg->get_block_for_node(inp) == bb) { // Block-local use?
2441 if (inp->is_Proj()) { // Skip through Proj's
2442 inp = inp->in(0);
2443 }
2444 ++_uses[inp->_idx]; // Count 1 block-local use
2445 }
2446 }
2448 // If this instruction has a 0 use count, then it is available
2449 if (!_uses[n->_idx]) {
2450 _current_latency[n->_idx] = _bundle_cycle_number;
2451 AddNodeToAvailableList(n);
2452 }
2454 #ifndef PRODUCT
2455 if (_cfg->C->trace_opto_output()) {
2456 tty->print("# uses: %3d: ", _uses[n->_idx]);
2457 n->dump();
2458 }
2459 #endif
2460 }
2462 #ifndef PRODUCT
2463 if (_cfg->C->trace_opto_output())
2464 tty->print("# <- ComputeUseCount\n");
2465 #endif
2466 }
2468 // This routine performs scheduling on each basic block in reverse order,
2469 // using instruction latencies and taking into account function unit
2470 // availability.
2471 void Scheduling::DoScheduling() {
2472 #ifndef PRODUCT
2473 if (_cfg->C->trace_opto_output())
2474 tty->print("# -> DoScheduling\n");
2475 #endif
2477 Block *succ_bb = NULL;
2478 Block *bb;
2480 // Walk over all the basic blocks in reverse order
2481 for (int i = _cfg->number_of_blocks() - 1; i >= 0; succ_bb = bb, i--) {
2482 bb = _cfg->get_block(i);
2484 #ifndef PRODUCT
2485 if (_cfg->C->trace_opto_output()) {
2486 tty->print("# Schedule BB#%03d (initial)\n", i);
2487 for (uint j = 0; j < bb->number_of_nodes(); j++) {
2488 bb->get_node(j)->dump();
2489 }
2490 }
2491 #endif
2493 // On the head node, skip processing
2494 if (bb == _cfg->get_root_block()) {
2495 continue;
2496 }
2498 // Skip empty, connector blocks
2499 if (bb->is_connector())
2500 continue;
2502 // If the following block is not the sole successor of
2503 // this one, then reset the pipeline information
2504 if (bb->_num_succs != 1 || bb->non_connector_successor(0) != succ_bb) {
2505 #ifndef PRODUCT
2506 if (_cfg->C->trace_opto_output()) {
2507 tty->print("*** bundle start of next BB, node %d, for %d instructions\n",
2508 _next_node->_idx, _bundle_instr_count);
2509 }
2510 #endif
2511 step_and_clear();
2512 }
2514 // Leave untouched the starting instruction, any Phis, a CreateEx node
2515 // or Top. bb->get_node(_bb_start) is the first schedulable instruction.
2516 _bb_end = bb->number_of_nodes()-1;
2517 for( _bb_start=1; _bb_start <= _bb_end; _bb_start++ ) {
2518 Node *n = bb->get_node(_bb_start);
2519 // Things not matched, like Phinodes and ProjNodes don't get scheduled.
2520 // Also, MachIdealNodes do not get scheduled
2521 if( !n->is_Mach() ) continue; // Skip non-machine nodes
2522 MachNode *mach = n->as_Mach();
2523 int iop = mach->ideal_Opcode();
2524 if( iop == Op_CreateEx ) continue; // CreateEx is pinned
2525 if( iop == Op_Con ) continue; // Do not schedule Top
2526 if( iop == Op_Node && // Do not schedule PhiNodes, ProjNodes
2527 mach->pipeline() == MachNode::pipeline_class() &&
2528 !n->is_SpillCopy() && !n->is_MachMerge() ) // Breakpoints, Prolog, etc
2529 continue;
2530 break; // Funny loop structure to be sure...
2531 }
2532 // Compute last "interesting" instruction in block - last instruction we
2533 // might schedule. _bb_end points just after last schedulable inst. We
2534 // normally schedule conditional branches (despite them being forced last
2535 // in the block), because they have delay slots we can fill. Calls all
2536 // have their delay slots filled in the template expansions, so we don't
2537 // bother scheduling them.
2538 Node *last = bb->get_node(_bb_end);
2539 // Ignore trailing NOPs.
2540 while (_bb_end > 0 && last->is_Mach() &&
2541 last->as_Mach()->ideal_Opcode() == Op_Con) {
2542 last = bb->get_node(--_bb_end);
2543 }
2544 assert(!last->is_Mach() || last->as_Mach()->ideal_Opcode() != Op_Con, "");
2545 if( last->is_Catch() ||
2546 // Exclude unreachable path case when Halt node is in a separate block.
2547 (_bb_end > 1 && last->is_Mach() && last->as_Mach()->ideal_Opcode() == Op_Halt) ) {
2548 // There must be a prior call. Skip it.
2549 while( !bb->get_node(--_bb_end)->is_MachCall() ) {
2550 assert( bb->get_node(_bb_end)->is_MachProj(), "skipping projections after expected call" );
2551 }
2552 } else if( last->is_MachNullCheck() ) {
2553 // Backup so the last null-checked memory instruction is
2554 // outside the schedulable range. Skip over the nullcheck,
2555 // projection, and the memory nodes.
2556 Node *mem = last->in(1);
2557 do {
2558 _bb_end--;
2559 } while (mem != bb->get_node(_bb_end));
2560 } else {
2561 // Set _bb_end to point after last schedulable inst.
2562 _bb_end++;
2563 }
2565 assert( _bb_start <= _bb_end, "inverted block ends" );
2567 // Compute the register antidependencies for the basic block
2568 ComputeRegisterAntidependencies(bb);
2569 if (_cfg->C->failing()) return; // too many D-U pinch points
2571 // Compute intra-bb latencies for the nodes
2572 ComputeLocalLatenciesForward(bb);
2574 // Compute the usage within the block, and set the list of all nodes
2575 // in the block that have no uses within the block.
2576 ComputeUseCount(bb);
2578 // Schedule the remaining instructions in the block
2579 while ( _available.size() > 0 ) {
2580 Node *n = ChooseNodeToBundle();
2581 guarantee(n != NULL, "no nodes available");
2582 AddNodeToBundle(n,bb);
2583 }
2585 assert( _scheduled.size() == _bb_end - _bb_start, "wrong number of instructions" );
2586 #ifdef ASSERT
2587 for( uint l = _bb_start; l < _bb_end; l++ ) {
2588 Node *n = bb->get_node(l);
2589 uint m;
2590 for( m = 0; m < _bb_end-_bb_start; m++ )
2591 if( _scheduled[m] == n )
2592 break;
2593 assert( m < _bb_end-_bb_start, "instruction missing in schedule" );
2594 }
2595 #endif
2597 // Now copy the instructions (in reverse order) back to the block
2598 for ( uint k = _bb_start; k < _bb_end; k++ )
2599 bb->map_node(_scheduled[_bb_end-k-1], k);
2601 #ifndef PRODUCT
2602 if (_cfg->C->trace_opto_output()) {
2603 tty->print("# Schedule BB#%03d (final)\n", i);
2604 uint current = 0;
2605 for (uint j = 0; j < bb->number_of_nodes(); j++) {
2606 Node *n = bb->get_node(j);
2607 if( valid_bundle_info(n) ) {
2608 Bundle *bundle = node_bundling(n);
2609 if (bundle->instr_count() > 0 || bundle->flags() > 0) {
2610 tty->print("*** Bundle: ");
2611 bundle->dump();
2612 }
2613 n->dump();
2614 }
2615 }
2616 }
2617 #endif
2618 #ifdef ASSERT
2619 verify_good_schedule(bb,"after block local scheduling");
2620 #endif
2621 }
2623 #ifndef PRODUCT
2624 if (_cfg->C->trace_opto_output())
2625 tty->print("# <- DoScheduling\n");
2626 #endif
2628 // Record final node-bundling array location
2629 _regalloc->C->set_node_bundling_base(_node_bundling_base);
2631 } // end DoScheduling
2633 // Verify that no live-range used in the block is killed in the block by a
2634 // wrong DEF. This doesn't verify live-ranges that span blocks.
2636 // Check for edge existence. Used to avoid adding redundant precedence edges.
2637 static bool edge_from_to( Node *from, Node *to ) {
2638 for( uint i=0; i<from->len(); i++ )
2639 if( from->in(i) == to )
2640 return true;
2641 return false;
2642 }
2644 #ifdef ASSERT
2645 void Scheduling::verify_do_def( Node *n, OptoReg::Name def, const char *msg ) {
2646 // Check for bad kills
2647 if( OptoReg::is_valid(def) ) { // Ignore stores & control flow
2648 Node *prior_use = _reg_node[def];
2649 if( prior_use && !edge_from_to(prior_use,n) ) {
2650 tty->print("%s = ",OptoReg::as_VMReg(def)->name());
2651 n->dump();
2652 tty->print_cr("...");
2653 prior_use->dump();
2654 assert(edge_from_to(prior_use,n),msg);
2655 }
2656 _reg_node.map(def,NULL); // Kill live USEs
2657 }
2658 }
2660 void Scheduling::verify_good_schedule( Block *b, const char *msg ) {
2662 // Zap to something reasonable for the verify code
2663 _reg_node.clear();
2665 // Walk over the block backwards. Check to make sure each DEF doesn't
2666 // kill a live value (other than the one it's supposed to). Add each
2667 // USE to the live set.
2668 for( uint i = b->number_of_nodes()-1; i >= _bb_start; i-- ) {
2669 Node *n = b->get_node(i);
2670 int n_op = n->Opcode();
2671 if( n_op == Op_MachProj && n->ideal_reg() == MachProjNode::fat_proj ) {
2672 // Fat-proj kills a slew of registers
2673 RegMask rm = n->out_RegMask();// Make local copy
2674 while( rm.is_NotEmpty() ) {
2675 OptoReg::Name kill = rm.find_first_elem();
2676 rm.Remove(kill);
2677 verify_do_def( n, kill, msg );
2678 }
2679 } else if( n_op != Op_Node ) { // Avoid brand new antidependence nodes
2680 // Get DEF'd registers the normal way
2681 verify_do_def( n, _regalloc->get_reg_first(n), msg );
2682 verify_do_def( n, _regalloc->get_reg_second(n), msg );
2683 }
2685 // Now make all USEs live
2686 for( uint i=1; i<n->req(); i++ ) {
2687 Node *def = n->in(i);
2688 assert(def != 0, "input edge required");
2689 OptoReg::Name reg_lo = _regalloc->get_reg_first(def);
2690 OptoReg::Name reg_hi = _regalloc->get_reg_second(def);
2691 if( OptoReg::is_valid(reg_lo) ) {
2692 assert(!_reg_node[reg_lo] || edge_from_to(_reg_node[reg_lo],def), msg);
2693 _reg_node.map(reg_lo,n);
2694 }
2695 if( OptoReg::is_valid(reg_hi) ) {
2696 assert(!_reg_node[reg_hi] || edge_from_to(_reg_node[reg_hi],def), msg);
2697 _reg_node.map(reg_hi,n);
2698 }
2699 }
2701 }
2703 // Zap to something reasonable for the Antidependence code
2704 _reg_node.clear();
2705 }
2706 #endif
2708 // Conditionally add precedence edges. Avoid putting edges on Projs.
2709 static void add_prec_edge_from_to( Node *from, Node *to ) {
2710 if( from->is_Proj() ) { // Put precedence edge on Proj's input
2711 assert( from->req() == 1 && (from->len() == 1 || from->in(1)==0), "no precedence edges on projections" );
2712 from = from->in(0);
2713 }
2714 if( from != to && // No cycles (for things like LD L0,[L0+4] )
2715 !edge_from_to( from, to ) ) // Avoid duplicate edge
2716 from->add_prec(to);
2717 }
2719 void Scheduling::anti_do_def( Block *b, Node *def, OptoReg::Name def_reg, int is_def ) {
2720 if( !OptoReg::is_valid(def_reg) ) // Ignore stores & control flow
2721 return;
2723 Node *pinch = _reg_node[def_reg]; // Get pinch point
2724 if ((pinch == NULL) || _cfg->get_block_for_node(pinch) != b || // No pinch-point yet?
2725 is_def ) { // Check for a true def (not a kill)
2726 _reg_node.map(def_reg,def); // Record def/kill as the optimistic pinch-point
2727 return;
2728 }
2730 Node *kill = def; // Rename 'def' to more descriptive 'kill'
2731 debug_only( def = (Node*)0xdeadbeef; )
2733 // After some number of kills there _may_ be a later def
2734 Node *later_def = NULL;
2736 // Finding a kill requires a real pinch-point.
2737 // Check for not already having a pinch-point.
2738 // Pinch points are Op_Node's.
2739 if( pinch->Opcode() != Op_Node ) { // Or later-def/kill as pinch-point?
2740 later_def = pinch; // Must be def/kill as optimistic pinch-point
2741 if ( _pinch_free_list.size() > 0) {
2742 pinch = _pinch_free_list.pop();
2743 } else {
2744 pinch = new (_cfg->C) Node(1); // Pinch point to-be
2745 }
2746 if (pinch->_idx >= _regalloc->node_regs_max_index()) {
2747 _cfg->C->record_method_not_compilable("too many D-U pinch points");
2748 return;
2749 }
2750 _cfg->map_node_to_block(pinch, b); // Pretend it's valid in this block (lazy init)
2751 _reg_node.map(def_reg,pinch); // Record pinch-point
2752 //_regalloc->set_bad(pinch->_idx); // Already initialized this way.
2753 if( later_def->outcnt() == 0 || later_def->ideal_reg() == MachProjNode::fat_proj ) { // Distinguish def from kill
2754 pinch->init_req(0, _cfg->C->top()); // set not NULL for the next call
2755 add_prec_edge_from_to(later_def,pinch); // Add edge from kill to pinch
2756 later_def = NULL; // and no later def
2757 }
2758 pinch->set_req(0,later_def); // Hook later def so we can find it
2759 } else { // Else have valid pinch point
2760 if( pinch->in(0) ) // If there is a later-def
2761 later_def = pinch->in(0); // Get it
2762 }
2764 // Add output-dependence edge from later def to kill
2765 if( later_def ) // If there is some original def
2766 add_prec_edge_from_to(later_def,kill); // Add edge from def to kill
2768 // See if current kill is also a use, and so is forced to be the pinch-point.
2769 if( pinch->Opcode() == Op_Node ) {
2770 Node *uses = kill->is_Proj() ? kill->in(0) : kill;
2771 for( uint i=1; i<uses->req(); i++ ) {
2772 if( _regalloc->get_reg_first(uses->in(i)) == def_reg ||
2773 _regalloc->get_reg_second(uses->in(i)) == def_reg ) {
2774 // Yes, found a use/kill pinch-point
2775 pinch->set_req(0,NULL); //
2776 pinch->replace_by(kill); // Move anti-dep edges up
2777 pinch = kill;
2778 _reg_node.map(def_reg,pinch);
2779 return;
2780 }
2781 }
2782 }
2784 // Add edge from kill to pinch-point
2785 add_prec_edge_from_to(kill,pinch);
2786 }
2788 void Scheduling::anti_do_use( Block *b, Node *use, OptoReg::Name use_reg ) {
2789 if( !OptoReg::is_valid(use_reg) ) // Ignore stores & control flow
2790 return;
2791 Node *pinch = _reg_node[use_reg]; // Get pinch point
2792 // Check for no later def_reg/kill in block
2793 if ((pinch != NULL) && _cfg->get_block_for_node(pinch) == b &&
2794 // Use has to be block-local as well
2795 _cfg->get_block_for_node(use) == b) {
2796 if( pinch->Opcode() == Op_Node && // Real pinch-point (not optimistic?)
2797 pinch->req() == 1 ) { // pinch not yet in block?
2798 pinch->del_req(0); // yank pointer to later-def, also set flag
2799 // Insert the pinch-point in the block just after the last use
2800 b->insert_node(pinch, b->find_node(use) + 1);
2801 _bb_end++; // Increase size scheduled region in block
2802 }
2804 add_prec_edge_from_to(pinch,use);
2805 }
2806 }
2808 // We insert antidependences between the reads and following write of
2809 // allocated registers to prevent illegal code motion. Hopefully, the
2810 // number of added references should be fairly small, especially as we
2811 // are only adding references within the current basic block.
2812 void Scheduling::ComputeRegisterAntidependencies(Block *b) {
2814 #ifdef ASSERT
2815 verify_good_schedule(b,"before block local scheduling");
2816 #endif
2818 // A valid schedule, for each register independently, is an endless cycle
2819 // of: a def, then some uses (connected to the def by true dependencies),
2820 // then some kills (defs with no uses), finally the cycle repeats with a new
2821 // def. The uses are allowed to float relative to each other, as are the
2822 // kills. No use is allowed to slide past a kill (or def). This requires
2823 // antidependencies between all uses of a single def and all kills that
2824 // follow, up to the next def. More edges are redundant, because later defs
2825 // & kills are already serialized with true or antidependencies. To keep
2826 // the edge count down, we add a 'pinch point' node if there's more than
2827 // one use or more than one kill/def.
2829 // We add dependencies in one bottom-up pass.
2831 // For each instruction we handle it's DEFs/KILLs, then it's USEs.
2833 // For each DEF/KILL, we check to see if there's a prior DEF/KILL for this
2834 // register. If not, we record the DEF/KILL in _reg_node, the
2835 // register-to-def mapping. If there is a prior DEF/KILL, we insert a
2836 // "pinch point", a new Node that's in the graph but not in the block.
2837 // We put edges from the prior and current DEF/KILLs to the pinch point.
2838 // We put the pinch point in _reg_node. If there's already a pinch point
2839 // we merely add an edge from the current DEF/KILL to the pinch point.
2841 // After doing the DEF/KILLs, we handle USEs. For each used register, we
2842 // put an edge from the pinch point to the USE.
2844 // To be expedient, the _reg_node array is pre-allocated for the whole
2845 // compilation. _reg_node is lazily initialized; it either contains a NULL,
2846 // or a valid def/kill/pinch-point, or a leftover node from some prior
2847 // block. Leftover node from some prior block is treated like a NULL (no
2848 // prior def, so no anti-dependence needed). Valid def is distinguished by
2849 // it being in the current block.
2850 bool fat_proj_seen = false;
2851 uint last_safept = _bb_end-1;
2852 Node* end_node = (_bb_end-1 >= _bb_start) ? b->get_node(last_safept) : NULL;
2853 Node* last_safept_node = end_node;
2854 for( uint i = _bb_end-1; i >= _bb_start; i-- ) {
2855 Node *n = b->get_node(i);
2856 int is_def = n->outcnt(); // def if some uses prior to adding precedence edges
2857 if( n->is_MachProj() && n->ideal_reg() == MachProjNode::fat_proj ) {
2858 // Fat-proj kills a slew of registers
2859 // This can add edges to 'n' and obscure whether or not it was a def,
2860 // hence the is_def flag.
2861 fat_proj_seen = true;
2862 RegMask rm = n->out_RegMask();// Make local copy
2863 while( rm.is_NotEmpty() ) {
2864 OptoReg::Name kill = rm.find_first_elem();
2865 rm.Remove(kill);
2866 anti_do_def( b, n, kill, is_def );
2867 }
2868 } else {
2869 // Get DEF'd registers the normal way
2870 anti_do_def( b, n, _regalloc->get_reg_first(n), is_def );
2871 anti_do_def( b, n, _regalloc->get_reg_second(n), is_def );
2872 }
2874 // Kill projections on a branch should appear to occur on the
2875 // branch, not afterwards, so grab the masks from the projections
2876 // and process them.
2877 if (n->is_MachBranch() || n->is_Mach() && n->as_Mach()->ideal_Opcode() == Op_Jump) {
2878 for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
2879 Node* use = n->fast_out(i);
2880 if (use->is_Proj()) {
2881 RegMask rm = use->out_RegMask();// Make local copy
2882 while( rm.is_NotEmpty() ) {
2883 OptoReg::Name kill = rm.find_first_elem();
2884 rm.Remove(kill);
2885 anti_do_def( b, n, kill, false );
2886 }
2887 }
2888 }
2889 }
2891 // Check each register used by this instruction for a following DEF/KILL
2892 // that must occur afterward and requires an anti-dependence edge.
2893 for( uint j=0; j<n->req(); j++ ) {
2894 Node *def = n->in(j);
2895 if( def ) {
2896 assert( !def->is_MachProj() || def->ideal_reg() != MachProjNode::fat_proj, "" );
2897 anti_do_use( b, n, _regalloc->get_reg_first(def) );
2898 anti_do_use( b, n, _regalloc->get_reg_second(def) );
2899 }
2900 }
2901 // Do not allow defs of new derived values to float above GC
2902 // points unless the base is definitely available at the GC point.
2904 Node *m = b->get_node(i);
2906 // Add precedence edge from following safepoint to use of derived pointer
2907 if( last_safept_node != end_node &&
2908 m != last_safept_node) {
2909 for (uint k = 1; k < m->req(); k++) {
2910 const Type *t = m->in(k)->bottom_type();
2911 if( t->isa_oop_ptr() &&
2912 t->is_ptr()->offset() != 0 ) {
2913 last_safept_node->add_prec( m );
2914 break;
2915 }
2916 }
2917 }
2919 if( n->jvms() ) { // Precedence edge from derived to safept
2920 // Check if last_safept_node was moved by pinch-point insertion in anti_do_use()
2921 if( b->get_node(last_safept) != last_safept_node ) {
2922 last_safept = b->find_node(last_safept_node);
2923 }
2924 for( uint j=last_safept; j > i; j-- ) {
2925 Node *mach = b->get_node(j);
2926 if( mach->is_Mach() && mach->as_Mach()->ideal_Opcode() == Op_AddP )
2927 mach->add_prec( n );
2928 }
2929 last_safept = i;
2930 last_safept_node = m;
2931 }
2932 }
2934 if (fat_proj_seen) {
2935 // Garbage collect pinch nodes that were not consumed.
2936 // They are usually created by a fat kill MachProj for a call.
2937 garbage_collect_pinch_nodes();
2938 }
2939 }
2941 // Garbage collect pinch nodes for reuse by other blocks.
2942 //
2943 // The block scheduler's insertion of anti-dependence
2944 // edges creates many pinch nodes when the block contains
2945 // 2 or more Calls. A pinch node is used to prevent a
2946 // combinatorial explosion of edges. If a set of kills for a
2947 // register is anti-dependent on a set of uses (or defs), rather
2948 // than adding an edge in the graph between each pair of kill
2949 // and use (or def), a pinch is inserted between them:
2950 //
2951 // use1 use2 use3
2952 // \ | /
2953 // \ | /
2954 // pinch
2955 // / | \
2956 // / | \
2957 // kill1 kill2 kill3
2958 //
2959 // One pinch node is created per register killed when
2960 // the second call is encountered during a backwards pass
2961 // over the block. Most of these pinch nodes are never
2962 // wired into the graph because the register is never
2963 // used or def'ed in the block.
2964 //
2965 void Scheduling::garbage_collect_pinch_nodes() {
2966 #ifndef PRODUCT
2967 if (_cfg->C->trace_opto_output()) tty->print("Reclaimed pinch nodes:");
2968 #endif
2969 int trace_cnt = 0;
2970 for (uint k = 0; k < _reg_node.Size(); k++) {
2971 Node* pinch = _reg_node[k];
2972 if ((pinch != NULL) && pinch->Opcode() == Op_Node &&
2973 // no predecence input edges
2974 (pinch->req() == pinch->len() || pinch->in(pinch->req()) == NULL) ) {
2975 cleanup_pinch(pinch);
2976 _pinch_free_list.push(pinch);
2977 _reg_node.map(k, NULL);
2978 #ifndef PRODUCT
2979 if (_cfg->C->trace_opto_output()) {
2980 trace_cnt++;
2981 if (trace_cnt > 40) {
2982 tty->print("\n");
2983 trace_cnt = 0;
2984 }
2985 tty->print(" %d", pinch->_idx);
2986 }
2987 #endif
2988 }
2989 }
2990 #ifndef PRODUCT
2991 if (_cfg->C->trace_opto_output()) tty->print("\n");
2992 #endif
2993 }
2995 // Clean up a pinch node for reuse.
2996 void Scheduling::cleanup_pinch( Node *pinch ) {
2997 assert (pinch && pinch->Opcode() == Op_Node && pinch->req() == 1, "just checking");
2999 for (DUIterator_Last imin, i = pinch->last_outs(imin); i >= imin; ) {
3000 Node* use = pinch->last_out(i);
3001 uint uses_found = 0;
3002 for (uint j = use->req(); j < use->len(); j++) {
3003 if (use->in(j) == pinch) {
3004 use->rm_prec(j);
3005 uses_found++;
3006 }
3007 }
3008 assert(uses_found > 0, "must be a precedence edge");
3009 i -= uses_found; // we deleted 1 or more copies of this edge
3010 }
3011 // May have a later_def entry
3012 pinch->set_req(0, NULL);
3013 }
3015 #ifndef PRODUCT
3017 void Scheduling::dump_available() const {
3018 tty->print("#Availist ");
3019 for (uint i = 0; i < _available.size(); i++)
3020 tty->print(" N%d/l%d", _available[i]->_idx,_current_latency[_available[i]->_idx]);
3021 tty->cr();
3022 }
3024 // Print Scheduling Statistics
3025 void Scheduling::print_statistics() {
3026 // Print the size added by nops for bundling
3027 tty->print("Nops added %d bytes to total of %d bytes",
3028 _total_nop_size, _total_method_size);
3029 if (_total_method_size > 0)
3030 tty->print(", for %.2f%%",
3031 ((double)_total_nop_size) / ((double) _total_method_size) * 100.0);
3032 tty->print("\n");
3034 // Print the number of branch shadows filled
3035 if (Pipeline::_branch_has_delay_slot) {
3036 tty->print("Of %d branches, %d had unconditional delay slots filled",
3037 _total_branches, _total_unconditional_delays);
3038 if (_total_branches > 0)
3039 tty->print(", for %.2f%%",
3040 ((double)_total_unconditional_delays) / ((double)_total_branches) * 100.0);
3041 tty->print("\n");
3042 }
3044 uint total_instructions = 0, total_bundles = 0;
3046 for (uint i = 1; i <= Pipeline::_max_instrs_per_cycle; i++) {
3047 uint bundle_count = _total_instructions_per_bundle[i];
3048 total_instructions += bundle_count * i;
3049 total_bundles += bundle_count;
3050 }
3052 if (total_bundles > 0)
3053 tty->print("Average ILP (excluding nops) is %.2f\n",
3054 ((double)total_instructions) / ((double)total_bundles));
3055 }
3056 #endif