1 /*
   2  * Copyright (c) 2007, 2015, 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   _clone_map(phase->C->clone_map()),      // map of nodes created in cloning
  58   _align_to_ref(NULL),                    // memory reference to align vectors to
  59   _disjoint_ptrs(arena(), 8,  0, OrderedPair::initial), // runtime disambiguated pointer pairs
  60   _dg(_arena),                            // dependence graph
  61   _visited(arena()),                      // visited node set
  62   _post_visited(arena()),                 // post visited node set
  63   _n_idx_list(arena(), 8),                // scratch list of (node,index) pairs
  64   _stk(arena(), 8, 0, NULL),              // scratch stack of nodes
  65   _nlist(arena(), 8, 0, NULL),            // scratch list of nodes
  66   _lpt(NULL),                             // loop tree node
  67   _lp(NULL),                              // LoopNode
  68   _bb(NULL),                              // basic block
  69   _iv(NULL),                              // induction var
  70   _race_possible(false),                  // cases where SDMU is true
  71   _early_return(true),                    // analysis evaluations routine
  72   _num_work_vecs(0),                      // amount of vector work we have
  73   _num_reductions(0),                     // amount of reduction work we have
  74   _do_vector_loop(phase->C->do_vector_loop()),  // whether to do vectorization/simd style
  75   _ii_first(-1),                          // first loop generation index - only if do_vector_loop()
  76   _ii_last(-1),                           // last loop generation index - only if do_vector_loop()
  77   _ii_order(arena(), 8, 0, 0),
  78   _vector_loop_debug(phase->C->has_method() && phase->C->method_has_option("VectorizeDebug"))
  79 {}
  80 
  81 //------------------------------transform_loop---------------------------
  82 void SuperWord::transform_loop(IdealLoopTree* lpt, bool do_optimization) {
  83   assert(UseSuperWord, "should be");
  84   // Do vectors exist on this architecture?
  85   if (Matcher::vector_width_in_bytes(T_BYTE) < 2) return;
  86 
  87   assert(lpt->_head->is_CountedLoop(), "must be");
  88   CountedLoopNode *cl = lpt->_head->as_CountedLoop();
  89 
  90   if (!cl->is_valid_counted_loop()) return; // skip malformed counted loop
  91 
  92   if (!cl->is_main_loop() ) return; // skip normal, pre, and post loops
  93 
  94   // Check for no control flow in body (other than exit)
  95   Node *cl_exit = cl->loopexit();
  96   if (cl_exit->in(0) != lpt->_head) return;
  97 
  98   // Make sure the are no extra control users of the loop backedge
  99   if (cl->back_control()->outcnt() != 1) {
 100     return;
 101   }
 102 
 103   // Check for pre-loop ending with CountedLoopEnd(Bool(Cmp(x,Opaque1(limit))))
 104   CountedLoopEndNode* pre_end = get_pre_loop_end(cl);
 105   if (pre_end == NULL) return;
 106   Node *pre_opaq1 = pre_end->limit();
 107   if (pre_opaq1->Opcode() != Op_Opaque1) return;
 108 
 109   init(); // initialize data structures
 110 
 111   set_lpt(lpt);
 112   set_lp(cl);
 113 
 114   // For now, define one block which is the entire loop body
 115   set_bb(cl);
 116 
 117   if (do_optimization) {
 118     assert(_packset.length() == 0, "packset must be empty");
 119     SLP_extract();
 120   }
 121 }
 122 
 123 //------------------------------early unrolling analysis------------------------------
 124 void SuperWord::unrolling_analysis(CountedLoopNode *cl, int &local_loop_unroll_factor) {
 125   bool is_slp = true;
 126   ResourceMark rm;
 127   size_t ignored_size = lpt()->_body.size();
 128   int *ignored_loop_nodes = NEW_RESOURCE_ARRAY(int, ignored_size);
 129   Node_Stack nstack((int)ignored_size);
 130   Node *cl_exit = cl->loopexit();
 131 
 132   // First clear the entries
 133   for (uint i = 0; i < lpt()->_body.size(); i++) {
 134     ignored_loop_nodes[i] = -1;
 135   }
 136 
 137   int max_vector = Matcher::max_vector_size(T_INT);
 138 
 139   // Process the loop, some/all of the stack entries will not be in order, ergo
 140   // need to preprocess the ignored initial state before we process the loop
 141   for (uint i = 0; i < lpt()->_body.size(); i++) {
 142     Node* n = lpt()->_body.at(i);
 143     if (n == cl->incr() ||
 144       n->is_reduction() ||
 145       n->is_AddP() ||
 146       n->is_Cmp() ||
 147       n->is_IfTrue() ||
 148       n->is_CountedLoop() ||
 149       (n == cl_exit)) {
 150       ignored_loop_nodes[i] = n->_idx;
 151       continue;
 152     }
 153 
 154     if (n->is_If()) {
 155       IfNode *iff = n->as_If();
 156       if (iff->_fcnt != COUNT_UNKNOWN && iff->_prob != PROB_UNKNOWN) {
 157         if (lpt()->is_loop_exit(iff)) {
 158           ignored_loop_nodes[i] = n->_idx;
 159           continue;
 160         }
 161       }
 162     }
 163 
 164     if (n->is_Phi() && (n->bottom_type() == Type::MEMORY)) {
 165       Node* n_tail = n->in(LoopNode::LoopBackControl);
 166       if (n_tail != n->in(LoopNode::EntryControl)) {
 167         if (!n_tail->is_Mem()) {
 168           is_slp = false;
 169           break;
 170         }
 171       }
 172     }
 173 
 174     // This must happen after check of phi/if
 175     if (n->is_Phi() || n->is_If()) {
 176       ignored_loop_nodes[i] = n->_idx;
 177       continue;
 178     }
 179 
 180     if (n->is_LoadStore() || n->is_MergeMem() ||
 181       (n->is_Proj() && !n->as_Proj()->is_CFG())) {
 182       is_slp = false;
 183       break;
 184     }
 185 
 186     if (n->is_Mem()) {
 187       Node* adr = n->in(MemNode::Address);
 188       Node* n_ctrl = _phase->get_ctrl(adr);
 189 
 190       // save a queue of post process nodes
 191       if (n_ctrl != NULL && lpt()->is_member(_phase->get_loop(n_ctrl))) {
 192         MemNode* current = n->as_Mem();
 193         BasicType bt = current->memory_type();
 194         if (is_java_primitive(bt) == false) {
 195           ignored_loop_nodes[i] = n->_idx;
 196           continue;
 197         }
 198 
 199         // Process the memory expression
 200         int stack_idx = 0;
 201         bool have_side_effects = true;
 202         if (adr->is_AddP() == false) {
 203           nstack.push(adr, stack_idx++);
 204         } else {
 205           // Mark the components of the memory operation in nstack
 206           SWPointer p1(current, this, &nstack, true);
 207           have_side_effects = p1.node_stack()->is_nonempty();
 208         }
 209 
 210         // Process the pointer stack
 211         while (have_side_effects) {
 212           Node* pointer_node = nstack.node();
 213           for (uint j = 0; j < lpt()->_body.size(); j++) {
 214             Node* cur_node = lpt()->_body.at(j);
 215             if (cur_node == pointer_node) {
 216               ignored_loop_nodes[j] = cur_node->_idx;
 217               break;
 218             }
 219           }
 220           nstack.pop();
 221           have_side_effects = nstack.is_nonempty();
 222         }
 223       }
 224     }
 225   }
 226 
 227   if (is_slp) {
 228     // Now we try to find the maximum supported consistent vector which the machine
 229     // description can use
 230     for (uint i = 0; i < lpt()->_body.size(); i++) {
 231       if (ignored_loop_nodes[i] != -1) continue;
 232 
 233       BasicType bt;
 234       Node* n = lpt()->_body.at(i);
 235       if (n->is_Store()) {
 236         bt = n->as_Mem()->memory_type();
 237       }
 238       else {
 239         bt = n->bottom_type()->basic_type();
 240       }
 241 
 242       int cur_max_vector = Matcher::max_vector_size(bt);
 243 
 244       // If a max vector exists which is not larger than _local_loop_unroll_factor
 245       // stop looking, we already have the max vector to map to.
 246       if (cur_max_vector <= local_loop_unroll_factor) {
 247         is_slp = false;
 248 #ifndef PRODUCT
 249         if (TraceSuperWordLoopUnrollAnalysis) {
 250           tty->print_cr("slp analysis fails: unroll limit equals max vector\n");
 251         }
 252 #endif
 253         break;
 254       }
 255 
 256       // Map the maximal common vector
 257       if (VectorNode::implemented(n->Opcode(), cur_max_vector, bt)) {
 258         if (cur_max_vector < max_vector) {
 259           max_vector = cur_max_vector;
 260         }
 261       }
 262     }
 263     if (is_slp) {
 264       local_loop_unroll_factor = max_vector;
 265     }
 266     cl->mark_passed_slp();
 267     cl->set_slp_max_unroll(local_loop_unroll_factor);
 268   }
 269 }
 270 
 271 //------------------------------SLP_extract---------------------------
 272 // Extract the superword level parallelism
 273 //
 274 // 1) A reverse post-order of nodes in the block is constructed.  By scanning
 275 //    this list from first to last, all definitions are visited before their uses.
 276 //
 277 // 2) A point-to-point dependence graph is constructed between memory references.
 278 //    This simplies the upcoming "independence" checker.
 279 //
 280 // 3) The maximum depth in the node graph from the beginning of the block
 281 //    to each node is computed.  This is used to prune the graph search
 282 //    in the independence checker.
 283 //
 284 // 4) For integer types, the necessary bit width is propagated backwards
 285 //    from stores to allow packed operations on byte, char, and short
 286 //    integers.  This reverses the promotion to type "int" that javac
 287 //    did for operations like: char c1,c2,c3;  c1 = c2 + c3.
 288 //
 289 // 5) One of the memory references is picked to be an aligned vector reference.
 290 //    The pre-loop trip count is adjusted to align this reference in the
 291 //    unrolled body.
 292 //
 293 // 6) The initial set of pack pairs is seeded with memory references.
 294 //
 295 // 7) The set of pack pairs is extended by following use->def and def->use links.
 296 //
 297 // 8) The pairs are combined into vector sized packs.
 298 //
 299 // 9) Reorder the memory slices to co-locate members of the memory packs.
 300 //
 301 // 10) Generate ideal vector nodes for the final set of packs and where necessary,
 302 //    inserting scalar promotion, vector creation from multiple scalars, and
 303 //    extraction of scalar values from vectors.
 304 //
 305 void SuperWord::SLP_extract() {
 306 
 307 #ifndef PRODUCT
 308   if (_do_vector_loop && TraceSuperWord) {
 309     tty->print("SuperWord::SLP_extract\n");
 310     tty->print("input loop\n");
 311     _lpt->dump_head();
 312     _lpt->dump();
 313     for (uint i = 0; i < _lpt->_body.size(); i++) {
 314       _lpt->_body.at(i)->dump();
 315     }
 316   }
 317 #endif
 318   // Ready the block
 319   if (!construct_bb()) {
 320     return; // Exit if no interesting nodes or complex graph.
 321   }
 322   // build    _dg, _disjoint_ptrs
 323   dependence_graph();
 324 
 325   // compute function depth(Node*)
 326   compute_max_depth();
 327 
 328   if (_do_vector_loop) {
 329     if (mark_generations() != -1) {
 330       hoist_loads_in_graph(); // this only rebuild the graph; all basic structs need rebuild explicitly
 331 
 332       if (!construct_bb()) {
 333         return; // Exit if no interesting nodes or complex graph.
 334       }
 335       dependence_graph();
 336       compute_max_depth();
 337     }
 338 
 339 #ifndef PRODUCT
 340     if (TraceSuperWord) {
 341       tty->print_cr("\nSuperWord::_do_vector_loop: graph after hoist_loads_in_graph");
 342       _lpt->dump_head();
 343       for (int j = 0; j < _block.length(); j++) {
 344         Node* n = _block.at(j);
 345         int d = depth(n);
 346         for (int i = 0;  i < d; i++) tty->print("%s", "  ");
 347         tty->print("%d :", d);
 348         n->dump();
 349       }
 350     }
 351 #endif
 352   }
 353 
 354   compute_vector_element_type();
 355 
 356   // Attempt vectorization
 357 
 358   find_adjacent_refs();
 359 
 360   extend_packlist();
 361 
 362   if (_do_vector_loop) {
 363     if (_packset.length() == 0) {
 364 #ifndef PRODUCT
 365       if (TraceSuperWord) {
 366         tty->print_cr("\nSuperWord::_do_vector_loop DFA could not build packset, now trying to build anyway");
 367       }
 368 #endif
 369       pack_parallel();
 370     }
 371   }
 372 
 373   combine_packs();
 374 
 375   construct_my_pack_map();
 376 
 377   filter_packs();
 378 
 379   schedule();
 380 
 381   output();
 382 }
 383 
 384 //------------------------------find_adjacent_refs---------------------------
 385 // Find the adjacent memory references and create pack pairs for them.
 386 // This is the initial set of packs that will then be extended by
 387 // following use->def and def->use links.  The align positions are
 388 // assigned relative to the reference "align_to_ref"
 389 void SuperWord::find_adjacent_refs() {
 390   // Get list of memory operations
 391   Node_List memops;
 392   for (int i = 0; i < _block.length(); i++) {
 393     Node* n = _block.at(i);
 394     if (n->is_Mem() && !n->is_LoadStore() && in_bb(n) &&
 395         is_java_primitive(n->as_Mem()->memory_type())) {
 396       int align = memory_alignment(n->as_Mem(), 0);
 397       if (align != bottom_align) {
 398         memops.push(n);
 399       }
 400     }
 401   }
 402 
 403   Node_List align_to_refs;
 404   int best_iv_adjustment = 0;
 405   MemNode* best_align_to_mem_ref = NULL;
 406 
 407   while (memops.size() != 0) {
 408     // Find a memory reference to align to.
 409     MemNode* mem_ref = find_align_to_ref(memops);
 410     if (mem_ref == NULL) break;
 411     align_to_refs.push(mem_ref);
 412     int iv_adjustment = get_iv_adjustment(mem_ref);
 413 
 414     if (best_align_to_mem_ref == NULL) {
 415       // Set memory reference which is the best from all memory operations
 416       // to be used for alignment. The pre-loop trip count is modified to align
 417       // this reference to a vector-aligned address.
 418       best_align_to_mem_ref = mem_ref;
 419       best_iv_adjustment = iv_adjustment;
 420     }
 421 
 422     SWPointer align_to_ref_p(mem_ref, this, NULL, false);
 423     // Set alignment relative to "align_to_ref" for all related memory operations.
 424     for (int i = memops.size() - 1; i >= 0; i--) {
 425       MemNode* s = memops.at(i)->as_Mem();
 426       if (isomorphic(s, mem_ref)) {
 427         SWPointer p2(s, this, NULL, false);
 428         if (p2.comparable(align_to_ref_p)) {
 429           int align = memory_alignment(s, iv_adjustment);
 430           set_alignment(s, align);
 431         }
 432       }
 433     }
 434 
 435     // Create initial pack pairs of memory operations for which
 436     // alignment is set and vectors will be aligned.
 437     bool create_pack = true;
 438     if (memory_alignment(mem_ref, best_iv_adjustment) == 0 || _do_vector_loop) {
 439       if (!Matcher::misaligned_vectors_ok()) {
 440         int vw = vector_width(mem_ref);
 441         int vw_best = vector_width(best_align_to_mem_ref);
 442         if (vw > vw_best) {
 443           // Do not vectorize a memory access with more elements per vector
 444           // if unaligned memory access is not allowed because number of
 445           // iterations in pre-loop will be not enough to align it.
 446           create_pack = false;
 447         } else {
 448           SWPointer p2(best_align_to_mem_ref, this, NULL, false);
 449           if (align_to_ref_p.invar() != p2.invar()) {
 450             // Do not vectorize memory accesses with different invariants
 451             // if unaligned memory accesses are not allowed.
 452             create_pack = false;
 453           }
 454         }
 455       }
 456     } else {
 457       if (same_velt_type(mem_ref, best_align_to_mem_ref)) {
 458         // Can't allow vectorization of unaligned memory accesses with the
 459         // same type since it could be overlapped accesses to the same array.
 460         create_pack = false;
 461       } else {
 462         // Allow independent (different type) unaligned memory operations
 463         // if HW supports them.
 464         if (!Matcher::misaligned_vectors_ok()) {
 465           create_pack = false;
 466         } else {
 467           // Check if packs of the same memory type but
 468           // with a different alignment were created before.
 469           for (uint i = 0; i < align_to_refs.size(); i++) {
 470             MemNode* mr = align_to_refs.at(i)->as_Mem();
 471             if (same_velt_type(mr, mem_ref) &&
 472                 memory_alignment(mr, iv_adjustment) != 0)
 473               create_pack = false;
 474           }
 475         }
 476       }
 477     }
 478     if (create_pack) {
 479       for (uint i = 0; i < memops.size(); i++) {
 480         Node* s1 = memops.at(i);
 481         int align = alignment(s1);
 482         if (align == top_align) continue;
 483         for (uint j = 0; j < memops.size(); j++) {
 484           Node* s2 = memops.at(j);
 485           if (alignment(s2) == top_align) continue;
 486           if (s1 != s2 && are_adjacent_refs(s1, s2)) {
 487             if (stmts_can_pack(s1, s2, align)) {
 488               Node_List* pair = new Node_List();
 489               pair->push(s1);
 490               pair->push(s2);
 491               if (!_do_vector_loop || _clone_map.idx(s1->_idx) == _clone_map.idx(s2->_idx)) {
 492                 _packset.append(pair);
 493               }
 494             }
 495           }
 496         }
 497       }
 498     } else { // Don't create unaligned pack
 499       // First, remove remaining memory ops of the same type from the list.
 500       for (int i = memops.size() - 1; i >= 0; i--) {
 501         MemNode* s = memops.at(i)->as_Mem();
 502         if (same_velt_type(s, mem_ref)) {
 503           memops.remove(i);
 504         }
 505       }
 506 
 507       // Second, remove already constructed packs of the same type.
 508       for (int i = _packset.length() - 1; i >= 0; i--) {
 509         Node_List* p = _packset.at(i);
 510         MemNode* s = p->at(0)->as_Mem();
 511         if (same_velt_type(s, mem_ref)) {
 512           remove_pack_at(i);
 513         }
 514       }
 515 
 516       // If needed find the best memory reference for loop alignment again.
 517       if (same_velt_type(mem_ref, best_align_to_mem_ref)) {
 518         // Put memory ops from remaining packs back on memops list for
 519         // the best alignment search.
 520         uint orig_msize = memops.size();
 521         for (int i = 0; i < _packset.length(); i++) {
 522           Node_List* p = _packset.at(i);
 523           MemNode* s = p->at(0)->as_Mem();
 524           assert(!same_velt_type(s, mem_ref), "sanity");
 525           memops.push(s);
 526         }
 527         MemNode* best_align_to_mem_ref = find_align_to_ref(memops);
 528         if (best_align_to_mem_ref == NULL) break;
 529         best_iv_adjustment = get_iv_adjustment(best_align_to_mem_ref);
 530         // Restore list.
 531         while (memops.size() > orig_msize)
 532           (void)memops.pop();
 533       }
 534     } // unaligned memory accesses
 535 
 536     // Remove used mem nodes.
 537     for (int i = memops.size() - 1; i >= 0; i--) {
 538       MemNode* m = memops.at(i)->as_Mem();
 539       if (alignment(m) != top_align) {
 540         memops.remove(i);
 541       }
 542     }
 543 
 544   } // while (memops.size() != 0
 545   set_align_to_ref(best_align_to_mem_ref);
 546 
 547 #ifndef PRODUCT
 548   if (TraceSuperWord) {
 549     tty->print_cr("\nAfter find_adjacent_refs");
 550     print_packset();
 551   }
 552 #endif
 553 }
 554 
 555 //------------------------------find_align_to_ref---------------------------
 556 // Find a memory reference to align the loop induction variable to.
 557 // Looks first at stores then at loads, looking for a memory reference
 558 // with the largest number of references similar to it.
 559 MemNode* SuperWord::find_align_to_ref(Node_List &memops) {
 560   GrowableArray<int> cmp_ct(arena(), memops.size(), memops.size(), 0);
 561 
 562   // Count number of comparable memory ops
 563   for (uint i = 0; i < memops.size(); i++) {
 564     MemNode* s1 = memops.at(i)->as_Mem();
 565     SWPointer p1(s1, this, NULL, false);
 566     // Discard if pre loop can't align this reference
 567     if (!ref_is_alignable(p1)) {
 568       *cmp_ct.adr_at(i) = 0;
 569       continue;
 570     }
 571     for (uint j = i+1; j < memops.size(); j++) {
 572       MemNode* s2 = memops.at(j)->as_Mem();
 573       if (isomorphic(s1, s2)) {
 574         SWPointer p2(s2, this, NULL, false);
 575         if (p1.comparable(p2)) {
 576           (*cmp_ct.adr_at(i))++;
 577           (*cmp_ct.adr_at(j))++;
 578         }
 579       }
 580     }
 581   }
 582 
 583   // Find Store (or Load) with the greatest number of "comparable" references,
 584   // biggest vector size, smallest data size and smallest iv offset.
 585   int max_ct        = 0;
 586   int max_vw        = 0;
 587   int max_idx       = -1;
 588   int min_size      = max_jint;
 589   int min_iv_offset = max_jint;
 590   for (uint j = 0; j < memops.size(); j++) {
 591     MemNode* s = memops.at(j)->as_Mem();
 592     if (s->is_Store()) {
 593       int vw = vector_width_in_bytes(s);
 594       assert(vw > 1, "sanity");
 595       SWPointer p(s, this, NULL, false);
 596       if (cmp_ct.at(j) >  max_ct ||
 597           cmp_ct.at(j) == max_ct &&
 598             (vw >  max_vw ||
 599              vw == max_vw &&
 600               (data_size(s) <  min_size ||
 601                data_size(s) == min_size &&
 602                  (p.offset_in_bytes() < min_iv_offset)))) {
 603         max_ct = cmp_ct.at(j);
 604         max_vw = vw;
 605         max_idx = j;
 606         min_size = data_size(s);
 607         min_iv_offset = p.offset_in_bytes();
 608       }
 609     }
 610   }
 611   // If no stores, look at loads
 612   if (max_ct == 0) {
 613     for (uint j = 0; j < memops.size(); j++) {
 614       MemNode* s = memops.at(j)->as_Mem();
 615       if (s->is_Load()) {
 616         int vw = vector_width_in_bytes(s);
 617         assert(vw > 1, "sanity");
 618         SWPointer p(s, this, NULL, false);
 619         if (cmp_ct.at(j) >  max_ct ||
 620             cmp_ct.at(j) == max_ct &&
 621               (vw >  max_vw ||
 622                vw == max_vw &&
 623                 (data_size(s) <  min_size ||
 624                  data_size(s) == min_size &&
 625                    (p.offset_in_bytes() < min_iv_offset)))) {
 626           max_ct = cmp_ct.at(j);
 627           max_vw = vw;
 628           max_idx = j;
 629           min_size = data_size(s);
 630           min_iv_offset = p.offset_in_bytes();
 631         }
 632       }
 633     }
 634   }
 635 
 636 #ifdef ASSERT
 637   if (TraceSuperWord && Verbose) {
 638     tty->print_cr("\nVector memops after find_align_to_ref");
 639     for (uint i = 0; i < memops.size(); i++) {
 640       MemNode* s = memops.at(i)->as_Mem();
 641       s->dump();
 642     }
 643   }
 644 #endif
 645 
 646   if (max_ct > 0) {
 647 #ifdef ASSERT
 648     if (TraceSuperWord) {
 649       tty->print("\nVector align to node: ");
 650       memops.at(max_idx)->as_Mem()->dump();
 651     }
 652 #endif
 653     return memops.at(max_idx)->as_Mem();
 654   }
 655   return NULL;
 656 }
 657 
 658 //------------------------------ref_is_alignable---------------------------
 659 // Can the preloop align the reference to position zero in the vector?
 660 bool SuperWord::ref_is_alignable(SWPointer& p) {
 661   if (!p.has_iv()) {
 662     return true;   // no induction variable
 663   }
 664   CountedLoopEndNode* pre_end = get_pre_loop_end(lp()->as_CountedLoop());
 665   assert(pre_end != NULL, "we must have a correct pre-loop");
 666   assert(pre_end->stride_is_con(), "pre loop stride is constant");
 667   int preloop_stride = pre_end->stride_con();
 668 
 669   int span = preloop_stride * p.scale_in_bytes();
 670   int mem_size = p.memory_size();
 671   int offset   = p.offset_in_bytes();
 672   // Stride one accesses are alignable if offset is aligned to memory operation size.
 673   // Offset can be unaligned when UseUnalignedAccesses is used.
 674   if (ABS(span) == mem_size && (ABS(offset) % mem_size) == 0) {
 675     return true;
 676   }
 677   // If the initial offset from start of the object is computable,
 678   // check if the pre-loop can align the final offset accordingly.
 679   //
 680   // In other words: Can we find an i such that the offset
 681   // after i pre-loop iterations is aligned to vw?
 682   //   (init_offset + pre_loop) % vw == 0              (1)
 683   // where
 684   //   pre_loop = i * span
 685   // is the number of bytes added to the offset by i pre-loop iterations.
 686   //
 687   // For this to hold we need pre_loop to increase init_offset by
 688   //   pre_loop = vw - (init_offset % vw)
 689   //
 690   // This is only possible if pre_loop is divisible by span because each
 691   // pre-loop iteration increases the initial offset by 'span' bytes:
 692   //   (vw - (init_offset % vw)) % span == 0
 693   //
 694   int vw = vector_width_in_bytes(p.mem());
 695   assert(vw > 1, "sanity");
 696   Node* init_nd = pre_end->init_trip();
 697   if (init_nd->is_Con() && p.invar() == NULL) {
 698     int init = init_nd->bottom_type()->is_int()->get_con();
 699     int init_offset = init * p.scale_in_bytes() + offset;
 700     assert(init_offset >= 0, "positive offset from object start");
 701     if (vw % span == 0) {
 702       // If vm is a multiple of span, we use formula (1).
 703       if (span > 0) {
 704         return (vw - (init_offset % vw)) % span == 0;
 705       } else {
 706         assert(span < 0, "nonzero stride * scale");
 707         return (init_offset % vw) % -span == 0;
 708       }
 709     } else if (span % vw == 0) {
 710       // If span is a multiple of vw, we can simplify formula (1) to:
 711       //   (init_offset + i * span) % vw == 0
 712       //     =>
 713       //   (init_offset % vw) + ((i * span) % vw) == 0
 714       //     =>
 715       //   init_offset % vw == 0
 716       //
 717       // Because we add a multiple of vw to the initial offset, the final
 718       // offset is a multiple of vw if and only if init_offset is a multiple.
 719       //
 720       return (init_offset % vw) == 0;
 721     }
 722   }
 723   return false;
 724 }
 725 
 726 //---------------------------get_iv_adjustment---------------------------
 727 // Calculate loop's iv adjustment for this memory ops.
 728 int SuperWord::get_iv_adjustment(MemNode* mem_ref) {
 729   SWPointer align_to_ref_p(mem_ref, this, NULL, false);
 730   int offset = align_to_ref_p.offset_in_bytes();
 731   int scale  = align_to_ref_p.scale_in_bytes();
 732   int elt_size = align_to_ref_p.memory_size();
 733   int vw       = vector_width_in_bytes(mem_ref);
 734   assert(vw > 1, "sanity");
 735   int iv_adjustment;
 736   if (scale != 0) {
 737     int stride_sign = (scale * iv_stride()) > 0 ? 1 : -1;
 738     // At least one iteration is executed in pre-loop by default. As result
 739     // several iterations are needed to align memory operations in main-loop even
 740     // if offset is 0.
 741     int iv_adjustment_in_bytes = (stride_sign * vw - (offset % vw));
 742     assert(((ABS(iv_adjustment_in_bytes) % elt_size) == 0),
 743            err_msg_res("(%d) should be divisible by (%d)", iv_adjustment_in_bytes, elt_size));
 744     iv_adjustment = iv_adjustment_in_bytes/elt_size;
 745   } else {
 746     // This memory op is not dependent on iv (scale == 0)
 747     iv_adjustment = 0;
 748   }
 749 
 750 #ifndef PRODUCT
 751   if (TraceSuperWord)
 752     tty->print_cr("\noffset = %d iv_adjust = %d elt_size = %d scale = %d iv_stride = %d vect_size %d",
 753                   offset, iv_adjustment, elt_size, scale, iv_stride(), vw);
 754 #endif
 755   return iv_adjustment;
 756 }
 757 
 758 //---------------------------dependence_graph---------------------------
 759 // Construct dependency graph.
 760 // Add dependence edges to load/store nodes for memory dependence
 761 //    A.out()->DependNode.in(1) and DependNode.out()->B.prec(x)
 762 void SuperWord::dependence_graph() {
 763   // First, assign a dependence node to each memory node
 764   for (int i = 0; i < _block.length(); i++ ) {
 765     Node *n = _block.at(i);
 766     if (n->is_Mem() || n->is_Phi() && n->bottom_type() == Type::MEMORY) {
 767       _dg.make_node(n);
 768     }
 769   }
 770 
 771   // For each memory slice, create the dependences
 772   for (int i = 0; i < _mem_slice_head.length(); i++) {
 773     Node* n      = _mem_slice_head.at(i);
 774     Node* n_tail = _mem_slice_tail.at(i);
 775 
 776     // Get slice in predecessor order (last is first)
 777     mem_slice_preds(n_tail, n, _nlist);
 778 
 779 #ifndef PRODUCT
 780     if(TraceSuperWord && Verbose) {
 781       tty->print_cr("SuperWord::dependence_graph: built a new mem slice");
 782       for (int j = _nlist.length() - 1; j >= 0 ; j--) {
 783         _nlist.at(j)->dump();
 784       }
 785     }
 786 #endif
 787     // Make the slice dependent on the root
 788     DepMem* slice = _dg.dep(n);
 789     _dg.make_edge(_dg.root(), slice);
 790 
 791     // Create a sink for the slice
 792     DepMem* slice_sink = _dg.make_node(NULL);
 793     _dg.make_edge(slice_sink, _dg.tail());
 794 
 795     // Now visit each pair of memory ops, creating the edges
 796     for (int j = _nlist.length() - 1; j >= 0 ; j--) {
 797       Node* s1 = _nlist.at(j);
 798 
 799       // If no dependency yet, use slice
 800       if (_dg.dep(s1)->in_cnt() == 0) {
 801         _dg.make_edge(slice, s1);
 802       }
 803       SWPointer p1(s1->as_Mem(), this, NULL, false);
 804       bool sink_dependent = true;
 805       for (int k = j - 1; k >= 0; k--) {
 806         Node* s2 = _nlist.at(k);
 807         if (s1->is_Load() && s2->is_Load())
 808           continue;
 809         SWPointer p2(s2->as_Mem(), this, NULL, false);
 810 
 811         int cmp = p1.cmp(p2);
 812         if (SuperWordRTDepCheck &&
 813             p1.base() != p2.base() && p1.valid() && p2.valid()) {
 814           // Create a runtime check to disambiguate
 815           OrderedPair pp(p1.base(), p2.base());
 816           _disjoint_ptrs.append_if_missing(pp);
 817         } else if (!SWPointer::not_equal(cmp)) {
 818           // Possibly same address
 819           _dg.make_edge(s1, s2);
 820           sink_dependent = false;
 821         }
 822       }
 823       if (sink_dependent) {
 824         _dg.make_edge(s1, slice_sink);
 825       }
 826     }
 827 #ifndef PRODUCT
 828     if (TraceSuperWord) {
 829       tty->print_cr("\nDependence graph for slice: %d", n->_idx);
 830       for (int q = 0; q < _nlist.length(); q++) {
 831         _dg.print(_nlist.at(q));
 832       }
 833       tty->cr();
 834     }
 835 #endif
 836     _nlist.clear();
 837   }
 838 
 839 #ifndef PRODUCT
 840   if (TraceSuperWord) {
 841     tty->print_cr("\ndisjoint_ptrs: %s", _disjoint_ptrs.length() > 0 ? "" : "NONE");
 842     for (int r = 0; r < _disjoint_ptrs.length(); r++) {
 843       _disjoint_ptrs.at(r).print();
 844       tty->cr();
 845     }
 846     tty->cr();
 847   }
 848 #endif
 849 }
 850 
 851 //---------------------------mem_slice_preds---------------------------
 852 // Return a memory slice (node list) in predecessor order starting at "start"
 853 void SuperWord::mem_slice_preds(Node* start, Node* stop, GrowableArray<Node*> &preds) {
 854   assert(preds.length() == 0, "start empty");
 855   Node* n = start;
 856   Node* prev = NULL;
 857   while (true) {
 858     assert(in_bb(n), "must be in block");
 859     for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
 860       Node* out = n->fast_out(i);
 861       if (out->is_Load()) {
 862         if (in_bb(out)) {
 863           preds.push(out);
 864         }
 865       } else {
 866         // FIXME
 867         if (out->is_MergeMem() && !in_bb(out)) {
 868           // Either unrolling is causing a memory edge not to disappear,
 869           // or need to run igvn.optimize() again before SLP
 870         } else if (out->is_Phi() && out->bottom_type() == Type::MEMORY && !in_bb(out)) {
 871           // Ditto.  Not sure what else to check further.
 872         } else if (out->Opcode() == Op_StoreCM && out->in(MemNode::OopStore) == n) {
 873           // StoreCM has an input edge used as a precedence edge.
 874           // Maybe an issue when oop stores are vectorized.
 875         } else {
 876           assert(out == prev || prev == NULL, "no branches off of store slice");
 877         }
 878       }
 879     }
 880     if (n == stop) break;
 881     preds.push(n);
 882     prev = n;
 883     assert(n->is_Mem(), err_msg_res("unexpected node %s", n->Name()));
 884     n = n->in(MemNode::Memory);
 885   }
 886 }
 887 
 888 //------------------------------stmts_can_pack---------------------------
 889 // Can s1 and s2 be in a pack with s1 immediately preceding s2 and
 890 // s1 aligned at "align"
 891 bool SuperWord::stmts_can_pack(Node* s1, Node* s2, int align) {
 892 
 893   // Do not use superword for non-primitives
 894   BasicType bt1 = velt_basic_type(s1);
 895   BasicType bt2 = velt_basic_type(s2);
 896   if(!is_java_primitive(bt1) || !is_java_primitive(bt2))
 897     return false;
 898   if (Matcher::max_vector_size(bt1) < 2) {
 899     return false; // No vectors for this type
 900   }
 901 
 902   if (isomorphic(s1, s2)) {
 903     if (independent(s1, s2) || reduction(s1, s2)) {
 904       if (!exists_at(s1, 0) && !exists_at(s2, 1)) {
 905         if (!s1->is_Mem() || are_adjacent_refs(s1, s2)) {
 906           int s1_align = alignment(s1);
 907           int s2_align = alignment(s2);
 908           if (s1_align == top_align || s1_align == align) {
 909             if (s2_align == top_align || s2_align == align + data_size(s1)) {
 910               return true;
 911             }
 912           }
 913         }
 914       }
 915     }
 916   }
 917   return false;
 918 }
 919 
 920 //------------------------------exists_at---------------------------
 921 // Does s exist in a pack at position pos?
 922 bool SuperWord::exists_at(Node* s, uint pos) {
 923   for (int i = 0; i < _packset.length(); i++) {
 924     Node_List* p = _packset.at(i);
 925     if (p->at(pos) == s) {
 926       return true;
 927     }
 928   }
 929   return false;
 930 }
 931 
 932 //------------------------------are_adjacent_refs---------------------------
 933 // Is s1 immediately before s2 in memory?
 934 bool SuperWord::are_adjacent_refs(Node* s1, Node* s2) {
 935   if (!s1->is_Mem() || !s2->is_Mem()) return false;
 936   if (!in_bb(s1)    || !in_bb(s2))    return false;
 937 
 938   // Do not use superword for non-primitives
 939   if (!is_java_primitive(s1->as_Mem()->memory_type()) ||
 940       !is_java_primitive(s2->as_Mem()->memory_type())) {
 941     return false;
 942   }
 943 
 944   // FIXME - co_locate_pack fails on Stores in different mem-slices, so
 945   // only pack memops that are in the same alias set until that's fixed.
 946   if (_phase->C->get_alias_index(s1->as_Mem()->adr_type()) !=
 947       _phase->C->get_alias_index(s2->as_Mem()->adr_type()))
 948     return false;
 949   SWPointer p1(s1->as_Mem(), this, NULL, false);
 950   SWPointer p2(s2->as_Mem(), this, NULL, false);
 951   if (p1.base() != p2.base() || !p1.comparable(p2)) return false;
 952   int diff = p2.offset_in_bytes() - p1.offset_in_bytes();
 953   return diff == data_size(s1);
 954 }
 955 
 956 //------------------------------isomorphic---------------------------
 957 // Are s1 and s2 similar?
 958 bool SuperWord::isomorphic(Node* s1, Node* s2) {
 959   if (s1->Opcode() != s2->Opcode()) return false;
 960   if (s1->req() != s2->req()) return false;
 961   if (s1->in(0) != s2->in(0)) return false;
 962   if (!same_velt_type(s1, s2)) return false;
 963   return true;
 964 }
 965 
 966 //------------------------------independent---------------------------
 967 // Is there no data path from s1 to s2 or s2 to s1?
 968 bool SuperWord::independent(Node* s1, Node* s2) {
 969   //  assert(s1->Opcode() == s2->Opcode(), "check isomorphic first");
 970   int d1 = depth(s1);
 971   int d2 = depth(s2);
 972   if (d1 == d2) return s1 != s2;
 973   Node* deep    = d1 > d2 ? s1 : s2;
 974   Node* shallow = d1 > d2 ? s2 : s1;
 975 
 976   visited_clear();
 977 
 978   return independent_path(shallow, deep);
 979 }
 980 
 981 //------------------------------reduction---------------------------
 982 // Is there a data path between s1 and s2 and the nodes reductions?
 983 bool SuperWord::reduction(Node* s1, Node* s2) {
 984   bool retValue = false;
 985   int d1 = depth(s1);
 986   int d2 = depth(s2);
 987   if (d1 + 1 == d2) {
 988     if (s1->is_reduction() && s2->is_reduction()) {
 989       // This is an ordered set, so s1 should define s2
 990       for (DUIterator_Fast imax, i = s1->fast_outs(imax); i < imax; i++) {
 991         Node* t1 = s1->fast_out(i);
 992         if (t1 == s2) {
 993           // both nodes are reductions and connected
 994           retValue = true;
 995         }
 996       }
 997     }
 998   }
 999 
1000   return retValue;
1001 }
1002 
1003 //------------------------------independent_path------------------------------
1004 // Helper for independent
1005 bool SuperWord::independent_path(Node* shallow, Node* deep, uint dp) {
1006   if (dp >= 1000) return false; // stop deep recursion
1007   visited_set(deep);
1008   int shal_depth = depth(shallow);
1009   assert(shal_depth <= depth(deep), "must be");
1010   for (DepPreds preds(deep, _dg); !preds.done(); preds.next()) {
1011     Node* pred = preds.current();
1012     if (in_bb(pred) && !visited_test(pred)) {
1013       if (shallow == pred) {
1014         return false;
1015       }
1016       if (shal_depth < depth(pred) && !independent_path(shallow, pred, dp+1)) {
1017         return false;
1018       }
1019     }
1020   }
1021   return true;
1022 }
1023 
1024 //------------------------------set_alignment---------------------------
1025 void SuperWord::set_alignment(Node* s1, Node* s2, int align) {
1026   set_alignment(s1, align);
1027   if (align == top_align || align == bottom_align) {
1028     set_alignment(s2, align);
1029   } else {
1030     set_alignment(s2, align + data_size(s1));
1031   }
1032 }
1033 
1034 //------------------------------data_size---------------------------
1035 int SuperWord::data_size(Node* s) {
1036   int bsize = type2aelembytes(velt_basic_type(s));
1037   assert(bsize != 0, "valid size");
1038   return bsize;
1039 }
1040 
1041 //------------------------------extend_packlist---------------------------
1042 // Extend packset by following use->def and def->use links from pack members.
1043 void SuperWord::extend_packlist() {
1044   bool changed;
1045   do {
1046     packset_sort(_packset.length());
1047     changed = false;
1048     for (int i = 0; i < _packset.length(); i++) {
1049       Node_List* p = _packset.at(i);
1050       changed |= follow_use_defs(p);
1051       changed |= follow_def_uses(p);
1052     }
1053   } while (changed);
1054 
1055   if (_race_possible) {
1056     for (int i = 0; i < _packset.length(); i++) {
1057       Node_List* p = _packset.at(i);
1058       order_def_uses(p);
1059     }
1060   }
1061 
1062 #ifndef PRODUCT
1063   if (TraceSuperWord) {
1064     tty->print_cr("\nAfter extend_packlist");
1065     print_packset();
1066   }
1067 #endif
1068 }
1069 
1070 //------------------------------follow_use_defs---------------------------
1071 // Extend the packset by visiting operand definitions of nodes in pack p
1072 bool SuperWord::follow_use_defs(Node_List* p) {
1073   assert(p->size() == 2, "just checking");
1074   Node* s1 = p->at(0);
1075   Node* s2 = p->at(1);
1076   assert(s1->req() == s2->req(), "just checking");
1077   assert(alignment(s1) + data_size(s1) == alignment(s2), "just checking");
1078 
1079   if (s1->is_Load()) return false;
1080 
1081   int align = alignment(s1);
1082   bool changed = false;
1083   int start = s1->is_Store() ? MemNode::ValueIn   : 1;
1084   int end   = s1->is_Store() ? MemNode::ValueIn+1 : s1->req();
1085   for (int j = start; j < end; j++) {
1086     Node* t1 = s1->in(j);
1087     Node* t2 = s2->in(j);
1088     if (!in_bb(t1) || !in_bb(t2))
1089       continue;
1090     if (stmts_can_pack(t1, t2, align)) {
1091       if (est_savings(t1, t2) >= 0) {
1092         Node_List* pair = new Node_List();
1093         pair->push(t1);
1094         pair->push(t2);
1095         _packset.append(pair);
1096         set_alignment(t1, t2, align);
1097         changed = true;
1098       }
1099     }
1100   }
1101   return changed;
1102 }
1103 
1104 //------------------------------follow_def_uses---------------------------
1105 // Extend the packset by visiting uses of nodes in pack p
1106 bool SuperWord::follow_def_uses(Node_List* p) {
1107   bool changed = false;
1108   Node* s1 = p->at(0);
1109   Node* s2 = p->at(1);
1110   assert(p->size() == 2, "just checking");
1111   assert(s1->req() == s2->req(), "just checking");
1112   assert(alignment(s1) + data_size(s1) == alignment(s2), "just checking");
1113 
1114   if (s1->is_Store()) return false;
1115 
1116   int align = alignment(s1);
1117   int savings = -1;
1118   int num_s1_uses = 0;
1119   Node* u1 = NULL;
1120   Node* u2 = NULL;
1121   for (DUIterator_Fast imax, i = s1->fast_outs(imax); i < imax; i++) {
1122     Node* t1 = s1->fast_out(i);
1123     num_s1_uses++;
1124     if (!in_bb(t1)) continue;
1125     for (DUIterator_Fast jmax, j = s2->fast_outs(jmax); j < jmax; j++) {
1126       Node* t2 = s2->fast_out(j);
1127       if (!in_bb(t2)) continue;
1128       if (!opnd_positions_match(s1, t1, s2, t2))
1129         continue;
1130       if (stmts_can_pack(t1, t2, align)) {
1131         int my_savings = est_savings(t1, t2);
1132         if (my_savings > savings) {
1133           savings = my_savings;
1134           u1 = t1;
1135           u2 = t2;
1136         }
1137       }
1138     }
1139   }
1140   if (num_s1_uses > 1) {
1141     _race_possible = true;
1142   }
1143   if (savings >= 0) {
1144     Node_List* pair = new Node_List();
1145     pair->push(u1);
1146     pair->push(u2);
1147     _packset.append(pair);
1148     set_alignment(u1, u2, align);
1149     changed = true;
1150   }
1151   return changed;
1152 }
1153 
1154 //------------------------------order_def_uses---------------------------
1155 // For extended packsets, ordinally arrange uses packset by major component
1156 void SuperWord::order_def_uses(Node_List* p) {
1157   Node* s1 = p->at(0);
1158 
1159   if (s1->is_Store()) return;
1160 
1161   // reductions are always managed beforehand
1162   if (s1->is_reduction()) return;
1163 
1164   for (DUIterator_Fast imax, i = s1->fast_outs(imax); i < imax; i++) {
1165     Node* t1 = s1->fast_out(i);
1166 
1167     // Only allow operand swap on commuting operations
1168     if (!t1->is_Add() && !t1->is_Mul()) {
1169       break;
1170     }
1171 
1172     // Now find t1's packset
1173     Node_List* p2 = NULL;
1174     for (int j = 0; j < _packset.length(); j++) {
1175       p2 = _packset.at(j);
1176       Node* first = p2->at(0);
1177       if (t1 == first) {
1178         break;
1179       }
1180       p2 = NULL;
1181     }
1182     // Arrange all sub components by the major component
1183     if (p2 != NULL) {
1184       for (uint j = 1; j < p->size(); j++) {
1185         Node* d1 = p->at(j);
1186         Node* u1 = p2->at(j);
1187         opnd_positions_match(s1, t1, d1, u1);
1188       }
1189     }
1190   }
1191 }
1192 
1193 //---------------------------opnd_positions_match-------------------------
1194 // Is the use of d1 in u1 at the same operand position as d2 in u2?
1195 bool SuperWord::opnd_positions_match(Node* d1, Node* u1, Node* d2, Node* u2) {
1196   // check reductions to see if they are marshalled to represent the reduction
1197   // operator in a specified opnd
1198   if (u1->is_reduction() && u2->is_reduction()) {
1199     // ensure reductions have phis and reduction definitions feeding the 1st operand
1200     Node* first = u1->in(2);
1201     if (first->is_Phi() || first->is_reduction()) {
1202       u1->swap_edges(1, 2);
1203     }
1204     // ensure reductions have phis and reduction definitions feeding the 1st operand
1205     first = u2->in(2);
1206     if (first->is_Phi() || first->is_reduction()) {
1207       u2->swap_edges(1, 2);
1208     }
1209     return true;
1210   }
1211 
1212   uint ct = u1->req();
1213   if (ct != u2->req()) return false;
1214   uint i1 = 0;
1215   uint i2 = 0;
1216   do {
1217     for (i1++; i1 < ct; i1++) if (u1->in(i1) == d1) break;
1218     for (i2++; i2 < ct; i2++) if (u2->in(i2) == d2) break;
1219     if (i1 != i2) {
1220       if ((i1 == (3-i2)) && (u2->is_Add() || u2->is_Mul())) {
1221         // Further analysis relies on operands position matching.
1222         u2->swap_edges(i1, i2);
1223       } else {
1224         return false;
1225       }
1226     }
1227   } while (i1 < ct);
1228   return true;
1229 }
1230 
1231 //------------------------------est_savings---------------------------
1232 // Estimate the savings from executing s1 and s2 as a pack
1233 int SuperWord::est_savings(Node* s1, Node* s2) {
1234   int save_in = 2 - 1; // 2 operations per instruction in packed form
1235 
1236   // inputs
1237   for (uint i = 1; i < s1->req(); i++) {
1238     Node* x1 = s1->in(i);
1239     Node* x2 = s2->in(i);
1240     if (x1 != x2) {
1241       if (are_adjacent_refs(x1, x2)) {
1242         save_in += adjacent_profit(x1, x2);
1243       } else if (!in_packset(x1, x2)) {
1244         save_in -= pack_cost(2);
1245       } else {
1246         save_in += unpack_cost(2);
1247       }
1248     }
1249   }
1250 
1251   // uses of result
1252   uint ct = 0;
1253   int save_use = 0;
1254   for (DUIterator_Fast imax, i = s1->fast_outs(imax); i < imax; i++) {
1255     Node* s1_use = s1->fast_out(i);
1256     for (int j = 0; j < _packset.length(); j++) {
1257       Node_List* p = _packset.at(j);
1258       if (p->at(0) == s1_use) {
1259         for (DUIterator_Fast kmax, k = s2->fast_outs(kmax); k < kmax; k++) {
1260           Node* s2_use = s2->fast_out(k);
1261           if (p->at(p->size()-1) == s2_use) {
1262             ct++;
1263             if (are_adjacent_refs(s1_use, s2_use)) {
1264               save_use += adjacent_profit(s1_use, s2_use);
1265             }
1266           }
1267         }
1268       }
1269     }
1270   }
1271 
1272   if (ct < s1->outcnt()) save_use += unpack_cost(1);
1273   if (ct < s2->outcnt()) save_use += unpack_cost(1);
1274 
1275   return MAX2(save_in, save_use);
1276 }
1277 
1278 //------------------------------costs---------------------------
1279 int SuperWord::adjacent_profit(Node* s1, Node* s2) { return 2; }
1280 int SuperWord::pack_cost(int ct)   { return ct; }
1281 int SuperWord::unpack_cost(int ct) { return ct; }
1282 
1283 //------------------------------combine_packs---------------------------
1284 // Combine packs A and B with A.last == B.first into A.first..,A.last,B.second,..B.last
1285 void SuperWord::combine_packs() {
1286   bool changed = true;
1287   // Combine packs regardless max vector size.
1288   while (changed) {
1289     changed = false;
1290     for (int i = 0; i < _packset.length(); i++) {
1291       Node_List* p1 = _packset.at(i);
1292       if (p1 == NULL) continue;
1293       // Because of sorting we can start at i + 1
1294       for (int j = i + 1; j < _packset.length(); j++) {
1295         Node_List* p2 = _packset.at(j);
1296         if (p2 == NULL) continue;
1297         if (i == j) continue;
1298         if (p1->at(p1->size()-1) == p2->at(0)) {
1299           for (uint k = 1; k < p2->size(); k++) {
1300             p1->push(p2->at(k));
1301           }
1302           _packset.at_put(j, NULL);
1303           changed = true;
1304         }
1305       }
1306     }
1307   }
1308 
1309   // Split packs which have size greater then max vector size.
1310   for (int i = 0; i < _packset.length(); i++) {
1311     Node_List* p1 = _packset.at(i);
1312     if (p1 != NULL) {
1313       BasicType bt = velt_basic_type(p1->at(0));
1314       uint max_vlen = Matcher::max_vector_size(bt); // Max elements in vector
1315       assert(is_power_of_2(max_vlen), "sanity");
1316       uint psize = p1->size();
1317       if (!is_power_of_2(psize)) {
1318         // Skip pack which can't be vector.
1319         // case1: for(...) { a[i] = i; }    elements values are different (i+x)
1320         // case2: for(...) { a[i] = b[i+1]; }  can't align both, load and store
1321         _packset.at_put(i, NULL);
1322         continue;
1323       }
1324       if (psize > max_vlen) {
1325         Node_List* pack = new Node_List();
1326         for (uint j = 0; j < psize; j++) {
1327           pack->push(p1->at(j));
1328           if (pack->size() >= max_vlen) {
1329             assert(is_power_of_2(pack->size()), "sanity");
1330             _packset.append(pack);
1331             pack = new Node_List();
1332           }
1333         }
1334         _packset.at_put(i, NULL);
1335       }
1336     }
1337   }
1338 
1339   // Compress list.
1340   for (int i = _packset.length() - 1; i >= 0; i--) {
1341     Node_List* p1 = _packset.at(i);
1342     if (p1 == NULL) {
1343       _packset.remove_at(i);
1344     }
1345   }
1346 
1347 #ifndef PRODUCT
1348   if (TraceSuperWord) {
1349     tty->print_cr("\nAfter combine_packs");
1350     print_packset();
1351   }
1352 #endif
1353 }
1354 
1355 //-----------------------------construct_my_pack_map--------------------------
1356 // Construct the map from nodes to packs.  Only valid after the
1357 // point where a node is only in one pack (after combine_packs).
1358 void SuperWord::construct_my_pack_map() {
1359   Node_List* rslt = NULL;
1360   for (int i = 0; i < _packset.length(); i++) {
1361     Node_List* p = _packset.at(i);
1362     for (uint j = 0; j < p->size(); j++) {
1363       Node* s = p->at(j);
1364       assert(my_pack(s) == NULL, "only in one pack");
1365       set_my_pack(s, p);
1366     }
1367   }
1368 }
1369 
1370 //------------------------------filter_packs---------------------------
1371 // Remove packs that are not implemented or not profitable.
1372 void SuperWord::filter_packs() {
1373   // Remove packs that are not implemented
1374   for (int i = _packset.length() - 1; i >= 0; i--) {
1375     Node_List* pk = _packset.at(i);
1376     bool impl = implemented(pk);
1377     if (!impl) {
1378 #ifndef PRODUCT
1379       if (TraceSuperWord && Verbose) {
1380         tty->print_cr("Unimplemented");
1381         pk->at(0)->dump();
1382       }
1383 #endif
1384       remove_pack_at(i);
1385     }
1386     Node *n = pk->at(0);
1387     if (n->is_reduction()) {
1388       _num_reductions++;
1389     } else {
1390       _num_work_vecs++;
1391     }
1392   }
1393 
1394   // Remove packs that are not profitable
1395   bool changed;
1396   do {
1397     changed = false;
1398     for (int i = _packset.length() - 1; i >= 0; i--) {
1399       Node_List* pk = _packset.at(i);
1400       bool prof = profitable(pk);
1401       if (!prof) {
1402 #ifndef PRODUCT
1403         if (TraceSuperWord && Verbose) {
1404           tty->print_cr("Unprofitable");
1405           pk->at(0)->dump();
1406         }
1407 #endif
1408         remove_pack_at(i);
1409         changed = true;
1410       }
1411     }
1412   } while (changed);
1413 
1414 #ifndef PRODUCT
1415   if (TraceSuperWord) {
1416     tty->print_cr("\nAfter filter_packs");
1417     print_packset();
1418     tty->cr();
1419   }
1420 #endif
1421 }
1422 
1423 //------------------------------implemented---------------------------
1424 // Can code be generated for pack p?
1425 bool SuperWord::implemented(Node_List* p) {
1426   bool retValue = false;
1427   Node* p0 = p->at(0);
1428   if (p0 != NULL) {
1429     int opc = p0->Opcode();
1430     uint size = p->size();
1431     if (p0->is_reduction()) {
1432       const Type *arith_type = p0->bottom_type();
1433       // Length 2 reductions of INT/LONG do not offer performance benefits
1434       if (((arith_type->basic_type() == T_INT) || (arith_type->basic_type() == T_LONG)) && (size == 2)) {
1435         retValue = false;
1436       } else {
1437         retValue = ReductionNode::implemented(opc, size, arith_type->basic_type());
1438       }
1439     } else {
1440       retValue = VectorNode::implemented(opc, size, velt_basic_type(p0));
1441     }
1442   }
1443   return retValue;
1444 }
1445 
1446 //------------------------------same_inputs--------------------------
1447 // For pack p, are all idx operands the same?
1448 static bool same_inputs(Node_List* p, int idx) {
1449   Node* p0 = p->at(0);
1450   uint vlen = p->size();
1451   Node* p0_def = p0->in(idx);
1452   for (uint i = 1; i < vlen; i++) {
1453     Node* pi = p->at(i);
1454     Node* pi_def = pi->in(idx);
1455     if (p0_def != pi_def)
1456       return false;
1457   }
1458   return true;
1459 }
1460 
1461 //------------------------------profitable---------------------------
1462 // For pack p, are all operands and all uses (with in the block) vector?
1463 bool SuperWord::profitable(Node_List* p) {
1464   Node* p0 = p->at(0);
1465   uint start, end;
1466   VectorNode::vector_operands(p0, &start, &end);
1467 
1468   // Return false if some inputs are not vectors or vectors with different
1469   // size or alignment.
1470   // Also, for now, return false if not scalar promotion case when inputs are
1471   // the same. Later, implement PackNode and allow differing, non-vector inputs
1472   // (maybe just the ones from outside the block.)
1473   for (uint i = start; i < end; i++) {
1474     if (!is_vector_use(p0, i))
1475       return false;
1476   }
1477   // Check if reductions are connected
1478   if (p0->is_reduction()) {
1479     Node* second_in = p0->in(2);
1480     Node_List* second_pk = my_pack(second_in);
1481     if ((second_pk == NULL) || (_num_work_vecs == _num_reductions)) {
1482       // Remove reduction flag if no parent pack or if not enough work
1483       // to cover reduction expansion overhead
1484       p0->remove_flag(Node::Flag_is_reduction);
1485       return false;
1486     } else if (second_pk->size() != p->size()) {
1487       return false;
1488     }
1489   }
1490   if (VectorNode::is_shift(p0)) {
1491     // For now, return false if shift count is vector or not scalar promotion
1492     // case (different shift counts) because it is not supported yet.
1493     Node* cnt = p0->in(2);
1494     Node_List* cnt_pk = my_pack(cnt);
1495     if (cnt_pk != NULL)
1496       return false;
1497     if (!same_inputs(p, 2))
1498       return false;
1499   }
1500   if (!p0->is_Store()) {
1501     // For now, return false if not all uses are vector.
1502     // Later, implement ExtractNode and allow non-vector uses (maybe
1503     // just the ones outside the block.)
1504     for (uint i = 0; i < p->size(); i++) {
1505       Node* def = p->at(i);
1506       for (DUIterator_Fast jmax, j = def->fast_outs(jmax); j < jmax; j++) {
1507         Node* use = def->fast_out(j);
1508         for (uint k = 0; k < use->req(); k++) {
1509           Node* n = use->in(k);
1510           if (def == n) {
1511             // reductions can be loop carried dependences
1512             if (def->is_reduction() && use->is_Phi())
1513               continue;
1514             if (!is_vector_use(use, k)) {
1515               return false;
1516             }
1517           }
1518         }
1519       }
1520     }
1521   }
1522   return true;
1523 }
1524 
1525 //------------------------------schedule---------------------------
1526 // Adjust the memory graph for the packed operations
1527 void SuperWord::schedule() {
1528 
1529   // Co-locate in the memory graph the members of each memory pack
1530   for (int i = 0; i < _packset.length(); i++) {
1531     co_locate_pack(_packset.at(i));
1532   }
1533 }
1534 
1535 //-------------------------------remove_and_insert-------------------
1536 // Remove "current" from its current position in the memory graph and insert
1537 // it after the appropriate insertion point (lip or uip).
1538 void SuperWord::remove_and_insert(MemNode *current, MemNode *prev, MemNode *lip,
1539                                   Node *uip, Unique_Node_List &sched_before) {
1540   Node* my_mem = current->in(MemNode::Memory);
1541   bool sched_up = sched_before.member(current);
1542 
1543   // remove current_store from its current position in the memmory graph
1544   for (DUIterator i = current->outs(); current->has_out(i); i++) {
1545     Node* use = current->out(i);
1546     if (use->is_Mem()) {
1547       assert(use->in(MemNode::Memory) == current, "must be");
1548       if (use == prev) { // connect prev to my_mem
1549           _igvn.replace_input_of(use, MemNode::Memory, my_mem);
1550           --i; //deleted this edge; rescan position
1551       } else if (sched_before.member(use)) {
1552         if (!sched_up) { // Will be moved together with current
1553           _igvn.replace_input_of(use, MemNode::Memory, uip);
1554           --i; //deleted this edge; rescan position
1555         }
1556       } else {
1557         if (sched_up) { // Will be moved together with current
1558           _igvn.replace_input_of(use, MemNode::Memory, lip);
1559           --i; //deleted this edge; rescan position
1560         }
1561       }
1562     }
1563   }
1564 
1565   Node *insert_pt =  sched_up ?  uip : lip;
1566 
1567   // all uses of insert_pt's memory state should use current's instead
1568   for (DUIterator i = insert_pt->outs(); insert_pt->has_out(i); i++) {
1569     Node* use = insert_pt->out(i);
1570     if (use->is_Mem()) {
1571       assert(use->in(MemNode::Memory) == insert_pt, "must be");
1572       _igvn.replace_input_of(use, MemNode::Memory, current);
1573       --i; //deleted this edge; rescan position
1574     } else if (!sched_up && use->is_Phi() && use->bottom_type() == Type::MEMORY) {
1575       uint pos; //lip (lower insert point) must be the last one in the memory slice
1576       for (pos=1; pos < use->req(); pos++) {
1577         if (use->in(pos) == insert_pt) break;
1578       }
1579       _igvn.replace_input_of(use, pos, current);
1580       --i;
1581     }
1582   }
1583 
1584   //connect current to insert_pt
1585   _igvn.replace_input_of(current, MemNode::Memory, insert_pt);
1586 }
1587 
1588 //------------------------------co_locate_pack----------------------------------
1589 // To schedule a store pack, we need to move any sandwiched memory ops either before
1590 // or after the pack, based upon dependence information:
1591 // (1) If any store in the pack depends on the sandwiched memory op, the
1592 //     sandwiched memory op must be scheduled BEFORE the pack;
1593 // (2) If a sandwiched memory op depends on any store in the pack, the
1594 //     sandwiched memory op must be scheduled AFTER the pack;
1595 // (3) If a sandwiched memory op (say, memA) depends on another sandwiched
1596 //     memory op (say memB), memB must be scheduled before memA. So, if memA is
1597 //     scheduled before the pack, memB must also be scheduled before the pack;
1598 // (4) If there is no dependence restriction for a sandwiched memory op, we simply
1599 //     schedule this store AFTER the pack
1600 // (5) We know there is no dependence cycle, so there in no other case;
1601 // (6) Finally, all memory ops in another single pack should be moved in the same direction.
1602 //
1603 // To schedule a load pack, we use the memory state of either the first or the last load in
1604 // the pack, based on the dependence constraint.
1605 void SuperWord::co_locate_pack(Node_List* pk) {
1606   if (pk->at(0)->is_Store()) {
1607     MemNode* first     = executed_first(pk)->as_Mem();
1608     MemNode* last      = executed_last(pk)->as_Mem();
1609     Unique_Node_List schedule_before_pack;
1610     Unique_Node_List memops;
1611 
1612     MemNode* current   = last->in(MemNode::Memory)->as_Mem();
1613     MemNode* previous  = last;
1614     while (true) {
1615       assert(in_bb(current), "stay in block");
1616       memops.push(previous);
1617       for (DUIterator i = current->outs(); current->has_out(i); i++) {
1618         Node* use = current->out(i);
1619         if (use->is_Mem() && use != previous)
1620           memops.push(use);
1621       }
1622       if (current == first) break;
1623       previous = current;
1624       current  = current->in(MemNode::Memory)->as_Mem();
1625     }
1626 
1627     // determine which memory operations should be scheduled before the pack
1628     for (uint i = 1; i < memops.size(); i++) {
1629       Node *s1 = memops.at(i);
1630       if (!in_pack(s1, pk) && !schedule_before_pack.member(s1)) {
1631         for (uint j = 0; j< i; j++) {
1632           Node *s2 = memops.at(j);
1633           if (!independent(s1, s2)) {
1634             if (in_pack(s2, pk) || schedule_before_pack.member(s2)) {
1635               schedule_before_pack.push(s1); // s1 must be scheduled before
1636               Node_List* mem_pk = my_pack(s1);
1637               if (mem_pk != NULL) {
1638                 for (uint ii = 0; ii < mem_pk->size(); ii++) {
1639                   Node* s = mem_pk->at(ii);  // follow partner
1640                   if (memops.member(s) && !schedule_before_pack.member(s))
1641                     schedule_before_pack.push(s);
1642                 }
1643               }
1644               break;
1645             }
1646           }
1647         }
1648       }
1649     }
1650 
1651     Node*    upper_insert_pt = first->in(MemNode::Memory);
1652     // Following code moves loads connected to upper_insert_pt below aliased stores.
1653     // Collect such loads here and reconnect them back to upper_insert_pt later.
1654     memops.clear();
1655     for (DUIterator i = upper_insert_pt->outs(); upper_insert_pt->has_out(i); i++) {
1656       Node* use = upper_insert_pt->out(i);
1657       if (use->is_Mem() && !use->is_Store()) {
1658         memops.push(use);
1659       }
1660     }
1661 
1662     MemNode* lower_insert_pt = last;
1663     previous                 = last; //previous store in pk
1664     current                  = last->in(MemNode::Memory)->as_Mem();
1665 
1666     // start scheduling from "last" to "first"
1667     while (true) {
1668       assert(in_bb(current), "stay in block");
1669       assert(in_pack(previous, pk), "previous stays in pack");
1670       Node* my_mem = current->in(MemNode::Memory);
1671 
1672       if (in_pack(current, pk)) {
1673         // Forward users of my memory state (except "previous) to my input memory state
1674         for (DUIterator i = current->outs(); current->has_out(i); i++) {
1675           Node* use = current->out(i);
1676           if (use->is_Mem() && use != previous) {
1677             assert(use->in(MemNode::Memory) == current, "must be");
1678             if (schedule_before_pack.member(use)) {
1679               _igvn.replace_input_of(use, MemNode::Memory, upper_insert_pt);
1680             } else {
1681               _igvn.replace_input_of(use, MemNode::Memory, lower_insert_pt);
1682             }
1683             --i; // deleted this edge; rescan position
1684           }
1685         }
1686         previous = current;
1687       } else { // !in_pack(current, pk) ==> a sandwiched store
1688         remove_and_insert(current, previous, lower_insert_pt, upper_insert_pt, schedule_before_pack);
1689       }
1690 
1691       if (current == first) break;
1692       current = my_mem->as_Mem();
1693     } // end while
1694 
1695     // Reconnect loads back to upper_insert_pt.
1696     for (uint i = 0; i < memops.size(); i++) {
1697       Node *ld = memops.at(i);
1698       if (ld->in(MemNode::Memory) != upper_insert_pt) {
1699         _igvn.replace_input_of(ld, MemNode::Memory, upper_insert_pt);
1700       }
1701     }
1702   } else if (pk->at(0)->is_Load()) { //load
1703     // all loads in the pack should have the same memory state. By default,
1704     // we use the memory state of the last load. However, if any load could
1705     // not be moved down due to the dependence constraint, we use the memory
1706     // state of the first load.
1707     Node* last_mem  = executed_last(pk)->in(MemNode::Memory);
1708     Node* first_mem = executed_first(pk)->in(MemNode::Memory);
1709     bool schedule_last = true;
1710     for (uint i = 0; i < pk->size(); i++) {
1711       Node* ld = pk->at(i);
1712       for (Node* current = last_mem; current != ld->in(MemNode::Memory);
1713            current=current->in(MemNode::Memory)) {
1714         assert(current != first_mem, "corrupted memory graph");
1715         if(current->is_Mem() && !independent(current, ld)){
1716           schedule_last = false; // a later store depends on this load
1717           break;
1718         }
1719       }
1720     }
1721 
1722     Node* mem_input = schedule_last ? last_mem : first_mem;
1723     _igvn.hash_delete(mem_input);
1724     // Give each load the same memory state
1725     for (uint i = 0; i < pk->size(); i++) {
1726       LoadNode* ld = pk->at(i)->as_Load();
1727       _igvn.replace_input_of(ld, MemNode::Memory, mem_input);
1728     }
1729   }
1730 }
1731 
1732 //------------------------------output---------------------------
1733 // Convert packs into vector node operations
1734 void SuperWord::output() {
1735   if (_packset.length() == 0) return;
1736 
1737 #ifndef PRODUCT
1738   if (TraceLoopOpts) {
1739     tty->print("SuperWord    ");
1740     lpt()->dump_head();
1741   }
1742 #endif
1743 
1744   // MUST ENSURE main loop's initial value is properly aligned:
1745   //  (iv_initial_value + min_iv_offset) % vector_width_in_bytes() == 0
1746 
1747   align_initial_loop_index(align_to_ref());
1748 
1749   // Insert extract (unpack) operations for scalar uses
1750   for (int i = 0; i < _packset.length(); i++) {
1751     insert_extracts(_packset.at(i));
1752   }
1753 
1754   Compile* C = _phase->C;
1755   uint max_vlen_in_bytes = 0;
1756   for (int i = 0; i < _block.length(); i++) {
1757     Node* n = _block.at(i);
1758     Node_List* p = my_pack(n);
1759     if (p && n == executed_last(p)) {
1760       uint vlen = p->size();
1761       uint vlen_in_bytes = 0;
1762       Node* vn = NULL;
1763       Node* low_adr = p->at(0);
1764       Node* first   = executed_first(p);
1765       int   opc = n->Opcode();
1766       if (n->is_Load()) {
1767         Node* ctl = n->in(MemNode::Control);
1768         Node* mem = first->in(MemNode::Memory);
1769         SWPointer p1(n->as_Mem(), this, NULL, false);
1770         // Identify the memory dependency for the new loadVector node by
1771         // walking up through memory chain.
1772         // This is done to give flexibility to the new loadVector node so that
1773         // it can move above independent storeVector nodes.
1774         while (mem->is_StoreVector()) {
1775           SWPointer p2(mem->as_Mem(), this, NULL, false);
1776           int cmp = p1.cmp(p2);
1777           if (SWPointer::not_equal(cmp) || !SWPointer::comparable(cmp)) {
1778             mem = mem->in(MemNode::Memory);
1779           } else {
1780             break; // dependent memory
1781           }
1782         }
1783         Node* adr = low_adr->in(MemNode::Address);
1784         const TypePtr* atyp = n->adr_type();
1785         vn = LoadVectorNode::make(opc, ctl, mem, adr, atyp, vlen, velt_basic_type(n), control_dependency(p));
1786         vlen_in_bytes = vn->as_LoadVector()->memory_size();
1787       } else if (n->is_Store()) {
1788         // Promote value to be stored to vector
1789         Node* val = vector_opd(p, MemNode::ValueIn);
1790         Node* ctl = n->in(MemNode::Control);
1791         Node* mem = first->in(MemNode::Memory);
1792         Node* adr = low_adr->in(MemNode::Address);
1793         const TypePtr* atyp = n->adr_type();
1794         vn = StoreVectorNode::make(opc, ctl, mem, adr, atyp, val, vlen);
1795         vlen_in_bytes = vn->as_StoreVector()->memory_size();
1796       } else if (n->req() == 3) {
1797         // Promote operands to vector
1798         Node* in1 = NULL;
1799         bool node_isa_reduction = n->is_reduction();
1800         if (node_isa_reduction) {
1801           // the input to the first reduction operation is retained
1802           in1 = low_adr->in(1);
1803         } else {
1804           in1 = vector_opd(p, 1);
1805         }
1806         Node* in2 = vector_opd(p, 2);
1807         if (VectorNode::is_invariant_vector(in1) && (node_isa_reduction == false) && (n->is_Add() || n->is_Mul())) {
1808           // Move invariant vector input into second position to avoid register spilling.
1809           Node* tmp = in1;
1810           in1 = in2;
1811           in2 = tmp;
1812         }
1813         if (node_isa_reduction) {
1814           const Type *arith_type = n->bottom_type();
1815           vn = ReductionNode::make(opc, NULL, in1, in2, arith_type->basic_type());
1816           if (in2->is_Load()) {
1817             vlen_in_bytes = in2->as_LoadVector()->memory_size();
1818           } else {
1819             vlen_in_bytes = in2->as_Vector()->length_in_bytes();
1820           }
1821         } else {
1822           vn = VectorNode::make(opc, in1, in2, vlen, velt_basic_type(n));
1823           vlen_in_bytes = vn->as_Vector()->length_in_bytes();
1824         }
1825       } else {
1826         ShouldNotReachHere();
1827       }
1828       assert(vn != NULL, "sanity");
1829       _igvn.register_new_node_with_optimizer(vn);
1830       _phase->set_ctrl(vn, _phase->get_ctrl(p->at(0)));
1831       for (uint j = 0; j < p->size(); j++) {
1832         Node* pm = p->at(j);
1833         _igvn.replace_node(pm, vn);
1834       }
1835       _igvn._worklist.push(vn);
1836 
1837       if (vlen_in_bytes > max_vlen_in_bytes) {
1838         max_vlen_in_bytes = vlen_in_bytes;
1839       }
1840 #ifdef ASSERT
1841       if (TraceNewVectors) {
1842         tty->print("new Vector node: ");
1843         vn->dump();
1844       }
1845 #endif
1846     }
1847   }
1848   C->set_max_vector_size(max_vlen_in_bytes);
1849 }
1850 
1851 //------------------------------vector_opd---------------------------
1852 // Create a vector operand for the nodes in pack p for operand: in(opd_idx)
1853 Node* SuperWord::vector_opd(Node_List* p, int opd_idx) {
1854   Node* p0 = p->at(0);
1855   uint vlen = p->size();
1856   Node* opd = p0->in(opd_idx);
1857 
1858   if (same_inputs(p, opd_idx)) {
1859     if (opd->is_Vector() || opd->is_LoadVector()) {
1860       assert(((opd_idx != 2) || !VectorNode::is_shift(p0)), "shift's count can't be vector");
1861       return opd; // input is matching vector
1862     }
1863     if ((opd_idx == 2) && VectorNode::is_shift(p0)) {
1864       Compile* C = _phase->C;
1865       Node* cnt = opd;
1866       // Vector instructions do not mask shift count, do it here.
1867       juint mask = (p0->bottom_type() == TypeInt::INT) ? (BitsPerInt - 1) : (BitsPerLong - 1);
1868       const TypeInt* t = opd->find_int_type();
1869       if (t != NULL && t->is_con()) {
1870         juint shift = t->get_con();
1871         if (shift > mask) { // Unsigned cmp
1872           cnt = ConNode::make(TypeInt::make(shift & mask));
1873         }
1874       } else {
1875         if (t == NULL || t->_lo < 0 || t->_hi > (int)mask) {
1876           cnt = ConNode::make(TypeInt::make(mask));
1877           _igvn.register_new_node_with_optimizer(cnt);
1878           cnt = new AndINode(opd, cnt);
1879           _igvn.register_new_node_with_optimizer(cnt);
1880           _phase->set_ctrl(cnt, _phase->get_ctrl(opd));
1881         }
1882         assert(opd->bottom_type()->isa_int(), "int type only");
1883         // Move non constant shift count into vector register.
1884         cnt = VectorNode::shift_count(p0, cnt, vlen, velt_basic_type(p0));
1885       }
1886       if (cnt != opd) {
1887         _igvn.register_new_node_with_optimizer(cnt);
1888         _phase->set_ctrl(cnt, _phase->get_ctrl(opd));
1889       }
1890       return cnt;
1891     }
1892     assert(!opd->is_StoreVector(), "such vector is not expected here");
1893     // Convert scalar input to vector with the same number of elements as
1894     // p0's vector. Use p0's type because size of operand's container in
1895     // vector should match p0's size regardless operand's size.
1896     const Type* p0_t = velt_type(p0);
1897     VectorNode* vn = VectorNode::scalar2vector(opd, vlen, p0_t);
1898 
1899     _igvn.register_new_node_with_optimizer(vn);
1900     _phase->set_ctrl(vn, _phase->get_ctrl(opd));
1901 #ifdef ASSERT
1902     if (TraceNewVectors) {
1903       tty->print("new Vector node: ");
1904       vn->dump();
1905     }
1906 #endif
1907     return vn;
1908   }
1909 
1910   // Insert pack operation
1911   BasicType bt = velt_basic_type(p0);
1912   PackNode* pk = PackNode::make(opd, vlen, bt);
1913   DEBUG_ONLY( const BasicType opd_bt = opd->bottom_type()->basic_type(); )
1914 
1915   for (uint i = 1; i < vlen; i++) {
1916     Node* pi = p->at(i);
1917     Node* in = pi->in(opd_idx);
1918     assert(my_pack(in) == NULL, "Should already have been unpacked");
1919     assert(opd_bt == in->bottom_type()->basic_type(), "all same type");
1920     pk->add_opd(in);
1921   }
1922   _igvn.register_new_node_with_optimizer(pk);
1923   _phase->set_ctrl(pk, _phase->get_ctrl(opd));
1924 #ifdef ASSERT
1925   if (TraceNewVectors) {
1926     tty->print("new Vector node: ");
1927     pk->dump();
1928   }
1929 #endif
1930   return pk;
1931 }
1932 
1933 //------------------------------insert_extracts---------------------------
1934 // If a use of pack p is not a vector use, then replace the
1935 // use with an extract operation.
1936 void SuperWord::insert_extracts(Node_List* p) {
1937   if (p->at(0)->is_Store()) return;
1938   assert(_n_idx_list.is_empty(), "empty (node,index) list");
1939 
1940   // Inspect each use of each pack member.  For each use that is
1941   // not a vector use, replace the use with an extract operation.
1942 
1943   for (uint i = 0; i < p->size(); i++) {
1944     Node* def = p->at(i);
1945     for (DUIterator_Fast jmax, j = def->fast_outs(jmax); j < jmax; j++) {
1946       Node* use = def->fast_out(j);
1947       for (uint k = 0; k < use->req(); k++) {
1948         Node* n = use->in(k);
1949         if (def == n) {
1950           if (!is_vector_use(use, k)) {
1951             _n_idx_list.push(use, k);
1952           }
1953         }
1954       }
1955     }
1956   }
1957 
1958   while (_n_idx_list.is_nonempty()) {
1959     Node* use = _n_idx_list.node();
1960     int   idx = _n_idx_list.index();
1961     _n_idx_list.pop();
1962     Node* def = use->in(idx);
1963 
1964     if (def->is_reduction()) continue;
1965 
1966     // Insert extract operation
1967     _igvn.hash_delete(def);
1968     int def_pos = alignment(def) / data_size(def);
1969 
1970     Node* ex = ExtractNode::make(def, def_pos, velt_basic_type(def));
1971     _igvn.register_new_node_with_optimizer(ex);
1972     _phase->set_ctrl(ex, _phase->get_ctrl(def));
1973     _igvn.replace_input_of(use, idx, ex);
1974     _igvn._worklist.push(def);
1975 
1976     bb_insert_after(ex, bb_idx(def));
1977     set_velt_type(ex, velt_type(def));
1978   }
1979 }
1980 
1981 //------------------------------is_vector_use---------------------------
1982 // Is use->in(u_idx) a vector use?
1983 bool SuperWord::is_vector_use(Node* use, int u_idx) {
1984   Node_List* u_pk = my_pack(use);
1985   if (u_pk == NULL) return false;
1986   if (use->is_reduction()) return true;
1987   Node* def = use->in(u_idx);
1988   Node_List* d_pk = my_pack(def);
1989   if (d_pk == NULL) {
1990     // check for scalar promotion
1991     Node* n = u_pk->at(0)->in(u_idx);
1992     for (uint i = 1; i < u_pk->size(); i++) {
1993       if (u_pk->at(i)->in(u_idx) != n) return false;
1994     }
1995     return true;
1996   }
1997   if (u_pk->size() != d_pk->size())
1998     return false;
1999   for (uint i = 0; i < u_pk->size(); i++) {
2000     Node* ui = u_pk->at(i);
2001     Node* di = d_pk->at(i);
2002     if (ui->in(u_idx) != di || alignment(ui) != alignment(di))
2003       return false;
2004   }
2005   return true;
2006 }
2007 
2008 //------------------------------construct_bb---------------------------
2009 // Construct reverse postorder list of block members
2010 bool SuperWord::construct_bb() {
2011   Node* entry = bb();
2012 
2013   assert(_stk.length() == 0,            "stk is empty");
2014   assert(_block.length() == 0,          "block is empty");
2015   assert(_data_entry.length() == 0,     "data_entry is empty");
2016   assert(_mem_slice_head.length() == 0, "mem_slice_head is empty");
2017   assert(_mem_slice_tail.length() == 0, "mem_slice_tail is empty");
2018 
2019   // Find non-control nodes with no inputs from within block,
2020   // create a temporary map from node _idx to bb_idx for use
2021   // by the visited and post_visited sets,
2022   // and count number of nodes in block.
2023   int bb_ct = 0;
2024   for (uint i = 0; i < lpt()->_body.size(); i++) {
2025     Node *n = lpt()->_body.at(i);
2026     set_bb_idx(n, i); // Create a temporary map
2027     if (in_bb(n)) {
2028       if (n->is_LoadStore() || n->is_MergeMem() ||
2029           (n->is_Proj() && !n->as_Proj()->is_CFG())) {
2030         // Bailout if the loop has LoadStore, MergeMem or data Proj
2031         // nodes. Superword optimization does not work with them.
2032         return false;
2033       }
2034       bb_ct++;
2035       if (!n->is_CFG()) {
2036         bool found = false;
2037         for (uint j = 0; j < n->req(); j++) {
2038           Node* def = n->in(j);
2039           if (def && in_bb(def)) {
2040             found = true;
2041             break;
2042           }
2043         }
2044         if (!found) {
2045           assert(n != entry, "can't be entry");
2046           _data_entry.push(n);
2047         }
2048       }
2049     }
2050   }
2051 
2052   // Find memory slices (head and tail)
2053   for (DUIterator_Fast imax, i = lp()->fast_outs(imax); i < imax; i++) {
2054     Node *n = lp()->fast_out(i);
2055     if (in_bb(n) && (n->is_Phi() && n->bottom_type() == Type::MEMORY)) {
2056       Node* n_tail  = n->in(LoopNode::LoopBackControl);
2057       if (n_tail != n->in(LoopNode::EntryControl)) {
2058         if (!n_tail->is_Mem()) {
2059           assert(n_tail->is_Mem(), err_msg_res("unexpected node for memory slice: %s", n_tail->Name()));
2060           return false; // Bailout
2061         }
2062         _mem_slice_head.push(n);
2063         _mem_slice_tail.push(n_tail);
2064       }
2065     }
2066   }
2067 
2068   // Create an RPO list of nodes in block
2069 
2070   visited_clear();
2071   post_visited_clear();
2072 
2073   // Push all non-control nodes with no inputs from within block, then control entry
2074   for (int j = 0; j < _data_entry.length(); j++) {
2075     Node* n = _data_entry.at(j);
2076     visited_set(n);
2077     _stk.push(n);
2078   }
2079   visited_set(entry);
2080   _stk.push(entry);
2081 
2082   // Do a depth first walk over out edges
2083   int rpo_idx = bb_ct - 1;
2084   int size;
2085   int reduction_uses = 0;
2086   while ((size = _stk.length()) > 0) {
2087     Node* n = _stk.top(); // Leave node on stack
2088     if (!visited_test_set(n)) {
2089       // forward arc in graph
2090     } else if (!post_visited_test(n)) {
2091       // cross or back arc
2092       for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
2093         Node *use = n->fast_out(i);
2094         if (in_bb(use) && !visited_test(use) &&
2095             // Don't go around backedge
2096             (!use->is_Phi() || n == entry)) {
2097           if (use->is_reduction()) {
2098             // First see if we can map the reduction on the given system we are on, then
2099             // make a data entry operation for each reduction we see.
2100             BasicType bt = use->bottom_type()->basic_type();
2101             if (ReductionNode::implemented(use->Opcode(), Matcher::min_vector_size(bt), bt)) {
2102               reduction_uses++;
2103             }
2104           }
2105           _stk.push(use);
2106         }
2107       }
2108       if (_stk.length() == size) {
2109         // There were no additional uses, post visit node now
2110         _stk.pop(); // Remove node from stack
2111         assert(rpo_idx >= 0, "");
2112         _block.at_put_grow(rpo_idx, n);
2113         rpo_idx--;
2114         post_visited_set(n);
2115         assert(rpo_idx >= 0 || _stk.is_empty(), "");
2116       }
2117     } else {
2118       _stk.pop(); // Remove post-visited node from stack
2119     }
2120   }
2121 
2122   // Create real map of block indices for nodes
2123   for (int j = 0; j < _block.length(); j++) {
2124     Node* n = _block.at(j);
2125     set_bb_idx(n, j);
2126   }
2127 
2128   // Ensure extra info is allocated.
2129   initialize_bb();
2130 
2131 #ifndef PRODUCT
2132   if (TraceSuperWord) {
2133     print_bb();
2134     tty->print_cr("\ndata entry nodes: %s", _data_entry.length() > 0 ? "" : "NONE");
2135     for (int m = 0; m < _data_entry.length(); m++) {
2136       tty->print("%3d ", m);
2137       _data_entry.at(m)->dump();
2138     }
2139     tty->print_cr("\nmemory slices: %s", _mem_slice_head.length() > 0 ? "" : "NONE");
2140     for (int m = 0; m < _mem_slice_head.length(); m++) {
2141       tty->print("%3d ", m); _mem_slice_head.at(m)->dump();
2142       tty->print("    ");    _mem_slice_tail.at(m)->dump();
2143     }
2144   }
2145 #endif
2146   assert(rpo_idx == -1 && bb_ct == _block.length(), "all block members found");
2147   return (_mem_slice_head.length() > 0) || (reduction_uses > 0) || (_data_entry.length() > 0);
2148 }
2149 
2150 //------------------------------initialize_bb---------------------------
2151 // Initialize per node info
2152 void SuperWord::initialize_bb() {
2153   Node* last = _block.at(_block.length() - 1);
2154   grow_node_info(bb_idx(last));
2155 }
2156 
2157 //------------------------------bb_insert_after---------------------------
2158 // Insert n into block after pos
2159 void SuperWord::bb_insert_after(Node* n, int pos) {
2160   int n_pos = pos + 1;
2161   // Make room
2162   for (int i = _block.length() - 1; i >= n_pos; i--) {
2163     _block.at_put_grow(i+1, _block.at(i));
2164   }
2165   for (int j = _node_info.length() - 1; j >= n_pos; j--) {
2166     _node_info.at_put_grow(j+1, _node_info.at(j));
2167   }
2168   // Set value
2169   _block.at_put_grow(n_pos, n);
2170   _node_info.at_put_grow(n_pos, SWNodeInfo::initial);
2171   // Adjust map from node->_idx to _block index
2172   for (int i = n_pos; i < _block.length(); i++) {
2173     set_bb_idx(_block.at(i), i);
2174   }
2175 }
2176 
2177 //------------------------------compute_max_depth---------------------------
2178 // Compute max depth for expressions from beginning of block
2179 // Use to prune search paths during test for independence.
2180 void SuperWord::compute_max_depth() {
2181   int ct = 0;
2182   bool again;
2183   do {
2184     again = false;
2185     for (int i = 0; i < _block.length(); i++) {
2186       Node* n = _block.at(i);
2187       if (!n->is_Phi()) {
2188         int d_orig = depth(n);
2189         int d_in   = 0;
2190         for (DepPreds preds(n, _dg); !preds.done(); preds.next()) {
2191           Node* pred = preds.current();
2192           if (in_bb(pred)) {
2193             d_in = MAX2(d_in, depth(pred));
2194           }
2195         }
2196         if (d_in + 1 != d_orig) {
2197           set_depth(n, d_in + 1);
2198           again = true;
2199         }
2200       }
2201     }
2202     ct++;
2203   } while (again);
2204 #ifndef PRODUCT
2205   if (TraceSuperWord && Verbose)
2206     tty->print_cr("compute_max_depth iterated: %d times", ct);
2207 #endif
2208 }
2209 
2210 //-------------------------compute_vector_element_type-----------------------
2211 // Compute necessary vector element type for expressions
2212 // This propagates backwards a narrower integer type when the
2213 // upper bits of the value are not needed.
2214 // Example:  char a,b,c;  a = b + c;
2215 // Normally the type of the add is integer, but for packed character
2216 // operations the type of the add needs to be char.
2217 void SuperWord::compute_vector_element_type() {
2218 #ifndef PRODUCT
2219   if (TraceSuperWord && Verbose)
2220     tty->print_cr("\ncompute_velt_type:");
2221 #endif
2222 
2223   // Initial type
2224   for (int i = 0; i < _block.length(); i++) {
2225     Node* n = _block.at(i);
2226     set_velt_type(n, container_type(n));
2227   }
2228 
2229   // Propagate integer narrowed type backwards through operations
2230   // that don't depend on higher order bits
2231   for (int i = _block.length() - 1; i >= 0; i--) {
2232     Node* n = _block.at(i);
2233     // Only integer types need be examined
2234     const Type* vtn = velt_type(n);
2235     if (vtn->basic_type() == T_INT) {
2236       uint start, end;
2237       VectorNode::vector_operands(n, &start, &end);
2238 
2239       for (uint j = start; j < end; j++) {
2240         Node* in  = n->in(j);
2241         // Don't propagate through a memory
2242         if (!in->is_Mem() && in_bb(in) && velt_type(in)->basic_type() == T_INT &&
2243             data_size(n) < data_size(in)) {
2244           bool same_type = true;
2245           for (DUIterator_Fast kmax, k = in->fast_outs(kmax); k < kmax; k++) {
2246             Node *use = in->fast_out(k);
2247             if (!in_bb(use) || !same_velt_type(use, n)) {
2248               same_type = false;
2249               break;
2250             }
2251           }
2252           if (same_type) {
2253             // For right shifts of small integer types (bool, byte, char, short)
2254             // we need precise information about sign-ness. Only Load nodes have
2255             // this information because Store nodes are the same for signed and
2256             // unsigned values. And any arithmetic operation after a load may
2257             // expand a value to signed Int so such right shifts can't be used
2258             // because vector elements do not have upper bits of Int.
2259             const Type* vt = vtn;
2260             if (VectorNode::is_shift(in)) {
2261               Node* load = in->in(1);
2262               if (load->is_Load() && in_bb(load) && (velt_type(load)->basic_type() == T_INT)) {
2263                 vt = velt_type(load);
2264               } else if (in->Opcode() != Op_LShiftI) {
2265                 // Widen type to Int to avoid creation of right shift vector
2266                 // (align + data_size(s1) check in stmts_can_pack() will fail).
2267                 // Note, left shifts work regardless type.
2268                 vt = TypeInt::INT;
2269               }
2270             }
2271             set_velt_type(in, vt);
2272           }
2273         }
2274       }
2275     }
2276   }
2277 #ifndef PRODUCT
2278   if (TraceSuperWord && Verbose) {
2279     for (int i = 0; i < _block.length(); i++) {
2280       Node* n = _block.at(i);
2281       velt_type(n)->dump();
2282       tty->print("\t");
2283       n->dump();
2284     }
2285   }
2286 #endif
2287 }
2288 
2289 //------------------------------memory_alignment---------------------------
2290 // Alignment within a vector memory reference
2291 int SuperWord::memory_alignment(MemNode* s, int iv_adjust) {
2292   SWPointer p(s, this, NULL, false);
2293   if (!p.valid()) {
2294     return bottom_align;
2295   }
2296   int vw = vector_width_in_bytes(s);
2297   if (vw < 2) {
2298     return bottom_align; // No vectors for this type
2299   }
2300   int offset  = p.offset_in_bytes();
2301   offset     += iv_adjust*p.memory_size();
2302   int off_rem = offset % vw;
2303   int off_mod = off_rem >= 0 ? off_rem : off_rem + vw;
2304   return off_mod;
2305 }
2306 
2307 //---------------------------container_type---------------------------
2308 // Smallest type containing range of values
2309 const Type* SuperWord::container_type(Node* n) {
2310   if (n->is_Mem()) {
2311     BasicType bt = n->as_Mem()->memory_type();
2312     if (n->is_Store() && (bt == T_CHAR)) {
2313       // Use T_SHORT type instead of T_CHAR for stored values because any
2314       // preceding arithmetic operation extends values to signed Int.
2315       bt = T_SHORT;
2316     }
2317     if (n->Opcode() == Op_LoadUB) {
2318       // Adjust type for unsigned byte loads, it is important for right shifts.
2319       // T_BOOLEAN is used because there is no basic type representing type
2320       // TypeInt::UBYTE. Use of T_BOOLEAN for vectors is fine because only
2321       // size (one byte) and sign is important.
2322       bt = T_BOOLEAN;
2323     }
2324     return Type::get_const_basic_type(bt);
2325   }
2326   const Type* t = _igvn.type(n);
2327   if (t->basic_type() == T_INT) {
2328     // A narrow type of arithmetic operations will be determined by
2329     // propagating the type of memory operations.
2330     return TypeInt::INT;
2331   }
2332   return t;
2333 }
2334 
2335 bool SuperWord::same_velt_type(Node* n1, Node* n2) {
2336   const Type* vt1 = velt_type(n1);
2337   const Type* vt2 = velt_type(n2);
2338   if (vt1->basic_type() == T_INT && vt2->basic_type() == T_INT) {
2339     // Compare vectors element sizes for integer types.
2340     return data_size(n1) == data_size(n2);
2341   }
2342   return vt1 == vt2;
2343 }
2344 
2345 //------------------------------in_packset---------------------------
2346 // Are s1 and s2 in a pack pair and ordered as s1,s2?
2347 bool SuperWord::in_packset(Node* s1, Node* s2) {
2348   for (int i = 0; i < _packset.length(); i++) {
2349     Node_List* p = _packset.at(i);
2350     assert(p->size() == 2, "must be");
2351     if (p->at(0) == s1 && p->at(p->size()-1) == s2) {
2352       return true;
2353     }
2354   }
2355   return false;
2356 }
2357 
2358 //------------------------------in_pack---------------------------
2359 // Is s in pack p?
2360 Node_List* SuperWord::in_pack(Node* s, Node_List* p) {
2361   for (uint i = 0; i < p->size(); i++) {
2362     if (p->at(i) == s) {
2363       return p;
2364     }
2365   }
2366   return NULL;
2367 }
2368 
2369 //------------------------------remove_pack_at---------------------------
2370 // Remove the pack at position pos in the packset
2371 void SuperWord::remove_pack_at(int pos) {
2372   Node_List* p = _packset.at(pos);
2373   for (uint i = 0; i < p->size(); i++) {
2374     Node* s = p->at(i);
2375     set_my_pack(s, NULL);
2376   }
2377   _packset.remove_at(pos);
2378 }
2379 
2380 void SuperWord::packset_sort(int n) {
2381   // simple bubble sort so that we capitalize with O(n) when its already sorted
2382   while (n != 0) {
2383     bool swapped = false;
2384     for (int i = 1; i < n; i++) {
2385       Node_List* q_low = _packset.at(i-1);
2386       Node_List* q_i = _packset.at(i);
2387 
2388       // only swap when we find something to swap
2389       if (alignment(q_low->at(0)) > alignment(q_i->at(0))) {
2390         Node_List* t = q_i;
2391         *(_packset.adr_at(i)) = q_low;
2392         *(_packset.adr_at(i-1)) = q_i;
2393         swapped = true;
2394       }
2395     }
2396     if (swapped == false) break;
2397     n--;
2398   }
2399 }
2400 
2401 //------------------------------executed_first---------------------------
2402 // Return the node executed first in pack p.  Uses the RPO block list
2403 // to determine order.
2404 Node* SuperWord::executed_first(Node_List* p) {
2405   Node* n = p->at(0);
2406   int n_rpo = bb_idx(n);
2407   for (uint i = 1; i < p->size(); i++) {
2408     Node* s = p->at(i);
2409     int s_rpo = bb_idx(s);
2410     if (s_rpo < n_rpo) {
2411       n = s;
2412       n_rpo = s_rpo;
2413     }
2414   }
2415   return n;
2416 }
2417 
2418 //------------------------------executed_last---------------------------
2419 // Return the node executed last in pack p.
2420 Node* SuperWord::executed_last(Node_List* p) {
2421   Node* n = p->at(0);
2422   int n_rpo = bb_idx(n);
2423   for (uint i = 1; i < p->size(); i++) {
2424     Node* s = p->at(i);
2425     int s_rpo = bb_idx(s);
2426     if (s_rpo > n_rpo) {
2427       n = s;
2428       n_rpo = s_rpo;
2429     }
2430   }
2431   return n;
2432 }
2433 
2434 LoadNode::ControlDependency SuperWord::control_dependency(Node_List* p) {
2435   LoadNode::ControlDependency dep = LoadNode::DependsOnlyOnTest;
2436   for (uint i = 0; i < p->size(); i++) {
2437     Node* n = p->at(i);
2438     assert(n->is_Load(), "only meaningful for loads");
2439     if (!n->depends_only_on_test()) {
2440       dep = LoadNode::Pinned;
2441     }
2442   }
2443   return dep;
2444 }
2445 
2446 
2447 //----------------------------align_initial_loop_index---------------------------
2448 // Adjust pre-loop limit so that in main loop, a load/store reference
2449 // to align_to_ref will be a position zero in the vector.
2450 //   (iv + k) mod vector_align == 0
2451 void SuperWord::align_initial_loop_index(MemNode* align_to_ref) {
2452   CountedLoopNode *main_head = lp()->as_CountedLoop();
2453   assert(main_head->is_main_loop(), "");
2454   CountedLoopEndNode* pre_end = get_pre_loop_end(main_head);
2455   assert(pre_end != NULL, "we must have a correct pre-loop");
2456   Node *pre_opaq1 = pre_end->limit();
2457   assert(pre_opaq1->Opcode() == Op_Opaque1, "");
2458   Opaque1Node *pre_opaq = (Opaque1Node*)pre_opaq1;
2459   Node *lim0 = pre_opaq->in(1);
2460 
2461   // Where we put new limit calculations
2462   Node *pre_ctrl = pre_end->loopnode()->in(LoopNode::EntryControl);
2463 
2464   // Ensure the original loop limit is available from the
2465   // pre-loop Opaque1 node.
2466   Node *orig_limit = pre_opaq->original_loop_limit();
2467   assert(orig_limit != NULL && _igvn.type(orig_limit) != Type::TOP, "");
2468 
2469   SWPointer align_to_ref_p(align_to_ref, this, NULL, false);
2470   assert(align_to_ref_p.valid(), "sanity");
2471 
2472   // Given:
2473   //     lim0 == original pre loop limit
2474   //     V == v_align (power of 2)
2475   //     invar == extra invariant piece of the address expression
2476   //     e == offset [ +/- invar ]
2477   //
2478   // When reassociating expressions involving '%' the basic rules are:
2479   //     (a - b) % k == 0   =>  a % k == b % k
2480   // and:
2481   //     (a + b) % k == 0   =>  a % k == (k - b) % k
2482   //
2483   // For stride > 0 && scale > 0,
2484   //   Derive the new pre-loop limit "lim" such that the two constraints:
2485   //     (1) lim = lim0 + N           (where N is some positive integer < V)
2486   //     (2) (e + lim) % V == 0
2487   //   are true.
2488   //
2489   //   Substituting (1) into (2),
2490   //     (e + lim0 + N) % V == 0
2491   //   solve for N:
2492   //     N = (V - (e + lim0)) % V
2493   //   substitute back into (1), so that new limit
2494   //     lim = lim0 + (V - (e + lim0)) % V
2495   //
2496   // For stride > 0 && scale < 0
2497   //   Constraints:
2498   //     lim = lim0 + N
2499   //     (e - lim) % V == 0
2500   //   Solving for lim:
2501   //     (e - lim0 - N) % V == 0
2502   //     N = (e - lim0) % V
2503   //     lim = lim0 + (e - lim0) % V
2504   //
2505   // For stride < 0 && scale > 0
2506   //   Constraints:
2507   //     lim = lim0 - N
2508   //     (e + lim) % V == 0
2509   //   Solving for lim:
2510   //     (e + lim0 - N) % V == 0
2511   //     N = (e + lim0) % V
2512   //     lim = lim0 - (e + lim0) % V
2513   //
2514   // For stride < 0 && scale < 0
2515   //   Constraints:
2516   //     lim = lim0 - N
2517   //     (e - lim) % V == 0
2518   //   Solving for lim:
2519   //     (e - lim0 + N) % V == 0
2520   //     N = (V - (e - lim0)) % V
2521   //     lim = lim0 - (V - (e - lim0)) % V
2522 
2523   int vw = vector_width_in_bytes(align_to_ref);
2524   int stride   = iv_stride();
2525   int scale    = align_to_ref_p.scale_in_bytes();
2526   int elt_size = align_to_ref_p.memory_size();
2527   int v_align  = vw / elt_size;
2528   assert(v_align > 1, "sanity");
2529   int offset   = align_to_ref_p.offset_in_bytes() / elt_size;
2530   Node *offsn  = _igvn.intcon(offset);
2531 
2532   Node *e = offsn;
2533   if (align_to_ref_p.invar() != NULL) {
2534     // incorporate any extra invariant piece producing (offset +/- invar) >>> log2(elt)
2535     Node* log2_elt = _igvn.intcon(exact_log2(elt_size));
2536     Node* aref     = new URShiftINode(align_to_ref_p.invar(), log2_elt);
2537     _igvn.register_new_node_with_optimizer(aref);
2538     _phase->set_ctrl(aref, pre_ctrl);
2539     if (align_to_ref_p.negate_invar()) {
2540       e = new SubINode(e, aref);
2541     } else {
2542       e = new AddINode(e, aref);
2543     }
2544     _igvn.register_new_node_with_optimizer(e);
2545     _phase->set_ctrl(e, pre_ctrl);
2546   }
2547   if (vw > ObjectAlignmentInBytes) {
2548     // incorporate base e +/- base && Mask >>> log2(elt)
2549     Node* xbase = new CastP2XNode(NULL, align_to_ref_p.base());
2550     _igvn.register_new_node_with_optimizer(xbase);
2551 #ifdef _LP64
2552     xbase  = new ConvL2INode(xbase);
2553     _igvn.register_new_node_with_optimizer(xbase);
2554 #endif
2555     Node* mask = _igvn.intcon(vw-1);
2556     Node* masked_xbase  = new AndINode(xbase, mask);
2557     _igvn.register_new_node_with_optimizer(masked_xbase);
2558     Node* log2_elt = _igvn.intcon(exact_log2(elt_size));
2559     Node* bref     = new URShiftINode(masked_xbase, log2_elt);
2560     _igvn.register_new_node_with_optimizer(bref);
2561     _phase->set_ctrl(bref, pre_ctrl);
2562     e = new AddINode(e, bref);
2563     _igvn.register_new_node_with_optimizer(e);
2564     _phase->set_ctrl(e, pre_ctrl);
2565   }
2566 
2567   // compute e +/- lim0
2568   if (scale < 0) {
2569     e = new SubINode(e, lim0);
2570   } else {
2571     e = new AddINode(e, lim0);
2572   }
2573   _igvn.register_new_node_with_optimizer(e);
2574   _phase->set_ctrl(e, pre_ctrl);
2575 
2576   if (stride * scale > 0) {
2577     // compute V - (e +/- lim0)
2578     Node* va  = _igvn.intcon(v_align);
2579     e = new SubINode(va, e);
2580     _igvn.register_new_node_with_optimizer(e);
2581     _phase->set_ctrl(e, pre_ctrl);
2582   }
2583   // compute N = (exp) % V
2584   Node* va_msk = _igvn.intcon(v_align - 1);
2585   Node* N = new AndINode(e, va_msk);
2586   _igvn.register_new_node_with_optimizer(N);
2587   _phase->set_ctrl(N, pre_ctrl);
2588 
2589   //   substitute back into (1), so that new limit
2590   //     lim = lim0 + N
2591   Node* lim;
2592   if (stride < 0) {
2593     lim = new SubINode(lim0, N);
2594   } else {
2595     lim = new AddINode(lim0, N);
2596   }
2597   _igvn.register_new_node_with_optimizer(lim);
2598   _phase->set_ctrl(lim, pre_ctrl);
2599   Node* constrained =
2600     (stride > 0) ? (Node*) new MinINode(lim, orig_limit)
2601                  : (Node*) new MaxINode(lim, orig_limit);
2602   _igvn.register_new_node_with_optimizer(constrained);
2603   _phase->set_ctrl(constrained, pre_ctrl);
2604   _igvn.hash_delete(pre_opaq);
2605   pre_opaq->set_req(1, constrained);
2606 }
2607 
2608 //----------------------------get_pre_loop_end---------------------------
2609 // Find pre loop end from main loop.  Returns null if none.
2610 CountedLoopEndNode* SuperWord::get_pre_loop_end(CountedLoopNode *cl) {
2611   Node *ctrl = cl->in(LoopNode::EntryControl);
2612   if (!ctrl->is_IfTrue() && !ctrl->is_IfFalse()) return NULL;
2613   Node *iffm = ctrl->in(0);
2614   if (!iffm->is_If()) return NULL;
2615   Node *p_f = iffm->in(0);
2616   if (!p_f->is_IfFalse()) return NULL;
2617   if (!p_f->in(0)->is_CountedLoopEnd()) return NULL;
2618   CountedLoopEndNode *pre_end = p_f->in(0)->as_CountedLoopEnd();
2619   CountedLoopNode* loop_node = pre_end->loopnode();
2620   if (loop_node == NULL || !loop_node->is_pre_loop()) return NULL;
2621   return pre_end;
2622 }
2623 
2624 
2625 //------------------------------init---------------------------
2626 void SuperWord::init() {
2627   _dg.init();
2628   _packset.clear();
2629   _disjoint_ptrs.clear();
2630   _block.clear();
2631   _data_entry.clear();
2632   _mem_slice_head.clear();
2633   _mem_slice_tail.clear();
2634   _iteration_first.clear();
2635   _iteration_last.clear();
2636   _node_info.clear();
2637   _align_to_ref = NULL;
2638   _lpt = NULL;
2639   _lp = NULL;
2640   _bb = NULL;
2641   _iv = NULL;
2642   _race_possible = 0;
2643   _early_return = false;
2644   _num_work_vecs = 0;
2645   _num_reductions = 0;
2646 }
2647 
2648 //------------------------------restart---------------------------
2649 void SuperWord::restart() {
2650   _dg.init();
2651   _packset.clear();
2652   _disjoint_ptrs.clear();
2653   _block.clear();
2654   _data_entry.clear();
2655   _mem_slice_head.clear();
2656   _mem_slice_tail.clear();
2657   _node_info.clear();
2658 }
2659 
2660 //------------------------------print_packset---------------------------
2661 void SuperWord::print_packset() {
2662 #ifndef PRODUCT
2663   tty->print_cr("packset");
2664   for (int i = 0; i < _packset.length(); i++) {
2665     tty->print_cr("Pack: %d", i);
2666     Node_List* p = _packset.at(i);
2667     print_pack(p);
2668   }
2669 #endif
2670 }
2671 
2672 //------------------------------print_pack---------------------------
2673 void SuperWord::print_pack(Node_List* p) {
2674   for (uint i = 0; i < p->size(); i++) {
2675     print_stmt(p->at(i));
2676   }
2677 }
2678 
2679 //------------------------------print_bb---------------------------
2680 void SuperWord::print_bb() {
2681 #ifndef PRODUCT
2682   tty->print_cr("\nBlock");
2683   for (int i = 0; i < _block.length(); i++) {
2684     Node* n = _block.at(i);
2685     tty->print("%d ", i);
2686     if (n) {
2687       n->dump();
2688     }
2689   }
2690 #endif
2691 }
2692 
2693 //------------------------------print_stmt---------------------------
2694 void SuperWord::print_stmt(Node* s) {
2695 #ifndef PRODUCT
2696   tty->print(" align: %d \t", alignment(s));
2697   s->dump();
2698 #endif
2699 }
2700 
2701 //------------------------------blank---------------------------
2702 char* SuperWord::blank(uint depth) {
2703   static char blanks[101];
2704   assert(depth < 101, "too deep");
2705   for (uint i = 0; i < depth; i++) blanks[i] = ' ';
2706   blanks[depth] = '\0';
2707   return blanks;
2708 }
2709 
2710 
2711 //==============================SWPointer===========================
2712 
2713 //----------------------------SWPointer------------------------
2714 SWPointer::SWPointer(MemNode* mem, SuperWord* slp, Node_Stack *nstack, bool analyze_only) :
2715   _mem(mem), _slp(slp),  _base(NULL),  _adr(NULL),
2716   _scale(0), _offset(0), _invar(NULL), _negate_invar(false),
2717   _nstack(nstack), _analyze_only(analyze_only),
2718   _stack_idx(0) {
2719 
2720   Node* adr = mem->in(MemNode::Address);
2721   if (!adr->is_AddP()) {
2722     assert(!valid(), "too complex");
2723     return;
2724   }
2725   // Match AddP(base, AddP(ptr, k*iv [+ invariant]), constant)
2726   Node* base = adr->in(AddPNode::Base);
2727   // The base address should be loop invariant
2728   if (!invariant(base)) {
2729     assert(!valid(), "base address is loop variant");
2730     return;
2731   }
2732   //unsafe reference could not be aligned appropriately without runtime checking
2733   if (base == NULL || base->bottom_type() == Type::TOP) {
2734     assert(!valid(), "unsafe access");
2735     return;
2736   }
2737   for (int i = 0; i < 3; i++) {
2738     if (!scaled_iv_plus_offset(adr->in(AddPNode::Offset))) {
2739       assert(!valid(), "too complex");
2740       return;
2741     }
2742     adr = adr->in(AddPNode::Address);
2743     if (base == adr || !adr->is_AddP()) {
2744       break; // stop looking at addp's
2745     }
2746   }
2747   _base = base;
2748   _adr  = adr;
2749   assert(valid(), "Usable");
2750 }
2751 
2752 // Following is used to create a temporary object during
2753 // the pattern match of an address expression.
2754 SWPointer::SWPointer(SWPointer* p) :
2755   _mem(p->_mem), _slp(p->_slp),  _base(NULL),  _adr(NULL),
2756   _scale(0), _offset(0), _invar(NULL), _negate_invar(false),
2757   _nstack(p->_nstack), _analyze_only(p->_analyze_only),
2758   _stack_idx(p->_stack_idx) {}
2759 
2760 //------------------------scaled_iv_plus_offset--------------------
2761 // Match: k*iv + offset
2762 // where: k is a constant that maybe zero, and
2763 //        offset is (k2 [+/- invariant]) where k2 maybe zero and invariant is optional
2764 bool SWPointer::scaled_iv_plus_offset(Node* n) {
2765   if (scaled_iv(n)) {
2766     return true;
2767   }
2768   if (offset_plus_k(n)) {
2769     return true;
2770   }
2771   int opc = n->Opcode();
2772   if (opc == Op_AddI) {
2773     if (scaled_iv(n->in(1)) && offset_plus_k(n->in(2))) {
2774       return true;
2775     }
2776     if (scaled_iv(n->in(2)) && offset_plus_k(n->in(1))) {
2777       return true;
2778     }
2779   } else if (opc == Op_SubI) {
2780     if (scaled_iv(n->in(1)) && offset_plus_k(n->in(2), true)) {
2781       return true;
2782     }
2783     if (scaled_iv(n->in(2)) && offset_plus_k(n->in(1))) {
2784       _scale *= -1;
2785       return true;
2786     }
2787   }
2788   return false;
2789 }
2790 
2791 //----------------------------scaled_iv------------------------
2792 // Match: k*iv where k is a constant that's not zero
2793 bool SWPointer::scaled_iv(Node* n) {
2794   if (_scale != 0) {
2795     return false;  // already found a scale
2796   }
2797   if (n == iv()) {
2798     _scale = 1;
2799     return true;
2800   }
2801   if (_analyze_only && (invariant(n) == false)) {
2802     _nstack->push(n, _stack_idx++);
2803   }
2804   int opc = n->Opcode();
2805   if (opc == Op_MulI) {
2806     if (n->in(1) == iv() && n->in(2)->is_Con()) {
2807       _scale = n->in(2)->get_int();
2808       return true;
2809     } else if (n->in(2) == iv() && n->in(1)->is_Con()) {
2810       _scale = n->in(1)->get_int();
2811       return true;
2812     }
2813   } else if (opc == Op_LShiftI) {
2814     if (n->in(1) == iv() && n->in(2)->is_Con()) {
2815       _scale = 1 << n->in(2)->get_int();
2816       return true;
2817     }
2818   } else if (opc == Op_ConvI2L) {
2819     if (scaled_iv_plus_offset(n->in(1))) {
2820       return true;
2821     }
2822   } else if (opc == Op_LShiftL) {
2823     if (!has_iv() && _invar == NULL) {
2824       // Need to preserve the current _offset value, so
2825       // create a temporary object for this expression subtree.
2826       // Hacky, so should re-engineer the address pattern match.
2827       SWPointer tmp(this);
2828       if (tmp.scaled_iv_plus_offset(n->in(1))) {
2829         if (tmp._invar == NULL) {
2830           int mult = 1 << n->in(2)->get_int();
2831           _scale   = tmp._scale  * mult;
2832           _offset += tmp._offset * mult;
2833           return true;
2834         }
2835       }
2836     }
2837   }
2838   return false;
2839 }
2840 
2841 //----------------------------offset_plus_k------------------------
2842 // Match: offset is (k [+/- invariant])
2843 // where k maybe zero and invariant is optional, but not both.
2844 bool SWPointer::offset_plus_k(Node* n, bool negate) {
2845   int opc = n->Opcode();
2846   if (opc == Op_ConI) {
2847     _offset += negate ? -(n->get_int()) : n->get_int();
2848     return true;
2849   } else if (opc == Op_ConL) {
2850     // Okay if value fits into an int
2851     const TypeLong* t = n->find_long_type();
2852     if (t->higher_equal(TypeLong::INT)) {
2853       jlong loff = n->get_long();
2854       jint  off  = (jint)loff;
2855       _offset += negate ? -off : loff;
2856       return true;
2857     }
2858     return false;
2859   }
2860   if (_invar != NULL) return false; // already have an invariant
2861   if (_analyze_only && (invariant(n) == false)) {
2862     _nstack->push(n, _stack_idx++);
2863   }
2864   if (opc == Op_AddI) {
2865     if (n->in(2)->is_Con() && invariant(n->in(1))) {
2866       _negate_invar = negate;
2867       _invar = n->in(1);
2868       _offset += negate ? -(n->in(2)->get_int()) : n->in(2)->get_int();
2869       return true;
2870     } else if (n->in(1)->is_Con() && invariant(n->in(2))) {
2871       _offset += negate ? -(n->in(1)->get_int()) : n->in(1)->get_int();
2872       _negate_invar = negate;
2873       _invar = n->in(2);
2874       return true;
2875     }
2876   }
2877   if (opc == Op_SubI) {
2878     if (n->in(2)->is_Con() && invariant(n->in(1))) {
2879       _negate_invar = negate;
2880       _invar = n->in(1);
2881       _offset += !negate ? -(n->in(2)->get_int()) : n->in(2)->get_int();
2882       return true;
2883     } else if (n->in(1)->is_Con() && invariant(n->in(2))) {
2884       _offset += negate ? -(n->in(1)->get_int()) : n->in(1)->get_int();
2885       _negate_invar = !negate;
2886       _invar = n->in(2);
2887       return true;
2888     }
2889   }
2890   if (invariant(n)) {
2891     _negate_invar = negate;
2892     _invar = n;
2893     return true;
2894   }
2895   return false;
2896 }
2897 
2898 //----------------------------print------------------------
2899 void SWPointer::print() {
2900 #ifndef PRODUCT
2901   tty->print("base: %d  adr: %d  scale: %d  offset: %d  invar: %c%d\n",
2902              _base != NULL ? _base->_idx : 0,
2903              _adr  != NULL ? _adr->_idx  : 0,
2904              _scale, _offset,
2905              _negate_invar?'-':'+',
2906              _invar != NULL ? _invar->_idx : 0);
2907 #endif
2908 }
2909 
2910 // ========================= OrderedPair =====================
2911 
2912 const OrderedPair OrderedPair::initial;
2913 
2914 // ========================= SWNodeInfo =====================
2915 
2916 const SWNodeInfo SWNodeInfo::initial;
2917 
2918 
2919 // ============================ DepGraph ===========================
2920 
2921 //------------------------------make_node---------------------------
2922 // Make a new dependence graph node for an ideal node.
2923 DepMem* DepGraph::make_node(Node* node) {
2924   DepMem* m = new (_arena) DepMem(node);
2925   if (node != NULL) {
2926     assert(_map.at_grow(node->_idx) == NULL, "one init only");
2927     _map.at_put_grow(node->_idx, m);
2928   }
2929   return m;
2930 }
2931 
2932 //------------------------------make_edge---------------------------
2933 // Make a new dependence graph edge from dpred -> dsucc
2934 DepEdge* DepGraph::make_edge(DepMem* dpred, DepMem* dsucc) {
2935   DepEdge* e = new (_arena) DepEdge(dpred, dsucc, dsucc->in_head(), dpred->out_head());
2936   dpred->set_out_head(e);
2937   dsucc->set_in_head(e);
2938   return e;
2939 }
2940 
2941 // ========================== DepMem ========================
2942 
2943 //------------------------------in_cnt---------------------------
2944 int DepMem::in_cnt() {
2945   int ct = 0;
2946   for (DepEdge* e = _in_head; e != NULL; e = e->next_in()) ct++;
2947   return ct;
2948 }
2949 
2950 //------------------------------out_cnt---------------------------
2951 int DepMem::out_cnt() {
2952   int ct = 0;
2953   for (DepEdge* e = _out_head; e != NULL; e = e->next_out()) ct++;
2954   return ct;
2955 }
2956 
2957 //------------------------------print-----------------------------
2958 void DepMem::print() {
2959 #ifndef PRODUCT
2960   tty->print("  DepNode %d (", _node->_idx);
2961   for (DepEdge* p = _in_head; p != NULL; p = p->next_in()) {
2962     Node* pred = p->pred()->node();
2963     tty->print(" %d", pred != NULL ? pred->_idx : 0);
2964   }
2965   tty->print(") [");
2966   for (DepEdge* s = _out_head; s != NULL; s = s->next_out()) {
2967     Node* succ = s->succ()->node();
2968     tty->print(" %d", succ != NULL ? succ->_idx : 0);
2969   }
2970   tty->print_cr(" ]");
2971 #endif
2972 }
2973 
2974 // =========================== DepEdge =========================
2975 
2976 //------------------------------DepPreds---------------------------
2977 void DepEdge::print() {
2978 #ifndef PRODUCT
2979   tty->print_cr("DepEdge: %d [ %d ]", _pred->node()->_idx, _succ->node()->_idx);
2980 #endif
2981 }
2982 
2983 // =========================== DepPreds =========================
2984 // Iterator over predecessor edges in the dependence graph.
2985 
2986 //------------------------------DepPreds---------------------------
2987 DepPreds::DepPreds(Node* n, DepGraph& dg) {
2988   _n = n;
2989   _done = false;
2990   if (_n->is_Store() || _n->is_Load()) {
2991     _next_idx = MemNode::Address;
2992     _end_idx  = n->req();
2993     _dep_next = dg.dep(_n)->in_head();
2994   } else if (_n->is_Mem()) {
2995     _next_idx = 0;
2996     _end_idx  = 0;
2997     _dep_next = dg.dep(_n)->in_head();
2998   } else {
2999     _next_idx = 1;
3000     _end_idx  = _n->req();
3001     _dep_next = NULL;
3002   }
3003   next();
3004 }
3005 
3006 //------------------------------next---------------------------
3007 void DepPreds::next() {
3008   if (_dep_next != NULL) {
3009     _current  = _dep_next->pred()->node();
3010     _dep_next = _dep_next->next_in();
3011   } else if (_next_idx < _end_idx) {
3012     _current  = _n->in(_next_idx++);
3013   } else {
3014     _done = true;
3015   }
3016 }
3017 
3018 // =========================== DepSuccs =========================
3019 // Iterator over successor edges in the dependence graph.
3020 
3021 //------------------------------DepSuccs---------------------------
3022 DepSuccs::DepSuccs(Node* n, DepGraph& dg) {
3023   _n = n;
3024   _done = false;
3025   if (_n->is_Load()) {
3026     _next_idx = 0;
3027     _end_idx  = _n->outcnt();
3028     _dep_next = dg.dep(_n)->out_head();
3029   } else if (_n->is_Mem() || _n->is_Phi() && _n->bottom_type() == Type::MEMORY) {
3030     _next_idx = 0;
3031     _end_idx  = 0;
3032     _dep_next = dg.dep(_n)->out_head();
3033   } else {
3034     _next_idx = 0;
3035     _end_idx  = _n->outcnt();
3036     _dep_next = NULL;
3037   }
3038   next();
3039 }
3040 
3041 //-------------------------------next---------------------------
3042 void DepSuccs::next() {
3043   if (_dep_next != NULL) {
3044     _current  = _dep_next->succ()->node();
3045     _dep_next = _dep_next->next_out();
3046   } else if (_next_idx < _end_idx) {
3047     _current  = _n->raw_out(_next_idx++);
3048   } else {
3049     _done = true;
3050   }
3051 }
3052 
3053 //
3054 // --------------------------------- vectorization/simd -----------------------------------
3055 //
3056 Node*  SuperWord::find_phi_for_mem_dep(LoadNode* ld) {
3057   assert(in_bb(ld), "must be in block");
3058   if (_clone_map.gen(ld->_idx) == _ii_first) {
3059 #ifndef PRODUCT
3060     if (_vector_loop_debug) {
3061       tty->print_cr("SuperWord::find_phi_for_mem_dep _clone_map.gen(ld->_idx)=%d",
3062                     _clone_map.gen(ld->_idx));
3063     }
3064 #endif
3065     return NULL; //we think that any ld in the first gen being vectorizable
3066   }
3067 
3068   Node* mem = ld->in(MemNode::Memory);
3069   if (mem->outcnt() <= 1) {
3070     // we don't want to remove the only edge from mem node to load
3071 #ifndef PRODUCT
3072     if (_vector_loop_debug) {
3073       tty->print_cr("SuperWord::find_phi_for_mem_dep input node %d to load %d has no other outputs and edge mem->load cannot be removed",
3074                     mem->_idx, ld->_idx);
3075       ld->dump();
3076       mem->dump();
3077     }
3078 #endif
3079     return NULL;
3080   }
3081   if (!in_bb(mem) || _clone_map.gen(mem->_idx) == _clone_map.gen(ld->_idx)) {
3082 #ifndef PRODUCT
3083     if (_vector_loop_debug) {
3084       tty->print_cr("SuperWord::find_phi_for_mem_dep _clone_map.gen(mem->_idx)=%d",
3085                     _clone_map.gen(mem->_idx));
3086     }
3087 #endif
3088     return NULL; // does not depend on loop volatile node or depends on the same generation
3089   }
3090 
3091   //otherwise first node should depend on mem-phi
3092   Node* first = first_node(ld);
3093   assert(first->is_Load(), "must be Load");
3094   Node* phi = first->as_Load()->in(MemNode::Memory);
3095   if (!phi->is_Phi() || phi->bottom_type() != Type::MEMORY) {
3096 #ifndef PRODUCT
3097     if (_vector_loop_debug) {
3098       tty->print_cr("SuperWord::find_phi_for_mem_dep load is not vectorizable node, since it's `first` does not take input from mem phi");
3099       ld->dump();
3100       first->dump();
3101     }
3102 #endif
3103     return NULL;
3104   }
3105 
3106   Node* tail = 0;
3107   for (int m = 0; m < _mem_slice_head.length(); m++) {
3108     if (_mem_slice_head.at(m) == phi) {
3109       tail = _mem_slice_tail.at(m);
3110     }
3111   }
3112   if (tail == 0) { //test that found phi is in the list  _mem_slice_head
3113 #ifndef PRODUCT
3114     if (_vector_loop_debug) {
3115       tty->print_cr("SuperWord::find_phi_for_mem_dep load %d is not vectorizable node, its phi %d is not _mem_slice_head",
3116                     ld->_idx, phi->_idx);
3117       ld->dump();
3118       phi->dump();
3119     }
3120 #endif
3121     return NULL;
3122   }
3123 
3124   // now all conditions are met
3125   return phi;
3126 }
3127 
3128 Node* SuperWord::first_node(Node* nd) {
3129   for (int ii = 0; ii < _iteration_first.length(); ii++) {
3130     Node* nnn = _iteration_first.at(ii);
3131     if (_clone_map.idx(nnn->_idx) == _clone_map.idx(nd->_idx)) {
3132 #ifndef PRODUCT
3133       if (_vector_loop_debug) {
3134         tty->print_cr("SuperWord::first_node: %d is the first iteration node for %d (_clone_map.idx(nnn->_idx) = %d)",
3135                       nnn->_idx, nd->_idx, _clone_map.idx(nnn->_idx));
3136       }
3137 #endif
3138       return nnn;
3139     }
3140   }
3141 
3142 #ifndef PRODUCT
3143   if (_vector_loop_debug) {
3144     tty->print_cr("SuperWord::first_node: did not find first iteration node for %d (_clone_map.idx(nd->_idx)=%d)",
3145                   nd->_idx, _clone_map.idx(nd->_idx));
3146   }
3147 #endif
3148   return 0;
3149 }
3150 
3151 Node* SuperWord::last_node(Node* nd) {
3152   for (int ii = 0; ii < _iteration_last.length(); ii++) {
3153     Node* nnn = _iteration_last.at(ii);
3154     if (_clone_map.idx(nnn->_idx) == _clone_map.idx(nd->_idx)) {
3155 #ifndef PRODUCT
3156       if (_vector_loop_debug) {
3157         tty->print_cr("SuperWord::last_node _clone_map.idx(nnn->_idx)=%d, _clone_map.idx(nd->_idx)=%d",
3158                       _clone_map.idx(nnn->_idx), _clone_map.idx(nd->_idx));
3159       }
3160 #endif
3161       return nnn;
3162     }
3163   }
3164   return 0;
3165 }
3166 
3167 int SuperWord::mark_generations() {
3168   Node *ii_err = 0, *tail_err;
3169   for (int i = 0; i < _mem_slice_head.length(); i++) {
3170     Node* phi  = _mem_slice_head.at(i);
3171     assert(phi->is_Phi(), "must be phi");
3172 
3173     Node* tail = _mem_slice_tail.at(i);
3174     if (_ii_last == -1) {
3175       tail_err = tail;
3176       _ii_last = _clone_map.gen(tail->_idx);
3177     }
3178     else if (_ii_last != _clone_map.gen(tail->_idx)) {
3179 #ifndef PRODUCT
3180       if (TraceSuperWord && Verbose) {
3181         tty->print_cr("SuperWord::mark_generations _ii_last error - found different generations in two tail nodes ");
3182         tail->dump();
3183         tail_err->dump();
3184       }
3185 #endif
3186       return -1;
3187     }
3188 
3189     // find first iteration in the loop
3190     for (DUIterator_Fast imax, i = phi->fast_outs(imax); i < imax; i++) {
3191       Node* ii = phi->fast_out(i);
3192       if (in_bb(ii) && ii->is_Store()) { // we speculate that normally Stores of one and one only generation have deps from mem phi
3193         if (_ii_first == -1) {
3194           ii_err = ii;
3195           _ii_first = _clone_map.gen(ii->_idx);
3196         } else if (_ii_first != _clone_map.gen(ii->_idx)) {
3197 #ifndef PRODUCT
3198           if (TraceSuperWord && Verbose) {
3199             tty->print_cr("SuperWord::mark_generations _ii_first error - found different generations in two nodes ");
3200             ii->dump();
3201             ii_err->dump();
3202           }
3203 #endif
3204           return -1; // this phi has Stores from different generations of unroll and cannot be simd/vectorized
3205         }
3206       }
3207     }//for (DUIterator_Fast imax,
3208   }//for (int i...
3209 
3210   if (_ii_first == -1 || _ii_last == -1) {
3211 #ifndef PRODUCT
3212     if (TraceSuperWord && Verbose) {
3213       tty->print_cr("SuperWord::mark_generations unknown error, something vent wrong");
3214     }
3215 #endif
3216     return -1; // something vent wrong
3217   }
3218   // collect nodes in the first and last generations
3219   assert(_iteration_first.length() == 0, "_iteration_first must be empty");
3220   assert(_iteration_last.length() == 0, "_iteration_last must be empty");
3221   for (int j = 0; j < _block.length(); j++) {
3222     Node* n = _block.at(j);
3223     node_idx_t gen = _clone_map.gen(n->_idx);
3224     if ((signed)gen == _ii_first) {
3225       _iteration_first.push(n);
3226     } else if ((signed)gen == _ii_last) {
3227       _iteration_last.push(n);
3228     }
3229   }
3230 
3231   // building order of iterations
3232   assert(_ii_order.length() == 0, "should be empty");
3233   if (ii_err != 0) {
3234     assert(in_bb(ii_err) && ii_err->is_Store(), "should be Store in bb");
3235     Node* nd = ii_err;
3236     while(_clone_map.gen(nd->_idx) != _ii_last) {
3237       _ii_order.push(_clone_map.gen(nd->_idx));
3238       bool found = false;
3239       for (DUIterator_Fast imax, i = nd->fast_outs(imax); i < imax; i++) {
3240         Node* use = nd->fast_out(i);
3241         if (_clone_map.idx(use->_idx) == _clone_map.idx(nd->_idx) && use->as_Store()->in(MemNode::Memory) == nd) {
3242           found = true;
3243           nd = use;
3244           break;
3245         }
3246       }//for
3247 
3248       if (found == false) {
3249 #ifndef PRODUCT
3250         if (TraceSuperWord && Verbose) {
3251           tty->print_cr("SuperWord::mark_generations: Cannot build order of iterations - no dependent Store for %d", nd->_idx);
3252         }
3253 #endif
3254         _ii_order.clear();
3255         return -1;
3256       }
3257     } //while
3258     _ii_order.push(_clone_map.gen(nd->_idx));
3259   }
3260 
3261 #ifndef PRODUCT
3262   if (_vector_loop_debug) {
3263     tty->print_cr("SuperWord::mark_generations");
3264     tty->print_cr("First generation (%d) nodes:", _ii_first);
3265     for (int ii = 0; ii < _iteration_first.length(); ii++)  _iteration_first.at(ii)->dump();
3266     tty->print_cr("Last generation (%d) nodes:", _ii_last);
3267     for (int ii = 0; ii < _iteration_last.length(); ii++)  _iteration_last.at(ii)->dump();
3268     tty->print_cr(" ");
3269 
3270     tty->print("SuperWord::List of generations: ");
3271     for (int jj = 0; jj < _ii_order.length(); ++jj) {
3272       tty->print("%d:%d ", jj, _ii_order.at(jj));
3273     }
3274     tty->print_cr(" ");
3275   }
3276 #endif
3277 
3278   return _ii_first;
3279 }
3280 
3281 bool SuperWord::fix_commutative_inputs(Node* gold, Node* fix) {
3282   assert(gold->is_Add() && fix->is_Add() || gold->is_Mul() && fix->is_Mul(), "should be only Add or Mul nodes");
3283   assert(_clone_map.idx(gold->_idx) == _clone_map.idx(fix->_idx), "should be clones of the same node");
3284   Node* gin1 = gold->in(1);
3285   Node* gin2 = gold->in(2);
3286   Node* fin1 = fix->in(1);
3287   Node* fin2 = fix->in(2);
3288   bool swapped = false;
3289 
3290   if (in_bb(gin1) && in_bb(gin2) && in_bb(fin1) && in_bb(fin1)) {
3291     if (_clone_map.idx(gin1->_idx) == _clone_map.idx(fin1->_idx) &&
3292         _clone_map.idx(gin2->_idx) == _clone_map.idx(fin2->_idx)) {
3293       return true; // nothing to fix
3294     }
3295     if (_clone_map.idx(gin1->_idx) == _clone_map.idx(fin2->_idx) &&
3296         _clone_map.idx(gin2->_idx) == _clone_map.idx(fin1->_idx)) {
3297       fix->swap_edges(1, 2);
3298       swapped = true;
3299     }
3300   }
3301   // at least one input comes from outside of bb
3302   if (gin1->_idx == fin1->_idx)  {
3303     return true; // nothing to fix
3304   }
3305   if (!swapped && (gin1->_idx == fin2->_idx || gin2->_idx == fin1->_idx))  { //swapping is expensive, check condition first
3306     fix->swap_edges(1, 2);
3307     swapped = true;
3308   }
3309 
3310   if (swapped) {
3311 #ifndef PRODUCT
3312     if (_vector_loop_debug) {
3313       tty->print_cr("SuperWord::fix_commutative_inputs: fixed node %d", fix->_idx);
3314     }
3315 #endif
3316     return true;
3317   }
3318 
3319 #ifndef PRODUCT
3320   if (TraceSuperWord && Verbose) {
3321     tty->print_cr("SuperWord::fix_commutative_inputs: cannot fix node %d", fix->_idx);
3322   }
3323 #endif
3324   return false;
3325 }
3326 
3327 bool SuperWord::pack_parallel() {
3328 #ifndef PRODUCT
3329   if (_vector_loop_debug) {
3330     tty->print_cr("SuperWord::pack_parallel: START");
3331   }
3332 #endif
3333 
3334   _packset.clear();
3335 
3336   for (int ii = 0; ii < _iteration_first.length(); ii++) {
3337     Node* nd = _iteration_first.at(ii);
3338     if (in_bb(nd) && (nd->is_Load() || nd->is_Store() || nd->is_Add() || nd->is_Mul())) {
3339       Node_List* pk = new Node_List();
3340       pk->push(nd);
3341       for (int gen = 1; gen < _ii_order.length(); ++gen) {
3342         for (int kk = 0; kk < _block.length(); kk++) {
3343           Node* clone = _block.at(kk);
3344           if (_clone_map.idx(clone->_idx) == _clone_map.idx(nd->_idx) &&
3345               _clone_map.gen(clone->_idx) == _ii_order.at(gen)) {
3346             if (nd->is_Add() || nd->is_Mul()) {
3347               fix_commutative_inputs(nd, clone);
3348             }
3349             pk->push(clone);
3350             if (pk->size() == 4) {
3351               _packset.append(pk);
3352 #ifndef PRODUCT
3353               if (_vector_loop_debug) {
3354                 tty->print_cr("SuperWord::pack_parallel: added pack ");
3355                 pk->dump();
3356               }
3357 #endif
3358               if (_clone_map.gen(clone->_idx) != _ii_last) {
3359                 pk = new Node_List();
3360               }
3361             }
3362             break;
3363           }
3364         }
3365       }//for
3366     }//if
3367   }//for
3368 
3369 #ifndef PRODUCT
3370   if (_vector_loop_debug) {
3371     tty->print_cr("SuperWord::pack_parallel: END");
3372   }
3373 #endif
3374 
3375   return true;
3376 }
3377 
3378 bool SuperWord::hoist_loads_in_graph() {
3379   GrowableArray<Node*> loads;
3380 
3381 #ifndef PRODUCT
3382   if (_vector_loop_debug) {
3383     tty->print_cr("SuperWord::hoist_loads_in_graph: total number _mem_slice_head.length() = %d", _mem_slice_head.length());
3384   }
3385 #endif
3386 
3387   for (int i = 0; i < _mem_slice_head.length(); i++) {
3388     Node* n = _mem_slice_head.at(i);
3389     if ( !in_bb(n) || !n->is_Phi() || n->bottom_type() != Type::MEMORY) {
3390 #ifndef PRODUCT
3391       if (TraceSuperWord && Verbose) {
3392         tty->print_cr("SuperWord::hoist_loads_in_graph: skipping unexpected node n=%d", n->_idx);
3393       }
3394 #endif
3395       continue;
3396     }
3397 
3398 #ifndef PRODUCT
3399     if (_vector_loop_debug) {
3400       tty->print_cr("SuperWord::hoist_loads_in_graph: processing phi %d  = _mem_slice_head.at(%d);", n->_idx, i);
3401     }
3402 #endif
3403 
3404     for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
3405       Node* ld = n->fast_out(i);
3406       if (ld->is_Load() && ld->as_Load()->in(MemNode::Memory) == n && in_bb(ld)) {
3407         for (int i = 0; i < _block.length(); i++) {
3408           Node* ld2 = _block.at(i);
3409           if (ld2->is_Load() &&
3410               _clone_map.idx(ld->_idx) == _clone_map.idx(ld2->_idx) &&
3411               _clone_map.gen(ld->_idx) != _clone_map.gen(ld2->_idx)) { // <= do not collect the first generation ld
3412 #ifndef PRODUCT
3413             if (_vector_loop_debug) {
3414               tty->print_cr("SuperWord::hoist_loads_in_graph: will try to hoist load ld2->_idx=%d, cloned from %d (ld->_idx=%d)",
3415                             ld2->_idx, _clone_map.idx(ld->_idx), ld->_idx);
3416             }
3417 #endif
3418             // could not do on-the-fly, since iterator is immutable
3419             loads.push(ld2);
3420           }
3421         }// for
3422       }//if
3423     }//for (DUIterator_Fast imax,
3424   }//for (int i = 0; i
3425 
3426   for (int i = 0; i < loads.length(); i++) {
3427     LoadNode* ld = loads.at(i)->as_Load();
3428     Node* phi = find_phi_for_mem_dep(ld);
3429     if (phi != NULL) {
3430 #ifndef PRODUCT
3431       if (_vector_loop_debug) {
3432         tty->print_cr("SuperWord::hoist_loads_in_graph replacing MemNode::Memory(%d) edge in %d with one from %d",
3433                       MemNode::Memory, ld->_idx, phi->_idx);
3434       }
3435 #endif
3436       _igvn.replace_input_of(ld, MemNode::Memory, phi);
3437     }
3438   }//for
3439 
3440   restart(); // invalidate all basic structures, since we rebuilt the graph
3441 
3442 #ifndef PRODUCT
3443   if (TraceSuperWord && Verbose) {
3444     tty->print_cr("\nSuperWord::hoist_loads_in_graph() the graph was rebuilt, all structures invalidated and need rebuild");
3445   }
3446 #endif
3447   return true;
3448 }
3449