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