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