1 /*
2 * Copyright (c) 1997, 2025, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.
8 *
9 * This code is distributed in the hope that it will be useful, but WITHOUT
10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
12 * version 2 for more details (a copy is included in the LICENSE file that
13 * accompanied this code).
14 *
15 * You should have received a copy of the GNU General Public License version
16 * 2 along with this work; if not, write to the Free Software Foundation,
17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18 *
19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20 * or visit www.oracle.com if you need additional information or have any
21 * questions.
22 *
23 */
24
25 #include "gc/shared/barrierSet.hpp"
26 #include "gc/shared/c2/barrierSetC2.hpp"
27 #include "memory/allocation.inline.hpp"
28 #include "memory/resourceArea.hpp"
29 #include "oops/compressedOops.hpp"
30 #include "opto/ad.hpp"
31 #include "opto/addnode.hpp"
32 #include "opto/callnode.hpp"
33 #include "opto/idealGraphPrinter.hpp"
34 #include "opto/matcher.hpp"
35 #include "opto/memnode.hpp"
36 #include "opto/movenode.hpp"
37 #include "opto/opcodes.hpp"
38 #include "opto/regmask.hpp"
39 #include "opto/rootnode.hpp"
40 #include "opto/runtime.hpp"
41 #include "opto/type.hpp"
42 #include "opto/vectornode.hpp"
43 #include "runtime/os.inline.hpp"
44 #include "runtime/sharedRuntime.hpp"
45 #include "utilities/align.hpp"
46
47 OptoReg::Name OptoReg::c_frame_pointer;
48
49 const RegMask *Matcher::idealreg2regmask[_last_machine_leaf];
50 RegMask Matcher::mreg2regmask[_last_Mach_Reg];
51 RegMask Matcher::caller_save_regmask;
52 RegMask Matcher::caller_save_regmask_exclude_soe;
53 RegMask Matcher::STACK_ONLY_mask;
54 RegMask Matcher::c_frame_ptr_mask;
55 const uint Matcher::_begin_rematerialize = _BEGIN_REMATERIALIZE;
56 const uint Matcher::_end_rematerialize = _END_REMATERIALIZE;
57
58 //---------------------------Matcher-------------------------------------------
59 Matcher::Matcher()
60 : PhaseTransform( Phase::Ins_Select ),
61 _states_arena(Chunk::medium_size, mtCompiler, Arena::Tag::tag_states),
62 _new_nodes(C->comp_arena()),
63 _visited(&_states_arena),
64 _shared(&_states_arena),
65 _dontcare(&_states_arena),
66 _reduceOp(reduceOp), _leftOp(leftOp), _rightOp(rightOp),
67 _swallowed(swallowed),
68 _begin_inst_chain_rule(_BEGIN_INST_CHAIN_RULE),
69 _end_inst_chain_rule(_END_INST_CHAIN_RULE),
70 _must_clone(must_clone),
71 _shared_nodes(C->comp_arena()),
72 #ifndef PRODUCT
73 _old2new_map(C->comp_arena()),
74 _new2old_map(C->comp_arena()),
75 _reused(C->comp_arena()),
76 #endif // !PRODUCT
77 _allocation_started(false),
78 _ruleName(ruleName),
79 _register_save_policy(register_save_policy),
80 _c_reg_save_policy(c_reg_save_policy),
81 _register_save_type(register_save_type),
82 _return_addr_mask(C->comp_arena()) {
83 C->set_matcher(this);
84
85 idealreg2spillmask [Op_RegI] = nullptr;
86 idealreg2spillmask [Op_RegN] = nullptr;
87 idealreg2spillmask [Op_RegL] = nullptr;
88 idealreg2spillmask [Op_RegF] = nullptr;
89 idealreg2spillmask [Op_RegD] = nullptr;
90 idealreg2spillmask [Op_RegP] = nullptr;
91 idealreg2spillmask [Op_VecA] = nullptr;
92 idealreg2spillmask [Op_VecS] = nullptr;
93 idealreg2spillmask [Op_VecD] = nullptr;
94 idealreg2spillmask [Op_VecX] = nullptr;
95 idealreg2spillmask [Op_VecY] = nullptr;
96 idealreg2spillmask [Op_VecZ] = nullptr;
97 idealreg2spillmask [Op_RegFlags] = nullptr;
98 idealreg2spillmask [Op_RegVectMask] = nullptr;
99
100 idealreg2debugmask [Op_RegI] = nullptr;
101 idealreg2debugmask [Op_RegN] = nullptr;
102 idealreg2debugmask [Op_RegL] = nullptr;
103 idealreg2debugmask [Op_RegF] = nullptr;
104 idealreg2debugmask [Op_RegD] = nullptr;
105 idealreg2debugmask [Op_RegP] = nullptr;
106 idealreg2debugmask [Op_VecA] = nullptr;
107 idealreg2debugmask [Op_VecS] = nullptr;
108 idealreg2debugmask [Op_VecD] = nullptr;
109 idealreg2debugmask [Op_VecX] = nullptr;
110 idealreg2debugmask [Op_VecY] = nullptr;
111 idealreg2debugmask [Op_VecZ] = nullptr;
112 idealreg2debugmask [Op_RegFlags] = nullptr;
113 idealreg2debugmask [Op_RegVectMask] = nullptr;
114
115 DEBUG_ONLY(_mem_node = nullptr;) // Ideal memory node consumed by mach node
116 }
117
118 //------------------------------warp_incoming_stk_arg------------------------
119 // This warps a VMReg into an OptoReg::Name
120 OptoReg::Name Matcher::warp_incoming_stk_arg( VMReg reg ) {
121 OptoReg::Name warped;
122 if( reg->is_stack() ) { // Stack slot argument?
123 warped = OptoReg::add(_old_SP, reg->reg2stack() );
124 warped = OptoReg::add(warped, C->out_preserve_stack_slots());
125 if( warped >= _in_arg_limit )
126 _in_arg_limit = OptoReg::add(warped, 1); // Bump max stack slot seen
127 return warped;
128 }
129 return OptoReg::as_OptoReg(reg);
130 }
131
132 //---------------------------compute_old_SP------------------------------------
133 OptoReg::Name Compile::compute_old_SP() {
134 int fixed = fixed_slots();
135 int preserve = in_preserve_stack_slots();
136 return OptoReg::stack2reg(align_up(fixed + preserve, (int)Matcher::stack_alignment_in_slots()));
137 }
138
139
140
141 #ifdef ASSERT
142 void Matcher::verify_new_nodes_only(Node* xroot) {
143 // Make sure that the new graph only references new nodes
144 ResourceMark rm;
145 Unique_Node_List worklist;
146 VectorSet visited;
147 worklist.push(xroot);
148 while (worklist.size() > 0) {
149 Node* n = worklist.pop();
150 if (visited.test_set(n->_idx)) {
151 continue;
152 }
153 assert(C->node_arena()->contains(n), "dead node");
154 for (uint j = 0; j < n->req(); j++) {
155 Node* in = n->in(j);
156 if (in != nullptr) {
157 worklist.push(in);
158 }
159 }
160 for (DUIterator_Fast jmax, j = n->fast_outs(jmax); j < jmax; j++) {
161 worklist.push(n->fast_out(j));
162 }
163 }
164 }
165 #endif
166
167 // Array of RegMask, one per returned values (inline type instances can
168 // be returned as multiple return values, one per field)
169 RegMask* Matcher::return_values_mask(const TypeFunc* tf) {
170 const TypeTuple* range = tf->range_cc();
171 uint cnt = range->cnt() - TypeFunc::Parms;
172 if (cnt == 0) {
173 return nullptr;
174 }
175 RegMask* mask = NEW_RESOURCE_ARRAY(RegMask, cnt);
176 BasicType* sig_bt = NEW_RESOURCE_ARRAY(BasicType, cnt);
177 VMRegPair* vm_parm_regs = NEW_RESOURCE_ARRAY(VMRegPair, cnt);
178 for (uint i = 0; i < cnt; i++) {
179 sig_bt[i] = range->field_at(i+TypeFunc::Parms)->basic_type();
180 new (mask + i) RegMask();
181 }
182
183 int regs = SharedRuntime::java_return_convention(sig_bt, vm_parm_regs, cnt);
184 if (regs <= 0) {
185 // We ran out of registers to store the null marker for a nullable inline type return.
186 // Since it is only set in the 'call_epilog', we can simply put it on the stack.
187 assert(tf->returns_inline_type_as_fields(), "should have been tested during graph construction");
188 // TODO 8284443 Can we teach the register allocator to reserve a stack slot instead?
189 // mask[--cnt] = STACK_ONLY_mask does not work (test with -XX:+StressGCM)
190 int slot = C->fixed_slots() - 2;
191 if (C->needs_stack_repair()) {
192 slot -= 2; // Account for stack increment value
193 }
194 mask[--cnt].Clear();
195 mask[cnt].Insert(OptoReg::stack2reg(slot));
196 }
197 for (uint i = 0; i < cnt; i++) {
198 mask[i].Clear();
199
200 OptoReg::Name reg1 = OptoReg::as_OptoReg(vm_parm_regs[i].first());
201 if (OptoReg::is_valid(reg1)) {
202 mask[i].Insert(reg1);
203 }
204 OptoReg::Name reg2 = OptoReg::as_OptoReg(vm_parm_regs[i].second());
205 if (OptoReg::is_valid(reg2)) {
206 mask[i].Insert(reg2);
207 }
208 }
209
210 return mask;
211 }
212
213 //---------------------------match---------------------------------------------
214 void Matcher::match( ) {
215 if( MaxLabelRootDepth < 100 ) { // Too small?
216 assert(false, "invalid MaxLabelRootDepth, increase it to 100 minimum");
217 MaxLabelRootDepth = 100;
218 }
219 // One-time initialization of some register masks.
220 init_spill_mask( C->root()->in(1) );
221 if (C->failing()) {
222 return;
223 }
224 assert(_return_addr_mask.is_Empty(),
225 "return address mask must be empty initially");
226 _return_addr_mask.Insert(return_addr());
227 #ifdef _LP64
228 // Pointers take 2 slots in 64-bit land
229 _return_addr_mask.Insert(OptoReg::add(return_addr(),1));
230 #endif
231
232 // Map Java-signature return types into return register-value
233 // machine registers.
234 _return_values_mask = return_values_mask(C->tf());
235
236 // ---------------
237 // Frame Layout
238
239 // Need the method signature to determine the incoming argument types,
240 // because the types determine which registers the incoming arguments are
241 // in, and this affects the matched code.
242 const TypeTuple *domain = C->tf()->domain_cc();
243 uint argcnt = domain->cnt() - TypeFunc::Parms;
244 BasicType *sig_bt = NEW_RESOURCE_ARRAY( BasicType, argcnt );
245 VMRegPair *vm_parm_regs = NEW_RESOURCE_ARRAY( VMRegPair, argcnt );
246 _parm_regs = NEW_RESOURCE_ARRAY( OptoRegPair, argcnt );
247 _calling_convention_mask = NEW_RESOURCE_ARRAY( RegMask, argcnt );
248 uint i;
249 for( i = 0; i<argcnt; i++ ) {
250 sig_bt[i] = domain->field_at(i+TypeFunc::Parms)->basic_type();
251 new (_calling_convention_mask + i) RegMask(C->comp_arena());
252 }
253
254 // Pass array of ideal registers and length to USER code (from the AD file)
255 // that will convert this to an array of register numbers.
256 const StartNode *start = C->start();
257 start->calling_convention( sig_bt, vm_parm_regs, argcnt );
258 #ifdef ASSERT
259 // Sanity check users' calling convention. Real handy while trying to
260 // get the initial port correct.
261 { for (uint i = 0; i<argcnt; i++) {
262 if( !vm_parm_regs[i].first()->is_valid() && !vm_parm_regs[i].second()->is_valid() ) {
263 assert(domain->field_at(i+TypeFunc::Parms)==Type::HALF, "only allowed on halve" );
264 _parm_regs[i].set_bad();
265 continue;
266 }
267 VMReg parm_reg = vm_parm_regs[i].first();
268 assert(parm_reg->is_valid(), "invalid arg?");
269 if (parm_reg->is_reg()) {
270 OptoReg::Name opto_parm_reg = OptoReg::as_OptoReg(parm_reg);
271 assert(can_be_java_arg(opto_parm_reg) ||
272 C->stub_function() == CAST_FROM_FN_PTR(address, OptoRuntime::rethrow_C) ||
273 opto_parm_reg == inline_cache_reg(),
274 "parameters in register must be preserved by runtime stubs");
275 }
276 for (uint j = 0; j < i; j++) {
277 assert(parm_reg != vm_parm_regs[j].first(),
278 "calling conv. must produce distinct regs");
279 }
280 }
281 }
282 #endif
283
284 // Do some initial frame layout.
285
286 // Compute the old incoming SP (may be called FP) as
287 // OptoReg::stack0() + locks + in_preserve_stack_slots + pad2.
288 _old_SP = C->compute_old_SP();
289 assert( is_even(_old_SP), "must be even" );
290
291 // Compute highest incoming stack argument as
292 // _old_SP + out_preserve_stack_slots + incoming argument size.
293 _in_arg_limit = OptoReg::add(_old_SP, C->out_preserve_stack_slots());
294 assert( is_even(_in_arg_limit), "out_preserve must be even" );
295 for( i = 0; i < argcnt; i++ ) {
296 // Permit args to have no register
297 _calling_convention_mask[i].Clear();
298 if( !vm_parm_regs[i].first()->is_valid() && !vm_parm_regs[i].second()->is_valid() ) {
299 _parm_regs[i].set_bad();
300 continue;
301 }
302 // calling_convention returns stack arguments as a count of
303 // slots beyond OptoReg::stack0()/VMRegImpl::stack0. We need to convert this to
304 // the allocators point of view, taking into account all the
305 // preserve area, locks & pad2.
306
307 OptoReg::Name reg1 = warp_incoming_stk_arg(vm_parm_regs[i].first());
308 if( OptoReg::is_valid(reg1))
309 _calling_convention_mask[i].Insert(reg1);
310
311 OptoReg::Name reg2 = warp_incoming_stk_arg(vm_parm_regs[i].second());
312 if( OptoReg::is_valid(reg2))
313 _calling_convention_mask[i].Insert(reg2);
314
315 // Saved biased stack-slot register number
316 _parm_regs[i].set_pair(reg2, reg1);
317 }
318
319 // Finally, make sure the incoming arguments take up an even number of
320 // words, in case the arguments or locals need to contain doubleword stack
321 // slots. The rest of the system assumes that stack slot pairs (in
322 // particular, in the spill area) which look aligned will in fact be
323 // aligned relative to the stack pointer in the target machine. Double
324 // stack slots will always be allocated aligned.
325 _new_SP = OptoReg::Name(align_up(_in_arg_limit, (int)RegMask::SlotsPerLong));
326
327 // Compute highest outgoing stack argument as
328 // _new_SP + out_preserve_stack_slots + max(outgoing argument size).
329 _out_arg_limit = OptoReg::add(_new_SP, C->out_preserve_stack_slots());
330 assert( is_even(_out_arg_limit), "out_preserve must be even" );
331
332 // ---------------
333 // Collect roots of matcher trees. Every node for which
334 // _shared[_idx] is cleared is guaranteed to not be shared, and thus
335 // can be a valid interior of some tree.
336 find_shared( C->root() );
337 find_shared( C->top() );
338
339 C->print_method(PHASE_BEFORE_MATCHING, 1);
340
341 // Create new ideal node ConP #null even if it does exist in old space
342 // to avoid false sharing if the corresponding mach node is not used.
343 // The corresponding mach node is only used in rare cases for derived
344 // pointers.
345 Node* new_ideal_null = ConNode::make(TypePtr::NULL_PTR);
346
347 // Swap out to old-space; emptying new-space
348 Arena* old = C->swap_old_and_new();
349
350 // Save debug and profile information for nodes in old space:
351 _old_node_note_array = C->node_note_array();
352 if (_old_node_note_array != nullptr) {
353 C->set_node_note_array(new(C->comp_arena()) GrowableArray<Node_Notes*>
354 (C->comp_arena(), _old_node_note_array->length(),
355 0, nullptr));
356 }
357
358 // Pre-size the new_node table to avoid the need for range checks.
359 grow_new_node_array(C->unique());
360
361 // Reset node counter so MachNodes start with _idx at 0
362 int live_nodes = C->live_nodes();
363 C->set_unique(0);
364 C->reset_dead_node_list();
365
366 // Recursively match trees from old space into new space.
367 // Correct leaves of new-space Nodes; they point to old-space.
368 _visited.clear();
369 Node* const n = xform(C->top(), live_nodes);
370 if (C->failing()) return;
371 C->set_cached_top_node(n);
372 if (!C->failing()) {
373 Node* xroot = xform( C->root(), 1 );
374 if (C->failing()) return;
375 if (xroot == nullptr) {
376 Matcher::soft_match_failure(); // recursive matching process failed
377 assert(false, "instruction match failed");
378 C->record_method_not_compilable("instruction match failed");
379 } else {
380 // During matching shared constants were attached to C->root()
381 // because xroot wasn't available yet, so transfer the uses to
382 // the xroot.
383 for( DUIterator_Fast jmax, j = C->root()->fast_outs(jmax); j < jmax; j++ ) {
384 Node* n = C->root()->fast_out(j);
385 if (C->node_arena()->contains(n)) {
386 assert(n->in(0) == C->root(), "should be control user");
387 n->set_req(0, xroot);
388 --j;
389 --jmax;
390 }
391 }
392
393 // Generate new mach node for ConP #null
394 assert(new_ideal_null != nullptr, "sanity");
395 _mach_null = match_tree(new_ideal_null);
396 // Don't set control, it will confuse GCM since there are no uses.
397 // The control will be set when this node is used first time
398 // in find_base_for_derived().
399 assert(_mach_null != nullptr || C->failure_is_artificial(), ""); // bailouts are handled below.
400
401 C->set_root(xroot->is_Root() ? xroot->as_Root() : nullptr);
402
403 #ifdef ASSERT
404 verify_new_nodes_only(xroot);
405 #endif
406 }
407 }
408 if (C->top() == nullptr || C->root() == nullptr) {
409 // New graph lost. This is due to a compilation failure we encountered earlier.
410 stringStream ss;
411 if (C->failure_reason() != nullptr) {
412 ss.print("graph lost: %s", C->failure_reason());
413 } else {
414 assert(C->failure_reason() != nullptr, "graph lost: reason unknown");
415 ss.print("graph lost: reason unknown");
416 }
417 C->record_method_not_compilable(ss.as_string() DEBUG_ONLY(COMMA true));
418 }
419 if (C->failing()) {
420 // delete old;
421 old->destruct_contents();
422 return;
423 }
424 assert( C->top(), "" );
425 assert( C->root(), "" );
426 validate_null_checks();
427
428 // Now smoke old-space
429 NOT_DEBUG( old->destruct_contents() );
430
431 // ------------------------
432 // Set up save-on-entry registers.
433 Fixup_Save_On_Entry( );
434
435 { // Cleanup mach IR after selection phase is over.
436 Compile::TracePhase tp(_t_postselect_cleanup);
437 do_postselect_cleanup();
438 if (C->failing()) return;
439 assert(verify_after_postselect_cleanup(), "");
440 }
441 }
442
443 //------------------------------Fixup_Save_On_Entry----------------------------
444 // The stated purpose of this routine is to take care of save-on-entry
445 // registers. However, the overall goal of the Match phase is to convert into
446 // machine-specific instructions which have RegMasks to guide allocation.
447 // So what this procedure really does is put a valid RegMask on each input
448 // to the machine-specific variations of all Return, TailCall and Halt
449 // instructions. It also adds edgs to define the save-on-entry values (and of
450 // course gives them a mask).
451
452 static RegMask *init_input_masks( uint size, RegMask &ret_adr, RegMask &fp ) {
453 RegMask *rms = NEW_RESOURCE_ARRAY( RegMask, size );
454 for (unsigned int i = 0; i < size; ++i) {
455 new (rms + i) RegMask(Compile::current()->comp_arena());
456 }
457 // Do all the pre-defined register masks
458 rms[TypeFunc::Control ] = RegMask::Empty;
459 rms[TypeFunc::I_O ] = RegMask::Empty;
460 rms[TypeFunc::Memory ] = RegMask::Empty;
461 rms[TypeFunc::ReturnAdr] = ret_adr;
462 rms[TypeFunc::FramePtr ] = fp;
463 return rms;
464 }
465
466 int Matcher::scalable_predicate_reg_slots() {
467 assert(Matcher::has_predicated_vectors() && Matcher::supports_scalable_vector(),
468 "scalable predicate vector should be supported");
469 int vector_reg_bit_size = Matcher::scalable_vector_reg_size(T_BYTE) << LogBitsPerByte;
470 // We assume each predicate register is one-eighth of the size of
471 // scalable vector register, one mask bit per vector byte.
472 int predicate_reg_bit_size = vector_reg_bit_size >> 3;
473 // Compute number of slots which is required when scalable predicate
474 // register is spilled. E.g. if scalable vector register is 640 bits,
475 // predicate register is 80 bits, which is 2.5 * slots.
476 // We will round up the slot number to power of 2, which is required
477 // by find_first_set().
478 int slots = predicate_reg_bit_size & (BitsPerInt - 1)
479 ? (predicate_reg_bit_size >> LogBitsPerInt) + 1
480 : predicate_reg_bit_size >> LogBitsPerInt;
481 return round_up_power_of_2(slots);
482 }
483
484 #define NOF_STACK_MASKS (2*13)
485
486 // Create the initial stack mask used by values spilling to the stack.
487 // Disallow any debug info in outgoing argument areas by setting the
488 // initial mask accordingly.
489 void Matcher::init_first_stack_mask() {
490
491 // Allocate storage for spill masks as masks for the appropriate load type.
492 RegMask *rms = (RegMask*)C->comp_arena()->AmallocWords(sizeof(RegMask) * NOF_STACK_MASKS);
493
494 // Initialize empty placeholder masks into the newly allocated arena
495 for (int i = 0; i < NOF_STACK_MASKS; i++) {
496 new (rms + i) RegMask(C->comp_arena());
497 }
498
499 int index = 0;
500 for (int i = Op_RegN; i <= Op_RegVectMask; ++i) {
501 idealreg2spillmask[i] = &rms[index++];
502 idealreg2debugmask[i] = &rms[index++];
503 }
504 assert(index == NOF_STACK_MASKS, "wrong size");
505
506 // At first, start with the empty mask
507 C->FIRST_STACK_mask().Clear();
508
509 // Add in the incoming argument area
510 OptoReg::Name init_in = OptoReg::add(_old_SP, C->out_preserve_stack_slots());
511 for (OptoReg::Name i = init_in; i < _in_arg_limit; i = OptoReg::add(i, 1)) {
512 C->FIRST_STACK_mask().Insert(i);
513 }
514
515 // Add in all bits past the outgoing argument area
516 C->FIRST_STACK_mask().Set_All_From(_out_arg_limit);
517
518 // Make spill masks. Registers for their class, plus FIRST_STACK_mask.
519 RegMask aligned_stack_mask(C->FIRST_STACK_mask(), C->comp_arena());
520 // Keep spill masks aligned.
521 aligned_stack_mask.clear_to_pairs();
522 assert(aligned_stack_mask.is_infinite_stack(), "should be infinite stack");
523 RegMask scalable_stack_mask(aligned_stack_mask, C->comp_arena());
524
525 *idealreg2spillmask[Op_RegP] = *idealreg2regmask[Op_RegP];
526 #ifdef _LP64
527 *idealreg2spillmask[Op_RegN] = *idealreg2regmask[Op_RegN];
528 idealreg2spillmask[Op_RegN]->OR(C->FIRST_STACK_mask());
529 idealreg2spillmask[Op_RegP]->OR(aligned_stack_mask);
530 #else
531 idealreg2spillmask[Op_RegP]->OR(C->FIRST_STACK_mask());
532 #endif
533 *idealreg2spillmask[Op_RegI] = *idealreg2regmask[Op_RegI];
534 idealreg2spillmask[Op_RegI]->OR(C->FIRST_STACK_mask());
535 *idealreg2spillmask[Op_RegL] = *idealreg2regmask[Op_RegL];
536 idealreg2spillmask[Op_RegL]->OR(aligned_stack_mask);
537 *idealreg2spillmask[Op_RegF] = *idealreg2regmask[Op_RegF];
538 idealreg2spillmask[Op_RegF]->OR(C->FIRST_STACK_mask());
539 *idealreg2spillmask[Op_RegD] = *idealreg2regmask[Op_RegD];
540 idealreg2spillmask[Op_RegD]->OR(aligned_stack_mask);
541
542 if (Matcher::has_predicated_vectors()) {
543 *idealreg2spillmask[Op_RegVectMask] = *idealreg2regmask[Op_RegVectMask];
544 idealreg2spillmask[Op_RegVectMask]->OR(aligned_stack_mask);
545 } else {
546 *idealreg2spillmask[Op_RegVectMask] = RegMask::Empty;
547 }
548
549 if (Matcher::vector_size_supported(T_BYTE,4)) {
550 *idealreg2spillmask[Op_VecS] = *idealreg2regmask[Op_VecS];
551 idealreg2spillmask[Op_VecS]->OR(C->FIRST_STACK_mask());
552 } else {
553 *idealreg2spillmask[Op_VecS] = RegMask::Empty;
554 }
555
556 if (Matcher::vector_size_supported(T_FLOAT,2)) {
557 // For VecD we need dual alignment and 8 bytes (2 slots) for spills.
558 // RA guarantees such alignment since it is needed for Double and Long values.
559 *idealreg2spillmask[Op_VecD] = *idealreg2regmask[Op_VecD];
560 idealreg2spillmask[Op_VecD]->OR(aligned_stack_mask);
561 } else {
562 *idealreg2spillmask[Op_VecD] = RegMask::Empty;
563 }
564
565 if (Matcher::vector_size_supported(T_FLOAT,4)) {
566 // For VecX we need quadro alignment and 16 bytes (4 slots) for spills.
567 //
568 // RA can use input arguments stack slots for spills but until RA
569 // we don't know frame size and offset of input arg stack slots.
570 //
571 // Exclude last input arg stack slots to avoid spilling vectors there
572 // otherwise vector spills could stomp over stack slots in caller frame.
573 OptoReg::Name in = OptoReg::add(_in_arg_limit, -1);
574 for (int k = 1; (in >= init_in) && (k < RegMask::SlotsPerVecX); k++) {
575 aligned_stack_mask.Remove(in);
576 in = OptoReg::add(in, -1);
577 }
578 aligned_stack_mask.clear_to_sets(RegMask::SlotsPerVecX);
579 assert(aligned_stack_mask.is_infinite_stack(), "should be infinite stack");
580 *idealreg2spillmask[Op_VecX] = *idealreg2regmask[Op_VecX];
581 idealreg2spillmask[Op_VecX]->OR(aligned_stack_mask);
582 } else {
583 *idealreg2spillmask[Op_VecX] = RegMask::Empty;
584 }
585
586 if (Matcher::vector_size_supported(T_FLOAT,8)) {
587 // For VecY we need octo alignment and 32 bytes (8 slots) for spills.
588 OptoReg::Name in = OptoReg::add(_in_arg_limit, -1);
589 for (int k = 1; (in >= init_in) && (k < RegMask::SlotsPerVecY); k++) {
590 aligned_stack_mask.Remove(in);
591 in = OptoReg::add(in, -1);
592 }
593 aligned_stack_mask.clear_to_sets(RegMask::SlotsPerVecY);
594 assert(aligned_stack_mask.is_infinite_stack(), "should be infinite stack");
595 *idealreg2spillmask[Op_VecY] = *idealreg2regmask[Op_VecY];
596 idealreg2spillmask[Op_VecY]->OR(aligned_stack_mask);
597 } else {
598 *idealreg2spillmask[Op_VecY] = RegMask::Empty;
599 }
600
601 if (Matcher::vector_size_supported(T_FLOAT,16)) {
602 // For VecZ we need enough alignment and 64 bytes (16 slots) for spills.
603 OptoReg::Name in = OptoReg::add(_in_arg_limit, -1);
604 for (int k = 1; (in >= init_in) && (k < RegMask::SlotsPerVecZ); k++) {
605 aligned_stack_mask.Remove(in);
606 in = OptoReg::add(in, -1);
607 }
608 aligned_stack_mask.clear_to_sets(RegMask::SlotsPerVecZ);
609 assert(aligned_stack_mask.is_infinite_stack(), "should be infinite stack");
610 *idealreg2spillmask[Op_VecZ] = *idealreg2regmask[Op_VecZ];
611 idealreg2spillmask[Op_VecZ]->OR(aligned_stack_mask);
612 } else {
613 *idealreg2spillmask[Op_VecZ] = RegMask::Empty;
614 }
615
616 if (Matcher::supports_scalable_vector()) {
617 int k = 1;
618 OptoReg::Name in = OptoReg::add(_in_arg_limit, -1);
619 if (Matcher::has_predicated_vectors()) {
620 // Exclude last input arg stack slots to avoid spilling vector register there,
621 // otherwise RegVectMask spills could stomp over stack slots in caller frame.
622 for (; (in >= init_in) && (k < scalable_predicate_reg_slots()); k++) {
623 scalable_stack_mask.Remove(in);
624 in = OptoReg::add(in, -1);
625 }
626
627 // For RegVectMask
628 scalable_stack_mask.clear_to_sets(scalable_predicate_reg_slots());
629 assert(scalable_stack_mask.is_infinite_stack(), "should be infinite stack");
630 *idealreg2spillmask[Op_RegVectMask] = *idealreg2regmask[Op_RegVectMask];
631 idealreg2spillmask[Op_RegVectMask]->OR(scalable_stack_mask);
632 }
633
634 // Exclude last input arg stack slots to avoid spilling vector register there,
635 // otherwise vector spills could stomp over stack slots in caller frame.
636 for (; (in >= init_in) && (k < scalable_vector_reg_size(T_FLOAT)); k++) {
637 scalable_stack_mask.Remove(in);
638 in = OptoReg::add(in, -1);
639 }
640
641 // For VecA
642 scalable_stack_mask.clear_to_sets(RegMask::SlotsPerVecA);
643 assert(scalable_stack_mask.is_infinite_stack(), "should be infinite stack");
644 *idealreg2spillmask[Op_VecA] = *idealreg2regmask[Op_VecA];
645 idealreg2spillmask[Op_VecA]->OR(scalable_stack_mask);
646 } else {
647 *idealreg2spillmask[Op_VecA] = RegMask::Empty;
648 }
649
650 if (UseFPUForSpilling) {
651 // This mask logic assumes that the spill operations are
652 // symmetric and that the registers involved are the same size.
653 // On sparc for instance we may have to use 64 bit moves will
654 // kill 2 registers when used with F0-F31.
655 idealreg2spillmask[Op_RegI]->OR(*idealreg2regmask[Op_RegF]);
656 idealreg2spillmask[Op_RegF]->OR(*idealreg2regmask[Op_RegI]);
657 #ifdef _LP64
658 idealreg2spillmask[Op_RegN]->OR(*idealreg2regmask[Op_RegF]);
659 idealreg2spillmask[Op_RegL]->OR(*idealreg2regmask[Op_RegD]);
660 idealreg2spillmask[Op_RegD]->OR(*idealreg2regmask[Op_RegL]);
661 idealreg2spillmask[Op_RegP]->OR(*idealreg2regmask[Op_RegD]);
662 #else
663 idealreg2spillmask[Op_RegP]->OR(*idealreg2regmask[Op_RegF]);
664 #ifdef ARM
665 // ARM has support for moving 64bit values between a pair of
666 // integer registers and a double register
667 idealreg2spillmask[Op_RegL]->OR(*idealreg2regmask[Op_RegD]);
668 idealreg2spillmask[Op_RegD]->OR(*idealreg2regmask[Op_RegL]);
669 #endif
670 #endif
671 }
672
673 // Make up debug masks. Any spill slot plus callee-save (SOE) registers.
674 // Caller-save (SOC, AS) registers are assumed to be trashable by the various
675 // inline-cache fixup routines.
676 *idealreg2debugmask [Op_RegN] = *idealreg2spillmask[Op_RegN];
677 *idealreg2debugmask [Op_RegI] = *idealreg2spillmask[Op_RegI];
678 *idealreg2debugmask [Op_RegL] = *idealreg2spillmask[Op_RegL];
679 *idealreg2debugmask [Op_RegF] = *idealreg2spillmask[Op_RegF];
680 *idealreg2debugmask [Op_RegD] = *idealreg2spillmask[Op_RegD];
681 *idealreg2debugmask [Op_RegP] = *idealreg2spillmask[Op_RegP];
682 *idealreg2debugmask [Op_RegVectMask] = *idealreg2spillmask[Op_RegVectMask];
683
684 *idealreg2debugmask [Op_VecA] = *idealreg2spillmask[Op_VecA];
685 *idealreg2debugmask [Op_VecS] = *idealreg2spillmask[Op_VecS];
686 *idealreg2debugmask [Op_VecD] = *idealreg2spillmask[Op_VecD];
687 *idealreg2debugmask [Op_VecX] = *idealreg2spillmask[Op_VecX];
688 *idealreg2debugmask [Op_VecY] = *idealreg2spillmask[Op_VecY];
689 *idealreg2debugmask [Op_VecZ] = *idealreg2spillmask[Op_VecZ];
690
691 // Prevent stub compilations from attempting to reference
692 // callee-saved (SOE) registers from debug info
693 bool exclude_soe = !Compile::current()->is_method_compilation();
694 RegMask* caller_save_mask = exclude_soe ? &caller_save_regmask_exclude_soe : &caller_save_regmask;
695
696 idealreg2debugmask[Op_RegN]->SUBTRACT(*caller_save_mask);
697 idealreg2debugmask[Op_RegI]->SUBTRACT(*caller_save_mask);
698 idealreg2debugmask[Op_RegL]->SUBTRACT(*caller_save_mask);
699 idealreg2debugmask[Op_RegF]->SUBTRACT(*caller_save_mask);
700 idealreg2debugmask[Op_RegD]->SUBTRACT(*caller_save_mask);
701 idealreg2debugmask[Op_RegP]->SUBTRACT(*caller_save_mask);
702 idealreg2debugmask[Op_RegVectMask]->SUBTRACT(*caller_save_mask);
703
704 idealreg2debugmask[Op_VecA]->SUBTRACT(*caller_save_mask);
705 idealreg2debugmask[Op_VecS]->SUBTRACT(*caller_save_mask);
706 idealreg2debugmask[Op_VecD]->SUBTRACT(*caller_save_mask);
707 idealreg2debugmask[Op_VecX]->SUBTRACT(*caller_save_mask);
708 idealreg2debugmask[Op_VecY]->SUBTRACT(*caller_save_mask);
709 idealreg2debugmask[Op_VecZ]->SUBTRACT(*caller_save_mask);
710 }
711
712 //---------------------------is_save_on_entry----------------------------------
713 bool Matcher::is_save_on_entry(int reg) {
714 return
715 _register_save_policy[reg] == 'E' ||
716 _register_save_policy[reg] == 'A'; // Save-on-entry register?
717 }
718
719 //---------------------------Fixup_Save_On_Entry-------------------------------
720 void Matcher::Fixup_Save_On_Entry( ) {
721 init_first_stack_mask();
722
723 Node *root = C->root(); // Short name for root
724 // Count number of save-on-entry registers.
725 uint soe_cnt = number_of_saved_registers();
726 uint i;
727
728 // Find the procedure Start Node
729 StartNode *start = C->start();
730 assert( start, "Expect a start node" );
731
732 // Input RegMask array shared by all Returns.
733 // The type for doubles and longs has a count of 2, but
734 // there is only 1 returned value
735 uint ret_edge_cnt = C->tf()->range_cc()->cnt();
736 RegMask *ret_rms = init_input_masks( ret_edge_cnt + soe_cnt, _return_addr_mask, c_frame_ptr_mask );
737 for (i = TypeFunc::Parms; i < ret_edge_cnt; i++) {
738 ret_rms[i] = _return_values_mask[i-TypeFunc::Parms];
739 }
740
741 // Input RegMask array shared by all ForwardExceptions
742 uint forw_exc_edge_cnt = TypeFunc::Parms;
743 RegMask* forw_exc_rms = init_input_masks( forw_exc_edge_cnt + soe_cnt, _return_addr_mask, c_frame_ptr_mask );
744
745 // Input RegMask array shared by all Rethrows.
746 uint reth_edge_cnt = TypeFunc::Parms+1;
747 RegMask *reth_rms = init_input_masks( reth_edge_cnt + soe_cnt, _return_addr_mask, c_frame_ptr_mask );
748 // Rethrow takes exception oop only, but in the argument 0 slot.
749 OptoReg::Name reg = find_receiver();
750 if (reg >= 0) {
751 reth_rms[TypeFunc::Parms] = mreg2regmask[reg];
752 #ifdef _LP64
753 // Need two slots for ptrs in 64-bit land
754 reth_rms[TypeFunc::Parms].Insert(OptoReg::add(OptoReg::Name(reg), 1));
755 #endif
756 }
757
758 // Input RegMask array shared by all TailCalls
759 uint tail_call_edge_cnt = TypeFunc::Parms+2;
760 RegMask *tail_call_rms = init_input_masks( tail_call_edge_cnt + soe_cnt, _return_addr_mask, c_frame_ptr_mask );
761
762 // Input RegMask array shared by all TailJumps
763 uint tail_jump_edge_cnt = TypeFunc::Parms+2;
764 RegMask *tail_jump_rms = init_input_masks( tail_jump_edge_cnt + soe_cnt, _return_addr_mask, c_frame_ptr_mask );
765
766 // TailCalls have 2 returned values (target & moop), whose masks come
767 // from the usual MachNode/MachOper mechanism. Find a sample
768 // TailCall to extract these masks and put the correct masks into
769 // the tail_call_rms array.
770 for( i=1; i < root->req(); i++ ) {
771 MachReturnNode *m = root->in(i)->as_MachReturn();
772 if( m->ideal_Opcode() == Op_TailCall ) {
773 tail_call_rms[TypeFunc::Parms+0] = m->MachNode::in_RegMask(TypeFunc::Parms+0);
774 tail_call_rms[TypeFunc::Parms+1] = m->MachNode::in_RegMask(TypeFunc::Parms+1);
775 break;
776 }
777 }
778
779 // TailJumps have 2 returned values (target & ex_oop), whose masks come
780 // from the usual MachNode/MachOper mechanism. Find a sample
781 // TailJump to extract these masks and put the correct masks into
782 // the tail_jump_rms array.
783 for( i=1; i < root->req(); i++ ) {
784 MachReturnNode *m = root->in(i)->as_MachReturn();
785 if( m->ideal_Opcode() == Op_TailJump ) {
786 tail_jump_rms[TypeFunc::Parms+0] = m->MachNode::in_RegMask(TypeFunc::Parms+0);
787 tail_jump_rms[TypeFunc::Parms+1] = m->MachNode::in_RegMask(TypeFunc::Parms+1);
788 break;
789 }
790 }
791
792 // Input RegMask array shared by all Halts
793 uint halt_edge_cnt = TypeFunc::Parms;
794 RegMask *halt_rms = init_input_masks( halt_edge_cnt + soe_cnt, _return_addr_mask, c_frame_ptr_mask );
795
796 // Capture the return input masks into each exit flavor
797 for( i=1; i < root->req(); i++ ) {
798 MachReturnNode *exit = root->in(i)->as_MachReturn();
799 switch( exit->ideal_Opcode() ) {
800 case Op_Return : exit->_in_rms = ret_rms; break;
801 case Op_Rethrow : exit->_in_rms = reth_rms; break;
802 case Op_TailCall : exit->_in_rms = tail_call_rms; break;
803 case Op_TailJump : exit->_in_rms = tail_jump_rms; break;
804 case Op_ForwardException: exit->_in_rms = forw_exc_rms; break;
805 case Op_Halt : exit->_in_rms = halt_rms; break;
806 default : ShouldNotReachHere();
807 }
808 }
809
810 // Next unused projection number from Start.
811 int proj_cnt = C->tf()->domain_cc()->cnt();
812
813 // Do all the save-on-entry registers. Make projections from Start for
814 // them, and give them a use at the exit points. To the allocator, they
815 // look like incoming register arguments.
816 for( i = 0; i < _last_Mach_Reg; i++ ) {
817 if( is_save_on_entry(i) ) {
818
819 // Add the save-on-entry to the mask array
820 ret_rms [ ret_edge_cnt] = mreg2regmask[i];
821 reth_rms [ reth_edge_cnt] = mreg2regmask[i];
822 tail_call_rms[tail_call_edge_cnt] = mreg2regmask[i];
823 tail_jump_rms[tail_jump_edge_cnt] = mreg2regmask[i];
824 forw_exc_rms [ forw_exc_edge_cnt] = mreg2regmask[i];
825 // Halts need the SOE registers, but only in the stack as debug info.
826 // A just-prior uncommon-trap or deoptimization will use the SOE regs.
827 halt_rms [ halt_edge_cnt] = *idealreg2spillmask[_register_save_type[i]];
828
829 Node *mproj;
830
831 // Is this a RegF low half of a RegD? Double up 2 adjacent RegF's
832 // into a single RegD.
833 if( (i&1) == 0 &&
834 _register_save_type[i ] == Op_RegF &&
835 _register_save_type[i+1] == Op_RegF &&
836 is_save_on_entry(i+1) ) {
837 // Add other bit for double
838 ret_rms [ ret_edge_cnt].Insert(OptoReg::Name(i+1));
839 reth_rms [ reth_edge_cnt].Insert(OptoReg::Name(i+1));
840 tail_call_rms[tail_call_edge_cnt].Insert(OptoReg::Name(i+1));
841 tail_jump_rms[tail_jump_edge_cnt].Insert(OptoReg::Name(i+1));
842 forw_exc_rms [ forw_exc_edge_cnt].Insert(OptoReg::Name(i+1));
843 halt_rms [ halt_edge_cnt].Insert(OptoReg::Name(i+1));
844 mproj = new MachProjNode( start, proj_cnt, ret_rms[ret_edge_cnt], Op_RegD );
845 proj_cnt += 2; // Skip 2 for doubles
846 }
847 else if( (i&1) == 1 && // Else check for high half of double
848 _register_save_type[i-1] == Op_RegF &&
849 _register_save_type[i ] == Op_RegF &&
850 is_save_on_entry(i-1) ) {
851 ret_rms [ ret_edge_cnt] = RegMask::Empty;
852 reth_rms [ reth_edge_cnt] = RegMask::Empty;
853 tail_call_rms[tail_call_edge_cnt] = RegMask::Empty;
854 tail_jump_rms[tail_jump_edge_cnt] = RegMask::Empty;
855 forw_exc_rms [ forw_exc_edge_cnt] = RegMask::Empty;
856 halt_rms [ halt_edge_cnt] = RegMask::Empty;
857 mproj = C->top();
858 }
859 // Is this a RegI low half of a RegL? Double up 2 adjacent RegI's
860 // into a single RegL.
861 else if( (i&1) == 0 &&
862 _register_save_type[i ] == Op_RegI &&
863 _register_save_type[i+1] == Op_RegI &&
864 is_save_on_entry(i+1) ) {
865 // Add other bit for long
866 ret_rms [ ret_edge_cnt].Insert(OptoReg::Name(i+1));
867 reth_rms [ reth_edge_cnt].Insert(OptoReg::Name(i+1));
868 tail_call_rms[tail_call_edge_cnt].Insert(OptoReg::Name(i+1));
869 tail_jump_rms[tail_jump_edge_cnt].Insert(OptoReg::Name(i+1));
870 forw_exc_rms [ forw_exc_edge_cnt].Insert(OptoReg::Name(i+1));
871 halt_rms [ halt_edge_cnt].Insert(OptoReg::Name(i+1));
872 mproj = new MachProjNode( start, proj_cnt, ret_rms[ret_edge_cnt], Op_RegL );
873 proj_cnt += 2; // Skip 2 for longs
874 }
875 else if( (i&1) == 1 && // Else check for high half of long
876 _register_save_type[i-1] == Op_RegI &&
877 _register_save_type[i ] == Op_RegI &&
878 is_save_on_entry(i-1) ) {
879 ret_rms [ ret_edge_cnt] = RegMask::Empty;
880 reth_rms [ reth_edge_cnt] = RegMask::Empty;
881 tail_call_rms[tail_call_edge_cnt] = RegMask::Empty;
882 tail_jump_rms[tail_jump_edge_cnt] = RegMask::Empty;
883 forw_exc_rms [ forw_exc_edge_cnt] = RegMask::Empty;
884 halt_rms [ halt_edge_cnt] = RegMask::Empty;
885 mproj = C->top();
886 } else {
887 // Make a projection for it off the Start
888 mproj = new MachProjNode( start, proj_cnt++, ret_rms[ret_edge_cnt], _register_save_type[i] );
889 }
890
891 ret_edge_cnt ++;
892 reth_edge_cnt ++;
893 tail_call_edge_cnt ++;
894 tail_jump_edge_cnt ++;
895 forw_exc_edge_cnt++;
896 halt_edge_cnt ++;
897
898 // Add a use of the SOE register to all exit paths
899 for (uint j=1; j < root->req(); j++) {
900 root->in(j)->add_req(mproj);
901 }
902 } // End of if a save-on-entry register
903 } // End of for all machine registers
904 }
905
906 //------------------------------init_spill_mask--------------------------------
907 void Matcher::init_spill_mask( Node *ret ) {
908 if( idealreg2regmask[Op_RegI] ) return; // One time only init
909
910 OptoReg::c_frame_pointer = c_frame_pointer();
911 c_frame_ptr_mask = RegMask(c_frame_pointer());
912 #ifdef _LP64
913 // pointers are twice as big
914 c_frame_ptr_mask.Insert(OptoReg::add(c_frame_pointer(),1));
915 #endif
916
917 // Start at OptoReg::stack0()
918 STACK_ONLY_mask.Clear();
919 // STACK_ONLY_mask is all stack bits
920 STACK_ONLY_mask.Set_All_From(OptoReg::stack2reg(0));
921
922 for (OptoReg::Name i = OptoReg::Name(0); i < OptoReg::Name(_last_Mach_Reg);
923 i = OptoReg::add(i, 1)) {
924 // Copy the register names over into the shared world.
925 // SharedInfo::regName[i] = regName[i];
926 // Handy RegMasks per machine register
927 mreg2regmask[i].Insert(i);
928
929 // Set up regmasks used to exclude save-on-call (and always-save) registers from debug masks.
930 if (_register_save_policy[i] == 'C' ||
931 _register_save_policy[i] == 'A') {
932 caller_save_regmask.Insert(i);
933 }
934 // Exclude save-on-entry registers from debug masks for stub compilations.
935 if (_register_save_policy[i] == 'C' ||
936 _register_save_policy[i] == 'A' ||
937 _register_save_policy[i] == 'E') {
938 caller_save_regmask_exclude_soe.Insert(i);
939 }
940 }
941
942 // Grab the Frame Pointer
943 Node *fp = ret->in(TypeFunc::FramePtr);
944 // Share frame pointer while making spill ops
945 set_shared(fp);
946
947 // Get the ADLC notion of the right regmask, for each basic type.
948 #ifdef _LP64
949 idealreg2regmask[Op_RegN] = regmask_for_ideal_register(Op_RegN, ret);
950 #endif
951 idealreg2regmask[Op_RegI] = regmask_for_ideal_register(Op_RegI, ret);
952 idealreg2regmask[Op_RegP] = regmask_for_ideal_register(Op_RegP, ret);
953 idealreg2regmask[Op_RegF] = regmask_for_ideal_register(Op_RegF, ret);
954 idealreg2regmask[Op_RegD] = regmask_for_ideal_register(Op_RegD, ret);
955 idealreg2regmask[Op_RegL] = regmask_for_ideal_register(Op_RegL, ret);
956 idealreg2regmask[Op_VecA] = regmask_for_ideal_register(Op_VecA, ret);
957 idealreg2regmask[Op_VecS] = regmask_for_ideal_register(Op_VecS, ret);
958 idealreg2regmask[Op_VecD] = regmask_for_ideal_register(Op_VecD, ret);
959 idealreg2regmask[Op_VecX] = regmask_for_ideal_register(Op_VecX, ret);
960 idealreg2regmask[Op_VecY] = regmask_for_ideal_register(Op_VecY, ret);
961 idealreg2regmask[Op_VecZ] = regmask_for_ideal_register(Op_VecZ, ret);
962 idealreg2regmask[Op_RegVectMask] = regmask_for_ideal_register(Op_RegVectMask, ret);
963 }
964
965 #ifdef ASSERT
966 static void match_alias_type(Compile* C, Node* n, Node* m) {
967 if (!VerifyAliases) return; // do not go looking for trouble by default
968 const TypePtr* nat = n->adr_type();
969 const TypePtr* mat = m->adr_type();
970 int nidx = C->get_alias_index(nat);
971 int midx = C->get_alias_index(mat);
972 // Detune the assert for cases like (AndI 0xFF (LoadB p)).
973 if (nidx == Compile::AliasIdxTop && midx >= Compile::AliasIdxRaw) {
974 for (uint i = 1; i < n->req(); i++) {
975 Node* n1 = n->in(i);
976 const TypePtr* n1at = n1->adr_type();
977 if (n1at != nullptr) {
978 nat = n1at;
979 nidx = C->get_alias_index(n1at);
980 }
981 }
982 }
983 // %%% Kludgery. Instead, fix ideal adr_type methods for all these cases:
984 if (nidx == Compile::AliasIdxTop && midx == Compile::AliasIdxRaw) {
985 switch (n->Opcode()) {
986 case Op_PrefetchAllocation:
987 nidx = Compile::AliasIdxRaw;
988 nat = TypeRawPtr::BOTTOM;
989 break;
990 }
991 }
992 if (nidx == Compile::AliasIdxRaw && midx == Compile::AliasIdxTop) {
993 switch (n->Opcode()) {
994 case Op_ClearArray:
995 midx = Compile::AliasIdxRaw;
996 mat = TypeRawPtr::BOTTOM;
997 break;
998 }
999 }
1000 if (nidx == Compile::AliasIdxTop && midx == Compile::AliasIdxBot) {
1001 switch (n->Opcode()) {
1002 case Op_Return:
1003 case Op_Rethrow:
1004 case Op_Halt:
1005 case Op_TailCall:
1006 case Op_TailJump:
1007 case Op_ForwardException:
1008 nidx = Compile::AliasIdxBot;
1009 nat = TypePtr::BOTTOM;
1010 break;
1011 }
1012 }
1013 if (nidx == Compile::AliasIdxBot && midx == Compile::AliasIdxTop) {
1014 switch (n->Opcode()) {
1015 case Op_StrComp:
1016 case Op_StrEquals:
1017 case Op_StrIndexOf:
1018 case Op_StrIndexOfChar:
1019 case Op_AryEq:
1020 case Op_VectorizedHashCode:
1021 case Op_CountPositives:
1022 case Op_MemBarVolatile:
1023 case Op_MemBarCPUOrder: // %%% these ideals should have narrower adr_type?
1024 case Op_StrInflatedCopy:
1025 case Op_StrCompressedCopy:
1026 case Op_OnSpinWait:
1027 case Op_EncodeISOArray:
1028 nidx = Compile::AliasIdxTop;
1029 nat = nullptr;
1030 break;
1031 }
1032 }
1033 if (nidx != midx) {
1034 if (PrintOpto || (PrintMiscellaneous && (WizardMode || Verbose))) {
1035 tty->print_cr("==== Matcher alias shift %d => %d", nidx, midx);
1036 n->dump();
1037 m->dump();
1038 }
1039 assert(C->subsume_loads() && C->must_alias(nat, midx),
1040 "must not lose alias info when matching");
1041 }
1042 }
1043 #endif
1044
1045 //------------------------------xform------------------------------------------
1046 // Given a Node in old-space, Match him (Label/Reduce) to produce a machine
1047 // Node in new-space. Given a new-space Node, recursively walk his children.
1048 Node *Matcher::transform( Node *n ) { ShouldNotCallThis(); return n; }
1049 Node *Matcher::xform( Node *n, int max_stack ) {
1050 // Use one stack to keep both: child's node/state and parent's node/index
1051 MStack mstack(max_stack * 2 * 2); // usually: C->live_nodes() * 2 * 2
1052 mstack.push(n, Visit, nullptr, -1); // set null as parent to indicate root
1053 while (mstack.is_nonempty()) {
1054 C->check_node_count(NodeLimitFudgeFactor, "too many nodes matching instructions");
1055 if (C->failing()) return nullptr;
1056 n = mstack.node(); // Leave node on stack
1057 Node_State nstate = mstack.state();
1058 if (nstate == Visit) {
1059 mstack.set_state(Post_Visit);
1060 Node *oldn = n;
1061 // Old-space or new-space check
1062 if (!C->node_arena()->contains(n)) {
1063 // Old space!
1064 Node* m;
1065 if (has_new_node(n)) { // Not yet Label/Reduced
1066 m = new_node(n);
1067 } else {
1068 if (!is_dontcare(n)) { // Matcher can match this guy
1069 // Calls match special. They match alone with no children.
1070 // Their children, the incoming arguments, match normally.
1071 m = n->is_SafePoint() ? match_sfpt(n->as_SafePoint()):match_tree(n);
1072 if (C->failing()) return nullptr;
1073 if (m == nullptr) { Matcher::soft_match_failure(); return nullptr; }
1074 if (n->is_MemBar()) {
1075 m->as_MachMemBar()->set_adr_type(n->adr_type());
1076 }
1077 } else { // Nothing the matcher cares about
1078 if (n->is_Proj() && n->in(0) != nullptr && n->in(0)->is_Multi()) { // Projections?
1079 // Convert to machine-dependent projection
1080 RegMask* mask = nullptr;
1081 if (n->in(0)->is_Call() && n->in(0)->as_Call()->tf()->returns_inline_type_as_fields()) {
1082 mask = return_values_mask(n->in(0)->as_Call()->tf());
1083 }
1084 m = n->in(0)->as_Multi()->match(n->as_Proj(), this, mask);
1085 NOT_PRODUCT(record_new2old(m, n);)
1086 if (m->in(0) != nullptr) // m might be top
1087 collect_null_checks(m, n);
1088 } else { // Else just a regular 'ol guy
1089 m = n->clone(); // So just clone into new-space
1090 NOT_PRODUCT(record_new2old(m, n);)
1091 // Def-Use edges will be added incrementally as Uses
1092 // of this node are matched.
1093 assert(m->outcnt() == 0, "no Uses of this clone yet");
1094 }
1095 }
1096
1097 set_new_node(n, m); // Map old to new
1098 if (_old_node_note_array != nullptr) {
1099 Node_Notes* nn = C->locate_node_notes(_old_node_note_array,
1100 n->_idx);
1101 C->set_node_notes_at(m->_idx, nn);
1102 }
1103 DEBUG_ONLY(match_alias_type(C, n, m));
1104 }
1105 n = m; // n is now a new-space node
1106 mstack.set_node(n);
1107 }
1108
1109 // New space!
1110 if (_visited.test_set(n->_idx)) continue; // while(mstack.is_nonempty())
1111
1112 int i;
1113 // Put precedence edges on stack first (match them last).
1114 for (i = oldn->req(); (uint)i < oldn->len(); i++) {
1115 Node *m = oldn->in(i);
1116 if (m == nullptr) break;
1117 // set -1 to call add_prec() instead of set_req() during Step1
1118 mstack.push(m, Visit, n, -1);
1119 }
1120
1121 // Handle precedence edges for interior nodes
1122 for (i = n->len()-1; (uint)i >= n->req(); i--) {
1123 Node *m = n->in(i);
1124 if (m == nullptr || C->node_arena()->contains(m)) continue;
1125 n->rm_prec(i);
1126 // set -1 to call add_prec() instead of set_req() during Step1
1127 mstack.push(m, Visit, n, -1);
1128 }
1129
1130 // For constant debug info, I'd rather have unmatched constants.
1131 int cnt = n->req();
1132 JVMState* jvms = n->jvms();
1133 int debug_cnt = jvms ? jvms->debug_start() : cnt;
1134
1135 // Now do only debug info. Clone constants rather than matching.
1136 // Constants are represented directly in the debug info without
1137 // the need for executable machine instructions.
1138 // Monitor boxes are also represented directly.
1139 for (i = cnt - 1; i >= debug_cnt; --i) { // For all debug inputs do
1140 Node *m = n->in(i); // Get input
1141 int op = m->Opcode();
1142 assert((op == Op_BoxLock) == jvms->is_monitor_use(i), "boxes only at monitor sites");
1143 if( op == Op_ConI || op == Op_ConP || op == Op_ConN || op == Op_ConNKlass ||
1144 op == Op_ConF || op == Op_ConD || op == Op_ConL
1145 // || op == Op_BoxLock // %%%% enable this and remove (+++) in chaitin.cpp
1146 ) {
1147 m = m->clone();
1148 NOT_PRODUCT(record_new2old(m, n));
1149 mstack.push(m, Post_Visit, n, i); // Don't need to visit
1150 mstack.push(m->in(0), Visit, m, 0);
1151 } else {
1152 mstack.push(m, Visit, n, i);
1153 }
1154 }
1155
1156 // And now walk his children, and convert his inputs to new-space.
1157 for( ; i >= 0; --i ) { // For all normal inputs do
1158 Node *m = n->in(i); // Get input
1159 if(m != nullptr)
1160 mstack.push(m, Visit, n, i);
1161 }
1162
1163 }
1164 else if (nstate == Post_Visit) {
1165 // Set xformed input
1166 Node *p = mstack.parent();
1167 if (p != nullptr) { // root doesn't have parent
1168 int i = (int)mstack.index();
1169 if (i >= 0)
1170 p->set_req(i, n); // required input
1171 else if (i == -1)
1172 p->add_prec(n); // precedence input
1173 else
1174 ShouldNotReachHere();
1175 }
1176 mstack.pop(); // remove processed node from stack
1177 }
1178 else {
1179 ShouldNotReachHere();
1180 }
1181 } // while (mstack.is_nonempty())
1182 return n; // Return new-space Node
1183 }
1184
1185 //------------------------------warp_outgoing_stk_arg------------------------
1186 OptoReg::Name Matcher::warp_outgoing_stk_arg( VMReg reg, OptoReg::Name begin_out_arg_area, OptoReg::Name &out_arg_limit_per_call ) {
1187 // Convert outgoing argument location to a pre-biased stack offset
1188 if (reg->is_stack()) {
1189 OptoReg::Name warped = reg->reg2stack();
1190 // Adjust the stack slot offset to be the register number used
1191 // by the allocator.
1192 warped = OptoReg::add(begin_out_arg_area, warped);
1193 // Keep track of the largest numbered stack slot used for an arg.
1194 // Largest used slot per call-site indicates the amount of stack
1195 // that is killed by the call.
1196 if (warped >= out_arg_limit_per_call) {
1197 out_arg_limit_per_call = OptoReg::add(warped, 1);
1198 }
1199 return warped;
1200 }
1201 return OptoReg::as_OptoReg(reg);
1202 }
1203
1204
1205 //------------------------------match_sfpt-------------------------------------
1206 // Helper function to match call instructions. Calls match special.
1207 // They match alone with no children. Their children, the incoming
1208 // arguments, match normally.
1209 MachNode *Matcher::match_sfpt( SafePointNode *sfpt ) {
1210 MachSafePointNode *msfpt = nullptr;
1211 MachCallNode *mcall = nullptr;
1212 uint cnt;
1213 // Split out case for SafePoint vs Call
1214 CallNode *call;
1215 const TypeTuple *domain;
1216 ciMethod* method = nullptr;
1217 if( sfpt->is_Call() ) {
1218 call = sfpt->as_Call();
1219 domain = call->tf()->domain_cc();
1220 cnt = domain->cnt();
1221
1222 // Match just the call, nothing else
1223 MachNode *m = match_tree(call);
1224 if (C->failing()) return nullptr;
1225 if( m == nullptr ) { Matcher::soft_match_failure(); return nullptr; }
1226
1227 // Copy data from the Ideal SafePoint to the machine version
1228 mcall = m->as_MachCall();
1229
1230 mcall->set_tf( call->tf());
1231 mcall->set_entry_point( call->entry_point());
1232 mcall->set_cnt( call->cnt());
1233 mcall->set_guaranteed_safepoint(call->guaranteed_safepoint());
1234
1235 if( mcall->is_MachCallJava() ) {
1236 MachCallJavaNode *mcall_java = mcall->as_MachCallJava();
1237 const CallJavaNode *call_java = call->as_CallJava();
1238 assert(call_java->validate_symbolic_info(), "inconsistent info");
1239 method = call_java->method();
1240 mcall_java->_method = method;
1241 mcall_java->_optimized_virtual = call_java->is_optimized_virtual();
1242 mcall_java->_override_symbolic_info = call_java->override_symbolic_info();
1243 mcall_java->_arg_escape = call_java->arg_escape();
1244 if( mcall_java->is_MachCallStaticJava() )
1245 mcall_java->as_MachCallStaticJava()->_name =
1246 call_java->as_CallStaticJava()->_name;
1247 if( mcall_java->is_MachCallDynamicJava() )
1248 mcall_java->as_MachCallDynamicJava()->_vtable_index =
1249 call_java->as_CallDynamicJava()->_vtable_index;
1250 }
1251 else if( mcall->is_MachCallRuntime() ) {
1252 MachCallRuntimeNode* mach_call_rt = mcall->as_MachCallRuntime();
1253 mach_call_rt->_name = call->as_CallRuntime()->_name;
1254 mach_call_rt->_leaf_no_fp = call->is_CallLeafNoFP();
1255 }
1256 msfpt = mcall;
1257 }
1258 // This is a non-call safepoint
1259 else {
1260 call = nullptr;
1261 domain = nullptr;
1262 MachNode *mn = match_tree(sfpt);
1263 if (C->failing()) return nullptr;
1264 msfpt = mn->as_MachSafePoint();
1265 cnt = TypeFunc::Parms;
1266 }
1267 msfpt->_has_ea_local_in_scope = sfpt->has_ea_local_in_scope();
1268
1269 // Advertise the correct memory effects (for anti-dependence computation).
1270 msfpt->set_adr_type(sfpt->adr_type());
1271
1272 // Allocate a private array of RegMasks. These RegMasks are not shared.
1273 msfpt->_in_rms = NEW_RESOURCE_ARRAY( RegMask, cnt );
1274 // Empty them all.
1275 for (uint i = 0; i < cnt; i++) {
1276 ::new (msfpt->_in_rms + i) RegMask(C->comp_arena());
1277 }
1278
1279 // Do all the pre-defined non-Empty register masks
1280 msfpt->_in_rms[TypeFunc::ReturnAdr] = _return_addr_mask;
1281 msfpt->_in_rms[TypeFunc::FramePtr ] = c_frame_ptr_mask;
1282
1283 // Place first outgoing argument can possibly be put.
1284 OptoReg::Name begin_out_arg_area = OptoReg::add(_new_SP, C->out_preserve_stack_slots());
1285 assert( is_even(begin_out_arg_area), "" );
1286 // Compute max outgoing register number per call site.
1287 OptoReg::Name out_arg_limit_per_call = begin_out_arg_area;
1288 // Calls to C may hammer extra stack slots above and beyond any arguments.
1289 // These are usually backing store for register arguments for varargs.
1290 if( call != nullptr && call->is_CallRuntime() )
1291 out_arg_limit_per_call = OptoReg::add(out_arg_limit_per_call,C->varargs_C_out_slots_killed());
1292
1293
1294 // Do the normal argument list (parameters) register masks
1295 // Null entry point is a special cast where the target of the call
1296 // is in a register.
1297 int adj = (call != nullptr && call->entry_point() == nullptr) ? 1 : 0;
1298 int argcnt = cnt - TypeFunc::Parms - adj;
1299 if( argcnt > 0 ) { // Skip it all if we have no args
1300 BasicType *sig_bt = NEW_RESOURCE_ARRAY( BasicType, argcnt );
1301 VMRegPair *parm_regs = NEW_RESOURCE_ARRAY( VMRegPair, argcnt );
1302 int i;
1303 for( i = 0; i < argcnt; i++ ) {
1304 sig_bt[i] = domain->field_at(i+TypeFunc::Parms+adj)->basic_type();
1305 }
1306 // V-call to pick proper calling convention
1307 call->calling_convention( sig_bt, parm_regs, argcnt );
1308
1309 #ifdef ASSERT
1310 // Sanity check users' calling convention. Really handy during
1311 // the initial porting effort. Fairly expensive otherwise.
1312 { for (int i = 0; i<argcnt; i++) {
1313 if( !parm_regs[i].first()->is_valid() &&
1314 !parm_regs[i].second()->is_valid() ) continue;
1315 VMReg reg1 = parm_regs[i].first();
1316 VMReg reg2 = parm_regs[i].second();
1317 for (int j = 0; j < i; j++) {
1318 if( !parm_regs[j].first()->is_valid() &&
1319 !parm_regs[j].second()->is_valid() ) continue;
1320 VMReg reg3 = parm_regs[j].first();
1321 VMReg reg4 = parm_regs[j].second();
1322 if( !reg1->is_valid() ) {
1323 assert( !reg2->is_valid(), "valid halvsies" );
1324 } else if( !reg3->is_valid() ) {
1325 assert( !reg4->is_valid(), "valid halvsies" );
1326 } else {
1327 assert( reg1 != reg2, "calling conv. must produce distinct regs");
1328 assert( reg1 != reg3, "calling conv. must produce distinct regs");
1329 assert( reg1 != reg4, "calling conv. must produce distinct regs");
1330 assert( reg2 != reg3, "calling conv. must produce distinct regs");
1331 assert( reg2 != reg4 || !reg2->is_valid(), "calling conv. must produce distinct regs");
1332 assert( reg3 != reg4, "calling conv. must produce distinct regs");
1333 }
1334 }
1335 }
1336 }
1337 #endif
1338
1339 // Visit each argument. Compute its outgoing register mask.
1340 // Return results now can have 2 bits returned.
1341 // Compute max over all outgoing arguments both per call-site
1342 // and over the entire method.
1343 for( i = 0; i < argcnt; i++ ) {
1344 // Address of incoming argument mask to fill in
1345 RegMask *rm = &mcall->_in_rms[i+TypeFunc::Parms+adj];
1346 VMReg first = parm_regs[i].first();
1347 VMReg second = parm_regs[i].second();
1348 if(!first->is_valid() &&
1349 !second->is_valid()) {
1350 continue; // Avoid Halves
1351 }
1352 // Handle case where arguments are in vector registers.
1353 if(call->in(TypeFunc::Parms + i)->bottom_type()->isa_vect()) {
1354 OptoReg::Name reg_fst = OptoReg::as_OptoReg(first);
1355 OptoReg::Name reg_snd = OptoReg::as_OptoReg(second);
1356 assert (reg_fst <= reg_snd, "fst=%d snd=%d", reg_fst, reg_snd);
1357 for (OptoReg::Name r = reg_fst; r <= reg_snd; r++) {
1358 rm->Insert(r);
1359 }
1360 }
1361 // Grab first register, adjust stack slots and insert in mask.
1362 OptoReg::Name reg1 = warp_outgoing_stk_arg(first, begin_out_arg_area, out_arg_limit_per_call );
1363 if (OptoReg::is_valid(reg1)) {
1364 rm->Insert( reg1 );
1365 }
1366 // Grab second register (if any), adjust stack slots and insert in mask.
1367 OptoReg::Name reg2 = warp_outgoing_stk_arg(second, begin_out_arg_area, out_arg_limit_per_call );
1368 if (OptoReg::is_valid(reg2)) {
1369 rm->Insert( reg2 );
1370 }
1371 } // End of for all arguments
1372 }
1373
1374 // Compute the max stack slot killed by any call. These will not be
1375 // available for debug info, and will be used to adjust FIRST_STACK_mask
1376 // after all call sites have been visited.
1377 if( _out_arg_limit < out_arg_limit_per_call)
1378 _out_arg_limit = out_arg_limit_per_call;
1379
1380 if (mcall) {
1381 // Kill the outgoing argument area, including any non-argument holes and
1382 // any legacy C-killed slots. Use Fat-Projections to do the killing.
1383 // Since the max-per-method covers the max-per-call-site and debug info
1384 // is excluded on the max-per-method basis, debug info cannot land in
1385 // this killed area.
1386 uint r_cnt = mcall->tf()->range_sig()->cnt();
1387 MachProjNode *proj = new MachProjNode( mcall, r_cnt+10000, RegMask::Empty, MachProjNode::fat_proj );
1388 for (int i = begin_out_arg_area; i < out_arg_limit_per_call; i++) {
1389 proj->_rout.Insert(OptoReg::Name(i));
1390 }
1391 if (!proj->_rout.is_Empty()) {
1392 push_projection(proj);
1393 }
1394 }
1395 // Transfer the safepoint information from the call to the mcall
1396 // Move the JVMState list
1397 msfpt->set_jvms(sfpt->jvms());
1398 for (JVMState* jvms = msfpt->jvms(); jvms; jvms = jvms->caller()) {
1399 jvms->set_map(sfpt);
1400 }
1401
1402 // Debug inputs begin just after the last incoming parameter
1403 assert((mcall == nullptr) || (mcall->jvms() == nullptr) ||
1404 (mcall->jvms()->debug_start() + mcall->_jvmadj == mcall->tf()->domain_cc()->cnt()), "");
1405
1406 // Add additional edges.
1407 if (msfpt->mach_constant_base_node_input() != (uint)-1 && !msfpt->is_MachCallLeaf()) {
1408 // For these calls we can not add MachConstantBase in expand(), as the
1409 // ins are not complete then.
1410 msfpt->ins_req(msfpt->mach_constant_base_node_input(), C->mach_constant_base_node());
1411 if (msfpt->jvms() &&
1412 msfpt->mach_constant_base_node_input() <= msfpt->jvms()->debug_start() + msfpt->_jvmadj) {
1413 // We added an edge before jvms, so we must adapt the position of the ins.
1414 msfpt->jvms()->adapt_position(+1);
1415 }
1416 }
1417
1418 // Registers killed by the call are set in the local scheduling pass
1419 // of Global Code Motion.
1420 return msfpt;
1421 }
1422
1423 //---------------------------match_tree----------------------------------------
1424 // Match a Ideal Node DAG - turn it into a tree; Label & Reduce. Used as part
1425 // of the whole-sale conversion from Ideal to Mach Nodes. Also used for
1426 // making GotoNodes while building the CFG and in init_spill_mask() to identify
1427 // a Load's result RegMask for memoization in idealreg2regmask[]
1428 MachNode *Matcher::match_tree( const Node *n ) {
1429 assert( n->Opcode() != Op_Phi, "cannot match" );
1430 assert( !n->is_block_start(), "cannot match" );
1431 // Set the mark for all locally allocated State objects.
1432 // When this call returns, the _states_arena arena will be reset
1433 // freeing all State objects.
1434 ResourceMark rm( &_states_arena );
1435
1436 LabelRootDepth = 0;
1437
1438 // StoreNodes require their Memory input to match any LoadNodes
1439 Node *mem = n->is_Store() ? n->in(MemNode::Memory) : (Node*)1 ;
1440 #ifdef ASSERT
1441 Node* save_mem_node = _mem_node;
1442 _mem_node = n->is_Store() ? (Node*)n : nullptr;
1443 #endif
1444 // State object for root node of match tree
1445 // Allocate it on _states_arena - stack allocation can cause stack overflow.
1446 State *s = new (&_states_arena) State;
1447 s->_kids[0] = nullptr;
1448 s->_kids[1] = nullptr;
1449 s->_leaf = (Node*)n;
1450 // Label the input tree, allocating labels from top-level arena
1451 Node* root_mem = mem;
1452 Label_Root(n, s, n->in(0), root_mem);
1453 if (C->failing()) return nullptr;
1454
1455 // The minimum cost match for the whole tree is found at the root State
1456 uint mincost = max_juint;
1457 uint cost = max_juint;
1458 uint i;
1459 for (i = 0; i < NUM_OPERANDS; i++) {
1460 if (s->valid(i) && // valid entry and
1461 s->cost(i) < cost && // low cost and
1462 s->rule(i) >= NUM_OPERANDS) {// not an operand
1463 mincost = i;
1464 cost = s->cost(i);
1465 }
1466 }
1467 if (mincost == max_juint) {
1468 #ifndef PRODUCT
1469 tty->print("No matching rule for:");
1470 s->dump();
1471 #endif
1472 Matcher::soft_match_failure();
1473 return nullptr;
1474 }
1475 // Reduce input tree based upon the state labels to machine Nodes
1476 MachNode *m = ReduceInst(s, s->rule(mincost), mem);
1477 // New-to-old mapping is done in ReduceInst, to cover complex instructions.
1478 NOT_PRODUCT(_old2new_map.map(n->_idx, m);)
1479
1480 // Add any Matcher-ignored edges
1481 uint cnt = n->req();
1482 uint start = 1;
1483 if( mem != (Node*)1 ) start = MemNode::Memory+1;
1484 if( n->is_AddP() ) {
1485 assert( mem == (Node*)1, "" );
1486 start = AddPNode::Base+1;
1487 }
1488 for( i = start; i < cnt; i++ ) {
1489 if( !n->match_edge(i) ) {
1490 if( i < m->req() )
1491 m->ins_req( i, n->in(i) );
1492 else
1493 m->add_req( n->in(i) );
1494 }
1495 }
1496
1497 DEBUG_ONLY( _mem_node = save_mem_node; )
1498 return m;
1499 }
1500
1501
1502 //------------------------------match_into_reg---------------------------------
1503 // Choose to either match this Node in a register or part of the current
1504 // match tree. Return true for requiring a register and false for matching
1505 // as part of the current match tree.
1506 static bool match_into_reg( const Node *n, Node *m, Node *control, int i, bool shared ) {
1507
1508 const Type *t = m->bottom_type();
1509
1510 if (t->singleton()) {
1511 // Never force constants into registers. Allow them to match as
1512 // constants or registers. Copies of the same value will share
1513 // the same register. See find_shared_node.
1514 return false;
1515 } else { // Not a constant
1516 if (!shared && Matcher::is_encode_and_store_pattern(n, m)) {
1517 // Make it possible to match "encode and store" patterns with non-shared
1518 // encode operations that are pinned to a control node (e.g. by CastPP
1519 // node removal in final graph reshaping). The matched instruction cannot
1520 // float above the encode's control node because it is pinned to the
1521 // store's control node.
1522 return false;
1523 }
1524 // Stop recursion if they have different Controls.
1525 Node* m_control = m->in(0);
1526 // Control of load's memory can post-dominates load's control.
1527 // So use it since load can't float above its memory.
1528 Node* mem_control = (m->is_Load()) ? m->in(MemNode::Memory)->in(0) : nullptr;
1529 if (control && m_control && control != m_control && control != mem_control) {
1530
1531 // Actually, we can live with the most conservative control we
1532 // find, if it post-dominates the others. This allows us to
1533 // pick up load/op/store trees where the load can float a little
1534 // above the store.
1535 Node *x = control;
1536 const uint max_scan = 6; // Arbitrary scan cutoff
1537 uint j;
1538 for (j=0; j<max_scan; j++) {
1539 if (x->is_Region()) // Bail out at merge points
1540 return true;
1541 x = x->in(0);
1542 if (x == m_control) // Does 'control' post-dominate
1543 break; // m->in(0)? If so, we can use it
1544 if (x == mem_control) // Does 'control' post-dominate
1545 break; // mem_control? If so, we can use it
1546 }
1547 if (j == max_scan) // No post-domination before scan end?
1548 return true; // Then break the match tree up
1549 }
1550 if ((m->is_DecodeN() && Matcher::narrow_oop_use_complex_address()) ||
1551 (m->is_DecodeNKlass() && Matcher::narrow_klass_use_complex_address())) {
1552 // These are commonly used in address expressions and can
1553 // efficiently fold into them on X64 in some cases.
1554 return false;
1555 }
1556 }
1557
1558 // Not forceable cloning. If shared, put it into a register.
1559 return shared;
1560 }
1561
1562
1563 //------------------------------Instruction Selection--------------------------
1564 // Label method walks a "tree" of nodes, using the ADLC generated DFA to match
1565 // ideal nodes to machine instructions. Trees are delimited by shared Nodes,
1566 // things the Matcher does not match (e.g., Memory), and things with different
1567 // Controls (hence forced into different blocks). We pass in the Control
1568 // selected for this entire State tree.
1569
1570 // The Matcher works on Trees, but an Intel add-to-memory requires a DAG: the
1571 // Store and the Load must have identical Memories (as well as identical
1572 // pointers). Since the Matcher does not have anything for Memory (and
1573 // does not handle DAGs), I have to match the Memory input myself. If the
1574 // Tree root is a Store or if there are multiple Loads in the tree, I require
1575 // all Loads to have the identical memory.
1576 Node* Matcher::Label_Root(const Node* n, State* svec, Node* control, Node*& mem) {
1577 // Since Label_Root is a recursive function, its possible that we might run
1578 // out of stack space. See bugs 6272980 & 6227033 for more info.
1579 LabelRootDepth++;
1580 if (LabelRootDepth > MaxLabelRootDepth) {
1581 // Bailout. Can for example be hit with a deep chain of operations.
1582 C->record_method_not_compilable("Out of stack space, increase MaxLabelRootDepth");
1583 return nullptr;
1584 }
1585 uint care = 0; // Edges matcher cares about
1586 uint cnt = n->req();
1587 uint i = 0;
1588
1589 // Examine children for memory state
1590 // Can only subsume a child into your match-tree if that child's memory state
1591 // is not modified along the path to another input.
1592 // It is unsafe even if the other inputs are separate roots.
1593 Node *input_mem = nullptr;
1594 for( i = 1; i < cnt; i++ ) {
1595 if( !n->match_edge(i) ) continue;
1596 Node *m = n->in(i); // Get ith input
1597 assert( m, "expect non-null children" );
1598 if( m->is_Load() ) {
1599 if( input_mem == nullptr ) {
1600 input_mem = m->in(MemNode::Memory);
1601 if (mem == (Node*)1) {
1602 // Save this memory to bail out if there's another memory access
1603 // to a different memory location in the same tree.
1604 mem = input_mem;
1605 }
1606 } else if( input_mem != m->in(MemNode::Memory) ) {
1607 input_mem = NodeSentinel;
1608 }
1609 }
1610 }
1611
1612 for( i = 1; i < cnt; i++ ){// For my children
1613 if( !n->match_edge(i) ) continue;
1614 Node *m = n->in(i); // Get ith input
1615 // Allocate states out of a private arena
1616 State *s = new (&_states_arena) State;
1617 svec->_kids[care++] = s;
1618 assert( care <= 2, "binary only for now" );
1619
1620 // Recursively label the State tree.
1621 s->_kids[0] = nullptr;
1622 s->_kids[1] = nullptr;
1623 s->_leaf = m;
1624
1625 // Check for leaves of the State Tree; things that cannot be a part of
1626 // the current tree. If it finds any, that value is matched as a
1627 // register operand. If not, then the normal matching is used.
1628 if( match_into_reg(n, m, control, i, is_shared(m)) ||
1629 // Stop recursion if this is a LoadNode and there is another memory access
1630 // to a different memory location in the same tree (for example, a StoreNode
1631 // at the root of this tree or another LoadNode in one of the children).
1632 ((mem!=(Node*)1) && m->is_Load() && m->in(MemNode::Memory) != mem) ||
1633 // Can NOT include the match of a subtree when its memory state
1634 // is used by any of the other subtrees
1635 (input_mem == NodeSentinel) ) {
1636 // Print when we exclude matching due to different memory states at input-loads
1637 if (PrintOpto && (Verbose && WizardMode) && (input_mem == NodeSentinel)
1638 && !((mem!=(Node*)1) && m->is_Load() && m->in(MemNode::Memory) != mem)) {
1639 tty->print_cr("invalid input_mem");
1640 }
1641 // Switch to a register-only opcode; this value must be in a register
1642 // and cannot be subsumed as part of a larger instruction.
1643 s->DFA( m->ideal_reg(), m );
1644
1645 } else {
1646 // If match tree has no control and we do, adopt it for entire tree
1647 if( control == nullptr && m->in(0) != nullptr && m->req() > 1 )
1648 control = m->in(0); // Pick up control
1649 // Else match as a normal part of the match tree.
1650 control = Label_Root(m, s, control, mem);
1651 if (C->failing()) return nullptr;
1652 }
1653 }
1654
1655 // Call DFA to match this node, and return
1656 svec->DFA( n->Opcode(), n );
1657
1658 uint x;
1659 for( x = 0; x < _LAST_MACH_OPER; x++ )
1660 if( svec->valid(x) )
1661 break;
1662
1663 if (x >= _LAST_MACH_OPER) {
1664 #ifdef ASSERT
1665 n->dump();
1666 svec->dump();
1667 #endif
1668 assert( false, "bad AD file" );
1669 C->record_failure("bad AD file");
1670 }
1671 return control;
1672 }
1673
1674
1675 // Con nodes reduced using the same rule can share their MachNode
1676 // which reduces the number of copies of a constant in the final
1677 // program. The register allocator is free to split uses later to
1678 // split live ranges.
1679 MachNode* Matcher::find_shared_node(Node* leaf, uint rule) {
1680 if (!leaf->is_Con() && !leaf->is_DecodeNarrowPtr()) return nullptr;
1681
1682 // See if this Con has already been reduced using this rule.
1683 if (_shared_nodes.max() <= leaf->_idx) return nullptr;
1684 MachNode* last = (MachNode*)_shared_nodes.at(leaf->_idx);
1685 if (last != nullptr && rule == last->rule()) {
1686 // Don't expect control change for DecodeN
1687 if (leaf->is_DecodeNarrowPtr())
1688 return last;
1689 // Get the new space root.
1690 Node* xroot = new_node(C->root());
1691 if (xroot == nullptr) {
1692 // This shouldn't happen give the order of matching.
1693 return nullptr;
1694 }
1695
1696 // Shared constants need to have their control be root so they
1697 // can be scheduled properly.
1698 Node* control = last->in(0);
1699 if (control != xroot) {
1700 if (control == nullptr || control == C->root()) {
1701 last->set_req(0, xroot);
1702 } else {
1703 assert(false, "unexpected control");
1704 return nullptr;
1705 }
1706 }
1707 return last;
1708 }
1709 return nullptr;
1710 }
1711
1712
1713 //------------------------------ReduceInst-------------------------------------
1714 // Reduce a State tree (with given Control) into a tree of MachNodes.
1715 // This routine (and it's cohort ReduceOper) convert Ideal Nodes into
1716 // complicated machine Nodes. Each MachNode covers some tree of Ideal Nodes.
1717 // Each MachNode has a number of complicated MachOper operands; each
1718 // MachOper also covers a further tree of Ideal Nodes.
1719
1720 // The root of the Ideal match tree is always an instruction, so we enter
1721 // the recursion here. After building the MachNode, we need to recurse
1722 // the tree checking for these cases:
1723 // (1) Child is an instruction -
1724 // Build the instruction (recursively), add it as an edge.
1725 // Build a simple operand (register) to hold the result of the instruction.
1726 // (2) Child is an interior part of an instruction -
1727 // Skip over it (do nothing)
1728 // (3) Child is the start of a operand -
1729 // Build the operand, place it inside the instruction
1730 // Call ReduceOper.
1731 MachNode *Matcher::ReduceInst( State *s, int rule, Node *&mem ) {
1732 assert( rule >= NUM_OPERANDS, "called with operand rule" );
1733
1734 MachNode* shared_node = find_shared_node(s->_leaf, rule);
1735 if (shared_node != nullptr) {
1736 return shared_node;
1737 }
1738
1739 // Build the object to represent this state & prepare for recursive calls
1740 MachNode *mach = s->MachNodeGenerator(rule);
1741 guarantee(mach != nullptr, "Missing MachNode");
1742 mach->_opnds[0] = s->MachOperGenerator(_reduceOp[rule]);
1743 assert( mach->_opnds[0] != nullptr, "Missing result operand" );
1744 Node *leaf = s->_leaf;
1745 NOT_PRODUCT(record_new2old(mach, leaf);)
1746 // Check for instruction or instruction chain rule
1747 if( rule >= _END_INST_CHAIN_RULE || rule < _BEGIN_INST_CHAIN_RULE ) {
1748 assert(C->node_arena()->contains(s->_leaf) || !has_new_node(s->_leaf),
1749 "duplicating node that's already been matched");
1750 // Instruction
1751 mach->add_req( leaf->in(0) ); // Set initial control
1752 // Reduce interior of complex instruction
1753 ReduceInst_Interior( s, rule, mem, mach, 1 );
1754 } else {
1755 // Instruction chain rules are data-dependent on their inputs
1756 mach->add_req(nullptr); // Set initial control to none
1757 ReduceInst_Chain_Rule( s, rule, mem, mach );
1758 }
1759
1760 // If a Memory was used, insert a Memory edge
1761 if( mem != (Node*)1 ) {
1762 mach->ins_req(MemNode::Memory,mem);
1763 #ifdef ASSERT
1764 // Verify adr type after matching memory operation
1765 const MachOper* oper = mach->memory_operand();
1766 if (oper != nullptr && oper != (MachOper*)-1) {
1767 // It has a unique memory operand. Find corresponding ideal mem node.
1768 Node* m = nullptr;
1769 if (leaf->is_Mem()) {
1770 m = leaf;
1771 } else {
1772 m = _mem_node;
1773 assert(m != nullptr && m->is_Mem(), "expecting memory node");
1774 }
1775 const Type* mach_at = mach->adr_type();
1776 // DecodeN node consumed by an address may have different type
1777 // than its input. Don't compare types for such case.
1778 if (m->adr_type() != mach_at &&
1779 (m->in(MemNode::Address)->is_DecodeNarrowPtr() ||
1780 (m->in(MemNode::Address)->is_AddP() &&
1781 m->in(MemNode::Address)->in(AddPNode::Address)->is_DecodeNarrowPtr()) ||
1782 (m->in(MemNode::Address)->is_AddP() &&
1783 m->in(MemNode::Address)->in(AddPNode::Address)->is_AddP() &&
1784 m->in(MemNode::Address)->in(AddPNode::Address)->in(AddPNode::Address)->is_DecodeNarrowPtr()))) {
1785 mach_at = m->adr_type();
1786 }
1787 if (m->adr_type() != mach_at) {
1788 m->dump();
1789 tty->print_cr("mach:");
1790 mach->dump(1);
1791 }
1792 assert(m->adr_type() == mach_at, "matcher should not change adr type");
1793 }
1794 #endif
1795 }
1796
1797 // If the _leaf is an AddP, insert the base edge
1798 if (leaf->is_AddP()) {
1799 mach->ins_req(AddPNode::Base,leaf->in(AddPNode::Base));
1800 }
1801
1802 uint number_of_projections_prior = number_of_projections();
1803
1804 // Perform any 1-to-many expansions required
1805 MachNode *ex = mach->Expand(s, _projection_list, mem);
1806 if (ex != mach) {
1807 assert(ex->ideal_reg() == mach->ideal_reg(), "ideal types should match");
1808 if( ex->in(1)->is_Con() )
1809 ex->in(1)->set_req(0, C->root());
1810 // Remove old node from the graph
1811 for( uint i=0; i<mach->req(); i++ ) {
1812 mach->set_req(i,nullptr);
1813 }
1814 NOT_PRODUCT(record_new2old(ex, s->_leaf);)
1815 }
1816
1817 // PhaseChaitin::fixup_spills will sometimes generate spill code
1818 // via the matcher. By the time, nodes have been wired into the CFG,
1819 // and any further nodes generated by expand rules will be left hanging
1820 // in space, and will not get emitted as output code. Catch this.
1821 // Also, catch any new register allocation constraints ("projections")
1822 // generated belatedly during spill code generation.
1823 if (_allocation_started) {
1824 guarantee(ex == mach, "no expand rules during spill generation");
1825 guarantee(number_of_projections_prior == number_of_projections(), "no allocation during spill generation");
1826 }
1827
1828 if (leaf->is_Con() || leaf->is_DecodeNarrowPtr()) {
1829 // Record the con for sharing
1830 _shared_nodes.map(leaf->_idx, ex);
1831 }
1832
1833 // Have mach nodes inherit GC barrier data
1834 mach->set_barrier_data(MemNode::barrier_data(leaf));
1835
1836 return ex;
1837 }
1838
1839 void Matcher::handle_precedence_edges(Node* n, MachNode *mach) {
1840 for (uint i = n->req(); i < n->len(); i++) {
1841 if (n->in(i) != nullptr) {
1842 mach->add_prec(n->in(i));
1843 }
1844 }
1845 }
1846
1847 void Matcher::ReduceInst_Chain_Rule(State* s, int rule, Node* &mem, MachNode* mach) {
1848 // 'op' is what I am expecting to receive
1849 int op = _leftOp[rule];
1850 // Operand type to catch childs result
1851 // This is what my child will give me.
1852 unsigned int opnd_class_instance = s->rule(op);
1853 // Choose between operand class or not.
1854 // This is what I will receive.
1855 int catch_op = (FIRST_OPERAND_CLASS <= op && op < NUM_OPERANDS) ? opnd_class_instance : op;
1856 // New rule for child. Chase operand classes to get the actual rule.
1857 unsigned int newrule = s->rule(catch_op);
1858
1859 if (newrule < NUM_OPERANDS) {
1860 // Chain from operand or operand class, may be output of shared node
1861 assert(opnd_class_instance < NUM_OPERANDS, "Bad AD file: Instruction chain rule must chain from operand");
1862 // Insert operand into array of operands for this instruction
1863 mach->_opnds[1] = s->MachOperGenerator(opnd_class_instance);
1864
1865 ReduceOper(s, newrule, mem, mach);
1866 } else {
1867 // Chain from the result of an instruction
1868 assert(newrule >= _LAST_MACH_OPER, "Do NOT chain from internal operand");
1869 mach->_opnds[1] = s->MachOperGenerator(_reduceOp[catch_op]);
1870 Node *mem1 = (Node*)1;
1871 DEBUG_ONLY(Node *save_mem_node = _mem_node;)
1872 mach->add_req( ReduceInst(s, newrule, mem1) );
1873 DEBUG_ONLY(_mem_node = save_mem_node;)
1874 }
1875 return;
1876 }
1877
1878
1879 uint Matcher::ReduceInst_Interior( State *s, int rule, Node *&mem, MachNode *mach, uint num_opnds ) {
1880 handle_precedence_edges(s->_leaf, mach);
1881
1882 if( s->_leaf->is_Load() ) {
1883 Node *mem2 = s->_leaf->in(MemNode::Memory);
1884 assert( mem == (Node*)1 || mem == mem2, "multiple Memories being matched at once?" );
1885 DEBUG_ONLY( if( mem == (Node*)1 ) _mem_node = s->_leaf;)
1886 mem = mem2;
1887 }
1888 if( s->_leaf->in(0) != nullptr && s->_leaf->req() > 1) {
1889 if( mach->in(0) == nullptr )
1890 mach->set_req(0, s->_leaf->in(0));
1891 }
1892
1893 // Now recursively walk the state tree & add operand list.
1894 for( uint i=0; i<2; i++ ) { // binary tree
1895 State *newstate = s->_kids[i];
1896 if( newstate == nullptr ) break; // Might only have 1 child
1897 // 'op' is what I am expecting to receive
1898 int op;
1899 if( i == 0 ) {
1900 op = _leftOp[rule];
1901 } else {
1902 op = _rightOp[rule];
1903 }
1904 // Operand type to catch childs result
1905 // This is what my child will give me.
1906 int opnd_class_instance = newstate->rule(op);
1907 // Choose between operand class or not.
1908 // This is what I will receive.
1909 int catch_op = (op >= FIRST_OPERAND_CLASS && op < NUM_OPERANDS) ? opnd_class_instance : op;
1910 // New rule for child. Chase operand classes to get the actual rule.
1911 int newrule = newstate->rule(catch_op);
1912
1913 if (newrule < NUM_OPERANDS) { // Operand/operandClass or internalOp/instruction?
1914 // Operand/operandClass
1915 // Insert operand into array of operands for this instruction
1916 mach->_opnds[num_opnds++] = newstate->MachOperGenerator(opnd_class_instance);
1917 ReduceOper(newstate, newrule, mem, mach);
1918
1919 } else { // Child is internal operand or new instruction
1920 if (newrule < _LAST_MACH_OPER) { // internal operand or instruction?
1921 // internal operand --> call ReduceInst_Interior
1922 // Interior of complex instruction. Do nothing but recurse.
1923 num_opnds = ReduceInst_Interior(newstate, newrule, mem, mach, num_opnds);
1924 } else {
1925 // instruction --> call build operand( ) to catch result
1926 // --> ReduceInst( newrule )
1927 mach->_opnds[num_opnds++] = s->MachOperGenerator(_reduceOp[catch_op]);
1928 Node *mem1 = (Node*)1;
1929 DEBUG_ONLY(Node *save_mem_node = _mem_node;)
1930 mach->add_req( ReduceInst( newstate, newrule, mem1 ) );
1931 DEBUG_ONLY(_mem_node = save_mem_node;)
1932 }
1933 }
1934 assert( mach->_opnds[num_opnds-1], "" );
1935 }
1936 return num_opnds;
1937 }
1938
1939 // This routine walks the interior of possible complex operands.
1940 // At each point we check our children in the match tree:
1941 // (1) No children -
1942 // We are a leaf; add _leaf field as an input to the MachNode
1943 // (2) Child is an internal operand -
1944 // Skip over it ( do nothing )
1945 // (3) Child is an instruction -
1946 // Call ReduceInst recursively and
1947 // and instruction as an input to the MachNode
1948 void Matcher::ReduceOper( State *s, int rule, Node *&mem, MachNode *mach ) {
1949 assert( rule < _LAST_MACH_OPER, "called with operand rule" );
1950 State *kid = s->_kids[0];
1951 assert( kid == nullptr || s->_leaf->in(0) == nullptr, "internal operands have no control" );
1952
1953 // Leaf? And not subsumed?
1954 if( kid == nullptr && !_swallowed[rule] ) {
1955 mach->add_req( s->_leaf ); // Add leaf pointer
1956 return; // Bail out
1957 }
1958
1959 if( s->_leaf->is_Load() ) {
1960 assert( mem == (Node*)1, "multiple Memories being matched at once?" );
1961 mem = s->_leaf->in(MemNode::Memory);
1962 DEBUG_ONLY(_mem_node = s->_leaf;)
1963 }
1964
1965 handle_precedence_edges(s->_leaf, mach);
1966
1967 if( s->_leaf->in(0) && s->_leaf->req() > 1) {
1968 if( !mach->in(0) )
1969 mach->set_req(0,s->_leaf->in(0));
1970 else {
1971 assert( s->_leaf->in(0) == mach->in(0), "same instruction, differing controls?" );
1972 }
1973 }
1974
1975 for (uint i = 0; kid != nullptr && i < 2; kid = s->_kids[1], i++) { // binary tree
1976 int newrule;
1977 if( i == 0) {
1978 newrule = kid->rule(_leftOp[rule]);
1979 } else {
1980 newrule = kid->rule(_rightOp[rule]);
1981 }
1982
1983 if (newrule < _LAST_MACH_OPER) { // Operand or instruction?
1984 // Internal operand; recurse but do nothing else
1985 ReduceOper(kid, newrule, mem, mach);
1986
1987 } else { // Child is a new instruction
1988 // Reduce the instruction, and add a direct pointer from this
1989 // machine instruction to the newly reduced one.
1990 Node *mem1 = (Node*)1;
1991 DEBUG_ONLY(Node *save_mem_node = _mem_node;)
1992 mach->add_req( ReduceInst( kid, newrule, mem1 ) );
1993 DEBUG_ONLY(_mem_node = save_mem_node;)
1994 }
1995 }
1996 }
1997
1998
1999 // -------------------------------------------------------------------------
2000 // Java-Java calling convention
2001 // (what you use when Java calls Java)
2002
2003 //------------------------------find_receiver----------------------------------
2004 // For a given signature, return the OptoReg for parameter 0.
2005 OptoReg::Name Matcher::find_receiver() {
2006 VMRegPair regs;
2007 BasicType sig_bt = T_OBJECT;
2008 SharedRuntime::java_calling_convention(&sig_bt, ®s, 1);
2009 // Return argument 0 register. In the LP64 build pointers
2010 // take 2 registers, but the VM wants only the 'main' name.
2011 return OptoReg::as_OptoReg(regs.first());
2012 }
2013
2014 bool Matcher::is_vshift_con_pattern(Node* n, Node* m) {
2015 if (n != nullptr && m != nullptr) {
2016 return VectorNode::is_vector_shift(n) &&
2017 VectorNode::is_vector_shift_count(m) && m->in(1)->is_Con();
2018 }
2019 return false;
2020 }
2021
2022 bool Matcher::clone_node(Node* n, Node* m, Matcher::MStack& mstack) {
2023 // Must clone all producers of flags, or we will not match correctly.
2024 // Suppose a compare setting int-flags is shared (e.g., a switch-tree)
2025 // then it will match into an ideal Op_RegFlags. Alas, the fp-flags
2026 // are also there, so we may match a float-branch to int-flags and
2027 // expect the allocator to haul the flags from the int-side to the
2028 // fp-side. No can do.
2029 if (_must_clone[m->Opcode()]) {
2030 mstack.push(m, Visit);
2031 return true;
2032 }
2033 return pd_clone_node(n, m, mstack);
2034 }
2035
2036 bool Matcher::clone_base_plus_offset_address(AddPNode* m, Matcher::MStack& mstack, VectorSet& address_visited) {
2037 Node *off = m->in(AddPNode::Offset);
2038 if (off->is_Con()) {
2039 address_visited.test_set(m->_idx); // Flag as address_visited
2040 mstack.push(m->in(AddPNode::Address), Pre_Visit);
2041 // Clone X+offset as it also folds into most addressing expressions
2042 mstack.push(off, Visit);
2043 mstack.push(m->in(AddPNode::Base), Pre_Visit);
2044 return true;
2045 }
2046 return false;
2047 }
2048
2049 // A method-klass-holder may be passed in the inline_cache_reg
2050 // and then expanded into the inline_cache_reg and a method_ptr register
2051 // defined in ad_<arch>.cpp
2052
2053 //------------------------------find_shared------------------------------------
2054 // Set bits if Node is shared or otherwise a root
2055 void Matcher::find_shared(Node* n) {
2056 // Allocate stack of size C->live_nodes() * 2 to avoid frequent realloc
2057 MStack mstack(C->live_nodes() * 2);
2058 // Mark nodes as address_visited if they are inputs to an address expression
2059 VectorSet address_visited;
2060 mstack.push(n, Visit); // Don't need to pre-visit root node
2061 while (mstack.is_nonempty()) {
2062 n = mstack.node(); // Leave node on stack
2063 Node_State nstate = mstack.state();
2064 uint nop = n->Opcode();
2065 if (nstate == Pre_Visit) {
2066 if (address_visited.test(n->_idx)) { // Visited in address already?
2067 // Flag as visited and shared now.
2068 set_visited(n);
2069 }
2070 if (is_visited(n)) { // Visited already?
2071 // Node is shared and has no reason to clone. Flag it as shared.
2072 // This causes it to match into a register for the sharing.
2073 set_shared(n); // Flag as shared and
2074 if (n->is_DecodeNarrowPtr()) {
2075 // Oop field/array element loads must be shared but since
2076 // they are shared through a DecodeN they may appear to have
2077 // a single use so force sharing here.
2078 set_shared(n->in(1));
2079 }
2080 mstack.pop(); // remove node from stack
2081 continue;
2082 }
2083 nstate = Visit; // Not already visited; so visit now
2084 }
2085 if (nstate == Visit) {
2086 mstack.set_state(Post_Visit);
2087 set_visited(n); // Flag as visited now
2088 bool mem_op = false;
2089 int mem_addr_idx = MemNode::Address;
2090 if (find_shared_visit(mstack, n, nop, mem_op, mem_addr_idx)) {
2091 continue;
2092 }
2093 for (int i = n->len() - 1; i >= 0; --i) { // For my children
2094 Node* m = n->in(i); // Get ith input
2095 if (m == nullptr) {
2096 continue; // Ignore nulls
2097 }
2098 if (clone_node(n, m, mstack)) {
2099 continue;
2100 }
2101
2102 // Clone addressing expressions as they are "free" in memory access instructions
2103 if (mem_op && i == mem_addr_idx && m->is_AddP() &&
2104 // When there are other uses besides address expressions
2105 // put it on stack and mark as shared.
2106 !is_visited(m)) {
2107 // Some inputs for address expression are not put on stack
2108 // to avoid marking them as shared and forcing them into register
2109 // if they are used only in address expressions.
2110 // But they should be marked as shared if there are other uses
2111 // besides address expressions.
2112
2113 if (pd_clone_address_expressions(m->as_AddP(), mstack, address_visited)) {
2114 continue;
2115 }
2116 } // if( mem_op &&
2117 mstack.push(m, Pre_Visit);
2118 } // for(int i = ...)
2119 }
2120 else if (nstate == Alt_Post_Visit) {
2121 mstack.pop(); // Remove node from stack
2122 // We cannot remove the Cmp input from the Bool here, as the Bool may be
2123 // shared and all users of the Bool need to move the Cmp in parallel.
2124 // This leaves both the Bool and the If pointing at the Cmp. To
2125 // prevent the Matcher from trying to Match the Cmp along both paths
2126 // BoolNode::match_edge always returns a zero.
2127
2128 // We reorder the Op_If in a pre-order manner, so we can visit without
2129 // accidentally sharing the Cmp (the Bool and the If make 2 users).
2130 n->add_req( n->in(1)->in(1) ); // Add the Cmp next to the Bool
2131 }
2132 else if (nstate == Post_Visit) {
2133 mstack.pop(); // Remove node from stack
2134
2135 // Now hack a few special opcodes
2136 uint opcode = n->Opcode();
2137 bool gc_handled = BarrierSet::barrier_set()->barrier_set_c2()->matcher_find_shared_post_visit(this, n, opcode);
2138 if (!gc_handled) {
2139 find_shared_post_visit(n, opcode);
2140 }
2141 }
2142 else {
2143 ShouldNotReachHere();
2144 }
2145 } // end of while (mstack.is_nonempty())
2146 }
2147
2148 bool Matcher::find_shared_visit(MStack& mstack, Node* n, uint opcode, bool& mem_op, int& mem_addr_idx) {
2149 switch(opcode) { // Handle some opcodes special
2150 case Op_Phi: // Treat Phis as shared roots
2151 case Op_Parm:
2152 case Op_Proj: // All handled specially during matching
2153 case Op_SafePointScalarObject:
2154 set_shared(n);
2155 set_dontcare(n);
2156 break;
2157 case Op_If:
2158 case Op_CountedLoopEnd:
2159 mstack.set_state(Alt_Post_Visit); // Alternative way
2160 // Convert (If (Bool (CmpX A B))) into (If (Bool) (CmpX A B)). Helps
2161 // with matching cmp/branch in 1 instruction. The Matcher needs the
2162 // Bool and CmpX side-by-side, because it can only get at constants
2163 // that are at the leaves of Match trees, and the Bool's condition acts
2164 // as a constant here.
2165 mstack.push(n->in(1), Visit); // Clone the Bool
2166 mstack.push(n->in(0), Pre_Visit); // Visit control input
2167 return true; // while (mstack.is_nonempty())
2168 case Op_ConvI2D: // These forms efficiently match with a prior
2169 case Op_ConvI2F: // Load but not a following Store
2170 if( n->in(1)->is_Load() && // Prior load
2171 n->outcnt() == 1 && // Not already shared
2172 n->unique_out()->is_Store() ) // Following store
2173 set_shared(n); // Force it to be a root
2174 break;
2175 case Op_ReverseBytesI:
2176 case Op_ReverseBytesL:
2177 if( n->in(1)->is_Load() && // Prior load
2178 n->outcnt() == 1 ) // Not already shared
2179 set_shared(n); // Force it to be a root
2180 break;
2181 case Op_BoxLock: // Can't match until we get stack-regs in ADLC
2182 case Op_IfFalse:
2183 case Op_IfTrue:
2184 case Op_MachProj:
2185 case Op_MergeMem:
2186 case Op_Catch:
2187 case Op_CatchProj:
2188 case Op_CProj:
2189 case Op_JumpProj:
2190 case Op_JProj:
2191 case Op_NeverBranch:
2192 set_dontcare(n);
2193 break;
2194 case Op_Jump:
2195 mstack.push(n->in(1), Pre_Visit); // Switch Value (could be shared)
2196 mstack.push(n->in(0), Pre_Visit); // Visit Control input
2197 return true; // while (mstack.is_nonempty())
2198 case Op_StrComp:
2199 case Op_StrEquals:
2200 case Op_StrIndexOf:
2201 case Op_StrIndexOfChar:
2202 case Op_AryEq:
2203 case Op_VectorizedHashCode:
2204 case Op_CountPositives:
2205 case Op_StrInflatedCopy:
2206 case Op_StrCompressedCopy:
2207 case Op_EncodeISOArray:
2208 case Op_FmaD:
2209 case Op_FmaF:
2210 case Op_FmaHF:
2211 case Op_FmaVD:
2212 case Op_FmaVF:
2213 case Op_FmaVHF:
2214 case Op_MacroLogicV:
2215 case Op_VectorCmpMasked:
2216 case Op_CompressV:
2217 case Op_CompressM:
2218 case Op_ExpandV:
2219 case Op_VectorLoadMask:
2220 set_shared(n); // Force result into register (it will be anyways)
2221 break;
2222 case Op_ConP: { // Convert pointers above the centerline to NUL
2223 TypeNode *tn = n->as_Type(); // Constants derive from type nodes
2224 const TypePtr* tp = tn->type()->is_ptr();
2225 if (tp->_ptr == TypePtr::AnyNull) {
2226 tn->set_type(TypePtr::NULL_PTR);
2227 }
2228 break;
2229 }
2230 case Op_ConN: { // Convert narrow pointers above the centerline to NUL
2231 TypeNode *tn = n->as_Type(); // Constants derive from type nodes
2232 const TypePtr* tp = tn->type()->make_ptr();
2233 if (tp && tp->_ptr == TypePtr::AnyNull) {
2234 tn->set_type(TypeNarrowOop::NULL_PTR);
2235 }
2236 break;
2237 }
2238 case Op_Binary: // These are introduced in the Post_Visit state.
2239 ShouldNotReachHere();
2240 break;
2241 case Op_ClearArray:
2242 case Op_SafePoint:
2243 mem_op = true;
2244 break;
2245 default:
2246 if( n->is_Store() ) {
2247 // Do match stores, despite no ideal reg
2248 mem_op = true;
2249 break;
2250 }
2251 if( n->is_Mem() ) { // Loads and LoadStores
2252 mem_op = true;
2253 // Loads must be root of match tree due to prior load conflict
2254 if( C->subsume_loads() == false )
2255 set_shared(n);
2256 }
2257 // Fall into default case
2258 if( !n->ideal_reg() )
2259 set_dontcare(n); // Unmatchable Nodes
2260 } // end_switch
2261 return false;
2262 }
2263
2264 void Matcher::find_shared_post_visit(Node* n, uint opcode) {
2265 if (n->is_predicated_vector()) {
2266 // Restructure into binary trees for Matching.
2267 if (n->req() == 4) {
2268 n->set_req(1, new BinaryNode(n->in(1), n->in(2)));
2269 n->set_req(2, n->in(3));
2270 n->del_req(3);
2271 } else if (n->req() == 5) {
2272 n->set_req(1, new BinaryNode(n->in(1), n->in(2)));
2273 n->set_req(2, new BinaryNode(n->in(3), n->in(4)));
2274 n->del_req(4);
2275 n->del_req(3);
2276 } else if (n->req() == 6) {
2277 Node* b3 = new BinaryNode(n->in(4), n->in(5));
2278 Node* b2 = new BinaryNode(n->in(3), b3);
2279 Node* b1 = new BinaryNode(n->in(2), b2);
2280 n->set_req(2, b1);
2281 n->del_req(5);
2282 n->del_req(4);
2283 n->del_req(3);
2284 }
2285 return;
2286 }
2287
2288 switch(opcode) { // Handle some opcodes special
2289 case Op_CompareAndExchangeB:
2290 case Op_CompareAndExchangeS:
2291 case Op_CompareAndExchangeI:
2292 case Op_CompareAndExchangeL:
2293 case Op_CompareAndExchangeP:
2294 case Op_CompareAndExchangeN:
2295 case Op_WeakCompareAndSwapB:
2296 case Op_WeakCompareAndSwapS:
2297 case Op_WeakCompareAndSwapI:
2298 case Op_WeakCompareAndSwapL:
2299 case Op_WeakCompareAndSwapP:
2300 case Op_WeakCompareAndSwapN:
2301 case Op_CompareAndSwapB:
2302 case Op_CompareAndSwapS:
2303 case Op_CompareAndSwapI:
2304 case Op_CompareAndSwapL:
2305 case Op_CompareAndSwapP:
2306 case Op_CompareAndSwapN: { // Convert trinary to binary-tree
2307 Node* newval = n->in(MemNode::ValueIn);
2308 Node* oldval = n->in(LoadStoreConditionalNode::ExpectedIn);
2309 Node* pair = new BinaryNode(oldval, newval);
2310 n->set_req(MemNode::ValueIn, pair);
2311 n->del_req(LoadStoreConditionalNode::ExpectedIn);
2312 break;
2313 }
2314 case Op_CMoveD: // Convert trinary to binary-tree
2315 case Op_CMoveF:
2316 case Op_CMoveI:
2317 case Op_CMoveL:
2318 case Op_CMoveN:
2319 case Op_CMoveP: {
2320 // Restructure into a binary tree for Matching. It's possible that
2321 // we could move this code up next to the graph reshaping for IfNodes
2322 // or vice-versa, but I do not want to debug this for Ladybird.
2323 // 10/2/2000 CNC.
2324 Node* pair1 = new BinaryNode(n->in(1), n->in(1)->in(1));
2325 n->set_req(1, pair1);
2326 Node* pair2 = new BinaryNode(n->in(2), n->in(3));
2327 n->set_req(2, pair2);
2328 n->del_req(3);
2329 break;
2330 }
2331 case Op_MacroLogicV: {
2332 Node* pair1 = new BinaryNode(n->in(1), n->in(2));
2333 Node* pair2 = new BinaryNode(n->in(3), n->in(4));
2334 n->set_req(1, pair1);
2335 n->set_req(2, pair2);
2336 n->del_req(4);
2337 n->del_req(3);
2338 break;
2339 }
2340 case Op_StoreVectorMasked: {
2341 Node* pair = new BinaryNode(n->in(3), n->in(4));
2342 n->set_req(3, pair);
2343 n->del_req(4);
2344 break;
2345 }
2346 case Op_SelectFromTwoVector:
2347 case Op_LoopLimit: {
2348 Node* pair1 = new BinaryNode(n->in(1), n->in(2));
2349 n->set_req(1, pair1);
2350 n->set_req(2, n->in(3));
2351 n->del_req(3);
2352 break;
2353 }
2354 case Op_StrEquals:
2355 case Op_StrIndexOfChar: {
2356 Node* pair1 = new BinaryNode(n->in(2), n->in(3));
2357 n->set_req(2, pair1);
2358 n->set_req(3, n->in(4));
2359 n->del_req(4);
2360 break;
2361 }
2362 case Op_StrComp:
2363 case Op_StrIndexOf:
2364 case Op_VectorizedHashCode: {
2365 Node* pair1 = new BinaryNode(n->in(2), n->in(3));
2366 n->set_req(2, pair1);
2367 Node* pair2 = new BinaryNode(n->in(4),n->in(5));
2368 n->set_req(3, pair2);
2369 n->del_req(5);
2370 n->del_req(4);
2371 break;
2372 }
2373 case Op_EncodeISOArray:
2374 case Op_StrCompressedCopy:
2375 case Op_StrInflatedCopy: {
2376 // Restructure into a binary tree for Matching.
2377 Node* pair = new BinaryNode(n->in(3), n->in(4));
2378 n->set_req(3, pair);
2379 n->del_req(4);
2380 break;
2381 }
2382 case Op_FmaD:
2383 case Op_FmaF:
2384 case Op_FmaHF:
2385 case Op_FmaVD:
2386 case Op_FmaVF:
2387 case Op_FmaVHF: {
2388 // Restructure into a binary tree for Matching.
2389 Node* pair = new BinaryNode(n->in(1), n->in(2));
2390 n->set_req(2, pair);
2391 n->set_req(1, n->in(3));
2392 n->del_req(3);
2393 break;
2394 }
2395 case Op_MulAddS2I: {
2396 Node* pair1 = new BinaryNode(n->in(1), n->in(2));
2397 Node* pair2 = new BinaryNode(n->in(3), n->in(4));
2398 n->set_req(1, pair1);
2399 n->set_req(2, pair2);
2400 n->del_req(4);
2401 n->del_req(3);
2402 break;
2403 }
2404 case Op_ClearArray: {
2405 Node* pair = new BinaryNode(n->in(2), n->in(3));
2406 n->set_req(2, pair);
2407 n->set_req(3, n->in(4));
2408 n->del_req(4);
2409 break;
2410 }
2411 case Op_VectorCmpMasked:
2412 case Op_CopySignD:
2413 case Op_SignumVF:
2414 case Op_SignumVD:
2415 case Op_SignumF:
2416 case Op_SignumD: {
2417 Node* pair = new BinaryNode(n->in(2), n->in(3));
2418 n->set_req(2, pair);
2419 n->del_req(3);
2420 break;
2421 }
2422 case Op_VectorBlend:
2423 case Op_VectorInsert: {
2424 Node* pair = new BinaryNode(n->in(1), n->in(2));
2425 n->set_req(1, pair);
2426 n->set_req(2, n->in(3));
2427 n->del_req(3);
2428 break;
2429 }
2430 case Op_LoadVectorGatherMasked: // fall-through
2431 case Op_StoreVectorScatter: {
2432 Node* pair = new BinaryNode(n->in(MemNode::ValueIn), n->in(MemNode::ValueIn+1));
2433 n->set_req(MemNode::ValueIn, pair);
2434 n->del_req(MemNode::ValueIn+1);
2435 break;
2436 }
2437 case Op_StoreVectorScatterMasked: {
2438 Node* pair = new BinaryNode(n->in(MemNode::ValueIn+1), n->in(MemNode::ValueIn+2));
2439 n->set_req(MemNode::ValueIn+1, pair);
2440 n->del_req(MemNode::ValueIn+2);
2441 pair = new BinaryNode(n->in(MemNode::ValueIn), n->in(MemNode::ValueIn+1));
2442 n->set_req(MemNode::ValueIn, pair);
2443 n->del_req(MemNode::ValueIn+1);
2444 break;
2445 }
2446 case Op_VectorMaskCmp: {
2447 n->set_req(1, new BinaryNode(n->in(1), n->in(2)));
2448 n->set_req(2, n->in(3));
2449 n->del_req(3);
2450 break;
2451 }
2452 case Op_PartialSubtypeCheck: {
2453 if (UseSecondarySupersTable && n->in(2)->is_Con()) {
2454 // PartialSubtypeCheck uses both constant and register operands for superclass input.
2455 n->set_req(2, new BinaryNode(n->in(2), n->in(2)));
2456 break;
2457 }
2458 break;
2459 }
2460 case Op_StoreLSpecial: {
2461 if (n->req() > (MemNode::ValueIn + 1) && n->in(MemNode::ValueIn + 1) != nullptr) {
2462 Node* pair = new BinaryNode(n->in(MemNode::ValueIn), n->in(MemNode::ValueIn + 1));
2463 n->set_req(MemNode::ValueIn, pair);
2464 n->del_req(MemNode::ValueIn + 1);
2465 }
2466 break;
2467 }
2468 default:
2469 break;
2470 }
2471 }
2472
2473 #ifndef PRODUCT
2474 void Matcher::record_new2old(Node* newn, Node* old) {
2475 _new2old_map.map(newn->_idx, old);
2476 if (!_reused.test_set(old->_igv_idx)) {
2477 // Reuse the Ideal-level IGV identifier so that the node can be tracked
2478 // across matching. If there are multiple machine nodes expanded from the
2479 // same Ideal node, only one will reuse its IGV identifier.
2480 newn->_igv_idx = old->_igv_idx;
2481 }
2482 }
2483
2484 // machine-independent root to machine-dependent root
2485 void Matcher::dump_old2new_map() {
2486 _old2new_map.dump();
2487 }
2488 #endif // !PRODUCT
2489
2490 //---------------------------collect_null_checks-------------------------------
2491 // Find null checks in the ideal graph; write a machine-specific node for
2492 // it. Used by later implicit-null-check handling. Actually collects
2493 // either an IfTrue or IfFalse for the common NOT-null path, AND the ideal
2494 // value being tested.
2495 void Matcher::collect_null_checks( Node *proj, Node *orig_proj ) {
2496 Node *iff = proj->in(0);
2497 if( iff->Opcode() == Op_If ) {
2498 // During matching If's have Bool & Cmp side-by-side
2499 BoolNode *b = iff->in(1)->as_Bool();
2500 Node *cmp = iff->in(2);
2501 int opc = cmp->Opcode();
2502 if (opc != Op_CmpP && opc != Op_CmpN) return;
2503
2504 const Type* ct = cmp->in(2)->bottom_type();
2505 if (ct == TypePtr::NULL_PTR ||
2506 (opc == Op_CmpN && ct == TypeNarrowOop::NULL_PTR)) {
2507
2508 bool push_it = false;
2509 if( proj->Opcode() == Op_IfTrue ) {
2510 #ifndef PRODUCT
2511 extern uint all_null_checks_found;
2512 all_null_checks_found++;
2513 #endif
2514 if( b->_test._test == BoolTest::ne ) {
2515 push_it = true;
2516 }
2517 } else {
2518 assert( proj->Opcode() == Op_IfFalse, "" );
2519 if( b->_test._test == BoolTest::eq ) {
2520 push_it = true;
2521 }
2522 }
2523 if( push_it ) {
2524 _null_check_tests.push(proj);
2525 Node* val = cmp->in(1);
2526 #ifdef _LP64
2527 if (val->bottom_type()->isa_narrowoop() &&
2528 !Matcher::narrow_oop_use_complex_address()) {
2529 //
2530 // Look for DecodeN node which should be pinned to orig_proj.
2531 // On platforms (Sparc) which can not handle 2 adds
2532 // in addressing mode we have to keep a DecodeN node and
2533 // use it to do implicit null check in address.
2534 //
2535 // DecodeN node was pinned to non-null path (orig_proj) during
2536 // CastPP transformation in final_graph_reshaping_impl().
2537 //
2538 uint cnt = orig_proj->outcnt();
2539 for (uint i = 0; i < orig_proj->outcnt(); i++) {
2540 Node* d = orig_proj->raw_out(i);
2541 if (d->is_DecodeN() && d->in(1) == val) {
2542 val = d;
2543 val->set_req(0, nullptr); // Unpin now.
2544 // Mark this as special case to distinguish from
2545 // a regular case: CmpP(DecodeN, null).
2546 val = (Node*)(((intptr_t)val) | 1);
2547 break;
2548 }
2549 }
2550 }
2551 #endif
2552 _null_check_tests.push(val);
2553 }
2554 }
2555 }
2556 }
2557
2558 //---------------------------validate_null_checks------------------------------
2559 // Its possible that the value being null checked is not the root of a match
2560 // tree. If so, I cannot use the value in an implicit null check.
2561 void Matcher::validate_null_checks( ) {
2562 uint cnt = _null_check_tests.size();
2563 for( uint i=0; i < cnt; i+=2 ) {
2564 Node *test = _null_check_tests[i];
2565 Node *val = _null_check_tests[i+1];
2566 bool is_decoden = ((intptr_t)val) & 1;
2567 val = (Node*)(((intptr_t)val) & ~1);
2568 if (has_new_node(val)) {
2569 Node* new_val = new_node(val);
2570 if (is_decoden) {
2571 assert(val->is_DecodeNarrowPtr() && val->in(0) == nullptr, "sanity");
2572 // Note: new_val may have a control edge if
2573 // the original ideal node DecodeN was matched before
2574 // it was unpinned in Matcher::collect_null_checks().
2575 // Unpin the mach node and mark it.
2576 new_val->set_req(0, nullptr);
2577 new_val = (Node*)(((intptr_t)new_val) | 1);
2578 }
2579 // Is a match-tree root, so replace with the matched value
2580 _null_check_tests.map(i+1, new_val);
2581 } else {
2582 // Yank from candidate list
2583 _null_check_tests.map(i+1,_null_check_tests[--cnt]);
2584 _null_check_tests.map(i,_null_check_tests[--cnt]);
2585 _null_check_tests.pop();
2586 _null_check_tests.pop();
2587 i-=2;
2588 }
2589 }
2590 }
2591
2592 bool Matcher::gen_narrow_oop_implicit_null_checks() {
2593 // Advice matcher to perform null checks on the narrow oop side.
2594 // Implicit checks are not possible on the uncompressed oop side anyway
2595 // (at least not for read accesses).
2596 // Performs significantly better (especially on Power 6).
2597 if (!os::zero_page_read_protected()) {
2598 return true;
2599 }
2600 return CompressedOops::use_implicit_null_checks() &&
2601 (narrow_oop_use_complex_address() ||
2602 CompressedOops::base() != nullptr);
2603 }
2604
2605 // Compute RegMask for an ideal register.
2606 const RegMask* Matcher::regmask_for_ideal_register(uint ideal_reg, Node* ret) {
2607 assert(!C->failing_internal() || C->failure_is_artificial(), "already failing.");
2608 if (C->failing()) {
2609 return nullptr;
2610 }
2611 const Type* t = Type::mreg2type[ideal_reg];
2612 if (t == nullptr) {
2613 assert(ideal_reg >= Op_VecA && ideal_reg <= Op_VecZ, "not a vector: %d", ideal_reg);
2614 return nullptr; // not supported
2615 }
2616 Node* fp = ret->in(TypeFunc::FramePtr);
2617 Node* mem = ret->in(TypeFunc::Memory);
2618 const TypePtr* atp = TypePtr::BOTTOM;
2619 MemNode::MemOrd mo = MemNode::unordered;
2620
2621 Node* spill;
2622 switch (ideal_reg) {
2623 case Op_RegN: spill = new LoadNNode(nullptr, mem, fp, atp, t->is_narrowoop(), mo); break;
2624 case Op_RegI: spill = new LoadINode(nullptr, mem, fp, atp, t->is_int(), mo); break;
2625 case Op_RegP: spill = new LoadPNode(nullptr, mem, fp, atp, t->is_ptr(), mo); break;
2626 case Op_RegF: spill = new LoadFNode(nullptr, mem, fp, atp, t, mo); break;
2627 case Op_RegD: spill = new LoadDNode(nullptr, mem, fp, atp, t, mo); break;
2628 case Op_RegL: spill = new LoadLNode(nullptr, mem, fp, atp, t->is_long(), mo); break;
2629
2630 case Op_VecA: // fall-through
2631 case Op_VecS: // fall-through
2632 case Op_VecD: // fall-through
2633 case Op_VecX: // fall-through
2634 case Op_VecY: // fall-through
2635 case Op_VecZ: spill = new LoadVectorNode(nullptr, mem, fp, atp, t->is_vect()); break;
2636 case Op_RegVectMask: return Matcher::predicate_reg_mask();
2637
2638 default: ShouldNotReachHere();
2639 }
2640 MachNode* mspill = match_tree(spill);
2641 assert(mspill != nullptr || C->failure_is_artificial(), "matching failed: %d", ideal_reg);
2642 if (C->failing()) {
2643 return nullptr;
2644 }
2645 // Handle generic vector operand case
2646 if (Matcher::supports_generic_vector_operands && t->isa_vect()) {
2647 specialize_mach_node(mspill);
2648 }
2649 return &mspill->out_RegMask();
2650 }
2651
2652 // Process Mach IR right after selection phase is over.
2653 void Matcher::do_postselect_cleanup() {
2654 if (supports_generic_vector_operands) {
2655 specialize_generic_vector_operands();
2656 if (C->failing()) return;
2657 }
2658 }
2659
2660 //----------------------------------------------------------------------
2661 // Generic machine operands elision.
2662 //----------------------------------------------------------------------
2663
2664 // Compute concrete vector operand for a generic TEMP vector mach node based on its user info.
2665 void Matcher::specialize_temp_node(MachTempNode* tmp, MachNode* use, uint idx) {
2666 assert(use->in(idx) == tmp, "not a user");
2667 assert(!Matcher::is_generic_vector(use->_opnds[0]), "use not processed yet");
2668
2669 if ((uint)idx == use->two_adr()) { // DEF_TEMP case
2670 tmp->_opnds[0] = use->_opnds[0]->clone();
2671 } else {
2672 uint ideal_vreg = vector_ideal_reg(C->max_vector_size());
2673 tmp->_opnds[0] = Matcher::pd_specialize_generic_vector_operand(tmp->_opnds[0], ideal_vreg, true /*is_temp*/);
2674 }
2675 }
2676
2677 // Compute concrete vector operand for a generic DEF/USE vector operand (of mach node m at index idx).
2678 MachOper* Matcher::specialize_vector_operand(MachNode* m, uint opnd_idx) {
2679 assert(Matcher::is_generic_vector(m->_opnds[opnd_idx]), "repeated updates");
2680 Node* def = nullptr;
2681 if (opnd_idx == 0) { // DEF
2682 def = m; // use mach node itself to compute vector operand type
2683 } else {
2684 int base_idx = m->operand_index(opnd_idx);
2685 def = m->in(base_idx);
2686 if (def->is_Mach()) {
2687 if (def->is_MachTemp() && Matcher::is_generic_vector(def->as_Mach()->_opnds[0])) {
2688 specialize_temp_node(def->as_MachTemp(), m, base_idx); // MachTemp node use site
2689 } else if (is_reg2reg_move(def->as_Mach())) {
2690 def = def->in(1); // skip over generic reg-to-reg moves
2691 }
2692 }
2693 }
2694 assert(def->bottom_type()->isa_vect(), "not a vector");
2695 uint ideal_vreg = def->bottom_type()->ideal_reg();
2696 return Matcher::pd_specialize_generic_vector_operand(m->_opnds[opnd_idx], ideal_vreg, false /*is_temp*/);
2697 }
2698
2699 void Matcher::specialize_mach_node(MachNode* m) {
2700 assert(!m->is_MachTemp(), "processed along with its user");
2701 // For generic use operands pull specific register class operands from
2702 // its def instruction's output operand (def operand).
2703 for (uint i = 0; i < m->num_opnds(); i++) {
2704 if (Matcher::is_generic_vector(m->_opnds[i])) {
2705 m->_opnds[i] = specialize_vector_operand(m, i);
2706 }
2707 }
2708 }
2709
2710 // Replace generic vector operands with concrete vector operands and eliminate generic reg-to-reg moves from the graph.
2711 void Matcher::specialize_generic_vector_operands() {
2712 assert(supports_generic_vector_operands, "sanity");
2713 ResourceMark rm;
2714
2715 // Replace generic vector operands (vec/legVec) with concrete ones (vec[SDXYZ]/legVec[SDXYZ])
2716 // and remove reg-to-reg vector moves (MoveVec2Leg and MoveLeg2Vec).
2717 Unique_Node_List live_nodes;
2718 C->identify_useful_nodes(live_nodes);
2719
2720 while (live_nodes.size() > 0) {
2721 MachNode* m = live_nodes.pop()->isa_Mach();
2722 if (m != nullptr) {
2723 if (Matcher::is_reg2reg_move(m)) {
2724 // Register allocator properly handles vec <=> leg moves using register masks.
2725 int opnd_idx = m->operand_index(1);
2726 Node* def = m->in(opnd_idx);
2727 m->subsume_by(def, C);
2728 } else if (m->is_MachTemp()) {
2729 // process MachTemp nodes at use site (see Matcher::specialize_vector_operand)
2730 } else {
2731 specialize_mach_node(m);
2732 }
2733 }
2734 }
2735 }
2736
2737 uint Matcher::vector_length(const Node* n) {
2738 const TypeVect* vt = n->bottom_type()->is_vect();
2739 return vt->length();
2740 }
2741
2742 uint Matcher::vector_length(const MachNode* use, const MachOper* opnd) {
2743 int def_idx = use->operand_index(opnd);
2744 Node* def = use->in(def_idx);
2745 return def->bottom_type()->is_vect()->length();
2746 }
2747
2748 uint Matcher::vector_length_in_bytes(const Node* n) {
2749 const TypeVect* vt = n->bottom_type()->is_vect();
2750 return vt->length_in_bytes();
2751 }
2752
2753 uint Matcher::vector_length_in_bytes(const MachNode* use, const MachOper* opnd) {
2754 uint def_idx = use->operand_index(opnd);
2755 Node* def = use->in(def_idx);
2756 return def->bottom_type()->is_vect()->length_in_bytes();
2757 }
2758
2759 BasicType Matcher::vector_element_basic_type(const Node* n) {
2760 const TypeVect* vt = n->bottom_type()->is_vect();
2761 return vt->element_basic_type();
2762 }
2763
2764 BasicType Matcher::vector_element_basic_type(const MachNode* use, const MachOper* opnd) {
2765 int def_idx = use->operand_index(opnd);
2766 Node* def = use->in(def_idx);
2767 return def->bottom_type()->is_vect()->element_basic_type();
2768 }
2769
2770 bool Matcher::is_non_long_integral_vector(const Node* n) {
2771 BasicType bt = vector_element_basic_type(n);
2772 assert(bt != T_CHAR, "char is not allowed in vector");
2773 return is_subword_type(bt) || bt == T_INT;
2774 }
2775
2776 bool Matcher::is_encode_and_store_pattern(const Node* n, const Node* m) {
2777 if (n == nullptr ||
2778 m == nullptr ||
2779 n->Opcode() != Op_StoreN ||
2780 !m->is_EncodeP() ||
2781 n->as_Store()->barrier_data() == 0) {
2782 return false;
2783 }
2784 assert(m == n->in(MemNode::ValueIn), "m should be input to n");
2785 return true;
2786 }
2787
2788 #ifdef ASSERT
2789 bool Matcher::verify_after_postselect_cleanup() {
2790 assert(!C->failing_internal() || C->failure_is_artificial(), "sanity");
2791 if (supports_generic_vector_operands) {
2792 Unique_Node_List useful;
2793 C->identify_useful_nodes(useful);
2794 for (uint i = 0; i < useful.size(); i++) {
2795 MachNode* m = useful.at(i)->isa_Mach();
2796 if (m != nullptr) {
2797 assert(!Matcher::is_reg2reg_move(m), "no MoveVec nodes allowed");
2798 for (uint j = 0; j < m->num_opnds(); j++) {
2799 assert(!Matcher::is_generic_vector(m->_opnds[j]), "no generic vector operands allowed");
2800 }
2801 }
2802 }
2803 }
2804 return true;
2805 }
2806 #endif // ASSERT
2807
2808 // Used by the DFA in dfa_xxx.cpp. Check for a following barrier or
2809 // atomic instruction acting as a store_load barrier without any
2810 // intervening volatile load, and thus we don't need a barrier here.
2811 // We retain the Node to act as a compiler ordering barrier.
2812 bool Matcher::post_store_load_barrier(const Node* vmb) {
2813 Compile* C = Compile::current();
2814 assert(vmb->is_MemBar(), "");
2815 assert(vmb->Opcode() != Op_MemBarAcquire && vmb->Opcode() != Op_LoadFence, "");
2816 const MemBarNode* membar = vmb->as_MemBar();
2817
2818 // Get the Ideal Proj node, ctrl, that can be used to iterate forward
2819 Node* ctrl = nullptr;
2820 for (DUIterator_Fast imax, i = membar->fast_outs(imax); i < imax; i++) {
2821 Node* p = membar->fast_out(i);
2822 assert(p->is_Proj(), "only projections here");
2823 if ((p->as_Proj()->_con == TypeFunc::Control) &&
2824 !C->node_arena()->contains(p)) { // Unmatched old-space only
2825 ctrl = p;
2826 break;
2827 }
2828 }
2829 assert((ctrl != nullptr), "missing control projection");
2830
2831 for (DUIterator_Fast jmax, j = ctrl->fast_outs(jmax); j < jmax; j++) {
2832 Node *x = ctrl->fast_out(j);
2833 int xop = x->Opcode();
2834
2835 // We don't need current barrier if we see another or a lock
2836 // before seeing volatile load.
2837 //
2838 // Op_Fastunlock previously appeared in the Op_* list below.
2839 // With the advent of 1-0 lock operations we're no longer guaranteed
2840 // that a monitor exit operation contains a serializing instruction.
2841
2842 if (xop == Op_MemBarVolatile ||
2843 xop == Op_CompareAndExchangeB ||
2844 xop == Op_CompareAndExchangeS ||
2845 xop == Op_CompareAndExchangeI ||
2846 xop == Op_CompareAndExchangeL ||
2847 xop == Op_CompareAndExchangeP ||
2848 xop == Op_CompareAndExchangeN ||
2849 xop == Op_WeakCompareAndSwapB ||
2850 xop == Op_WeakCompareAndSwapS ||
2851 xop == Op_WeakCompareAndSwapL ||
2852 xop == Op_WeakCompareAndSwapP ||
2853 xop == Op_WeakCompareAndSwapN ||
2854 xop == Op_WeakCompareAndSwapI ||
2855 xop == Op_CompareAndSwapB ||
2856 xop == Op_CompareAndSwapS ||
2857 xop == Op_CompareAndSwapL ||
2858 xop == Op_CompareAndSwapP ||
2859 xop == Op_CompareAndSwapN ||
2860 xop == Op_CompareAndSwapI ||
2861 BarrierSet::barrier_set()->barrier_set_c2()->matcher_is_store_load_barrier(x, xop)) {
2862 return true;
2863 }
2864
2865 // Op_FastLock previously appeared in the Op_* list above.
2866 if (xop == Op_FastLock) {
2867 return true;
2868 }
2869
2870 if (x->is_MemBar()) {
2871 // We must retain this membar if there is an upcoming volatile
2872 // load, which will be followed by acquire membar.
2873 if (xop == Op_MemBarAcquire || xop == Op_LoadFence) {
2874 return false;
2875 } else {
2876 // For other kinds of barriers, check by pretending we
2877 // are them, and seeing if we can be removed.
2878 return post_store_load_barrier(x->as_MemBar());
2879 }
2880 }
2881
2882 // probably not necessary to check for these
2883 if (x->is_Call() || x->is_SafePoint() || x->is_block_proj()) {
2884 return false;
2885 }
2886 }
2887 return false;
2888 }
2889
2890 // Check whether node n is a branch to an uncommon trap that we could
2891 // optimize as test with very high branch costs in case of going to
2892 // the uncommon trap. The code must be able to be recompiled to use
2893 // a cheaper test.
2894 bool Matcher::branches_to_uncommon_trap(const Node *n) {
2895 // Don't do it for natives, adapters, or runtime stubs
2896 Compile *C = Compile::current();
2897 if (!C->is_method_compilation()) return false;
2898
2899 assert(n->is_If(), "You should only call this on if nodes.");
2900 IfNode *ifn = n->as_If();
2901
2902 Node *ifFalse = nullptr;
2903 for (DUIterator_Fast imax, i = ifn->fast_outs(imax); i < imax; i++) {
2904 if (ifn->fast_out(i)->is_IfFalse()) {
2905 ifFalse = ifn->fast_out(i);
2906 break;
2907 }
2908 }
2909 assert(ifFalse, "An If should have an ifFalse. Graph is broken.");
2910
2911 Node *reg = ifFalse;
2912 int cnt = 4; // We must protect against cycles. Limit to 4 iterations.
2913 // Alternatively use visited set? Seems too expensive.
2914 while (reg != nullptr && cnt > 0) {
2915 CallNode *call = nullptr;
2916 RegionNode *nxt_reg = nullptr;
2917 for (DUIterator_Fast imax, i = reg->fast_outs(imax); i < imax; i++) {
2918 Node *o = reg->fast_out(i);
2919 if (o->is_Call()) {
2920 call = o->as_Call();
2921 }
2922 if (o->is_Region()) {
2923 nxt_reg = o->as_Region();
2924 }
2925 }
2926
2927 if (call &&
2928 call->entry_point() == OptoRuntime::uncommon_trap_blob()->entry_point()) {
2929 const Type* trtype = call->in(TypeFunc::Parms)->bottom_type();
2930 if (trtype->isa_int() && trtype->is_int()->is_con()) {
2931 jint tr_con = trtype->is_int()->get_con();
2932 Deoptimization::DeoptReason reason = Deoptimization::trap_request_reason(tr_con);
2933 Deoptimization::DeoptAction action = Deoptimization::trap_request_action(tr_con);
2934 assert((int)reason < (int)BitsPerInt, "recode bit map");
2935
2936 if (is_set_nth_bit(C->allowed_deopt_reasons(), (int)reason)
2937 && action != Deoptimization::Action_none) {
2938 // This uncommon trap is sure to recompile, eventually.
2939 // When that happens, C->too_many_traps will prevent
2940 // this transformation from happening again.
2941 return true;
2942 }
2943 }
2944 }
2945
2946 reg = nxt_reg;
2947 cnt--;
2948 }
2949
2950 return false;
2951 }
2952
2953 //=============================================================================
2954 //---------------------------State---------------------------------------------
2955 State::State(void) : _rule() {
2956 #ifdef ASSERT
2957 _id = 0;
2958 _kids[0] = _kids[1] = (State*)(intptr_t) CONST64(0xcafebabecafebabe);
2959 _leaf = (Node*)(intptr_t) CONST64(0xbaadf00dbaadf00d);
2960 #endif
2961 }
2962
2963 #ifdef ASSERT
2964 State::~State() {
2965 _id = 99;
2966 _kids[0] = _kids[1] = (State*)(intptr_t) CONST64(0xcafebabecafebabe);
2967 _leaf = (Node*)(intptr_t) CONST64(0xbaadf00dbaadf00d);
2968 memset(_cost, -3, sizeof(_cost));
2969 memset(_rule, -3, sizeof(_rule));
2970 }
2971 #endif
2972
2973 #ifndef PRODUCT
2974 //---------------------------dump----------------------------------------------
2975 void State::dump() {
2976 tty->print("\n");
2977 dump(0);
2978 }
2979
2980 void State::dump(int depth) {
2981 for (int j = 0; j < depth; j++) {
2982 tty->print(" ");
2983 }
2984 tty->print("--N: ");
2985 _leaf->dump();
2986 uint i;
2987 for (i = 0; i < _LAST_MACH_OPER; i++) {
2988 // Check for valid entry
2989 if (valid(i)) {
2990 for (int j = 0; j < depth; j++) {
2991 tty->print(" ");
2992 }
2993 assert(cost(i) != max_juint, "cost must be a valid value");
2994 assert(rule(i) < _last_Mach_Node, "rule[i] must be valid rule");
2995 tty->print_cr("%s %d %s",
2996 ruleName[i], cost(i), ruleName[rule(i)] );
2997 }
2998 }
2999 tty->cr();
3000
3001 for (i = 0; i < 2; i++) {
3002 if (_kids[i]) {
3003 _kids[i]->dump(depth + 1);
3004 }
3005 }
3006 }
3007 #endif