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 #ifndef SHARE_OPTO_SUPERWORD_HPP
25 #define SHARE_OPTO_SUPERWORD_HPP
26 
27 #include "opto/loopnode.hpp"
28 #include "opto/node.hpp"
29 #include "opto/phaseX.hpp"
30 #include "opto/vectornode.hpp"
31 #include "utilities/growableArray.hpp"
32 #include "libadt/dict.hpp"
33 
34 //
35 //                  S U P E R W O R D   T R A N S F O R M
36 //
37 // SuperWords are short, fixed length vectors.
38 //
39 // Algorithm from:
40 //
41 // Exploiting SuperWord Level Parallelism with
42 //   Multimedia Instruction Sets
43 // by
44 //   Samuel Larsen and Saman Amarasinghe
45 //   MIT Laboratory for Computer Science
46 // date
47 //   May 2000
48 // published in
49 //   ACM SIGPLAN Notices
50 //   Proceedings of ACM PLDI '00,  Volume 35 Issue 5
51 //
52 // Definition 3.1 A Pack is an n-tuple, <s1, ...,sn>, where
53 // s1,...,sn are independent isomorphic statements in a basic
54 // block.
55 //
56 // Definition 3.2 A PackSet is a set of Packs.
57 //
58 // Definition 3.3 A Pair is a Pack of size two, where the
59 // first statement is considered the left element, and the
60 // second statement is considered the right element.
61 
62 class SWPointer;
63 class OrderedPair;
64 
65 // ========================= Dependence Graph =====================
66 
67 class DepMem;
68 
69 //------------------------------DepEdge---------------------------
70 // An edge in the dependence graph.  The edges incident to a dependence
71 // node are threaded through _next_in for incoming edges and _next_out
72 // for outgoing edges.
73 class DepEdge : public ResourceObj {
74  protected:
75   DepMem* _pred;
76   DepMem* _succ;
77   DepEdge* _next_in;   // list of in edges, null terminated
78   DepEdge* _next_out;  // list of out edges, null terminated
79 
80  public:
DepEdge(DepMem * pred,DepMem * succ,DepEdge * next_in,DepEdge * next_out)81   DepEdge(DepMem* pred, DepMem* succ, DepEdge* next_in, DepEdge* next_out) :
82     _pred(pred), _succ(succ), _next_in(next_in), _next_out(next_out) {}
83 
next_in()84   DepEdge* next_in()  { return _next_in; }
next_out()85   DepEdge* next_out() { return _next_out; }
pred()86   DepMem*  pred()     { return _pred; }
succ()87   DepMem*  succ()     { return _succ; }
88 
89   void print();
90 };
91 
92 //------------------------------DepMem---------------------------
93 // A node in the dependence graph.  _in_head starts the threaded list of
94 // incoming edges, and _out_head starts the list of outgoing edges.
95 class DepMem : public ResourceObj {
96  protected:
97   Node*    _node;     // Corresponding ideal node
98   DepEdge* _in_head;  // Head of list of in edges, null terminated
99   DepEdge* _out_head; // Head of list of out edges, null terminated
100 
101  public:
DepMem(Node * node)102   DepMem(Node* node) : _node(node), _in_head(NULL), _out_head(NULL) {}
103 
node()104   Node*    node()                { return _node;     }
in_head()105   DepEdge* in_head()             { return _in_head;  }
out_head()106   DepEdge* out_head()            { return _out_head; }
set_in_head(DepEdge * hd)107   void set_in_head(DepEdge* hd)  { _in_head = hd;    }
set_out_head(DepEdge * hd)108   void set_out_head(DepEdge* hd) { _out_head = hd;   }
109 
110   int in_cnt();  // Incoming edge count
111   int out_cnt(); // Outgoing edge count
112 
113   void print();
114 };
115 
116 //------------------------------DepGraph---------------------------
117 class DepGraph {
118  protected:
119   Arena* _arena;
120   GrowableArray<DepMem*> _map;
121   DepMem* _root;
122   DepMem* _tail;
123 
124  public:
DepGraph(Arena * a)125   DepGraph(Arena* a) : _arena(a), _map(a, 8,  0, NULL) {
126     _root = new (_arena) DepMem(NULL);
127     _tail = new (_arena) DepMem(NULL);
128   }
129 
root()130   DepMem* root() { return _root; }
tail()131   DepMem* tail() { return _tail; }
132 
133   // Return dependence node corresponding to an ideal node
dep(Node * node)134   DepMem* dep(Node* node) { return _map.at(node->_idx); }
135 
136   // Make a new dependence graph node for an ideal node.
137   DepMem* make_node(Node* node);
138 
139   // Make a new dependence graph edge dprec->dsucc
140   DepEdge* make_edge(DepMem* dpred, DepMem* dsucc);
141 
make_edge(Node * pred,Node * succ)142   DepEdge* make_edge(Node* pred,   Node* succ)   { return make_edge(dep(pred), dep(succ)); }
make_edge(DepMem * pred,Node * succ)143   DepEdge* make_edge(DepMem* pred, Node* succ)   { return make_edge(pred,      dep(succ)); }
make_edge(Node * pred,DepMem * succ)144   DepEdge* make_edge(Node* pred,   DepMem* succ) { return make_edge(dep(pred), succ);      }
145 
init()146   void init() { _map.clear(); } // initialize
147 
print(Node * n)148   void print(Node* n)   { dep(n)->print(); }
print(DepMem * d)149   void print(DepMem* d) { d->print(); }
150 };
151 
152 //------------------------------DepPreds---------------------------
153 // Iterator over predecessors in the dependence graph and
154 // non-memory-graph inputs of ideal nodes.
155 class DepPreds : public StackObj {
156 private:
157   Node*    _n;
158   int      _next_idx, _end_idx;
159   DepEdge* _dep_next;
160   Node*    _current;
161   bool     _done;
162 
163 public:
164   DepPreds(Node* n, DepGraph& dg);
current()165   Node* current() { return _current; }
done()166   bool  done()    { return _done; }
167   void  next();
168 };
169 
170 //------------------------------DepSuccs---------------------------
171 // Iterator over successors in the dependence graph and
172 // non-memory-graph outputs of ideal nodes.
173 class DepSuccs : public StackObj {
174 private:
175   Node*    _n;
176   int      _next_idx, _end_idx;
177   DepEdge* _dep_next;
178   Node*    _current;
179   bool     _done;
180 
181 public:
182   DepSuccs(Node* n, DepGraph& dg);
current()183   Node* current() { return _current; }
done()184   bool  done()    { return _done; }
185   void  next();
186 };
187 
188 
189 // ========================= SuperWord =====================
190 
191 // -----------------------------SWNodeInfo---------------------------------
192 // Per node info needed by SuperWord
193 class SWNodeInfo {
194  public:
195   int         _alignment; // memory alignment for a node
196   int         _depth;     // Max expression (DAG) depth from block start
197   const Type* _velt_type; // vector element type
198   Node_List*  _my_pack;   // pack containing this node
199 
SWNodeInfo()200   SWNodeInfo() : _alignment(-1), _depth(0), _velt_type(NULL), _my_pack(NULL) {}
201   static const SWNodeInfo initial;
202 };
203 
204 class SuperWord;
205 class CMoveKit {
206  friend class SuperWord;
207  private:
208   SuperWord* _sw;
209   Dict* _dict;
CMoveKit(Arena * a,SuperWord * sw)210   CMoveKit(Arena* a, SuperWord* sw) : _sw(sw)  {_dict = new Dict(cmpkey, hashkey, a);}
_2p(Node * key) const211   void*     _2p(Node* key)        const  { return (void*)(intptr_t)key; } // 2 conversion functions to make gcc happy
dict() const212   Dict*     dict()                const  { return _dict; }
map(Node * key,Node_List * val)213   void map(Node* key, Node_List* val)    { assert(_dict->operator[](_2p(key)) == NULL, "key existed"); _dict->Insert(_2p(key), (void*)val); }
unmap(Node * key)214   void unmap(Node* key)                  { _dict->Delete(_2p(key)); }
pack(Node * key) const215   Node_List* pack(Node* key)      const  { return (Node_List*)_dict->operator[](_2p(key)); }
216   Node* is_Bool_candidate(Node* nd) const; // if it is the right candidate return corresponding CMove* ,
217   Node* is_CmpD_candidate(Node* nd) const; // otherwise return NULL
218   Node_List* make_cmovevd_pack(Node_List* cmovd_pk);
219   bool test_cmpd_pack(Node_List* cmpd_pk, Node_List* cmovd_pk);
220 };//class CMoveKit
221 
222 // JVMCI: OrderedPair is moved up to deal with compilation issues on Windows
223 //------------------------------OrderedPair---------------------------
224 // Ordered pair of Node*.
225 class OrderedPair {
226  protected:
227   Node* _p1;
228   Node* _p2;
229  public:
OrderedPair()230   OrderedPair() : _p1(NULL), _p2(NULL) {}
OrderedPair(Node * p1,Node * p2)231   OrderedPair(Node* p1, Node* p2) {
232     if (p1->_idx < p2->_idx) {
233       _p1 = p1; _p2 = p2;
234     } else {
235       _p1 = p2; _p2 = p1;
236     }
237   }
238 
operator ==(const OrderedPair & rhs)239   bool operator==(const OrderedPair &rhs) {
240     return _p1 == rhs._p1 && _p2 == rhs._p2;
241   }
print()242   void print() { tty->print("  (%d, %d)", _p1->_idx, _p2->_idx); }
243 
244   static const OrderedPair initial;
245 };
246 
247 // -----------------------------SuperWord---------------------------------
248 // Transforms scalar operations into packed (superword) operations.
249 class SuperWord : public ResourceObj {
250  friend class SWPointer;
251  friend class CMoveKit;
252  private:
253   PhaseIdealLoop* _phase;
254   Arena*          _arena;
255   PhaseIterGVN   &_igvn;
256 
257   enum consts { top_align = -1, bottom_align = -666 };
258 
259   GrowableArray<Node_List*> _packset;    // Packs for the current block
260 
261   GrowableArray<int> _bb_idx;            // Map from Node _idx to index within block
262 
263   GrowableArray<Node*> _block;           // Nodes in current block
264   GrowableArray<Node*> _post_block;      // Nodes in post loop block
265   GrowableArray<Node*> _data_entry;      // Nodes with all inputs from outside
266   GrowableArray<Node*> _mem_slice_head;  // Memory slice head nodes
267   GrowableArray<Node*> _mem_slice_tail;  // Memory slice tail nodes
268   GrowableArray<Node*> _iteration_first; // nodes in the generation that has deps from phi
269   GrowableArray<Node*> _iteration_last;  // nodes in the generation that has deps to   phi
270   GrowableArray<SWNodeInfo> _node_info;  // Info needed per node
271   CloneMap&            _clone_map;       // map of nodes created in cloning
272   CMoveKit             _cmovev_kit;      // support for vectorization of CMov
273   MemNode* _align_to_ref;                // Memory reference that pre-loop will align to
274 
275   GrowableArray<OrderedPair> _disjoint_ptrs; // runtime disambiguated pointer pairs
276 
277   DepGraph _dg; // Dependence graph
278 
279   // Scratch pads
280   VectorSet    _visited;       // Visited set
281   VectorSet    _post_visited;  // Post-visited set
282   Node_Stack   _n_idx_list;    // List of (node,index) pairs
283   GrowableArray<Node*> _nlist; // List of nodes
284   GrowableArray<Node*> _stk;   // Stack of nodes
285 
286  public:
287   SuperWord(PhaseIdealLoop* phase);
288 
289   void transform_loop(IdealLoopTree* lpt, bool do_optimization);
290 
291   void unrolling_analysis(int &local_loop_unroll_factor);
292 
293   // Accessors for SWPointer
phase() const294   PhaseIdealLoop* phase() const    { return _phase; }
lpt() const295   IdealLoopTree* lpt() const       { return _lpt; }
iv() const296   PhiNode* iv() const              { return _iv; }
297 
early_return() const298   bool early_return() const        { return _early_return; }
299 
300 #ifndef PRODUCT
is_debug()301   bool     is_debug()              { return _vector_loop_debug > 0; }
is_trace_alignment()302   bool     is_trace_alignment()    { return (_vector_loop_debug & 2) > 0; }
is_trace_mem_slice()303   bool     is_trace_mem_slice()    { return (_vector_loop_debug & 4) > 0; }
is_trace_loop()304   bool     is_trace_loop()         { return (_vector_loop_debug & 8) > 0; }
is_trace_adjacent()305   bool     is_trace_adjacent()     { return (_vector_loop_debug & 16) > 0; }
is_trace_cmov()306   bool     is_trace_cmov()         { return (_vector_loop_debug & 32) > 0; }
is_trace_loop_reverse()307   bool     is_trace_loop_reverse() { return (_vector_loop_debug & 64) > 0; }
308 #endif
do_vector_loop()309   bool     do_vector_loop()        { return _do_vector_loop; }
do_reserve_copy()310   bool     do_reserve_copy()       { return _do_reserve_copy; }
311  private:
312   IdealLoopTree* _lpt;             // Current loop tree node
313   CountedLoopNode* _lp;            // Current CountedLoopNode
314   CountedLoopEndNode* _pre_loop_end; // Current CountedLoopEndNode of pre loop
315   Node*          _bb;              // Current basic block
316   PhiNode*       _iv;              // Induction var
317   bool           _race_possible;   // In cases where SDMU is true
318   bool           _early_return;    // True if we do not initialize
319   bool           _do_vector_loop;  // whether to do vectorization/simd style
320   bool           _do_reserve_copy; // do reserve copy of the graph(loop) before final modification in output
321   int            _num_work_vecs;   // Number of non memory vector operations
322   int            _num_reductions;  // Number of reduction expressions applied
323   int            _ii_first;        // generation with direct deps from mem phi
324   int            _ii_last;         // generation with direct deps to   mem phi
325   GrowableArray<int> _ii_order;
326 #ifndef PRODUCT
327   uintx          _vector_loop_debug; // provide more printing in debug mode
328 #endif
329 
330   // Accessors
arena()331   Arena* arena()                   { return _arena; }
332 
bb()333   Node* bb()                       { return _bb; }
set_bb(Node * bb)334   void set_bb(Node* bb)            { _bb = bb; }
set_lpt(IdealLoopTree * lpt)335   void set_lpt(IdealLoopTree* lpt) { _lpt = lpt; }
lp() const336   CountedLoopNode* lp() const      { return _lp; }
set_lp(CountedLoopNode * lp)337   void set_lp(CountedLoopNode* lp) {
338     _lp = lp;
339     _iv = lp->as_CountedLoop()->phi()->as_Phi();
340   }
iv_stride() const341   int iv_stride() const            { return lp()->stride_con(); }
342 
pre_loop_head() const343   CountedLoopNode* pre_loop_head() const {
344     assert(_pre_loop_end != NULL && _pre_loop_end->loopnode() != NULL, "should find head from pre loop end");
345     return _pre_loop_end->loopnode();
346   }
set_pre_loop_end(CountedLoopEndNode * pre_loop_end)347   void set_pre_loop_end(CountedLoopEndNode* pre_loop_end) {
348     assert(pre_loop_end, "must be valid");
349     _pre_loop_end = pre_loop_end;
350   }
pre_loop_end() const351   CountedLoopEndNode* pre_loop_end() const {
352 #ifdef ASSERT
353     assert(_lp != NULL, "sanity");
354     assert(_pre_loop_end != NULL, "should be set when fetched");
355     Node* found_pre_end = find_pre_loop_end(_lp);
356     assert(_pre_loop_end == found_pre_end && _pre_loop_end == pre_loop_head()->loopexit(),
357            "should find the pre loop end and must be the same result");
358 #endif
359     return _pre_loop_end;
360   }
361 
vector_width(Node * n)362   int vector_width(Node* n) {
363     BasicType bt = velt_basic_type(n);
364     return MIN2(ABS(iv_stride()), Matcher::max_vector_size(bt));
365   }
vector_width_in_bytes(Node * n)366   int vector_width_in_bytes(Node* n) {
367     BasicType bt = velt_basic_type(n);
368     return vector_width(n)*type2aelembytes(bt);
369   }
370   int get_vw_bytes_special(MemNode* s);
align_to_ref()371   MemNode* align_to_ref()            { return _align_to_ref; }
set_align_to_ref(MemNode * m)372   void  set_align_to_ref(MemNode* m) { _align_to_ref = m; }
373 
ctrl(Node * n) const374   Node* ctrl(Node* n) const { return _phase->has_ctrl(n) ? _phase->get_ctrl(n) : n; }
375 
376   // block accessors
in_bb(Node * n)377   bool in_bb(Node* n)      { return n != NULL && n->outcnt() > 0 && ctrl(n) == _bb; }
bb_idx(Node * n)378   int  bb_idx(Node* n)     { assert(in_bb(n), "must be"); return _bb_idx.at(n->_idx); }
set_bb_idx(Node * n,int i)379   void set_bb_idx(Node* n, int i) { _bb_idx.at_put_grow(n->_idx, i); }
380 
381   // visited set accessors
visited_clear()382   void visited_clear()           { _visited.clear(); }
visited_set(Node * n)383   void visited_set(Node* n)      { return _visited.set(bb_idx(n)); }
visited_test(Node * n)384   int visited_test(Node* n)      { return _visited.test(bb_idx(n)); }
visited_test_set(Node * n)385   int visited_test_set(Node* n)  { return _visited.test_set(bb_idx(n)); }
post_visited_clear()386   void post_visited_clear()      { _post_visited.clear(); }
post_visited_set(Node * n)387   void post_visited_set(Node* n) { return _post_visited.set(bb_idx(n)); }
post_visited_test(Node * n)388   int post_visited_test(Node* n) { return _post_visited.test(bb_idx(n)); }
389 
390   // Ensure node_info contains element "i"
grow_node_info(int i)391   void grow_node_info(int i) { if (i >= _node_info.length()) _node_info.at_put_grow(i, SWNodeInfo::initial); }
392 
393   // should we align vector memory references on this platform?
vectors_should_be_aligned()394   bool vectors_should_be_aligned() { return !Matcher::misaligned_vectors_ok() || AlignVector; }
395 
396   // memory alignment for a node
alignment(Node * n)397   int alignment(Node* n)                     { return _node_info.adr_at(bb_idx(n))->_alignment; }
set_alignment(Node * n,int a)398   void set_alignment(Node* n, int a)         { int i = bb_idx(n); grow_node_info(i); _node_info.adr_at(i)->_alignment = a; }
399 
400   // Max expression (DAG) depth from beginning of the block for each node
depth(Node * n)401   int depth(Node* n)                         { return _node_info.adr_at(bb_idx(n))->_depth; }
set_depth(Node * n,int d)402   void set_depth(Node* n, int d)             { int i = bb_idx(n); grow_node_info(i); _node_info.adr_at(i)->_depth = d; }
403 
404   // vector element type
velt_type(Node * n)405   const Type* velt_type(Node* n)             { return _node_info.adr_at(bb_idx(n))->_velt_type; }
velt_basic_type(Node * n)406   BasicType velt_basic_type(Node* n)         { return velt_type(n)->array_element_basic_type(); }
set_velt_type(Node * n,const Type * t)407   void set_velt_type(Node* n, const Type* t) { int i = bb_idx(n); grow_node_info(i); _node_info.adr_at(i)->_velt_type = t; }
408   bool same_velt_type(Node* n1, Node* n2);
409 
410   // my_pack
my_pack(Node * n)411   Node_List* my_pack(Node* n)                 { return !in_bb(n) ? NULL : _node_info.adr_at(bb_idx(n))->_my_pack; }
set_my_pack(Node * n,Node_List * p)412   void set_my_pack(Node* n, Node_List* p)     { int i = bb_idx(n); grow_node_info(i); _node_info.adr_at(i)->_my_pack = p; }
413   // is pack good for converting into one vector node replacing 12 nodes of Cmp, Bool, CMov
414   bool is_cmov_pack(Node_List* p);
is_cmov_pack_internal_node(Node_List * p,Node * nd)415   bool is_cmov_pack_internal_node(Node_List* p, Node* nd) { return is_cmov_pack(p) && !nd->is_CMove(); }
416   // For pack p, are all idx operands the same?
417   bool same_inputs(Node_List* p, int idx);
418   // CloneMap utilities
419   bool same_origin_idx(Node* a, Node* b) const;
420   bool same_generation(Node* a, Node* b) const;
421 
422   // methods
423 
424   // Extract the superword level parallelism
425   void SLP_extract();
426   // Find the adjacent memory references and create pack pairs for them.
427   void find_adjacent_refs();
428   // Tracing support
429   #ifndef PRODUCT
430   void find_adjacent_refs_trace_1(Node* best_align_to_mem_ref, int best_iv_adjustment);
431   void print_loop(bool whole);
432   #endif
433   // Find a memory reference to align the loop induction variable to.
434   MemNode* find_align_to_ref(Node_List &memops, int &idx);
435   // Calculate loop's iv adjustment for this memory ops.
436   int get_iv_adjustment(MemNode* mem);
437   // Can the preloop align the reference to position zero in the vector?
438   bool ref_is_alignable(SWPointer& p);
439   // rebuild the graph so all loads in different iterations of cloned loop become dependant on phi node (in _do_vector_loop only)
440   bool hoist_loads_in_graph();
441   // Test whether MemNode::Memory dependency to the same load but in the first iteration of this loop is coming from memory phi
442   // Return false if failed
443   Node* find_phi_for_mem_dep(LoadNode* ld);
444   // Return same node but from the first generation. Return 0, if not found
445   Node* first_node(Node* nd);
446   // Return same node as this but from the last generation. Return 0, if not found
447   Node* last_node(Node* n);
448   // Mark nodes belonging to first and last generation
449   // returns first generation index or -1 if vectorization/simd is impossible
450   int mark_generations();
451   // swapping inputs of commutative instruction (Add or Mul)
452   bool fix_commutative_inputs(Node* gold, Node* fix);
453   // make packs forcefully (in _do_vector_loop only)
454   bool pack_parallel();
455   // Construct dependency graph.
456   void dependence_graph();
457   // Return a memory slice (node list) in predecessor order starting at "start"
458   void mem_slice_preds(Node* start, Node* stop, GrowableArray<Node*> &preds);
459   // Can s1 and s2 be in a pack with s1 immediately preceding s2 and  s1 aligned at "align"
460   bool stmts_can_pack(Node* s1, Node* s2, int align);
461   // Does s exist in a pack at position pos?
462   bool exists_at(Node* s, uint pos);
463   // Is s1 immediately before s2 in memory?
464   bool are_adjacent_refs(Node* s1, Node* s2);
465   // Are s1 and s2 similar?
466   bool isomorphic(Node* s1, Node* s2);
467   // Is there no data path from s1 to s2 or s2 to s1?
468   bool independent(Node* s1, Node* s2);
469   // For a node pair (s1, s2) which is isomorphic and independent,
470   // do s1 and s2 have similar input edges?
471   bool have_similar_inputs(Node* s1, Node* s2);
472   // Is there a data path between s1 and s2 and both are reductions?
473   bool reduction(Node* s1, Node* s2);
474   // Helper for independent
475   bool independent_path(Node* shallow, Node* deep, uint dp=0);
476   void set_alignment(Node* s1, Node* s2, int align);
477   int data_size(Node* s);
478   // Extend packset by following use->def and def->use links from pack members.
479   void extend_packlist();
480   // Extend the packset by visiting operand definitions of nodes in pack p
481   bool follow_use_defs(Node_List* p);
482   // Extend the packset by visiting uses of nodes in pack p
483   bool follow_def_uses(Node_List* p);
484   // For extended packsets, ordinally arrange uses packset by major component
485   void order_def_uses(Node_List* p);
486   // Estimate the savings from executing s1 and s2 as a pack
487   int est_savings(Node* s1, Node* s2);
488   int adjacent_profit(Node* s1, Node* s2);
489   int pack_cost(int ct);
490   int unpack_cost(int ct);
491   // Combine packs A and B with A.last == B.first into A.first..,A.last,B.second,..B.last
492   void combine_packs();
493   // Construct the map from nodes to packs.
494   void construct_my_pack_map();
495   // Remove packs that are not implemented or not profitable.
496   void filter_packs();
497   // Merge CMoveD into new vector-nodes
498   void merge_packs_to_cmovd();
499   // Adjust the memory graph for the packed operations
500   void schedule();
501   // Remove "current" from its current position in the memory graph and insert
502   // it after the appropriate insert points (lip or uip);
503   void remove_and_insert(MemNode *current, MemNode *prev, MemNode *lip, Node *uip, Unique_Node_List &schd_before);
504   // Within a store pack, schedule stores together by moving out the sandwiched memory ops according
505   // to dependence info; and within a load pack, move loads down to the last executed load.
506   void co_locate_pack(Node_List* p);
507   Node* pick_mem_state(Node_List* pk);
508   Node* find_first_mem_state(Node_List* pk);
509   Node* find_last_mem_state(Node_List* pk, Node* first_mem);
510 
511   // Convert packs into vector node operations
512   void output();
513   // Create a vector operand for the nodes in pack p for operand: in(opd_idx)
514   Node* vector_opd(Node_List* p, int opd_idx);
515   // Can code be generated for pack p?
516   bool implemented(Node_List* p);
517   // For pack p, are all operands and all uses (with in the block) vector?
518   bool profitable(Node_List* p);
519   // If a use of pack p is not a vector use, then replace the use with an extract operation.
520   void insert_extracts(Node_List* p);
521   // Is use->in(u_idx) a vector use?
522   bool is_vector_use(Node* use, int u_idx);
523   // Construct reverse postorder list of block members
524   bool construct_bb();
525   // Initialize per node info
526   void initialize_bb();
527   // Insert n into block after pos
528   void bb_insert_after(Node* n, int pos);
529   // Compute max depth for expressions from beginning of block
530   void compute_max_depth();
531   // Compute necessary vector element type for expressions
532   void compute_vector_element_type();
533   // Are s1 and s2 in a pack pair and ordered as s1,s2?
534   bool in_packset(Node* s1, Node* s2);
535   // Is s in pack p?
536   Node_List* in_pack(Node* s, Node_List* p);
537   // Remove the pack at position pos in the packset
538   void remove_pack_at(int pos);
539   // Return the node executed first in pack p.
540   Node* executed_first(Node_List* p);
541   // Return the node executed last in pack p.
542   Node* executed_last(Node_List* p);
543   static LoadNode::ControlDependency control_dependency(Node_List* p);
544   // Alignment within a vector memory reference
545   int memory_alignment(MemNode* s, int iv_adjust);
546   // (Start, end] half-open range defining which operands are vector
547   void vector_opd_range(Node* n, uint* start, uint* end);
548   // Smallest type containing range of values
549   const Type* container_type(Node* n);
550   // Adjust pre-loop limit so that in main loop, a load/store reference
551   // to align_to_ref will be a position zero in the vector.
552   void align_initial_loop_index(MemNode* align_to_ref);
553   // Find pre loop end from main loop.  Returns null if none.
554   CountedLoopEndNode* find_pre_loop_end(CountedLoopNode *cl) const;
555   // Is the use of d1 in u1 at the same operand position as d2 in u2?
556   bool opnd_positions_match(Node* d1, Node* u1, Node* d2, Node* u2);
557   void init();
558   // clean up some basic structures - used if the ideal graph was rebuilt
559   void restart();
560 
561   // print methods
562   void print_packset();
563   void print_pack(Node_List* p);
564   void print_bb();
565   void print_stmt(Node* s);
566   char* blank(uint depth);
567 
568   void packset_sort(int n);
569 };
570 
571 
572 
573 //------------------------------SWPointer---------------------------
574 // Information about an address for dependence checking and vector alignment
575 class SWPointer {
576  protected:
577   MemNode*   _mem;           // My memory reference node
578   SuperWord* _slp;           // SuperWord class
579 
580   Node* _base;               // NULL if unsafe nonheap reference
581   Node* _adr;                // address pointer
582   int   _scale;              // multiplier for iv (in bytes), 0 if no loop iv
583   int   _offset;             // constant offset (in bytes)
584 
585   Node* _invar;              // invariant offset (in bytes), NULL if none
586   bool  _negate_invar;       // if true then use: (0 - _invar)
587   Node* _invar_scale;        // multiplier for invariant
588 
589   Node_Stack* _nstack;       // stack used to record a swpointer trace of variants
590   bool        _analyze_only; // Used in loop unrolling only for swpointer trace
591   uint        _stack_idx;    // Used in loop unrolling only for swpointer trace
592 
phase() const593   PhaseIdealLoop* phase() const { return _slp->phase(); }
lpt() const594   IdealLoopTree*  lpt() const   { return _slp->lpt(); }
iv() const595   PhiNode*        iv() const    { return _slp->iv();  } // Induction var
596 
597   bool is_main_loop_member(Node* n) const;
598   bool invariant(Node* n) const;
599 
600   // Match: k*iv + offset
601   bool scaled_iv_plus_offset(Node* n);
602   // Match: k*iv where k is a constant that's not zero
603   bool scaled_iv(Node* n);
604   // Match: offset is (k [+/- invariant])
605   bool offset_plus_k(Node* n, bool negate = false);
606 
607  public:
608   enum CMP {
609     Less          = 1,
610     Greater       = 2,
611     Equal         = 4,
612     NotEqual      = (Less | Greater),
613     NotComparable = (Less | Greater | Equal)
614   };
615 
616   SWPointer(MemNode* mem, SuperWord* slp, Node_Stack *nstack, bool analyze_only);
617   // Following is used to create a temporary object during
618   // the pattern match of an address expression.
619   SWPointer(SWPointer* p);
620 
valid()621   bool valid()  { return _adr != NULL; }
has_iv()622   bool has_iv() { return _scale != 0; }
623 
base()624   Node* base()             { return _base; }
adr()625   Node* adr()              { return _adr; }
mem()626   MemNode* mem()           { return _mem; }
scale_in_bytes()627   int   scale_in_bytes()   { return _scale; }
invar()628   Node* invar()            { return _invar; }
negate_invar()629   bool  negate_invar()     { return _negate_invar; }
invar_scale()630   Node* invar_scale()      { return _invar_scale; }
offset_in_bytes()631   int   offset_in_bytes()  { return _offset; }
memory_size()632   int   memory_size()      { return _mem->memory_size(); }
node_stack()633   Node_Stack* node_stack() { return _nstack; }
634 
635   // Comparable?
invar_equals(SWPointer & q)636   bool invar_equals(SWPointer& q) {
637       return (_invar        == q._invar   &&
638               _invar_scale  == q._invar_scale &&
639               _negate_invar == q._negate_invar);
640   }
641 
cmp(SWPointer & q)642   int cmp(SWPointer& q) {
643     if (valid() && q.valid() &&
644         (_adr == q._adr || (_base == _adr && q._base == q._adr)) &&
645         _scale == q._scale   && invar_equals(q)) {
646       bool overlap = q._offset <   _offset +   memory_size() &&
647                        _offset < q._offset + q.memory_size();
648       return overlap ? Equal : (_offset < q._offset ? Less : Greater);
649     } else {
650       return NotComparable;
651     }
652   }
653 
not_equal(SWPointer & q)654   bool not_equal(SWPointer& q)    { return not_equal(cmp(q)); }
equal(SWPointer & q)655   bool equal(SWPointer& q)        { return equal(cmp(q)); }
comparable(SWPointer & q)656   bool comparable(SWPointer& q)   { return comparable(cmp(q)); }
not_equal(int cmp)657   static bool not_equal(int cmp)  { return cmp <= NotEqual; }
equal(int cmp)658   static bool equal(int cmp)      { return cmp == Equal; }
comparable(int cmp)659   static bool comparable(int cmp) { return cmp < NotComparable; }
660 
661   void print();
662 
663 #ifndef PRODUCT
664   class Tracer {
665     friend class SuperWord;
666     friend class SWPointer;
667     SuperWord*   _slp;
668     static int   _depth;
669     int _depth_save;
670     void print_depth() const;
depth() const671     int  depth() const    { return _depth; }
set_depth(int d)672     void set_depth(int d) { _depth = d; }
inc_depth()673     void inc_depth()      { _depth++;}
dec_depth()674     void dec_depth()      { if (_depth > 0) _depth--;}
store_depth()675     void store_depth()    {_depth_save = _depth;}
restore_depth()676     void restore_depth()  {_depth = _depth_save;}
677 
678     class Depth {
679       friend class Tracer;
680       friend class SWPointer;
681       friend class SuperWord;
Depth()682       Depth()  { ++_depth; }
Depth(int x)683       Depth(int x)  { _depth = 0; }
~Depth()684       ~Depth() { if (_depth > 0) --_depth;}
685     };
Tracer(SuperWord * slp)686     Tracer (SuperWord* slp) : _slp(slp) {}
687 
688     // tracing functions
689     void ctor_1(Node* mem);
690     void ctor_2(Node* adr);
691     void ctor_3(Node* adr, int i);
692     void ctor_4(Node* adr, int i);
693     void ctor_5(Node* adr, Node* base,  int i);
694     void ctor_6(Node* mem);
695 
696     void invariant_1(Node *n, Node *n_c) const;
697 
698     void scaled_iv_plus_offset_1(Node* n);
699     void scaled_iv_plus_offset_2(Node* n);
700     void scaled_iv_plus_offset_3(Node* n);
701     void scaled_iv_plus_offset_4(Node* n);
702     void scaled_iv_plus_offset_5(Node* n);
703     void scaled_iv_plus_offset_6(Node* n);
704     void scaled_iv_plus_offset_7(Node* n);
705     void scaled_iv_plus_offset_8(Node* n);
706 
707     void scaled_iv_1(Node* n);
708     void scaled_iv_2(Node* n, int scale);
709     void scaled_iv_3(Node* n, int scale);
710     void scaled_iv_4(Node* n, int scale);
711     void scaled_iv_5(Node* n, int scale);
712     void scaled_iv_6(Node* n, int scale);
713     void scaled_iv_7(Node* n);
714     void scaled_iv_8(Node* n, SWPointer* tmp);
715     void scaled_iv_9(Node* n, int _scale, int _offset, Node* _invar, bool _negate_invar);
716     void scaled_iv_10(Node* n);
717 
718     void offset_plus_k_1(Node* n);
719     void offset_plus_k_2(Node* n, int _offset);
720     void offset_plus_k_3(Node* n, int _offset);
721     void offset_plus_k_4(Node* n);
722     void offset_plus_k_5(Node* n, Node* _invar);
723     void offset_plus_k_6(Node* n, Node* _invar, bool _negate_invar, int _offset);
724     void offset_plus_k_7(Node* n, Node* _invar, bool _negate_invar, int _offset);
725     void offset_plus_k_8(Node* n, Node* _invar, bool _negate_invar, int _offset);
726     void offset_plus_k_9(Node* n, Node* _invar, bool _negate_invar, int _offset);
727     void offset_plus_k_10(Node* n, Node* _invar, bool _negate_invar, int _offset);
728     void offset_plus_k_11(Node* n);
729 
730   } _tracer;//TRacer;
731 #endif
732 };
733 
734 #endif // SHARE_OPTO_SUPERWORD_HPP
735