1 /*
2 * Copyright 1997-2007 Sun Microsystems, Inc. All Rights Reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.
8 *
9 * This code is distributed in the hope that it will be useful, but WITHOUT
10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
12 * version 2 for more details (a copy is included in the LICENSE file that
13 * accompanied this code).
14 *
15 * You should have received a copy of the GNU General Public License version
16 * 2 along with this work; if not, write to the Free Software Foundation,
17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18 *
19 * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
20 * CA 95054 USA or visit www.sun.com if you need additional information or
21 * have any questions.
22 *
23 */
24
25 #include "incls/_precompiled.incl"
26 #include "incls/_matcher.cpp.incl"
27
28 OptoReg::Name OptoReg::c_frame_pointer;
29
30
31
32 const int Matcher::base2reg[Type::lastype] = {
33 Node::NotAMachineReg,0,0, Op_RegI, Op_RegL, 0, Op_RegN,
34 Node::NotAMachineReg, Node::NotAMachineReg, /* tuple, array */
35 Op_RegP, Op_RegP, Op_RegP, Op_RegP, Op_RegP, Op_RegP, /* the pointers */
36 0, 0/*abio*/,
37 Op_RegP /* Return address */, 0, /* the memories */
38 Op_RegF, Op_RegF, Op_RegF, Op_RegD, Op_RegD, Op_RegD,
39 0 /*bottom*/
40 };
41
42 const RegMask *Matcher::idealreg2regmask[_last_machine_leaf];
43 RegMask Matcher::mreg2regmask[_last_Mach_Reg];
44 RegMask Matcher::STACK_ONLY_mask;
45 RegMask Matcher::c_frame_ptr_mask;
46 const uint Matcher::_begin_rematerialize = _BEGIN_REMATERIALIZE;
47 const uint Matcher::_end_rematerialize = _END_REMATERIALIZE;
48
49 //---------------------------Matcher-------------------------------------------
50 Matcher::Matcher( Node_List &proj_list ) :
51 PhaseTransform( Phase::Ins_Select ),
52 #ifdef ASSERT
53 _old2new_map(C->comp_arena()),
54 _new2old_map(C->comp_arena()),
55 #endif
56 _shared_nodes(C->comp_arena()),
57 _reduceOp(reduceOp), _leftOp(leftOp), _rightOp(rightOp),
58 _swallowed(swallowed),
59 _begin_inst_chain_rule(_BEGIN_INST_CHAIN_RULE),
60 _end_inst_chain_rule(_END_INST_CHAIN_RULE),
61 _must_clone(must_clone), _proj_list(proj_list),
62 _register_save_policy(register_save_policy),
63 _c_reg_save_policy(c_reg_save_policy),
64 _register_save_type(register_save_type),
65 _ruleName(ruleName),
66 _allocation_started(false),
67 _states_arena(Chunk::medium_size),
68 _visited(&_states_arena),
69 _shared(&_states_arena),
70 _dontcare(&_states_arena) {
71 C->set_matcher(this);
72
73 idealreg2spillmask[Op_RegI] = NULL;
74 idealreg2spillmask[Op_RegN] = NULL;
75 idealreg2spillmask[Op_RegL] = NULL;
76 idealreg2spillmask[Op_RegF] = NULL;
77 idealreg2spillmask[Op_RegD] = NULL;
78 idealreg2spillmask[Op_RegP] = NULL;
79
80 idealreg2debugmask[Op_RegI] = NULL;
81 idealreg2debugmask[Op_RegN] = NULL;
82 idealreg2debugmask[Op_RegL] = NULL;
83 idealreg2debugmask[Op_RegF] = NULL;
84 idealreg2debugmask[Op_RegD] = NULL;
85 idealreg2debugmask[Op_RegP] = NULL;
86 }
87
88 //------------------------------warp_incoming_stk_arg------------------------
89 // This warps a VMReg into an OptoReg::Name
90 OptoReg::Name Matcher::warp_incoming_stk_arg( VMReg reg ) {
91 OptoReg::Name warped;
92 if( reg->is_stack() ) { // Stack slot argument?
93 warped = OptoReg::add(_old_SP, reg->reg2stack() );
94 warped = OptoReg::add(warped, C->out_preserve_stack_slots());
95 if( warped >= _in_arg_limit )
96 _in_arg_limit = OptoReg::add(warped, 1); // Bump max stack slot seen
97 if (!RegMask::can_represent(warped)) {
98 // the compiler cannot represent this method's calling sequence
99 C->record_method_not_compilable_all_tiers("unsupported incoming calling sequence");
100 return OptoReg::Bad;
101 }
102 return warped;
103 }
104 return OptoReg::as_OptoReg(reg);
105 }
106
107 //---------------------------compute_old_SP------------------------------------
108 OptoReg::Name Compile::compute_old_SP() {
109 int fixed = fixed_slots();
110 int preserve = in_preserve_stack_slots();
111 return OptoReg::stack2reg(round_to(fixed + preserve, Matcher::stack_alignment_in_slots()));
112 }
113
114
115
116 #ifdef ASSERT
117 void Matcher::verify_new_nodes_only(Node* xroot) {
118 // Make sure that the new graph only references new nodes
119 ResourceMark rm;
120 Unique_Node_List worklist;
121 VectorSet visited(Thread::current()->resource_area());
122 worklist.push(xroot);
123 while (worklist.size() > 0) {
124 Node* n = worklist.pop();
125 visited <<= n->_idx;
126 assert(C->node_arena()->contains(n), "dead node");
127 for (uint j = 0; j < n->req(); j++) {
128 Node* in = n->in(j);
129 if (in != NULL) {
130 assert(C->node_arena()->contains(in), "dead node");
131 if (!visited.test(in->_idx)) {
132 worklist.push(in);
133 }
134 }
135 }
136 }
137 }
138 #endif
139
140
141 //---------------------------match---------------------------------------------
142 void Matcher::match( ) {
143 // One-time initialization of some register masks.
144 init_spill_mask( C->root()->in(1) );
145 _return_addr_mask = return_addr();
146 #ifdef _LP64
147 // Pointers take 2 slots in 64-bit land
148 _return_addr_mask.Insert(OptoReg::add(return_addr(),1));
149 #endif
150
151 // Map a Java-signature return type into return register-value
152 // machine registers for 0, 1 and 2 returned values.
153 const TypeTuple *range = C->tf()->range();
154 if( range->cnt() > TypeFunc::Parms ) { // If not a void function
155 // Get ideal-register return type
156 int ireg = base2reg[range->field_at(TypeFunc::Parms)->base()];
157 // Get machine return register
158 uint sop = C->start()->Opcode();
159 OptoRegPair regs = return_value(ireg, false);
160
161 // And mask for same
162 _return_value_mask = RegMask(regs.first());
163 if( OptoReg::is_valid(regs.second()) )
164 _return_value_mask.Insert(regs.second());
165 }
166
167 // ---------------
168 // Frame Layout
169
170 // Need the method signature to determine the incoming argument types,
171 // because the types determine which registers the incoming arguments are
172 // in, and this affects the matched code.
173 const TypeTuple *domain = C->tf()->domain();
174 uint argcnt = domain->cnt() - TypeFunc::Parms;
175 BasicType *sig_bt = NEW_RESOURCE_ARRAY( BasicType, argcnt );
176 VMRegPair *vm_parm_regs = NEW_RESOURCE_ARRAY( VMRegPair, argcnt );
177 _parm_regs = NEW_RESOURCE_ARRAY( OptoRegPair, argcnt );
178 _calling_convention_mask = NEW_RESOURCE_ARRAY( RegMask, argcnt );
179 uint i;
180 for( i = 0; i<argcnt; i++ ) {
181 sig_bt[i] = domain->field_at(i+TypeFunc::Parms)->basic_type();
182 }
183
184 // Pass array of ideal registers and length to USER code (from the AD file)
185 // that will convert this to an array of register numbers.
186 const StartNode *start = C->start();
187 start->calling_convention( sig_bt, vm_parm_regs, argcnt );
188 #ifdef ASSERT
189 // Sanity check users' calling convention. Real handy while trying to
190 // get the initial port correct.
191 { for (uint i = 0; i<argcnt; i++) {
192 if( !vm_parm_regs[i].first()->is_valid() && !vm_parm_regs[i].second()->is_valid() ) {
193 assert(domain->field_at(i+TypeFunc::Parms)==Type::HALF, "only allowed on halve" );
194 _parm_regs[i].set_bad();
195 continue;
196 }
197 VMReg parm_reg = vm_parm_regs[i].first();
198 assert(parm_reg->is_valid(), "invalid arg?");
199 if (parm_reg->is_reg()) {
200 OptoReg::Name opto_parm_reg = OptoReg::as_OptoReg(parm_reg);
201 assert(can_be_java_arg(opto_parm_reg) ||
202 C->stub_function() == CAST_FROM_FN_PTR(address, OptoRuntime::rethrow_C) ||
203 opto_parm_reg == inline_cache_reg(),
204 "parameters in register must be preserved by runtime stubs");
205 }
206 for (uint j = 0; j < i; j++) {
207 assert(parm_reg != vm_parm_regs[j].first(),
208 "calling conv. must produce distinct regs");
209 }
210 }
211 }
212 #endif
213
214 // Do some initial frame layout.
215
216 // Compute the old incoming SP (may be called FP) as
217 // OptoReg::stack0() + locks + in_preserve_stack_slots + pad2.
218 _old_SP = C->compute_old_SP();
219 assert( is_even(_old_SP), "must be even" );
220
221 // Compute highest incoming stack argument as
222 // _old_SP + out_preserve_stack_slots + incoming argument size.
223 _in_arg_limit = OptoReg::add(_old_SP, C->out_preserve_stack_slots());
224 assert( is_even(_in_arg_limit), "out_preserve must be even" );
225 for( i = 0; i < argcnt; i++ ) {
226 // Permit args to have no register
227 _calling_convention_mask[i].Clear();
228 if( !vm_parm_regs[i].first()->is_valid() && !vm_parm_regs[i].second()->is_valid() ) {
229 continue;
230 }
231 // calling_convention returns stack arguments as a count of
232 // slots beyond OptoReg::stack0()/VMRegImpl::stack0. We need to convert this to
233 // the allocators point of view, taking into account all the
234 // preserve area, locks & pad2.
235
236 OptoReg::Name reg1 = warp_incoming_stk_arg(vm_parm_regs[i].first());
237 if( OptoReg::is_valid(reg1))
238 _calling_convention_mask[i].Insert(reg1);
239
240 OptoReg::Name reg2 = warp_incoming_stk_arg(vm_parm_regs[i].second());
241 if( OptoReg::is_valid(reg2))
242 _calling_convention_mask[i].Insert(reg2);
243
244 // Saved biased stack-slot register number
245 _parm_regs[i].set_pair(reg2, reg1);
246 }
247
248 // Finally, make sure the incoming arguments take up an even number of
249 // words, in case the arguments or locals need to contain doubleword stack
250 // slots. The rest of the system assumes that stack slot pairs (in
251 // particular, in the spill area) which look aligned will in fact be
252 // aligned relative to the stack pointer in the target machine. Double
253 // stack slots will always be allocated aligned.
254 _new_SP = OptoReg::Name(round_to(_in_arg_limit, RegMask::SlotsPerLong));
255
256 // Compute highest outgoing stack argument as
257 // _new_SP + out_preserve_stack_slots + max(outgoing argument size).
258 _out_arg_limit = OptoReg::add(_new_SP, C->out_preserve_stack_slots());
259 assert( is_even(_out_arg_limit), "out_preserve must be even" );
260
261 if (!RegMask::can_represent(OptoReg::add(_out_arg_limit,-1))) {
262 // the compiler cannot represent this method's calling sequence
263 C->record_method_not_compilable("must be able to represent all call arguments in reg mask");
264 }
265
266 if (C->failing()) return; // bailed out on incoming arg failure
267
268 // ---------------
269 // Collect roots of matcher trees. Every node for which
270 // _shared[_idx] is cleared is guaranteed to not be shared, and thus
271 // can be a valid interior of some tree.
272 find_shared( C->root() );
273 find_shared( C->top() );
274
275 C->print_method("Before Matching", 2);
276
277 // Swap out to old-space; emptying new-space
278 Arena *old = C->node_arena()->move_contents(C->old_arena());
279
280 // Save debug and profile information for nodes in old space:
281 _old_node_note_array = C->node_note_array();
282 if (_old_node_note_array != NULL) {
283 C->set_node_note_array(new(C->comp_arena()) GrowableArray<Node_Notes*>
284 (C->comp_arena(), _old_node_note_array->length(),
285 0, NULL));
286 }
287
288 // Pre-size the new_node table to avoid the need for range checks.
289 grow_new_node_array(C->unique());
290
291 // Reset node counter so MachNodes start with _idx at 0
292 int nodes = C->unique(); // save value
293 C->set_unique(0);
294
295 // Recursively match trees from old space into new space.
296 // Correct leaves of new-space Nodes; they point to old-space.
297 _visited.Clear(); // Clear visit bits for xform call
298 C->set_cached_top_node(xform( C->top(), nodes ));
299 if (!C->failing()) {
300 Node* xroot = xform( C->root(), 1 );
301 if (xroot == NULL) {
302 Matcher::soft_match_failure(); // recursive matching process failed
303 C->record_method_not_compilable("instruction match failed");
304 } else {
305 // During matching shared constants were attached to C->root()
306 // because xroot wasn't available yet, so transfer the uses to
307 // the xroot.
308 for( DUIterator_Fast jmax, j = C->root()->fast_outs(jmax); j < jmax; j++ ) {
309 Node* n = C->root()->fast_out(j);
310 if (C->node_arena()->contains(n)) {
311 assert(n->in(0) == C->root(), "should be control user");
312 n->set_req(0, xroot);
313 --j;
314 --jmax;
315 }
316 }
317
318 C->set_root(xroot->is_Root() ? xroot->as_Root() : NULL);
319 #ifdef ASSERT
320 verify_new_nodes_only(xroot);
321 #endif
322 }
323 }
324 if (C->top() == NULL || C->root() == NULL) {
325 C->record_method_not_compilable("graph lost"); // %%% cannot happen?
326 }
327 if (C->failing()) {
328 // delete old;
329 old->destruct_contents();
330 return;
331 }
332 assert( C->top(), "" );
333 assert( C->root(), "" );
334 validate_null_checks();
335
336 // Now smoke old-space
337 NOT_DEBUG( old->destruct_contents() );
338
339 // ------------------------
340 // Set up save-on-entry registers
341 Fixup_Save_On_Entry( );
342 }
343
344
345 //------------------------------Fixup_Save_On_Entry----------------------------
346 // The stated purpose of this routine is to take care of save-on-entry
347 // registers. However, the overall goal of the Match phase is to convert into
348 // machine-specific instructions which have RegMasks to guide allocation.
349 // So what this procedure really does is put a valid RegMask on each input
350 // to the machine-specific variations of all Return, TailCall and Halt
351 // instructions. It also adds edgs to define the save-on-entry values (and of
352 // course gives them a mask).
353
354 static RegMask *init_input_masks( uint size, RegMask &ret_adr, RegMask &fp ) {
355 RegMask *rms = NEW_RESOURCE_ARRAY( RegMask, size );
356 // Do all the pre-defined register masks
357 rms[TypeFunc::Control ] = RegMask::Empty;
358 rms[TypeFunc::I_O ] = RegMask::Empty;
359 rms[TypeFunc::Memory ] = RegMask::Empty;
360 rms[TypeFunc::ReturnAdr] = ret_adr;
361 rms[TypeFunc::FramePtr ] = fp;
362 return rms;
363 }
364
365 //---------------------------init_first_stack_mask-----------------------------
366 // Create the initial stack mask used by values spilling to the stack.
367 // Disallow any debug info in outgoing argument areas by setting the
368 // initial mask accordingly.
369 void Matcher::init_first_stack_mask() {
370
371 // Allocate storage for spill masks as masks for the appropriate load type.
372 RegMask *rms = (RegMask*)C->comp_arena()->Amalloc_D(sizeof(RegMask)*12);
373 idealreg2spillmask[Op_RegN] = &rms[0];
374 idealreg2spillmask[Op_RegI] = &rms[1];
375 idealreg2spillmask[Op_RegL] = &rms[2];
376 idealreg2spillmask[Op_RegF] = &rms[3];
377 idealreg2spillmask[Op_RegD] = &rms[4];
378 idealreg2spillmask[Op_RegP] = &rms[5];
379 idealreg2debugmask[Op_RegN] = &rms[6];
380 idealreg2debugmask[Op_RegI] = &rms[7];
381 idealreg2debugmask[Op_RegL] = &rms[8];
382 idealreg2debugmask[Op_RegF] = &rms[9];
383 idealreg2debugmask[Op_RegD] = &rms[10];
384 idealreg2debugmask[Op_RegP] = &rms[11];
385
386 OptoReg::Name i;
387
388 // At first, start with the empty mask
389 C->FIRST_STACK_mask().Clear();
390
391 // Add in the incoming argument area
392 OptoReg::Name init = OptoReg::add(_old_SP, C->out_preserve_stack_slots());
393 for (i = init; i < _in_arg_limit; i = OptoReg::add(i,1))
394 C->FIRST_STACK_mask().Insert(i);
395
396 // Add in all bits past the outgoing argument area
397 guarantee(RegMask::can_represent(OptoReg::add(_out_arg_limit,-1)),
398 "must be able to represent all call arguments in reg mask");
399 init = _out_arg_limit;
400 for (i = init; RegMask::can_represent(i); i = OptoReg::add(i,1))
401 C->FIRST_STACK_mask().Insert(i);
402
403 // Finally, set the "infinite stack" bit.
404 C->FIRST_STACK_mask().set_AllStack();
405
406 // Make spill masks. Registers for their class, plus FIRST_STACK_mask.
407 #ifdef _LP64
408 *idealreg2spillmask[Op_RegN] = *idealreg2regmask[Op_RegN];
409 idealreg2spillmask[Op_RegN]->OR(C->FIRST_STACK_mask());
410 #endif
411 *idealreg2spillmask[Op_RegI] = *idealreg2regmask[Op_RegI];
412 idealreg2spillmask[Op_RegI]->OR(C->FIRST_STACK_mask());
413 *idealreg2spillmask[Op_RegL] = *idealreg2regmask[Op_RegL];
414 idealreg2spillmask[Op_RegL]->OR(C->FIRST_STACK_mask());
415 *idealreg2spillmask[Op_RegF] = *idealreg2regmask[Op_RegF];
416 idealreg2spillmask[Op_RegF]->OR(C->FIRST_STACK_mask());
417 *idealreg2spillmask[Op_RegD] = *idealreg2regmask[Op_RegD];
418 idealreg2spillmask[Op_RegD]->OR(C->FIRST_STACK_mask());
419 *idealreg2spillmask[Op_RegP] = *idealreg2regmask[Op_RegP];
420 idealreg2spillmask[Op_RegP]->OR(C->FIRST_STACK_mask());
421
422 // Make up debug masks. Any spill slot plus callee-save registers.
423 // Caller-save registers are assumed to be trashable by the various
424 // inline-cache fixup routines.
425 *idealreg2debugmask[Op_RegN]= *idealreg2spillmask[Op_RegN];
426 *idealreg2debugmask[Op_RegI]= *idealreg2spillmask[Op_RegI];
427 *idealreg2debugmask[Op_RegL]= *idealreg2spillmask[Op_RegL];
428 *idealreg2debugmask[Op_RegF]= *idealreg2spillmask[Op_RegF];
429 *idealreg2debugmask[Op_RegD]= *idealreg2spillmask[Op_RegD];
430 *idealreg2debugmask[Op_RegP]= *idealreg2spillmask[Op_RegP];
431
432 // Prevent stub compilations from attempting to reference
433 // callee-saved registers from debug info
434 bool exclude_soe = !Compile::current()->is_method_compilation();
435
436 for( i=OptoReg::Name(0); i<OptoReg::Name(_last_Mach_Reg); i = OptoReg::add(i,1) ) {
437 // registers the caller has to save do not work
438 if( _register_save_policy[i] == 'C' ||
439 _register_save_policy[i] == 'A' ||
440 (_register_save_policy[i] == 'E' && exclude_soe) ) {
441 idealreg2debugmask[Op_RegN]->Remove(i);
442 idealreg2debugmask[Op_RegI]->Remove(i); // Exclude save-on-call
443 idealreg2debugmask[Op_RegL]->Remove(i); // registers from debug
444 idealreg2debugmask[Op_RegF]->Remove(i); // masks
445 idealreg2debugmask[Op_RegD]->Remove(i);
446 idealreg2debugmask[Op_RegP]->Remove(i);
447 }
448 }
449 }
450
451 //---------------------------is_save_on_entry----------------------------------
452 bool Matcher::is_save_on_entry( int reg ) {
453 return
454 _register_save_policy[reg] == 'E' ||
455 _register_save_policy[reg] == 'A' || // Save-on-entry register?
456 // Also save argument registers in the trampolining stubs
457 (C->save_argument_registers() && is_spillable_arg(reg));
458 }
459
460 //---------------------------Fixup_Save_On_Entry-------------------------------
461 void Matcher::Fixup_Save_On_Entry( ) {
462 init_first_stack_mask();
463
464 Node *root = C->root(); // Short name for root
465 // Count number of save-on-entry registers.
466 uint soe_cnt = number_of_saved_registers();
467 uint i;
468
469 // Find the procedure Start Node
470 StartNode *start = C->start();
471 assert( start, "Expect a start node" );
472
473 // Save argument registers in the trampolining stubs
474 if( C->save_argument_registers() )
475 for( i = 0; i < _last_Mach_Reg; i++ )
476 if( is_spillable_arg(i) )
477 soe_cnt++;
478
479 // Input RegMask array shared by all Returns.
480 // The type for doubles and longs has a count of 2, but
481 // there is only 1 returned value
482 uint ret_edge_cnt = TypeFunc::Parms + ((C->tf()->range()->cnt() == TypeFunc::Parms) ? 0 : 1);
483 RegMask *ret_rms = init_input_masks( ret_edge_cnt + soe_cnt, _return_addr_mask, c_frame_ptr_mask );
484 // Returns have 0 or 1 returned values depending on call signature.
485 // Return register is specified by return_value in the AD file.
486 if (ret_edge_cnt > TypeFunc::Parms)
487 ret_rms[TypeFunc::Parms+0] = _return_value_mask;
488
489 // Input RegMask array shared by all Rethrows.
490 uint reth_edge_cnt = TypeFunc::Parms+1;
491 RegMask *reth_rms = init_input_masks( reth_edge_cnt + soe_cnt, _return_addr_mask, c_frame_ptr_mask );
492 // Rethrow takes exception oop only, but in the argument 0 slot.
493 reth_rms[TypeFunc::Parms] = mreg2regmask[find_receiver(false)];
494 #ifdef _LP64
495 // Need two slots for ptrs in 64-bit land
496 reth_rms[TypeFunc::Parms].Insert(OptoReg::add(OptoReg::Name(find_receiver(false)),1));
497 #endif
498
499 // Input RegMask array shared by all TailCalls
500 uint tail_call_edge_cnt = TypeFunc::Parms+2;
501 RegMask *tail_call_rms = init_input_masks( tail_call_edge_cnt + soe_cnt, _return_addr_mask, c_frame_ptr_mask );
502
503 // Input RegMask array shared by all TailJumps
504 uint tail_jump_edge_cnt = TypeFunc::Parms+2;
505 RegMask *tail_jump_rms = init_input_masks( tail_jump_edge_cnt + soe_cnt, _return_addr_mask, c_frame_ptr_mask );
506
507 // TailCalls have 2 returned values (target & moop), whose masks come
508 // from the usual MachNode/MachOper mechanism. Find a sample
509 // TailCall to extract these masks and put the correct masks into
510 // the tail_call_rms array.
511 for( i=1; i < root->req(); i++ ) {
512 MachReturnNode *m = root->in(i)->as_MachReturn();
513 if( m->ideal_Opcode() == Op_TailCall ) {
514 tail_call_rms[TypeFunc::Parms+0] = m->MachNode::in_RegMask(TypeFunc::Parms+0);
515 tail_call_rms[TypeFunc::Parms+1] = m->MachNode::in_RegMask(TypeFunc::Parms+1);
516 break;
517 }
518 }
519
520 // TailJumps have 2 returned values (target & ex_oop), whose masks come
521 // from the usual MachNode/MachOper mechanism. Find a sample
522 // TailJump to extract these masks and put the correct masks into
523 // the tail_jump_rms array.
524 for( i=1; i < root->req(); i++ ) {
525 MachReturnNode *m = root->in(i)->as_MachReturn();
526 if( m->ideal_Opcode() == Op_TailJump ) {
527 tail_jump_rms[TypeFunc::Parms+0] = m->MachNode::in_RegMask(TypeFunc::Parms+0);
528 tail_jump_rms[TypeFunc::Parms+1] = m->MachNode::in_RegMask(TypeFunc::Parms+1);
529 break;
530 }
531 }
532
533 // Input RegMask array shared by all Halts
534 uint halt_edge_cnt = TypeFunc::Parms;
535 RegMask *halt_rms = init_input_masks( halt_edge_cnt + soe_cnt, _return_addr_mask, c_frame_ptr_mask );
536
537 // Capture the return input masks into each exit flavor
538 for( i=1; i < root->req(); i++ ) {
539 MachReturnNode *exit = root->in(i)->as_MachReturn();
540 switch( exit->ideal_Opcode() ) {
541 case Op_Return : exit->_in_rms = ret_rms; break;
542 case Op_Rethrow : exit->_in_rms = reth_rms; break;
543 case Op_TailCall : exit->_in_rms = tail_call_rms; break;
544 case Op_TailJump : exit->_in_rms = tail_jump_rms; break;
545 case Op_Halt : exit->_in_rms = halt_rms; break;
546 default : ShouldNotReachHere();
547 }
548 }
549
550 // Next unused projection number from Start.
551 int proj_cnt = C->tf()->domain()->cnt();
552
553 // Do all the save-on-entry registers. Make projections from Start for
554 // them, and give them a use at the exit points. To the allocator, they
555 // look like incoming register arguments.
556 for( i = 0; i < _last_Mach_Reg; i++ ) {
557 if( is_save_on_entry(i) ) {
558
559 // Add the save-on-entry to the mask array
560 ret_rms [ ret_edge_cnt] = mreg2regmask[i];
561 reth_rms [ reth_edge_cnt] = mreg2regmask[i];
562 tail_call_rms[tail_call_edge_cnt] = mreg2regmask[i];
563 tail_jump_rms[tail_jump_edge_cnt] = mreg2regmask[i];
564 // Halts need the SOE registers, but only in the stack as debug info.
565 // A just-prior uncommon-trap or deoptimization will use the SOE regs.
566 halt_rms [ halt_edge_cnt] = *idealreg2spillmask[_register_save_type[i]];
567
568 Node *mproj;
569
570 // Is this a RegF low half of a RegD? Double up 2 adjacent RegF's
571 // into a single RegD.
572 if( (i&1) == 0 &&
573 _register_save_type[i ] == Op_RegF &&
574 _register_save_type[i+1] == Op_RegF &&
575 is_save_on_entry(i+1) ) {
576 // Add other bit for double
577 ret_rms [ ret_edge_cnt].Insert(OptoReg::Name(i+1));
578 reth_rms [ reth_edge_cnt].Insert(OptoReg::Name(i+1));
579 tail_call_rms[tail_call_edge_cnt].Insert(OptoReg::Name(i+1));
580 tail_jump_rms[tail_jump_edge_cnt].Insert(OptoReg::Name(i+1));
581 halt_rms [ halt_edge_cnt].Insert(OptoReg::Name(i+1));
582 mproj = new (C, 1) MachProjNode( start, proj_cnt, ret_rms[ret_edge_cnt], Op_RegD );
583 proj_cnt += 2; // Skip 2 for doubles
584 }
585 else if( (i&1) == 1 && // Else check for high half of double
586 _register_save_type[i-1] == Op_RegF &&
587 _register_save_type[i ] == Op_RegF &&
588 is_save_on_entry(i-1) ) {
589 ret_rms [ ret_edge_cnt] = RegMask::Empty;
590 reth_rms [ reth_edge_cnt] = RegMask::Empty;
591 tail_call_rms[tail_call_edge_cnt] = RegMask::Empty;
592 tail_jump_rms[tail_jump_edge_cnt] = RegMask::Empty;
593 halt_rms [ halt_edge_cnt] = RegMask::Empty;
594 mproj = C->top();
595 }
596 // Is this a RegI low half of a RegL? Double up 2 adjacent RegI's
597 // into a single RegL.
598 else if( (i&1) == 0 &&
599 _register_save_type[i ] == Op_RegI &&
600 _register_save_type[i+1] == Op_RegI &&
601 is_save_on_entry(i+1) ) {
602 // Add other bit for long
603 ret_rms [ ret_edge_cnt].Insert(OptoReg::Name(i+1));
604 reth_rms [ reth_edge_cnt].Insert(OptoReg::Name(i+1));
605 tail_call_rms[tail_call_edge_cnt].Insert(OptoReg::Name(i+1));
606 tail_jump_rms[tail_jump_edge_cnt].Insert(OptoReg::Name(i+1));
607 halt_rms [ halt_edge_cnt].Insert(OptoReg::Name(i+1));
608 mproj = new (C, 1) MachProjNode( start, proj_cnt, ret_rms[ret_edge_cnt], Op_RegL );
609 proj_cnt += 2; // Skip 2 for longs
610 }
611 else if( (i&1) == 1 && // Else check for high half of long
612 _register_save_type[i-1] == Op_RegI &&
613 _register_save_type[i ] == Op_RegI &&
614 is_save_on_entry(i-1) ) {
615 ret_rms [ ret_edge_cnt] = RegMask::Empty;
616 reth_rms [ reth_edge_cnt] = RegMask::Empty;
617 tail_call_rms[tail_call_edge_cnt] = RegMask::Empty;
618 tail_jump_rms[tail_jump_edge_cnt] = RegMask::Empty;
619 halt_rms [ halt_edge_cnt] = RegMask::Empty;
620 mproj = C->top();
621 } else {
622 // Make a projection for it off the Start
623 mproj = new (C, 1) MachProjNode( start, proj_cnt++, ret_rms[ret_edge_cnt], _register_save_type[i] );
624 }
625
626 ret_edge_cnt ++;
627 reth_edge_cnt ++;
628 tail_call_edge_cnt ++;
629 tail_jump_edge_cnt ++;
630 halt_edge_cnt ++;
631
632 // Add a use of the SOE register to all exit paths
633 for( uint j=1; j < root->req(); j++ )
634 root->in(j)->add_req(mproj);
635 } // End of if a save-on-entry register
636 } // End of for all machine registers
637 }
638
639 //------------------------------init_spill_mask--------------------------------
640 void Matcher::init_spill_mask( Node *ret ) {
641 if( idealreg2regmask[Op_RegI] ) return; // One time only init
642
643 OptoReg::c_frame_pointer = c_frame_pointer();
644 c_frame_ptr_mask = c_frame_pointer();
645 #ifdef _LP64
646 // pointers are twice as big
647 c_frame_ptr_mask.Insert(OptoReg::add(c_frame_pointer(),1));
648 #endif
649
650 // Start at OptoReg::stack0()
651 STACK_ONLY_mask.Clear();
652 OptoReg::Name init = OptoReg::stack2reg(0);
653 // STACK_ONLY_mask is all stack bits
654 OptoReg::Name i;
655 for (i = init; RegMask::can_represent(i); i = OptoReg::add(i,1))
656 STACK_ONLY_mask.Insert(i);
657 // Also set the "infinite stack" bit.
658 STACK_ONLY_mask.set_AllStack();
659
660 // Copy the register names over into the shared world
661 for( i=OptoReg::Name(0); i<OptoReg::Name(_last_Mach_Reg); i = OptoReg::add(i,1) ) {
662 // SharedInfo::regName[i] = regName[i];
663 // Handy RegMasks per machine register
664 mreg2regmask[i].Insert(i);
665 }
666
667 // Grab the Frame Pointer
668 Node *fp = ret->in(TypeFunc::FramePtr);
669 Node *mem = ret->in(TypeFunc::Memory);
670 const TypePtr* atp = TypePtr::BOTTOM;
671 // Share frame pointer while making spill ops
672 set_shared(fp);
673
674 // Compute generic short-offset Loads
675 #ifdef _LP64
676 MachNode *spillCP = match_tree(new (C, 3) LoadNNode(NULL,mem,fp,atp,TypeInstPtr::BOTTOM));
677 #endif
678 MachNode *spillI = match_tree(new (C, 3) LoadINode(NULL,mem,fp,atp));
679 MachNode *spillL = match_tree(new (C, 3) LoadLNode(NULL,mem,fp,atp));
680 MachNode *spillF = match_tree(new (C, 3) LoadFNode(NULL,mem,fp,atp));
681 MachNode *spillD = match_tree(new (C, 3) LoadDNode(NULL,mem,fp,atp));
682 MachNode *spillP = match_tree(new (C, 3) LoadPNode(NULL,mem,fp,atp,TypeInstPtr::BOTTOM));
683 assert(spillI != NULL && spillL != NULL && spillF != NULL &&
684 spillD != NULL && spillP != NULL, "");
685
686 // Get the ADLC notion of the right regmask, for each basic type.
687 #ifdef _LP64
688 idealreg2regmask[Op_RegN] = &spillCP->out_RegMask();
689 #endif
690 idealreg2regmask[Op_RegI] = &spillI->out_RegMask();
691 idealreg2regmask[Op_RegL] = &spillL->out_RegMask();
692 idealreg2regmask[Op_RegF] = &spillF->out_RegMask();
693 idealreg2regmask[Op_RegD] = &spillD->out_RegMask();
694 idealreg2regmask[Op_RegP] = &spillP->out_RegMask();
695 }
696
697 #ifdef ASSERT
698 static void match_alias_type(Compile* C, Node* n, Node* m) {
699 if (!VerifyAliases) return; // do not go looking for trouble by default
700 const TypePtr* nat = n->adr_type();
701 const TypePtr* mat = m->adr_type();
702 int nidx = C->get_alias_index(nat);
703 int midx = C->get_alias_index(mat);
704 // Detune the assert for cases like (AndI 0xFF (LoadB p)).
705 if (nidx == Compile::AliasIdxTop && midx >= Compile::AliasIdxRaw) {
706 for (uint i = 1; i < n->req(); i++) {
707 Node* n1 = n->in(i);
708 const TypePtr* n1at = n1->adr_type();
709 if (n1at != NULL) {
710 nat = n1at;
711 nidx = C->get_alias_index(n1at);
712 }
713 }
714 }
715 // %%% Kludgery. Instead, fix ideal adr_type methods for all these cases:
716 if (nidx == Compile::AliasIdxTop && midx == Compile::AliasIdxRaw) {
717 switch (n->Opcode()) {
718 case Op_PrefetchRead:
719 case Op_PrefetchWrite:
720 nidx = Compile::AliasIdxRaw;
721 nat = TypeRawPtr::BOTTOM;
722 break;
723 }
724 }
725 if (nidx == Compile::AliasIdxRaw && midx == Compile::AliasIdxTop) {
726 switch (n->Opcode()) {
727 case Op_ClearArray:
728 midx = Compile::AliasIdxRaw;
729 mat = TypeRawPtr::BOTTOM;
730 break;
731 }
732 }
733 if (nidx == Compile::AliasIdxTop && midx == Compile::AliasIdxBot) {
734 switch (n->Opcode()) {
735 case Op_Return:
736 case Op_Rethrow:
737 case Op_Halt:
738 case Op_TailCall:
739 case Op_TailJump:
740 nidx = Compile::AliasIdxBot;
741 nat = TypePtr::BOTTOM;
742 break;
743 }
744 }
745 if (nidx == Compile::AliasIdxBot && midx == Compile::AliasIdxTop) {
746 switch (n->Opcode()) {
747 case Op_StrComp:
748 case Op_AryEq:
749 case Op_MemBarVolatile:
750 case Op_MemBarCPUOrder: // %%% these ideals should have narrower adr_type?
751 nidx = Compile::AliasIdxTop;
752 nat = NULL;
753 break;
754 }
755 }
756 if (nidx != midx) {
757 if (PrintOpto || (PrintMiscellaneous && (WizardMode || Verbose))) {
758 tty->print_cr("==== Matcher alias shift %d => %d", nidx, midx);
759 n->dump();
760 m->dump();
761 }
762 assert(C->subsume_loads() && C->must_alias(nat, midx),
763 "must not lose alias info when matching");
764 }
765 }
766 #endif
767
768
769 //------------------------------MStack-----------------------------------------
770 // State and MStack class used in xform() and find_shared() iterative methods.
771 enum Node_State { Pre_Visit, // node has to be pre-visited
772 Visit, // visit node
773 Post_Visit, // post-visit node
774 Alt_Post_Visit // alternative post-visit path
775 };
776
777 class MStack: public Node_Stack {
778 public:
779 MStack(int size) : Node_Stack(size) { }
780
781 void push(Node *n, Node_State ns) {
782 Node_Stack::push(n, (uint)ns);
783 }
784 void push(Node *n, Node_State ns, Node *parent, int indx) {
785 ++_inode_top;
786 if ((_inode_top + 1) >= _inode_max) grow();
787 _inode_top->node = parent;
788 _inode_top->indx = (uint)indx;
789 ++_inode_top;
790 _inode_top->node = n;
791 _inode_top->indx = (uint)ns;
792 }
793 Node *parent() {
794 pop();
795 return node();
796 }
797 Node_State state() const {
798 return (Node_State)index();
799 }
800 void set_state(Node_State ns) {
801 set_index((uint)ns);
802 }
803 };
804
805
806 //------------------------------xform------------------------------------------
807 // Given a Node in old-space, Match him (Label/Reduce) to produce a machine
808 // Node in new-space. Given a new-space Node, recursively walk his children.
809 Node *Matcher::transform( Node *n ) { ShouldNotCallThis(); return n; }
810 Node *Matcher::xform( Node *n, int max_stack ) {
811 // Use one stack to keep both: child's node/state and parent's node/index
812 MStack mstack(max_stack * 2 * 2); // C->unique() * 2 * 2
813 mstack.push(n, Visit, NULL, -1); // set NULL as parent to indicate root
814
815 while (mstack.is_nonempty()) {
816 n = mstack.node(); // Leave node on stack
817 Node_State nstate = mstack.state();
818 if (nstate == Visit) {
819 mstack.set_state(Post_Visit);
820 Node *oldn = n;
821 // Old-space or new-space check
822 if (!C->node_arena()->contains(n)) {
823 // Old space!
824 Node* m;
825 if (has_new_node(n)) { // Not yet Label/Reduced
826 m = new_node(n);
827 } else {
828 if (!is_dontcare(n)) { // Matcher can match this guy
829 // Calls match special. They match alone with no children.
830 // Their children, the incoming arguments, match normally.
831 m = n->is_SafePoint() ? match_sfpt(n->as_SafePoint()):match_tree(n);
832 if (C->failing()) return NULL;
833 if (m == NULL) { Matcher::soft_match_failure(); return NULL; }
834 } else { // Nothing the matcher cares about
835 if( n->is_Proj() && n->in(0)->is_Multi()) { // Projections?
836 // Convert to machine-dependent projection
837 m = n->in(0)->as_Multi()->match( n->as_Proj(), this );
838 #ifdef ASSERT
839 _new2old_map.map(m->_idx, n);
840 #endif
841 if (m->in(0) != NULL) // m might be top
842 collect_null_checks(m);
843 } else { // Else just a regular 'ol guy
844 m = n->clone(); // So just clone into new-space
845 #ifdef ASSERT
846 _new2old_map.map(m->_idx, n);
847 #endif
848 // Def-Use edges will be added incrementally as Uses
849 // of this node are matched.
850 assert(m->outcnt() == 0, "no Uses of this clone yet");
851 }
852 }
853
854 set_new_node(n, m); // Map old to new
855 if (_old_node_note_array != NULL) {
856 Node_Notes* nn = C->locate_node_notes(_old_node_note_array,
857 n->_idx);
858 C->set_node_notes_at(m->_idx, nn);
859 }
860 debug_only(match_alias_type(C, n, m));
861 }
862 n = m; // n is now a new-space node
863 mstack.set_node(n);
864 }
865
866 // New space!
867 if (_visited.test_set(n->_idx)) continue; // while(mstack.is_nonempty())
868
869 int i;
870 // Put precedence edges on stack first (match them last).
871 for (i = oldn->req(); (uint)i < oldn->len(); i++) {
872 Node *m = oldn->in(i);
873 if (m == NULL) break;
874 // set -1 to call add_prec() instead of set_req() during Step1
875 mstack.push(m, Visit, n, -1);
876 }
877
878 // For constant debug info, I'd rather have unmatched constants.
879 int cnt = n->req();
880 JVMState* jvms = n->jvms();
881 int debug_cnt = jvms ? jvms->debug_start() : cnt;
882
883 // Now do only debug info. Clone constants rather than matching.
884 // Constants are represented directly in the debug info without
885 // the need for executable machine instructions.
886 // Monitor boxes are also represented directly.
887 for (i = cnt - 1; i >= debug_cnt; --i) { // For all debug inputs do
888 Node *m = n->in(i); // Get input
889 int op = m->Opcode();
890 assert((op == Op_BoxLock) == jvms->is_monitor_use(i), "boxes only at monitor sites");
891 if( op == Op_ConI || op == Op_ConP || op == Op_ConN ||
892 op == Op_ConF || op == Op_ConD || op == Op_ConL
893 // || op == Op_BoxLock // %%%% enable this and remove (+++) in chaitin.cpp
894 ) {
895 m = m->clone();
896 #ifdef ASSERT
897 _new2old_map.map(m->_idx, n);
898 #endif
899 mstack.push(m, Post_Visit, n, i); // Don't neet to visit
900 mstack.push(m->in(0), Visit, m, 0);
901 } else {
902 mstack.push(m, Visit, n, i);
903 }
904 }
905
906 // And now walk his children, and convert his inputs to new-space.
907 for( ; i >= 0; --i ) { // For all normal inputs do
908 Node *m = n->in(i); // Get input
909 if(m != NULL)
910 mstack.push(m, Visit, n, i);
911 }
912
913 }
914 else if (nstate == Post_Visit) {
915 // Set xformed input
916 Node *p = mstack.parent();
917 if (p != NULL) { // root doesn't have parent
918 int i = (int)mstack.index();
919 if (i >= 0)
920 p->set_req(i, n); // required input
921 else if (i == -1)
922 p->add_prec(n); // precedence input
923 else
924 ShouldNotReachHere();
925 }
926 mstack.pop(); // remove processed node from stack
927 }
928 else {
929 ShouldNotReachHere();
930 }
931 } // while (mstack.is_nonempty())
932 return n; // Return new-space Node
933 }
934
935 //------------------------------warp_outgoing_stk_arg------------------------
936 OptoReg::Name Matcher::warp_outgoing_stk_arg( VMReg reg, OptoReg::Name begin_out_arg_area, OptoReg::Name &out_arg_limit_per_call ) {
937 // Convert outgoing argument location to a pre-biased stack offset
938 if (reg->is_stack()) {
939 OptoReg::Name warped = reg->reg2stack();
940 // Adjust the stack slot offset to be the register number used
941 // by the allocator.
942 warped = OptoReg::add(begin_out_arg_area, warped);
943 // Keep track of the largest numbered stack slot used for an arg.
944 // Largest used slot per call-site indicates the amount of stack
945 // that is killed by the call.
946 if( warped >= out_arg_limit_per_call )
947 out_arg_limit_per_call = OptoReg::add(warped,1);
948 if (!RegMask::can_represent(warped)) {
949 C->record_method_not_compilable_all_tiers("unsupported calling sequence");
950 return OptoReg::Bad;
951 }
952 return warped;
953 }
954 return OptoReg::as_OptoReg(reg);
955 }
956
957
958 //------------------------------match_sfpt-------------------------------------
959 // Helper function to match call instructions. Calls match special.
960 // They match alone with no children. Their children, the incoming
961 // arguments, match normally.
962 MachNode *Matcher::match_sfpt( SafePointNode *sfpt ) {
963 MachSafePointNode *msfpt = NULL;
964 MachCallNode *mcall = NULL;
965 uint cnt;
966 // Split out case for SafePoint vs Call
967 CallNode *call;
968 const TypeTuple *domain;
969 ciMethod* method = NULL;
970 if( sfpt->is_Call() ) {
971 call = sfpt->as_Call();
972 domain = call->tf()->domain();
973 cnt = domain->cnt();
974
975 // Match just the call, nothing else
976 MachNode *m = match_tree(call);
977 if (C->failing()) return NULL;
978 if( m == NULL ) { Matcher::soft_match_failure(); return NULL; }
979
980 // Copy data from the Ideal SafePoint to the machine version
981 mcall = m->as_MachCall();
982
983 mcall->set_tf( call->tf());
984 mcall->set_entry_point(call->entry_point());
985 mcall->set_cnt( call->cnt());
986
987 if( mcall->is_MachCallJava() ) {
988 MachCallJavaNode *mcall_java = mcall->as_MachCallJava();
989 const CallJavaNode *call_java = call->as_CallJava();
990 method = call_java->method();
991 mcall_java->_method = method;
992 mcall_java->_bci = call_java->_bci;
993 mcall_java->_optimized_virtual = call_java->is_optimized_virtual();
994 if( mcall_java->is_MachCallStaticJava() )
995 mcall_java->as_MachCallStaticJava()->_name =
996 call_java->as_CallStaticJava()->_name;
997 if( mcall_java->is_MachCallDynamicJava() )
998 mcall_java->as_MachCallDynamicJava()->_vtable_index =
999 call_java->as_CallDynamicJava()->_vtable_index;
1000 }
1001 else if( mcall->is_MachCallRuntime() ) {
1002 mcall->as_MachCallRuntime()->_name = call->as_CallRuntime()->_name;
1003 }
1004 msfpt = mcall;
1005 }
1006 // This is a non-call safepoint
1007 else {
1008 call = NULL;
1009 domain = NULL;
1010 MachNode *mn = match_tree(sfpt);
1011 if (C->failing()) return NULL;
1012 msfpt = mn->as_MachSafePoint();
1013 cnt = TypeFunc::Parms;
1014 }
1015
1016 // Advertise the correct memory effects (for anti-dependence computation).
1017 msfpt->set_adr_type(sfpt->adr_type());
1018
1019 // Allocate a private array of RegMasks. These RegMasks are not shared.
1020 msfpt->_in_rms = NEW_RESOURCE_ARRAY( RegMask, cnt );
1021 // Empty them all.
1022 memset( msfpt->_in_rms, 0, sizeof(RegMask)*cnt );
1023
1024 // Do all the pre-defined non-Empty register masks
1025 msfpt->_in_rms[TypeFunc::ReturnAdr] = _return_addr_mask;
1026 msfpt->_in_rms[TypeFunc::FramePtr ] = c_frame_ptr_mask;
1027
1028 // Place first outgoing argument can possibly be put.
1029 OptoReg::Name begin_out_arg_area = OptoReg::add(_new_SP, C->out_preserve_stack_slots());
1030 assert( is_even(begin_out_arg_area), "" );
1031 // Compute max outgoing register number per call site.
1032 OptoReg::Name out_arg_limit_per_call = begin_out_arg_area;
1033 // Calls to C may hammer extra stack slots above and beyond any arguments.
1034 // These are usually backing store for register arguments for varargs.
1035 if( call != NULL && call->is_CallRuntime() )
1036 out_arg_limit_per_call = OptoReg::add(out_arg_limit_per_call,C->varargs_C_out_slots_killed());
1037
1038
1039 // Do the normal argument list (parameters) register masks
1040 int argcnt = cnt - TypeFunc::Parms;
1041 if( argcnt > 0 ) { // Skip it all if we have no args
1042 BasicType *sig_bt = NEW_RESOURCE_ARRAY( BasicType, argcnt );
1043 VMRegPair *parm_regs = NEW_RESOURCE_ARRAY( VMRegPair, argcnt );
1044 int i;
1045 for( i = 0; i < argcnt; i++ ) {
1046 sig_bt[i] = domain->field_at(i+TypeFunc::Parms)->basic_type();
1047 }
1048 // V-call to pick proper calling convention
1049 call->calling_convention( sig_bt, parm_regs, argcnt );
1050
1051 #ifdef ASSERT
1052 // Sanity check users' calling convention. Really handy during
1053 // the initial porting effort. Fairly expensive otherwise.
1054 { for (int i = 0; i<argcnt; i++) {
1055 if( !parm_regs[i].first()->is_valid() &&
1056 !parm_regs[i].second()->is_valid() ) continue;
1057 VMReg reg1 = parm_regs[i].first();
1058 VMReg reg2 = parm_regs[i].second();
1059 for (int j = 0; j < i; j++) {
1060 if( !parm_regs[j].first()->is_valid() &&
1061 !parm_regs[j].second()->is_valid() ) continue;
1062 VMReg reg3 = parm_regs[j].first();
1063 VMReg reg4 = parm_regs[j].second();
1064 if( !reg1->is_valid() ) {
1065 assert( !reg2->is_valid(), "valid halvsies" );
1066 } else if( !reg3->is_valid() ) {
1067 assert( !reg4->is_valid(), "valid halvsies" );
1068 } else {
1069 assert( reg1 != reg2, "calling conv. must produce distinct regs");
1070 assert( reg1 != reg3, "calling conv. must produce distinct regs");
1071 assert( reg1 != reg4, "calling conv. must produce distinct regs");
1072 assert( reg2 != reg3, "calling conv. must produce distinct regs");
1073 assert( reg2 != reg4 || !reg2->is_valid(), "calling conv. must produce distinct regs");
1074 assert( reg3 != reg4, "calling conv. must produce distinct regs");
1075 }
1076 }
1077 }
1078 }
1079 #endif
1080
1081 // Visit each argument. Compute its outgoing register mask.
1082 // Return results now can have 2 bits returned.
1083 // Compute max over all outgoing arguments both per call-site
1084 // and over the entire method.
1085 for( i = 0; i < argcnt; i++ ) {
1086 // Address of incoming argument mask to fill in
1087 RegMask *rm = &mcall->_in_rms[i+TypeFunc::Parms];
1088 if( !parm_regs[i].first()->is_valid() &&
1089 !parm_regs[i].second()->is_valid() ) {
1090 continue; // Avoid Halves
1091 }
1092 // Grab first register, adjust stack slots and insert in mask.
1093 OptoReg::Name reg1 = warp_outgoing_stk_arg(parm_regs[i].first(), begin_out_arg_area, out_arg_limit_per_call );
1094 if (OptoReg::is_valid(reg1))
1095 rm->Insert( reg1 );
1096 // Grab second register (if any), adjust stack slots and insert in mask.
1097 OptoReg::Name reg2 = warp_outgoing_stk_arg(parm_regs[i].second(), begin_out_arg_area, out_arg_limit_per_call );
1098 if (OptoReg::is_valid(reg2))
1099 rm->Insert( reg2 );
1100 } // End of for all arguments
1101
1102 // Compute number of stack slots needed to restore stack in case of
1103 // Pascal-style argument popping.
1104 mcall->_argsize = out_arg_limit_per_call - begin_out_arg_area;
1105 }
1106
1107 // Compute the max stack slot killed by any call. These will not be
1108 // available for debug info, and will be used to adjust FIRST_STACK_mask
1109 // after all call sites have been visited.
1110 if( _out_arg_limit < out_arg_limit_per_call)
1111 _out_arg_limit = out_arg_limit_per_call;
1112
1113 if (mcall) {
1114 // Kill the outgoing argument area, including any non-argument holes and
1115 // any legacy C-killed slots. Use Fat-Projections to do the killing.
1116 // Since the max-per-method covers the max-per-call-site and debug info
1117 // is excluded on the max-per-method basis, debug info cannot land in
1118 // this killed area.
1119 uint r_cnt = mcall->tf()->range()->cnt();
1120 MachProjNode *proj = new (C, 1) MachProjNode( mcall, r_cnt+10000, RegMask::Empty, MachProjNode::fat_proj );
1121 if (!RegMask::can_represent(OptoReg::Name(out_arg_limit_per_call-1))) {
1122 C->record_method_not_compilable_all_tiers("unsupported outgoing calling sequence");
1123 } else {
1124 for (int i = begin_out_arg_area; i < out_arg_limit_per_call; i++)
1125 proj->_rout.Insert(OptoReg::Name(i));
1126 }
1127 if( proj->_rout.is_NotEmpty() )
1128 _proj_list.push(proj);
1129 }
1130 // Transfer the safepoint information from the call to the mcall
1131 // Move the JVMState list
1132 msfpt->set_jvms(sfpt->jvms());
1133 for (JVMState* jvms = msfpt->jvms(); jvms; jvms = jvms->caller()) {
1134 jvms->set_map(sfpt);
1135 }
1136
1137 // Debug inputs begin just after the last incoming parameter
1138 assert( (mcall == NULL) || (mcall->jvms() == NULL) ||
1139 (mcall->jvms()->debug_start() + mcall->_jvmadj == mcall->tf()->domain()->cnt()), "" );
1140
1141 // Move the OopMap
1142 msfpt->_oop_map = sfpt->_oop_map;
1143
1144 // Registers killed by the call are set in the local scheduling pass
1145 // of Global Code Motion.
1146 return msfpt;
1147 }
1148
1149 //---------------------------match_tree----------------------------------------
1150 // Match a Ideal Node DAG - turn it into a tree; Label & Reduce. Used as part
1151 // of the whole-sale conversion from Ideal to Mach Nodes. Also used for
1152 // making GotoNodes while building the CFG and in init_spill_mask() to identify
1153 // a Load's result RegMask for memoization in idealreg2regmask[]
1154 MachNode *Matcher::match_tree( const Node *n ) {
1155 assert( n->Opcode() != Op_Phi, "cannot match" );
1156 assert( !n->is_block_start(), "cannot match" );
1157 // Set the mark for all locally allocated State objects.
1158 // When this call returns, the _states_arena arena will be reset
1159 // freeing all State objects.
1160 ResourceMark rm( &_states_arena );
1161
1162 LabelRootDepth = 0;
1163
1164 // StoreNodes require their Memory input to match any LoadNodes
1165 Node *mem = n->is_Store() ? n->in(MemNode::Memory) : (Node*)1 ;
1166
1167 // State object for root node of match tree
1168 // Allocate it on _states_arena - stack allocation can cause stack overflow.
1169 State *s = new (&_states_arena) State;
1170 s->_kids[0] = NULL;
1171 s->_kids[1] = NULL;
1172 s->_leaf = (Node*)n;
1173 // Label the input tree, allocating labels from top-level arena
1174 Label_Root( n, s, n->in(0), mem );
1175 if (C->failing()) return NULL;
1176
1177 // The minimum cost match for the whole tree is found at the root State
1178 uint mincost = max_juint;
1179 uint cost = max_juint;
1180 uint i;
1181 for( i = 0; i < NUM_OPERANDS; i++ ) {
1182 if( s->valid(i) && // valid entry and
1183 s->_cost[i] < cost && // low cost and
1184 s->_rule[i] >= NUM_OPERANDS ) // not an operand
1185 cost = s->_cost[mincost=i];
1186 }
1187 if (mincost == max_juint) {
1188 #ifndef PRODUCT
1189 tty->print("No matching rule for:");
1190 s->dump();
1191 #endif
1192 Matcher::soft_match_failure();
1193 return NULL;
1194 }
1195 // Reduce input tree based upon the state labels to machine Nodes
1196 MachNode *m = ReduceInst( s, s->_rule[mincost], mem );
1197 #ifdef ASSERT
1198 _old2new_map.map(n->_idx, m);
1199 _new2old_map.map(m->_idx, (Node*)n);
1200 #endif
1201
1202 // Add any Matcher-ignored edges
1203 uint cnt = n->req();
1204 uint start = 1;
1205 if( mem != (Node*)1 ) start = MemNode::Memory+1;
1206 if( n->is_AddP() ) {
1207 assert( mem == (Node*)1, "" );
1208 start = AddPNode::Base+1;
1209 }
1210 for( i = start; i < cnt; i++ ) {
1211 if( !n->match_edge(i) ) {
1212 if( i < m->req() )
1213 m->ins_req( i, n->in(i) );
1214 else
1215 m->add_req( n->in(i) );
1216 }
1217 }
1218
1219 return m;
1220 }
1221
1222
1223 //------------------------------match_into_reg---------------------------------
1224 // Choose to either match this Node in a register or part of the current
1225 // match tree. Return true for requiring a register and false for matching
1226 // as part of the current match tree.
1227 static bool match_into_reg( const Node *n, Node *m, Node *control, int i, bool shared ) {
1228
1229 const Type *t = m->bottom_type();
1230
1231 if( t->singleton() ) {
1232 // Never force constants into registers. Allow them to match as
1233 // constants or registers. Copies of the same value will share
1234 // the same register. See find_shared_node.
1235 return false;
1236 } else { // Not a constant
1237 // Stop recursion if they have different Controls.
1238 // Slot 0 of constants is not really a Control.
1239 if( control && m->in(0) && control != m->in(0) ) {
1240
1241 // Actually, we can live with the most conservative control we
1242 // find, if it post-dominates the others. This allows us to
1243 // pick up load/op/store trees where the load can float a little
1244 // above the store.
1245 Node *x = control;
1246 const uint max_scan = 6; // Arbitrary scan cutoff
1247 uint j;
1248 for( j=0; j<max_scan; j++ ) {
1249 if( x->is_Region() ) // Bail out at merge points
1250 return true;
1251 x = x->in(0);
1252 if( x == m->in(0) ) // Does 'control' post-dominate
1253 break; // m->in(0)? If so, we can use it
1254 }
1255 if( j == max_scan ) // No post-domination before scan end?
1256 return true; // Then break the match tree up
1257 }
1258 if (m->is_DecodeN() && Matcher::clone_shift_expressions) {
1259 // These are commonly used in address expressions and can
1260 // efficiently fold into them on X64 in some cases.
1261 return false;
1262 }
1263 }
1264
1265 // Not forceably cloning. If shared, put it into a register.
1266 return shared;
1267 }
1268
1269
1270 //------------------------------Instruction Selection--------------------------
1271 // Label method walks a "tree" of nodes, using the ADLC generated DFA to match
1272 // ideal nodes to machine instructions. Trees are delimited by shared Nodes,
1273 // things the Matcher does not match (e.g., Memory), and things with different
1274 // Controls (hence forced into different blocks). We pass in the Control
1275 // selected for this entire State tree.
1276
1277 // The Matcher works on Trees, but an Intel add-to-memory requires a DAG: the
1278 // Store and the Load must have identical Memories (as well as identical
1279 // pointers). Since the Matcher does not have anything for Memory (and
1280 // does not handle DAGs), I have to match the Memory input myself. If the
1281 // Tree root is a Store, I require all Loads to have the identical memory.
1282 Node *Matcher::Label_Root( const Node *n, State *svec, Node *control, const Node *mem){
1283 // Since Label_Root is a recursive function, its possible that we might run
1284 // out of stack space. See bugs 6272980 & 6227033 for more info.
1285 LabelRootDepth++;
1286 if (LabelRootDepth > MaxLabelRootDepth) {
1287 C->record_method_not_compilable_all_tiers("Out of stack space, increase MaxLabelRootDepth");
1288 return NULL;
1289 }
1290 uint care = 0; // Edges matcher cares about
1291 uint cnt = n->req();
1292 uint i = 0;
1293
1294 // Examine children for memory state
1295 // Can only subsume a child into your match-tree if that child's memory state
1296 // is not modified along the path to another input.
1297 // It is unsafe even if the other inputs are separate roots.
1298 Node *input_mem = NULL;
1299 for( i = 1; i < cnt; i++ ) {
1300 if( !n->match_edge(i) ) continue;
1301 Node *m = n->in(i); // Get ith input
1302 assert( m, "expect non-null children" );
1303 if( m->is_Load() ) {
1304 if( input_mem == NULL ) {
1305 input_mem = m->in(MemNode::Memory);
1306 } else if( input_mem != m->in(MemNode::Memory) ) {
1307 input_mem = NodeSentinel;
1308 }
1309 }
1310 }
1311
1312 for( i = 1; i < cnt; i++ ){// For my children
1313 if( !n->match_edge(i) ) continue;
1314 Node *m = n->in(i); // Get ith input
1315 // Allocate states out of a private arena
1316 State *s = new (&_states_arena) State;
1317 svec->_kids[care++] = s;
1318 assert( care <= 2, "binary only for now" );
1319
1320 // Recursively label the State tree.
1321 s->_kids[0] = NULL;
1322 s->_kids[1] = NULL;
1323 s->_leaf = m;
1324
1325 // Check for leaves of the State Tree; things that cannot be a part of
1326 // the current tree. If it finds any, that value is matched as a
1327 // register operand. If not, then the normal matching is used.
1328 if( match_into_reg(n, m, control, i, is_shared(m)) ||
1329 //
1330 // Stop recursion if this is LoadNode and the root of this tree is a
1331 // StoreNode and the load & store have different memories.
1332 ((mem!=(Node*)1) && m->is_Load() && m->in(MemNode::Memory) != mem) ||
1333 // Can NOT include the match of a subtree when its memory state
1334 // is used by any of the other subtrees
1335 (input_mem == NodeSentinel) ) {
1336 #ifndef PRODUCT
1337 // Print when we exclude matching due to different memory states at input-loads
1338 if( PrintOpto && (Verbose && WizardMode) && (input_mem == NodeSentinel)
1339 && !((mem!=(Node*)1) && m->is_Load() && m->in(MemNode::Memory) != mem) ) {
1340 tty->print_cr("invalid input_mem");
1341 }
1342 #endif
1343 // Switch to a register-only opcode; this value must be in a register
1344 // and cannot be subsumed as part of a larger instruction.
1345 s->DFA( m->ideal_reg(), m );
1346
1347 } else {
1348 // If match tree has no control and we do, adopt it for entire tree
1349 if( control == NULL && m->in(0) != NULL && m->req() > 1 )
1350 control = m->in(0); // Pick up control
1351 // Else match as a normal part of the match tree.
1352 control = Label_Root(m,s,control,mem);
1353 if (C->failing()) return NULL;
1354 }
1355 }
1356
1357
1358 // Call DFA to match this node, and return
1359 svec->DFA( n->Opcode(), n );
1360
1361 #ifdef ASSERT
1362 uint x;
1363 for( x = 0; x < _LAST_MACH_OPER; x++ )
1364 if( svec->valid(x) )
1365 break;
1366
1367 if (x >= _LAST_MACH_OPER) {
1368 n->dump();
1369 svec->dump();
1370 assert( false, "bad AD file" );
1371 }
1372 #endif
1373 return control;
1374 }
1375
1376
1377 // Con nodes reduced using the same rule can share their MachNode
1378 // which reduces the number of copies of a constant in the final
1379 // program. The register allocator is free to split uses later to
1380 // split live ranges.
1381 MachNode* Matcher::find_shared_node(Node* leaf, uint rule) {
1382 if (!leaf->is_Con() && !leaf->is_DecodeN()) return NULL;
1383
1384 // See if this Con has already been reduced using this rule.
1385 if (_shared_nodes.Size() <= leaf->_idx) return NULL;
1386 MachNode* last = (MachNode*)_shared_nodes.at(leaf->_idx);
1387 if (last != NULL && rule == last->rule()) {
1388 // Don't expect control change for DecodeN
1389 if (leaf->is_DecodeN())
1390 return last;
1391 // Get the new space root.
1392 Node* xroot = new_node(C->root());
1393 if (xroot == NULL) {
1394 // This shouldn't happen give the order of matching.
1395 return NULL;
1396 }
1397
1398 // Shared constants need to have their control be root so they
1399 // can be scheduled properly.
1400 Node* control = last->in(0);
1401 if (control != xroot) {
1402 if (control == NULL || control == C->root()) {
1403 last->set_req(0, xroot);
1404 } else {
1405 assert(false, "unexpected control");
1406 return NULL;
1407 }
1408 }
1409 return last;
1410 }
1411 return NULL;
1412 }
1413
1414
1415 //------------------------------ReduceInst-------------------------------------
1416 // Reduce a State tree (with given Control) into a tree of MachNodes.
1417 // This routine (and it's cohort ReduceOper) convert Ideal Nodes into
1418 // complicated machine Nodes. Each MachNode covers some tree of Ideal Nodes.
1419 // Each MachNode has a number of complicated MachOper operands; each
1420 // MachOper also covers a further tree of Ideal Nodes.
1421
1422 // The root of the Ideal match tree is always an instruction, so we enter
1423 // the recursion here. After building the MachNode, we need to recurse
1424 // the tree checking for these cases:
1425 // (1) Child is an instruction -
1426 // Build the instruction (recursively), add it as an edge.
1427 // Build a simple operand (register) to hold the result of the instruction.
1428 // (2) Child is an interior part of an instruction -
1429 // Skip over it (do nothing)
1430 // (3) Child is the start of a operand -
1431 // Build the operand, place it inside the instruction
1432 // Call ReduceOper.
1433 MachNode *Matcher::ReduceInst( State *s, int rule, Node *&mem ) {
1434 assert( rule >= NUM_OPERANDS, "called with operand rule" );
1435
1436 MachNode* shared_node = find_shared_node(s->_leaf, rule);
1437 if (shared_node != NULL) {
1438 return shared_node;
1439 }
1440
1441 // Build the object to represent this state & prepare for recursive calls
1442 MachNode *mach = s->MachNodeGenerator( rule, C );
1443 mach->_opnds[0] = s->MachOperGenerator( _reduceOp[rule], C );
1444 assert( mach->_opnds[0] != NULL, "Missing result operand" );
1445 Node *leaf = s->_leaf;
1446 // Check for instruction or instruction chain rule
1447 if( rule >= _END_INST_CHAIN_RULE || rule < _BEGIN_INST_CHAIN_RULE ) {
1448 // Instruction
1449 mach->add_req( leaf->in(0) ); // Set initial control
1450 // Reduce interior of complex instruction
1451 ReduceInst_Interior( s, rule, mem, mach, 1 );
1452 } else {
1453 // Instruction chain rules are data-dependent on their inputs
1454 mach->add_req(0); // Set initial control to none
1455 ReduceInst_Chain_Rule( s, rule, mem, mach );
1456 }
1457
1458 // If a Memory was used, insert a Memory edge
1459 if( mem != (Node*)1 )
1460 mach->ins_req(MemNode::Memory,mem);
1461
1462 // If the _leaf is an AddP, insert the base edge
1463 if( leaf->is_AddP() )
1464 mach->ins_req(AddPNode::Base,leaf->in(AddPNode::Base));
1465
1466 uint num_proj = _proj_list.size();
1467
1468 // Perform any 1-to-many expansions required
1469 MachNode *ex = mach->Expand(s,_proj_list);
1470 if( ex != mach ) {
1471 assert(ex->ideal_reg() == mach->ideal_reg(), "ideal types should match");
1472 if( ex->in(1)->is_Con() )
1473 ex->in(1)->set_req(0, C->root());
1474 // Remove old node from the graph
1475 for( uint i=0; i<mach->req(); i++ ) {
1476 mach->set_req(i,NULL);
1477 }
1478 #ifdef ASSERT
1479 _new2old_map.map(ex->_idx, s->_leaf);
1480 #endif
1481 }
1482
1483 // PhaseChaitin::fixup_spills will sometimes generate spill code
1484 // via the matcher. By the time, nodes have been wired into the CFG,
1485 // and any further nodes generated by expand rules will be left hanging
1486 // in space, and will not get emitted as output code. Catch this.
1487 // Also, catch any new register allocation constraints ("projections")
1488 // generated belatedly during spill code generation.
1489 if (_allocation_started) {
1490 guarantee(ex == mach, "no expand rules during spill generation");
1491 guarantee(_proj_list.size() == num_proj, "no allocation during spill generation");
1492 }
1493
1494 if (leaf->is_Con() || leaf->is_DecodeN()) {
1495 // Record the con for sharing
1496 _shared_nodes.map(leaf->_idx, ex);
1497 }
1498
1499 return ex;
1500 }
1501
1502 void Matcher::ReduceInst_Chain_Rule( State *s, int rule, Node *&mem, MachNode *mach ) {
1503 // 'op' is what I am expecting to receive
1504 int op = _leftOp[rule];
1505 // Operand type to catch childs result
1506 // This is what my child will give me.
1507 int opnd_class_instance = s->_rule[op];
1508 // Choose between operand class or not.
1509 // This is what I will recieve.
1510 int catch_op = (FIRST_OPERAND_CLASS <= op && op < NUM_OPERANDS) ? opnd_class_instance : op;
1511 // New rule for child. Chase operand classes to get the actual rule.
1512 int newrule = s->_rule[catch_op];
1513
1514 if( newrule < NUM_OPERANDS ) {
1515 // Chain from operand or operand class, may be output of shared node
1516 assert( 0 <= opnd_class_instance && opnd_class_instance < NUM_OPERANDS,
1517 "Bad AD file: Instruction chain rule must chain from operand");
1518 // Insert operand into array of operands for this instruction
1519 mach->_opnds[1] = s->MachOperGenerator( opnd_class_instance, C );
1520
1521 ReduceOper( s, newrule, mem, mach );
1522 } else {
1523 // Chain from the result of an instruction
1524 assert( newrule >= _LAST_MACH_OPER, "Do NOT chain from internal operand");
1525 mach->_opnds[1] = s->MachOperGenerator( _reduceOp[catch_op], C );
1526 Node *mem1 = (Node*)1;
1527 mach->add_req( ReduceInst(s, newrule, mem1) );
1528 }
1529 return;
1530 }
1531
1532
1533 uint Matcher::ReduceInst_Interior( State *s, int rule, Node *&mem, MachNode *mach, uint num_opnds ) {
1534 if( s->_leaf->is_Load() ) {
1535 Node *mem2 = s->_leaf->in(MemNode::Memory);
1536 assert( mem == (Node*)1 || mem == mem2, "multiple Memories being matched at once?" );
1537 mem = mem2;
1538 }
1539 if( s->_leaf->in(0) != NULL && s->_leaf->req() > 1) {
1540 if( mach->in(0) == NULL )
1541 mach->set_req(0, s->_leaf->in(0));
1542 }
1543
1544 // Now recursively walk the state tree & add operand list.
1545 for( uint i=0; i<2; i++ ) { // binary tree
1546 State *newstate = s->_kids[i];
1547 if( newstate == NULL ) break; // Might only have 1 child
1548 // 'op' is what I am expecting to receive
1549 int op;
1550 if( i == 0 ) {
1551 op = _leftOp[rule];
1552 } else {
1553 op = _rightOp[rule];
1554 }
1555 // Operand type to catch childs result
1556 // This is what my child will give me.
1557 int opnd_class_instance = newstate->_rule[op];
1558 // Choose between operand class or not.
1559 // This is what I will receive.
1560 int catch_op = (op >= FIRST_OPERAND_CLASS && op < NUM_OPERANDS) ? opnd_class_instance : op;
1561 // New rule for child. Chase operand classes to get the actual rule.
1562 int newrule = newstate->_rule[catch_op];
1563
1564 if( newrule < NUM_OPERANDS ) { // Operand/operandClass or internalOp/instruction?
1565 // Operand/operandClass
1566 // Insert operand into array of operands for this instruction
1567 mach->_opnds[num_opnds++] = newstate->MachOperGenerator( opnd_class_instance, C );
1568 ReduceOper( newstate, newrule, mem, mach );
1569
1570 } else { // Child is internal operand or new instruction
1571 if( newrule < _LAST_MACH_OPER ) { // internal operand or instruction?
1572 // internal operand --> call ReduceInst_Interior
1573 // Interior of complex instruction. Do nothing but recurse.
1574 num_opnds = ReduceInst_Interior( newstate, newrule, mem, mach, num_opnds );
1575 } else {
1576 // instruction --> call build operand( ) to catch result
1577 // --> ReduceInst( newrule )
1578 mach->_opnds[num_opnds++] = s->MachOperGenerator( _reduceOp[catch_op], C );
1579 Node *mem1 = (Node*)1;
1580 mach->add_req( ReduceInst( newstate, newrule, mem1 ) );
1581 }
1582 }
1583 assert( mach->_opnds[num_opnds-1], "" );
1584 }
1585 return num_opnds;
1586 }
1587
1588 // This routine walks the interior of possible complex operands.
1589 // At each point we check our children in the match tree:
1590 // (1) No children -
1591 // We are a leaf; add _leaf field as an input to the MachNode
1592 // (2) Child is an internal operand -
1593 // Skip over it ( do nothing )
1594 // (3) Child is an instruction -
1595 // Call ReduceInst recursively and
1596 // and instruction as an input to the MachNode
1597 void Matcher::ReduceOper( State *s, int rule, Node *&mem, MachNode *mach ) {
1598 assert( rule < _LAST_MACH_OPER, "called with operand rule" );
1599 State *kid = s->_kids[0];
1600 assert( kid == NULL || s->_leaf->in(0) == NULL, "internal operands have no control" );
1601
1602 // Leaf? And not subsumed?
1603 if( kid == NULL && !_swallowed[rule] ) {
1604 mach->add_req( s->_leaf ); // Add leaf pointer
1605 return; // Bail out
1606 }
1607
1608 if( s->_leaf->is_Load() ) {
1609 assert( mem == (Node*)1, "multiple Memories being matched at once?" );
1610 mem = s->_leaf->in(MemNode::Memory);
1611 }
1612 if( s->_leaf->in(0) && s->_leaf->req() > 1) {
1613 if( !mach->in(0) )
1614 mach->set_req(0,s->_leaf->in(0));
1615 else {
1616 assert( s->_leaf->in(0) == mach->in(0), "same instruction, differing controls?" );
1617 }
1618 }
1619
1620 for( uint i=0; kid != NULL && i<2; kid = s->_kids[1], i++ ) { // binary tree
1621 int newrule;
1622 if( i == 0 )
1623 newrule = kid->_rule[_leftOp[rule]];
1624 else
1625 newrule = kid->_rule[_rightOp[rule]];
1626
1627 if( newrule < _LAST_MACH_OPER ) { // Operand or instruction?
1628 // Internal operand; recurse but do nothing else
1629 ReduceOper( kid, newrule, mem, mach );
1630
1631 } else { // Child is a new instruction
1632 // Reduce the instruction, and add a direct pointer from this
1633 // machine instruction to the newly reduced one.
1634 Node *mem1 = (Node*)1;
1635 mach->add_req( ReduceInst( kid, newrule, mem1 ) );
1636 }
1637 }
1638 }
1639
1640
1641 // -------------------------------------------------------------------------
1642 // Java-Java calling convention
1643 // (what you use when Java calls Java)
1644
1645 //------------------------------find_receiver----------------------------------
1646 // For a given signature, return the OptoReg for parameter 0.
1647 OptoReg::Name Matcher::find_receiver( bool is_outgoing ) {
1648 VMRegPair regs;
1649 BasicType sig_bt = T_OBJECT;
1650 calling_convention(&sig_bt, ®s, 1, is_outgoing);
1651 // Return argument 0 register. In the LP64 build pointers
1652 // take 2 registers, but the VM wants only the 'main' name.
1653 return OptoReg::as_OptoReg(regs.first());
1654 }
1655
1656 // A method-klass-holder may be passed in the inline_cache_reg
1657 // and then expanded into the inline_cache_reg and a method_oop register
1658 // defined in ad_<arch>.cpp
1659
1660
1661 //------------------------------find_shared------------------------------------
1662 // Set bits if Node is shared or otherwise a root
1663 void Matcher::find_shared( Node *n ) {
1664 // Allocate stack of size C->unique() * 2 to avoid frequent realloc
1665 MStack mstack(C->unique() * 2);
1666 mstack.push(n, Visit); // Don't need to pre-visit root node
1667 while (mstack.is_nonempty()) {
1668 n = mstack.node(); // Leave node on stack
1669 Node_State nstate = mstack.state();
1670 if (nstate == Pre_Visit) {
1671 if (is_visited(n)) { // Visited already?
1672 // Node is shared and has no reason to clone. Flag it as shared.
1673 // This causes it to match into a register for the sharing.
1674 set_shared(n); // Flag as shared and
1675 mstack.pop(); // remove node from stack
1676 continue;
1677 }
1678 nstate = Visit; // Not already visited; so visit now
1679 }
1680 if (nstate == Visit) {
1681 mstack.set_state(Post_Visit);
1682 set_visited(n); // Flag as visited now
1683 bool mem_op = false;
1684
1685 switch( n->Opcode() ) { // Handle some opcodes special
1686 case Op_Phi: // Treat Phis as shared roots
1687 case Op_Parm:
1688 case Op_Proj: // All handled specially during matching
1689 case Op_SafePointScalarObject:
1690 set_shared(n);
1691 set_dontcare(n);
1692 break;
1693 case Op_If:
1694 case Op_CountedLoopEnd:
1695 mstack.set_state(Alt_Post_Visit); // Alternative way
1696 // Convert (If (Bool (CmpX A B))) into (If (Bool) (CmpX A B)). Helps
1697 // with matching cmp/branch in 1 instruction. The Matcher needs the
1698 // Bool and CmpX side-by-side, because it can only get at constants
1699 // that are at the leaves of Match trees, and the Bool's condition acts
1700 // as a constant here.
1701 mstack.push(n->in(1), Visit); // Clone the Bool
1702 mstack.push(n->in(0), Pre_Visit); // Visit control input
1703 continue; // while (mstack.is_nonempty())
1704 case Op_ConvI2D: // These forms efficiently match with a prior
1705 case Op_ConvI2F: // Load but not a following Store
1706 if( n->in(1)->is_Load() && // Prior load
1707 n->outcnt() == 1 && // Not already shared
1708 n->unique_out()->is_Store() ) // Following store
1709 set_shared(n); // Force it to be a root
1710 break;
1711 case Op_ReverseBytesI:
1712 case Op_ReverseBytesL:
1713 if( n->in(1)->is_Load() && // Prior load
1714 n->outcnt() == 1 ) // Not already shared
1715 set_shared(n); // Force it to be a root
1716 break;
1717 case Op_BoxLock: // Cant match until we get stack-regs in ADLC
1718 case Op_IfFalse:
1719 case Op_IfTrue:
1720 case Op_MachProj:
1721 case Op_MergeMem:
1722 case Op_Catch:
1723 case Op_CatchProj:
1724 case Op_CProj:
1725 case Op_JumpProj:
1726 case Op_JProj:
1727 case Op_NeverBranch:
1728 set_dontcare(n);
1729 break;
1730 case Op_Jump:
1731 mstack.push(n->in(1), Visit); // Switch Value
1732 mstack.push(n->in(0), Pre_Visit); // Visit Control input
1733 continue; // while (mstack.is_nonempty())
1734 case Op_StrComp:
1735 case Op_AryEq:
1736 set_shared(n); // Force result into register (it will be anyways)
1737 break;
1738 case Op_ConP: { // Convert pointers above the centerline to NUL
1739 TypeNode *tn = n->as_Type(); // Constants derive from type nodes
1740 const TypePtr* tp = tn->type()->is_ptr();
1741 if (tp->_ptr == TypePtr::AnyNull) {
1742 tn->set_type(TypePtr::NULL_PTR);
1743 }
1744 break;
1745 }
1746 case Op_ConN: { // Convert narrow pointers above the centerline to NUL
1747 TypeNode *tn = n->as_Type(); // Constants derive from type nodes
1748 const TypePtr* tp = tn->type()->is_narrowoop()->make_oopptr();
1749 if (tp->_ptr == TypePtr::AnyNull) {
1750 tn->set_type(TypeNarrowOop::NULL_PTR);
1751 }
1752 break;
1753 }
1754 case Op_Binary: // These are introduced in the Post_Visit state.
1755 ShouldNotReachHere();
1756 break;
1757 case Op_StoreB: // Do match these, despite no ideal reg
1758 case Op_StoreC:
1759 case Op_StoreCM:
1760 case Op_StoreD:
1761 case Op_StoreF:
1762 case Op_StoreI:
1763 case Op_StoreL:
1764 case Op_StoreP:
1765 case Op_StoreN:
1766 case Op_Store16B:
1767 case Op_Store8B:
1768 case Op_Store4B:
1769 case Op_Store8C:
1770 case Op_Store4C:
1771 case Op_Store2C:
1772 case Op_Store4I:
1773 case Op_Store2I:
1774 case Op_Store2L:
1775 case Op_Store4F:
1776 case Op_Store2F:
1777 case Op_Store2D:
1778 case Op_ClearArray:
1779 case Op_SafePoint:
1780 mem_op = true;
1781 break;
1782 case Op_LoadB:
1783 case Op_LoadC:
1784 case Op_LoadD:
1785 case Op_LoadF:
1786 case Op_LoadI:
1787 case Op_LoadKlass:
1788 case Op_LoadNKlass:
1789 case Op_LoadL:
1790 case Op_LoadS:
1791 case Op_LoadP:
1792 case Op_LoadN:
1793 case Op_LoadRange:
1794 case Op_LoadD_unaligned:
1795 case Op_LoadL_unaligned:
1796 case Op_Load16B:
1797 case Op_Load8B:
1798 case Op_Load4B:
1799 case Op_Load4C:
1800 case Op_Load2C:
1801 case Op_Load8C:
1802 case Op_Load8S:
1803 case Op_Load4S:
1804 case Op_Load2S:
1805 case Op_Load4I:
1806 case Op_Load2I:
1807 case Op_Load2L:
1808 case Op_Load4F:
1809 case Op_Load2F:
1810 case Op_Load2D:
1811 mem_op = true;
1812 // Must be root of match tree due to prior load conflict
1813 if( C->subsume_loads() == false ) {
1814 set_shared(n);
1815 }
1816 // Fall into default case
1817 default:
1818 if( !n->ideal_reg() )
1819 set_dontcare(n); // Unmatchable Nodes
1820 } // end_switch
1821
1822 for(int i = n->req() - 1; i >= 0; --i) { // For my children
1823 Node *m = n->in(i); // Get ith input
1824 if (m == NULL) continue; // Ignore NULLs
1825 uint mop = m->Opcode();
1826
1827 // Must clone all producers of flags, or we will not match correctly.
1828 // Suppose a compare setting int-flags is shared (e.g., a switch-tree)
1829 // then it will match into an ideal Op_RegFlags. Alas, the fp-flags
1830 // are also there, so we may match a float-branch to int-flags and
1831 // expect the allocator to haul the flags from the int-side to the
1832 // fp-side. No can do.
1833 if( _must_clone[mop] ) {
1834 mstack.push(m, Visit);
1835 continue; // for(int i = ...)
1836 }
1837
1838 // Clone addressing expressions as they are "free" in most instructions
1839 if( mem_op && i == MemNode::Address && mop == Op_AddP ) {
1840 Node *off = m->in(AddPNode::Offset);
1841 if( off->is_Con() ) {
1842 set_visited(m); // Flag as visited now
1843 Node *adr = m->in(AddPNode::Address);
1844
1845 // Intel, ARM and friends can handle 2 adds in addressing mode
1846 if( clone_shift_expressions && adr->is_AddP() &&
1847 // AtomicAdd is not an addressing expression.
1848 // Cheap to find it by looking for screwy base.
1849 !adr->in(AddPNode::Base)->is_top() ) {
1850 set_visited(adr); // Flag as visited now
1851 Node *shift = adr->in(AddPNode::Offset);
1852 // Check for shift by small constant as well
1853 if( shift->Opcode() == Op_LShiftX && shift->in(2)->is_Con() &&
1854 shift->in(2)->get_int() <= 3 ) {
1855 set_visited(shift); // Flag as visited now
1856 mstack.push(shift->in(2), Visit);
1857 #ifdef _LP64
1858 // Allow Matcher to match the rule which bypass
1859 // ConvI2L operation for an array index on LP64
1860 // if the index value is positive.
1861 if( shift->in(1)->Opcode() == Op_ConvI2L &&
1862 shift->in(1)->as_Type()->type()->is_long()->_lo >= 0 ) {
1863 set_visited(shift->in(1)); // Flag as visited now
1864 mstack.push(shift->in(1)->in(1), Pre_Visit);
1865 } else
1866 #endif
1867 mstack.push(shift->in(1), Pre_Visit);
1868 } else {
1869 mstack.push(shift, Pre_Visit);
1870 }
1871 mstack.push(adr->in(AddPNode::Address), Pre_Visit);
1872 mstack.push(adr->in(AddPNode::Base), Pre_Visit);
1873 } else { // Sparc, Alpha, PPC and friends
1874 mstack.push(adr, Pre_Visit);
1875 }
1876
1877 // Clone X+offset as it also folds into most addressing expressions
1878 mstack.push(off, Visit);
1879 mstack.push(m->in(AddPNode::Base), Pre_Visit);
1880 continue; // for(int i = ...)
1881 } // if( off->is_Con() )
1882 } // if( mem_op &&
1883 mstack.push(m, Pre_Visit);
1884 } // for(int i = ...)
1885 }
1886 else if (nstate == Alt_Post_Visit) {
1887 mstack.pop(); // Remove node from stack
1888 // We cannot remove the Cmp input from the Bool here, as the Bool may be
1889 // shared and all users of the Bool need to move the Cmp in parallel.
1890 // This leaves both the Bool and the If pointing at the Cmp. To
1891 // prevent the Matcher from trying to Match the Cmp along both paths
1892 // BoolNode::match_edge always returns a zero.
1893
1894 // We reorder the Op_If in a pre-order manner, so we can visit without
1895 // accidently sharing the Cmp (the Bool and the If make 2 users).
1896 n->add_req( n->in(1)->in(1) ); // Add the Cmp next to the Bool
1897 }
1898 else if (nstate == Post_Visit) {
1899 mstack.pop(); // Remove node from stack
1900
1901 // Now hack a few special opcodes
1902 switch( n->Opcode() ) { // Handle some opcodes special
1903 case Op_StorePConditional:
1904 case Op_StoreLConditional:
1905 case Op_CompareAndSwapI:
1906 case Op_CompareAndSwapL:
1907 case Op_CompareAndSwapP:
1908 case Op_CompareAndSwapN: { // Convert trinary to binary-tree
1909 Node *newval = n->in(MemNode::ValueIn );
1910 Node *oldval = n->in(LoadStoreNode::ExpectedIn);
1911 Node *pair = new (C, 3) BinaryNode( oldval, newval );
1912 n->set_req(MemNode::ValueIn,pair);
1913 n->del_req(LoadStoreNode::ExpectedIn);
1914 break;
1915 }
1916 case Op_CMoveD: // Convert trinary to binary-tree
1917 case Op_CMoveF:
1918 case Op_CMoveI:
1919 case Op_CMoveL:
1920 case Op_CMoveN:
1921 case Op_CMoveP: {
1922 // Restructure into a binary tree for Matching. It's possible that
1923 // we could move this code up next to the graph reshaping for IfNodes
1924 // or vice-versa, but I do not want to debug this for Ladybird.
1925 // 10/2/2000 CNC.
1926 Node *pair1 = new (C, 3) BinaryNode(n->in(1),n->in(1)->in(1));
1927 n->set_req(1,pair1);
1928 Node *pair2 = new (C, 3) BinaryNode(n->in(2),n->in(3));
1929 n->set_req(2,pair2);
1930 n->del_req(3);
1931 break;
1932 }
1933 default:
1934 break;
1935 }
1936 }
1937 else {
1938 ShouldNotReachHere();
1939 }
1940 } // end of while (mstack.is_nonempty())
1941 }
1942
1943 #ifdef ASSERT
1944 // machine-independent root to machine-dependent root
1945 void Matcher::dump_old2new_map() {
1946 _old2new_map.dump();
1947 }
1948 #endif
1949
1950 //---------------------------collect_null_checks-------------------------------
1951 // Find null checks in the ideal graph; write a machine-specific node for
1952 // it. Used by later implicit-null-check handling. Actually collects
1953 // either an IfTrue or IfFalse for the common NOT-null path, AND the ideal
1954 // value being tested.
1955 void Matcher::collect_null_checks( Node *proj ) {
1956 Node *iff = proj->in(0);
1957 if( iff->Opcode() == Op_If ) {
1958 // During matching If's have Bool & Cmp side-by-side
1959 BoolNode *b = iff->in(1)->as_Bool();
1960 Node *cmp = iff->in(2);
1961 int opc = cmp->Opcode();
1962 if (opc != Op_CmpP && opc != Op_CmpN) return;
1963
1964 const Type* ct = cmp->in(2)->bottom_type();
1965 if (ct == TypePtr::NULL_PTR ||
1966 (opc == Op_CmpN && ct == TypeNarrowOop::NULL_PTR)) {
1967
1968 if( proj->Opcode() == Op_IfTrue ) {
1969 extern int all_null_checks_found;
1970 all_null_checks_found++;
1971 if( b->_test._test == BoolTest::ne ) {
1972 _null_check_tests.push(proj);
1973 _null_check_tests.push(cmp->in(1));
1974 }
1975 } else {
1976 assert( proj->Opcode() == Op_IfFalse, "" );
1977 if( b->_test._test == BoolTest::eq ) {
1978 _null_check_tests.push(proj);
1979 _null_check_tests.push(cmp->in(1));
1980 }
1981 }
1982 }
1983 }
1984 }
1985
1986 //---------------------------validate_null_checks------------------------------
1987 // Its possible that the value being NULL checked is not the root of a match
1988 // tree. If so, I cannot use the value in an implicit null check.
1989 void Matcher::validate_null_checks( ) {
1990 uint cnt = _null_check_tests.size();
1991 for( uint i=0; i < cnt; i+=2 ) {
1992 Node *test = _null_check_tests[i];
1993 Node *val = _null_check_tests[i+1];
1994 if (has_new_node(val)) {
1995 // Is a match-tree root, so replace with the matched value
1996 _null_check_tests.map(i+1, new_node(val));
1997 } else {
1998 // Yank from candidate list
1999 _null_check_tests.map(i+1,_null_check_tests[--cnt]);
2000 _null_check_tests.map(i,_null_check_tests[--cnt]);
2001 _null_check_tests.pop();
2002 _null_check_tests.pop();
2003 i-=2;
2004 }
2005 }
2006 }
2007
2008
2009 // Used by the DFA in dfa_sparc.cpp. Check for a prior FastLock
2010 // acting as an Acquire and thus we don't need an Acquire here. We
2011 // retain the Node to act as a compiler ordering barrier.
2012 bool Matcher::prior_fast_lock( const Node *acq ) {
2013 Node *r = acq->in(0);
2014 if( !r->is_Region() || r->req() <= 1 ) return false;
2015 Node *proj = r->in(1);
2016 if( !proj->is_Proj() ) return false;
2017 Node *call = proj->in(0);
2018 if( !call->is_Call() || call->as_Call()->entry_point() != OptoRuntime::complete_monitor_locking_Java() )
2019 return false;
2020
2021 return true;
2022 }
2023
2024 // Used by the DFA in dfa_sparc.cpp. Check for a following FastUnLock
2025 // acting as a Release and thus we don't need a Release here. We
2026 // retain the Node to act as a compiler ordering barrier.
2027 bool Matcher::post_fast_unlock( const Node *rel ) {
2028 Compile *C = Compile::current();
2029 assert( rel->Opcode() == Op_MemBarRelease, "" );
2030 const MemBarReleaseNode *mem = (const MemBarReleaseNode*)rel;
2031 DUIterator_Fast imax, i = mem->fast_outs(imax);
2032 Node *ctrl = NULL;
2033 while( true ) {
2034 ctrl = mem->fast_out(i); // Throw out-of-bounds if proj not found
2035 assert( ctrl->is_Proj(), "only projections here" );
2036 ProjNode *proj = (ProjNode*)ctrl;
2037 if( proj->_con == TypeFunc::Control &&
2038 !C->node_arena()->contains(ctrl) ) // Unmatched old-space only
2039 break;
2040 i++;
2041 }
2042 Node *iff = NULL;
2043 for( DUIterator_Fast jmax, j = ctrl->fast_outs(jmax); j < jmax; j++ ) {
2044 Node *x = ctrl->fast_out(j);
2045 if( x->is_If() && x->req() > 1 &&
2046 !C->node_arena()->contains(x) ) { // Unmatched old-space only
2047 iff = x;
2048 break;
2049 }
2050 }
2051 if( !iff ) return false;
2052 Node *bol = iff->in(1);
2053 // The iff might be some random subclass of If or bol might be Con-Top
2054 if (!bol->is_Bool()) return false;
2055 assert( bol->req() > 1, "" );
2056 return (bol->in(1)->Opcode() == Op_FastUnlock);
2057 }
2058
2059 // Used by the DFA in dfa_xxx.cpp. Check for a following barrier or
2060 // atomic instruction acting as a store_load barrier without any
2061 // intervening volatile load, and thus we don't need a barrier here.
2062 // We retain the Node to act as a compiler ordering barrier.
2063 bool Matcher::post_store_load_barrier(const Node *vmb) {
2064 Compile *C = Compile::current();
2065 assert( vmb->is_MemBar(), "" );
2066 assert( vmb->Opcode() != Op_MemBarAcquire, "" );
2067 const MemBarNode *mem = (const MemBarNode*)vmb;
2068
2069 // Get the Proj node, ctrl, that can be used to iterate forward
2070 Node *ctrl = NULL;
2071 DUIterator_Fast imax, i = mem->fast_outs(imax);
2072 while( true ) {
2073 ctrl = mem->fast_out(i); // Throw out-of-bounds if proj not found
2074 assert( ctrl->is_Proj(), "only projections here" );
2075 ProjNode *proj = (ProjNode*)ctrl;
2076 if( proj->_con == TypeFunc::Control &&
2077 !C->node_arena()->contains(ctrl) ) // Unmatched old-space only
2078 break;
2079 i++;
2080 }
2081
2082 for( DUIterator_Fast jmax, j = ctrl->fast_outs(jmax); j < jmax; j++ ) {
2083 Node *x = ctrl->fast_out(j);
2084 int xop = x->Opcode();
2085
2086 // We don't need current barrier if we see another or a lock
2087 // before seeing volatile load.
2088 //
2089 // Op_Fastunlock previously appeared in the Op_* list below.
2090 // With the advent of 1-0 lock operations we're no longer guaranteed
2091 // that a monitor exit operation contains a serializing instruction.
2092
2093 if (xop == Op_MemBarVolatile ||
2094 xop == Op_FastLock ||
2095 xop == Op_CompareAndSwapL ||
2096 xop == Op_CompareAndSwapP ||
2097 xop == Op_CompareAndSwapN ||
2098 xop == Op_CompareAndSwapI)
2099 return true;
2100
2101 if (x->is_MemBar()) {
2102 // We must retain this membar if there is an upcoming volatile
2103 // load, which will be preceded by acquire membar.
2104 if (xop == Op_MemBarAcquire)
2105 return false;
2106 // For other kinds of barriers, check by pretending we
2107 // are them, and seeing if we can be removed.
2108 else
2109 return post_store_load_barrier((const MemBarNode*)x);
2110 }
2111
2112 // Delicate code to detect case of an upcoming fastlock block
2113 if( x->is_If() && x->req() > 1 &&
2114 !C->node_arena()->contains(x) ) { // Unmatched old-space only
2115 Node *iff = x;
2116 Node *bol = iff->in(1);
2117 // The iff might be some random subclass of If or bol might be Con-Top
2118 if (!bol->is_Bool()) return false;
2119 assert( bol->req() > 1, "" );
2120 return (bol->in(1)->Opcode() == Op_FastUnlock);
2121 }
2122 // probably not necessary to check for these
2123 if (x->is_Call() || x->is_SafePoint() || x->is_block_proj())
2124 return false;
2125 }
2126 return false;
2127 }
2128
2129 //=============================================================================
2130 //---------------------------State---------------------------------------------
2131 State::State(void) {
2132 #ifdef ASSERT
2133 _id = 0;
2134 _kids[0] = _kids[1] = (State*)(intptr_t) CONST64(0xcafebabecafebabe);
2135 _leaf = (Node*)(intptr_t) CONST64(0xbaadf00dbaadf00d);
2136 //memset(_cost, -1, sizeof(_cost));
2137 //memset(_rule, -1, sizeof(_rule));
2138 #endif
2139 memset(_valid, 0, sizeof(_valid));
2140 }
2141
2142 #ifdef ASSERT
2143 State::~State() {
2144 _id = 99;
2145 _kids[0] = _kids[1] = (State*)(intptr_t) CONST64(0xcafebabecafebabe);
2146 _leaf = (Node*)(intptr_t) CONST64(0xbaadf00dbaadf00d);
2147 memset(_cost, -3, sizeof(_cost));
2148 memset(_rule, -3, sizeof(_rule));
2149 }
2150 #endif
2151
2152 #ifndef PRODUCT
2153 //---------------------------dump----------------------------------------------
2154 void State::dump() {
2155 tty->print("\n");
2156 dump(0);
2157 }
2158
2159 void State::dump(int depth) {
2160 for( int j = 0; j < depth; j++ )
2161 tty->print(" ");
2162 tty->print("--N: ");
2163 _leaf->dump();
2164 uint i;
2165 for( i = 0; i < _LAST_MACH_OPER; i++ )
2166 // Check for valid entry
2167 if( valid(i) ) {
2168 for( int j = 0; j < depth; j++ )
2169 tty->print(" ");
2170 assert(_cost[i] != max_juint, "cost must be a valid value");
2171 assert(_rule[i] < _last_Mach_Node, "rule[i] must be valid rule");
2172 tty->print_cr("%s %d %s",
2173 ruleName[i], _cost[i], ruleName[_rule[i]] );
2174 }
2175 tty->print_cr("");
2176
2177 for( i=0; i<2; i++ )
2178 if( _kids[i] )
2179 _kids[i]->dump(depth+1);
2180 }
2181 #endif