Fri, 15 Jun 2012 01:25:19 -0700
7119644: Increase superword's vector size up to 256 bits
Summary: Increase vector size up to 256-bits for YMM AVX registers on x86.
Reviewed-by: never, twisti, roland
1 /*
2 * Copyright (c) 2007, 2012, 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 */
24 #include "precompiled.hpp"
25 #include "compiler/compileLog.hpp"
26 #include "libadt/vectset.hpp"
27 #include "memory/allocation.inline.hpp"
28 #include "opto/addnode.hpp"
29 #include "opto/callnode.hpp"
30 #include "opto/divnode.hpp"
31 #include "opto/matcher.hpp"
32 #include "opto/memnode.hpp"
33 #include "opto/mulnode.hpp"
34 #include "opto/opcodes.hpp"
35 #include "opto/superword.hpp"
36 #include "opto/vectornode.hpp"
38 //
39 // S U P E R W O R D T R A N S F O R M
40 //=============================================================================
42 //------------------------------SuperWord---------------------------
43 SuperWord::SuperWord(PhaseIdealLoop* phase) :
44 _phase(phase),
45 _igvn(phase->_igvn),
46 _arena(phase->C->comp_arena()),
47 _packset(arena(), 8, 0, NULL), // packs for the current block
48 _bb_idx(arena(), (int)(1.10 * phase->C->unique()), 0, 0), // node idx to index in bb
49 _block(arena(), 8, 0, NULL), // nodes in current block
50 _data_entry(arena(), 8, 0, NULL), // nodes with all inputs from outside
51 _mem_slice_head(arena(), 8, 0, NULL), // memory slice heads
52 _mem_slice_tail(arena(), 8, 0, NULL), // memory slice tails
53 _node_info(arena(), 8, 0, SWNodeInfo::initial), // info needed per node
54 _align_to_ref(NULL), // memory reference to align vectors to
55 _disjoint_ptrs(arena(), 8, 0, OrderedPair::initial), // runtime disambiguated pointer pairs
56 _dg(_arena), // dependence graph
57 _visited(arena()), // visited node set
58 _post_visited(arena()), // post visited node set
59 _n_idx_list(arena(), 8), // scratch list of (node,index) pairs
60 _stk(arena(), 8, 0, NULL), // scratch stack of nodes
61 _nlist(arena(), 8, 0, NULL), // scratch list of nodes
62 _lpt(NULL), // loop tree node
63 _lp(NULL), // LoopNode
64 _bb(NULL), // basic block
65 _iv(NULL) // induction var
66 {}
68 //------------------------------transform_loop---------------------------
69 void SuperWord::transform_loop(IdealLoopTree* lpt) {
70 assert(UseSuperWord, "should be");
71 // Do vectors exist on this architecture?
72 if (Matcher::vector_width_in_bytes(T_BYTE) < 2) return;
74 assert(lpt->_head->is_CountedLoop(), "must be");
75 CountedLoopNode *cl = lpt->_head->as_CountedLoop();
77 if (!cl->is_valid_counted_loop()) return; // skip malformed counted loop
79 if (!cl->is_main_loop() ) return; // skip normal, pre, and post loops
81 // Check for no control flow in body (other than exit)
82 Node *cl_exit = cl->loopexit();
83 if (cl_exit->in(0) != lpt->_head) return;
85 // Make sure the are no extra control users of the loop backedge
86 if (cl->back_control()->outcnt() != 1) {
87 return;
88 }
90 // Check for pre-loop ending with CountedLoopEnd(Bool(Cmp(x,Opaque1(limit))))
91 CountedLoopEndNode* pre_end = get_pre_loop_end(cl);
92 if (pre_end == NULL) return;
93 Node *pre_opaq1 = pre_end->limit();
94 if (pre_opaq1->Opcode() != Op_Opaque1) return;
96 init(); // initialize data structures
98 set_lpt(lpt);
99 set_lp(cl);
101 // For now, define one block which is the entire loop body
102 set_bb(cl);
104 assert(_packset.length() == 0, "packset must be empty");
105 SLP_extract();
106 }
108 //------------------------------SLP_extract---------------------------
109 // Extract the superword level parallelism
110 //
111 // 1) A reverse post-order of nodes in the block is constructed. By scanning
112 // this list from first to last, all definitions are visited before their uses.
113 //
114 // 2) A point-to-point dependence graph is constructed between memory references.
115 // This simplies the upcoming "independence" checker.
116 //
117 // 3) The maximum depth in the node graph from the beginning of the block
118 // to each node is computed. This is used to prune the graph search
119 // in the independence checker.
120 //
121 // 4) For integer types, the necessary bit width is propagated backwards
122 // from stores to allow packed operations on byte, char, and short
123 // integers. This reverses the promotion to type "int" that javac
124 // did for operations like: char c1,c2,c3; c1 = c2 + c3.
125 //
126 // 5) One of the memory references is picked to be an aligned vector reference.
127 // The pre-loop trip count is adjusted to align this reference in the
128 // unrolled body.
129 //
130 // 6) The initial set of pack pairs is seeded with memory references.
131 //
132 // 7) The set of pack pairs is extended by following use->def and def->use links.
133 //
134 // 8) The pairs are combined into vector sized packs.
135 //
136 // 9) Reorder the memory slices to co-locate members of the memory packs.
137 //
138 // 10) Generate ideal vector nodes for the final set of packs and where necessary,
139 // inserting scalar promotion, vector creation from multiple scalars, and
140 // extraction of scalar values from vectors.
141 //
142 void SuperWord::SLP_extract() {
144 // Ready the block
146 construct_bb();
148 dependence_graph();
150 compute_max_depth();
152 compute_vector_element_type();
154 // Attempt vectorization
156 find_adjacent_refs();
158 extend_packlist();
160 combine_packs();
162 construct_my_pack_map();
164 filter_packs();
166 schedule();
168 output();
169 }
171 //------------------------------find_adjacent_refs---------------------------
172 // Find the adjacent memory references and create pack pairs for them.
173 // This is the initial set of packs that will then be extended by
174 // following use->def and def->use links. The align positions are
175 // assigned relative to the reference "align_to_ref"
176 void SuperWord::find_adjacent_refs() {
177 // Get list of memory operations
178 Node_List memops;
179 for (int i = 0; i < _block.length(); i++) {
180 Node* n = _block.at(i);
181 if (n->is_Mem() && !n->is_LoadStore() && in_bb(n) &&
182 is_java_primitive(n->as_Mem()->memory_type())) {
183 int align = memory_alignment(n->as_Mem(), 0);
184 if (align != bottom_align) {
185 memops.push(n);
186 }
187 }
188 }
190 Node_List align_to_refs;
191 int best_iv_adjustment = 0;
192 MemNode* best_align_to_mem_ref = NULL;
194 while (memops.size() != 0) {
195 // Find a memory reference to align to.
196 MemNode* mem_ref = find_align_to_ref(memops);
197 if (mem_ref == NULL) break;
198 align_to_refs.push(mem_ref);
199 int iv_adjustment = get_iv_adjustment(mem_ref);
201 if (best_align_to_mem_ref == NULL) {
202 // Set memory reference which is the best from all memory operations
203 // to be used for alignment. The pre-loop trip count is modified to align
204 // this reference to a vector-aligned address.
205 best_align_to_mem_ref = mem_ref;
206 best_iv_adjustment = iv_adjustment;
207 }
209 SWPointer align_to_ref_p(mem_ref, this);
210 // Set alignment relative to "align_to_ref" for all related memory operations.
211 for (int i = memops.size() - 1; i >= 0; i--) {
212 MemNode* s = memops.at(i)->as_Mem();
213 if (isomorphic(s, mem_ref)) {
214 SWPointer p2(s, this);
215 if (p2.comparable(align_to_ref_p)) {
216 int align = memory_alignment(s, iv_adjustment);
217 set_alignment(s, align);
218 }
219 }
220 }
222 // Create initial pack pairs of memory operations for which
223 // alignment is set and vectors will be aligned.
224 bool create_pack = true;
225 if (memory_alignment(mem_ref, best_iv_adjustment) != 0) {
226 if (same_velt_type(mem_ref, best_align_to_mem_ref)) {
227 // Can't allow vectorization of unaligned memory accesses with the
228 // same type since it could be overlapped accesses to the same array.
229 create_pack = false;
230 } else {
231 // Allow independent (different type) unaligned memory operations
232 // if HW supports them.
233 if (!Matcher::misaligned_vectors_ok()) {
234 create_pack = false;
235 } else {
236 // Check if packs of the same memory type but
237 // with a different alignment were created before.
238 for (uint i = 0; i < align_to_refs.size(); i++) {
239 MemNode* mr = align_to_refs.at(i)->as_Mem();
240 if (same_velt_type(mr, mem_ref) &&
241 memory_alignment(mr, iv_adjustment) != 0)
242 create_pack = false;
243 }
244 }
245 }
246 }
247 if (create_pack) {
248 for (uint i = 0; i < memops.size(); i++) {
249 Node* s1 = memops.at(i);
250 int align = alignment(s1);
251 if (align == top_align) continue;
252 for (uint j = 0; j < memops.size(); j++) {
253 Node* s2 = memops.at(j);
254 if (alignment(s2) == top_align) continue;
255 if (s1 != s2 && are_adjacent_refs(s1, s2)) {
256 if (stmts_can_pack(s1, s2, align)) {
257 Node_List* pair = new Node_List();
258 pair->push(s1);
259 pair->push(s2);
260 _packset.append(pair);
261 }
262 }
263 }
264 }
265 } else { // Don't create unaligned pack
266 // First, remove remaining memory ops of the same type from the list.
267 for (int i = memops.size() - 1; i >= 0; i--) {
268 MemNode* s = memops.at(i)->as_Mem();
269 if (same_velt_type(s, mem_ref)) {
270 memops.remove(i);
271 }
272 }
274 // Second, remove already constructed packs of the same type.
275 for (int i = _packset.length() - 1; i >= 0; i--) {
276 Node_List* p = _packset.at(i);
277 MemNode* s = p->at(0)->as_Mem();
278 if (same_velt_type(s, mem_ref)) {
279 remove_pack_at(i);
280 }
281 }
283 // If needed find the best memory reference for loop alignment again.
284 if (same_velt_type(mem_ref, best_align_to_mem_ref)) {
285 // Put memory ops from remaining packs back on memops list for
286 // the best alignment search.
287 uint orig_msize = memops.size();
288 for (int i = 0; i < _packset.length(); i++) {
289 Node_List* p = _packset.at(i);
290 MemNode* s = p->at(0)->as_Mem();
291 assert(!same_velt_type(s, mem_ref), "sanity");
292 memops.push(s);
293 }
294 MemNode* best_align_to_mem_ref = find_align_to_ref(memops);
295 if (best_align_to_mem_ref == NULL) break;
296 best_iv_adjustment = get_iv_adjustment(best_align_to_mem_ref);
297 // Restore list.
298 while (memops.size() > orig_msize)
299 (void)memops.pop();
300 }
301 } // unaligned memory accesses
303 // Remove used mem nodes.
304 for (int i = memops.size() - 1; i >= 0; i--) {
305 MemNode* m = memops.at(i)->as_Mem();
306 if (alignment(m) != top_align) {
307 memops.remove(i);
308 }
309 }
311 } // while (memops.size() != 0
312 set_align_to_ref(best_align_to_mem_ref);
314 #ifndef PRODUCT
315 if (TraceSuperWord) {
316 tty->print_cr("\nAfter find_adjacent_refs");
317 print_packset();
318 }
319 #endif
320 }
322 //------------------------------find_align_to_ref---------------------------
323 // Find a memory reference to align the loop induction variable to.
324 // Looks first at stores then at loads, looking for a memory reference
325 // with the largest number of references similar to it.
326 MemNode* SuperWord::find_align_to_ref(Node_List &memops) {
327 GrowableArray<int> cmp_ct(arena(), memops.size(), memops.size(), 0);
329 // Count number of comparable memory ops
330 for (uint i = 0; i < memops.size(); i++) {
331 MemNode* s1 = memops.at(i)->as_Mem();
332 SWPointer p1(s1, this);
333 // Discard if pre loop can't align this reference
334 if (!ref_is_alignable(p1)) {
335 *cmp_ct.adr_at(i) = 0;
336 continue;
337 }
338 for (uint j = i+1; j < memops.size(); j++) {
339 MemNode* s2 = memops.at(j)->as_Mem();
340 if (isomorphic(s1, s2)) {
341 SWPointer p2(s2, this);
342 if (p1.comparable(p2)) {
343 (*cmp_ct.adr_at(i))++;
344 (*cmp_ct.adr_at(j))++;
345 }
346 }
347 }
348 }
350 // Find Store (or Load) with the greatest number of "comparable" references,
351 // biggest vector size, smallest data size and smallest iv offset.
352 int max_ct = 0;
353 int max_vw = 0;
354 int max_idx = -1;
355 int min_size = max_jint;
356 int min_iv_offset = max_jint;
357 for (uint j = 0; j < memops.size(); j++) {
358 MemNode* s = memops.at(j)->as_Mem();
359 if (s->is_Store()) {
360 int vw = vector_width_in_bytes(velt_basic_type(s));
361 assert(vw > 1, "sanity");
362 SWPointer p(s, this);
363 if (cmp_ct.at(j) > max_ct ||
364 cmp_ct.at(j) == max_ct &&
365 (vw > max_vw ||
366 vw == max_vw &&
367 (data_size(s) < min_size ||
368 data_size(s) == min_size &&
369 (p.offset_in_bytes() < min_iv_offset)))) {
370 max_ct = cmp_ct.at(j);
371 max_vw = vw;
372 max_idx = j;
373 min_size = data_size(s);
374 min_iv_offset = p.offset_in_bytes();
375 }
376 }
377 }
378 // If no stores, look at loads
379 if (max_ct == 0) {
380 for (uint j = 0; j < memops.size(); j++) {
381 MemNode* s = memops.at(j)->as_Mem();
382 if (s->is_Load()) {
383 int vw = vector_width_in_bytes(velt_basic_type(s));
384 assert(vw > 1, "sanity");
385 SWPointer p(s, this);
386 if (cmp_ct.at(j) > max_ct ||
387 cmp_ct.at(j) == max_ct &&
388 (vw > max_vw ||
389 vw == max_vw &&
390 (data_size(s) < min_size ||
391 data_size(s) == min_size &&
392 (p.offset_in_bytes() < min_iv_offset)))) {
393 max_ct = cmp_ct.at(j);
394 max_vw = vw;
395 max_idx = j;
396 min_size = data_size(s);
397 min_iv_offset = p.offset_in_bytes();
398 }
399 }
400 }
401 }
403 #ifdef ASSERT
404 if (TraceSuperWord && Verbose) {
405 tty->print_cr("\nVector memops after find_align_to_refs");
406 for (uint i = 0; i < memops.size(); i++) {
407 MemNode* s = memops.at(i)->as_Mem();
408 s->dump();
409 }
410 }
411 #endif
413 if (max_ct > 0) {
414 #ifdef ASSERT
415 if (TraceSuperWord) {
416 tty->print("\nVector align to node: ");
417 memops.at(max_idx)->as_Mem()->dump();
418 }
419 #endif
420 return memops.at(max_idx)->as_Mem();
421 }
422 return NULL;
423 }
425 //------------------------------ref_is_alignable---------------------------
426 // Can the preloop align the reference to position zero in the vector?
427 bool SuperWord::ref_is_alignable(SWPointer& p) {
428 if (!p.has_iv()) {
429 return true; // no induction variable
430 }
431 CountedLoopEndNode* pre_end = get_pre_loop_end(lp()->as_CountedLoop());
432 assert(pre_end->stride_is_con(), "pre loop stride is constant");
433 int preloop_stride = pre_end->stride_con();
435 int span = preloop_stride * p.scale_in_bytes();
437 // Stride one accesses are alignable.
438 if (ABS(span) == p.memory_size())
439 return true;
441 // If initial offset from start of object is computable,
442 // compute alignment within the vector.
443 BasicType bt = velt_basic_type(p.mem());
444 int vw = vector_width_in_bytes(bt);
445 assert(vw > 1, "sanity");
446 if (vw % span == 0) {
447 Node* init_nd = pre_end->init_trip();
448 if (init_nd->is_Con() && p.invar() == NULL) {
449 int init = init_nd->bottom_type()->is_int()->get_con();
451 int init_offset = init * p.scale_in_bytes() + p.offset_in_bytes();
452 assert(init_offset >= 0, "positive offset from object start");
454 if (span > 0) {
455 return (vw - (init_offset % vw)) % span == 0;
456 } else {
457 assert(span < 0, "nonzero stride * scale");
458 return (init_offset % vw) % -span == 0;
459 }
460 }
461 }
462 return false;
463 }
465 //---------------------------get_iv_adjustment---------------------------
466 // Calculate loop's iv adjustment for this memory ops.
467 int SuperWord::get_iv_adjustment(MemNode* mem_ref) {
468 SWPointer align_to_ref_p(mem_ref, this);
469 int offset = align_to_ref_p.offset_in_bytes();
470 int scale = align_to_ref_p.scale_in_bytes();
471 BasicType bt = velt_basic_type(mem_ref);
472 int vw = vector_width_in_bytes(bt);
473 assert(vw > 1, "sanity");
474 int stride_sign = (scale * iv_stride()) > 0 ? 1 : -1;
475 int iv_adjustment = (stride_sign * vw - (offset % vw)) % vw;
477 #ifndef PRODUCT
478 if (TraceSuperWord)
479 tty->print_cr("\noffset = %d iv_adjust = %d elt_size = %d scale = %d iv_stride = %d vect_size %d",
480 offset, iv_adjustment, align_to_ref_p.memory_size(), scale, iv_stride(), vw);
481 #endif
482 return iv_adjustment;
483 }
485 //---------------------------dependence_graph---------------------------
486 // Construct dependency graph.
487 // Add dependence edges to load/store nodes for memory dependence
488 // A.out()->DependNode.in(1) and DependNode.out()->B.prec(x)
489 void SuperWord::dependence_graph() {
490 // First, assign a dependence node to each memory node
491 for (int i = 0; i < _block.length(); i++ ) {
492 Node *n = _block.at(i);
493 if (n->is_Mem() || n->is_Phi() && n->bottom_type() == Type::MEMORY) {
494 _dg.make_node(n);
495 }
496 }
498 // For each memory slice, create the dependences
499 for (int i = 0; i < _mem_slice_head.length(); i++) {
500 Node* n = _mem_slice_head.at(i);
501 Node* n_tail = _mem_slice_tail.at(i);
503 // Get slice in predecessor order (last is first)
504 mem_slice_preds(n_tail, n, _nlist);
506 // Make the slice dependent on the root
507 DepMem* slice = _dg.dep(n);
508 _dg.make_edge(_dg.root(), slice);
510 // Create a sink for the slice
511 DepMem* slice_sink = _dg.make_node(NULL);
512 _dg.make_edge(slice_sink, _dg.tail());
514 // Now visit each pair of memory ops, creating the edges
515 for (int j = _nlist.length() - 1; j >= 0 ; j--) {
516 Node* s1 = _nlist.at(j);
518 // If no dependency yet, use slice
519 if (_dg.dep(s1)->in_cnt() == 0) {
520 _dg.make_edge(slice, s1);
521 }
522 SWPointer p1(s1->as_Mem(), this);
523 bool sink_dependent = true;
524 for (int k = j - 1; k >= 0; k--) {
525 Node* s2 = _nlist.at(k);
526 if (s1->is_Load() && s2->is_Load())
527 continue;
528 SWPointer p2(s2->as_Mem(), this);
530 int cmp = p1.cmp(p2);
531 if (SuperWordRTDepCheck &&
532 p1.base() != p2.base() && p1.valid() && p2.valid()) {
533 // Create a runtime check to disambiguate
534 OrderedPair pp(p1.base(), p2.base());
535 _disjoint_ptrs.append_if_missing(pp);
536 } else if (!SWPointer::not_equal(cmp)) {
537 // Possibly same address
538 _dg.make_edge(s1, s2);
539 sink_dependent = false;
540 }
541 }
542 if (sink_dependent) {
543 _dg.make_edge(s1, slice_sink);
544 }
545 }
546 #ifndef PRODUCT
547 if (TraceSuperWord) {
548 tty->print_cr("\nDependence graph for slice: %d", n->_idx);
549 for (int q = 0; q < _nlist.length(); q++) {
550 _dg.print(_nlist.at(q));
551 }
552 tty->cr();
553 }
554 #endif
555 _nlist.clear();
556 }
558 #ifndef PRODUCT
559 if (TraceSuperWord) {
560 tty->print_cr("\ndisjoint_ptrs: %s", _disjoint_ptrs.length() > 0 ? "" : "NONE");
561 for (int r = 0; r < _disjoint_ptrs.length(); r++) {
562 _disjoint_ptrs.at(r).print();
563 tty->cr();
564 }
565 tty->cr();
566 }
567 #endif
568 }
570 //---------------------------mem_slice_preds---------------------------
571 // Return a memory slice (node list) in predecessor order starting at "start"
572 void SuperWord::mem_slice_preds(Node* start, Node* stop, GrowableArray<Node*> &preds) {
573 assert(preds.length() == 0, "start empty");
574 Node* n = start;
575 Node* prev = NULL;
576 while (true) {
577 assert(in_bb(n), "must be in block");
578 for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
579 Node* out = n->fast_out(i);
580 if (out->is_Load()) {
581 if (in_bb(out)) {
582 preds.push(out);
583 }
584 } else {
585 // FIXME
586 if (out->is_MergeMem() && !in_bb(out)) {
587 // Either unrolling is causing a memory edge not to disappear,
588 // or need to run igvn.optimize() again before SLP
589 } else if (out->is_Phi() && out->bottom_type() == Type::MEMORY && !in_bb(out)) {
590 // Ditto. Not sure what else to check further.
591 } else if (out->Opcode() == Op_StoreCM && out->in(MemNode::OopStore) == n) {
592 // StoreCM has an input edge used as a precedence edge.
593 // Maybe an issue when oop stores are vectorized.
594 } else {
595 assert(out == prev || prev == NULL, "no branches off of store slice");
596 }
597 }
598 }
599 if (n == stop) break;
600 preds.push(n);
601 prev = n;
602 n = n->in(MemNode::Memory);
603 }
604 }
606 //------------------------------stmts_can_pack---------------------------
607 // Can s1 and s2 be in a pack with s1 immediately preceding s2 and
608 // s1 aligned at "align"
609 bool SuperWord::stmts_can_pack(Node* s1, Node* s2, int align) {
611 // Do not use superword for non-primitives
612 BasicType bt1 = velt_basic_type(s1);
613 BasicType bt2 = velt_basic_type(s2);
614 if(!is_java_primitive(bt1) || !is_java_primitive(bt2))
615 return false;
616 if (Matcher::max_vector_size(bt1) < 2) {
617 return false; // No vectors for this type
618 }
620 if (isomorphic(s1, s2)) {
621 if (independent(s1, s2)) {
622 if (!exists_at(s1, 0) && !exists_at(s2, 1)) {
623 if (!s1->is_Mem() || are_adjacent_refs(s1, s2)) {
624 int s1_align = alignment(s1);
625 int s2_align = alignment(s2);
626 if (s1_align == top_align || s1_align == align) {
627 if (s2_align == top_align || s2_align == align + data_size(s1)) {
628 return true;
629 }
630 }
631 }
632 }
633 }
634 }
635 return false;
636 }
638 //------------------------------exists_at---------------------------
639 // Does s exist in a pack at position pos?
640 bool SuperWord::exists_at(Node* s, uint pos) {
641 for (int i = 0; i < _packset.length(); i++) {
642 Node_List* p = _packset.at(i);
643 if (p->at(pos) == s) {
644 return true;
645 }
646 }
647 return false;
648 }
650 //------------------------------are_adjacent_refs---------------------------
651 // Is s1 immediately before s2 in memory?
652 bool SuperWord::are_adjacent_refs(Node* s1, Node* s2) {
653 if (!s1->is_Mem() || !s2->is_Mem()) return false;
654 if (!in_bb(s1) || !in_bb(s2)) return false;
656 // Do not use superword for non-primitives
657 if (!is_java_primitive(s1->as_Mem()->memory_type()) ||
658 !is_java_primitive(s2->as_Mem()->memory_type())) {
659 return false;
660 }
662 // FIXME - co_locate_pack fails on Stores in different mem-slices, so
663 // only pack memops that are in the same alias set until that's fixed.
664 if (_phase->C->get_alias_index(s1->as_Mem()->adr_type()) !=
665 _phase->C->get_alias_index(s2->as_Mem()->adr_type()))
666 return false;
667 SWPointer p1(s1->as_Mem(), this);
668 SWPointer p2(s2->as_Mem(), this);
669 if (p1.base() != p2.base() || !p1.comparable(p2)) return false;
670 int diff = p2.offset_in_bytes() - p1.offset_in_bytes();
671 return diff == data_size(s1);
672 }
674 //------------------------------isomorphic---------------------------
675 // Are s1 and s2 similar?
676 bool SuperWord::isomorphic(Node* s1, Node* s2) {
677 if (s1->Opcode() != s2->Opcode()) return false;
678 if (s1->req() != s2->req()) return false;
679 if (s1->in(0) != s2->in(0)) return false;
680 if (!same_velt_type(s1, s2)) return false;
681 return true;
682 }
684 //------------------------------independent---------------------------
685 // Is there no data path from s1 to s2 or s2 to s1?
686 bool SuperWord::independent(Node* s1, Node* s2) {
687 // assert(s1->Opcode() == s2->Opcode(), "check isomorphic first");
688 int d1 = depth(s1);
689 int d2 = depth(s2);
690 if (d1 == d2) return s1 != s2;
691 Node* deep = d1 > d2 ? s1 : s2;
692 Node* shallow = d1 > d2 ? s2 : s1;
694 visited_clear();
696 return independent_path(shallow, deep);
697 }
699 //------------------------------independent_path------------------------------
700 // Helper for independent
701 bool SuperWord::independent_path(Node* shallow, Node* deep, uint dp) {
702 if (dp >= 1000) return false; // stop deep recursion
703 visited_set(deep);
704 int shal_depth = depth(shallow);
705 assert(shal_depth <= depth(deep), "must be");
706 for (DepPreds preds(deep, _dg); !preds.done(); preds.next()) {
707 Node* pred = preds.current();
708 if (in_bb(pred) && !visited_test(pred)) {
709 if (shallow == pred) {
710 return false;
711 }
712 if (shal_depth < depth(pred) && !independent_path(shallow, pred, dp+1)) {
713 return false;
714 }
715 }
716 }
717 return true;
718 }
720 //------------------------------set_alignment---------------------------
721 void SuperWord::set_alignment(Node* s1, Node* s2, int align) {
722 set_alignment(s1, align);
723 if (align == top_align || align == bottom_align) {
724 set_alignment(s2, align);
725 } else {
726 set_alignment(s2, align + data_size(s1));
727 }
728 }
730 //------------------------------data_size---------------------------
731 int SuperWord::data_size(Node* s) {
732 int bsize = type2aelembytes(velt_basic_type(s));
733 assert(bsize != 0, "valid size");
734 return bsize;
735 }
737 //------------------------------extend_packlist---------------------------
738 // Extend packset by following use->def and def->use links from pack members.
739 void SuperWord::extend_packlist() {
740 bool changed;
741 do {
742 changed = false;
743 for (int i = 0; i < _packset.length(); i++) {
744 Node_List* p = _packset.at(i);
745 changed |= follow_use_defs(p);
746 changed |= follow_def_uses(p);
747 }
748 } while (changed);
750 #ifndef PRODUCT
751 if (TraceSuperWord) {
752 tty->print_cr("\nAfter extend_packlist");
753 print_packset();
754 }
755 #endif
756 }
758 //------------------------------follow_use_defs---------------------------
759 // Extend the packset by visiting operand definitions of nodes in pack p
760 bool SuperWord::follow_use_defs(Node_List* p) {
761 assert(p->size() == 2, "just checking");
762 Node* s1 = p->at(0);
763 Node* s2 = p->at(1);
764 assert(s1->req() == s2->req(), "just checking");
765 assert(alignment(s1) + data_size(s1) == alignment(s2), "just checking");
767 if (s1->is_Load()) return false;
769 int align = alignment(s1);
770 bool changed = false;
771 int start = s1->is_Store() ? MemNode::ValueIn : 1;
772 int end = s1->is_Store() ? MemNode::ValueIn+1 : s1->req();
773 for (int j = start; j < end; j++) {
774 Node* t1 = s1->in(j);
775 Node* t2 = s2->in(j);
776 if (!in_bb(t1) || !in_bb(t2))
777 continue;
778 if (stmts_can_pack(t1, t2, align)) {
779 if (est_savings(t1, t2) >= 0) {
780 Node_List* pair = new Node_List();
781 pair->push(t1);
782 pair->push(t2);
783 _packset.append(pair);
784 set_alignment(t1, t2, align);
785 changed = true;
786 }
787 }
788 }
789 return changed;
790 }
792 //------------------------------follow_def_uses---------------------------
793 // Extend the packset by visiting uses of nodes in pack p
794 bool SuperWord::follow_def_uses(Node_List* p) {
795 bool changed = false;
796 Node* s1 = p->at(0);
797 Node* s2 = p->at(1);
798 assert(p->size() == 2, "just checking");
799 assert(s1->req() == s2->req(), "just checking");
800 assert(alignment(s1) + data_size(s1) == alignment(s2), "just checking");
802 if (s1->is_Store()) return false;
804 int align = alignment(s1);
805 int savings = -1;
806 Node* u1 = NULL;
807 Node* u2 = NULL;
808 for (DUIterator_Fast imax, i = s1->fast_outs(imax); i < imax; i++) {
809 Node* t1 = s1->fast_out(i);
810 if (!in_bb(t1)) continue;
811 for (DUIterator_Fast jmax, j = s2->fast_outs(jmax); j < jmax; j++) {
812 Node* t2 = s2->fast_out(j);
813 if (!in_bb(t2)) continue;
814 if (!opnd_positions_match(s1, t1, s2, t2))
815 continue;
816 if (stmts_can_pack(t1, t2, align)) {
817 int my_savings = est_savings(t1, t2);
818 if (my_savings > savings) {
819 savings = my_savings;
820 u1 = t1;
821 u2 = t2;
822 }
823 }
824 }
825 }
826 if (savings >= 0) {
827 Node_List* pair = new Node_List();
828 pair->push(u1);
829 pair->push(u2);
830 _packset.append(pair);
831 set_alignment(u1, u2, align);
832 changed = true;
833 }
834 return changed;
835 }
837 //---------------------------opnd_positions_match-------------------------
838 // Is the use of d1 in u1 at the same operand position as d2 in u2?
839 bool SuperWord::opnd_positions_match(Node* d1, Node* u1, Node* d2, Node* u2) {
840 uint ct = u1->req();
841 if (ct != u2->req()) return false;
842 uint i1 = 0;
843 uint i2 = 0;
844 do {
845 for (i1++; i1 < ct; i1++) if (u1->in(i1) == d1) break;
846 for (i2++; i2 < ct; i2++) if (u2->in(i2) == d2) break;
847 if (i1 != i2) {
848 if ((i1 == (3-i2)) && (u2->is_Add() || u2->is_Mul())) {
849 // Further analysis relies on operands position matching.
850 u2->swap_edges(i1, i2);
851 } else {
852 return false;
853 }
854 }
855 } while (i1 < ct);
856 return true;
857 }
859 //------------------------------est_savings---------------------------
860 // Estimate the savings from executing s1 and s2 as a pack
861 int SuperWord::est_savings(Node* s1, Node* s2) {
862 int save_in = 2 - 1; // 2 operations per instruction in packed form
864 // inputs
865 for (uint i = 1; i < s1->req(); i++) {
866 Node* x1 = s1->in(i);
867 Node* x2 = s2->in(i);
868 if (x1 != x2) {
869 if (are_adjacent_refs(x1, x2)) {
870 save_in += adjacent_profit(x1, x2);
871 } else if (!in_packset(x1, x2)) {
872 save_in -= pack_cost(2);
873 } else {
874 save_in += unpack_cost(2);
875 }
876 }
877 }
879 // uses of result
880 uint ct = 0;
881 int save_use = 0;
882 for (DUIterator_Fast imax, i = s1->fast_outs(imax); i < imax; i++) {
883 Node* s1_use = s1->fast_out(i);
884 for (int j = 0; j < _packset.length(); j++) {
885 Node_List* p = _packset.at(j);
886 if (p->at(0) == s1_use) {
887 for (DUIterator_Fast kmax, k = s2->fast_outs(kmax); k < kmax; k++) {
888 Node* s2_use = s2->fast_out(k);
889 if (p->at(p->size()-1) == s2_use) {
890 ct++;
891 if (are_adjacent_refs(s1_use, s2_use)) {
892 save_use += adjacent_profit(s1_use, s2_use);
893 }
894 }
895 }
896 }
897 }
898 }
900 if (ct < s1->outcnt()) save_use += unpack_cost(1);
901 if (ct < s2->outcnt()) save_use += unpack_cost(1);
903 return MAX2(save_in, save_use);
904 }
906 //------------------------------costs---------------------------
907 int SuperWord::adjacent_profit(Node* s1, Node* s2) { return 2; }
908 int SuperWord::pack_cost(int ct) { return ct; }
909 int SuperWord::unpack_cost(int ct) { return ct; }
911 //------------------------------combine_packs---------------------------
912 // Combine packs A and B with A.last == B.first into A.first..,A.last,B.second,..B.last
913 void SuperWord::combine_packs() {
914 bool changed = true;
915 // Combine packs regardless max vector size.
916 while (changed) {
917 changed = false;
918 for (int i = 0; i < _packset.length(); i++) {
919 Node_List* p1 = _packset.at(i);
920 if (p1 == NULL) continue;
921 for (int j = 0; j < _packset.length(); j++) {
922 Node_List* p2 = _packset.at(j);
923 if (p2 == NULL) continue;
924 if (i == j) continue;
925 if (p1->at(p1->size()-1) == p2->at(0)) {
926 for (uint k = 1; k < p2->size(); k++) {
927 p1->push(p2->at(k));
928 }
929 _packset.at_put(j, NULL);
930 changed = true;
931 }
932 }
933 }
934 }
936 // Split packs which have size greater then max vector size.
937 for (int i = 0; i < _packset.length(); i++) {
938 Node_List* p1 = _packset.at(i);
939 if (p1 != NULL) {
940 BasicType bt = velt_basic_type(p1->at(0));
941 uint max_vlen = Matcher::max_vector_size(bt); // Max elements in vector
942 assert(is_power_of_2(max_vlen), "sanity");
943 uint psize = p1->size();
944 if (!is_power_of_2(psize)) {
945 // Skip pack which can't be vector.
946 // case1: for(...) { a[i] = i; } elements values are different (i+x)
947 // case2: for(...) { a[i] = b[i+1]; } can't align both, load and store
948 _packset.at_put(i, NULL);
949 continue;
950 }
951 if (psize > max_vlen) {
952 Node_List* pack = new Node_List();
953 for (uint j = 0; j < psize; j++) {
954 pack->push(p1->at(j));
955 if (pack->size() >= max_vlen) {
956 assert(is_power_of_2(pack->size()), "sanity");
957 _packset.append(pack);
958 pack = new Node_List();
959 }
960 }
961 _packset.at_put(i, NULL);
962 }
963 }
964 }
966 // Compress list.
967 for (int i = _packset.length() - 1; i >= 0; i--) {
968 Node_List* p1 = _packset.at(i);
969 if (p1 == NULL) {
970 _packset.remove_at(i);
971 }
972 }
974 #ifndef PRODUCT
975 if (TraceSuperWord) {
976 tty->print_cr("\nAfter combine_packs");
977 print_packset();
978 }
979 #endif
980 }
982 //-----------------------------construct_my_pack_map--------------------------
983 // Construct the map from nodes to packs. Only valid after the
984 // point where a node is only in one pack (after combine_packs).
985 void SuperWord::construct_my_pack_map() {
986 Node_List* rslt = NULL;
987 for (int i = 0; i < _packset.length(); i++) {
988 Node_List* p = _packset.at(i);
989 for (uint j = 0; j < p->size(); j++) {
990 Node* s = p->at(j);
991 assert(my_pack(s) == NULL, "only in one pack");
992 set_my_pack(s, p);
993 }
994 }
995 }
997 //------------------------------filter_packs---------------------------
998 // Remove packs that are not implemented or not profitable.
999 void SuperWord::filter_packs() {
1001 // Remove packs that are not implemented
1002 for (int i = _packset.length() - 1; i >= 0; i--) {
1003 Node_List* pk = _packset.at(i);
1004 bool impl = implemented(pk);
1005 if (!impl) {
1006 #ifndef PRODUCT
1007 if (TraceSuperWord && Verbose) {
1008 tty->print_cr("Unimplemented");
1009 pk->at(0)->dump();
1010 }
1011 #endif
1012 remove_pack_at(i);
1013 }
1014 }
1016 // Remove packs that are not profitable
1017 bool changed;
1018 do {
1019 changed = false;
1020 for (int i = _packset.length() - 1; i >= 0; i--) {
1021 Node_List* pk = _packset.at(i);
1022 bool prof = profitable(pk);
1023 if (!prof) {
1024 #ifndef PRODUCT
1025 if (TraceSuperWord && Verbose) {
1026 tty->print_cr("Unprofitable");
1027 pk->at(0)->dump();
1028 }
1029 #endif
1030 remove_pack_at(i);
1031 changed = true;
1032 }
1033 }
1034 } while (changed);
1036 #ifndef PRODUCT
1037 if (TraceSuperWord) {
1038 tty->print_cr("\nAfter filter_packs");
1039 print_packset();
1040 tty->cr();
1041 }
1042 #endif
1043 }
1045 //------------------------------implemented---------------------------
1046 // Can code be generated for pack p?
1047 bool SuperWord::implemented(Node_List* p) {
1048 Node* p0 = p->at(0);
1049 return VectorNode::implemented(p0->Opcode(), p->size(), velt_basic_type(p0));
1050 }
1052 //------------------------------profitable---------------------------
1053 // For pack p, are all operands and all uses (with in the block) vector?
1054 bool SuperWord::profitable(Node_List* p) {
1055 Node* p0 = p->at(0);
1056 uint start, end;
1057 vector_opd_range(p0, &start, &end);
1059 // Return false if some input is not vector and inside block
1060 for (uint i = start; i < end; i++) {
1061 if (!is_vector_use(p0, i)) {
1062 // For now, return false if not scalar promotion case (inputs are the same.)
1063 // Later, implement PackNode and allow differing, non-vector inputs
1064 // (maybe just the ones from outside the block.)
1065 Node* p0_def = p0->in(i);
1066 for (uint j = 1; j < p->size(); j++) {
1067 Node* use = p->at(j);
1068 Node* def = use->in(i);
1069 if (p0_def != def)
1070 return false;
1071 }
1072 }
1073 }
1074 if (!p0->is_Store()) {
1075 // For now, return false if not all uses are vector.
1076 // Later, implement ExtractNode and allow non-vector uses (maybe
1077 // just the ones outside the block.)
1078 for (uint i = 0; i < p->size(); i++) {
1079 Node* def = p->at(i);
1080 for (DUIterator_Fast jmax, j = def->fast_outs(jmax); j < jmax; j++) {
1081 Node* use = def->fast_out(j);
1082 for (uint k = 0; k < use->req(); k++) {
1083 Node* n = use->in(k);
1084 if (def == n) {
1085 if (!is_vector_use(use, k)) {
1086 return false;
1087 }
1088 }
1089 }
1090 }
1091 }
1092 }
1093 return true;
1094 }
1096 //------------------------------schedule---------------------------
1097 // Adjust the memory graph for the packed operations
1098 void SuperWord::schedule() {
1100 // Co-locate in the memory graph the members of each memory pack
1101 for (int i = 0; i < _packset.length(); i++) {
1102 co_locate_pack(_packset.at(i));
1103 }
1104 }
1106 //-------------------------------remove_and_insert-------------------
1107 // Remove "current" from its current position in the memory graph and insert
1108 // it after the appropriate insertion point (lip or uip).
1109 void SuperWord::remove_and_insert(MemNode *current, MemNode *prev, MemNode *lip,
1110 Node *uip, Unique_Node_List &sched_before) {
1111 Node* my_mem = current->in(MemNode::Memory);
1112 bool sched_up = sched_before.member(current);
1114 // remove current_store from its current position in the memmory graph
1115 for (DUIterator i = current->outs(); current->has_out(i); i++) {
1116 Node* use = current->out(i);
1117 if (use->is_Mem()) {
1118 assert(use->in(MemNode::Memory) == current, "must be");
1119 if (use == prev) { // connect prev to my_mem
1120 _igvn.replace_input_of(use, MemNode::Memory, my_mem);
1121 --i; //deleted this edge; rescan position
1122 } else if (sched_before.member(use)) {
1123 if (!sched_up) { // Will be moved together with current
1124 _igvn.replace_input_of(use, MemNode::Memory, uip);
1125 --i; //deleted this edge; rescan position
1126 }
1127 } else {
1128 if (sched_up) { // Will be moved together with current
1129 _igvn.replace_input_of(use, MemNode::Memory, lip);
1130 --i; //deleted this edge; rescan position
1131 }
1132 }
1133 }
1134 }
1136 Node *insert_pt = sched_up ? uip : lip;
1138 // all uses of insert_pt's memory state should use current's instead
1139 for (DUIterator i = insert_pt->outs(); insert_pt->has_out(i); i++) {
1140 Node* use = insert_pt->out(i);
1141 if (use->is_Mem()) {
1142 assert(use->in(MemNode::Memory) == insert_pt, "must be");
1143 _igvn.replace_input_of(use, MemNode::Memory, current);
1144 --i; //deleted this edge; rescan position
1145 } else if (!sched_up && use->is_Phi() && use->bottom_type() == Type::MEMORY) {
1146 uint pos; //lip (lower insert point) must be the last one in the memory slice
1147 for (pos=1; pos < use->req(); pos++) {
1148 if (use->in(pos) == insert_pt) break;
1149 }
1150 _igvn.replace_input_of(use, pos, current);
1151 --i;
1152 }
1153 }
1155 //connect current to insert_pt
1156 _igvn.replace_input_of(current, MemNode::Memory, insert_pt);
1157 }
1159 //------------------------------co_locate_pack----------------------------------
1160 // To schedule a store pack, we need to move any sandwiched memory ops either before
1161 // or after the pack, based upon dependence information:
1162 // (1) If any store in the pack depends on the sandwiched memory op, the
1163 // sandwiched memory op must be scheduled BEFORE the pack;
1164 // (2) If a sandwiched memory op depends on any store in the pack, the
1165 // sandwiched memory op must be scheduled AFTER the pack;
1166 // (3) If a sandwiched memory op (say, memA) depends on another sandwiched
1167 // memory op (say memB), memB must be scheduled before memA. So, if memA is
1168 // scheduled before the pack, memB must also be scheduled before the pack;
1169 // (4) If there is no dependence restriction for a sandwiched memory op, we simply
1170 // schedule this store AFTER the pack
1171 // (5) We know there is no dependence cycle, so there in no other case;
1172 // (6) Finally, all memory ops in another single pack should be moved in the same direction.
1173 //
1174 // To schedule a load pack, we use the memory state of either the first or the last load in
1175 // the pack, based on the dependence constraint.
1176 void SuperWord::co_locate_pack(Node_List* pk) {
1177 if (pk->at(0)->is_Store()) {
1178 MemNode* first = executed_first(pk)->as_Mem();
1179 MemNode* last = executed_last(pk)->as_Mem();
1180 Unique_Node_List schedule_before_pack;
1181 Unique_Node_List memops;
1183 MemNode* current = last->in(MemNode::Memory)->as_Mem();
1184 MemNode* previous = last;
1185 while (true) {
1186 assert(in_bb(current), "stay in block");
1187 memops.push(previous);
1188 for (DUIterator i = current->outs(); current->has_out(i); i++) {
1189 Node* use = current->out(i);
1190 if (use->is_Mem() && use != previous)
1191 memops.push(use);
1192 }
1193 if (current == first) break;
1194 previous = current;
1195 current = current->in(MemNode::Memory)->as_Mem();
1196 }
1198 // determine which memory operations should be scheduled before the pack
1199 for (uint i = 1; i < memops.size(); i++) {
1200 Node *s1 = memops.at(i);
1201 if (!in_pack(s1, pk) && !schedule_before_pack.member(s1)) {
1202 for (uint j = 0; j< i; j++) {
1203 Node *s2 = memops.at(j);
1204 if (!independent(s1, s2)) {
1205 if (in_pack(s2, pk) || schedule_before_pack.member(s2)) {
1206 schedule_before_pack.push(s1); // s1 must be scheduled before
1207 Node_List* mem_pk = my_pack(s1);
1208 if (mem_pk != NULL) {
1209 for (uint ii = 0; ii < mem_pk->size(); ii++) {
1210 Node* s = mem_pk->at(ii); // follow partner
1211 if (memops.member(s) && !schedule_before_pack.member(s))
1212 schedule_before_pack.push(s);
1213 }
1214 }
1215 break;
1216 }
1217 }
1218 }
1219 }
1220 }
1222 Node* upper_insert_pt = first->in(MemNode::Memory);
1223 // Following code moves loads connected to upper_insert_pt below aliased stores.
1224 // Collect such loads here and reconnect them back to upper_insert_pt later.
1225 memops.clear();
1226 for (DUIterator i = upper_insert_pt->outs(); upper_insert_pt->has_out(i); i++) {
1227 Node* use = upper_insert_pt->out(i);
1228 if (!use->is_Store())
1229 memops.push(use);
1230 }
1232 MemNode* lower_insert_pt = last;
1233 previous = last; //previous store in pk
1234 current = last->in(MemNode::Memory)->as_Mem();
1236 // start scheduling from "last" to "first"
1237 while (true) {
1238 assert(in_bb(current), "stay in block");
1239 assert(in_pack(previous, pk), "previous stays in pack");
1240 Node* my_mem = current->in(MemNode::Memory);
1242 if (in_pack(current, pk)) {
1243 // Forward users of my memory state (except "previous) to my input memory state
1244 for (DUIterator i = current->outs(); current->has_out(i); i++) {
1245 Node* use = current->out(i);
1246 if (use->is_Mem() && use != previous) {
1247 assert(use->in(MemNode::Memory) == current, "must be");
1248 if (schedule_before_pack.member(use)) {
1249 _igvn.replace_input_of(use, MemNode::Memory, upper_insert_pt);
1250 } else {
1251 _igvn.replace_input_of(use, MemNode::Memory, lower_insert_pt);
1252 }
1253 --i; // deleted this edge; rescan position
1254 }
1255 }
1256 previous = current;
1257 } else { // !in_pack(current, pk) ==> a sandwiched store
1258 remove_and_insert(current, previous, lower_insert_pt, upper_insert_pt, schedule_before_pack);
1259 }
1261 if (current == first) break;
1262 current = my_mem->as_Mem();
1263 } // end while
1265 // Reconnect loads back to upper_insert_pt.
1266 for (uint i = 0; i < memops.size(); i++) {
1267 Node *ld = memops.at(i);
1268 if (ld->in(MemNode::Memory) != upper_insert_pt) {
1269 _igvn.replace_input_of(ld, MemNode::Memory, upper_insert_pt);
1270 }
1271 }
1272 } else if (pk->at(0)->is_Load()) { //load
1273 // all loads in the pack should have the same memory state. By default,
1274 // we use the memory state of the last load. However, if any load could
1275 // not be moved down due to the dependence constraint, we use the memory
1276 // state of the first load.
1277 Node* last_mem = executed_last(pk)->in(MemNode::Memory);
1278 Node* first_mem = executed_first(pk)->in(MemNode::Memory);
1279 bool schedule_last = true;
1280 for (uint i = 0; i < pk->size(); i++) {
1281 Node* ld = pk->at(i);
1282 for (Node* current = last_mem; current != ld->in(MemNode::Memory);
1283 current=current->in(MemNode::Memory)) {
1284 assert(current != first_mem, "corrupted memory graph");
1285 if(current->is_Mem() && !independent(current, ld)){
1286 schedule_last = false; // a later store depends on this load
1287 break;
1288 }
1289 }
1290 }
1292 Node* mem_input = schedule_last ? last_mem : first_mem;
1293 _igvn.hash_delete(mem_input);
1294 // Give each load the same memory state
1295 for (uint i = 0; i < pk->size(); i++) {
1296 LoadNode* ld = pk->at(i)->as_Load();
1297 _igvn.replace_input_of(ld, MemNode::Memory, mem_input);
1298 }
1299 }
1300 }
1302 //------------------------------output---------------------------
1303 // Convert packs into vector node operations
1304 void SuperWord::output() {
1305 if (_packset.length() == 0) return;
1307 #ifndef PRODUCT
1308 if (TraceLoopOpts) {
1309 tty->print("SuperWord ");
1310 lpt()->dump_head();
1311 }
1312 #endif
1314 // MUST ENSURE main loop's initial value is properly aligned:
1315 // (iv_initial_value + min_iv_offset) % vector_width_in_bytes() == 0
1317 align_initial_loop_index(align_to_ref());
1319 // Insert extract (unpack) operations for scalar uses
1320 for (int i = 0; i < _packset.length(); i++) {
1321 insert_extracts(_packset.at(i));
1322 }
1324 for (int i = 0; i < _block.length(); i++) {
1325 Node* n = _block.at(i);
1326 Node_List* p = my_pack(n);
1327 if (p && n == executed_last(p)) {
1328 uint vlen = p->size();
1329 Node* vn = NULL;
1330 Node* low_adr = p->at(0);
1331 Node* first = executed_first(p);
1332 int opc = n->Opcode();
1333 if (n->is_Load()) {
1334 Node* ctl = n->in(MemNode::Control);
1335 Node* mem = first->in(MemNode::Memory);
1336 Node* adr = low_adr->in(MemNode::Address);
1337 const TypePtr* atyp = n->adr_type();
1338 vn = LoadVectorNode::make(_phase->C, opc, ctl, mem, adr, atyp, vlen, velt_basic_type(n));
1339 } else if (n->is_Store()) {
1340 // Promote value to be stored to vector
1341 Node* val = vector_opd(p, MemNode::ValueIn);
1342 Node* ctl = n->in(MemNode::Control);
1343 Node* mem = first->in(MemNode::Memory);
1344 Node* adr = low_adr->in(MemNode::Address);
1345 const TypePtr* atyp = n->adr_type();
1346 vn = StoreVectorNode::make(_phase->C, opc, ctl, mem, adr, atyp, val, vlen);
1347 } else if (n->req() == 3) {
1348 // Promote operands to vector
1349 Node* in1 = vector_opd(p, 1);
1350 Node* in2 = vector_opd(p, 2);
1351 vn = VectorNode::make(_phase->C, opc, in1, in2, vlen, velt_basic_type(n));
1352 } else {
1353 ShouldNotReachHere();
1354 }
1355 assert(vn != NULL, "sanity");
1356 _phase->_igvn.register_new_node_with_optimizer(vn);
1357 _phase->set_ctrl(vn, _phase->get_ctrl(p->at(0)));
1358 for (uint j = 0; j < p->size(); j++) {
1359 Node* pm = p->at(j);
1360 _igvn.replace_node(pm, vn);
1361 }
1362 _igvn._worklist.push(vn);
1363 #ifdef ASSERT
1364 if (TraceSuperWord) {
1365 tty->print("new Vector node: ");
1366 vn->dump();
1367 }
1368 #endif
1369 }
1370 }
1371 }
1373 //------------------------------vector_opd---------------------------
1374 // Create a vector operand for the nodes in pack p for operand: in(opd_idx)
1375 Node* SuperWord::vector_opd(Node_List* p, int opd_idx) {
1376 Node* p0 = p->at(0);
1377 uint vlen = p->size();
1378 Node* opd = p0->in(opd_idx);
1380 bool same_opd = true;
1381 for (uint i = 1; i < vlen; i++) {
1382 Node* pi = p->at(i);
1383 Node* in = pi->in(opd_idx);
1384 if (opd != in) {
1385 same_opd = false;
1386 break;
1387 }
1388 }
1390 if (same_opd) {
1391 if (opd->is_Vector() || opd->is_LoadVector()) {
1392 return opd; // input is matching vector
1393 }
1394 assert(!opd->is_StoreVector(), "such vector is not expected here");
1395 // Convert scalar input to vector with the same number of elements as
1396 // p0's vector. Use p0's type because size of operand's container in
1397 // vector should match p0's size regardless operand's size.
1398 const Type* p0_t = velt_type(p0);
1399 VectorNode* vn = VectorNode::scalar2vector(_phase->C, opd, vlen, p0_t);
1401 _phase->_igvn.register_new_node_with_optimizer(vn);
1402 _phase->set_ctrl(vn, _phase->get_ctrl(opd));
1403 #ifdef ASSERT
1404 if (TraceSuperWord) {
1405 tty->print("new Vector node: ");
1406 vn->dump();
1407 }
1408 #endif
1409 return vn;
1410 }
1412 // Insert pack operation
1413 BasicType bt = velt_basic_type(p0);
1414 PackNode* pk = PackNode::make(_phase->C, opd, vlen, bt);
1415 DEBUG_ONLY( const BasicType opd_bt = opd->bottom_type()->basic_type(); )
1417 for (uint i = 1; i < vlen; i++) {
1418 Node* pi = p->at(i);
1419 Node* in = pi->in(opd_idx);
1420 assert(my_pack(in) == NULL, "Should already have been unpacked");
1421 assert(opd_bt == in->bottom_type()->basic_type(), "all same type");
1422 pk->add_opd(i, in);
1423 }
1424 _phase->_igvn.register_new_node_with_optimizer(pk);
1425 _phase->set_ctrl(pk, _phase->get_ctrl(opd));
1426 #ifdef ASSERT
1427 if (TraceSuperWord) {
1428 tty->print("new Pack node: ");
1429 pk->dump();
1430 }
1431 #endif
1432 return pk;
1433 }
1435 //------------------------------insert_extracts---------------------------
1436 // If a use of pack p is not a vector use, then replace the
1437 // use with an extract operation.
1438 void SuperWord::insert_extracts(Node_List* p) {
1439 if (p->at(0)->is_Store()) return;
1440 assert(_n_idx_list.is_empty(), "empty (node,index) list");
1442 // Inspect each use of each pack member. For each use that is
1443 // not a vector use, replace the use with an extract operation.
1445 for (uint i = 0; i < p->size(); i++) {
1446 Node* def = p->at(i);
1447 for (DUIterator_Fast jmax, j = def->fast_outs(jmax); j < jmax; j++) {
1448 Node* use = def->fast_out(j);
1449 for (uint k = 0; k < use->req(); k++) {
1450 Node* n = use->in(k);
1451 if (def == n) {
1452 if (!is_vector_use(use, k)) {
1453 _n_idx_list.push(use, k);
1454 }
1455 }
1456 }
1457 }
1458 }
1460 while (_n_idx_list.is_nonempty()) {
1461 Node* use = _n_idx_list.node();
1462 int idx = _n_idx_list.index();
1463 _n_idx_list.pop();
1464 Node* def = use->in(idx);
1466 // Insert extract operation
1467 _igvn.hash_delete(def);
1468 int def_pos = alignment(def) / data_size(def);
1470 Node* ex = ExtractNode::make(_phase->C, def, def_pos, velt_basic_type(def));
1471 _phase->_igvn.register_new_node_with_optimizer(ex);
1472 _phase->set_ctrl(ex, _phase->get_ctrl(def));
1473 _igvn.replace_input_of(use, idx, ex);
1474 _igvn._worklist.push(def);
1476 bb_insert_after(ex, bb_idx(def));
1477 set_velt_type(ex, velt_type(def));
1478 }
1479 }
1481 //------------------------------is_vector_use---------------------------
1482 // Is use->in(u_idx) a vector use?
1483 bool SuperWord::is_vector_use(Node* use, int u_idx) {
1484 Node_List* u_pk = my_pack(use);
1485 if (u_pk == NULL) return false;
1486 Node* def = use->in(u_idx);
1487 Node_List* d_pk = my_pack(def);
1488 if (d_pk == NULL) {
1489 // check for scalar promotion
1490 Node* n = u_pk->at(0)->in(u_idx);
1491 for (uint i = 1; i < u_pk->size(); i++) {
1492 if (u_pk->at(i)->in(u_idx) != n) return false;
1493 }
1494 return true;
1495 }
1496 if (u_pk->size() != d_pk->size())
1497 return false;
1498 for (uint i = 0; i < u_pk->size(); i++) {
1499 Node* ui = u_pk->at(i);
1500 Node* di = d_pk->at(i);
1501 if (ui->in(u_idx) != di || alignment(ui) != alignment(di))
1502 return false;
1503 }
1504 return true;
1505 }
1507 //------------------------------construct_bb---------------------------
1508 // Construct reverse postorder list of block members
1509 void SuperWord::construct_bb() {
1510 Node* entry = bb();
1512 assert(_stk.length() == 0, "stk is empty");
1513 assert(_block.length() == 0, "block is empty");
1514 assert(_data_entry.length() == 0, "data_entry is empty");
1515 assert(_mem_slice_head.length() == 0, "mem_slice_head is empty");
1516 assert(_mem_slice_tail.length() == 0, "mem_slice_tail is empty");
1518 // Find non-control nodes with no inputs from within block,
1519 // create a temporary map from node _idx to bb_idx for use
1520 // by the visited and post_visited sets,
1521 // and count number of nodes in block.
1522 int bb_ct = 0;
1523 for (uint i = 0; i < lpt()->_body.size(); i++ ) {
1524 Node *n = lpt()->_body.at(i);
1525 set_bb_idx(n, i); // Create a temporary map
1526 if (in_bb(n)) {
1527 bb_ct++;
1528 if (!n->is_CFG()) {
1529 bool found = false;
1530 for (uint j = 0; j < n->req(); j++) {
1531 Node* def = n->in(j);
1532 if (def && in_bb(def)) {
1533 found = true;
1534 break;
1535 }
1536 }
1537 if (!found) {
1538 assert(n != entry, "can't be entry");
1539 _data_entry.push(n);
1540 }
1541 }
1542 }
1543 }
1545 // Find memory slices (head and tail)
1546 for (DUIterator_Fast imax, i = lp()->fast_outs(imax); i < imax; i++) {
1547 Node *n = lp()->fast_out(i);
1548 if (in_bb(n) && (n->is_Phi() && n->bottom_type() == Type::MEMORY)) {
1549 Node* n_tail = n->in(LoopNode::LoopBackControl);
1550 if (n_tail != n->in(LoopNode::EntryControl)) {
1551 _mem_slice_head.push(n);
1552 _mem_slice_tail.push(n_tail);
1553 }
1554 }
1555 }
1557 // Create an RPO list of nodes in block
1559 visited_clear();
1560 post_visited_clear();
1562 // Push all non-control nodes with no inputs from within block, then control entry
1563 for (int j = 0; j < _data_entry.length(); j++) {
1564 Node* n = _data_entry.at(j);
1565 visited_set(n);
1566 _stk.push(n);
1567 }
1568 visited_set(entry);
1569 _stk.push(entry);
1571 // Do a depth first walk over out edges
1572 int rpo_idx = bb_ct - 1;
1573 int size;
1574 while ((size = _stk.length()) > 0) {
1575 Node* n = _stk.top(); // Leave node on stack
1576 if (!visited_test_set(n)) {
1577 // forward arc in graph
1578 } else if (!post_visited_test(n)) {
1579 // cross or back arc
1580 for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
1581 Node *use = n->fast_out(i);
1582 if (in_bb(use) && !visited_test(use) &&
1583 // Don't go around backedge
1584 (!use->is_Phi() || n == entry)) {
1585 _stk.push(use);
1586 }
1587 }
1588 if (_stk.length() == size) {
1589 // There were no additional uses, post visit node now
1590 _stk.pop(); // Remove node from stack
1591 assert(rpo_idx >= 0, "");
1592 _block.at_put_grow(rpo_idx, n);
1593 rpo_idx--;
1594 post_visited_set(n);
1595 assert(rpo_idx >= 0 || _stk.is_empty(), "");
1596 }
1597 } else {
1598 _stk.pop(); // Remove post-visited node from stack
1599 }
1600 }
1602 // Create real map of block indices for nodes
1603 for (int j = 0; j < _block.length(); j++) {
1604 Node* n = _block.at(j);
1605 set_bb_idx(n, j);
1606 }
1608 initialize_bb(); // Ensure extra info is allocated.
1610 #ifndef PRODUCT
1611 if (TraceSuperWord) {
1612 print_bb();
1613 tty->print_cr("\ndata entry nodes: %s", _data_entry.length() > 0 ? "" : "NONE");
1614 for (int m = 0; m < _data_entry.length(); m++) {
1615 tty->print("%3d ", m);
1616 _data_entry.at(m)->dump();
1617 }
1618 tty->print_cr("\nmemory slices: %s", _mem_slice_head.length() > 0 ? "" : "NONE");
1619 for (int m = 0; m < _mem_slice_head.length(); m++) {
1620 tty->print("%3d ", m); _mem_slice_head.at(m)->dump();
1621 tty->print(" "); _mem_slice_tail.at(m)->dump();
1622 }
1623 }
1624 #endif
1625 assert(rpo_idx == -1 && bb_ct == _block.length(), "all block members found");
1626 }
1628 //------------------------------initialize_bb---------------------------
1629 // Initialize per node info
1630 void SuperWord::initialize_bb() {
1631 Node* last = _block.at(_block.length() - 1);
1632 grow_node_info(bb_idx(last));
1633 }
1635 //------------------------------bb_insert_after---------------------------
1636 // Insert n into block after pos
1637 void SuperWord::bb_insert_after(Node* n, int pos) {
1638 int n_pos = pos + 1;
1639 // Make room
1640 for (int i = _block.length() - 1; i >= n_pos; i--) {
1641 _block.at_put_grow(i+1, _block.at(i));
1642 }
1643 for (int j = _node_info.length() - 1; j >= n_pos; j--) {
1644 _node_info.at_put_grow(j+1, _node_info.at(j));
1645 }
1646 // Set value
1647 _block.at_put_grow(n_pos, n);
1648 _node_info.at_put_grow(n_pos, SWNodeInfo::initial);
1649 // Adjust map from node->_idx to _block index
1650 for (int i = n_pos; i < _block.length(); i++) {
1651 set_bb_idx(_block.at(i), i);
1652 }
1653 }
1655 //------------------------------compute_max_depth---------------------------
1656 // Compute max depth for expressions from beginning of block
1657 // Use to prune search paths during test for independence.
1658 void SuperWord::compute_max_depth() {
1659 int ct = 0;
1660 bool again;
1661 do {
1662 again = false;
1663 for (int i = 0; i < _block.length(); i++) {
1664 Node* n = _block.at(i);
1665 if (!n->is_Phi()) {
1666 int d_orig = depth(n);
1667 int d_in = 0;
1668 for (DepPreds preds(n, _dg); !preds.done(); preds.next()) {
1669 Node* pred = preds.current();
1670 if (in_bb(pred)) {
1671 d_in = MAX2(d_in, depth(pred));
1672 }
1673 }
1674 if (d_in + 1 != d_orig) {
1675 set_depth(n, d_in + 1);
1676 again = true;
1677 }
1678 }
1679 }
1680 ct++;
1681 } while (again);
1682 #ifndef PRODUCT
1683 if (TraceSuperWord && Verbose)
1684 tty->print_cr("compute_max_depth iterated: %d times", ct);
1685 #endif
1686 }
1688 //-------------------------compute_vector_element_type-----------------------
1689 // Compute necessary vector element type for expressions
1690 // This propagates backwards a narrower integer type when the
1691 // upper bits of the value are not needed.
1692 // Example: char a,b,c; a = b + c;
1693 // Normally the type of the add is integer, but for packed character
1694 // operations the type of the add needs to be char.
1695 void SuperWord::compute_vector_element_type() {
1696 #ifndef PRODUCT
1697 if (TraceSuperWord && Verbose)
1698 tty->print_cr("\ncompute_velt_type:");
1699 #endif
1701 // Initial type
1702 for (int i = 0; i < _block.length(); i++) {
1703 Node* n = _block.at(i);
1704 set_velt_type(n, container_type(n));
1705 }
1707 // Propagate narrowed type backwards through operations
1708 // that don't depend on higher order bits
1709 for (int i = _block.length() - 1; i >= 0; i--) {
1710 Node* n = _block.at(i);
1711 // Only integer types need be examined
1712 if (n->bottom_type()->isa_int()) {
1713 uint start, end;
1714 vector_opd_range(n, &start, &end);
1715 const Type* vt = velt_type(n);
1717 for (uint j = start; j < end; j++) {
1718 Node* in = n->in(j);
1719 // Don't propagate through a type conversion
1720 if (n->bottom_type() != in->bottom_type())
1721 continue;
1722 switch(in->Opcode()) {
1723 case Op_AddI: case Op_AddL:
1724 case Op_SubI: case Op_SubL:
1725 case Op_MulI: case Op_MulL:
1726 case Op_AndI: case Op_AndL:
1727 case Op_OrI: case Op_OrL:
1728 case Op_XorI: case Op_XorL:
1729 case Op_LShiftI: case Op_LShiftL:
1730 case Op_CMoveI: case Op_CMoveL:
1731 if (in_bb(in)) {
1732 bool same_type = true;
1733 for (DUIterator_Fast kmax, k = in->fast_outs(kmax); k < kmax; k++) {
1734 Node *use = in->fast_out(k);
1735 if (!in_bb(use) || !same_velt_type(use, n)) {
1736 same_type = false;
1737 break;
1738 }
1739 }
1740 if (same_type) {
1741 set_velt_type(in, vt);
1742 }
1743 }
1744 }
1745 }
1746 }
1747 }
1748 #ifndef PRODUCT
1749 if (TraceSuperWord && Verbose) {
1750 for (int i = 0; i < _block.length(); i++) {
1751 Node* n = _block.at(i);
1752 velt_type(n)->dump();
1753 tty->print("\t");
1754 n->dump();
1755 }
1756 }
1757 #endif
1758 }
1760 //------------------------------memory_alignment---------------------------
1761 // Alignment within a vector memory reference
1762 int SuperWord::memory_alignment(MemNode* s, int iv_adjust_in_bytes) {
1763 SWPointer p(s, this);
1764 if (!p.valid()) {
1765 return bottom_align;
1766 }
1767 int vw = vector_width_in_bytes(velt_basic_type(s));
1768 if (vw < 2) {
1769 return bottom_align; // No vectors for this type
1770 }
1771 int offset = p.offset_in_bytes();
1772 offset += iv_adjust_in_bytes;
1773 int off_rem = offset % vw;
1774 int off_mod = off_rem >= 0 ? off_rem : off_rem + vw;
1775 return off_mod;
1776 }
1778 //---------------------------container_type---------------------------
1779 // Smallest type containing range of values
1780 const Type* SuperWord::container_type(Node* n) {
1781 if (n->is_Mem()) {
1782 return Type::get_const_basic_type(n->as_Mem()->memory_type());
1783 }
1784 const Type* t = _igvn.type(n);
1785 if (t->basic_type() == T_INT) {
1786 if (t->higher_equal(TypeInt::BOOL)) return TypeInt::BOOL;
1787 if (t->higher_equal(TypeInt::BYTE)) return TypeInt::BYTE;
1788 if (t->higher_equal(TypeInt::CHAR)) return TypeInt::CHAR;
1789 if (t->higher_equal(TypeInt::SHORT)) return TypeInt::SHORT;
1790 return TypeInt::INT;
1791 }
1792 return t;
1793 }
1795 bool SuperWord::same_velt_type(Node* n1, Node* n2) {
1796 const Type* vt1 = velt_type(n1);
1797 const Type* vt2 = velt_type(n1);
1798 if (vt1->basic_type() == T_INT && vt2->basic_type() == T_INT) {
1799 // Compare vectors element sizes for integer types.
1800 return data_size(n1) == data_size(n2);
1801 }
1802 return vt1 == vt2;
1803 }
1805 //-------------------------vector_opd_range-----------------------
1806 // (Start, end] half-open range defining which operands are vector
1807 void SuperWord::vector_opd_range(Node* n, uint* start, uint* end) {
1808 switch (n->Opcode()) {
1809 case Op_LoadB: case Op_LoadUB:
1810 case Op_LoadS: case Op_LoadUS:
1811 case Op_LoadI: case Op_LoadL:
1812 case Op_LoadF: case Op_LoadD:
1813 case Op_LoadP:
1814 *start = 0;
1815 *end = 0;
1816 return;
1817 case Op_StoreB: case Op_StoreC:
1818 case Op_StoreI: case Op_StoreL:
1819 case Op_StoreF: case Op_StoreD:
1820 case Op_StoreP:
1821 *start = MemNode::ValueIn;
1822 *end = *start + 1;
1823 return;
1824 case Op_LShiftI: case Op_LShiftL:
1825 *start = 1;
1826 *end = 2;
1827 return;
1828 case Op_CMoveI: case Op_CMoveL: case Op_CMoveF: case Op_CMoveD:
1829 *start = 2;
1830 *end = n->req();
1831 return;
1832 }
1833 *start = 1;
1834 *end = n->req(); // default is all operands
1835 }
1837 //------------------------------in_packset---------------------------
1838 // Are s1 and s2 in a pack pair and ordered as s1,s2?
1839 bool SuperWord::in_packset(Node* s1, Node* s2) {
1840 for (int i = 0; i < _packset.length(); i++) {
1841 Node_List* p = _packset.at(i);
1842 assert(p->size() == 2, "must be");
1843 if (p->at(0) == s1 && p->at(p->size()-1) == s2) {
1844 return true;
1845 }
1846 }
1847 return false;
1848 }
1850 //------------------------------in_pack---------------------------
1851 // Is s in pack p?
1852 Node_List* SuperWord::in_pack(Node* s, Node_List* p) {
1853 for (uint i = 0; i < p->size(); i++) {
1854 if (p->at(i) == s) {
1855 return p;
1856 }
1857 }
1858 return NULL;
1859 }
1861 //------------------------------remove_pack_at---------------------------
1862 // Remove the pack at position pos in the packset
1863 void SuperWord::remove_pack_at(int pos) {
1864 Node_List* p = _packset.at(pos);
1865 for (uint i = 0; i < p->size(); i++) {
1866 Node* s = p->at(i);
1867 set_my_pack(s, NULL);
1868 }
1869 _packset.remove_at(pos);
1870 }
1872 //------------------------------executed_first---------------------------
1873 // Return the node executed first in pack p. Uses the RPO block list
1874 // to determine order.
1875 Node* SuperWord::executed_first(Node_List* p) {
1876 Node* n = p->at(0);
1877 int n_rpo = bb_idx(n);
1878 for (uint i = 1; i < p->size(); i++) {
1879 Node* s = p->at(i);
1880 int s_rpo = bb_idx(s);
1881 if (s_rpo < n_rpo) {
1882 n = s;
1883 n_rpo = s_rpo;
1884 }
1885 }
1886 return n;
1887 }
1889 //------------------------------executed_last---------------------------
1890 // Return the node executed last in pack p.
1891 Node* SuperWord::executed_last(Node_List* p) {
1892 Node* n = p->at(0);
1893 int n_rpo = bb_idx(n);
1894 for (uint i = 1; i < p->size(); i++) {
1895 Node* s = p->at(i);
1896 int s_rpo = bb_idx(s);
1897 if (s_rpo > n_rpo) {
1898 n = s;
1899 n_rpo = s_rpo;
1900 }
1901 }
1902 return n;
1903 }
1905 //----------------------------align_initial_loop_index---------------------------
1906 // Adjust pre-loop limit so that in main loop, a load/store reference
1907 // to align_to_ref will be a position zero in the vector.
1908 // (iv + k) mod vector_align == 0
1909 void SuperWord::align_initial_loop_index(MemNode* align_to_ref) {
1910 CountedLoopNode *main_head = lp()->as_CountedLoop();
1911 assert(main_head->is_main_loop(), "");
1912 CountedLoopEndNode* pre_end = get_pre_loop_end(main_head);
1913 assert(pre_end != NULL, "");
1914 Node *pre_opaq1 = pre_end->limit();
1915 assert(pre_opaq1->Opcode() == Op_Opaque1, "");
1916 Opaque1Node *pre_opaq = (Opaque1Node*)pre_opaq1;
1917 Node *lim0 = pre_opaq->in(1);
1919 // Where we put new limit calculations
1920 Node *pre_ctrl = pre_end->loopnode()->in(LoopNode::EntryControl);
1922 // Ensure the original loop limit is available from the
1923 // pre-loop Opaque1 node.
1924 Node *orig_limit = pre_opaq->original_loop_limit();
1925 assert(orig_limit != NULL && _igvn.type(orig_limit) != Type::TOP, "");
1927 SWPointer align_to_ref_p(align_to_ref, this);
1928 assert(align_to_ref_p.valid(), "sanity");
1930 // Given:
1931 // lim0 == original pre loop limit
1932 // V == v_align (power of 2)
1933 // invar == extra invariant piece of the address expression
1934 // e == k [ +/- invar ]
1935 //
1936 // When reassociating expressions involving '%' the basic rules are:
1937 // (a - b) % k == 0 => a % k == b % k
1938 // and:
1939 // (a + b) % k == 0 => a % k == (k - b) % k
1940 //
1941 // For stride > 0 && scale > 0,
1942 // Derive the new pre-loop limit "lim" such that the two constraints:
1943 // (1) lim = lim0 + N (where N is some positive integer < V)
1944 // (2) (e + lim) % V == 0
1945 // are true.
1946 //
1947 // Substituting (1) into (2),
1948 // (e + lim0 + N) % V == 0
1949 // solve for N:
1950 // N = (V - (e + lim0)) % V
1951 // substitute back into (1), so that new limit
1952 // lim = lim0 + (V - (e + lim0)) % V
1953 //
1954 // For stride > 0 && scale < 0
1955 // Constraints:
1956 // lim = lim0 + N
1957 // (e - lim) % V == 0
1958 // Solving for lim:
1959 // (e - lim0 - N) % V == 0
1960 // N = (e - lim0) % V
1961 // lim = lim0 + (e - lim0) % V
1962 //
1963 // For stride < 0 && scale > 0
1964 // Constraints:
1965 // lim = lim0 - N
1966 // (e + lim) % V == 0
1967 // Solving for lim:
1968 // (e + lim0 - N) % V == 0
1969 // N = (e + lim0) % V
1970 // lim = lim0 - (e + lim0) % V
1971 //
1972 // For stride < 0 && scale < 0
1973 // Constraints:
1974 // lim = lim0 - N
1975 // (e - lim) % V == 0
1976 // Solving for lim:
1977 // (e - lim0 + N) % V == 0
1978 // N = (V - (e - lim0)) % V
1979 // lim = lim0 - (V - (e - lim0)) % V
1981 int vw = vector_width_in_bytes(velt_basic_type(align_to_ref));
1982 assert(vw > 1, "sanity");
1983 int stride = iv_stride();
1984 int scale = align_to_ref_p.scale_in_bytes();
1985 int elt_size = align_to_ref_p.memory_size();
1986 int v_align = vw / elt_size;
1987 int k = align_to_ref_p.offset_in_bytes() / elt_size;
1989 Node *kn = _igvn.intcon(k);
1991 Node *e = kn;
1992 if (align_to_ref_p.invar() != NULL) {
1993 // incorporate any extra invariant piece producing k +/- invar >>> log2(elt)
1994 Node* log2_elt = _igvn.intcon(exact_log2(elt_size));
1995 Node* aref = new (_phase->C, 3) URShiftINode(align_to_ref_p.invar(), log2_elt);
1996 _phase->_igvn.register_new_node_with_optimizer(aref);
1997 _phase->set_ctrl(aref, pre_ctrl);
1998 if (align_to_ref_p.negate_invar()) {
1999 e = new (_phase->C, 3) SubINode(e, aref);
2000 } else {
2001 e = new (_phase->C, 3) AddINode(e, aref);
2002 }
2003 _phase->_igvn.register_new_node_with_optimizer(e);
2004 _phase->set_ctrl(e, pre_ctrl);
2005 }
2006 if (vw > ObjectAlignmentInBytes) {
2007 // incorporate base e +/- base && Mask >>> log2(elt)
2008 Node* mask = _igvn.MakeConX(~(-1 << exact_log2(vw)));
2009 Node* xbase = new(_phase->C, 2) CastP2XNode(NULL, align_to_ref_p.base());
2010 _phase->_igvn.register_new_node_with_optimizer(xbase);
2011 Node* masked_xbase = new (_phase->C, 3) AndXNode(xbase, mask);
2012 _phase->_igvn.register_new_node_with_optimizer(masked_xbase);
2013 #ifdef _LP64
2014 masked_xbase = new (_phase->C, 2) ConvL2INode(masked_xbase);
2015 _phase->_igvn.register_new_node_with_optimizer(masked_xbase);
2016 #endif
2017 Node* log2_elt = _igvn.intcon(exact_log2(elt_size));
2018 Node* bref = new (_phase->C, 3) URShiftINode(masked_xbase, log2_elt);
2019 _phase->_igvn.register_new_node_with_optimizer(bref);
2020 _phase->set_ctrl(bref, pre_ctrl);
2021 e = new (_phase->C, 3) AddINode(e, bref);
2022 _phase->_igvn.register_new_node_with_optimizer(e);
2023 _phase->set_ctrl(e, pre_ctrl);
2024 }
2026 // compute e +/- lim0
2027 if (scale < 0) {
2028 e = new (_phase->C, 3) SubINode(e, lim0);
2029 } else {
2030 e = new (_phase->C, 3) AddINode(e, lim0);
2031 }
2032 _phase->_igvn.register_new_node_with_optimizer(e);
2033 _phase->set_ctrl(e, pre_ctrl);
2035 if (stride * scale > 0) {
2036 // compute V - (e +/- lim0)
2037 Node* va = _igvn.intcon(v_align);
2038 e = new (_phase->C, 3) SubINode(va, e);
2039 _phase->_igvn.register_new_node_with_optimizer(e);
2040 _phase->set_ctrl(e, pre_ctrl);
2041 }
2042 // compute N = (exp) % V
2043 Node* va_msk = _igvn.intcon(v_align - 1);
2044 Node* N = new (_phase->C, 3) AndINode(e, va_msk);
2045 _phase->_igvn.register_new_node_with_optimizer(N);
2046 _phase->set_ctrl(N, pre_ctrl);
2048 // substitute back into (1), so that new limit
2049 // lim = lim0 + N
2050 Node* lim;
2051 if (stride < 0) {
2052 lim = new (_phase->C, 3) SubINode(lim0, N);
2053 } else {
2054 lim = new (_phase->C, 3) AddINode(lim0, N);
2055 }
2056 _phase->_igvn.register_new_node_with_optimizer(lim);
2057 _phase->set_ctrl(lim, pre_ctrl);
2058 Node* constrained =
2059 (stride > 0) ? (Node*) new (_phase->C,3) MinINode(lim, orig_limit)
2060 : (Node*) new (_phase->C,3) MaxINode(lim, orig_limit);
2061 _phase->_igvn.register_new_node_with_optimizer(constrained);
2062 _phase->set_ctrl(constrained, pre_ctrl);
2063 _igvn.hash_delete(pre_opaq);
2064 pre_opaq->set_req(1, constrained);
2065 }
2067 //----------------------------get_pre_loop_end---------------------------
2068 // Find pre loop end from main loop. Returns null if none.
2069 CountedLoopEndNode* SuperWord::get_pre_loop_end(CountedLoopNode *cl) {
2070 Node *ctrl = cl->in(LoopNode::EntryControl);
2071 if (!ctrl->is_IfTrue() && !ctrl->is_IfFalse()) return NULL;
2072 Node *iffm = ctrl->in(0);
2073 if (!iffm->is_If()) return NULL;
2074 Node *p_f = iffm->in(0);
2075 if (!p_f->is_IfFalse()) return NULL;
2076 if (!p_f->in(0)->is_CountedLoopEnd()) return NULL;
2077 CountedLoopEndNode *pre_end = p_f->in(0)->as_CountedLoopEnd();
2078 if (!pre_end->loopnode()->is_pre_loop()) return NULL;
2079 return pre_end;
2080 }
2083 //------------------------------init---------------------------
2084 void SuperWord::init() {
2085 _dg.init();
2086 _packset.clear();
2087 _disjoint_ptrs.clear();
2088 _block.clear();
2089 _data_entry.clear();
2090 _mem_slice_head.clear();
2091 _mem_slice_tail.clear();
2092 _node_info.clear();
2093 _align_to_ref = NULL;
2094 _lpt = NULL;
2095 _lp = NULL;
2096 _bb = NULL;
2097 _iv = NULL;
2098 }
2100 //------------------------------print_packset---------------------------
2101 void SuperWord::print_packset() {
2102 #ifndef PRODUCT
2103 tty->print_cr("packset");
2104 for (int i = 0; i < _packset.length(); i++) {
2105 tty->print_cr("Pack: %d", i);
2106 Node_List* p = _packset.at(i);
2107 print_pack(p);
2108 }
2109 #endif
2110 }
2112 //------------------------------print_pack---------------------------
2113 void SuperWord::print_pack(Node_List* p) {
2114 for (uint i = 0; i < p->size(); i++) {
2115 print_stmt(p->at(i));
2116 }
2117 }
2119 //------------------------------print_bb---------------------------
2120 void SuperWord::print_bb() {
2121 #ifndef PRODUCT
2122 tty->print_cr("\nBlock");
2123 for (int i = 0; i < _block.length(); i++) {
2124 Node* n = _block.at(i);
2125 tty->print("%d ", i);
2126 if (n) {
2127 n->dump();
2128 }
2129 }
2130 #endif
2131 }
2133 //------------------------------print_stmt---------------------------
2134 void SuperWord::print_stmt(Node* s) {
2135 #ifndef PRODUCT
2136 tty->print(" align: %d \t", alignment(s));
2137 s->dump();
2138 #endif
2139 }
2141 //------------------------------blank---------------------------
2142 char* SuperWord::blank(uint depth) {
2143 static char blanks[101];
2144 assert(depth < 101, "too deep");
2145 for (uint i = 0; i < depth; i++) blanks[i] = ' ';
2146 blanks[depth] = '\0';
2147 return blanks;
2148 }
2151 //==============================SWPointer===========================
2153 //----------------------------SWPointer------------------------
2154 SWPointer::SWPointer(MemNode* mem, SuperWord* slp) :
2155 _mem(mem), _slp(slp), _base(NULL), _adr(NULL),
2156 _scale(0), _offset(0), _invar(NULL), _negate_invar(false) {
2158 Node* adr = mem->in(MemNode::Address);
2159 if (!adr->is_AddP()) {
2160 assert(!valid(), "too complex");
2161 return;
2162 }
2163 // Match AddP(base, AddP(ptr, k*iv [+ invariant]), constant)
2164 Node* base = adr->in(AddPNode::Base);
2165 //unsafe reference could not be aligned appropriately without runtime checking
2166 if (base == NULL || base->bottom_type() == Type::TOP) {
2167 assert(!valid(), "unsafe access");
2168 return;
2169 }
2170 for (int i = 0; i < 3; i++) {
2171 if (!scaled_iv_plus_offset(adr->in(AddPNode::Offset))) {
2172 assert(!valid(), "too complex");
2173 return;
2174 }
2175 adr = adr->in(AddPNode::Address);
2176 if (base == adr || !adr->is_AddP()) {
2177 break; // stop looking at addp's
2178 }
2179 }
2180 _base = base;
2181 _adr = adr;
2182 assert(valid(), "Usable");
2183 }
2185 // Following is used to create a temporary object during
2186 // the pattern match of an address expression.
2187 SWPointer::SWPointer(SWPointer* p) :
2188 _mem(p->_mem), _slp(p->_slp), _base(NULL), _adr(NULL),
2189 _scale(0), _offset(0), _invar(NULL), _negate_invar(false) {}
2191 //------------------------scaled_iv_plus_offset--------------------
2192 // Match: k*iv + offset
2193 // where: k is a constant that maybe zero, and
2194 // offset is (k2 [+/- invariant]) where k2 maybe zero and invariant is optional
2195 bool SWPointer::scaled_iv_plus_offset(Node* n) {
2196 if (scaled_iv(n)) {
2197 return true;
2198 }
2199 if (offset_plus_k(n)) {
2200 return true;
2201 }
2202 int opc = n->Opcode();
2203 if (opc == Op_AddI) {
2204 if (scaled_iv(n->in(1)) && offset_plus_k(n->in(2))) {
2205 return true;
2206 }
2207 if (scaled_iv(n->in(2)) && offset_plus_k(n->in(1))) {
2208 return true;
2209 }
2210 } else if (opc == Op_SubI) {
2211 if (scaled_iv(n->in(1)) && offset_plus_k(n->in(2), true)) {
2212 return true;
2213 }
2214 if (scaled_iv(n->in(2)) && offset_plus_k(n->in(1))) {
2215 _scale *= -1;
2216 return true;
2217 }
2218 }
2219 return false;
2220 }
2222 //----------------------------scaled_iv------------------------
2223 // Match: k*iv where k is a constant that's not zero
2224 bool SWPointer::scaled_iv(Node* n) {
2225 if (_scale != 0) {
2226 return false; // already found a scale
2227 }
2228 if (n == iv()) {
2229 _scale = 1;
2230 return true;
2231 }
2232 int opc = n->Opcode();
2233 if (opc == Op_MulI) {
2234 if (n->in(1) == iv() && n->in(2)->is_Con()) {
2235 _scale = n->in(2)->get_int();
2236 return true;
2237 } else if (n->in(2) == iv() && n->in(1)->is_Con()) {
2238 _scale = n->in(1)->get_int();
2239 return true;
2240 }
2241 } else if (opc == Op_LShiftI) {
2242 if (n->in(1) == iv() && n->in(2)->is_Con()) {
2243 _scale = 1 << n->in(2)->get_int();
2244 return true;
2245 }
2246 } else if (opc == Op_ConvI2L) {
2247 if (scaled_iv_plus_offset(n->in(1))) {
2248 return true;
2249 }
2250 } else if (opc == Op_LShiftL) {
2251 if (!has_iv() && _invar == NULL) {
2252 // Need to preserve the current _offset value, so
2253 // create a temporary object for this expression subtree.
2254 // Hacky, so should re-engineer the address pattern match.
2255 SWPointer tmp(this);
2256 if (tmp.scaled_iv_plus_offset(n->in(1))) {
2257 if (tmp._invar == NULL) {
2258 int mult = 1 << n->in(2)->get_int();
2259 _scale = tmp._scale * mult;
2260 _offset += tmp._offset * mult;
2261 return true;
2262 }
2263 }
2264 }
2265 }
2266 return false;
2267 }
2269 //----------------------------offset_plus_k------------------------
2270 // Match: offset is (k [+/- invariant])
2271 // where k maybe zero and invariant is optional, but not both.
2272 bool SWPointer::offset_plus_k(Node* n, bool negate) {
2273 int opc = n->Opcode();
2274 if (opc == Op_ConI) {
2275 _offset += negate ? -(n->get_int()) : n->get_int();
2276 return true;
2277 } else if (opc == Op_ConL) {
2278 // Okay if value fits into an int
2279 const TypeLong* t = n->find_long_type();
2280 if (t->higher_equal(TypeLong::INT)) {
2281 jlong loff = n->get_long();
2282 jint off = (jint)loff;
2283 _offset += negate ? -off : loff;
2284 return true;
2285 }
2286 return false;
2287 }
2288 if (_invar != NULL) return false; // already have an invariant
2289 if (opc == Op_AddI) {
2290 if (n->in(2)->is_Con() && invariant(n->in(1))) {
2291 _negate_invar = negate;
2292 _invar = n->in(1);
2293 _offset += negate ? -(n->in(2)->get_int()) : n->in(2)->get_int();
2294 return true;
2295 } else if (n->in(1)->is_Con() && invariant(n->in(2))) {
2296 _offset += negate ? -(n->in(1)->get_int()) : n->in(1)->get_int();
2297 _negate_invar = negate;
2298 _invar = n->in(2);
2299 return true;
2300 }
2301 }
2302 if (opc == Op_SubI) {
2303 if (n->in(2)->is_Con() && invariant(n->in(1))) {
2304 _negate_invar = negate;
2305 _invar = n->in(1);
2306 _offset += !negate ? -(n->in(2)->get_int()) : n->in(2)->get_int();
2307 return true;
2308 } else if (n->in(1)->is_Con() && invariant(n->in(2))) {
2309 _offset += negate ? -(n->in(1)->get_int()) : n->in(1)->get_int();
2310 _negate_invar = !negate;
2311 _invar = n->in(2);
2312 return true;
2313 }
2314 }
2315 if (invariant(n)) {
2316 _negate_invar = negate;
2317 _invar = n;
2318 return true;
2319 }
2320 return false;
2321 }
2323 //----------------------------print------------------------
2324 void SWPointer::print() {
2325 #ifndef PRODUCT
2326 tty->print("base: %d adr: %d scale: %d offset: %d invar: %c%d\n",
2327 _base != NULL ? _base->_idx : 0,
2328 _adr != NULL ? _adr->_idx : 0,
2329 _scale, _offset,
2330 _negate_invar?'-':'+',
2331 _invar != NULL ? _invar->_idx : 0);
2332 #endif
2333 }
2335 // ========================= OrderedPair =====================
2337 const OrderedPair OrderedPair::initial;
2339 // ========================= SWNodeInfo =====================
2341 const SWNodeInfo SWNodeInfo::initial;
2344 // ============================ DepGraph ===========================
2346 //------------------------------make_node---------------------------
2347 // Make a new dependence graph node for an ideal node.
2348 DepMem* DepGraph::make_node(Node* node) {
2349 DepMem* m = new (_arena) DepMem(node);
2350 if (node != NULL) {
2351 assert(_map.at_grow(node->_idx) == NULL, "one init only");
2352 _map.at_put_grow(node->_idx, m);
2353 }
2354 return m;
2355 }
2357 //------------------------------make_edge---------------------------
2358 // Make a new dependence graph edge from dpred -> dsucc
2359 DepEdge* DepGraph::make_edge(DepMem* dpred, DepMem* dsucc) {
2360 DepEdge* e = new (_arena) DepEdge(dpred, dsucc, dsucc->in_head(), dpred->out_head());
2361 dpred->set_out_head(e);
2362 dsucc->set_in_head(e);
2363 return e;
2364 }
2366 // ========================== DepMem ========================
2368 //------------------------------in_cnt---------------------------
2369 int DepMem::in_cnt() {
2370 int ct = 0;
2371 for (DepEdge* e = _in_head; e != NULL; e = e->next_in()) ct++;
2372 return ct;
2373 }
2375 //------------------------------out_cnt---------------------------
2376 int DepMem::out_cnt() {
2377 int ct = 0;
2378 for (DepEdge* e = _out_head; e != NULL; e = e->next_out()) ct++;
2379 return ct;
2380 }
2382 //------------------------------print-----------------------------
2383 void DepMem::print() {
2384 #ifndef PRODUCT
2385 tty->print(" DepNode %d (", _node->_idx);
2386 for (DepEdge* p = _in_head; p != NULL; p = p->next_in()) {
2387 Node* pred = p->pred()->node();
2388 tty->print(" %d", pred != NULL ? pred->_idx : 0);
2389 }
2390 tty->print(") [");
2391 for (DepEdge* s = _out_head; s != NULL; s = s->next_out()) {
2392 Node* succ = s->succ()->node();
2393 tty->print(" %d", succ != NULL ? succ->_idx : 0);
2394 }
2395 tty->print_cr(" ]");
2396 #endif
2397 }
2399 // =========================== DepEdge =========================
2401 //------------------------------DepPreds---------------------------
2402 void DepEdge::print() {
2403 #ifndef PRODUCT
2404 tty->print_cr("DepEdge: %d [ %d ]", _pred->node()->_idx, _succ->node()->_idx);
2405 #endif
2406 }
2408 // =========================== DepPreds =========================
2409 // Iterator over predecessor edges in the dependence graph.
2411 //------------------------------DepPreds---------------------------
2412 DepPreds::DepPreds(Node* n, DepGraph& dg) {
2413 _n = n;
2414 _done = false;
2415 if (_n->is_Store() || _n->is_Load()) {
2416 _next_idx = MemNode::Address;
2417 _end_idx = n->req();
2418 _dep_next = dg.dep(_n)->in_head();
2419 } else if (_n->is_Mem()) {
2420 _next_idx = 0;
2421 _end_idx = 0;
2422 _dep_next = dg.dep(_n)->in_head();
2423 } else {
2424 _next_idx = 1;
2425 _end_idx = _n->req();
2426 _dep_next = NULL;
2427 }
2428 next();
2429 }
2431 //------------------------------next---------------------------
2432 void DepPreds::next() {
2433 if (_dep_next != NULL) {
2434 _current = _dep_next->pred()->node();
2435 _dep_next = _dep_next->next_in();
2436 } else if (_next_idx < _end_idx) {
2437 _current = _n->in(_next_idx++);
2438 } else {
2439 _done = true;
2440 }
2441 }
2443 // =========================== DepSuccs =========================
2444 // Iterator over successor edges in the dependence graph.
2446 //------------------------------DepSuccs---------------------------
2447 DepSuccs::DepSuccs(Node* n, DepGraph& dg) {
2448 _n = n;
2449 _done = false;
2450 if (_n->is_Load()) {
2451 _next_idx = 0;
2452 _end_idx = _n->outcnt();
2453 _dep_next = dg.dep(_n)->out_head();
2454 } else if (_n->is_Mem() || _n->is_Phi() && _n->bottom_type() == Type::MEMORY) {
2455 _next_idx = 0;
2456 _end_idx = 0;
2457 _dep_next = dg.dep(_n)->out_head();
2458 } else {
2459 _next_idx = 0;
2460 _end_idx = _n->outcnt();
2461 _dep_next = NULL;
2462 }
2463 next();
2464 }
2466 //-------------------------------next---------------------------
2467 void DepSuccs::next() {
2468 if (_dep_next != NULL) {
2469 _current = _dep_next->succ()->node();
2470 _dep_next = _dep_next->next_out();
2471 } else if (_next_idx < _end_idx) {
2472 _current = _n->raw_out(_next_idx++);
2473 } else {
2474 _done = true;
2475 }
2476 }