1 /*
   2  * Copyright (c) 2007, 2020, 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 "memory/resourceArea.hpp"
  29 #include "opto/addnode.hpp"
  30 #include "opto/callnode.hpp"
  31 #include "opto/castnode.hpp"
  32 #include "opto/convertnode.hpp"
  33 #include "opto/divnode.hpp"
  34 #include "opto/matcher.hpp"
  35 #include "opto/memnode.hpp"
  36 #include "opto/mulnode.hpp"
  37 #include "opto/opcodes.hpp"
  38 #include "opto/opaquenode.hpp"
  39 #include "opto/superword.hpp"
  40 #include "opto/vectornode.hpp"
  41 #include "opto/movenode.hpp"
  42 #include "utilities/powerOfTwo.hpp"
  43 
  44 //
  45 //                  S U P E R W O R D   T R A N S F O R M
  46 //=============================================================================
  47 
  48 //------------------------------SuperWord---------------------------
  49 SuperWord::SuperWord(PhaseIdealLoop* phase) :
  50   _phase(phase),
  51   _arena(phase->C->comp_arena()),
  52   _igvn(phase->_igvn),
  53   _packset(arena(), 8,  0, NULL),         // packs for the current block
  54   _bb_idx(arena(), (int)(1.10 * phase->C->unique()), 0, 0), // node idx to index in bb
  55   _block(arena(), 8,  0, NULL),           // nodes in current block
  56   _post_block(arena(), 8, 0, NULL),       // nodes common to current block which are marked as post loop vectorizable
  57   _data_entry(arena(), 8,  0, NULL),      // nodes with all inputs from outside
  58   _mem_slice_head(arena(), 8,  0, NULL),  // memory slice heads
  59   _mem_slice_tail(arena(), 8,  0, NULL),  // memory slice tails
  60   _node_info(arena(), 8,  0, SWNodeInfo::initial), // info needed per node
  61   _clone_map(phase->C->clone_map()),      // map of nodes created in cloning
  62   _cmovev_kit(_arena, this),              // map to facilitate CMoveV creation
  63   _align_to_ref(NULL),                    // memory reference to align vectors to
  64   _disjoint_ptrs(arena(), 8,  0, OrderedPair::initial), // runtime disambiguated pointer pairs
  65   _dg(_arena),                            // dependence graph
  66   _visited(arena()),                      // visited node set
  67   _post_visited(arena()),                 // post visited node set
  68   _n_idx_list(arena(), 8),                // scratch list of (node,index) pairs
  69   _nlist(arena(), 8, 0, NULL),            // scratch list of nodes
  70   _stk(arena(), 8, 0, NULL),              // scratch stack of nodes
  71   _lpt(NULL),                             // loop tree node
  72   _lp(NULL),                              // LoopNode
  73   _bb(NULL),                              // basic block
  74   _iv(NULL),                              // induction var
  75   _race_possible(false),                  // cases where SDMU is true
  76   _early_return(true),                    // analysis evaluations routine
  77   _do_vector_loop(phase->C->do_vector_loop()),  // whether to do vectorization/simd style
  78   _do_reserve_copy(DoReserveCopyInSuperWord),
  79   _num_work_vecs(0),                      // amount of vector work we have
  80   _num_reductions(0),                     // amount of reduction work we have
  81   _ii_first(-1),                          // first loop generation index - only if do_vector_loop()
  82   _ii_last(-1),                           // last loop generation index - only if do_vector_loop()
  83   _ii_order(arena(), 8, 0, 0)
  84 {
  85 #ifndef PRODUCT
  86   _vector_loop_debug = 0;
  87   if (_phase->C->method() != NULL) {
  88     _vector_loop_debug = phase->C->directive()->VectorizeDebugOption;
  89   }
  90 
  91 #endif
  92 }
  93 
  94 //------------------------------transform_loop---------------------------
  95 void SuperWord::transform_loop(IdealLoopTree* lpt, bool do_optimization) {
  96   assert(UseSuperWord, "should be");
  97   // Do vectors exist on this architecture?
  98   if (Matcher::vector_width_in_bytes(T_BYTE) < 2) return;
  99 
 100   assert(lpt->_head->is_CountedLoop(), "must be");
 101   CountedLoopNode *cl = lpt->_head->as_CountedLoop();
 102 
 103   if (!cl->is_valid_counted_loop()) return; // skip malformed counted loop
 104 
 105   bool post_loop_allowed = (PostLoopMultiversioning && Matcher::has_predicated_vectors() && cl->is_post_loop());
 106   if (post_loop_allowed) {
 107     if (cl->is_reduction_loop()) return; // no predication mapping
 108     Node *limit = cl->limit();
 109     if (limit->is_Con()) return; // non constant limits only
 110     // Now check the limit for expressions we do not handle
 111     if (limit->is_Add()) {
 112       Node *in2 = limit->in(2);
 113       if (in2->is_Con()) {
 114         int val = in2->get_int();
 115         // should not try to program these cases
 116         if (val < 0) return;
 117       }
 118     }
 119   }
 120 
 121   // skip any loop that has not been assigned max unroll by analysis
 122   if (do_optimization) {
 123     if (SuperWordLoopUnrollAnalysis && cl->slp_max_unroll() == 0) return;
 124   }
 125 
 126   // Check for no control flow in body (other than exit)
 127   Node *cl_exit = cl->loopexit();
 128   if (cl->is_main_loop() && (cl_exit->in(0) != lpt->_head)) {
 129     #ifndef PRODUCT
 130       if (TraceSuperWord) {
 131         tty->print_cr("SuperWord::transform_loop: loop too complicated, cl_exit->in(0) != lpt->_head");
 132         tty->print("cl_exit %d", cl_exit->_idx); cl_exit->dump();
 133         tty->print("cl_exit->in(0) %d", cl_exit->in(0)->_idx); cl_exit->in(0)->dump();
 134         tty->print("lpt->_head %d", lpt->_head->_idx); lpt->_head->dump();
 135         lpt->dump_head();
 136       }
 137     #endif
 138     return;
 139   }
 140 
 141   // Make sure the are no extra control users of the loop backedge
 142   if (cl->back_control()->outcnt() != 1) {
 143     return;
 144   }
 145 
 146   // Skip any loops already optimized by slp
 147   if (cl->is_vectorized_loop()) return;
 148 
 149   if (cl->is_unroll_only()) return;
 150 
 151   if (cl->is_main_loop()) {
 152     // Check for pre-loop ending with CountedLoopEnd(Bool(Cmp(x,Opaque1(limit))))
 153     CountedLoopEndNode* pre_end = get_pre_loop_end(cl);
 154     if (pre_end == NULL) return;
 155     Node *pre_opaq1 = pre_end->limit();
 156     if (pre_opaq1->Opcode() != Op_Opaque1) return;
 157   }
 158 
 159   init(); // initialize data structures
 160 
 161   set_lpt(lpt);
 162   set_lp(cl);
 163 
 164   // For now, define one block which is the entire loop body
 165   set_bb(cl);
 166 
 167   if (do_optimization) {
 168     assert(_packset.length() == 0, "packset must be empty");
 169     SLP_extract();
 170     if (PostLoopMultiversioning && Matcher::has_predicated_vectors()) {
 171       if (cl->is_vectorized_loop() && cl->is_main_loop() && !cl->is_reduction_loop()) {
 172         IdealLoopTree *lpt_next = lpt->_next;
 173         CountedLoopNode *cl_next = lpt_next->_head->as_CountedLoop();
 174         _phase->has_range_checks(lpt_next);
 175         if (cl_next->is_post_loop() && !cl_next->range_checks_present()) {
 176           if (!cl_next->is_vectorized_loop()) {
 177             int slp_max_unroll_factor = cl->slp_max_unroll();
 178             cl_next->set_slp_max_unroll(slp_max_unroll_factor);
 179           }
 180         }
 181       }
 182     }
 183   }
 184 }
 185 
 186 //------------------------------early unrolling analysis------------------------------
 187 void SuperWord::unrolling_analysis(int &local_loop_unroll_factor) {
 188   bool is_slp = true;
 189   ResourceMark rm;
 190   size_t ignored_size = lpt()->_body.size();
 191   int *ignored_loop_nodes = NEW_RESOURCE_ARRAY(int, ignored_size);
 192   Node_Stack nstack((int)ignored_size);
 193   CountedLoopNode *cl = lpt()->_head->as_CountedLoop();
 194   Node *cl_exit = cl->loopexit_or_null();
 195   int rpo_idx = _post_block.length();
 196 
 197   assert(rpo_idx == 0, "post loop block is empty");
 198 
 199   // First clear the entries
 200   for (uint i = 0; i < lpt()->_body.size(); i++) {
 201     ignored_loop_nodes[i] = -1;
 202   }
 203 
 204   int max_vector = Matcher::max_vector_size(T_BYTE);
 205   bool post_loop_allowed = (PostLoopMultiversioning && Matcher::has_predicated_vectors() && cl->is_post_loop());
 206 
 207   // Process the loop, some/all of the stack entries will not be in order, ergo
 208   // need to preprocess the ignored initial state before we process the loop
 209   for (uint i = 0; i < lpt()->_body.size(); i++) {
 210     Node* n = lpt()->_body.at(i);
 211     if (n == cl->incr() ||
 212       n->is_reduction() ||
 213       n->is_AddP() ||
 214       n->is_Cmp() ||
 215       n->is_IfTrue() ||
 216       n->is_CountedLoop() ||
 217       (n == cl_exit)) {
 218       ignored_loop_nodes[i] = n->_idx;
 219       continue;
 220     }
 221 
 222     if (n->is_If()) {
 223       IfNode *iff = n->as_If();
 224       if (iff->_fcnt != COUNT_UNKNOWN && iff->_prob != PROB_UNKNOWN) {
 225         if (lpt()->is_loop_exit(iff)) {
 226           ignored_loop_nodes[i] = n->_idx;
 227           continue;
 228         }
 229       }
 230     }
 231 
 232     if (n->is_Phi() && (n->bottom_type() == Type::MEMORY)) {
 233       Node* n_tail = n->in(LoopNode::LoopBackControl);
 234       if (n_tail != n->in(LoopNode::EntryControl)) {
 235         if (!n_tail->is_Mem()) {
 236           is_slp = false;
 237           break;
 238         }
 239       }
 240     }
 241 
 242     // This must happen after check of phi/if
 243     if (n->is_Phi() || n->is_If()) {
 244       ignored_loop_nodes[i] = n->_idx;
 245       continue;
 246     }
 247 
 248     if (n->is_LoadStore() || n->is_MergeMem() ||
 249       (n->is_Proj() && !n->as_Proj()->is_CFG())) {
 250       is_slp = false;
 251       break;
 252     }
 253 
 254     // Ignore nodes with non-primitive type.
 255     BasicType bt;
 256     if (n->is_Mem()) {
 257       bt = n->as_Mem()->memory_type();
 258     } else {
 259       bt = n->bottom_type()->basic_type();
 260     }
 261     if (is_java_primitive(bt) == false) {
 262       ignored_loop_nodes[i] = n->_idx;
 263       continue;
 264     }
 265 
 266     if (n->is_Mem()) {
 267       MemNode* current = n->as_Mem();
 268       Node* adr = n->in(MemNode::Address);
 269       Node* n_ctrl = _phase->get_ctrl(adr);
 270 
 271       // save a queue of post process nodes
 272       if (n_ctrl != NULL && lpt()->is_member(_phase->get_loop(n_ctrl))) {
 273         // Process the memory expression
 274         int stack_idx = 0;
 275         bool have_side_effects = true;
 276         if (adr->is_AddP() == false) {
 277           nstack.push(adr, stack_idx++);
 278         } else {
 279           // Mark the components of the memory operation in nstack
 280           SWPointer p1(current, this, &nstack, true);
 281           have_side_effects = p1.node_stack()->is_nonempty();
 282         }
 283 
 284         // Process the pointer stack
 285         while (have_side_effects) {
 286           Node* pointer_node = nstack.node();
 287           for (uint j = 0; j < lpt()->_body.size(); j++) {
 288             Node* cur_node = lpt()->_body.at(j);
 289             if (cur_node == pointer_node) {
 290               ignored_loop_nodes[j] = cur_node->_idx;
 291               break;
 292             }
 293           }
 294           nstack.pop();
 295           have_side_effects = nstack.is_nonempty();
 296         }
 297       }
 298     }
 299   }
 300 
 301   if (is_slp) {
 302     // Now we try to find the maximum supported consistent vector which the machine
 303     // description can use
 304     bool small_basic_type = false;
 305     bool flag_small_bt = false;
 306     for (uint i = 0; i < lpt()->_body.size(); i++) {
 307       if (ignored_loop_nodes[i] != -1) continue;
 308 
 309       BasicType bt;
 310       Node* n = lpt()->_body.at(i);
 311       if (n->is_Mem()) {
 312         bt = n->as_Mem()->memory_type();
 313       } else {
 314         bt = n->bottom_type()->basic_type();
 315       }
 316 
 317       if (post_loop_allowed) {
 318         if (!small_basic_type) {
 319           switch (bt) {
 320           case T_CHAR:
 321           case T_BYTE:
 322           case T_SHORT:
 323             small_basic_type = true;
 324             break;
 325 
 326           case T_LONG:
 327             // TODO: Remove when support completed for mask context with LONG.
 328             //       Support needs to be augmented for logical qword operations, currently we map to dword
 329             //       buckets for vectors on logicals as these were legacy.
 330             small_basic_type = true;
 331             break;
 332 
 333           default:
 334             break;
 335           }
 336         }
 337       }
 338 
 339       if (is_java_primitive(bt) == false) continue;
 340 
 341          int cur_max_vector = Matcher::max_vector_size(bt);
 342 
 343       // If a max vector exists which is not larger than _local_loop_unroll_factor
 344       // stop looking, we already have the max vector to map to.
 345       if (cur_max_vector < local_loop_unroll_factor) {
 346         is_slp = false;
 347         if (TraceSuperWordLoopUnrollAnalysis) {
 348           tty->print_cr("slp analysis fails: unroll limit greater than max vector\n");
 349         }
 350         break;
 351       }
 352 
 353       // Map the maximal common vector
 354       if (VectorNode::implemented(n->Opcode(), cur_max_vector, bt)) {
 355         if (cur_max_vector < max_vector && !flag_small_bt) {
 356           max_vector = cur_max_vector;
 357         } else if (cur_max_vector > max_vector && UseSubwordForMaxVector) {
 358           // Analyse subword in the loop to set maximum vector size to take advantage of full vector width for subword types.
 359           // Here we analyze if narrowing is likely to happen and if it is we set vector size more aggressively.
 360           // We check for possibility of narrowing by looking through chain operations using subword types.
 361           if (is_subword_type(bt)) {
 362             uint start, end;
 363             VectorNode::vector_operands(n, &start, &end);
 364 
 365             for (uint j = start; j < end; j++) {
 366               Node* in = n->in(j);
 367               // Don't propagate through a memory
 368               if (!in->is_Mem() && in_bb(in) && in->bottom_type()->basic_type() == T_INT) {
 369                 bool same_type = true;
 370                 for (DUIterator_Fast kmax, k = in->fast_outs(kmax); k < kmax; k++) {
 371                   Node *use = in->fast_out(k);
 372                   if (!in_bb(use) && use->bottom_type()->basic_type() != bt) {
 373                     same_type = false;
 374                     break;
 375                   }
 376                 }
 377                 if (same_type) {
 378                   max_vector = cur_max_vector;
 379                   flag_small_bt = true;
 380                   cl->mark_subword_loop();
 381                 }
 382               }
 383             }
 384           }
 385         }
 386         // We only process post loops on predicated targets where we want to
 387         // mask map the loop to a single iteration
 388         if (post_loop_allowed) {
 389           _post_block.at_put_grow(rpo_idx++, n);
 390         }
 391       }
 392     }
 393     if (is_slp) {
 394       local_loop_unroll_factor = max_vector;
 395       cl->mark_passed_slp();
 396     }
 397     cl->mark_was_slp();
 398     if (cl->is_main_loop()) {
 399       cl->set_slp_max_unroll(local_loop_unroll_factor);
 400     } else if (post_loop_allowed) {
 401       if (!small_basic_type) {
 402         // avoid replication context for small basic types in programmable masked loops
 403         cl->set_slp_max_unroll(local_loop_unroll_factor);
 404       }
 405     }
 406   }
 407 }
 408 
 409 //------------------------------SLP_extract---------------------------
 410 // Extract the superword level parallelism
 411 //
 412 // 1) A reverse post-order of nodes in the block is constructed.  By scanning
 413 //    this list from first to last, all definitions are visited before their uses.
 414 //
 415 // 2) A point-to-point dependence graph is constructed between memory references.
 416 //    This simplies the upcoming "independence" checker.
 417 //
 418 // 3) The maximum depth in the node graph from the beginning of the block
 419 //    to each node is computed.  This is used to prune the graph search
 420 //    in the independence checker.
 421 //
 422 // 4) For integer types, the necessary bit width is propagated backwards
 423 //    from stores to allow packed operations on byte, char, and short
 424 //    integers.  This reverses the promotion to type "int" that javac
 425 //    did for operations like: char c1,c2,c3;  c1 = c2 + c3.
 426 //
 427 // 5) One of the memory references is picked to be an aligned vector reference.
 428 //    The pre-loop trip count is adjusted to align this reference in the
 429 //    unrolled body.
 430 //
 431 // 6) The initial set of pack pairs is seeded with memory references.
 432 //
 433 // 7) The set of pack pairs is extended by following use->def and def->use links.
 434 //
 435 // 8) The pairs are combined into vector sized packs.
 436 //
 437 // 9) Reorder the memory slices to co-locate members of the memory packs.
 438 //
 439 // 10) Generate ideal vector nodes for the final set of packs and where necessary,
 440 //    inserting scalar promotion, vector creation from multiple scalars, and
 441 //    extraction of scalar values from vectors.
 442 //
 443 void SuperWord::SLP_extract() {
 444 
 445 #ifndef PRODUCT
 446   if (_do_vector_loop && TraceSuperWord) {
 447     tty->print("SuperWord::SLP_extract\n");
 448     tty->print("input loop\n");
 449     _lpt->dump_head();
 450     _lpt->dump();
 451     for (uint i = 0; i < _lpt->_body.size(); i++) {
 452       _lpt->_body.at(i)->dump();
 453     }
 454   }
 455 #endif
 456   // Ready the block
 457   if (!construct_bb()) {
 458     return; // Exit if no interesting nodes or complex graph.
 459   }
 460 
 461   // build    _dg, _disjoint_ptrs
 462   dependence_graph();
 463 
 464   // compute function depth(Node*)
 465   compute_max_depth();
 466 
 467   CountedLoopNode *cl = lpt()->_head->as_CountedLoop();
 468   bool post_loop_allowed = (PostLoopMultiversioning && Matcher::has_predicated_vectors() && cl->is_post_loop());
 469   if (cl->is_main_loop()) {
 470     if (_do_vector_loop) {
 471       if (mark_generations() != -1) {
 472         hoist_loads_in_graph(); // this only rebuild the graph; all basic structs need rebuild explicitly
 473 
 474         if (!construct_bb()) {
 475           return; // Exit if no interesting nodes or complex graph.
 476         }
 477         dependence_graph();
 478         compute_max_depth();
 479       }
 480 
 481 #ifndef PRODUCT
 482       if (TraceSuperWord) {
 483         tty->print_cr("\nSuperWord::_do_vector_loop: graph after hoist_loads_in_graph");
 484         _lpt->dump_head();
 485         for (int j = 0; j < _block.length(); j++) {
 486           Node* n = _block.at(j);
 487           int d = depth(n);
 488           for (int i = 0; i < d; i++) tty->print("%s", "  ");
 489           tty->print("%d :", d);
 490           n->dump();
 491         }
 492       }
 493 #endif
 494     }
 495 
 496     compute_vector_element_type();
 497 
 498     // Attempt vectorization
 499 
 500     find_adjacent_refs();
 501 
 502     if (align_to_ref() == NULL) {
 503       return; // Did not find memory reference to align vectors
 504     }
 505 
 506     extend_packlist();
 507 
 508     if (_do_vector_loop) {
 509       if (_packset.length() == 0) {
 510         if (TraceSuperWord) {
 511           tty->print_cr("\nSuperWord::_do_vector_loop DFA could not build packset, now trying to build anyway");
 512         }
 513         pack_parallel();
 514       }
 515     }
 516 
 517     combine_packs();
 518 
 519     construct_my_pack_map();
 520     if (UseVectorCmov) {
 521       merge_packs_to_cmovd();
 522     }
 523 
 524     filter_packs();
 525 
 526     schedule();
 527   } else if (post_loop_allowed) {
 528     int saved_mapped_unroll_factor = cl->slp_max_unroll();
 529     if (saved_mapped_unroll_factor) {
 530       int vector_mapped_unroll_factor = saved_mapped_unroll_factor;
 531 
 532       // now reset the slp_unroll_factor so that we can check the analysis mapped
 533       // what the vector loop was mapped to
 534       cl->set_slp_max_unroll(0);
 535 
 536       // do the analysis on the post loop
 537       unrolling_analysis(vector_mapped_unroll_factor);
 538 
 539       // if our analyzed loop is a canonical fit, start processing it
 540       if (vector_mapped_unroll_factor == saved_mapped_unroll_factor) {
 541         // now add the vector nodes to packsets
 542         for (int i = 0; i < _post_block.length(); i++) {
 543           Node* n = _post_block.at(i);
 544           Node_List* singleton = new Node_List();
 545           singleton->push(n);
 546           _packset.append(singleton);
 547           set_my_pack(n, singleton);
 548         }
 549 
 550         // map base types for vector usage
 551         compute_vector_element_type();
 552       } else {
 553         return;
 554       }
 555     } else {
 556       // for some reason we could not map the slp analysis state of the vectorized loop
 557       return;
 558     }
 559   }
 560 
 561   output();
 562 }
 563 
 564 //------------------------------find_adjacent_refs---------------------------
 565 // Find the adjacent memory references and create pack pairs for them.
 566 // This is the initial set of packs that will then be extended by
 567 // following use->def and def->use links.  The align positions are
 568 // assigned relative to the reference "align_to_ref"
 569 void SuperWord::find_adjacent_refs() {
 570   // Get list of memory operations
 571   Node_List memops;
 572   for (int i = 0; i < _block.length(); i++) {
 573     Node* n = _block.at(i);
 574     if (n->is_Mem() && !n->is_LoadStore() && in_bb(n) &&
 575         is_java_primitive(n->as_Mem()->memory_type())) {
 576       int align = memory_alignment(n->as_Mem(), 0);
 577       if (align != bottom_align) {
 578         memops.push(n);
 579       }
 580     }
 581   }
 582   if (TraceSuperWord) {
 583     tty->print_cr("\nfind_adjacent_refs found %d memops", memops.size());
 584   }
 585 
 586   Node_List align_to_refs;
 587   int max_idx;
 588   int best_iv_adjustment = 0;
 589   MemNode* best_align_to_mem_ref = NULL;
 590 
 591   while (memops.size() != 0) {
 592     // Find a memory reference to align to.
 593     MemNode* mem_ref = find_align_to_ref(memops, max_idx);
 594     if (mem_ref == NULL) break;
 595     align_to_refs.push(mem_ref);
 596     int iv_adjustment = get_iv_adjustment(mem_ref);
 597 
 598     if (best_align_to_mem_ref == NULL) {
 599       // Set memory reference which is the best from all memory operations
 600       // to be used for alignment. The pre-loop trip count is modified to align
 601       // this reference to a vector-aligned address.
 602       best_align_to_mem_ref = mem_ref;
 603       best_iv_adjustment = iv_adjustment;
 604       NOT_PRODUCT(find_adjacent_refs_trace_1(best_align_to_mem_ref, best_iv_adjustment);)
 605     }
 606 
 607     SWPointer align_to_ref_p(mem_ref, this, NULL, false);
 608     // Set alignment relative to "align_to_ref" for all related memory operations.
 609     for (int i = memops.size() - 1; i >= 0; i--) {
 610       MemNode* s = memops.at(i)->as_Mem();
 611       if (isomorphic(s, mem_ref) &&
 612            (!_do_vector_loop || same_origin_idx(s, mem_ref))) {
 613         SWPointer p2(s, this, NULL, false);
 614         if (p2.comparable(align_to_ref_p)) {
 615           int align = memory_alignment(s, iv_adjustment);
 616           set_alignment(s, align);
 617         }
 618       }
 619     }
 620 
 621     // Create initial pack pairs of memory operations for which
 622     // alignment is set and vectors will be aligned.
 623     bool create_pack = true;
 624     if (memory_alignment(mem_ref, best_iv_adjustment) == 0 || _do_vector_loop) {
 625       if (vectors_should_be_aligned()) {
 626         int vw = vector_width(mem_ref);
 627         int vw_best = vector_width(best_align_to_mem_ref);
 628         if (vw > vw_best) {
 629           // Do not vectorize a memory access with more elements per vector
 630           // if unaligned memory access is not allowed because number of
 631           // iterations in pre-loop will be not enough to align it.
 632           create_pack = false;
 633         } else {
 634           SWPointer p2(best_align_to_mem_ref, this, NULL, false);
 635           if (align_to_ref_p.invar() != p2.invar()) {
 636             // Do not vectorize memory accesses with different invariants
 637             // if unaligned memory accesses are not allowed.
 638             create_pack = false;
 639           }
 640         }
 641       }
 642     } else {
 643       if (same_velt_type(mem_ref, best_align_to_mem_ref)) {
 644         // Can't allow vectorization of unaligned memory accesses with the
 645         // same type since it could be overlapped accesses to the same array.
 646         create_pack = false;
 647       } else {
 648         // Allow independent (different type) unaligned memory operations
 649         // if HW supports them.
 650         if (vectors_should_be_aligned()) {
 651           create_pack = false;
 652         } else {
 653           // Check if packs of the same memory type but
 654           // with a different alignment were created before.
 655           for (uint i = 0; i < align_to_refs.size(); i++) {
 656             MemNode* mr = align_to_refs.at(i)->as_Mem();
 657             if (mr == mem_ref) {
 658               // Skip when we are looking at same memory operation.
 659               continue;
 660             }
 661             if (same_velt_type(mr, mem_ref) &&
 662                 memory_alignment(mr, iv_adjustment) != 0)
 663               create_pack = false;
 664           }
 665         }
 666       }
 667     }
 668     if (create_pack) {
 669       for (uint i = 0; i < memops.size(); i++) {
 670         Node* s1 = memops.at(i);
 671         int align = alignment(s1);
 672         if (align == top_align) continue;
 673         for (uint j = 0; j < memops.size(); j++) {
 674           Node* s2 = memops.at(j);
 675           if (alignment(s2) == top_align) continue;
 676           if (s1 != s2 && are_adjacent_refs(s1, s2)) {
 677             if (stmts_can_pack(s1, s2, align)) {
 678               Node_List* pair = new Node_List();
 679               pair->push(s1);
 680               pair->push(s2);
 681               if (!_do_vector_loop || same_origin_idx(s1, s2)) {
 682                 _packset.append(pair);
 683               }
 684             }
 685           }
 686         }
 687       }
 688     } else { // Don't create unaligned pack
 689       // First, remove remaining memory ops of the same type from the list.
 690       for (int i = memops.size() - 1; i >= 0; i--) {
 691         MemNode* s = memops.at(i)->as_Mem();
 692         if (same_velt_type(s, mem_ref)) {
 693           memops.remove(i);
 694         }
 695       }
 696 
 697       // Second, remove already constructed packs of the same type.
 698       for (int i = _packset.length() - 1; i >= 0; i--) {
 699         Node_List* p = _packset.at(i);
 700         MemNode* s = p->at(0)->as_Mem();
 701         if (same_velt_type(s, mem_ref)) {
 702           remove_pack_at(i);
 703         }
 704       }
 705 
 706       // If needed find the best memory reference for loop alignment again.
 707       if (same_velt_type(mem_ref, best_align_to_mem_ref)) {
 708         // Put memory ops from remaining packs back on memops list for
 709         // the best alignment search.
 710         uint orig_msize = memops.size();
 711         for (int i = 0; i < _packset.length(); i++) {
 712           Node_List* p = _packset.at(i);
 713           MemNode* s = p->at(0)->as_Mem();
 714           assert(!same_velt_type(s, mem_ref), "sanity");
 715           memops.push(s);
 716         }
 717         best_align_to_mem_ref = find_align_to_ref(memops, max_idx);
 718         if (best_align_to_mem_ref == NULL) {
 719           if (TraceSuperWord) {
 720             tty->print_cr("SuperWord::find_adjacent_refs(): best_align_to_mem_ref == NULL");
 721           }
 722           // best_align_to_mem_ref will be used for adjusting the pre-loop limit in
 723           // SuperWord::align_initial_loop_index. Find one with the biggest vector size,
 724           // smallest data size and smallest iv offset from memory ops from remaining packs.
 725           if (_packset.length() > 0) {
 726             if (orig_msize == 0) {
 727               best_align_to_mem_ref = memops.at(max_idx)->as_Mem();
 728             } else {
 729               for (uint i = 0; i < orig_msize; i++) {
 730                 memops.remove(0);
 731               }
 732               best_align_to_mem_ref = find_align_to_ref(memops, max_idx);
 733               assert(best_align_to_mem_ref == NULL, "sanity");
 734               best_align_to_mem_ref = memops.at(max_idx)->as_Mem();
 735             }
 736             assert(best_align_to_mem_ref != NULL, "sanity");
 737           }
 738           break;
 739         }
 740         best_iv_adjustment = get_iv_adjustment(best_align_to_mem_ref);
 741         NOT_PRODUCT(find_adjacent_refs_trace_1(best_align_to_mem_ref, best_iv_adjustment);)
 742         // Restore list.
 743         while (memops.size() > orig_msize)
 744           (void)memops.pop();
 745       }
 746     } // unaligned memory accesses
 747 
 748     // Remove used mem nodes.
 749     for (int i = memops.size() - 1; i >= 0; i--) {
 750       MemNode* m = memops.at(i)->as_Mem();
 751       if (alignment(m) != top_align) {
 752         memops.remove(i);
 753       }
 754     }
 755 
 756   } // while (memops.size() != 0
 757   set_align_to_ref(best_align_to_mem_ref);
 758 
 759   if (TraceSuperWord) {
 760     tty->print_cr("\nAfter find_adjacent_refs");
 761     print_packset();
 762   }
 763 }
 764 
 765 #ifndef PRODUCT
 766 void SuperWord::find_adjacent_refs_trace_1(Node* best_align_to_mem_ref, int best_iv_adjustment) {
 767   if (is_trace_adjacent()) {
 768     tty->print("SuperWord::find_adjacent_refs best_align_to_mem_ref = %d, best_iv_adjustment = %d",
 769        best_align_to_mem_ref->_idx, best_iv_adjustment);
 770        best_align_to_mem_ref->dump();
 771   }
 772 }
 773 #endif
 774 
 775 //------------------------------find_align_to_ref---------------------------
 776 // Find a memory reference to align the loop induction variable to.
 777 // Looks first at stores then at loads, looking for a memory reference
 778 // with the largest number of references similar to it.
 779 MemNode* SuperWord::find_align_to_ref(Node_List &memops, int &idx) {
 780   GrowableArray<int> cmp_ct(arena(), memops.size(), memops.size(), 0);
 781 
 782   // Count number of comparable memory ops
 783   for (uint i = 0; i < memops.size(); i++) {
 784     MemNode* s1 = memops.at(i)->as_Mem();
 785     SWPointer p1(s1, this, NULL, false);
 786     // Only discard unalignable memory references if vector memory references
 787     // should be aligned on this platform.
 788     if (vectors_should_be_aligned() && !ref_is_alignable(p1)) {
 789       *cmp_ct.adr_at(i) = 0;
 790       continue;
 791     }
 792     for (uint j = i+1; j < memops.size(); j++) {
 793       MemNode* s2 = memops.at(j)->as_Mem();
 794       if (isomorphic(s1, s2)) {
 795         SWPointer p2(s2, this, NULL, false);
 796         if (p1.comparable(p2)) {
 797           (*cmp_ct.adr_at(i))++;
 798           (*cmp_ct.adr_at(j))++;
 799         }
 800       }
 801     }
 802   }
 803 
 804   // Find Store (or Load) with the greatest number of "comparable" references,
 805   // biggest vector size, smallest data size and smallest iv offset.
 806   int max_ct        = 0;
 807   int max_vw        = 0;
 808   int max_idx       = -1;
 809   int min_size      = max_jint;
 810   int min_iv_offset = max_jint;
 811   for (uint j = 0; j < memops.size(); j++) {
 812     MemNode* s = memops.at(j)->as_Mem();
 813     if (s->is_Store()) {
 814       int vw = vector_width_in_bytes(s);
 815       assert(vw > 1, "sanity");
 816       SWPointer p(s, this, NULL, false);
 817       if ( cmp_ct.at(j) >  max_ct ||
 818           (cmp_ct.at(j) == max_ct &&
 819             ( vw >  max_vw ||
 820              (vw == max_vw &&
 821               ( data_size(s) <  min_size ||
 822                (data_size(s) == min_size &&
 823                 p.offset_in_bytes() < min_iv_offset)))))) {
 824         max_ct = cmp_ct.at(j);
 825         max_vw = vw;
 826         max_idx = j;
 827         min_size = data_size(s);
 828         min_iv_offset = p.offset_in_bytes();
 829       }
 830     }
 831   }
 832   // If no stores, look at loads
 833   if (max_ct == 0) {
 834     for (uint j = 0; j < memops.size(); j++) {
 835       MemNode* s = memops.at(j)->as_Mem();
 836       if (s->is_Load()) {
 837         int vw = vector_width_in_bytes(s);
 838         assert(vw > 1, "sanity");
 839         SWPointer p(s, this, NULL, false);
 840         if ( cmp_ct.at(j) >  max_ct ||
 841             (cmp_ct.at(j) == max_ct &&
 842               ( vw >  max_vw ||
 843                (vw == max_vw &&
 844                 ( data_size(s) <  min_size ||
 845                  (data_size(s) == min_size &&
 846                   p.offset_in_bytes() < min_iv_offset)))))) {
 847           max_ct = cmp_ct.at(j);
 848           max_vw = vw;
 849           max_idx = j;
 850           min_size = data_size(s);
 851           min_iv_offset = p.offset_in_bytes();
 852         }
 853       }
 854     }
 855   }
 856 
 857 #ifdef ASSERT
 858   if (TraceSuperWord && Verbose) {
 859     tty->print_cr("\nVector memops after find_align_to_ref");
 860     for (uint i = 0; i < memops.size(); i++) {
 861       MemNode* s = memops.at(i)->as_Mem();
 862       s->dump();
 863     }
 864   }
 865 #endif
 866 
 867   idx = max_idx;
 868   if (max_ct > 0) {
 869 #ifdef ASSERT
 870     if (TraceSuperWord) {
 871       tty->print("\nVector align to node: ");
 872       memops.at(max_idx)->as_Mem()->dump();
 873     }
 874 #endif
 875     return memops.at(max_idx)->as_Mem();
 876   }
 877   return NULL;
 878 }
 879 
 880 //------------------span_works_for_memory_size-----------------------------
 881 static bool span_works_for_memory_size(MemNode* mem, int span, int mem_size, int offset) {
 882   bool span_matches_memory = false;
 883   if ((mem_size == type2aelembytes(T_BYTE) || mem_size == type2aelembytes(T_SHORT))
 884     && ABS(span) == type2aelembytes(T_INT)) {
 885     // There is a mismatch on span size compared to memory.
 886     for (DUIterator_Fast jmax, j = mem->fast_outs(jmax); j < jmax; j++) {
 887       Node* use = mem->fast_out(j);
 888       if (!VectorNode::is_type_transition_to_int(use)) {
 889         return false;
 890       }
 891     }
 892     // If all uses transition to integer, it means that we can successfully align even on mismatch.
 893     return true;
 894   }
 895   else {
 896     span_matches_memory = ABS(span) == mem_size;
 897   }
 898   return span_matches_memory && (ABS(offset) % mem_size) == 0;
 899 }
 900 
 901 //------------------------------ref_is_alignable---------------------------
 902 // Can the preloop align the reference to position zero in the vector?
 903 bool SuperWord::ref_is_alignable(SWPointer& p) {
 904   if (!p.has_iv()) {
 905     return true;   // no induction variable
 906   }
 907   CountedLoopEndNode* pre_end = get_pre_loop_end(lp()->as_CountedLoop());
 908   assert(pre_end != NULL, "we must have a correct pre-loop");
 909   assert(pre_end->stride_is_con(), "pre loop stride is constant");
 910   int preloop_stride = pre_end->stride_con();
 911 
 912   int span = preloop_stride * p.scale_in_bytes();
 913   int mem_size = p.memory_size();
 914   int offset   = p.offset_in_bytes();
 915   // Stride one accesses are alignable if offset is aligned to memory operation size.
 916   // Offset can be unaligned when UseUnalignedAccesses is used.
 917   if (span_works_for_memory_size(p.mem(), span, mem_size, offset)) {
 918     return true;
 919   }
 920   // If the initial offset from start of the object is computable,
 921   // check if the pre-loop can align the final offset accordingly.
 922   //
 923   // In other words: Can we find an i such that the offset
 924   // after i pre-loop iterations is aligned to vw?
 925   //   (init_offset + pre_loop) % vw == 0              (1)
 926   // where
 927   //   pre_loop = i * span
 928   // is the number of bytes added to the offset by i pre-loop iterations.
 929   //
 930   // For this to hold we need pre_loop to increase init_offset by
 931   //   pre_loop = vw - (init_offset % vw)
 932   //
 933   // This is only possible if pre_loop is divisible by span because each
 934   // pre-loop iteration increases the initial offset by 'span' bytes:
 935   //   (vw - (init_offset % vw)) % span == 0
 936   //
 937   int vw = vector_width_in_bytes(p.mem());
 938   assert(vw > 1, "sanity");
 939   Node* init_nd = pre_end->init_trip();
 940   if (init_nd->is_Con() && p.invar() == NULL) {
 941     int init = init_nd->bottom_type()->is_int()->get_con();
 942     int init_offset = init * p.scale_in_bytes() + offset;
 943     if (init_offset < 0) { // negative offset from object start?
 944       return false;        // may happen in dead loop
 945     }
 946     if (vw % span == 0) {
 947       // If vm is a multiple of span, we use formula (1).
 948       if (span > 0) {
 949         return (vw - (init_offset % vw)) % span == 0;
 950       } else {
 951         assert(span < 0, "nonzero stride * scale");
 952         return (init_offset % vw) % -span == 0;
 953       }
 954     } else if (span % vw == 0) {
 955       // If span is a multiple of vw, we can simplify formula (1) to:
 956       //   (init_offset + i * span) % vw == 0
 957       //     =>
 958       //   (init_offset % vw) + ((i * span) % vw) == 0
 959       //     =>
 960       //   init_offset % vw == 0
 961       //
 962       // Because we add a multiple of vw to the initial offset, the final
 963       // offset is a multiple of vw if and only if init_offset is a multiple.
 964       //
 965       return (init_offset % vw) == 0;
 966     }
 967   }
 968   return false;
 969 }
 970 //---------------------------get_vw_bytes_special------------------------
 971 int SuperWord::get_vw_bytes_special(MemNode* s) {
 972   // Get the vector width in bytes.
 973   int vw = vector_width_in_bytes(s);
 974 
 975   // Check for special case where there is an MulAddS2I usage where short vectors are going to need combined.
 976   BasicType btype = velt_basic_type(s);
 977   if (type2aelembytes(btype) == 2) {
 978     bool should_combine_adjacent = true;
 979     for (DUIterator_Fast imax, i = s->fast_outs(imax); i < imax; i++) {
 980       Node* user = s->fast_out(i);
 981       if (!VectorNode::is_muladds2i(user)) {
 982         should_combine_adjacent = false;
 983       }
 984     }
 985     if (should_combine_adjacent) {
 986       vw = MIN2(Matcher::max_vector_size(btype)*type2aelembytes(btype), vw * 2);
 987     }
 988   }
 989 
 990   return vw;
 991 }
 992 
 993 //---------------------------get_iv_adjustment---------------------------
 994 // Calculate loop's iv adjustment for this memory ops.
 995 int SuperWord::get_iv_adjustment(MemNode* mem_ref) {
 996   SWPointer align_to_ref_p(mem_ref, this, NULL, false);
 997   int offset = align_to_ref_p.offset_in_bytes();
 998   int scale  = align_to_ref_p.scale_in_bytes();
 999   int elt_size = align_to_ref_p.memory_size();
1000   int vw       = get_vw_bytes_special(mem_ref);
1001   assert(vw > 1, "sanity");
1002   int iv_adjustment;
1003   if (scale != 0) {
1004     int stride_sign = (scale * iv_stride()) > 0 ? 1 : -1;
1005     // At least one iteration is executed in pre-loop by default. As result
1006     // several iterations are needed to align memory operations in main-loop even
1007     // if offset is 0.
1008     int iv_adjustment_in_bytes = (stride_sign * vw - (offset % vw));
1009     // iv_adjustment_in_bytes must be a multiple of elt_size if vector memory
1010     // references should be aligned on this platform.
1011     assert((ABS(iv_adjustment_in_bytes) % elt_size) == 0 || !vectors_should_be_aligned(),
1012            "(%d) should be divisible by (%d)", iv_adjustment_in_bytes, elt_size);
1013     iv_adjustment = iv_adjustment_in_bytes/elt_size;
1014   } else {
1015     // This memory op is not dependent on iv (scale == 0)
1016     iv_adjustment = 0;
1017   }
1018 
1019 #ifndef PRODUCT
1020   if (TraceSuperWord) {
1021     tty->print("SuperWord::get_iv_adjustment: n = %d, noffset = %d iv_adjust = %d elt_size = %d scale = %d iv_stride = %d vect_size %d: ",
1022       mem_ref->_idx, offset, iv_adjustment, elt_size, scale, iv_stride(), vw);
1023     mem_ref->dump();
1024   }
1025 #endif
1026   return iv_adjustment;
1027 }
1028 
1029 //---------------------------dependence_graph---------------------------
1030 // Construct dependency graph.
1031 // Add dependence edges to load/store nodes for memory dependence
1032 //    A.out()->DependNode.in(1) and DependNode.out()->B.prec(x)
1033 void SuperWord::dependence_graph() {
1034   CountedLoopNode *cl = lpt()->_head->as_CountedLoop();
1035   // First, assign a dependence node to each memory node
1036   for (int i = 0; i < _block.length(); i++ ) {
1037     Node *n = _block.at(i);
1038     if (n->is_Mem() || (n->is_Phi() && n->bottom_type() == Type::MEMORY)) {
1039       _dg.make_node(n);
1040     }
1041   }
1042 
1043   // For each memory slice, create the dependences
1044   for (int i = 0; i < _mem_slice_head.length(); i++) {
1045     Node* n      = _mem_slice_head.at(i);
1046     Node* n_tail = _mem_slice_tail.at(i);
1047 
1048     // Get slice in predecessor order (last is first)
1049     if (cl->is_main_loop()) {
1050       mem_slice_preds(n_tail, n, _nlist);
1051     }
1052 
1053 #ifndef PRODUCT
1054     if(TraceSuperWord && Verbose) {
1055       tty->print_cr("SuperWord::dependence_graph: built a new mem slice");
1056       for (int j = _nlist.length() - 1; j >= 0 ; j--) {
1057         _nlist.at(j)->dump();
1058       }
1059     }
1060 #endif
1061     // Make the slice dependent on the root
1062     DepMem* slice = _dg.dep(n);
1063     _dg.make_edge(_dg.root(), slice);
1064 
1065     // Create a sink for the slice
1066     DepMem* slice_sink = _dg.make_node(NULL);
1067     _dg.make_edge(slice_sink, _dg.tail());
1068 
1069     // Now visit each pair of memory ops, creating the edges
1070     for (int j = _nlist.length() - 1; j >= 0 ; j--) {
1071       Node* s1 = _nlist.at(j);
1072 
1073       // If no dependency yet, use slice
1074       if (_dg.dep(s1)->in_cnt() == 0) {
1075         _dg.make_edge(slice, s1);
1076       }
1077       SWPointer p1(s1->as_Mem(), this, NULL, false);
1078       bool sink_dependent = true;
1079       for (int k = j - 1; k >= 0; k--) {
1080         Node* s2 = _nlist.at(k);
1081         if (s1->is_Load() && s2->is_Load())
1082           continue;
1083         SWPointer p2(s2->as_Mem(), this, NULL, false);
1084 
1085         int cmp = p1.cmp(p2);
1086         if (SuperWordRTDepCheck &&
1087             p1.base() != p2.base() && p1.valid() && p2.valid()) {
1088           // Create a runtime check to disambiguate
1089           OrderedPair pp(p1.base(), p2.base());
1090           _disjoint_ptrs.append_if_missing(pp);
1091         } else if (!SWPointer::not_equal(cmp)) {
1092           // Possibly same address
1093           _dg.make_edge(s1, s2);
1094           sink_dependent = false;
1095         }
1096       }
1097       if (sink_dependent) {
1098         _dg.make_edge(s1, slice_sink);
1099       }
1100     }
1101 
1102     if (TraceSuperWord) {
1103       tty->print_cr("\nDependence graph for slice: %d", n->_idx);
1104       for (int q = 0; q < _nlist.length(); q++) {
1105         _dg.print(_nlist.at(q));
1106       }
1107       tty->cr();
1108     }
1109 
1110     _nlist.clear();
1111   }
1112 
1113   if (TraceSuperWord) {
1114     tty->print_cr("\ndisjoint_ptrs: %s", _disjoint_ptrs.length() > 0 ? "" : "NONE");
1115     for (int r = 0; r < _disjoint_ptrs.length(); r++) {
1116       _disjoint_ptrs.at(r).print();
1117       tty->cr();
1118     }
1119     tty->cr();
1120   }
1121 
1122 }
1123 
1124 //---------------------------mem_slice_preds---------------------------
1125 // Return a memory slice (node list) in predecessor order starting at "start"
1126 void SuperWord::mem_slice_preds(Node* start, Node* stop, GrowableArray<Node*> &preds) {
1127   assert(preds.length() == 0, "start empty");
1128   Node* n = start;
1129   Node* prev = NULL;
1130   while (true) {
1131     NOT_PRODUCT( if(is_trace_mem_slice()) tty->print_cr("SuperWord::mem_slice_preds: n %d", n->_idx);)
1132     assert(in_bb(n), "must be in block");
1133     for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
1134       Node* out = n->fast_out(i);
1135       if (out->is_Load()) {
1136         if (in_bb(out)) {
1137           preds.push(out);
1138           if (TraceSuperWord && Verbose) {
1139             tty->print_cr("SuperWord::mem_slice_preds: added pred(%d)", out->_idx);
1140           }
1141         }
1142       } else {
1143         // FIXME
1144         if (out->is_MergeMem() && !in_bb(out)) {
1145           // Either unrolling is causing a memory edge not to disappear,
1146           // or need to run igvn.optimize() again before SLP
1147         } else if (out->is_Phi() && out->bottom_type() == Type::MEMORY && !in_bb(out)) {
1148           // Ditto.  Not sure what else to check further.
1149         } else if (out->Opcode() == Op_StoreCM && out->in(MemNode::OopStore) == n) {
1150           // StoreCM has an input edge used as a precedence edge.
1151           // Maybe an issue when oop stores are vectorized.
1152         } else {
1153           assert(out == prev || prev == NULL, "no branches off of store slice");
1154         }
1155       }//else
1156     }//for
1157     if (n == stop) break;
1158     preds.push(n);
1159     if (TraceSuperWord && Verbose) {
1160       tty->print_cr("SuperWord::mem_slice_preds: added pred(%d)", n->_idx);
1161     }
1162     prev = n;
1163     assert(n->is_Mem(), "unexpected node %s", n->Name());
1164     n = n->in(MemNode::Memory);
1165   }
1166 }
1167 
1168 //------------------------------stmts_can_pack---------------------------
1169 // Can s1 and s2 be in a pack with s1 immediately preceding s2 and
1170 // s1 aligned at "align"
1171 bool SuperWord::stmts_can_pack(Node* s1, Node* s2, int align) {
1172 
1173   // Do not use superword for non-primitives
1174   BasicType bt1 = velt_basic_type(s1);
1175   BasicType bt2 = velt_basic_type(s2);
1176   if(!is_java_primitive(bt1) || !is_java_primitive(bt2))
1177     return false;
1178   if (Matcher::max_vector_size(bt1) < 2) {
1179     return false; // No vectors for this type
1180   }
1181 
1182   if (isomorphic(s1, s2)) {
1183     if ((independent(s1, s2) && have_similar_inputs(s1, s2)) || reduction(s1, s2)) {
1184       if (!exists_at(s1, 0) && !exists_at(s2, 1)) {
1185         if (!s1->is_Mem() || are_adjacent_refs(s1, s2)) {
1186           int s1_align = alignment(s1);
1187           int s2_align = alignment(s2);
1188           if (s1_align == top_align || s1_align == align) {
1189             if (s2_align == top_align || s2_align == align + data_size(s1)) {
1190               return true;
1191             }
1192           }
1193         }
1194       }
1195     }
1196   }
1197   return false;
1198 }
1199 
1200 //------------------------------exists_at---------------------------
1201 // Does s exist in a pack at position pos?
1202 bool SuperWord::exists_at(Node* s, uint pos) {
1203   for (int i = 0; i < _packset.length(); i++) {
1204     Node_List* p = _packset.at(i);
1205     if (p->at(pos) == s) {
1206       return true;
1207     }
1208   }
1209   return false;
1210 }
1211 
1212 //------------------------------are_adjacent_refs---------------------------
1213 // Is s1 immediately before s2 in memory?
1214 bool SuperWord::are_adjacent_refs(Node* s1, Node* s2) {
1215   if (!s1->is_Mem() || !s2->is_Mem()) return false;
1216   if (!in_bb(s1)    || !in_bb(s2))    return false;
1217 
1218   // Do not use superword for non-primitives
1219   if (!is_java_primitive(s1->as_Mem()->memory_type()) ||
1220       !is_java_primitive(s2->as_Mem()->memory_type())) {
1221     return false;
1222   }
1223 
1224   // FIXME - co_locate_pack fails on Stores in different mem-slices, so
1225   // only pack memops that are in the same alias set until that's fixed.
1226   if (_phase->C->get_alias_index(s1->as_Mem()->adr_type()) !=
1227       _phase->C->get_alias_index(s2->as_Mem()->adr_type()))
1228     return false;
1229   SWPointer p1(s1->as_Mem(), this, NULL, false);
1230   SWPointer p2(s2->as_Mem(), this, NULL, false);
1231   if (p1.base() != p2.base() || !p1.comparable(p2)) return false;
1232   int diff = p2.offset_in_bytes() - p1.offset_in_bytes();
1233   return diff == data_size(s1);
1234 }
1235 
1236 //------------------------------isomorphic---------------------------
1237 // Are s1 and s2 similar?
1238 bool SuperWord::isomorphic(Node* s1, Node* s2) {
1239   if (s1->Opcode() != s2->Opcode()) return false;
1240   if (s1->req() != s2->req()) return false;
1241   if (!same_velt_type(s1, s2)) return false;
1242   Node* s1_ctrl = s1->in(0);
1243   Node* s2_ctrl = s2->in(0);
1244   // If the control nodes are equivalent, no further checks are required to test for isomorphism.
1245   if (s1_ctrl == s2_ctrl) {
1246     return true;
1247   } else {
1248     bool s1_ctrl_inv = ((s1_ctrl == NULL) ? true : lpt()->is_invariant(s1_ctrl));
1249     bool s2_ctrl_inv = ((s2_ctrl == NULL) ? true : lpt()->is_invariant(s2_ctrl));
1250     // If the control nodes are not invariant for the loop, fail isomorphism test.
1251     if (!s1_ctrl_inv || !s2_ctrl_inv) {
1252       return false;
1253     }
1254     if(s1_ctrl != NULL && s2_ctrl != NULL) {
1255       if (s1_ctrl->is_Proj()) {
1256         s1_ctrl = s1_ctrl->in(0);
1257         assert(lpt()->is_invariant(s1_ctrl), "must be invariant");
1258       }
1259       if (s2_ctrl->is_Proj()) {
1260         s2_ctrl = s2_ctrl->in(0);
1261         assert(lpt()->is_invariant(s2_ctrl), "must be invariant");
1262       }
1263       if (!s1_ctrl->is_RangeCheck() || !s2_ctrl->is_RangeCheck()) {
1264         return false;
1265       }
1266     }
1267     // Control nodes are invariant. However, we have no way of checking whether they resolve
1268     // in an equivalent manner. But, we know that invariant range checks are guaranteed to
1269     // throw before the loop (if they would have thrown). Thus, the loop would not have been reached.
1270     // Therefore, if the control nodes for both are range checks, we accept them to be isomorphic.
1271     for (DUIterator_Fast imax, i = s1->fast_outs(imax); i < imax; i++) {
1272       Node* t1 = s1->fast_out(i);
1273       for (DUIterator_Fast jmax, j = s2->fast_outs(jmax); j < jmax; j++) {
1274         Node* t2 = s2->fast_out(j);
1275         if (VectorNode::is_muladds2i(t1) && VectorNode::is_muladds2i(t2)) {
1276           return true;
1277         }
1278       }
1279     }
1280   }
1281   return false;
1282 }
1283 
1284 //------------------------------independent---------------------------
1285 // Is there no data path from s1 to s2 or s2 to s1?
1286 bool SuperWord::independent(Node* s1, Node* s2) {
1287   //  assert(s1->Opcode() == s2->Opcode(), "check isomorphic first");
1288   int d1 = depth(s1);
1289   int d2 = depth(s2);
1290   if (d1 == d2) return s1 != s2;
1291   Node* deep    = d1 > d2 ? s1 : s2;
1292   Node* shallow = d1 > d2 ? s2 : s1;
1293 
1294   visited_clear();
1295 
1296   return independent_path(shallow, deep);
1297 }
1298 
1299 //--------------------------have_similar_inputs-----------------------
1300 // For a node pair (s1, s2) which is isomorphic and independent,
1301 // do s1 and s2 have similar input edges?
1302 bool SuperWord::have_similar_inputs(Node* s1, Node* s2) {
1303   // assert(isomorphic(s1, s2) == true, "check isomorphic");
1304   // assert(independent(s1, s2) == true, "check independent");
1305   if (s1->req() > 1 && !s1->is_Store() && !s1->is_Load()) {
1306     for (uint i = 1; i < s1->req(); i++) {
1307       if (s1->in(i)->Opcode() != s2->in(i)->Opcode()) return false;
1308     }
1309   }
1310   return true;
1311 }
1312 
1313 //------------------------------reduction---------------------------
1314 // Is there a data path between s1 and s2 and the nodes reductions?
1315 bool SuperWord::reduction(Node* s1, Node* s2) {
1316   bool retValue = false;
1317   int d1 = depth(s1);
1318   int d2 = depth(s2);
1319   if (d1 + 1 == d2) {
1320     if (s1->is_reduction() && s2->is_reduction()) {
1321       // This is an ordered set, so s1 should define s2
1322       for (DUIterator_Fast imax, i = s1->fast_outs(imax); i < imax; i++) {
1323         Node* t1 = s1->fast_out(i);
1324         if (t1 == s2) {
1325           // both nodes are reductions and connected
1326           retValue = true;
1327         }
1328       }
1329     }
1330   }
1331 
1332   return retValue;
1333 }
1334 
1335 //------------------------------independent_path------------------------------
1336 // Helper for independent
1337 bool SuperWord::independent_path(Node* shallow, Node* deep, uint dp) {
1338   if (dp >= 1000) return false; // stop deep recursion
1339   visited_set(deep);
1340   int shal_depth = depth(shallow);
1341   assert(shal_depth <= depth(deep), "must be");
1342   for (DepPreds preds(deep, _dg); !preds.done(); preds.next()) {
1343     Node* pred = preds.current();
1344     if (in_bb(pred) && !visited_test(pred)) {
1345       if (shallow == pred) {
1346         return false;
1347       }
1348       if (shal_depth < depth(pred) && !independent_path(shallow, pred, dp+1)) {
1349         return false;
1350       }
1351     }
1352   }
1353   return true;
1354 }
1355 
1356 //------------------------------set_alignment---------------------------
1357 void SuperWord::set_alignment(Node* s1, Node* s2, int align) {
1358   set_alignment(s1, align);
1359   if (align == top_align || align == bottom_align) {
1360     set_alignment(s2, align);
1361   } else {
1362     set_alignment(s2, align + data_size(s1));
1363   }
1364 }
1365 
1366 //------------------------------data_size---------------------------
1367 int SuperWord::data_size(Node* s) {
1368   Node* use = NULL; //test if the node is a candidate for CMoveV optimization, then return the size of CMov
1369   if (UseVectorCmov) {
1370     use = _cmovev_kit.is_Bool_candidate(s);
1371     if (use != NULL) {
1372       return data_size(use);
1373     }
1374     use = _cmovev_kit.is_CmpD_candidate(s);
1375     if (use != NULL) {
1376       return data_size(use);
1377     }
1378   }
1379 
1380   int bsize = type2aelembytes(velt_basic_type(s));
1381   assert(bsize != 0, "valid size");
1382   return bsize;
1383 }
1384 
1385 //------------------------------extend_packlist---------------------------
1386 // Extend packset by following use->def and def->use links from pack members.
1387 void SuperWord::extend_packlist() {
1388   bool changed;
1389   do {
1390     packset_sort(_packset.length());
1391     changed = false;
1392     for (int i = 0; i < _packset.length(); i++) {
1393       Node_List* p = _packset.at(i);
1394       changed |= follow_use_defs(p);
1395       changed |= follow_def_uses(p);
1396     }
1397   } while (changed);
1398 
1399   if (_race_possible) {
1400     for (int i = 0; i < _packset.length(); i++) {
1401       Node_List* p = _packset.at(i);
1402       order_def_uses(p);
1403     }
1404   }
1405 
1406   if (TraceSuperWord) {
1407     tty->print_cr("\nAfter extend_packlist");
1408     print_packset();
1409   }
1410 }
1411 
1412 //------------------------------follow_use_defs---------------------------
1413 // Extend the packset by visiting operand definitions of nodes in pack p
1414 bool SuperWord::follow_use_defs(Node_List* p) {
1415   assert(p->size() == 2, "just checking");
1416   Node* s1 = p->at(0);
1417   Node* s2 = p->at(1);
1418   assert(s1->req() == s2->req(), "just checking");
1419   assert(alignment(s1) + data_size(s1) == alignment(s2), "just checking");
1420 
1421   if (s1->is_Load()) return false;
1422 
1423   int align = alignment(s1);
1424   NOT_PRODUCT(if(is_trace_alignment()) tty->print_cr("SuperWord::follow_use_defs: s1 %d, align %d", s1->_idx, align);)
1425   bool changed = false;
1426   int start = s1->is_Store() ? MemNode::ValueIn   : 1;
1427   int end   = s1->is_Store() ? MemNode::ValueIn+1 : s1->req();
1428   for (int j = start; j < end; j++) {
1429     Node* t1 = s1->in(j);
1430     Node* t2 = s2->in(j);
1431     if (!in_bb(t1) || !in_bb(t2))
1432       continue;
1433     if (stmts_can_pack(t1, t2, align)) {
1434       if (est_savings(t1, t2) >= 0) {
1435         Node_List* pair = new Node_List();
1436         pair->push(t1);
1437         pair->push(t2);
1438         _packset.append(pair);
1439         NOT_PRODUCT(if(is_trace_alignment()) tty->print_cr("SuperWord::follow_use_defs: set_alignment(%d, %d, %d)", t1->_idx, t2->_idx, align);)
1440         set_alignment(t1, t2, align);
1441         changed = true;
1442       }
1443     }
1444   }
1445   return changed;
1446 }
1447 
1448 //------------------------------follow_def_uses---------------------------
1449 // Extend the packset by visiting uses of nodes in pack p
1450 bool SuperWord::follow_def_uses(Node_List* p) {
1451   bool changed = false;
1452   Node* s1 = p->at(0);
1453   Node* s2 = p->at(1);
1454   assert(p->size() == 2, "just checking");
1455   assert(s1->req() == s2->req(), "just checking");
1456   assert(alignment(s1) + data_size(s1) == alignment(s2), "just checking");
1457 
1458   if (s1->is_Store()) return false;
1459 
1460   int align = alignment(s1);
1461   NOT_PRODUCT(if(is_trace_alignment()) tty->print_cr("SuperWord::follow_def_uses: s1 %d, align %d", s1->_idx, align);)
1462   int savings = -1;
1463   int num_s1_uses = 0;
1464   Node* u1 = NULL;
1465   Node* u2 = NULL;
1466   for (DUIterator_Fast imax, i = s1->fast_outs(imax); i < imax; i++) {
1467     Node* t1 = s1->fast_out(i);
1468     num_s1_uses++;
1469     if (!in_bb(t1)) continue;
1470     for (DUIterator_Fast jmax, j = s2->fast_outs(jmax); j < jmax; j++) {
1471       Node* t2 = s2->fast_out(j);
1472       if (!in_bb(t2)) continue;
1473       if (t2->Opcode() == Op_AddI && t2 == _lp->as_CountedLoop()->incr()) continue; // don't mess with the iv
1474       if (!opnd_positions_match(s1, t1, s2, t2))
1475         continue;
1476       if (stmts_can_pack(t1, t2, align)) {
1477         int my_savings = est_savings(t1, t2);
1478         if (my_savings > savings) {
1479           savings = my_savings;
1480           u1 = t1;
1481           u2 = t2;
1482         }
1483       }
1484     }
1485   }
1486   if (num_s1_uses > 1) {
1487     _race_possible = true;
1488   }
1489   if (savings >= 0) {
1490     Node_List* pair = new Node_List();
1491     pair->push(u1);
1492     pair->push(u2);
1493     _packset.append(pair);
1494     NOT_PRODUCT(if(is_trace_alignment()) tty->print_cr("SuperWord::follow_def_uses: set_alignment(%d, %d, %d)", u1->_idx, u2->_idx, align);)
1495     set_alignment(u1, u2, align);
1496     changed = true;
1497   }
1498   return changed;
1499 }
1500 
1501 //------------------------------order_def_uses---------------------------
1502 // For extended packsets, ordinally arrange uses packset by major component
1503 void SuperWord::order_def_uses(Node_List* p) {
1504   Node* s1 = p->at(0);
1505 
1506   if (s1->is_Store()) return;
1507 
1508   // reductions are always managed beforehand
1509   if (s1->is_reduction()) return;
1510 
1511   for (DUIterator_Fast imax, i = s1->fast_outs(imax); i < imax; i++) {
1512     Node* t1 = s1->fast_out(i);
1513 
1514     // Only allow operand swap on commuting operations
1515     if (!t1->is_Add() && !t1->is_Mul() && !VectorNode::is_muladds2i(t1)) {
1516       break;
1517     }
1518 
1519     // Now find t1's packset
1520     Node_List* p2 = NULL;
1521     for (int j = 0; j < _packset.length(); j++) {
1522       p2 = _packset.at(j);
1523       Node* first = p2->at(0);
1524       if (t1 == first) {
1525         break;
1526       }
1527       p2 = NULL;
1528     }
1529     // Arrange all sub components by the major component
1530     if (p2 != NULL) {
1531       for (uint j = 1; j < p->size(); j++) {
1532         Node* d1 = p->at(j);
1533         Node* u1 = p2->at(j);
1534         opnd_positions_match(s1, t1, d1, u1);
1535       }
1536     }
1537   }
1538 }
1539 
1540 //---------------------------opnd_positions_match-------------------------
1541 // Is the use of d1 in u1 at the same operand position as d2 in u2?
1542 bool SuperWord::opnd_positions_match(Node* d1, Node* u1, Node* d2, Node* u2) {
1543   // check reductions to see if they are marshalled to represent the reduction
1544   // operator in a specified opnd
1545   if (u1->is_reduction() && u2->is_reduction()) {
1546     // ensure reductions have phis and reduction definitions feeding the 1st operand
1547     Node* first = u1->in(2);
1548     if (first->is_Phi() || first->is_reduction()) {
1549       u1->swap_edges(1, 2);
1550     }
1551     // ensure reductions have phis and reduction definitions feeding the 1st operand
1552     first = u2->in(2);
1553     if (first->is_Phi() || first->is_reduction()) {
1554       u2->swap_edges(1, 2);
1555     }
1556     return true;
1557   }
1558 
1559   uint ct = u1->req();
1560   if (ct != u2->req()) return false;
1561   uint i1 = 0;
1562   uint i2 = 0;
1563   do {
1564     for (i1++; i1 < ct; i1++) if (u1->in(i1) == d1) break;
1565     for (i2++; i2 < ct; i2++) if (u2->in(i2) == d2) break;
1566     if (i1 != i2) {
1567       if ((i1 == (3-i2)) && (u2->is_Add() || u2->is_Mul())) {
1568         // Further analysis relies on operands position matching.
1569         u2->swap_edges(i1, i2);
1570       } else if (VectorNode::is_muladds2i(u2) && u1 != u2) {
1571         if (i1 == 5 - i2) { // ((i1 == 3 && i2 == 2) || (i1 == 2 && i2 == 3) || (i1 == 1 && i2 == 4) || (i1 == 4 && i2 == 1))
1572           u2->swap_edges(1, 2);
1573           u2->swap_edges(3, 4);
1574         }
1575         if (i1 == 3 - i2 || i1 == 7 - i2) { // ((i1 == 1 && i2 == 2) || (i1 == 2 && i2 == 1) || (i1 == 3 && i2 == 4) || (i1 == 4 && i2 == 3))
1576           u2->swap_edges(2, 3);
1577           u2->swap_edges(1, 4);
1578         }
1579         return false; // Just swap the edges, the muladds2i nodes get packed in follow_use_defs
1580       } else {
1581         return false;
1582       }
1583     } else if (i1 == i2 && VectorNode::is_muladds2i(u2) && u1 != u2) {
1584       u2->swap_edges(1, 3);
1585       u2->swap_edges(2, 4);
1586       return false; // Just swap the edges, the muladds2i nodes get packed in follow_use_defs
1587     }
1588   } while (i1 < ct);
1589   return true;
1590 }
1591 
1592 //------------------------------est_savings---------------------------
1593 // Estimate the savings from executing s1 and s2 as a pack
1594 int SuperWord::est_savings(Node* s1, Node* s2) {
1595   int save_in = 2 - 1; // 2 operations per instruction in packed form
1596 
1597   // inputs
1598   for (uint i = 1; i < s1->req(); i++) {
1599     Node* x1 = s1->in(i);
1600     Node* x2 = s2->in(i);
1601     if (x1 != x2) {
1602       if (are_adjacent_refs(x1, x2)) {
1603         save_in += adjacent_profit(x1, x2);
1604       } else if (!in_packset(x1, x2)) {
1605         save_in -= pack_cost(2);
1606       } else {
1607         save_in += unpack_cost(2);
1608       }
1609     }
1610   }
1611 
1612   // uses of result
1613   uint ct = 0;
1614   int save_use = 0;
1615   for (DUIterator_Fast imax, i = s1->fast_outs(imax); i < imax; i++) {
1616     Node* s1_use = s1->fast_out(i);
1617     for (int j = 0; j < _packset.length(); j++) {
1618       Node_List* p = _packset.at(j);
1619       if (p->at(0) == s1_use) {
1620         for (DUIterator_Fast kmax, k = s2->fast_outs(kmax); k < kmax; k++) {
1621           Node* s2_use = s2->fast_out(k);
1622           if (p->at(p->size()-1) == s2_use) {
1623             ct++;
1624             if (are_adjacent_refs(s1_use, s2_use)) {
1625               save_use += adjacent_profit(s1_use, s2_use);
1626             }
1627           }
1628         }
1629       }
1630     }
1631   }
1632 
1633   if (ct < s1->outcnt()) save_use += unpack_cost(1);
1634   if (ct < s2->outcnt()) save_use += unpack_cost(1);
1635 
1636   return MAX2(save_in, save_use);
1637 }
1638 
1639 //------------------------------costs---------------------------
1640 int SuperWord::adjacent_profit(Node* s1, Node* s2) { return 2; }
1641 int SuperWord::pack_cost(int ct)   { return ct; }
1642 int SuperWord::unpack_cost(int ct) { return ct; }
1643 
1644 //------------------------------combine_packs---------------------------
1645 // Combine packs A and B with A.last == B.first into A.first..,A.last,B.second,..B.last
1646 void SuperWord::combine_packs() {
1647   bool changed = true;
1648   // Combine packs regardless max vector size.
1649   while (changed) {
1650     changed = false;
1651     for (int i = 0; i < _packset.length(); i++) {
1652       Node_List* p1 = _packset.at(i);
1653       if (p1 == NULL) continue;
1654       // Because of sorting we can start at i + 1
1655       for (int j = i + 1; j < _packset.length(); j++) {
1656         Node_List* p2 = _packset.at(j);
1657         if (p2 == NULL) continue;
1658         if (i == j) continue;
1659         if (p1->at(p1->size()-1) == p2->at(0)) {
1660           for (uint k = 1; k < p2->size(); k++) {
1661             p1->push(p2->at(k));
1662           }
1663           _packset.at_put(j, NULL);
1664           changed = true;
1665         }
1666       }
1667     }
1668   }
1669 
1670   // Split packs which have size greater then max vector size.
1671   for (int i = 0; i < _packset.length(); i++) {
1672     Node_List* p1 = _packset.at(i);
1673     if (p1 != NULL) {
1674       BasicType bt = velt_basic_type(p1->at(0));
1675       uint max_vlen = Matcher::max_vector_size(bt); // Max elements in vector
1676       assert(is_power_of_2(max_vlen), "sanity");
1677       uint psize = p1->size();
1678       if (!is_power_of_2(psize)) {
1679         // Skip pack which can't be vector.
1680         // case1: for(...) { a[i] = i; }    elements values are different (i+x)
1681         // case2: for(...) { a[i] = b[i+1]; }  can't align both, load and store
1682         _packset.at_put(i, NULL);
1683         continue;
1684       }
1685       if (psize > max_vlen) {
1686         Node_List* pack = new Node_List();
1687         for (uint j = 0; j < psize; j++) {
1688           pack->push(p1->at(j));
1689           if (pack->size() >= max_vlen) {
1690             assert(is_power_of_2(pack->size()), "sanity");
1691             _packset.append(pack);
1692             pack = new Node_List();
1693           }
1694         }
1695         _packset.at_put(i, NULL);
1696       }
1697     }
1698   }
1699 
1700   // Compress list.
1701   for (int i = _packset.length() - 1; i >= 0; i--) {
1702     Node_List* p1 = _packset.at(i);
1703     if (p1 == NULL) {
1704       _packset.remove_at(i);
1705     }
1706   }
1707 
1708   if (TraceSuperWord) {
1709     tty->print_cr("\nAfter combine_packs");
1710     print_packset();
1711   }
1712 }
1713 
1714 //-----------------------------construct_my_pack_map--------------------------
1715 // Construct the map from nodes to packs.  Only valid after the
1716 // point where a node is only in one pack (after combine_packs).
1717 void SuperWord::construct_my_pack_map() {
1718   Node_List* rslt = NULL;
1719   for (int i = 0; i < _packset.length(); i++) {
1720     Node_List* p = _packset.at(i);
1721     for (uint j = 0; j < p->size(); j++) {
1722       Node* s = p->at(j);
1723       assert(my_pack(s) == NULL, "only in one pack");
1724       set_my_pack(s, p);
1725     }
1726   }
1727 }
1728 
1729 //------------------------------filter_packs---------------------------
1730 // Remove packs that are not implemented or not profitable.
1731 void SuperWord::filter_packs() {
1732   // Remove packs that are not implemented
1733   for (int i = _packset.length() - 1; i >= 0; i--) {
1734     Node_List* pk = _packset.at(i);
1735     bool impl = implemented(pk);
1736     if (!impl) {
1737 #ifndef PRODUCT
1738       if (TraceSuperWord && Verbose) {
1739         tty->print_cr("Unimplemented");
1740         pk->at(0)->dump();
1741       }
1742 #endif
1743       remove_pack_at(i);
1744     }
1745     Node *n = pk->at(0);
1746     if (n->is_reduction()) {
1747       _num_reductions++;
1748     } else {
1749       _num_work_vecs++;
1750     }
1751   }
1752 
1753   // Remove packs that are not profitable
1754   bool changed;
1755   do {
1756     changed = false;
1757     for (int i = _packset.length() - 1; i >= 0; i--) {
1758       Node_List* pk = _packset.at(i);
1759       bool prof = profitable(pk);
1760       if (!prof) {
1761 #ifndef PRODUCT
1762         if (TraceSuperWord && Verbose) {
1763           tty->print_cr("Unprofitable");
1764           pk->at(0)->dump();
1765         }
1766 #endif
1767         remove_pack_at(i);
1768         changed = true;
1769       }
1770     }
1771   } while (changed);
1772 
1773 #ifndef PRODUCT
1774   if (TraceSuperWord) {
1775     tty->print_cr("\nAfter filter_packs");
1776     print_packset();
1777     tty->cr();
1778   }
1779 #endif
1780 }
1781 
1782 //------------------------------merge_packs_to_cmovd---------------------------
1783 // Merge CMoveD into new vector-nodes
1784 // We want to catch this pattern and subsume CmpD and Bool into CMoveD
1785 //
1786 //                   SubD             ConD
1787 //                  /  |               /
1788 //                 /   |           /   /
1789 //                /    |       /      /
1790 //               /     |   /         /
1791 //              /      /            /
1792 //             /    /  |           /
1793 //            v /      |          /
1794 //         CmpD        |         /
1795 //          |          |        /
1796 //          v          |       /
1797 //         Bool        |      /
1798 //           \         |     /
1799 //             \       |    /
1800 //               \     |   /
1801 //                 \   |  /
1802 //                   \ v /
1803 //                   CMoveD
1804 //
1805 
1806 void SuperWord::merge_packs_to_cmovd() {
1807   for (int i = _packset.length() - 1; i >= 0; i--) {
1808     _cmovev_kit.make_cmovevd_pack(_packset.at(i));
1809   }
1810   #ifndef PRODUCT
1811     if (TraceSuperWord) {
1812       tty->print_cr("\nSuperWord::merge_packs_to_cmovd(): After merge");
1813       print_packset();
1814       tty->cr();
1815     }
1816   #endif
1817 }
1818 
1819 Node* CMoveKit::is_Bool_candidate(Node* def) const {
1820   Node* use = NULL;
1821   if (!def->is_Bool() || def->in(0) != NULL || def->outcnt() != 1) {
1822     return NULL;
1823   }
1824   for (DUIterator_Fast jmax, j = def->fast_outs(jmax); j < jmax; j++) {
1825     use = def->fast_out(j);
1826     if (!_sw->same_generation(def, use) || !use->is_CMove()) {
1827       return NULL;
1828     }
1829   }
1830   return use;
1831 }
1832 
1833 Node* CMoveKit::is_CmpD_candidate(Node* def) const {
1834   Node* use = NULL;
1835   if (!def->is_Cmp() || def->in(0) != NULL || def->outcnt() != 1) {
1836     return NULL;
1837   }
1838   for (DUIterator_Fast jmax, j = def->fast_outs(jmax); j < jmax; j++) {
1839     use = def->fast_out(j);
1840     if (!_sw->same_generation(def, use) || (use = is_Bool_candidate(use)) == NULL || !_sw->same_generation(def, use)) {
1841       return NULL;
1842     }
1843   }
1844   return use;
1845 }
1846 
1847 Node_List* CMoveKit::make_cmovevd_pack(Node_List* cmovd_pk) {
1848   Node *cmovd = cmovd_pk->at(0);
1849   if (!cmovd->is_CMove()) {
1850     return NULL;
1851   }
1852   if (cmovd->Opcode() != Op_CMoveF && cmovd->Opcode() != Op_CMoveD) {
1853     return NULL;
1854   }
1855   if (pack(cmovd) != NULL) { // already in the cmov pack
1856     return NULL;
1857   }
1858   if (cmovd->in(0) != NULL) {
1859     NOT_PRODUCT(if(_sw->is_trace_cmov()) {tty->print("CMoveKit::make_cmovevd_pack: CMoveD %d has control flow, escaping...", cmovd->_idx); cmovd->dump();})
1860     return NULL;
1861   }
1862 
1863   Node* bol = cmovd->as_CMove()->in(CMoveNode::Condition);
1864   if (!bol->is_Bool()
1865       || bol->outcnt() != 1
1866       || !_sw->same_generation(bol, cmovd)
1867       || bol->in(0) != NULL  // BoolNode has control flow!!
1868       || _sw->my_pack(bol) == NULL) {
1869       NOT_PRODUCT(if(_sw->is_trace_cmov()) {tty->print("CMoveKit::make_cmovevd_pack: Bool %d does not fit CMoveD %d for building vector, escaping...", bol->_idx, cmovd->_idx); bol->dump();})
1870       return NULL;
1871   }
1872   Node_List* bool_pk = _sw->my_pack(bol);
1873   if (bool_pk->size() != cmovd_pk->size() ) {
1874     return NULL;
1875   }
1876 
1877   Node* cmpd = bol->in(1);
1878   if (!cmpd->is_Cmp()
1879       || cmpd->outcnt() != 1
1880       || !_sw->same_generation(cmpd, cmovd)
1881       || cmpd->in(0) != NULL  // CmpDNode has control flow!!
1882       || _sw->my_pack(cmpd) == NULL) {
1883       NOT_PRODUCT(if(_sw->is_trace_cmov()) {tty->print("CMoveKit::make_cmovevd_pack: CmpD %d does not fit CMoveD %d for building vector, escaping...", cmpd->_idx, cmovd->_idx); cmpd->dump();})
1884       return NULL;
1885   }
1886   Node_List* cmpd_pk = _sw->my_pack(cmpd);
1887   if (cmpd_pk->size() != cmovd_pk->size() ) {
1888     return NULL;
1889   }
1890 
1891   if (!test_cmpd_pack(cmpd_pk, cmovd_pk)) {
1892     NOT_PRODUCT(if(_sw->is_trace_cmov()) {tty->print("CMoveKit::make_cmovevd_pack: cmpd pack for CmpD %d failed vectorization test", cmpd->_idx); cmpd->dump();})
1893     return NULL;
1894   }
1895 
1896   Node_List* new_cmpd_pk = new Node_List();
1897   uint sz = cmovd_pk->size() - 1;
1898   for (uint i = 0; i <= sz; ++i) {
1899     Node* cmov = cmovd_pk->at(i);
1900     Node* bol  = bool_pk->at(i);
1901     Node* cmp  = cmpd_pk->at(i);
1902 
1903     new_cmpd_pk->insert(i, cmov);
1904 
1905     map(cmov, new_cmpd_pk);
1906     map(bol, new_cmpd_pk);
1907     map(cmp, new_cmpd_pk);
1908 
1909     _sw->set_my_pack(cmov, new_cmpd_pk); // and keep old packs for cmp and bool
1910   }
1911   _sw->_packset.remove(cmovd_pk);
1912   _sw->_packset.remove(bool_pk);
1913   _sw->_packset.remove(cmpd_pk);
1914   _sw->_packset.append(new_cmpd_pk);
1915   NOT_PRODUCT(if(_sw->is_trace_cmov()) {tty->print_cr("CMoveKit::make_cmovevd_pack: added syntactic CMoveD pack"); _sw->print_pack(new_cmpd_pk);})
1916   return new_cmpd_pk;
1917 }
1918 
1919 bool CMoveKit::test_cmpd_pack(Node_List* cmpd_pk, Node_List* cmovd_pk) {
1920   Node* cmpd0 = cmpd_pk->at(0);
1921   assert(cmpd0->is_Cmp(), "CMoveKit::test_cmpd_pack: should be CmpDNode");
1922   assert(cmovd_pk->at(0)->is_CMove(), "CMoveKit::test_cmpd_pack: should be CMoveD");
1923   assert(cmpd_pk->size() == cmovd_pk->size(), "CMoveKit::test_cmpd_pack: should be same size");
1924   Node* in1 = cmpd0->in(1);
1925   Node* in2 = cmpd0->in(2);
1926   Node_List* in1_pk = _sw->my_pack(in1);
1927   Node_List* in2_pk = _sw->my_pack(in2);
1928 
1929   if (  (in1_pk != NULL && in1_pk->size() != cmpd_pk->size())
1930      || (in2_pk != NULL && in2_pk->size() != cmpd_pk->size()) ) {
1931     return false;
1932   }
1933 
1934   // test if "all" in1 are in the same pack or the same node
1935   if (in1_pk == NULL) {
1936     for (uint j = 1; j < cmpd_pk->size(); j++) {
1937       if (cmpd_pk->at(j)->in(1) != in1) {
1938         return false;
1939       }
1940     }//for: in1_pk is not pack but all CmpD nodes in the pack have the same in(1)
1941   }
1942   // test if "all" in2 are in the same pack or the same node
1943   if (in2_pk == NULL) {
1944     for (uint j = 1; j < cmpd_pk->size(); j++) {
1945       if (cmpd_pk->at(j)->in(2) != in2) {
1946         return false;
1947       }
1948     }//for: in2_pk is not pack but all CmpD nodes in the pack have the same in(2)
1949   }
1950   //now check if cmpd_pk may be subsumed in vector built for cmovd_pk
1951   int cmovd_ind1, cmovd_ind2;
1952   if (cmpd_pk->at(0)->in(1) == cmovd_pk->at(0)->as_CMove()->in(CMoveNode::IfFalse)
1953    && cmpd_pk->at(0)->in(2) == cmovd_pk->at(0)->as_CMove()->in(CMoveNode::IfTrue)) {
1954       cmovd_ind1 = CMoveNode::IfFalse;
1955       cmovd_ind2 = CMoveNode::IfTrue;
1956   } else if (cmpd_pk->at(0)->in(2) == cmovd_pk->at(0)->as_CMove()->in(CMoveNode::IfFalse)
1957           && cmpd_pk->at(0)->in(1) == cmovd_pk->at(0)->as_CMove()->in(CMoveNode::IfTrue)) {
1958       cmovd_ind2 = CMoveNode::IfFalse;
1959       cmovd_ind1 = CMoveNode::IfTrue;
1960   }
1961   else {
1962     return false;
1963   }
1964 
1965   for (uint j = 1; j < cmpd_pk->size(); j++) {
1966     if (cmpd_pk->at(j)->in(1) != cmovd_pk->at(j)->as_CMove()->in(cmovd_ind1)
1967         || cmpd_pk->at(j)->in(2) != cmovd_pk->at(j)->as_CMove()->in(cmovd_ind2)) {
1968         return false;
1969     }//if
1970   }
1971   NOT_PRODUCT(if(_sw->is_trace_cmov()) { tty->print("CMoveKit::test_cmpd_pack: cmpd pack for 1st CmpD %d is OK for vectorization: ", cmpd0->_idx); cmpd0->dump(); })
1972   return true;
1973 }
1974 
1975 //------------------------------implemented---------------------------
1976 // Can code be generated for pack p?
1977 bool SuperWord::implemented(Node_List* p) {
1978   bool retValue = false;
1979   Node* p0 = p->at(0);
1980   if (p0 != NULL) {
1981     int opc = p0->Opcode();
1982     uint size = p->size();
1983     if (p0->is_reduction()) {
1984       const Type *arith_type = p0->bottom_type();
1985       // Length 2 reductions of INT/LONG do not offer performance benefits
1986       if (((arith_type->basic_type() == T_INT) || (arith_type->basic_type() == T_LONG)) && (size == 2)) {
1987         retValue = false;
1988       } else {
1989         retValue = ReductionNode::implemented(opc, size, arith_type->basic_type());
1990       }
1991     } else {
1992       retValue = VectorNode::implemented(opc, size, velt_basic_type(p0));
1993     }
1994     if (!retValue) {
1995       if (is_cmov_pack(p)) {
1996         NOT_PRODUCT(if(is_trace_cmov()) {tty->print_cr("SWPointer::implemented: found cmpd pack"); print_pack(p);})
1997         return true;
1998       }
1999     }
2000   }
2001   return retValue;
2002 }
2003 
2004 bool SuperWord::is_cmov_pack(Node_List* p) {
2005   return _cmovev_kit.pack(p->at(0)) != NULL;
2006 }
2007 //------------------------------same_inputs--------------------------
2008 // For pack p, are all idx operands the same?
2009 bool SuperWord::same_inputs(Node_List* p, int idx) {
2010   Node* p0 = p->at(0);
2011   uint vlen = p->size();
2012   Node* p0_def = p0->in(idx);
2013   for (uint i = 1; i < vlen; i++) {
2014     Node* pi = p->at(i);
2015     Node* pi_def = pi->in(idx);
2016     if (p0_def != pi_def) {
2017       return false;
2018     }
2019   }
2020   return true;
2021 }
2022 
2023 //------------------------------profitable---------------------------
2024 // For pack p, are all operands and all uses (with in the block) vector?
2025 bool SuperWord::profitable(Node_List* p) {
2026   Node* p0 = p->at(0);
2027   uint start, end;
2028   VectorNode::vector_operands(p0, &start, &end);
2029 
2030   // Return false if some inputs are not vectors or vectors with different
2031   // size or alignment.
2032   // Also, for now, return false if not scalar promotion case when inputs are
2033   // the same. Later, implement PackNode and allow differing, non-vector inputs
2034   // (maybe just the ones from outside the block.)
2035   for (uint i = start; i < end; i++) {
2036     if (!is_vector_use(p0, i)) {
2037       return false;
2038     }
2039   }
2040   // Check if reductions are connected
2041   if (p0->is_reduction()) {
2042     Node* second_in = p0->in(2);
2043     Node_List* second_pk = my_pack(second_in);
2044     if ((second_pk == NULL) || (_num_work_vecs == _num_reductions)) {
2045       // Remove reduction flag if no parent pack or if not enough work
2046       // to cover reduction expansion overhead
2047       p0->remove_flag(Node::Flag_is_reduction);
2048       return false;
2049     } else if (second_pk->size() != p->size()) {
2050       return false;
2051     }
2052   }
2053   if (VectorNode::is_shift(p0)) {
2054     // For now, return false if shift count is vector or not scalar promotion
2055     // case (different shift counts) because it is not supported yet.
2056     Node* cnt = p0->in(2);
2057     Node_List* cnt_pk = my_pack(cnt);
2058     if (cnt_pk != NULL)
2059       return false;
2060     if (!same_inputs(p, 2))
2061       return false;
2062   }
2063   if (!p0->is_Store()) {
2064     // For now, return false if not all uses are vector.
2065     // Later, implement ExtractNode and allow non-vector uses (maybe
2066     // just the ones outside the block.)
2067     for (uint i = 0; i < p->size(); i++) {
2068       Node* def = p->at(i);
2069       if (is_cmov_pack_internal_node(p, def)) {
2070         continue;
2071       }
2072       for (DUIterator_Fast jmax, j = def->fast_outs(jmax); j < jmax; j++) {
2073         Node* use = def->fast_out(j);
2074         for (uint k = 0; k < use->req(); k++) {
2075           Node* n = use->in(k);
2076           if (def == n) {
2077             // Reductions should only have a Phi use at the loop head or a non-phi use
2078             // outside of the loop if it is the last element of the pack (e.g. SafePoint).
2079             if (def->is_reduction() &&
2080                 ((use->is_Phi() && use->in(0) == _lpt->_head) ||
2081                  (!_lpt->is_member(_phase->get_loop(_phase->ctrl_or_self(use))) && i == p->size()-1))) {
2082               continue;
2083             }
2084             if (!is_vector_use(use, k)) {
2085               return false;
2086             }
2087           }
2088         }
2089       }
2090     }
2091   }
2092   return true;
2093 }
2094 
2095 //------------------------------schedule---------------------------
2096 // Adjust the memory graph for the packed operations
2097 void SuperWord::schedule() {
2098 
2099   // Co-locate in the memory graph the members of each memory pack
2100   for (int i = 0; i < _packset.length(); i++) {
2101     co_locate_pack(_packset.at(i));
2102   }
2103 }
2104 
2105 //-------------------------------remove_and_insert-------------------
2106 // Remove "current" from its current position in the memory graph and insert
2107 // it after the appropriate insertion point (lip or uip).
2108 void SuperWord::remove_and_insert(MemNode *current, MemNode *prev, MemNode *lip,
2109                                   Node *uip, Unique_Node_List &sched_before) {
2110   Node* my_mem = current->in(MemNode::Memory);
2111   bool sched_up = sched_before.member(current);
2112 
2113   // remove current_store from its current position in the memmory graph
2114   for (DUIterator i = current->outs(); current->has_out(i); i++) {
2115     Node* use = current->out(i);
2116     if (use->is_Mem()) {
2117       assert(use->in(MemNode::Memory) == current, "must be");
2118       if (use == prev) { // connect prev to my_mem
2119           _igvn.replace_input_of(use, MemNode::Memory, my_mem);
2120           --i; //deleted this edge; rescan position
2121       } else if (sched_before.member(use)) {
2122         if (!sched_up) { // Will be moved together with current
2123           _igvn.replace_input_of(use, MemNode::Memory, uip);
2124           --i; //deleted this edge; rescan position
2125         }
2126       } else {
2127         if (sched_up) { // Will be moved together with current
2128           _igvn.replace_input_of(use, MemNode::Memory, lip);
2129           --i; //deleted this edge; rescan position
2130         }
2131       }
2132     }
2133   }
2134 
2135   Node *insert_pt =  sched_up ?  uip : lip;
2136 
2137   // all uses of insert_pt's memory state should use current's instead
2138   for (DUIterator i = insert_pt->outs(); insert_pt->has_out(i); i++) {
2139     Node* use = insert_pt->out(i);
2140     if (use->is_Mem()) {
2141       assert(use->in(MemNode::Memory) == insert_pt, "must be");
2142       _igvn.replace_input_of(use, MemNode::Memory, current);
2143       --i; //deleted this edge; rescan position
2144     } else if (!sched_up && use->is_Phi() && use->bottom_type() == Type::MEMORY) {
2145       uint pos; //lip (lower insert point) must be the last one in the memory slice
2146       for (pos=1; pos < use->req(); pos++) {
2147         if (use->in(pos) == insert_pt) break;
2148       }
2149       _igvn.replace_input_of(use, pos, current);
2150       --i;
2151     }
2152   }
2153 
2154   //connect current to insert_pt
2155   _igvn.replace_input_of(current, MemNode::Memory, insert_pt);
2156 }
2157 
2158 //------------------------------co_locate_pack----------------------------------
2159 // To schedule a store pack, we need to move any sandwiched memory ops either before
2160 // or after the pack, based upon dependence information:
2161 // (1) If any store in the pack depends on the sandwiched memory op, the
2162 //     sandwiched memory op must be scheduled BEFORE the pack;
2163 // (2) If a sandwiched memory op depends on any store in the pack, the
2164 //     sandwiched memory op must be scheduled AFTER the pack;
2165 // (3) If a sandwiched memory op (say, memA) depends on another sandwiched
2166 //     memory op (say memB), memB must be scheduled before memA. So, if memA is
2167 //     scheduled before the pack, memB must also be scheduled before the pack;
2168 // (4) If there is no dependence restriction for a sandwiched memory op, we simply
2169 //     schedule this store AFTER the pack
2170 // (5) We know there is no dependence cycle, so there in no other case;
2171 // (6) Finally, all memory ops in another single pack should be moved in the same direction.
2172 //
2173 // To schedule a load pack, we use the memory state of either the first or the last load in
2174 // the pack, based on the dependence constraint.
2175 void SuperWord::co_locate_pack(Node_List* pk) {
2176   if (pk->at(0)->is_Store()) {
2177     MemNode* first     = executed_first(pk)->as_Mem();
2178     MemNode* last      = executed_last(pk)->as_Mem();
2179     Unique_Node_List schedule_before_pack;
2180     Unique_Node_List memops;
2181 
2182     MemNode* current   = last->in(MemNode::Memory)->as_Mem();
2183     MemNode* previous  = last;
2184     while (true) {
2185       assert(in_bb(current), "stay in block");
2186       memops.push(previous);
2187       for (DUIterator i = current->outs(); current->has_out(i); i++) {
2188         Node* use = current->out(i);
2189         if (use->is_Mem() && use != previous)
2190           memops.push(use);
2191       }
2192       if (current == first) break;
2193       previous = current;
2194       current  = current->in(MemNode::Memory)->as_Mem();
2195     }
2196 
2197     // determine which memory operations should be scheduled before the pack
2198     for (uint i = 1; i < memops.size(); i++) {
2199       Node *s1 = memops.at(i);
2200       if (!in_pack(s1, pk) && !schedule_before_pack.member(s1)) {
2201         for (uint j = 0; j< i; j++) {
2202           Node *s2 = memops.at(j);
2203           if (!independent(s1, s2)) {
2204             if (in_pack(s2, pk) || schedule_before_pack.member(s2)) {
2205               schedule_before_pack.push(s1); // s1 must be scheduled before
2206               Node_List* mem_pk = my_pack(s1);
2207               if (mem_pk != NULL) {
2208                 for (uint ii = 0; ii < mem_pk->size(); ii++) {
2209                   Node* s = mem_pk->at(ii);  // follow partner
2210                   if (memops.member(s) && !schedule_before_pack.member(s))
2211                     schedule_before_pack.push(s);
2212                 }
2213               }
2214               break;
2215             }
2216           }
2217         }
2218       }
2219     }
2220 
2221     Node*    upper_insert_pt = first->in(MemNode::Memory);
2222     // Following code moves loads connected to upper_insert_pt below aliased stores.
2223     // Collect such loads here and reconnect them back to upper_insert_pt later.
2224     memops.clear();
2225     for (DUIterator i = upper_insert_pt->outs(); upper_insert_pt->has_out(i); i++) {
2226       Node* use = upper_insert_pt->out(i);
2227       if (use->is_Mem() && !use->is_Store()) {
2228         memops.push(use);
2229       }
2230     }
2231 
2232     MemNode* lower_insert_pt = last;
2233     previous                 = last; //previous store in pk
2234     current                  = last->in(MemNode::Memory)->as_Mem();
2235 
2236     // start scheduling from "last" to "first"
2237     while (true) {
2238       assert(in_bb(current), "stay in block");
2239       assert(in_pack(previous, pk), "previous stays in pack");
2240       Node* my_mem = current->in(MemNode::Memory);
2241 
2242       if (in_pack(current, pk)) {
2243         // Forward users of my memory state (except "previous) to my input memory state
2244         for (DUIterator i = current->outs(); current->has_out(i); i++) {
2245           Node* use = current->out(i);
2246           if (use->is_Mem() && use != previous) {
2247             assert(use->in(MemNode::Memory) == current, "must be");
2248             if (schedule_before_pack.member(use)) {
2249               _igvn.replace_input_of(use, MemNode::Memory, upper_insert_pt);
2250             } else {
2251               _igvn.replace_input_of(use, MemNode::Memory, lower_insert_pt);
2252             }
2253             --i; // deleted this edge; rescan position
2254           }
2255         }
2256         previous = current;
2257       } else { // !in_pack(current, pk) ==> a sandwiched store
2258         remove_and_insert(current, previous, lower_insert_pt, upper_insert_pt, schedule_before_pack);
2259       }
2260 
2261       if (current == first) break;
2262       current = my_mem->as_Mem();
2263     } // end while
2264 
2265     // Reconnect loads back to upper_insert_pt.
2266     for (uint i = 0; i < memops.size(); i++) {
2267       Node *ld = memops.at(i);
2268       if (ld->in(MemNode::Memory) != upper_insert_pt) {
2269         _igvn.replace_input_of(ld, MemNode::Memory, upper_insert_pt);
2270       }
2271     }
2272   } else if (pk->at(0)->is_Load()) { // Load pack
2273     // All loads in the pack should have the same memory state. By default,
2274     // we use the memory state of the last load. However, if any load could
2275     // not be moved down due to the dependence constraint, we use the memory
2276     // state of the first load.
2277     Node* mem_input = pick_mem_state(pk);
2278     _igvn.hash_delete(mem_input);
2279     // Give each load the same memory state
2280     for (uint i = 0; i < pk->size(); i++) {
2281       LoadNode* ld = pk->at(i)->as_Load();
2282       _igvn.replace_input_of(ld, MemNode::Memory, mem_input);
2283     }
2284   }
2285 }
2286 
2287 // Finds the first and last memory state and then picks either of them by checking dependence constraints.
2288 // If a store is dependent on an earlier load then we need to pick the memory state of the first load and cannot
2289 // pick the memory state of the last load.
2290 Node* SuperWord::pick_mem_state(Node_List* pk) {
2291   Node* first_mem = find_first_mem_state(pk);
2292   Node* last_mem  = find_last_mem_state(pk, first_mem);
2293 
2294   for (uint i = 0; i < pk->size(); i++) {
2295     Node* ld = pk->at(i);
2296     for (Node* current = last_mem; current != ld->in(MemNode::Memory); current = current->in(MemNode::Memory)) {
2297       assert(current->is_Mem() && in_bb(current), "unexpected memory");
2298       assert(current != first_mem, "corrupted memory graph");
2299       if (!independent(current, ld)) {
2300 #ifdef ASSERT
2301         // Added assertion code since no case has been observed that should pick the first memory state.
2302         // Remove the assertion code whenever we find a (valid) case that really needs the first memory state.
2303         pk->dump();
2304         first_mem->dump();
2305         last_mem->dump();
2306         current->dump();
2307         ld->dump();
2308         ld->in(MemNode::Memory)->dump();
2309         assert(false, "never observed that first memory should be picked");
2310 #endif
2311         return first_mem; // A later store depends on this load, pick memory state of first load
2312       }
2313     }
2314   }
2315   return last_mem;
2316 }
2317 
2318 // Walk the memory graph from the current first load until the
2319 // start of the loop and check if nodes on the way are memory
2320 // edges of loads in the pack. The last one we encounter is the
2321 // first load.
2322 Node* SuperWord::find_first_mem_state(Node_List* pk) {
2323   Node* first_mem = pk->at(0)->in(MemNode::Memory);
2324   for (Node* current = first_mem; in_bb(current); current = current->is_Phi() ? current->in(LoopNode::EntryControl) : current->in(MemNode::Memory)) {
2325     assert(current->is_Mem() || (current->is_Phi() && current->in(0) == bb()), "unexpected memory");
2326     for (uint i = 1; i < pk->size(); i++) {
2327       Node* ld = pk->at(i);
2328       if (ld->in(MemNode::Memory) == current) {
2329         first_mem = current;
2330         break;
2331       }
2332     }
2333   }
2334   return first_mem;
2335 }
2336 
2337 // Find the last load by going over the pack again and walking
2338 // the memory graph from the loads of the pack to the memory of
2339 // the first load. If we encounter the memory of the current last
2340 // load, then we started from further down in the memory graph and
2341 // the load we started from is the last load.
2342 Node* SuperWord::find_last_mem_state(Node_List* pk, Node* first_mem) {
2343   Node* last_mem = pk->at(0)->in(MemNode::Memory);
2344   for (uint i = 0; i < pk->size(); i++) {
2345     Node* ld = pk->at(i);
2346     for (Node* current = ld->in(MemNode::Memory); current != first_mem; current = current->in(MemNode::Memory)) {
2347       assert(current->is_Mem() && in_bb(current), "unexpected memory");
2348       if (current->in(MemNode::Memory) == last_mem) {
2349         last_mem = ld->in(MemNode::Memory);
2350       }
2351     }
2352   }
2353   return last_mem;
2354 }
2355 
2356 #ifndef PRODUCT
2357 void SuperWord::print_loop(bool whole) {
2358   Node_Stack stack(_arena, _phase->C->unique() >> 2);
2359   Node_List rpo_list;
2360   VectorSet visited(_arena);
2361   visited.set(lpt()->_head->_idx);
2362   _phase->rpo(lpt()->_head, stack, visited, rpo_list);
2363   _phase->dump(lpt(), rpo_list.size(), rpo_list );
2364   if(whole) {
2365     tty->print_cr("\n Whole loop tree");
2366     _phase->dump();
2367     tty->print_cr(" End of whole loop tree\n");
2368   }
2369 }
2370 #endif
2371 
2372 //------------------------------output---------------------------
2373 // Convert packs into vector node operations
2374 void SuperWord::output() {
2375   CountedLoopNode *cl = lpt()->_head->as_CountedLoop();
2376   Compile* C = _phase->C;
2377   if (_packset.length() == 0) {
2378     if (cl->is_main_loop()) {
2379       // Instigate more unrolling for optimization when vectorization fails.
2380       C->set_major_progress();
2381       cl->set_notpassed_slp();
2382       cl->mark_do_unroll_only();
2383     }
2384     return;
2385   }
2386 
2387 #ifndef PRODUCT
2388   if (TraceLoopOpts) {
2389     tty->print("SuperWord::output    ");
2390     lpt()->dump_head();
2391   }
2392 #endif
2393 
2394   if (cl->is_main_loop()) {
2395     // MUST ENSURE main loop's initial value is properly aligned:
2396     //  (iv_initial_value + min_iv_offset) % vector_width_in_bytes() == 0
2397 
2398     align_initial_loop_index(align_to_ref());
2399 
2400     // Insert extract (unpack) operations for scalar uses
2401     for (int i = 0; i < _packset.length(); i++) {
2402       insert_extracts(_packset.at(i));
2403     }
2404   }
2405 
2406   uint max_vlen_in_bytes = 0;
2407   uint max_vlen = 0;
2408   bool can_process_post_loop = (PostLoopMultiversioning && Matcher::has_predicated_vectors() && cl->is_post_loop());
2409 
2410   NOT_PRODUCT(if(is_trace_loop_reverse()) {tty->print_cr("SWPointer::output: print loop before create_reserve_version_of_loop"); print_loop(true);})
2411 
2412   CountedLoopReserveKit make_reversable(_phase, _lpt, do_reserve_copy());
2413 
2414   NOT_PRODUCT(if(is_trace_loop_reverse()) {tty->print_cr("SWPointer::output: print loop after create_reserve_version_of_loop"); print_loop(true);})
2415 
2416   if (do_reserve_copy() && !make_reversable.has_reserved()) {
2417     NOT_PRODUCT(if(is_trace_loop_reverse() || TraceLoopOpts) {tty->print_cr("SWPointer::output: loop was not reserved correctly, exiting SuperWord");})
2418     return;
2419   }
2420 
2421   for (int i = 0; i < _block.length(); i++) {
2422     Node* n = _block.at(i);
2423     Node_List* p = my_pack(n);
2424     if (p && n == executed_last(p)) {
2425       uint vlen = p->size();
2426       uint vlen_in_bytes = 0;
2427       Node* vn = NULL;
2428       Node* low_adr = p->at(0);
2429       Node* first   = executed_first(p);
2430       if (can_process_post_loop) {
2431         // override vlen with the main loops vector length
2432         vlen = cl->slp_max_unroll();
2433       }
2434       NOT_PRODUCT(if(is_trace_cmov()) {tty->print_cr("SWPointer::output: %d executed first, %d executed last in pack", first->_idx, n->_idx); print_pack(p);})
2435       int   opc = n->Opcode();
2436       if (n->is_Load()) {
2437         Node* ctl = n->in(MemNode::Control);
2438         Node* mem = first->in(MemNode::Memory);
2439         SWPointer p1(n->as_Mem(), this, NULL, false);
2440         // Identify the memory dependency for the new loadVector node by
2441         // walking up through memory chain.
2442         // This is done to give flexibility to the new loadVector node so that
2443         // it can move above independent storeVector nodes.
2444         while (mem->is_StoreVector()) {
2445           SWPointer p2(mem->as_Mem(), this, NULL, false);
2446           int cmp = p1.cmp(p2);
2447           if (SWPointer::not_equal(cmp) || !SWPointer::comparable(cmp)) {
2448             mem = mem->in(MemNode::Memory);
2449           } else {
2450             break; // dependent memory
2451           }
2452         }
2453         Node* adr = low_adr->in(MemNode::Address);
2454         const TypePtr* atyp = n->adr_type();
2455         vn = LoadVectorNode::make(opc, ctl, mem, adr, atyp, vlen, velt_basic_type(n), control_dependency(p));
2456         vlen_in_bytes = vn->as_LoadVector()->memory_size();
2457       } else if (n->is_Store()) {
2458         // Promote value to be stored to vector
2459         Node* val = vector_opd(p, MemNode::ValueIn);
2460         if (val == NULL) {
2461           if (do_reserve_copy()) {
2462             NOT_PRODUCT(if(is_trace_loop_reverse() || TraceLoopOpts) {tty->print_cr("SWPointer::output: val should not be NULL, exiting SuperWord");})
2463             return; //and reverse to backup IG
2464           }
2465           ShouldNotReachHere();
2466         }
2467 
2468         Node* ctl = n->in(MemNode::Control);
2469         Node* mem = first->in(MemNode::Memory);
2470         Node* adr = low_adr->in(MemNode::Address);
2471         const TypePtr* atyp = n->adr_type();
2472         vn = StoreVectorNode::make(opc, ctl, mem, adr, atyp, val, vlen);
2473         vlen_in_bytes = vn->as_StoreVector()->memory_size();
2474       } else if (VectorNode::is_scalar_rotate(n)) {
2475         Node* in1 = low_adr->in(1);
2476         Node* in2 = p->at(0)->in(2);
2477         assert(in2->bottom_type()->isa_int(), "Shift must always be an int value");
2478         // If rotation count is non-constant or greater than 8bit value create a vector.
2479         if (!in2->is_Con() || -0x80 > in2->get_int() || in2->get_int() >= 0x80) {
2480           in2 =  vector_opd(p, 2);
2481         }
2482         vn = VectorNode::make(opc, in1, in2, vlen, velt_basic_type(n));
2483         vlen_in_bytes = vn->as_Vector()->length_in_bytes();
2484       } else if (VectorNode::is_roundopD(n)) {
2485         Node* in1 = vector_opd(p, 1);
2486         Node* in2 = low_adr->in(2);
2487         assert(in2->is_Con(), "Constant rounding mode expected.");
2488         vn = VectorNode::make(opc, in1, in2, vlen, velt_basic_type(n));
2489         vlen_in_bytes = vn->as_Vector()->length_in_bytes();
2490       } else if (VectorNode::is_muladds2i(n)) {
2491         assert(n->req() == 5u, "MulAddS2I should have 4 operands.");
2492         Node* in1 = vector_opd(p, 1);
2493         Node* in2 = vector_opd(p, 2);
2494         vn = VectorNode::make(opc, in1, in2, vlen, velt_basic_type(n));
2495         vlen_in_bytes = vn->as_Vector()->length_in_bytes();
2496       } else if (n->req() == 3 && !is_cmov_pack(p)) {
2497         // Promote operands to vector
2498         Node* in1 = NULL;
2499         bool node_isa_reduction = n->is_reduction();
2500         if (node_isa_reduction) {
2501           // the input to the first reduction operation is retained
2502           in1 = low_adr->in(1);
2503         } else {
2504           in1 = vector_opd(p, 1);
2505           if (in1 == NULL) {
2506             if (do_reserve_copy()) {
2507               NOT_PRODUCT(if(is_trace_loop_reverse() || TraceLoopOpts) {tty->print_cr("SWPointer::output: in1 should not be NULL, exiting SuperWord");})
2508               return; //and reverse to backup IG
2509             }
2510             ShouldNotReachHere();
2511           }
2512         }
2513         Node* in2 = vector_opd(p, 2);
2514         if (in2 == NULL) {
2515           if (do_reserve_copy()) {
2516             NOT_PRODUCT(if(is_trace_loop_reverse() || TraceLoopOpts) {tty->print_cr("SWPointer::output: in2 should not be NULL, exiting SuperWord");})
2517             return; //and reverse to backup IG
2518           }
2519           ShouldNotReachHere();
2520         }
2521         if (VectorNode::is_invariant_vector(in1) && (node_isa_reduction == false) && (n->is_Add() || n->is_Mul())) {
2522           // Move invariant vector input into second position to avoid register spilling.
2523           Node* tmp = in1;
2524           in1 = in2;
2525           in2 = tmp;
2526         }
2527         if (node_isa_reduction) {
2528           const Type *arith_type = n->bottom_type();
2529           vn = ReductionNode::make(opc, NULL, in1, in2, arith_type->basic_type());
2530           if (in2->is_Load()) {
2531             vlen_in_bytes = in2->as_LoadVector()->memory_size();
2532           } else {
2533             vlen_in_bytes = in2->as_Vector()->length_in_bytes();
2534           }
2535         } else {
2536           vn = VectorNode::make(opc, in1, in2, vlen, velt_basic_type(n));
2537           vlen_in_bytes = vn->as_Vector()->length_in_bytes();
2538         }
2539       } else if (opc == Op_SqrtF || opc == Op_SqrtD ||
2540                  opc == Op_AbsF || opc == Op_AbsD ||
2541                  opc == Op_AbsI || opc == Op_AbsL ||
2542                  opc == Op_NegF || opc == Op_NegD ||
2543                  opc == Op_PopCountI) {
2544         assert(n->req() == 2, "only one input expected");
2545         Node* in = vector_opd(p, 1);
2546         vn = VectorNode::make(opc, in, NULL, vlen, velt_basic_type(n));
2547         vlen_in_bytes = vn->as_Vector()->length_in_bytes();
2548       } else if (is_cmov_pack(p)) {
2549         if (can_process_post_loop) {
2550           // do not refactor of flow in post loop context
2551           return;
2552         }
2553         if (!n->is_CMove()) {
2554           continue;
2555         }
2556         // place here CMoveVDNode
2557         NOT_PRODUCT(if(is_trace_cmov()) {tty->print_cr("SWPointer::output: print before CMove vectorization"); print_loop(false);})
2558         Node* bol = n->in(CMoveNode::Condition);
2559         if (!bol->is_Bool() && bol->Opcode() == Op_ExtractI && bol->req() > 1 ) {
2560           NOT_PRODUCT(if(is_trace_cmov()) {tty->print_cr("SWPointer::output: %d is not Bool node, trying its in(1) node %d", bol->_idx, bol->in(1)->_idx); bol->dump(); bol->in(1)->dump();})
2561           bol = bol->in(1); //may be ExtractNode
2562         }
2563 
2564         assert(bol->is_Bool(), "should be BoolNode - too late to bail out!");
2565         if (!bol->is_Bool()) {
2566           if (do_reserve_copy()) {
2567             NOT_PRODUCT(if(is_trace_loop_reverse() || TraceLoopOpts) {tty->print_cr("SWPointer::output: expected %d bool node, exiting SuperWord", bol->_idx); bol->dump();})
2568             return; //and reverse to backup IG
2569           }
2570           ShouldNotReachHere();
2571         }
2572 
2573         int cond = (int)bol->as_Bool()->_test._test;
2574         Node* in_cc  = _igvn.intcon(cond);
2575         NOT_PRODUCT(if(is_trace_cmov()) {tty->print("SWPointer::output: created intcon in_cc node %d", in_cc->_idx); in_cc->dump();})
2576         Node* cc = bol->clone();
2577         cc->set_req(1, in_cc);
2578         NOT_PRODUCT(if(is_trace_cmov()) {tty->print("SWPointer::output: created bool cc node %d", cc->_idx); cc->dump();})
2579 
2580         Node* src1 = vector_opd(p, 2); //2=CMoveNode::IfFalse
2581         if (src1 == NULL) {
2582           if (do_reserve_copy()) {
2583             NOT_PRODUCT(if(is_trace_loop_reverse() || TraceLoopOpts) {tty->print_cr("SWPointer::output: src1 should not be NULL, exiting SuperWord");})
2584             return; //and reverse to backup IG
2585           }
2586           ShouldNotReachHere();
2587         }
2588         Node* src2 = vector_opd(p, 3); //3=CMoveNode::IfTrue
2589         if (src2 == NULL) {
2590           if (do_reserve_copy()) {
2591             NOT_PRODUCT(if(is_trace_loop_reverse() || TraceLoopOpts) {tty->print_cr("SWPointer::output: src2 should not be NULL, exiting SuperWord");})
2592             return; //and reverse to backup IG
2593           }
2594           ShouldNotReachHere();
2595         }
2596         BasicType bt = velt_basic_type(n);
2597         const TypeVect* vt = TypeVect::make(bt, vlen);
2598         assert(bt == T_FLOAT || bt == T_DOUBLE, "Only vectorization for FP cmovs is supported");
2599         if (bt == T_FLOAT) {
2600           vn = new CMoveVFNode(cc, src1, src2, vt);
2601         } else {
2602           assert(bt == T_DOUBLE, "Expected double");
2603           vn = new CMoveVDNode(cc, src1, src2, vt);
2604         }
2605         NOT_PRODUCT(if(is_trace_cmov()) {tty->print("SWPointer::output: created new CMove node %d: ", vn->_idx); vn->dump();})
2606       } else if (opc == Op_FmaD || opc == Op_FmaF) {
2607         // Promote operands to vector
2608         Node* in1 = vector_opd(p, 1);
2609         Node* in2 = vector_opd(p, 2);
2610         Node* in3 = vector_opd(p, 3);
2611         vn = VectorNode::make(opc, in1, in2, in3, vlen, velt_basic_type(n));
2612         vlen_in_bytes = vn->as_Vector()->length_in_bytes();
2613       } else {
2614         if (do_reserve_copy()) {
2615           NOT_PRODUCT(if(is_trace_loop_reverse() || TraceLoopOpts) {tty->print_cr("SWPointer::output: ShouldNotReachHere, exiting SuperWord");})
2616           return; //and reverse to backup IG
2617         }
2618         ShouldNotReachHere();
2619       }
2620 
2621       assert(vn != NULL, "sanity");
2622       if (vn == NULL) {
2623         if (do_reserve_copy()){
2624           NOT_PRODUCT(if(is_trace_loop_reverse() || TraceLoopOpts) {tty->print_cr("SWPointer::output: got NULL node, cannot proceed, exiting SuperWord");})
2625           return; //and reverse to backup IG
2626         }
2627         ShouldNotReachHere();
2628       }
2629 
2630       _block.at_put(i, vn);
2631       _igvn.register_new_node_with_optimizer(vn);
2632       _phase->set_ctrl(vn, _phase->get_ctrl(p->at(0)));
2633       for (uint j = 0; j < p->size(); j++) {
2634         Node* pm = p->at(j);
2635         _igvn.replace_node(pm, vn);
2636       }
2637       _igvn._worklist.push(vn);
2638 
2639       if (can_process_post_loop) {
2640         // first check if the vector size if the maximum vector which we can use on the machine,
2641         // other vector size have reduced values for predicated data mapping.
2642         if (vlen_in_bytes != (uint)MaxVectorSize) {
2643           return;
2644         }
2645       }
2646 
2647       if (vlen > max_vlen) {
2648         max_vlen = vlen;
2649       }
2650       if (vlen_in_bytes > max_vlen_in_bytes) {
2651         max_vlen_in_bytes = vlen_in_bytes;
2652       }
2653 #ifdef ASSERT
2654       if (TraceNewVectors) {
2655         tty->print("new Vector node: ");
2656         vn->dump();
2657       }
2658 #endif
2659     }
2660   }//for (int i = 0; i < _block.length(); i++)
2661 
2662   if (max_vlen_in_bytes > C->max_vector_size()) {
2663     C->set_max_vector_size(max_vlen_in_bytes);
2664   }
2665   if (max_vlen_in_bytes > 0) {
2666     cl->mark_loop_vectorized();
2667   }
2668 
2669   if (SuperWordLoopUnrollAnalysis) {
2670     if (cl->has_passed_slp()) {
2671       uint slp_max_unroll_factor = cl->slp_max_unroll();
2672       if (slp_max_unroll_factor == max_vlen) {
2673         if (TraceSuperWordLoopUnrollAnalysis) {
2674           tty->print_cr("vector loop(unroll=%d, len=%d)\n", max_vlen, max_vlen_in_bytes*BitsPerByte);
2675         }
2676 
2677         // For atomic unrolled loops which are vector mapped, instigate more unrolling
2678         cl->set_notpassed_slp();
2679         if (cl->is_main_loop()) {
2680           // if vector resources are limited, do not allow additional unrolling, also
2681           // do not unroll more on pure vector loops which were not reduced so that we can
2682           // program the post loop to single iteration execution.
2683           if (FLOATPRESSURE > 8) {
2684             C->set_major_progress();
2685             cl->mark_do_unroll_only();
2686           }
2687         }
2688 
2689         if (do_reserve_copy()) {
2690           if (can_process_post_loop) {
2691             // Now create the difference of trip and limit and use it as our mask index.
2692             // Note: We limited the unroll of the vectorized loop so that
2693             //       only vlen-1 size iterations can remain to be mask programmed.
2694             Node *incr = cl->incr();
2695             SubINode *index = new SubINode(cl->limit(), cl->init_trip());
2696             _igvn.register_new_node_with_optimizer(index);
2697             SetVectMaskINode  *mask = new SetVectMaskINode(_phase->get_ctrl(cl->init_trip()), index);
2698             _igvn.register_new_node_with_optimizer(mask);
2699             // make this a single iteration loop
2700             AddINode *new_incr = new AddINode(incr->in(1), mask);
2701             _igvn.register_new_node_with_optimizer(new_incr);
2702             _phase->set_ctrl(new_incr, _phase->get_ctrl(incr));
2703             _igvn.replace_node(incr, new_incr);
2704             cl->mark_is_multiversioned();
2705             cl->loopexit()->add_flag(Node::Flag_has_vector_mask_set);
2706           }
2707         }
2708       }
2709     }
2710   }
2711 
2712   if (do_reserve_copy()) {
2713     make_reversable.use_new();
2714   }
2715   NOT_PRODUCT(if(is_trace_loop_reverse()) {tty->print_cr("\n Final loop after SuperWord"); print_loop(true);})
2716   return;
2717 }
2718 
2719 //------------------------------vector_opd---------------------------
2720 // Create a vector operand for the nodes in pack p for operand: in(opd_idx)
2721 Node* SuperWord::vector_opd(Node_List* p, int opd_idx) {
2722   Node* p0 = p->at(0);
2723   uint vlen = p->size();
2724   Node* opd = p0->in(opd_idx);
2725   CountedLoopNode *cl = lpt()->_head->as_CountedLoop();
2726 
2727   if (PostLoopMultiversioning && Matcher::has_predicated_vectors() && cl->is_post_loop()) {
2728     // override vlen with the main loops vector length
2729     vlen = cl->slp_max_unroll();
2730   }
2731 
2732   if (same_inputs(p, opd_idx)) {
2733     if (opd->is_Vector() || opd->is_LoadVector()) {
2734       assert(((opd_idx != 2) || !VectorNode::is_shift(p0)), "shift's count can't be vector");
2735       if (opd_idx == 2 && VectorNode::is_shift(p0)) {
2736         NOT_PRODUCT(if(is_trace_loop_reverse() || TraceLoopOpts) {tty->print_cr("shift's count can't be vector");})
2737         return NULL;
2738       }
2739       return opd; // input is matching vector
2740     }
2741     if ((opd_idx == 2) && VectorNode::is_shift(p0)) {
2742       Compile* C = _phase->C;
2743       Node* cnt = opd;
2744       // Vector instructions do not mask shift count, do it here.
2745       juint mask = (p0->bottom_type() == TypeInt::INT) ? (BitsPerInt - 1) : (BitsPerLong - 1);
2746       const TypeInt* t = opd->find_int_type();
2747       if (t != NULL && t->is_con()) {
2748         juint shift = t->get_con();
2749         if (shift > mask) { // Unsigned cmp
2750           cnt = ConNode::make(TypeInt::make(shift & mask));
2751         }
2752       } else {
2753         if (t == NULL || t->_lo < 0 || t->_hi > (int)mask) {
2754           cnt = ConNode::make(TypeInt::make(mask));
2755           _igvn.register_new_node_with_optimizer(cnt);
2756           cnt = new AndINode(opd, cnt);
2757           _igvn.register_new_node_with_optimizer(cnt);
2758           _phase->set_ctrl(cnt, _phase->get_ctrl(opd));
2759         }
2760         assert(opd->bottom_type()->isa_int(), "int type only");
2761         if (!opd->bottom_type()->isa_int()) {
2762           NOT_PRODUCT(if(is_trace_loop_reverse() || TraceLoopOpts) {tty->print_cr("Should be int type only");})
2763           return NULL;
2764         }
2765       }
2766       // Move shift count into vector register.
2767       cnt = VectorNode::shift_count(p0, cnt, vlen, velt_basic_type(p0));
2768       _igvn.register_new_node_with_optimizer(cnt);
2769       _phase->set_ctrl(cnt, _phase->get_ctrl(opd));
2770       return cnt;
2771     }
2772     assert(!opd->is_StoreVector(), "such vector is not expected here");
2773     if (opd->is_StoreVector()) {
2774       NOT_PRODUCT(if(is_trace_loop_reverse() || TraceLoopOpts) {tty->print_cr("StoreVector is not expected here");})
2775       return NULL;
2776     }
2777     // Convert scalar input to vector with the same number of elements as
2778     // p0's vector. Use p0's type because size of operand's container in
2779     // vector should match p0's size regardless operand's size.
2780     const Type* p0_t = NULL;
2781     VectorNode* vn = NULL;
2782     if (opd_idx == 2 && VectorNode::is_scalar_rotate(p0)) {
2783        Node* conv = opd;
2784        p0_t =  TypeInt::INT;
2785        if (p0->bottom_type()->isa_long()) {
2786          p0_t = TypeLong::LONG;
2787          conv = new ConvI2LNode(opd);
2788          _igvn.register_new_node_with_optimizer(conv);
2789          _phase->set_ctrl(conv, _phase->get_ctrl(opd));
2790        }
2791        vn = VectorNode::scalar2vector(conv, vlen, p0_t);
2792     } else {
2793        p0_t =  velt_type(p0);
2794        vn = VectorNode::scalar2vector(opd, vlen, p0_t);
2795     }
2796 
2797     _igvn.register_new_node_with_optimizer(vn);
2798     _phase->set_ctrl(vn, _phase->get_ctrl(opd));
2799 #ifdef ASSERT
2800     if (TraceNewVectors) {
2801       tty->print("new Vector node: ");
2802       vn->dump();
2803     }
2804 #endif
2805     return vn;
2806   }
2807 
2808   // Insert pack operation
2809   BasicType bt = velt_basic_type(p0);
2810   PackNode* pk = PackNode::make(opd, vlen, bt);
2811   DEBUG_ONLY( const BasicType opd_bt = opd->bottom_type()->basic_type(); )
2812 
2813   for (uint i = 1; i < vlen; i++) {
2814     Node* pi = p->at(i);
2815     Node* in = pi->in(opd_idx);
2816     assert(my_pack(in) == NULL, "Should already have been unpacked");
2817     if (my_pack(in) != NULL) {
2818       NOT_PRODUCT(if(is_trace_loop_reverse() || TraceLoopOpts) {tty->print_cr("Should already have been unpacked");})
2819       return NULL;
2820     }
2821     assert(opd_bt == in->bottom_type()->basic_type(), "all same type");
2822     pk->add_opd(in);
2823     if (VectorNode::is_muladds2i(pi)) {
2824       Node* in2 = pi->in(opd_idx + 2);
2825       assert(my_pack(in2) == NULL, "Should already have been unpacked");
2826       if (my_pack(in2) != NULL) {
2827         NOT_PRODUCT(if (is_trace_loop_reverse() || TraceLoopOpts) { tty->print_cr("Should already have been unpacked"); })
2828           return NULL;
2829       }
2830       assert(opd_bt == in2->bottom_type()->basic_type(), "all same type");
2831       pk->add_opd(in2);
2832     }
2833   }
2834   _igvn.register_new_node_with_optimizer(pk);
2835   _phase->set_ctrl(pk, _phase->get_ctrl(opd));
2836 #ifdef ASSERT
2837   if (TraceNewVectors) {
2838     tty->print("new Vector node: ");
2839     pk->dump();
2840   }
2841 #endif
2842   return pk;
2843 }
2844 
2845 //------------------------------insert_extracts---------------------------
2846 // If a use of pack p is not a vector use, then replace the
2847 // use with an extract operation.
2848 void SuperWord::insert_extracts(Node_List* p) {
2849   if (p->at(0)->is_Store()) return;
2850   assert(_n_idx_list.is_empty(), "empty (node,index) list");
2851 
2852   // Inspect each use of each pack member.  For each use that is
2853   // not a vector use, replace the use with an extract operation.
2854 
2855   for (uint i = 0; i < p->size(); i++) {
2856     Node* def = p->at(i);
2857     for (DUIterator_Fast jmax, j = def->fast_outs(jmax); j < jmax; j++) {
2858       Node* use = def->fast_out(j);
2859       for (uint k = 0; k < use->req(); k++) {
2860         Node* n = use->in(k);
2861         if (def == n) {
2862           Node_List* u_pk = my_pack(use);
2863           if ((u_pk == NULL || !is_cmov_pack(u_pk) || use->is_CMove()) && !is_vector_use(use, k)) {
2864               _n_idx_list.push(use, k);
2865           }
2866         }
2867       }
2868     }
2869   }
2870 
2871   while (_n_idx_list.is_nonempty()) {
2872     Node* use = _n_idx_list.node();
2873     int   idx = _n_idx_list.index();
2874     _n_idx_list.pop();
2875     Node* def = use->in(idx);
2876 
2877     if (def->is_reduction()) continue;
2878 
2879     // Insert extract operation
2880     _igvn.hash_delete(def);
2881     int def_pos = alignment(def) / data_size(def);
2882 
2883     Node* ex = ExtractNode::make(def, def_pos, velt_basic_type(def));
2884     _igvn.register_new_node_with_optimizer(ex);
2885     _phase->set_ctrl(ex, _phase->get_ctrl(def));
2886     _igvn.replace_input_of(use, idx, ex);
2887     _igvn._worklist.push(def);
2888 
2889     bb_insert_after(ex, bb_idx(def));
2890     set_velt_type(ex, velt_type(def));
2891   }
2892 }
2893 
2894 //------------------------------is_vector_use---------------------------
2895 // Is use->in(u_idx) a vector use?
2896 bool SuperWord::is_vector_use(Node* use, int u_idx) {
2897   Node_List* u_pk = my_pack(use);
2898   if (u_pk == NULL) return false;
2899   if (use->is_reduction()) return true;
2900   Node* def = use->in(u_idx);
2901   Node_List* d_pk = my_pack(def);
2902   if (d_pk == NULL) {
2903     // check for scalar promotion
2904     Node* n = u_pk->at(0)->in(u_idx);
2905     for (uint i = 1; i < u_pk->size(); i++) {
2906       if (u_pk->at(i)->in(u_idx) != n) return false;
2907     }
2908     return true;
2909   }
2910   if (VectorNode::is_muladds2i(use)) {
2911     // MulAddS2I takes shorts and produces ints - hence the special checks
2912     // on alignment and size.
2913     if (u_pk->size() * 2 != d_pk->size()) {
2914       return false;
2915     }
2916     for (uint i = 0; i < MIN2(d_pk->size(), u_pk->size()); i++) {
2917       Node* ui = u_pk->at(i);
2918       Node* di = d_pk->at(i);
2919       if (alignment(ui) != alignment(di) * 2) {
2920         return false;
2921       }
2922     }
2923     return true;
2924   }
2925   if (u_pk->size() != d_pk->size())
2926     return false;
2927   for (uint i = 0; i < u_pk->size(); i++) {
2928     Node* ui = u_pk->at(i);
2929     Node* di = d_pk->at(i);
2930     if (ui->in(u_idx) != di || alignment(ui) != alignment(di))
2931       return false;
2932   }
2933   return true;
2934 }
2935 
2936 //------------------------------construct_bb---------------------------
2937 // Construct reverse postorder list of block members
2938 bool SuperWord::construct_bb() {
2939   Node* entry = bb();
2940 
2941   assert(_stk.length() == 0,            "stk is empty");
2942   assert(_block.length() == 0,          "block is empty");
2943   assert(_data_entry.length() == 0,     "data_entry is empty");
2944   assert(_mem_slice_head.length() == 0, "mem_slice_head is empty");
2945   assert(_mem_slice_tail.length() == 0, "mem_slice_tail is empty");
2946 
2947   // Find non-control nodes with no inputs from within block,
2948   // create a temporary map from node _idx to bb_idx for use
2949   // by the visited and post_visited sets,
2950   // and count number of nodes in block.
2951   int bb_ct = 0;
2952   for (uint i = 0; i < lpt()->_body.size(); i++) {
2953     Node *n = lpt()->_body.at(i);
2954     set_bb_idx(n, i); // Create a temporary map
2955     if (in_bb(n)) {
2956       if (n->is_LoadStore() || n->is_MergeMem() ||
2957           (n->is_Proj() && !n->as_Proj()->is_CFG())) {
2958         // Bailout if the loop has LoadStore, MergeMem or data Proj
2959         // nodes. Superword optimization does not work with them.
2960         return false;
2961       }
2962       bb_ct++;
2963       if (!n->is_CFG()) {
2964         bool found = false;
2965         for (uint j = 0; j < n->req(); j++) {
2966           Node* def = n->in(j);
2967           if (def && in_bb(def)) {
2968             found = true;
2969             break;
2970           }
2971         }
2972         if (!found) {
2973           assert(n != entry, "can't be entry");
2974           _data_entry.push(n);
2975         }
2976       }
2977     }
2978   }
2979 
2980   // Find memory slices (head and tail)
2981   for (DUIterator_Fast imax, i = lp()->fast_outs(imax); i < imax; i++) {
2982     Node *n = lp()->fast_out(i);
2983     if (in_bb(n) && (n->is_Phi() && n->bottom_type() == Type::MEMORY)) {
2984       Node* n_tail  = n->in(LoopNode::LoopBackControl);
2985       if (n_tail != n->in(LoopNode::EntryControl)) {
2986         if (!n_tail->is_Mem()) {
2987           assert(n_tail->is_Mem(), "unexpected node for memory slice: %s", n_tail->Name());
2988           return false; // Bailout
2989         }
2990         _mem_slice_head.push(n);
2991         _mem_slice_tail.push(n_tail);
2992       }
2993     }
2994   }
2995 
2996   // Create an RPO list of nodes in block
2997 
2998   visited_clear();
2999   post_visited_clear();
3000 
3001   // Push all non-control nodes with no inputs from within block, then control entry
3002   for (int j = 0; j < _data_entry.length(); j++) {
3003     Node* n = _data_entry.at(j);
3004     visited_set(n);
3005     _stk.push(n);
3006   }
3007   visited_set(entry);
3008   _stk.push(entry);
3009 
3010   // Do a depth first walk over out edges
3011   int rpo_idx = bb_ct - 1;
3012   int size;
3013   int reduction_uses = 0;
3014   while ((size = _stk.length()) > 0) {
3015     Node* n = _stk.top(); // Leave node on stack
3016     if (!visited_test_set(n)) {
3017       // forward arc in graph
3018     } else if (!post_visited_test(n)) {
3019       // cross or back arc
3020       for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
3021         Node *use = n->fast_out(i);
3022         if (in_bb(use) && !visited_test(use) &&
3023             // Don't go around backedge
3024             (!use->is_Phi() || n == entry)) {
3025           if (use->is_reduction()) {
3026             // First see if we can map the reduction on the given system we are on, then
3027             // make a data entry operation for each reduction we see.
3028             BasicType bt = use->bottom_type()->basic_type();
3029             if (ReductionNode::implemented(use->Opcode(), Matcher::min_vector_size(bt), bt)) {
3030               reduction_uses++;
3031             }
3032           }
3033           _stk.push(use);
3034         }
3035       }
3036       if (_stk.length() == size) {
3037         // There were no additional uses, post visit node now
3038         _stk.pop(); // Remove node from stack
3039         assert(rpo_idx >= 0, "");
3040         _block.at_put_grow(rpo_idx, n);
3041         rpo_idx--;
3042         post_visited_set(n);
3043         assert(rpo_idx >= 0 || _stk.is_empty(), "");
3044       }
3045     } else {
3046       _stk.pop(); // Remove post-visited node from stack
3047     }
3048   }//while
3049 
3050   int ii_current = -1;
3051   unsigned int load_idx = (unsigned int)-1;
3052   _ii_order.clear();
3053   // Create real map of block indices for nodes
3054   for (int j = 0; j < _block.length(); j++) {
3055     Node* n = _block.at(j);
3056     set_bb_idx(n, j);
3057     if (_do_vector_loop && n->is_Load()) {
3058       if (ii_current == -1) {
3059         ii_current = _clone_map.gen(n->_idx);
3060         _ii_order.push(ii_current);
3061         load_idx = _clone_map.idx(n->_idx);
3062       } else if (_clone_map.idx(n->_idx) == load_idx && _clone_map.gen(n->_idx) != ii_current) {
3063         ii_current = _clone_map.gen(n->_idx);
3064         _ii_order.push(ii_current);
3065       }
3066     }
3067   }//for
3068 
3069   // Ensure extra info is allocated.
3070   initialize_bb();
3071 
3072 #ifndef PRODUCT
3073   if (_vector_loop_debug && _ii_order.length() > 0) {
3074     tty->print("SuperWord::construct_bb: List of generations: ");
3075     for (int jj = 0; jj < _ii_order.length(); ++jj) {
3076       tty->print("  %d:%d", jj, _ii_order.at(jj));
3077     }
3078     tty->print_cr(" ");
3079   }
3080   if (TraceSuperWord) {
3081     print_bb();
3082     tty->print_cr("\ndata entry nodes: %s", _data_entry.length() > 0 ? "" : "NONE");
3083     for (int m = 0; m < _data_entry.length(); m++) {
3084       tty->print("%3d ", m);
3085       _data_entry.at(m)->dump();
3086     }
3087     tty->print_cr("\nmemory slices: %s", _mem_slice_head.length() > 0 ? "" : "NONE");
3088     for (int m = 0; m < _mem_slice_head.length(); m++) {
3089       tty->print("%3d ", m); _mem_slice_head.at(m)->dump();
3090       tty->print("    ");    _mem_slice_tail.at(m)->dump();
3091     }
3092   }
3093 #endif
3094   assert(rpo_idx == -1 && bb_ct == _block.length(), "all block members found");
3095   return (_mem_slice_head.length() > 0) || (reduction_uses > 0) || (_data_entry.length() > 0);
3096 }
3097 
3098 //------------------------------initialize_bb---------------------------
3099 // Initialize per node info
3100 void SuperWord::initialize_bb() {
3101   Node* last = _block.at(_block.length() - 1);
3102   grow_node_info(bb_idx(last));
3103 }
3104 
3105 //------------------------------bb_insert_after---------------------------
3106 // Insert n into block after pos
3107 void SuperWord::bb_insert_after(Node* n, int pos) {
3108   int n_pos = pos + 1;
3109   // Make room
3110   for (int i = _block.length() - 1; i >= n_pos; i--) {
3111     _block.at_put_grow(i+1, _block.at(i));
3112   }
3113   for (int j = _node_info.length() - 1; j >= n_pos; j--) {
3114     _node_info.at_put_grow(j+1, _node_info.at(j));
3115   }
3116   // Set value
3117   _block.at_put_grow(n_pos, n);
3118   _node_info.at_put_grow(n_pos, SWNodeInfo::initial);
3119   // Adjust map from node->_idx to _block index
3120   for (int i = n_pos; i < _block.length(); i++) {
3121     set_bb_idx(_block.at(i), i);
3122   }
3123 }
3124 
3125 //------------------------------compute_max_depth---------------------------
3126 // Compute max depth for expressions from beginning of block
3127 // Use to prune search paths during test for independence.
3128 void SuperWord::compute_max_depth() {
3129   int ct = 0;
3130   bool again;
3131   do {
3132     again = false;
3133     for (int i = 0; i < _block.length(); i++) {
3134       Node* n = _block.at(i);
3135       if (!n->is_Phi()) {
3136         int d_orig = depth(n);
3137         int d_in   = 0;
3138         for (DepPreds preds(n, _dg); !preds.done(); preds.next()) {
3139           Node* pred = preds.current();
3140           if (in_bb(pred)) {
3141             d_in = MAX2(d_in, depth(pred));
3142           }
3143         }
3144         if (d_in + 1 != d_orig) {
3145           set_depth(n, d_in + 1);
3146           again = true;
3147         }
3148       }
3149     }
3150     ct++;
3151   } while (again);
3152 
3153   if (TraceSuperWord && Verbose) {
3154     tty->print_cr("compute_max_depth iterated: %d times", ct);
3155   }
3156 }
3157 
3158 //-------------------------compute_vector_element_type-----------------------
3159 // Compute necessary vector element type for expressions
3160 // This propagates backwards a narrower integer type when the
3161 // upper bits of the value are not needed.
3162 // Example:  char a,b,c;  a = b + c;
3163 // Normally the type of the add is integer, but for packed character
3164 // operations the type of the add needs to be char.
3165 void SuperWord::compute_vector_element_type() {
3166   if (TraceSuperWord && Verbose) {
3167     tty->print_cr("\ncompute_velt_type:");
3168   }
3169 
3170   // Initial type
3171   for (int i = 0; i < _block.length(); i++) {
3172     Node* n = _block.at(i);
3173     set_velt_type(n, container_type(n));
3174   }
3175 
3176   // Propagate integer narrowed type backwards through operations
3177   // that don't depend on higher order bits
3178   for (int i = _block.length() - 1; i >= 0; i--) {
3179     Node* n = _block.at(i);
3180     // Only integer types need be examined
3181     const Type* vtn = velt_type(n);
3182     if (vtn->basic_type() == T_INT) {
3183       uint start, end;
3184       VectorNode::vector_operands(n, &start, &end);
3185 
3186       for (uint j = start; j < end; j++) {
3187         Node* in  = n->in(j);
3188         // Don't propagate through a memory
3189         if (!in->is_Mem() && in_bb(in) && velt_type(in)->basic_type() == T_INT &&
3190             data_size(n) < data_size(in)) {
3191           bool same_type = true;
3192           for (DUIterator_Fast kmax, k = in->fast_outs(kmax); k < kmax; k++) {
3193             Node *use = in->fast_out(k);
3194             if (!in_bb(use) || !same_velt_type(use, n)) {
3195               same_type = false;
3196               break;
3197             }
3198           }
3199           if (same_type) {
3200             // For right shifts of small integer types (bool, byte, char, short)
3201             // we need precise information about sign-ness. Only Load nodes have
3202             // this information because Store nodes are the same for signed and
3203             // unsigned values. And any arithmetic operation after a load may
3204             // expand a value to signed Int so such right shifts can't be used
3205             // because vector elements do not have upper bits of Int.
3206             const Type* vt = vtn;
3207             if (VectorNode::is_shift(in)) {
3208               Node* load = in->in(1);
3209               if (load->is_Load() && in_bb(load) && (velt_type(load)->basic_type() == T_INT)) {
3210                 vt = velt_type(load);
3211               } else if (in->Opcode() != Op_LShiftI) {
3212                 // Widen type to Int to avoid creation of right shift vector
3213                 // (align + data_size(s1) check in stmts_can_pack() will fail).
3214                 // Note, left shifts work regardless type.
3215                 vt = TypeInt::INT;
3216               }
3217             }
3218             set_velt_type(in, vt);
3219           }
3220         }
3221       }
3222     }
3223   }
3224 #ifndef PRODUCT
3225   if (TraceSuperWord && Verbose) {
3226     for (int i = 0; i < _block.length(); i++) {
3227       Node* n = _block.at(i);
3228       velt_type(n)->dump();
3229       tty->print("\t");
3230       n->dump();
3231     }
3232   }
3233 #endif
3234 }
3235 
3236 //------------------------------memory_alignment---------------------------
3237 // Alignment within a vector memory reference
3238 int SuperWord::memory_alignment(MemNode* s, int iv_adjust) {
3239 #ifndef PRODUCT
3240   if ((TraceSuperWord && Verbose) || is_trace_alignment()) {
3241     tty->print("SuperWord::memory_alignment within a vector memory reference for %d:  ", s->_idx); s->dump();
3242   }
3243 #endif
3244   NOT_PRODUCT(SWPointer::Tracer::Depth ddd(0);)
3245   SWPointer p(s, this, NULL, false);
3246   if (!p.valid()) {
3247     NOT_PRODUCT(if(is_trace_alignment()) tty->print_cr("SWPointer::memory_alignment: SWPointer p invalid, return bottom_align");)
3248     return bottom_align;
3249   }
3250   int vw = get_vw_bytes_special(s);
3251   if (vw < 2) {
3252     NOT_PRODUCT(if(is_trace_alignment()) tty->print_cr("SWPointer::memory_alignment: vector_width_in_bytes < 2, return bottom_align");)
3253     return bottom_align; // No vectors for this type
3254   }
3255   int offset  = p.offset_in_bytes();
3256   offset     += iv_adjust*p.memory_size();
3257   int off_rem = offset % vw;
3258   int off_mod = off_rem >= 0 ? off_rem : off_rem + vw;
3259 #ifndef PRODUCT
3260   if ((TraceSuperWord && Verbose) || is_trace_alignment()) {
3261     tty->print_cr("SWPointer::memory_alignment: off_rem = %d, off_mod = %d", off_rem, off_mod);
3262   }
3263 #endif
3264   return off_mod;
3265 }
3266 
3267 //---------------------------container_type---------------------------
3268 // Smallest type containing range of values
3269 const Type* SuperWord::container_type(Node* n) {
3270   if (n->is_Mem()) {
3271     BasicType bt = n->as_Mem()->memory_type();
3272     if (n->is_Store() && (bt == T_CHAR)) {
3273       // Use T_SHORT type instead of T_CHAR for stored values because any
3274       // preceding arithmetic operation extends values to signed Int.
3275       bt = T_SHORT;
3276     }
3277     if (n->Opcode() == Op_LoadUB) {
3278       // Adjust type for unsigned byte loads, it is important for right shifts.
3279       // T_BOOLEAN is used because there is no basic type representing type
3280       // TypeInt::UBYTE. Use of T_BOOLEAN for vectors is fine because only
3281       // size (one byte) and sign is important.
3282       bt = T_BOOLEAN;
3283     }
3284     return Type::get_const_basic_type(bt);
3285   }
3286   const Type* t = _igvn.type(n);
3287   if (t->basic_type() == T_INT) {
3288     // A narrow type of arithmetic operations will be determined by
3289     // propagating the type of memory operations.
3290     return TypeInt::INT;
3291   }
3292   return t;
3293 }
3294 
3295 bool SuperWord::same_velt_type(Node* n1, Node* n2) {
3296   const Type* vt1 = velt_type(n1);
3297   const Type* vt2 = velt_type(n2);
3298   if (vt1->basic_type() == T_INT && vt2->basic_type() == T_INT) {
3299     // Compare vectors element sizes for integer types.
3300     return data_size(n1) == data_size(n2);
3301   }
3302   return vt1 == vt2;
3303 }
3304 
3305 //------------------------------in_packset---------------------------
3306 // Are s1 and s2 in a pack pair and ordered as s1,s2?
3307 bool SuperWord::in_packset(Node* s1, Node* s2) {
3308   for (int i = 0; i < _packset.length(); i++) {
3309     Node_List* p = _packset.at(i);
3310     assert(p->size() == 2, "must be");
3311     if (p->at(0) == s1 && p->at(p->size()-1) == s2) {
3312       return true;
3313     }
3314   }
3315   return false;
3316 }
3317 
3318 //------------------------------in_pack---------------------------
3319 // Is s in pack p?
3320 Node_List* SuperWord::in_pack(Node* s, Node_List* p) {
3321   for (uint i = 0; i < p->size(); i++) {
3322     if (p->at(i) == s) {
3323       return p;
3324     }
3325   }
3326   return NULL;
3327 }
3328 
3329 //------------------------------remove_pack_at---------------------------
3330 // Remove the pack at position pos in the packset
3331 void SuperWord::remove_pack_at(int pos) {
3332   Node_List* p = _packset.at(pos);
3333   for (uint i = 0; i < p->size(); i++) {
3334     Node* s = p->at(i);
3335     set_my_pack(s, NULL);
3336   }
3337   _packset.remove_at(pos);
3338 }
3339 
3340 void SuperWord::packset_sort(int n) {
3341   // simple bubble sort so that we capitalize with O(n) when its already sorted
3342   while (n != 0) {
3343     bool swapped = false;
3344     for (int i = 1; i < n; i++) {
3345       Node_List* q_low = _packset.at(i-1);
3346       Node_List* q_i = _packset.at(i);
3347 
3348       // only swap when we find something to swap
3349       if (alignment(q_low->at(0)) > alignment(q_i->at(0))) {
3350         Node_List* t = q_i;
3351         *(_packset.adr_at(i)) = q_low;
3352         *(_packset.adr_at(i-1)) = q_i;
3353         swapped = true;
3354       }
3355     }
3356     if (swapped == false) break;
3357     n--;
3358   }
3359 }
3360 
3361 //------------------------------executed_first---------------------------
3362 // Return the node executed first in pack p.  Uses the RPO block list
3363 // to determine order.
3364 Node* SuperWord::executed_first(Node_List* p) {
3365   Node* n = p->at(0);
3366   int n_rpo = bb_idx(n);
3367   for (uint i = 1; i < p->size(); i++) {
3368     Node* s = p->at(i);
3369     int s_rpo = bb_idx(s);
3370     if (s_rpo < n_rpo) {
3371       n = s;
3372       n_rpo = s_rpo;
3373     }
3374   }
3375   return n;
3376 }
3377 
3378 //------------------------------executed_last---------------------------
3379 // Return the node executed last in pack p.
3380 Node* SuperWord::executed_last(Node_List* p) {
3381   Node* n = p->at(0);
3382   int n_rpo = bb_idx(n);
3383   for (uint i = 1; i < p->size(); i++) {
3384     Node* s = p->at(i);
3385     int s_rpo = bb_idx(s);
3386     if (s_rpo > n_rpo) {
3387       n = s;
3388       n_rpo = s_rpo;
3389     }
3390   }
3391   return n;
3392 }
3393 
3394 LoadNode::ControlDependency SuperWord::control_dependency(Node_List* p) {
3395   LoadNode::ControlDependency dep = LoadNode::DependsOnlyOnTest;
3396   for (uint i = 0; i < p->size(); i++) {
3397     Node* n = p->at(i);
3398     assert(n->is_Load(), "only meaningful for loads");
3399     if (!n->depends_only_on_test()) {
3400       if (n->as_Load()->has_unknown_control_dependency() &&
3401           dep != LoadNode::Pinned) {
3402         // Upgrade to unknown control...
3403         dep = LoadNode::UnknownControl;
3404       } else {
3405         // Otherwise, we must pin it.
3406         dep = LoadNode::Pinned;
3407       }
3408     }
3409   }
3410   return dep;
3411 }
3412 
3413 
3414 //----------------------------align_initial_loop_index---------------------------
3415 // Adjust pre-loop limit so that in main loop, a load/store reference
3416 // to align_to_ref will be a position zero in the vector.
3417 //   (iv + k) mod vector_align == 0
3418 void SuperWord::align_initial_loop_index(MemNode* align_to_ref) {
3419   CountedLoopNode *main_head = lp()->as_CountedLoop();
3420   assert(main_head->is_main_loop(), "");
3421   CountedLoopEndNode* pre_end = get_pre_loop_end(main_head);
3422   assert(pre_end != NULL, "we must have a correct pre-loop");
3423   Node *pre_opaq1 = pre_end->limit();
3424   assert(pre_opaq1->Opcode() == Op_Opaque1, "");
3425   Opaque1Node *pre_opaq = (Opaque1Node*)pre_opaq1;
3426   Node *lim0 = pre_opaq->in(1);
3427 
3428   // Where we put new limit calculations
3429   Node *pre_ctrl = pre_end->loopnode()->in(LoopNode::EntryControl);
3430 
3431   // Ensure the original loop limit is available from the
3432   // pre-loop Opaque1 node.
3433   Node *orig_limit = pre_opaq->original_loop_limit();
3434   assert(orig_limit != NULL && _igvn.type(orig_limit) != Type::TOP, "");
3435 
3436   SWPointer align_to_ref_p(align_to_ref, this, NULL, false);
3437   assert(align_to_ref_p.valid(), "sanity");
3438 
3439   // Given:
3440   //     lim0 == original pre loop limit
3441   //     V == v_align (power of 2)
3442   //     invar == extra invariant piece of the address expression
3443   //     e == offset [ +/- invar ]
3444   //
3445   // When reassociating expressions involving '%' the basic rules are:
3446   //     (a - b) % k == 0   =>  a % k == b % k
3447   // and:
3448   //     (a + b) % k == 0   =>  a % k == (k - b) % k
3449   //
3450   // For stride > 0 && scale > 0,
3451   //   Derive the new pre-loop limit "lim" such that the two constraints:
3452   //     (1) lim = lim0 + N           (where N is some positive integer < V)
3453   //     (2) (e + lim) % V == 0
3454   //   are true.
3455   //
3456   //   Substituting (1) into (2),
3457   //     (e + lim0 + N) % V == 0
3458   //   solve for N:
3459   //     N = (V - (e + lim0)) % V
3460   //   substitute back into (1), so that new limit
3461   //     lim = lim0 + (V - (e + lim0)) % V
3462   //
3463   // For stride > 0 && scale < 0
3464   //   Constraints:
3465   //     lim = lim0 + N
3466   //     (e - lim) % V == 0
3467   //   Solving for lim:
3468   //     (e - lim0 - N) % V == 0
3469   //     N = (e - lim0) % V
3470   //     lim = lim0 + (e - lim0) % V
3471   //
3472   // For stride < 0 && scale > 0
3473   //   Constraints:
3474   //     lim = lim0 - N
3475   //     (e + lim) % V == 0
3476   //   Solving for lim:
3477   //     (e + lim0 - N) % V == 0
3478   //     N = (e + lim0) % V
3479   //     lim = lim0 - (e + lim0) % V
3480   //
3481   // For stride < 0 && scale < 0
3482   //   Constraints:
3483   //     lim = lim0 - N
3484   //     (e - lim) % V == 0
3485   //   Solving for lim:
3486   //     (e - lim0 + N) % V == 0
3487   //     N = (V - (e - lim0)) % V
3488   //     lim = lim0 - (V - (e - lim0)) % V
3489 
3490   int vw = vector_width_in_bytes(align_to_ref);
3491   int stride   = iv_stride();
3492   int scale    = align_to_ref_p.scale_in_bytes();
3493   int elt_size = align_to_ref_p.memory_size();
3494   int v_align  = vw / elt_size;
3495   assert(v_align > 1, "sanity");
3496   int offset   = align_to_ref_p.offset_in_bytes() / elt_size;
3497   Node *offsn  = _igvn.intcon(offset);
3498 
3499   Node *e = offsn;
3500   if (align_to_ref_p.invar() != NULL) {
3501     // incorporate any extra invariant piece producing (offset +/- invar) >>> log2(elt)
3502     Node* log2_elt = _igvn.intcon(exact_log2(elt_size));
3503     Node* invar = align_to_ref_p.invar();
3504     if (_igvn.type(invar)->isa_long()) {
3505       // Computations are done % (vector width/element size) so it's
3506       // safe to simply convert invar to an int and loose the upper 32
3507       // bit half.
3508       invar = new ConvL2INode(invar);
3509       _igvn.register_new_node_with_optimizer(invar);
3510     }
3511     Node* aref = new URShiftINode(invar, log2_elt);
3512     _igvn.register_new_node_with_optimizer(aref);
3513     _phase->set_ctrl(aref, pre_ctrl);
3514     if (align_to_ref_p.negate_invar()) {
3515       e = new SubINode(e, aref);
3516     } else {
3517       e = new AddINode(e, aref);
3518     }
3519     _igvn.register_new_node_with_optimizer(e);
3520     _phase->set_ctrl(e, pre_ctrl);
3521   }
3522   if (vw > ObjectAlignmentInBytes || align_to_ref_p.base()->is_top()) {
3523     // incorporate base e +/- base && Mask >>> log2(elt)
3524     Node* xbase = new CastP2XNode(NULL, align_to_ref_p.adr());
3525     _igvn.register_new_node_with_optimizer(xbase);
3526 #ifdef _LP64
3527     xbase  = new ConvL2INode(xbase);
3528     _igvn.register_new_node_with_optimizer(xbase);
3529 #endif
3530     Node* mask = _igvn.intcon(vw-1);
3531     Node* masked_xbase  = new AndINode(xbase, mask);
3532     _igvn.register_new_node_with_optimizer(masked_xbase);
3533     Node* log2_elt = _igvn.intcon(exact_log2(elt_size));
3534     Node* bref     = new URShiftINode(masked_xbase, log2_elt);
3535     _igvn.register_new_node_with_optimizer(bref);
3536     _phase->set_ctrl(bref, pre_ctrl);
3537     e = new AddINode(e, bref);
3538     _igvn.register_new_node_with_optimizer(e);
3539     _phase->set_ctrl(e, pre_ctrl);
3540   }
3541 
3542   // compute e +/- lim0
3543   if (scale < 0) {
3544     e = new SubINode(e, lim0);
3545   } else {
3546     e = new AddINode(e, lim0);
3547   }
3548   _igvn.register_new_node_with_optimizer(e);
3549   _phase->set_ctrl(e, pre_ctrl);
3550 
3551   if (stride * scale > 0) {
3552     // compute V - (e +/- lim0)
3553     Node* va  = _igvn.intcon(v_align);
3554     e = new SubINode(va, e);
3555     _igvn.register_new_node_with_optimizer(e);
3556     _phase->set_ctrl(e, pre_ctrl);
3557   }
3558   // compute N = (exp) % V
3559   Node* va_msk = _igvn.intcon(v_align - 1);
3560   Node* N = new AndINode(e, va_msk);
3561   _igvn.register_new_node_with_optimizer(N);
3562   _phase->set_ctrl(N, pre_ctrl);
3563 
3564   //   substitute back into (1), so that new limit
3565   //     lim = lim0 + N
3566   Node* lim;
3567   if (stride < 0) {
3568     lim = new SubINode(lim0, N);
3569   } else {
3570     lim = new AddINode(lim0, N);
3571   }
3572   _igvn.register_new_node_with_optimizer(lim);
3573   _phase->set_ctrl(lim, pre_ctrl);
3574   Node* constrained =
3575     (stride > 0) ? (Node*) new MinINode(lim, orig_limit)
3576                  : (Node*) new MaxINode(lim, orig_limit);
3577   _igvn.register_new_node_with_optimizer(constrained);
3578   _phase->set_ctrl(constrained, pre_ctrl);
3579   _igvn.replace_input_of(pre_opaq, 1, constrained);
3580 }
3581 
3582 //----------------------------get_pre_loop_end---------------------------
3583 // Find pre loop end from main loop.  Returns null if none.
3584 CountedLoopEndNode* SuperWord::get_pre_loop_end(CountedLoopNode* cl) {
3585   // The loop cannot be optimized if the graph shape at
3586   // the loop entry is inappropriate.
3587   if (!PhaseIdealLoop::is_canonical_loop_entry(cl)) {
3588     return NULL;
3589   }
3590 
3591   Node* p_f = cl->skip_predicates()->in(0)->in(0);
3592   if (!p_f->is_IfFalse()) return NULL;
3593   if (!p_f->in(0)->is_CountedLoopEnd()) return NULL;
3594   CountedLoopEndNode* pre_end = p_f->in(0)->as_CountedLoopEnd();
3595   CountedLoopNode* loop_node = pre_end->loopnode();
3596   if (loop_node == NULL || !loop_node->is_pre_loop()) return NULL;
3597   return pre_end;
3598 }
3599 
3600 //------------------------------init---------------------------
3601 void SuperWord::init() {
3602   _dg.init();
3603   _packset.clear();
3604   _disjoint_ptrs.clear();
3605   _block.clear();
3606   _post_block.clear();
3607   _data_entry.clear();
3608   _mem_slice_head.clear();
3609   _mem_slice_tail.clear();
3610   _iteration_first.clear();
3611   _iteration_last.clear();
3612   _node_info.clear();
3613   _align_to_ref = NULL;
3614   _lpt = NULL;
3615   _lp = NULL;
3616   _bb = NULL;
3617   _iv = NULL;
3618   _race_possible = 0;
3619   _early_return = false;
3620   _num_work_vecs = 0;
3621   _num_reductions = 0;
3622 }
3623 
3624 //------------------------------restart---------------------------
3625 void SuperWord::restart() {
3626   _dg.init();
3627   _packset.clear();
3628   _disjoint_ptrs.clear();
3629   _block.clear();
3630   _post_block.clear();
3631   _data_entry.clear();
3632   _mem_slice_head.clear();
3633   _mem_slice_tail.clear();
3634   _node_info.clear();
3635 }
3636 
3637 //------------------------------print_packset---------------------------
3638 void SuperWord::print_packset() {
3639 #ifndef PRODUCT
3640   tty->print_cr("packset");
3641   for (int i = 0; i < _packset.length(); i++) {
3642     tty->print_cr("Pack: %d", i);
3643     Node_List* p = _packset.at(i);
3644     print_pack(p);
3645   }
3646 #endif
3647 }
3648 
3649 //------------------------------print_pack---------------------------
3650 void SuperWord::print_pack(Node_List* p) {
3651   for (uint i = 0; i < p->size(); i++) {
3652     print_stmt(p->at(i));
3653   }
3654 }
3655 
3656 //------------------------------print_bb---------------------------
3657 void SuperWord::print_bb() {
3658 #ifndef PRODUCT
3659   tty->print_cr("\nBlock");
3660   for (int i = 0; i < _block.length(); i++) {
3661     Node* n = _block.at(i);
3662     tty->print("%d ", i);
3663     if (n) {
3664       n->dump();
3665     }
3666   }
3667 #endif
3668 }
3669 
3670 //------------------------------print_stmt---------------------------
3671 void SuperWord::print_stmt(Node* s) {
3672 #ifndef PRODUCT
3673   tty->print(" align: %d \t", alignment(s));
3674   s->dump();
3675 #endif
3676 }
3677 
3678 //------------------------------blank---------------------------
3679 char* SuperWord::blank(uint depth) {
3680   static char blanks[101];
3681   assert(depth < 101, "too deep");
3682   for (uint i = 0; i < depth; i++) blanks[i] = ' ';
3683   blanks[depth] = '\0';
3684   return blanks;
3685 }
3686 
3687 
3688 //==============================SWPointer===========================
3689 #ifndef PRODUCT
3690 int SWPointer::Tracer::_depth = 0;
3691 #endif
3692 //----------------------------SWPointer------------------------
3693 SWPointer::SWPointer(MemNode* mem, SuperWord* slp, Node_Stack *nstack, bool analyze_only) :
3694   _mem(mem), _slp(slp),  _base(NULL),  _adr(NULL),
3695   _scale(0), _offset(0), _invar(NULL), _negate_invar(false),
3696   _nstack(nstack), _analyze_only(analyze_only),
3697   _stack_idx(0)
3698 #ifndef PRODUCT
3699   , _tracer(slp)
3700 #endif
3701 {
3702   NOT_PRODUCT(_tracer.ctor_1(mem);)
3703 
3704   Node* adr = mem->in(MemNode::Address);
3705   if (!adr->is_AddP()) {
3706     assert(!valid(), "too complex");
3707     return;
3708   }
3709   // Match AddP(base, AddP(ptr, k*iv [+ invariant]), constant)
3710   Node* base = adr->in(AddPNode::Base);
3711   // The base address should be loop invariant
3712   if (!invariant(base)) {
3713     assert(!valid(), "base address is loop variant");
3714     return;
3715   }
3716   // unsafe references require misaligned vector access support
3717   if (base->is_top() && !Matcher::misaligned_vectors_ok()) {
3718     assert(!valid(), "unsafe access");
3719     return;
3720   }
3721 
3722   NOT_PRODUCT(if(_slp->is_trace_alignment()) _tracer.store_depth();)
3723   NOT_PRODUCT(_tracer.ctor_2(adr);)
3724 
3725   int i;
3726   for (i = 0; i < 3; i++) {
3727     NOT_PRODUCT(_tracer.ctor_3(adr, i);)
3728 
3729     if (!scaled_iv_plus_offset(adr->in(AddPNode::Offset))) {
3730       assert(!valid(), "too complex");
3731       return;
3732     }
3733     adr = adr->in(AddPNode::Address);
3734     NOT_PRODUCT(_tracer.ctor_4(adr, i);)
3735 
3736     if (base == adr || !adr->is_AddP()) {
3737       NOT_PRODUCT(_tracer.ctor_5(adr, base, i);)
3738       break; // stop looking at addp's
3739     }
3740   }
3741   if (!invariant(adr)) {
3742     assert(!valid(), "adr is loop variant");
3743     return;
3744   }
3745 
3746   if (!base->is_top() && adr != base) {
3747     assert(!valid(), "adr and base differ");
3748     return;
3749   }
3750 
3751   NOT_PRODUCT(if(_slp->is_trace_alignment()) _tracer.restore_depth();)
3752   NOT_PRODUCT(_tracer.ctor_6(mem);)
3753 
3754   _base = base;
3755   _adr  = adr;
3756   assert(valid(), "Usable");
3757 }
3758 
3759 // Following is used to create a temporary object during
3760 // the pattern match of an address expression.
3761 SWPointer::SWPointer(SWPointer* p) :
3762   _mem(p->_mem), _slp(p->_slp),  _base(NULL),  _adr(NULL),
3763   _scale(0), _offset(0), _invar(NULL), _negate_invar(false),
3764   _nstack(p->_nstack), _analyze_only(p->_analyze_only),
3765   _stack_idx(p->_stack_idx)
3766   #ifndef PRODUCT
3767   , _tracer(p->_slp)
3768   #endif
3769 {}
3770 
3771 
3772 bool SWPointer::invariant(Node* n) {
3773   NOT_PRODUCT(Tracer::Depth dd;)
3774   Node *n_c = phase()->get_ctrl(n);
3775   NOT_PRODUCT(_tracer.invariant_1(n, n_c);)
3776   return !lpt()->is_member(phase()->get_loop(n_c));
3777 }
3778 
3779 //------------------------scaled_iv_plus_offset--------------------
3780 // Match: k*iv + offset
3781 // where: k is a constant that maybe zero, and
3782 //        offset is (k2 [+/- invariant]) where k2 maybe zero and invariant is optional
3783 bool SWPointer::scaled_iv_plus_offset(Node* n) {
3784   NOT_PRODUCT(Tracer::Depth ddd;)
3785   NOT_PRODUCT(_tracer.scaled_iv_plus_offset_1(n);)
3786 
3787   if (scaled_iv(n)) {
3788     NOT_PRODUCT(_tracer.scaled_iv_plus_offset_2(n);)
3789     return true;
3790   }
3791 
3792   if (offset_plus_k(n)) {
3793     NOT_PRODUCT(_tracer.scaled_iv_plus_offset_3(n);)
3794     return true;
3795   }
3796 
3797   int opc = n->Opcode();
3798   if (opc == Op_AddI) {
3799     if (offset_plus_k(n->in(2)) && scaled_iv_plus_offset(n->in(1))) {
3800       NOT_PRODUCT(_tracer.scaled_iv_plus_offset_4(n);)
3801       return true;
3802     }
3803     if (offset_plus_k(n->in(1)) && scaled_iv_plus_offset(n->in(2))) {
3804       NOT_PRODUCT(_tracer.scaled_iv_plus_offset_5(n);)
3805       return true;
3806     }
3807   } else if (opc == Op_SubI) {
3808     if (offset_plus_k(n->in(2), true) && scaled_iv_plus_offset(n->in(1))) {
3809       NOT_PRODUCT(_tracer.scaled_iv_plus_offset_6(n);)
3810       return true;
3811     }
3812     if (offset_plus_k(n->in(1)) && scaled_iv_plus_offset(n->in(2))) {
3813       _scale *= -1;
3814       NOT_PRODUCT(_tracer.scaled_iv_plus_offset_7(n);)
3815       return true;
3816     }
3817   }
3818 
3819   NOT_PRODUCT(_tracer.scaled_iv_plus_offset_8(n);)
3820   return false;
3821 }
3822 
3823 //----------------------------scaled_iv------------------------
3824 // Match: k*iv where k is a constant that's not zero
3825 bool SWPointer::scaled_iv(Node* n) {
3826   NOT_PRODUCT(Tracer::Depth ddd;)
3827   NOT_PRODUCT(_tracer.scaled_iv_1(n);)
3828 
3829   if (_scale != 0) { // already found a scale
3830     NOT_PRODUCT(_tracer.scaled_iv_2(n, _scale);)
3831     return false;
3832   }
3833 
3834   if (n == iv()) {
3835     _scale = 1;
3836     NOT_PRODUCT(_tracer.scaled_iv_3(n, _scale);)
3837     return true;
3838   }
3839   if (_analyze_only && (invariant(n) == false)) {
3840     _nstack->push(n, _stack_idx++);
3841   }
3842 
3843   int opc = n->Opcode();
3844   if (opc == Op_MulI) {
3845     if (n->in(1) == iv() && n->in(2)->is_Con()) {
3846       _scale = n->in(2)->get_int();
3847       NOT_PRODUCT(_tracer.scaled_iv_4(n, _scale);)
3848       return true;
3849     } else if (n->in(2) == iv() && n->in(1)->is_Con()) {
3850       _scale = n->in(1)->get_int();
3851       NOT_PRODUCT(_tracer.scaled_iv_5(n, _scale);)
3852       return true;
3853     }
3854   } else if (opc == Op_LShiftI) {
3855     if (n->in(1) == iv() && n->in(2)->is_Con()) {
3856       _scale = 1 << n->in(2)->get_int();
3857       NOT_PRODUCT(_tracer.scaled_iv_6(n, _scale);)
3858       return true;
3859     }
3860   } else if (opc == Op_ConvI2L) {
3861     if (n->in(1)->Opcode() == Op_CastII &&
3862         n->in(1)->as_CastII()->has_range_check()) {
3863       // Skip range check dependent CastII nodes
3864       n = n->in(1);
3865     }
3866     if (scaled_iv_plus_offset(n->in(1))) {
3867       NOT_PRODUCT(_tracer.scaled_iv_7(n);)
3868       return true;
3869     }
3870   } else if (opc == Op_LShiftL) {
3871     if (!has_iv() && _invar == NULL) {
3872       // Need to preserve the current _offset value, so
3873       // create a temporary object for this expression subtree.
3874       // Hacky, so should re-engineer the address pattern match.
3875       NOT_PRODUCT(Tracer::Depth dddd;)
3876       SWPointer tmp(this);
3877       NOT_PRODUCT(_tracer.scaled_iv_8(n, &tmp);)
3878 
3879       if (tmp.scaled_iv_plus_offset(n->in(1))) {
3880         if (tmp._invar == NULL || _slp->do_vector_loop()) {
3881           int mult = 1 << n->in(2)->get_int();
3882           _scale   = tmp._scale  * mult;
3883           _offset += tmp._offset * mult;
3884           _invar = tmp._invar;
3885           NOT_PRODUCT(_tracer.scaled_iv_9(n, _scale, _offset, mult);)
3886           return true;
3887         }
3888       }
3889     }
3890   }
3891   NOT_PRODUCT(_tracer.scaled_iv_10(n);)
3892   return false;
3893 }
3894 
3895 //----------------------------offset_plus_k------------------------
3896 // Match: offset is (k [+/- invariant])
3897 // where k maybe zero and invariant is optional, but not both.
3898 bool SWPointer::offset_plus_k(Node* n, bool negate) {
3899   NOT_PRODUCT(Tracer::Depth ddd;)
3900   NOT_PRODUCT(_tracer.offset_plus_k_1(n);)
3901 
3902   int opc = n->Opcode();
3903   if (opc == Op_ConI) {
3904     _offset += negate ? -(n->get_int()) : n->get_int();
3905     NOT_PRODUCT(_tracer.offset_plus_k_2(n, _offset);)
3906     return true;
3907   } else if (opc == Op_ConL) {
3908     // Okay if value fits into an int
3909     const TypeLong* t = n->find_long_type();
3910     if (t->higher_equal(TypeLong::INT)) {
3911       jlong loff = n->get_long();
3912       jint  off  = (jint)loff;
3913       _offset += negate ? -off : loff;
3914       NOT_PRODUCT(_tracer.offset_plus_k_3(n, _offset);)
3915       return true;
3916     }
3917     NOT_PRODUCT(_tracer.offset_plus_k_4(n);)
3918     return false;
3919   }
3920   if (_invar != NULL) { // already has an invariant
3921     NOT_PRODUCT(_tracer.offset_plus_k_5(n, _invar);)
3922     return false;
3923   }
3924 
3925   if (_analyze_only && (invariant(n) == false)) {
3926     _nstack->push(n, _stack_idx++);
3927   }
3928   if (opc == Op_AddI) {
3929     if (n->in(2)->is_Con() && invariant(n->in(1))) {
3930       _negate_invar = negate;
3931       _invar = n->in(1);
3932       _offset += negate ? -(n->in(2)->get_int()) : n->in(2)->get_int();
3933       NOT_PRODUCT(_tracer.offset_plus_k_6(n, _invar, _negate_invar, _offset);)
3934       return true;
3935     } else if (n->in(1)->is_Con() && invariant(n->in(2))) {
3936       _offset += negate ? -(n->in(1)->get_int()) : n->in(1)->get_int();
3937       _negate_invar = negate;
3938       _invar = n->in(2);
3939       NOT_PRODUCT(_tracer.offset_plus_k_7(n, _invar, _negate_invar, _offset);)
3940       return true;
3941     }
3942   }
3943   if (opc == Op_SubI) {
3944     if (n->in(2)->is_Con() && invariant(n->in(1))) {
3945       _negate_invar = negate;
3946       _invar = n->in(1);
3947       _offset += !negate ? -(n->in(2)->get_int()) : n->in(2)->get_int();
3948       NOT_PRODUCT(_tracer.offset_plus_k_8(n, _invar, _negate_invar, _offset);)
3949       return true;
3950     } else if (n->in(1)->is_Con() && invariant(n->in(2))) {
3951       _offset += negate ? -(n->in(1)->get_int()) : n->in(1)->get_int();
3952       _negate_invar = !negate;
3953       _invar = n->in(2);
3954       NOT_PRODUCT(_tracer.offset_plus_k_9(n, _invar, _negate_invar, _offset);)
3955       return true;
3956     }
3957   }
3958   if (invariant(n)) {
3959     if (opc == Op_ConvI2L) {
3960       n = n->in(1);
3961       if (n->Opcode() == Op_CastII &&
3962           n->as_CastII()->has_range_check()) {
3963         // Skip range check dependent CastII nodes
3964         assert(invariant(n), "sanity");
3965         n = n->in(1);
3966       }
3967     }
3968     _negate_invar = negate;
3969     _invar = n;
3970     NOT_PRODUCT(_tracer.offset_plus_k_10(n, _invar, _negate_invar, _offset);)
3971     return true;
3972   }
3973 
3974   NOT_PRODUCT(_tracer.offset_plus_k_11(n);)
3975   return false;
3976 }
3977 
3978 //----------------------------print------------------------
3979 void SWPointer::print() {
3980 #ifndef PRODUCT
3981   tty->print("base: %d  adr: %d  scale: %d  offset: %d  invar: %c%d\n",
3982              _base != NULL ? _base->_idx : 0,
3983              _adr  != NULL ? _adr->_idx  : 0,
3984              _scale, _offset,
3985              _negate_invar?'-':'+',
3986              _invar != NULL ? _invar->_idx : 0);
3987 #endif
3988 }
3989 
3990 //----------------------------tracing------------------------
3991 #ifndef PRODUCT
3992 void SWPointer::Tracer::print_depth() {
3993   for (int ii = 0; ii<_depth; ++ii) tty->print("  ");
3994 }
3995 
3996 void SWPointer::Tracer::ctor_1 (Node* mem) {
3997   if(_slp->is_trace_alignment()) {
3998     print_depth(); tty->print(" %d SWPointer::SWPointer: start alignment analysis", mem->_idx); mem->dump();
3999   }
4000 }
4001 
4002 void SWPointer::Tracer::ctor_2(Node* adr) {
4003   if(_slp->is_trace_alignment()) {
4004     //store_depth();
4005     inc_depth();
4006     print_depth(); tty->print(" %d (adr) SWPointer::SWPointer: ", adr->_idx); adr->dump();
4007     inc_depth();
4008     print_depth(); tty->print(" %d (base) SWPointer::SWPointer: ", adr->in(AddPNode::Base)->_idx); adr->in(AddPNode::Base)->dump();
4009   }
4010 }
4011 
4012 void SWPointer::Tracer::ctor_3(Node* adr, int i) {
4013   if(_slp->is_trace_alignment()) {
4014     inc_depth();
4015     Node* offset = adr->in(AddPNode::Offset);
4016     print_depth(); tty->print(" %d (offset) SWPointer::SWPointer: i = %d: ", offset->_idx, i); offset->dump();
4017   }
4018 }
4019 
4020 void SWPointer::Tracer::ctor_4(Node* adr, int i) {
4021   if(_slp->is_trace_alignment()) {
4022     inc_depth();
4023     print_depth(); tty->print(" %d (adr) SWPointer::SWPointer: i = %d: ", adr->_idx, i); adr->dump();
4024   }
4025 }
4026 
4027 void SWPointer::Tracer::ctor_5(Node* adr, Node* base, int i) {
4028   if(_slp->is_trace_alignment()) {
4029     inc_depth();
4030     if (base == adr) {
4031       print_depth(); tty->print_cr("  \\ %d (adr) == %d (base) SWPointer::SWPointer: breaking analysis at i = %d", adr->_idx, base->_idx, i);
4032     } else if (!adr->is_AddP()) {
4033       print_depth(); tty->print_cr("  \\ %d (adr) is NOT Addp SWPointer::SWPointer: breaking analysis at i = %d", adr->_idx, i);
4034     }
4035   }
4036 }
4037 
4038 void SWPointer::Tracer::ctor_6(Node* mem) {
4039   if(_slp->is_trace_alignment()) {
4040     //restore_depth();
4041     print_depth(); tty->print_cr(" %d (adr) SWPointer::SWPointer: stop analysis", mem->_idx);
4042   }
4043 }
4044 
4045 void SWPointer::Tracer::invariant_1(Node *n, Node *n_c) {
4046   if (_slp->do_vector_loop() && _slp->is_debug() && _slp->_lpt->is_member(_slp->_phase->get_loop(n_c)) != (int)_slp->in_bb(n)) {
4047     int is_member =  _slp->_lpt->is_member(_slp->_phase->get_loop(n_c));
4048     int in_bb     =  _slp->in_bb(n);
4049     print_depth(); tty->print("  \\ ");  tty->print_cr(" %d SWPointer::invariant  conditions differ: n_c %d", n->_idx, n_c->_idx);
4050     print_depth(); tty->print("  \\ ");  tty->print_cr("is_member %d, in_bb %d", is_member, in_bb);
4051     print_depth(); tty->print("  \\ ");  n->dump();
4052     print_depth(); tty->print("  \\ ");  n_c->dump();
4053   }
4054 }
4055 
4056 void SWPointer::Tracer::scaled_iv_plus_offset_1(Node* n) {
4057   if(_slp->is_trace_alignment()) {
4058     print_depth(); tty->print(" %d SWPointer::scaled_iv_plus_offset testing node: ", n->_idx);
4059     n->dump();
4060   }
4061 }
4062 
4063 void SWPointer::Tracer::scaled_iv_plus_offset_2(Node* n) {
4064   if(_slp->is_trace_alignment()) {
4065     print_depth(); tty->print_cr(" %d SWPointer::scaled_iv_plus_offset: PASSED", n->_idx);
4066   }
4067 }
4068 
4069 void SWPointer::Tracer::scaled_iv_plus_offset_3(Node* n) {
4070   if(_slp->is_trace_alignment()) {
4071     print_depth(); tty->print_cr(" %d SWPointer::scaled_iv_plus_offset: PASSED", n->_idx);
4072   }
4073 }
4074 
4075 void SWPointer::Tracer::scaled_iv_plus_offset_4(Node* n) {
4076   if(_slp->is_trace_alignment()) {
4077     print_depth(); tty->print_cr(" %d SWPointer::scaled_iv_plus_offset: Op_AddI PASSED", n->_idx);
4078     print_depth(); tty->print("  \\ %d SWPointer::scaled_iv_plus_offset: in(1) is scaled_iv: ", n->in(1)->_idx); n->in(1)->dump();
4079     print_depth(); tty->print("  \\ %d SWPointer::scaled_iv_plus_offset: in(2) is offset_plus_k: ", n->in(2)->_idx); n->in(2)->dump();
4080   }
4081 }
4082 
4083 void SWPointer::Tracer::scaled_iv_plus_offset_5(Node* n) {
4084   if(_slp->is_trace_alignment()) {
4085     print_depth(); tty->print_cr(" %d SWPointer::scaled_iv_plus_offset: Op_AddI PASSED", n->_idx);
4086     print_depth(); tty->print("  \\ %d SWPointer::scaled_iv_plus_offset: in(2) is scaled_iv: ", n->in(2)->_idx); n->in(2)->dump();
4087     print_depth(); tty->print("  \\ %d SWPointer::scaled_iv_plus_offset: in(1) is offset_plus_k: ", n->in(1)->_idx); n->in(1)->dump();
4088   }
4089 }
4090 
4091 void SWPointer::Tracer::scaled_iv_plus_offset_6(Node* n) {
4092   if(_slp->is_trace_alignment()) {
4093     print_depth(); tty->print_cr(" %d SWPointer::scaled_iv_plus_offset: Op_SubI PASSED", n->_idx);
4094     print_depth(); tty->print("  \\  %d SWPointer::scaled_iv_plus_offset: in(1) is scaled_iv: ", n->in(1)->_idx); n->in(1)->dump();
4095     print_depth(); tty->print("  \\ %d SWPointer::scaled_iv_plus_offset: in(2) is offset_plus_k: ", n->in(2)->_idx); n->in(2)->dump();
4096   }
4097 }
4098 
4099 void SWPointer::Tracer::scaled_iv_plus_offset_7(Node* n) {
4100   if(_slp->is_trace_alignment()) {
4101     print_depth(); tty->print_cr(" %d SWPointer::scaled_iv_plus_offset: Op_SubI PASSED", n->_idx);
4102     print_depth(); tty->print("  \\ %d SWPointer::scaled_iv_plus_offset: in(2) is scaled_iv: ", n->in(2)->_idx); n->in(2)->dump();
4103     print_depth(); tty->print("  \\ %d SWPointer::scaled_iv_plus_offset: in(1) is offset_plus_k: ", n->in(1)->_idx); n->in(1)->dump();
4104   }
4105 }
4106 
4107 void SWPointer::Tracer::scaled_iv_plus_offset_8(Node* n) {
4108   if(_slp->is_trace_alignment()) {
4109     print_depth(); tty->print_cr(" %d SWPointer::scaled_iv_plus_offset: FAILED", n->_idx);
4110   }
4111 }
4112 
4113 void SWPointer::Tracer::scaled_iv_1(Node* n) {
4114   if(_slp->is_trace_alignment()) {
4115     print_depth(); tty->print(" %d SWPointer::scaled_iv: testing node: ", n->_idx); n->dump();
4116   }
4117 }
4118 
4119 void SWPointer::Tracer::scaled_iv_2(Node* n, int scale) {
4120   if(_slp->is_trace_alignment()) {
4121     print_depth(); tty->print_cr(" %d SWPointer::scaled_iv: FAILED since another _scale has been detected before", n->_idx);
4122     print_depth(); tty->print_cr("  \\ SWPointer::scaled_iv: _scale (%d) != 0", scale);
4123   }
4124 }
4125 
4126 void SWPointer::Tracer::scaled_iv_3(Node* n, int scale) {
4127   if(_slp->is_trace_alignment()) {
4128     print_depth(); tty->print_cr(" %d SWPointer::scaled_iv: is iv, setting _scale = %d", n->_idx, scale);
4129   }
4130 }
4131 
4132 void SWPointer::Tracer::scaled_iv_4(Node* n, int scale) {
4133   if(_slp->is_trace_alignment()) {
4134     print_depth(); tty->print_cr(" %d SWPointer::scaled_iv: Op_MulI PASSED, setting _scale = %d", n->_idx, scale);
4135     print_depth(); tty->print("  \\ %d SWPointer::scaled_iv: in(1) is iv: ", n->in(1)->_idx); n->in(1)->dump();
4136     print_depth(); tty->print("  \\ %d SWPointer::scaled_iv: in(2) is Con: ", n->in(2)->_idx); n->in(2)->dump();
4137   }
4138 }
4139 
4140 void SWPointer::Tracer::scaled_iv_5(Node* n, int scale) {
4141   if(_slp->is_trace_alignment()) {
4142     print_depth(); tty->print_cr(" %d SWPointer::scaled_iv: Op_MulI PASSED, setting _scale = %d", n->_idx, scale);
4143     print_depth(); tty->print("  \\ %d SWPointer::scaled_iv: in(2) is iv: ", n->in(2)->_idx); n->in(2)->dump();
4144     print_depth(); tty->print("  \\ %d SWPointer::scaled_iv: in(1) is Con: ", n->in(1)->_idx); n->in(1)->dump();
4145   }
4146 }
4147 
4148 void SWPointer::Tracer::scaled_iv_6(Node* n, int scale) {
4149   if(_slp->is_trace_alignment()) {
4150     print_depth(); tty->print_cr(" %d SWPointer::scaled_iv: Op_LShiftI PASSED, setting _scale = %d", n->_idx, scale);
4151     print_depth(); tty->print("  \\ %d SWPointer::scaled_iv: in(1) is iv: ", n->in(1)->_idx); n->in(1)->dump();
4152     print_depth(); tty->print("  \\ %d SWPointer::scaled_iv: in(2) is Con: ", n->in(2)->_idx); n->in(2)->dump();
4153   }
4154 }
4155 
4156 void SWPointer::Tracer::scaled_iv_7(Node* n) {
4157   if(_slp->is_trace_alignment()) {
4158     print_depth(); tty->print_cr(" %d SWPointer::scaled_iv: Op_ConvI2L PASSED", n->_idx);
4159     print_depth(); tty->print_cr("  \\ SWPointer::scaled_iv: in(1) %d is scaled_iv_plus_offset: ", n->in(1)->_idx);
4160     inc_depth(); inc_depth();
4161     print_depth(); n->in(1)->dump();
4162     dec_depth(); dec_depth();
4163   }
4164 }
4165 
4166 void SWPointer::Tracer::scaled_iv_8(Node* n, SWPointer* tmp) {
4167   if(_slp->is_trace_alignment()) {
4168     print_depth(); tty->print(" %d SWPointer::scaled_iv: Op_LShiftL, creating tmp SWPointer: ", n->_idx); tmp->print();
4169   }
4170 }
4171 
4172 void SWPointer::Tracer::scaled_iv_9(Node* n, int scale, int _offset, int mult) {
4173   if(_slp->is_trace_alignment()) {
4174     print_depth(); tty->print_cr(" %d SWPointer::scaled_iv: Op_LShiftL PASSED, setting _scale = %d, _offset = %d", n->_idx, scale, _offset);
4175     print_depth(); tty->print_cr("  \\ SWPointer::scaled_iv: in(1) %d is scaled_iv_plus_offset, in(2) %d used to get mult = %d: _scale = %d, _offset = %d",
4176     n->in(1)->_idx, n->in(2)->_idx, mult, scale, _offset);
4177     inc_depth(); inc_depth();
4178     print_depth(); n->in(1)->dump();
4179     print_depth(); n->in(2)->dump();
4180     dec_depth(); dec_depth();
4181   }
4182 }
4183 
4184 void SWPointer::Tracer::scaled_iv_10(Node* n) {
4185   if(_slp->is_trace_alignment()) {
4186     print_depth(); tty->print_cr(" %d SWPointer::scaled_iv: FAILED", n->_idx);
4187   }
4188 }
4189 
4190 void SWPointer::Tracer::offset_plus_k_1(Node* n) {
4191   if(_slp->is_trace_alignment()) {
4192     print_depth(); tty->print(" %d SWPointer::offset_plus_k: testing node: ", n->_idx); n->dump();
4193   }
4194 }
4195 
4196 void SWPointer::Tracer::offset_plus_k_2(Node* n, int _offset) {
4197   if(_slp->is_trace_alignment()) {
4198     print_depth(); tty->print_cr(" %d SWPointer::offset_plus_k: Op_ConI PASSED, setting _offset = %d", n->_idx, _offset);
4199   }
4200 }
4201 
4202 void SWPointer::Tracer::offset_plus_k_3(Node* n, int _offset) {
4203   if(_slp->is_trace_alignment()) {
4204     print_depth(); tty->print_cr(" %d SWPointer::offset_plus_k: Op_ConL PASSED, setting _offset = %d", n->_idx, _offset);
4205   }
4206 }
4207 
4208 void SWPointer::Tracer::offset_plus_k_4(Node* n) {
4209   if(_slp->is_trace_alignment()) {
4210     print_depth(); tty->print_cr(" %d SWPointer::offset_plus_k: FAILED", n->_idx);
4211     print_depth(); tty->print_cr("  \\ " JLONG_FORMAT " SWPointer::offset_plus_k: Op_ConL FAILED, k is too big", n->get_long());
4212   }
4213 }
4214 
4215 void SWPointer::Tracer::offset_plus_k_5(Node* n, Node* _invar) {
4216   if(_slp->is_trace_alignment()) {
4217     print_depth(); tty->print_cr(" %d SWPointer::offset_plus_k: FAILED since another invariant has been detected before", n->_idx);
4218     print_depth(); tty->print("  \\ %d SWPointer::offset_plus_k: _invar != NULL: ", _invar->_idx); _invar->dump();
4219   }
4220 }
4221 
4222 void SWPointer::Tracer::offset_plus_k_6(Node* n, Node* _invar, bool _negate_invar, int _offset) {
4223   if(_slp->is_trace_alignment()) {
4224     print_depth(); tty->print_cr(" %d SWPointer::offset_plus_k: Op_AddI PASSED, setting _negate_invar = %d, _invar = %d, _offset = %d",
4225     n->_idx, _negate_invar, _invar->_idx, _offset);
4226     print_depth(); tty->print("  \\ %d SWPointer::offset_plus_k: in(2) is Con: ", n->in(2)->_idx); n->in(2)->dump();
4227     print_depth(); tty->print("  \\ %d SWPointer::offset_plus_k: in(1) is invariant: ", _invar->_idx); _invar->dump();
4228   }
4229 }
4230 
4231 void SWPointer::Tracer::offset_plus_k_7(Node* n, Node* _invar, bool _negate_invar, int _offset) {
4232   if(_slp->is_trace_alignment()) {
4233     print_depth(); tty->print_cr(" %d SWPointer::offset_plus_k: Op_AddI PASSED, setting _negate_invar = %d, _invar = %d, _offset = %d",
4234     n->_idx, _negate_invar, _invar->_idx, _offset);
4235     print_depth(); tty->print("  \\ %d SWPointer::offset_plus_k: in(1) is Con: ", n->in(1)->_idx); n->in(1)->dump();
4236     print_depth(); tty->print("  \\ %d SWPointer::offset_plus_k: in(2) is invariant: ", _invar->_idx); _invar->dump();
4237   }
4238 }
4239 
4240 void SWPointer::Tracer::offset_plus_k_8(Node* n, Node* _invar, bool _negate_invar, int _offset) {
4241   if(_slp->is_trace_alignment()) {
4242     print_depth(); tty->print_cr(" %d SWPointer::offset_plus_k: Op_SubI is PASSED, setting _negate_invar = %d, _invar = %d, _offset = %d",
4243     n->_idx, _negate_invar, _invar->_idx, _offset);
4244     print_depth(); tty->print("  \\ %d SWPointer::offset_plus_k: in(2) is Con: ", n->in(2)->_idx); n->in(2)->dump();
4245     print_depth(); tty->print("  \\ %d SWPointer::offset_plus_k: in(1) is invariant: ", _invar->_idx); _invar->dump();
4246   }
4247 }
4248 
4249 void SWPointer::Tracer::offset_plus_k_9(Node* n, Node* _invar, bool _negate_invar, int _offset) {
4250   if(_slp->is_trace_alignment()) {
4251     print_depth(); tty->print_cr(" %d SWPointer::offset_plus_k: Op_SubI PASSED, setting _negate_invar = %d, _invar = %d, _offset = %d", n->_idx, _negate_invar, _invar->_idx, _offset);
4252     print_depth(); tty->print("  \\ %d SWPointer::offset_plus_k: in(1) is Con: ", n->in(1)->_idx); n->in(1)->dump();
4253     print_depth(); tty->print("  \\ %d SWPointer::offset_plus_k: in(2) is invariant: ", _invar->_idx); _invar->dump();
4254   }
4255 }
4256 
4257 void SWPointer::Tracer::offset_plus_k_10(Node* n, Node* _invar, bool _negate_invar, int _offset) {
4258   if(_slp->is_trace_alignment()) {
4259     print_depth(); tty->print_cr(" %d SWPointer::offset_plus_k: PASSED, setting _negate_invar = %d, _invar = %d, _offset = %d", n->_idx, _negate_invar, _invar->_idx, _offset);
4260     print_depth(); tty->print_cr("  \\ %d SWPointer::offset_plus_k: is invariant", n->_idx);
4261   }
4262 }
4263 
4264 void SWPointer::Tracer::offset_plus_k_11(Node* n) {
4265   if(_slp->is_trace_alignment()) {
4266     print_depth(); tty->print_cr(" %d SWPointer::offset_plus_k: FAILED", n->_idx);
4267   }
4268 }
4269 
4270 #endif
4271 // ========================= OrderedPair =====================
4272 
4273 const OrderedPair OrderedPair::initial;
4274 
4275 // ========================= SWNodeInfo =====================
4276 
4277 const SWNodeInfo SWNodeInfo::initial;
4278 
4279 
4280 // ============================ DepGraph ===========================
4281 
4282 //------------------------------make_node---------------------------
4283 // Make a new dependence graph node for an ideal node.
4284 DepMem* DepGraph::make_node(Node* node) {
4285   DepMem* m = new (_arena) DepMem(node);
4286   if (node != NULL) {
4287     assert(_map.at_grow(node->_idx) == NULL, "one init only");
4288     _map.at_put_grow(node->_idx, m);
4289   }
4290   return m;
4291 }
4292 
4293 //------------------------------make_edge---------------------------
4294 // Make a new dependence graph edge from dpred -> dsucc
4295 DepEdge* DepGraph::make_edge(DepMem* dpred, DepMem* dsucc) {
4296   DepEdge* e = new (_arena) DepEdge(dpred, dsucc, dsucc->in_head(), dpred->out_head());
4297   dpred->set_out_head(e);
4298   dsucc->set_in_head(e);
4299   return e;
4300 }
4301 
4302 // ========================== DepMem ========================
4303 
4304 //------------------------------in_cnt---------------------------
4305 int DepMem::in_cnt() {
4306   int ct = 0;
4307   for (DepEdge* e = _in_head; e != NULL; e = e->next_in()) ct++;
4308   return ct;
4309 }
4310 
4311 //------------------------------out_cnt---------------------------
4312 int DepMem::out_cnt() {
4313   int ct = 0;
4314   for (DepEdge* e = _out_head; e != NULL; e = e->next_out()) ct++;
4315   return ct;
4316 }
4317 
4318 //------------------------------print-----------------------------
4319 void DepMem::print() {
4320 #ifndef PRODUCT
4321   tty->print("  DepNode %d (", _node->_idx);
4322   for (DepEdge* p = _in_head; p != NULL; p = p->next_in()) {
4323     Node* pred = p->pred()->node();
4324     tty->print(" %d", pred != NULL ? pred->_idx : 0);
4325   }
4326   tty->print(") [");
4327   for (DepEdge* s = _out_head; s != NULL; s = s->next_out()) {
4328     Node* succ = s->succ()->node();
4329     tty->print(" %d", succ != NULL ? succ->_idx : 0);
4330   }
4331   tty->print_cr(" ]");
4332 #endif
4333 }
4334 
4335 // =========================== DepEdge =========================
4336 
4337 //------------------------------DepPreds---------------------------
4338 void DepEdge::print() {
4339 #ifndef PRODUCT
4340   tty->print_cr("DepEdge: %d [ %d ]", _pred->node()->_idx, _succ->node()->_idx);
4341 #endif
4342 }
4343 
4344 // =========================== DepPreds =========================
4345 // Iterator over predecessor edges in the dependence graph.
4346 
4347 //------------------------------DepPreds---------------------------
4348 DepPreds::DepPreds(Node* n, DepGraph& dg) {
4349   _n = n;
4350   _done = false;
4351   if (_n->is_Store() || _n->is_Load()) {
4352     _next_idx = MemNode::Address;
4353     _end_idx  = n->req();
4354     _dep_next = dg.dep(_n)->in_head();
4355   } else if (_n->is_Mem()) {
4356     _next_idx = 0;
4357     _end_idx  = 0;
4358     _dep_next = dg.dep(_n)->in_head();
4359   } else {
4360     _next_idx = 1;
4361     _end_idx  = _n->req();
4362     _dep_next = NULL;
4363   }
4364   next();
4365 }
4366 
4367 //------------------------------next---------------------------
4368 void DepPreds::next() {
4369   if (_dep_next != NULL) {
4370     _current  = _dep_next->pred()->node();
4371     _dep_next = _dep_next->next_in();
4372   } else if (_next_idx < _end_idx) {
4373     _current  = _n->in(_next_idx++);
4374   } else {
4375     _done = true;
4376   }
4377 }
4378 
4379 // =========================== DepSuccs =========================
4380 // Iterator over successor edges in the dependence graph.
4381 
4382 //------------------------------DepSuccs---------------------------
4383 DepSuccs::DepSuccs(Node* n, DepGraph& dg) {
4384   _n = n;
4385   _done = false;
4386   if (_n->is_Load()) {
4387     _next_idx = 0;
4388     _end_idx  = _n->outcnt();
4389     _dep_next = dg.dep(_n)->out_head();
4390   } else if (_n->is_Mem() || (_n->is_Phi() && _n->bottom_type() == Type::MEMORY)) {
4391     _next_idx = 0;
4392     _end_idx  = 0;
4393     _dep_next = dg.dep(_n)->out_head();
4394   } else {
4395     _next_idx = 0;
4396     _end_idx  = _n->outcnt();
4397     _dep_next = NULL;
4398   }
4399   next();
4400 }
4401 
4402 //-------------------------------next---------------------------
4403 void DepSuccs::next() {
4404   if (_dep_next != NULL) {
4405     _current  = _dep_next->succ()->node();
4406     _dep_next = _dep_next->next_out();
4407   } else if (_next_idx < _end_idx) {
4408     _current  = _n->raw_out(_next_idx++);
4409   } else {
4410     _done = true;
4411   }
4412 }
4413 
4414 //
4415 // --------------------------------- vectorization/simd -----------------------------------
4416 //
4417 bool SuperWord::same_origin_idx(Node* a, Node* b) const {
4418   return a != NULL && b != NULL && _clone_map.same_idx(a->_idx, b->_idx);
4419 }
4420 bool SuperWord::same_generation(Node* a, Node* b) const {
4421   return a != NULL && b != NULL && _clone_map.same_gen(a->_idx, b->_idx);
4422 }
4423 
4424 Node*  SuperWord::find_phi_for_mem_dep(LoadNode* ld) {
4425   assert(in_bb(ld), "must be in block");
4426   if (_clone_map.gen(ld->_idx) == _ii_first) {
4427 #ifndef PRODUCT
4428     if (_vector_loop_debug) {
4429       tty->print_cr("SuperWord::find_phi_for_mem_dep _clone_map.gen(ld->_idx)=%d",
4430         _clone_map.gen(ld->_idx));
4431     }
4432 #endif
4433     return NULL; //we think that any ld in the first gen being vectorizable
4434   }
4435 
4436   Node* mem = ld->in(MemNode::Memory);
4437   if (mem->outcnt() <= 1) {
4438     // we don't want to remove the only edge from mem node to load
4439 #ifndef PRODUCT
4440     if (_vector_loop_debug) {
4441       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",
4442         mem->_idx, ld->_idx);
4443       ld->dump();
4444       mem->dump();
4445     }
4446 #endif
4447     return NULL;
4448   }
4449   if (!in_bb(mem) || same_generation(mem, ld)) {
4450 #ifndef PRODUCT
4451     if (_vector_loop_debug) {
4452       tty->print_cr("SuperWord::find_phi_for_mem_dep _clone_map.gen(mem->_idx)=%d",
4453         _clone_map.gen(mem->_idx));
4454     }
4455 #endif
4456     return NULL; // does not depend on loop volatile node or depends on the same generation
4457   }
4458 
4459   //otherwise first node should depend on mem-phi
4460   Node* first = first_node(ld);
4461   assert(first->is_Load(), "must be Load");
4462   Node* phi = first->as_Load()->in(MemNode::Memory);
4463   if (!phi->is_Phi() || phi->bottom_type() != Type::MEMORY) {
4464 #ifndef PRODUCT
4465     if (_vector_loop_debug) {
4466       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");
4467       ld->dump();
4468       first->dump();
4469     }
4470 #endif
4471     return NULL;
4472   }
4473 
4474   Node* tail = 0;
4475   for (int m = 0; m < _mem_slice_head.length(); m++) {
4476     if (_mem_slice_head.at(m) == phi) {
4477       tail = _mem_slice_tail.at(m);
4478     }
4479   }
4480   if (tail == 0) { //test that found phi is in the list  _mem_slice_head
4481 #ifndef PRODUCT
4482     if (_vector_loop_debug) {
4483       tty->print_cr("SuperWord::find_phi_for_mem_dep load %d is not vectorizable node, its phi %d is not _mem_slice_head",
4484         ld->_idx, phi->_idx);
4485       ld->dump();
4486       phi->dump();
4487     }
4488 #endif
4489     return NULL;
4490   }
4491 
4492   // now all conditions are met
4493   return phi;
4494 }
4495 
4496 Node* SuperWord::first_node(Node* nd) {
4497   for (int ii = 0; ii < _iteration_first.length(); ii++) {
4498     Node* nnn = _iteration_first.at(ii);
4499     if (same_origin_idx(nnn, nd)) {
4500 #ifndef PRODUCT
4501       if (_vector_loop_debug) {
4502         tty->print_cr("SuperWord::first_node: %d is the first iteration node for %d (_clone_map.idx(nnn->_idx) = %d)",
4503           nnn->_idx, nd->_idx, _clone_map.idx(nnn->_idx));
4504       }
4505 #endif
4506       return nnn;
4507     }
4508   }
4509 
4510 #ifndef PRODUCT
4511   if (_vector_loop_debug) {
4512     tty->print_cr("SuperWord::first_node: did not find first iteration node for %d (_clone_map.idx(nd->_idx)=%d)",
4513       nd->_idx, _clone_map.idx(nd->_idx));
4514   }
4515 #endif
4516   return 0;
4517 }
4518 
4519 Node* SuperWord::last_node(Node* nd) {
4520   for (int ii = 0; ii < _iteration_last.length(); ii++) {
4521     Node* nnn = _iteration_last.at(ii);
4522     if (same_origin_idx(nnn, nd)) {
4523 #ifndef PRODUCT
4524       if (_vector_loop_debug) {
4525         tty->print_cr("SuperWord::last_node _clone_map.idx(nnn->_idx)=%d, _clone_map.idx(nd->_idx)=%d",
4526           _clone_map.idx(nnn->_idx), _clone_map.idx(nd->_idx));
4527       }
4528 #endif
4529       return nnn;
4530     }
4531   }
4532   return 0;
4533 }
4534 
4535 int SuperWord::mark_generations() {
4536   Node *ii_err = NULL, *tail_err = NULL;
4537   for (int i = 0; i < _mem_slice_head.length(); i++) {
4538     Node* phi  = _mem_slice_head.at(i);
4539     assert(phi->is_Phi(), "must be phi");
4540 
4541     Node* tail = _mem_slice_tail.at(i);
4542     if (_ii_last == -1) {
4543       tail_err = tail;
4544       _ii_last = _clone_map.gen(tail->_idx);
4545     }
4546     else if (_ii_last != _clone_map.gen(tail->_idx)) {
4547 #ifndef PRODUCT
4548       if (TraceSuperWord && Verbose) {
4549         tty->print_cr("SuperWord::mark_generations _ii_last error - found different generations in two tail nodes ");
4550         tail->dump();
4551         tail_err->dump();
4552       }
4553 #endif
4554       return -1;
4555     }
4556 
4557     // find first iteration in the loop
4558     for (DUIterator_Fast imax, i = phi->fast_outs(imax); i < imax; i++) {
4559       Node* ii = phi->fast_out(i);
4560       if (in_bb(ii) && ii->is_Store()) { // we speculate that normally Stores of one and one only generation have deps from mem phi
4561         if (_ii_first == -1) {
4562           ii_err = ii;
4563           _ii_first = _clone_map.gen(ii->_idx);
4564         } else if (_ii_first != _clone_map.gen(ii->_idx)) {
4565 #ifndef PRODUCT
4566           if (TraceSuperWord && Verbose) {
4567             tty->print_cr("SuperWord::mark_generations: _ii_first was found before and not equal to one in this node (%d)", _ii_first);
4568             ii->dump();
4569             if (ii_err!= 0) {
4570               ii_err->dump();
4571             }
4572           }
4573 #endif
4574           return -1; // this phi has Stores from different generations of unroll and cannot be simd/vectorized
4575         }
4576       }
4577     }//for (DUIterator_Fast imax,
4578   }//for (int i...
4579 
4580   if (_ii_first == -1 || _ii_last == -1) {
4581     if (TraceSuperWord && Verbose) {
4582       tty->print_cr("SuperWord::mark_generations unknown error, something vent wrong");
4583     }
4584     return -1; // something vent wrong
4585   }
4586   // collect nodes in the first and last generations
4587   assert(_iteration_first.length() == 0, "_iteration_first must be empty");
4588   assert(_iteration_last.length() == 0, "_iteration_last must be empty");
4589   for (int j = 0; j < _block.length(); j++) {
4590     Node* n = _block.at(j);
4591     node_idx_t gen = _clone_map.gen(n->_idx);
4592     if ((signed)gen == _ii_first) {
4593       _iteration_first.push(n);
4594     } else if ((signed)gen == _ii_last) {
4595       _iteration_last.push(n);
4596     }
4597   }
4598 
4599   // building order of iterations
4600   if (_ii_order.length() == 0 && ii_err != 0) {
4601     assert(in_bb(ii_err) && ii_err->is_Store(), "should be Store in bb");
4602     Node* nd = ii_err;
4603     while(_clone_map.gen(nd->_idx) != _ii_last) {
4604       _ii_order.push(_clone_map.gen(nd->_idx));
4605       bool found = false;
4606       for (DUIterator_Fast imax, i = nd->fast_outs(imax); i < imax; i++) {
4607         Node* use = nd->fast_out(i);
4608         if (same_origin_idx(use, nd) && use->as_Store()->in(MemNode::Memory) == nd) {
4609           found = true;
4610           nd = use;
4611           break;
4612         }
4613       }//for
4614 
4615       if (found == false) {
4616         if (TraceSuperWord && Verbose) {
4617           tty->print_cr("SuperWord::mark_generations: Cannot build order of iterations - no dependent Store for %d", nd->_idx);
4618         }
4619         _ii_order.clear();
4620         return -1;
4621       }
4622     } //while
4623     _ii_order.push(_clone_map.gen(nd->_idx));
4624   }
4625 
4626 #ifndef PRODUCT
4627   if (_vector_loop_debug) {
4628     tty->print_cr("SuperWord::mark_generations");
4629     tty->print_cr("First generation (%d) nodes:", _ii_first);
4630     for (int ii = 0; ii < _iteration_first.length(); ii++)  _iteration_first.at(ii)->dump();
4631     tty->print_cr("Last generation (%d) nodes:", _ii_last);
4632     for (int ii = 0; ii < _iteration_last.length(); ii++)  _iteration_last.at(ii)->dump();
4633     tty->print_cr(" ");
4634 
4635     tty->print("SuperWord::List of generations: ");
4636     for (int jj = 0; jj < _ii_order.length(); ++jj) {
4637       tty->print("%d:%d ", jj, _ii_order.at(jj));
4638     }
4639     tty->print_cr(" ");
4640   }
4641 #endif
4642 
4643   return _ii_first;
4644 }
4645 
4646 bool SuperWord::fix_commutative_inputs(Node* gold, Node* fix) {
4647   assert(gold->is_Add() && fix->is_Add() || gold->is_Mul() && fix->is_Mul(), "should be only Add or Mul nodes");
4648   assert(same_origin_idx(gold, fix), "should be clones of the same node");
4649   Node* gin1 = gold->in(1);
4650   Node* gin2 = gold->in(2);
4651   Node* fin1 = fix->in(1);
4652   Node* fin2 = fix->in(2);
4653   bool swapped = false;
4654 
4655   if (in_bb(gin1) && in_bb(gin2) && in_bb(fin1) && in_bb(fin1)) {
4656     if (same_origin_idx(gin1, fin1) &&
4657         same_origin_idx(gin2, fin2)) {
4658       return true; // nothing to fix
4659     }
4660     if (same_origin_idx(gin1, fin2) &&
4661         same_origin_idx(gin2, fin1)) {
4662       fix->swap_edges(1, 2);
4663       swapped = true;
4664     }
4665   }
4666   // at least one input comes from outside of bb
4667   if (gin1->_idx == fin1->_idx)  {
4668     return true; // nothing to fix
4669   }
4670   if (!swapped && (gin1->_idx == fin2->_idx || gin2->_idx == fin1->_idx))  { //swapping is expensive, check condition first
4671     fix->swap_edges(1, 2);
4672     swapped = true;
4673   }
4674 
4675   if (swapped) {
4676 #ifndef PRODUCT
4677     if (_vector_loop_debug) {
4678       tty->print_cr("SuperWord::fix_commutative_inputs: fixed node %d", fix->_idx);
4679     }
4680 #endif
4681     return true;
4682   }
4683 
4684   if (TraceSuperWord && Verbose) {
4685     tty->print_cr("SuperWord::fix_commutative_inputs: cannot fix node %d", fix->_idx);
4686   }
4687 
4688   return false;
4689 }
4690 
4691 bool SuperWord::pack_parallel() {
4692 #ifndef PRODUCT
4693   if (_vector_loop_debug) {
4694     tty->print_cr("SuperWord::pack_parallel: START");
4695   }
4696 #endif
4697 
4698   _packset.clear();
4699 
4700   for (int ii = 0; ii < _iteration_first.length(); ii++) {
4701     Node* nd = _iteration_first.at(ii);
4702     if (in_bb(nd) && (nd->is_Load() || nd->is_Store() || nd->is_Add() || nd->is_Mul())) {
4703       Node_List* pk = new Node_List();
4704       pk->push(nd);
4705       for (int gen = 1; gen < _ii_order.length(); ++gen) {
4706         for (int kk = 0; kk < _block.length(); kk++) {
4707           Node* clone = _block.at(kk);
4708           if (same_origin_idx(clone, nd) &&
4709               _clone_map.gen(clone->_idx) == _ii_order.at(gen)) {
4710             if (nd->is_Add() || nd->is_Mul()) {
4711               fix_commutative_inputs(nd, clone);
4712             }
4713             pk->push(clone);
4714             if (pk->size() == 4) {
4715               _packset.append(pk);
4716 #ifndef PRODUCT
4717               if (_vector_loop_debug) {
4718                 tty->print_cr("SuperWord::pack_parallel: added pack ");
4719                 pk->dump();
4720               }
4721 #endif
4722               if (_clone_map.gen(clone->_idx) != _ii_last) {
4723                 pk = new Node_List();
4724               }
4725             }
4726             break;
4727           }
4728         }
4729       }//for
4730     }//if
4731   }//for
4732 
4733 #ifndef PRODUCT
4734   if (_vector_loop_debug) {
4735     tty->print_cr("SuperWord::pack_parallel: END");
4736   }
4737 #endif
4738 
4739   return true;
4740 }
4741 
4742 bool SuperWord::hoist_loads_in_graph() {
4743   GrowableArray<Node*> loads;
4744 
4745 #ifndef PRODUCT
4746   if (_vector_loop_debug) {
4747     tty->print_cr("SuperWord::hoist_loads_in_graph: total number _mem_slice_head.length() = %d", _mem_slice_head.length());
4748   }
4749 #endif
4750 
4751   for (int i = 0; i < _mem_slice_head.length(); i++) {
4752     Node* n = _mem_slice_head.at(i);
4753     if ( !in_bb(n) || !n->is_Phi() || n->bottom_type() != Type::MEMORY) {
4754       if (TraceSuperWord && Verbose) {
4755         tty->print_cr("SuperWord::hoist_loads_in_graph: skipping unexpected node n=%d", n->_idx);
4756       }
4757       continue;
4758     }
4759 
4760 #ifndef PRODUCT
4761     if (_vector_loop_debug) {
4762       tty->print_cr("SuperWord::hoist_loads_in_graph: processing phi %d  = _mem_slice_head.at(%d);", n->_idx, i);
4763     }
4764 #endif
4765 
4766     for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
4767       Node* ld = n->fast_out(i);
4768       if (ld->is_Load() && ld->as_Load()->in(MemNode::Memory) == n && in_bb(ld)) {
4769         for (int i = 0; i < _block.length(); i++) {
4770           Node* ld2 = _block.at(i);
4771           if (ld2->is_Load() && same_origin_idx(ld, ld2) &&
4772               !same_generation(ld, ld2)) { // <= do not collect the first generation ld
4773 #ifndef PRODUCT
4774             if (_vector_loop_debug) {
4775               tty->print_cr("SuperWord::hoist_loads_in_graph: will try to hoist load ld2->_idx=%d, cloned from %d (ld->_idx=%d)",
4776                 ld2->_idx, _clone_map.idx(ld->_idx), ld->_idx);
4777             }
4778 #endif
4779             // could not do on-the-fly, since iterator is immutable
4780             loads.push(ld2);
4781           }
4782         }// for
4783       }//if
4784     }//for (DUIterator_Fast imax,
4785   }//for (int i = 0; i
4786 
4787   for (int i = 0; i < loads.length(); i++) {
4788     LoadNode* ld = loads.at(i)->as_Load();
4789     Node* phi = find_phi_for_mem_dep(ld);
4790     if (phi != NULL) {
4791 #ifndef PRODUCT
4792       if (_vector_loop_debug) {
4793         tty->print_cr("SuperWord::hoist_loads_in_graph replacing MemNode::Memory(%d) edge in %d with one from %d",
4794           MemNode::Memory, ld->_idx, phi->_idx);
4795       }
4796 #endif
4797       _igvn.replace_input_of(ld, MemNode::Memory, phi);
4798     }
4799   }//for
4800 
4801   restart(); // invalidate all basic structures, since we rebuilt the graph
4802 
4803   if (TraceSuperWord && Verbose) {
4804     tty->print_cr("\nSuperWord::hoist_loads_in_graph() the graph was rebuilt, all structures invalidated and need rebuild");
4805   }
4806 
4807   return true;
4808 }