1 /*
2  * Copyright (c) 2005, 2018, 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 
25 #include "precompiled.hpp"
26 #include "compiler/compileLog.hpp"
27 #include "gc/shared/collectedHeap.inline.hpp"
28 #include "libadt/vectset.hpp"
29 #include "memory/universe.hpp"
30 #include "opto/addnode.hpp"
31 #include "opto/arraycopynode.hpp"
32 #include "opto/callnode.hpp"
33 #include "opto/castnode.hpp"
34 #include "opto/cfgnode.hpp"
35 #include "opto/compile.hpp"
36 #include "opto/convertnode.hpp"
37 #include "opto/graphKit.hpp"
38 #include "opto/locknode.hpp"
39 #include "opto/loopnode.hpp"
40 #include "opto/macro.hpp"
41 #include "opto/memnode.hpp"
42 #include "opto/narrowptrnode.hpp"
43 #include "opto/node.hpp"
44 #include "opto/opaquenode.hpp"
45 #include "opto/phaseX.hpp"
46 #include "opto/rootnode.hpp"
47 #include "opto/runtime.hpp"
48 #include "opto/subnode.hpp"
49 #include "opto/type.hpp"
50 #include "runtime/sharedRuntime.hpp"
51 #include "utilities/macros.hpp"
52 #if INCLUDE_G1GC
53 #include "gc/g1/g1ThreadLocalData.hpp"
54 #endif // INCLUDE_G1GC
55 #if INCLUDE_SHENANDOAHGC
56 #include "gc/shenandoah/c2/shenandoahBarrierSetC2.hpp"
57 #endif
58 
59 
60 //
61 // Replace any references to "oldref" in inputs to "use" with "newref".
62 // Returns the number of replacements made.
63 //
replace_input(Node * use,Node * oldref,Node * newref)64 int PhaseMacroExpand::replace_input(Node *use, Node *oldref, Node *newref) {
65   int nreplacements = 0;
66   uint req = use->req();
67   for (uint j = 0; j < use->len(); j++) {
68     Node *uin = use->in(j);
69     if (uin == oldref) {
70       if (j < req)
71         use->set_req(j, newref);
72       else
73         use->set_prec(j, newref);
74       nreplacements++;
75     } else if (j >= req && uin == NULL) {
76       break;
77     }
78   }
79   return nreplacements;
80 }
81 
copy_call_debug_info(CallNode * oldcall,CallNode * newcall)82 void PhaseMacroExpand::copy_call_debug_info(CallNode *oldcall, CallNode * newcall) {
83   // Copy debug information and adjust JVMState information
84   uint old_dbg_start = oldcall->tf()->domain()->cnt();
85   uint new_dbg_start = newcall->tf()->domain()->cnt();
86   int jvms_adj  = new_dbg_start - old_dbg_start;
87   assert (new_dbg_start == newcall->req(), "argument count mismatch");
88 
89   // SafePointScalarObject node could be referenced several times in debug info.
90   // Use Dict to record cloned nodes.
91   Dict* sosn_map = new Dict(cmpkey,hashkey);
92   for (uint i = old_dbg_start; i < oldcall->req(); i++) {
93     Node* old_in = oldcall->in(i);
94     // Clone old SafePointScalarObjectNodes, adjusting their field contents.
95     if (old_in != NULL && old_in->is_SafePointScalarObject()) {
96       SafePointScalarObjectNode* old_sosn = old_in->as_SafePointScalarObject();
97       uint old_unique = C->unique();
98       Node* new_in = old_sosn->clone(sosn_map);
99       if (old_unique != C->unique()) { // New node?
100         new_in->set_req(0, C->root()); // reset control edge
101         new_in = transform_later(new_in); // Register new node.
102       }
103       old_in = new_in;
104     }
105     newcall->add_req(old_in);
106   }
107 
108   // JVMS may be shared so clone it before we modify it
109   newcall->set_jvms(oldcall->jvms() != NULL ? oldcall->jvms()->clone_deep(C) : NULL);
110   for (JVMState *jvms = newcall->jvms(); jvms != NULL; jvms = jvms->caller()) {
111     jvms->set_map(newcall);
112     jvms->set_locoff(jvms->locoff()+jvms_adj);
113     jvms->set_stkoff(jvms->stkoff()+jvms_adj);
114     jvms->set_monoff(jvms->monoff()+jvms_adj);
115     jvms->set_scloff(jvms->scloff()+jvms_adj);
116     jvms->set_endoff(jvms->endoff()+jvms_adj);
117   }
118 }
119 
opt_bits_test(Node * ctrl,Node * region,int edge,Node * word,int mask,int bits,bool return_fast_path)120 Node* PhaseMacroExpand::opt_bits_test(Node* ctrl, Node* region, int edge, Node* word, int mask, int bits, bool return_fast_path) {
121   Node* cmp;
122   if (mask != 0) {
123     Node* and_node = transform_later(new AndXNode(word, MakeConX(mask)));
124     cmp = transform_later(new CmpXNode(and_node, MakeConX(bits)));
125   } else {
126     cmp = word;
127   }
128   Node* bol = transform_later(new BoolNode(cmp, BoolTest::ne));
129   IfNode* iff = new IfNode( ctrl, bol, PROB_MIN, COUNT_UNKNOWN );
130   transform_later(iff);
131 
132   // Fast path taken.
133   Node *fast_taken = transform_later(new IfFalseNode(iff));
134 
135   // Fast path not-taken, i.e. slow path
136   Node *slow_taken = transform_later(new IfTrueNode(iff));
137 
138   if (return_fast_path) {
139     region->init_req(edge, slow_taken); // Capture slow-control
140     return fast_taken;
141   } else {
142     region->init_req(edge, fast_taken); // Capture fast-control
143     return slow_taken;
144   }
145 }
146 
147 //--------------------copy_predefined_input_for_runtime_call--------------------
copy_predefined_input_for_runtime_call(Node * ctrl,CallNode * oldcall,CallNode * call)148 void PhaseMacroExpand::copy_predefined_input_for_runtime_call(Node * ctrl, CallNode* oldcall, CallNode* call) {
149   // Set fixed predefined input arguments
150   call->init_req( TypeFunc::Control, ctrl );
151   call->init_req( TypeFunc::I_O    , oldcall->in( TypeFunc::I_O) );
152   call->init_req( TypeFunc::Memory , oldcall->in( TypeFunc::Memory ) ); // ?????
153   call->init_req( TypeFunc::ReturnAdr, oldcall->in( TypeFunc::ReturnAdr ) );
154   call->init_req( TypeFunc::FramePtr, oldcall->in( TypeFunc::FramePtr ) );
155 }
156 
157 //------------------------------make_slow_call---------------------------------
make_slow_call(CallNode * oldcall,const TypeFunc * slow_call_type,address slow_call,const char * leaf_name,Node * slow_path,Node * parm0,Node * parm1,Node * parm2)158 CallNode* PhaseMacroExpand::make_slow_call(CallNode *oldcall, const TypeFunc* slow_call_type,
159                                            address slow_call, const char* leaf_name, Node* slow_path,
160                                            Node* parm0, Node* parm1, Node* parm2) {
161 
162   // Slow-path call
163  CallNode *call = leaf_name
164    ? (CallNode*)new CallLeafNode      ( slow_call_type, slow_call, leaf_name, TypeRawPtr::BOTTOM )
165    : (CallNode*)new CallStaticJavaNode( slow_call_type, slow_call, OptoRuntime::stub_name(slow_call), oldcall->jvms()->bci(), TypeRawPtr::BOTTOM );
166 
167   // Slow path call has no side-effects, uses few values
168   copy_predefined_input_for_runtime_call(slow_path, oldcall, call );
169   if (parm0 != NULL)  call->init_req(TypeFunc::Parms+0, parm0);
170   if (parm1 != NULL)  call->init_req(TypeFunc::Parms+1, parm1);
171   if (parm2 != NULL)  call->init_req(TypeFunc::Parms+2, parm2);
172   copy_call_debug_info(oldcall, call);
173   call->set_cnt(PROB_UNLIKELY_MAG(4));  // Same effect as RC_UNCOMMON.
174   _igvn.replace_node(oldcall, call);
175   transform_later(call);
176 
177   return call;
178 }
179 
extract_call_projections(CallNode * call)180 void PhaseMacroExpand::extract_call_projections(CallNode *call) {
181   _fallthroughproj = NULL;
182   _fallthroughcatchproj = NULL;
183   _ioproj_fallthrough = NULL;
184   _ioproj_catchall = NULL;
185   _catchallcatchproj = NULL;
186   _memproj_fallthrough = NULL;
187   _memproj_catchall = NULL;
188   _resproj = NULL;
189   for (DUIterator_Fast imax, i = call->fast_outs(imax); i < imax; i++) {
190     ProjNode *pn = call->fast_out(i)->as_Proj();
191     switch (pn->_con) {
192       case TypeFunc::Control:
193       {
194         // For Control (fallthrough) and I_O (catch_all_index) we have CatchProj -> Catch -> Proj
195         _fallthroughproj = pn;
196         DUIterator_Fast jmax, j = pn->fast_outs(jmax);
197         const Node *cn = pn->fast_out(j);
198         if (cn->is_Catch()) {
199           ProjNode *cpn = NULL;
200           for (DUIterator_Fast kmax, k = cn->fast_outs(kmax); k < kmax; k++) {
201             cpn = cn->fast_out(k)->as_Proj();
202             assert(cpn->is_CatchProj(), "must be a CatchProjNode");
203             if (cpn->_con == CatchProjNode::fall_through_index)
204               _fallthroughcatchproj = cpn;
205             else {
206               assert(cpn->_con == CatchProjNode::catch_all_index, "must be correct index.");
207               _catchallcatchproj = cpn;
208             }
209           }
210         }
211         break;
212       }
213       case TypeFunc::I_O:
214         if (pn->_is_io_use)
215           _ioproj_catchall = pn;
216         else
217           _ioproj_fallthrough = pn;
218         break;
219       case TypeFunc::Memory:
220         if (pn->_is_io_use)
221           _memproj_catchall = pn;
222         else
223           _memproj_fallthrough = pn;
224         break;
225       case TypeFunc::Parms:
226         _resproj = pn;
227         break;
228       default:
229         assert(false, "unexpected projection from allocation node.");
230     }
231   }
232 
233 }
234 
eliminate_gc_barrier(Node * p2x)235 void PhaseMacroExpand::eliminate_gc_barrier(Node* p2x) {
236   BarrierSetC2 *bs = BarrierSet::barrier_set()->barrier_set_c2();
237   bs->eliminate_gc_barrier(this, p2x);
238 }
239 
240 // Search for a memory operation for the specified memory slice.
scan_mem_chain(Node * mem,int alias_idx,int offset,Node * start_mem,Node * alloc,PhaseGVN * phase)241 static Node *scan_mem_chain(Node *mem, int alias_idx, int offset, Node *start_mem, Node *alloc, PhaseGVN *phase) {
242   Node *orig_mem = mem;
243   Node *alloc_mem = alloc->in(TypeFunc::Memory);
244   const TypeOopPtr *tinst = phase->C->get_adr_type(alias_idx)->isa_oopptr();
245   while (true) {
246     if (mem == alloc_mem || mem == start_mem ) {
247       return mem;  // hit one of our sentinels
248     } else if (mem->is_MergeMem()) {
249       mem = mem->as_MergeMem()->memory_at(alias_idx);
250     } else if (mem->is_Proj() && mem->as_Proj()->_con == TypeFunc::Memory) {
251       Node *in = mem->in(0);
252       // we can safely skip over safepoints, calls, locks and membars because we
253       // already know that the object is safe to eliminate.
254       if (in->is_Initialize() && in->as_Initialize()->allocation() == alloc) {
255         return in;
256       } else if (in->is_Call()) {
257         CallNode *call = in->as_Call();
258         if (call->may_modify(tinst, phase)) {
259           assert(call->is_ArrayCopy(), "ArrayCopy is the only call node that doesn't make allocation escape");
260           if (call->as_ArrayCopy()->modifies(offset, offset, phase, false)) {
261             return in;
262           }
263         }
264         mem = in->in(TypeFunc::Memory);
265       } else if (in->is_MemBar()) {
266         ArrayCopyNode* ac = NULL;
267         if (ArrayCopyNode::may_modify(tinst, in->as_MemBar(), phase, ac)) {
268           assert(ac != NULL && ac->is_clonebasic(), "Only basic clone is a non escaping clone");
269           return ac;
270         }
271         mem = in->in(TypeFunc::Memory);
272       } else {
273         assert(false, "unexpected projection");
274       }
275     } else if (mem->is_Store()) {
276       const TypePtr* atype = mem->as_Store()->adr_type();
277       int adr_idx = phase->C->get_alias_index(atype);
278       if (adr_idx == alias_idx) {
279         assert(atype->isa_oopptr(), "address type must be oopptr");
280         int adr_offset = atype->offset();
281         uint adr_iid = atype->is_oopptr()->instance_id();
282         // Array elements references have the same alias_idx
283         // but different offset and different instance_id.
284         if (adr_offset == offset && adr_iid == alloc->_idx)
285           return mem;
286       } else {
287         assert(adr_idx == Compile::AliasIdxRaw, "address must match or be raw");
288       }
289       mem = mem->in(MemNode::Memory);
290     } else if (mem->is_ClearArray()) {
291       if (!ClearArrayNode::step_through(&mem, alloc->_idx, phase)) {
292         // Can not bypass initialization of the instance
293         // we are looking.
294         debug_only(intptr_t offset;)
295         assert(alloc == AllocateNode::Ideal_allocation(mem->in(3), phase, offset), "sanity");
296         InitializeNode* init = alloc->as_Allocate()->initialization();
297         // We are looking for stored value, return Initialize node
298         // or memory edge from Allocate node.
299         if (init != NULL)
300           return init;
301         else
302           return alloc->in(TypeFunc::Memory); // It will produce zero value (see callers).
303       }
304       // Otherwise skip it (the call updated 'mem' value).
305     } else if (mem->Opcode() == Op_SCMemProj) {
306       mem = mem->in(0);
307       Node* adr = NULL;
308       if (mem->is_LoadStore()) {
309         adr = mem->in(MemNode::Address);
310       } else {
311         assert(mem->Opcode() == Op_EncodeISOArray ||
312                mem->Opcode() == Op_StrCompressedCopy, "sanity");
313         adr = mem->in(3); // Destination array
314       }
315       const TypePtr* atype = adr->bottom_type()->is_ptr();
316       int adr_idx = phase->C->get_alias_index(atype);
317       if (adr_idx == alias_idx) {
318         DEBUG_ONLY(mem->dump();)
319         assert(false, "Object is not scalar replaceable if a LoadStore node accesses its field");
320         return NULL;
321       }
322       mem = mem->in(MemNode::Memory);
323    } else if (mem->Opcode() == Op_StrInflatedCopy) {
324       Node* adr = mem->in(3); // Destination array
325       const TypePtr* atype = adr->bottom_type()->is_ptr();
326       int adr_idx = phase->C->get_alias_index(atype);
327       if (adr_idx == alias_idx) {
328         DEBUG_ONLY(mem->dump();)
329         assert(false, "Object is not scalar replaceable if a StrInflatedCopy node accesses its field");
330         return NULL;
331       }
332       mem = mem->in(MemNode::Memory);
333     } else {
334       return mem;
335     }
336     assert(mem != orig_mem, "dead memory loop");
337   }
338 }
339 
340 // Generate loads from source of the arraycopy for fields of
341 // destination needed at a deoptimization point
make_arraycopy_load(ArrayCopyNode * ac,intptr_t offset,Node * ctl,Node * mem,BasicType ft,const Type * ftype,AllocateNode * alloc)342 Node* PhaseMacroExpand::make_arraycopy_load(ArrayCopyNode* ac, intptr_t offset, Node* ctl, Node* mem, BasicType ft, const Type *ftype, AllocateNode *alloc) {
343   BasicType bt = ft;
344   const Type *type = ftype;
345   if (ft == T_NARROWOOP) {
346     bt = T_OBJECT;
347     type = ftype->make_oopptr();
348   }
349   Node* res = NULL;
350   if (ac->is_clonebasic()) {
351     assert(ac->in(ArrayCopyNode::Src) != ac->in(ArrayCopyNode::Dest), "clone source equals destination");
352     Node* base = ac->in(ArrayCopyNode::Src)->in(AddPNode::Base);
353     Node* adr = _igvn.transform(new AddPNode(base, base, MakeConX(offset)));
354     const TypePtr* adr_type = _igvn.type(base)->is_ptr()->add_offset(offset);
355     res = LoadNode::make(_igvn, ctl, mem, adr, adr_type, type, bt, MemNode::unordered, LoadNode::UnknownControl);
356   } else {
357     if (ac->modifies(offset, offset, &_igvn, true)) {
358       assert(ac->in(ArrayCopyNode::Dest) == alloc->result_cast(), "arraycopy destination should be allocation's result");
359       uint shift = exact_log2(type2aelembytes(bt));
360       Node* src_pos = ac->in(ArrayCopyNode::SrcPos);
361       Node* dest_pos = ac->in(ArrayCopyNode::DestPos);
362       const TypeInt* src_pos_t = _igvn.type(src_pos)->is_int();
363       const TypeInt* dest_pos_t = _igvn.type(dest_pos)->is_int();
364 
365       Node* adr = NULL;
366       const TypePtr* adr_type = NULL;
367       if (src_pos_t->is_con() && dest_pos_t->is_con()) {
368         intptr_t off = ((src_pos_t->get_con() - dest_pos_t->get_con()) << shift) + offset;
369         Node* base = ac->in(ArrayCopyNode::Src);
370         adr = _igvn.transform(new AddPNode(base, base, MakeConX(off)));
371         adr_type = _igvn.type(base)->is_ptr()->add_offset(off);
372         if (ac->in(ArrayCopyNode::Src) == ac->in(ArrayCopyNode::Dest)) {
373           // Don't emit a new load from src if src == dst but try to get the value from memory instead
374           return value_from_mem(ac->in(TypeFunc::Memory), ctl, ft, ftype, adr_type->isa_oopptr(), alloc);
375         }
376       } else {
377         Node* diff = _igvn.transform(new SubINode(ac->in(ArrayCopyNode::SrcPos), ac->in(ArrayCopyNode::DestPos)));
378 #ifdef _LP64
379         diff = _igvn.transform(new ConvI2LNode(diff));
380 #endif
381         diff = _igvn.transform(new LShiftXNode(diff, intcon(shift)));
382 
383         Node* off = _igvn.transform(new AddXNode(MakeConX(offset), diff));
384         Node* base = ac->in(ArrayCopyNode::Src);
385         adr = _igvn.transform(new AddPNode(base, base, off));
386         adr_type = _igvn.type(base)->is_ptr()->add_offset(Type::OffsetBot);
387         if (ac->in(ArrayCopyNode::Src) == ac->in(ArrayCopyNode::Dest)) {
388           // Non constant offset in the array: we can't statically
389           // determine the value
390           return NULL;
391         }
392       }
393       res = LoadNode::make(_igvn, ctl, mem, adr, adr_type, type, bt, MemNode::unordered, LoadNode::UnknownControl);
394     }
395   }
396   if (res != NULL) {
397     res = _igvn.transform(res);
398     if (ftype->isa_narrowoop()) {
399       // PhaseMacroExpand::scalar_replacement adds DecodeN nodes
400       res = _igvn.transform(new EncodePNode(res, ftype));
401     }
402     return res;
403   }
404   return NULL;
405 }
406 
407 //
408 // Given a Memory Phi, compute a value Phi containing the values from stores
409 // on the input paths.
410 // Note: this function is recursive, its depth is limited by the "level" argument
411 // Returns the computed Phi, or NULL if it cannot compute it.
value_from_mem_phi(Node * mem,BasicType ft,const Type * phi_type,const TypeOopPtr * adr_t,AllocateNode * alloc,Node_Stack * value_phis,int level)412 Node *PhaseMacroExpand::value_from_mem_phi(Node *mem, BasicType ft, const Type *phi_type, const TypeOopPtr *adr_t, AllocateNode *alloc, Node_Stack *value_phis, int level) {
413   assert(mem->is_Phi(), "sanity");
414   int alias_idx = C->get_alias_index(adr_t);
415   int offset = adr_t->offset();
416   int instance_id = adr_t->instance_id();
417 
418   // Check if an appropriate value phi already exists.
419   Node* region = mem->in(0);
420   for (DUIterator_Fast kmax, k = region->fast_outs(kmax); k < kmax; k++) {
421     Node* phi = region->fast_out(k);
422     if (phi->is_Phi() && phi != mem &&
423         phi->as_Phi()->is_same_inst_field(phi_type, (int)mem->_idx, instance_id, alias_idx, offset)) {
424       return phi;
425     }
426   }
427   // Check if an appropriate new value phi already exists.
428   Node* new_phi = value_phis->find(mem->_idx);
429   if (new_phi != NULL)
430     return new_phi;
431 
432   if (level <= 0) {
433     return NULL; // Give up: phi tree too deep
434   }
435   Node *start_mem = C->start()->proj_out_or_null(TypeFunc::Memory);
436   Node *alloc_mem = alloc->in(TypeFunc::Memory);
437 
438   uint length = mem->req();
439   GrowableArray <Node *> values(length, length, NULL, false);
440 
441   // create a new Phi for the value
442   PhiNode *phi = new PhiNode(mem->in(0), phi_type, NULL, mem->_idx, instance_id, alias_idx, offset);
443   transform_later(phi);
444   value_phis->push(phi, mem->_idx);
445 
446   for (uint j = 1; j < length; j++) {
447     Node *in = mem->in(j);
448     if (in == NULL || in->is_top()) {
449       values.at_put(j, in);
450     } else  {
451       Node *val = scan_mem_chain(in, alias_idx, offset, start_mem, alloc, &_igvn);
452       if (val == start_mem || val == alloc_mem) {
453         // hit a sentinel, return appropriate 0 value
454         values.at_put(j, _igvn.zerocon(ft));
455         continue;
456       }
457       if (val->is_Initialize()) {
458         val = val->as_Initialize()->find_captured_store(offset, type2aelembytes(ft), &_igvn);
459       }
460       if (val == NULL) {
461         return NULL;  // can't find a value on this path
462       }
463       if (val == mem) {
464         values.at_put(j, mem);
465       } else if (val->is_Store()) {
466         Node* n = val->in(MemNode::ValueIn);
467         BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
468         n = bs->step_over_gc_barrier(n);
469         values.at_put(j, n);
470       } else if(val->is_Proj() && val->in(0) == alloc) {
471         values.at_put(j, _igvn.zerocon(ft));
472       } else if (val->is_Phi()) {
473         val = value_from_mem_phi(val, ft, phi_type, adr_t, alloc, value_phis, level-1);
474         if (val == NULL) {
475           return NULL;
476         }
477         values.at_put(j, val);
478       } else if (val->Opcode() == Op_SCMemProj) {
479         assert(val->in(0)->is_LoadStore() ||
480                val->in(0)->Opcode() == Op_EncodeISOArray ||
481                val->in(0)->Opcode() == Op_StrCompressedCopy, "sanity");
482         assert(false, "Object is not scalar replaceable if a LoadStore node accesses its field");
483         return NULL;
484       } else if (val->is_ArrayCopy()) {
485         Node* res = make_arraycopy_load(val->as_ArrayCopy(), offset, val->in(0), val->in(TypeFunc::Memory), ft, phi_type, alloc);
486         if (res == NULL) {
487           return NULL;
488         }
489         values.at_put(j, res);
490       } else {
491 #ifdef ASSERT
492         val->dump();
493         assert(false, "unknown node on this path");
494 #endif
495         return NULL;  // unknown node on this path
496       }
497     }
498   }
499   // Set Phi's inputs
500   for (uint j = 1; j < length; j++) {
501     if (values.at(j) == mem) {
502       phi->init_req(j, phi);
503     } else {
504       phi->init_req(j, values.at(j));
505     }
506   }
507   return phi;
508 }
509 
510 // Search the last value stored into the object's field.
value_from_mem(Node * sfpt_mem,Node * sfpt_ctl,BasicType ft,const Type * ftype,const TypeOopPtr * adr_t,AllocateNode * alloc)511 Node *PhaseMacroExpand::value_from_mem(Node *sfpt_mem, Node *sfpt_ctl, BasicType ft, const Type *ftype, const TypeOopPtr *adr_t, AllocateNode *alloc) {
512   assert(adr_t->is_known_instance_field(), "instance required");
513   int instance_id = adr_t->instance_id();
514   assert((uint)instance_id == alloc->_idx, "wrong allocation");
515 
516   int alias_idx = C->get_alias_index(adr_t);
517   int offset = adr_t->offset();
518   Node *start_mem = C->start()->proj_out_or_null(TypeFunc::Memory);
519   Node *alloc_ctrl = alloc->in(TypeFunc::Control);
520   Node *alloc_mem = alloc->in(TypeFunc::Memory);
521   Arena *a = Thread::current()->resource_area();
522   VectorSet visited(a);
523 
524   bool done = sfpt_mem == alloc_mem;
525   Node *mem = sfpt_mem;
526   while (!done) {
527     if (visited.test_set(mem->_idx)) {
528       return NULL;  // found a loop, give up
529     }
530     mem = scan_mem_chain(mem, alias_idx, offset, start_mem, alloc, &_igvn);
531     if (mem == start_mem || mem == alloc_mem) {
532       done = true;  // hit a sentinel, return appropriate 0 value
533     } else if (mem->is_Initialize()) {
534       mem = mem->as_Initialize()->find_captured_store(offset, type2aelembytes(ft), &_igvn);
535       if (mem == NULL) {
536         done = true; // Something go wrong.
537       } else if (mem->is_Store()) {
538         const TypePtr* atype = mem->as_Store()->adr_type();
539         assert(C->get_alias_index(atype) == Compile::AliasIdxRaw, "store is correct memory slice");
540         done = true;
541       }
542     } else if (mem->is_Store()) {
543       const TypeOopPtr* atype = mem->as_Store()->adr_type()->isa_oopptr();
544       assert(atype != NULL, "address type must be oopptr");
545       assert(C->get_alias_index(atype) == alias_idx &&
546              atype->is_known_instance_field() && atype->offset() == offset &&
547              atype->instance_id() == instance_id, "store is correct memory slice");
548       done = true;
549     } else if (mem->is_Phi()) {
550       // try to find a phi's unique input
551       Node *unique_input = NULL;
552       Node *top = C->top();
553       for (uint i = 1; i < mem->req(); i++) {
554         Node *n = scan_mem_chain(mem->in(i), alias_idx, offset, start_mem, alloc, &_igvn);
555         if (n == NULL || n == top || n == mem) {
556           continue;
557         } else if (unique_input == NULL) {
558           unique_input = n;
559         } else if (unique_input != n) {
560           unique_input = top;
561           break;
562         }
563       }
564       if (unique_input != NULL && unique_input != top) {
565         mem = unique_input;
566       } else {
567         done = true;
568       }
569     } else if (mem->is_ArrayCopy()) {
570       done = true;
571     } else {
572       assert(false, "unexpected node");
573     }
574   }
575   if (mem != NULL) {
576     if (mem == start_mem || mem == alloc_mem) {
577       // hit a sentinel, return appropriate 0 value
578       return _igvn.zerocon(ft);
579     } else if (mem->is_Store()) {
580       Node* n = mem->in(MemNode::ValueIn);
581       BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
582       n = bs->step_over_gc_barrier(n);
583       return n;
584     } else if (mem->is_Phi()) {
585       // attempt to produce a Phi reflecting the values on the input paths of the Phi
586       Node_Stack value_phis(a, 8);
587       Node * phi = value_from_mem_phi(mem, ft, ftype, adr_t, alloc, &value_phis, ValueSearchLimit);
588       if (phi != NULL) {
589         return phi;
590       } else {
591         // Kill all new Phis
592         while(value_phis.is_nonempty()) {
593           Node* n = value_phis.node();
594           _igvn.replace_node(n, C->top());
595           value_phis.pop();
596         }
597       }
598     } else if (mem->is_ArrayCopy()) {
599       Node* ctl = mem->in(0);
600       Node* m = mem->in(TypeFunc::Memory);
601       if (sfpt_ctl->is_Proj() && sfpt_ctl->as_Proj()->is_uncommon_trap_proj(Deoptimization::Reason_none)) {
602         // pin the loads in the uncommon trap path
603         ctl = sfpt_ctl;
604         m = sfpt_mem;
605       }
606       return make_arraycopy_load(mem->as_ArrayCopy(), offset, ctl, m, ft, ftype, alloc);
607     }
608   }
609   // Something go wrong.
610   return NULL;
611 }
612 
613 // Check the possibility of scalar replacement.
can_eliminate_allocation(AllocateNode * alloc,GrowableArray<SafePointNode * > & safepoints)614 bool PhaseMacroExpand::can_eliminate_allocation(AllocateNode *alloc, GrowableArray <SafePointNode *>& safepoints) {
615   //  Scan the uses of the allocation to check for anything that would
616   //  prevent us from eliminating it.
617   NOT_PRODUCT( const char* fail_eliminate = NULL; )
618   DEBUG_ONLY( Node* disq_node = NULL; )
619   bool  can_eliminate = true;
620 
621   Node* res = alloc->result_cast();
622   const TypeOopPtr* res_type = NULL;
623   if (res == NULL) {
624     // All users were eliminated.
625   } else if (!res->is_CheckCastPP()) {
626     NOT_PRODUCT(fail_eliminate = "Allocation does not have unique CheckCastPP";)
627     can_eliminate = false;
628   } else {
629     res_type = _igvn.type(res)->isa_oopptr();
630     if (res_type == NULL) {
631       NOT_PRODUCT(fail_eliminate = "Neither instance or array allocation";)
632       can_eliminate = false;
633     } else if (res_type->isa_aryptr()) {
634       int length = alloc->in(AllocateNode::ALength)->find_int_con(-1);
635       if (length < 0) {
636         NOT_PRODUCT(fail_eliminate = "Array's size is not constant";)
637         can_eliminate = false;
638       }
639     }
640   }
641 
642   if (can_eliminate && res != NULL) {
643     for (DUIterator_Fast jmax, j = res->fast_outs(jmax);
644                                j < jmax && can_eliminate; j++) {
645       Node* use = res->fast_out(j);
646 
647       if (use->is_AddP()) {
648         const TypePtr* addp_type = _igvn.type(use)->is_ptr();
649         int offset = addp_type->offset();
650 
651         if (offset == Type::OffsetTop || offset == Type::OffsetBot) {
652           NOT_PRODUCT(fail_eliminate = "Undefined field referrence";)
653           can_eliminate = false;
654           break;
655         }
656         for (DUIterator_Fast kmax, k = use->fast_outs(kmax);
657                                    k < kmax && can_eliminate; k++) {
658           Node* n = use->fast_out(k);
659           if (!n->is_Store() && n->Opcode() != Op_CastP2X &&
660               SHENANDOAHGC_ONLY((!UseShenandoahGC || !ShenandoahBarrierSetC2::is_shenandoah_wb_pre_call(n)) &&)
661               !(n->is_ArrayCopy() &&
662                 n->as_ArrayCopy()->is_clonebasic() &&
663                 n->in(ArrayCopyNode::Dest) == use)) {
664             DEBUG_ONLY(disq_node = n;)
665             if (n->is_Load() || n->is_LoadStore()) {
666               NOT_PRODUCT(fail_eliminate = "Field load";)
667             } else {
668               NOT_PRODUCT(fail_eliminate = "Not store field referrence";)
669             }
670             can_eliminate = false;
671           }
672         }
673       } else if (use->is_ArrayCopy() &&
674                  (use->as_ArrayCopy()->is_arraycopy_validated() ||
675                   use->as_ArrayCopy()->is_copyof_validated() ||
676                   use->as_ArrayCopy()->is_copyofrange_validated()) &&
677                  use->in(ArrayCopyNode::Dest) == res) {
678         // ok to eliminate
679       } else if (use->is_SafePoint()) {
680         SafePointNode* sfpt = use->as_SafePoint();
681         if (sfpt->is_Call() && sfpt->as_Call()->has_non_debug_use(res)) {
682           // Object is passed as argument.
683           DEBUG_ONLY(disq_node = use;)
684           NOT_PRODUCT(fail_eliminate = "Object is passed as argument";)
685           can_eliminate = false;
686         }
687         Node* sfptMem = sfpt->memory();
688         if (sfptMem == NULL || sfptMem->is_top()) {
689           DEBUG_ONLY(disq_node = use;)
690           NOT_PRODUCT(fail_eliminate = "NULL or TOP memory";)
691           can_eliminate = false;
692         } else {
693           safepoints.append_if_missing(sfpt);
694         }
695       } else if (use->Opcode() != Op_CastP2X) { // CastP2X is used by card mark
696         if (use->is_Phi()) {
697           if (use->outcnt() == 1 && use->unique_out()->Opcode() == Op_Return) {
698             NOT_PRODUCT(fail_eliminate = "Object is return value";)
699           } else {
700             NOT_PRODUCT(fail_eliminate = "Object is referenced by Phi";)
701           }
702           DEBUG_ONLY(disq_node = use;)
703         } else {
704           if (use->Opcode() == Op_Return) {
705             NOT_PRODUCT(fail_eliminate = "Object is return value";)
706           }else {
707             NOT_PRODUCT(fail_eliminate = "Object is referenced by node";)
708           }
709           DEBUG_ONLY(disq_node = use;)
710         }
711         can_eliminate = false;
712       }
713     }
714   }
715 
716 #ifndef PRODUCT
717   if (PrintEliminateAllocations) {
718     if (can_eliminate) {
719       tty->print("Scalar ");
720       if (res == NULL)
721         alloc->dump();
722       else
723         res->dump();
724     } else if (alloc->_is_scalar_replaceable) {
725       tty->print("NotScalar (%s)", fail_eliminate);
726       if (res == NULL)
727         alloc->dump();
728       else
729         res->dump();
730 #ifdef ASSERT
731       if (disq_node != NULL) {
732           tty->print("  >>>> ");
733           disq_node->dump();
734       }
735 #endif /*ASSERT*/
736     }
737   }
738 #endif
739   return can_eliminate;
740 }
741 
742 // Do scalar replacement.
scalar_replacement(AllocateNode * alloc,GrowableArray<SafePointNode * > & safepoints)743 bool PhaseMacroExpand::scalar_replacement(AllocateNode *alloc, GrowableArray <SafePointNode *>& safepoints) {
744   GrowableArray <SafePointNode *> safepoints_done;
745 
746   ciKlass* klass = NULL;
747   ciInstanceKlass* iklass = NULL;
748   int nfields = 0;
749   int array_base = 0;
750   int element_size = 0;
751   BasicType basic_elem_type = T_ILLEGAL;
752   ciType* elem_type = NULL;
753 
754   Node* res = alloc->result_cast();
755   assert(res == NULL || res->is_CheckCastPP(), "unexpected AllocateNode result");
756   const TypeOopPtr* res_type = NULL;
757   if (res != NULL) { // Could be NULL when there are no users
758     res_type = _igvn.type(res)->isa_oopptr();
759   }
760 
761   if (res != NULL) {
762     klass = res_type->klass();
763     if (res_type->isa_instptr()) {
764       // find the fields of the class which will be needed for safepoint debug information
765       assert(klass->is_instance_klass(), "must be an instance klass.");
766       iklass = klass->as_instance_klass();
767       nfields = iklass->nof_nonstatic_fields();
768     } else {
769       // find the array's elements which will be needed for safepoint debug information
770       nfields = alloc->in(AllocateNode::ALength)->find_int_con(-1);
771       assert(klass->is_array_klass() && nfields >= 0, "must be an array klass.");
772       elem_type = klass->as_array_klass()->element_type();
773       basic_elem_type = elem_type->basic_type();
774       array_base = arrayOopDesc::base_offset_in_bytes(basic_elem_type);
775       element_size = type2aelembytes(basic_elem_type);
776     }
777   }
778   //
779   // Process the safepoint uses
780   //
781   while (safepoints.length() > 0) {
782     SafePointNode* sfpt = safepoints.pop();
783     Node* mem = sfpt->memory();
784     Node* ctl = sfpt->control();
785     assert(sfpt->jvms() != NULL, "missed JVMS");
786     // Fields of scalar objs are referenced only at the end
787     // of regular debuginfo at the last (youngest) JVMS.
788     // Record relative start index.
789     uint first_ind = (sfpt->req() - sfpt->jvms()->scloff());
790     SafePointScalarObjectNode* sobj = new SafePointScalarObjectNode(res_type,
791 #ifdef ASSERT
792                                                  alloc,
793 #endif
794                                                  first_ind, nfields);
795     sobj->init_req(0, C->root());
796     transform_later(sobj);
797 
798     // Scan object's fields adding an input to the safepoint for each field.
799     for (int j = 0; j < nfields; j++) {
800       intptr_t offset;
801       ciField* field = NULL;
802       if (iklass != NULL) {
803         field = iklass->nonstatic_field_at(j);
804         offset = field->offset();
805         elem_type = field->type();
806         basic_elem_type = field->layout_type();
807       } else {
808         offset = array_base + j * (intptr_t)element_size;
809       }
810 
811       const Type *field_type;
812       // The next code is taken from Parse::do_get_xxx().
813       if (basic_elem_type == T_OBJECT || basic_elem_type == T_ARRAY) {
814         if (!elem_type->is_loaded()) {
815           field_type = TypeInstPtr::BOTTOM;
816         } else if (field != NULL && field->is_static_constant()) {
817           // This can happen if the constant oop is non-perm.
818           ciObject* con = field->constant_value().as_object();
819           // Do not "join" in the previous type; it doesn't add value,
820           // and may yield a vacuous result if the field is of interface type.
821           field_type = TypeOopPtr::make_from_constant(con)->isa_oopptr();
822           assert(field_type != NULL, "field singleton type must be consistent");
823         } else {
824           field_type = TypeOopPtr::make_from_klass(elem_type->as_klass());
825         }
826         if (UseCompressedOops) {
827           field_type = field_type->make_narrowoop();
828           basic_elem_type = T_NARROWOOP;
829         }
830       } else {
831         field_type = Type::get_const_basic_type(basic_elem_type);
832       }
833 
834       const TypeOopPtr *field_addr_type = res_type->add_offset(offset)->isa_oopptr();
835 
836       Node *field_val = value_from_mem(mem, ctl, basic_elem_type, field_type, field_addr_type, alloc);
837       if (field_val == NULL) {
838         // We weren't able to find a value for this field,
839         // give up on eliminating this allocation.
840 
841         // Remove any extra entries we added to the safepoint.
842         uint last = sfpt->req() - 1;
843         for (int k = 0;  k < j; k++) {
844           sfpt->del_req(last--);
845         }
846         _igvn._worklist.push(sfpt);
847         // rollback processed safepoints
848         while (safepoints_done.length() > 0) {
849           SafePointNode* sfpt_done = safepoints_done.pop();
850           // remove any extra entries we added to the safepoint
851           last = sfpt_done->req() - 1;
852           for (int k = 0;  k < nfields; k++) {
853             sfpt_done->del_req(last--);
854           }
855           JVMState *jvms = sfpt_done->jvms();
856           jvms->set_endoff(sfpt_done->req());
857           // Now make a pass over the debug information replacing any references
858           // to SafePointScalarObjectNode with the allocated object.
859           int start = jvms->debug_start();
860           int end   = jvms->debug_end();
861           for (int i = start; i < end; i++) {
862             if (sfpt_done->in(i)->is_SafePointScalarObject()) {
863               SafePointScalarObjectNode* scobj = sfpt_done->in(i)->as_SafePointScalarObject();
864               if (scobj->first_index(jvms) == sfpt_done->req() &&
865                   scobj->n_fields() == (uint)nfields) {
866                 assert(scobj->alloc() == alloc, "sanity");
867                 sfpt_done->set_req(i, res);
868               }
869             }
870           }
871           _igvn._worklist.push(sfpt_done);
872         }
873 #ifndef PRODUCT
874         if (PrintEliminateAllocations) {
875           if (field != NULL) {
876             tty->print("=== At SafePoint node %d can't find value of Field: ",
877                        sfpt->_idx);
878             field->print();
879             int field_idx = C->get_alias_index(field_addr_type);
880             tty->print(" (alias_idx=%d)", field_idx);
881           } else { // Array's element
882             tty->print("=== At SafePoint node %d can't find value of array element [%d]",
883                        sfpt->_idx, j);
884           }
885           tty->print(", which prevents elimination of: ");
886           if (res == NULL)
887             alloc->dump();
888           else
889             res->dump();
890         }
891 #endif
892         return false;
893       }
894       if (UseCompressedOops && field_type->isa_narrowoop()) {
895         // Enable "DecodeN(EncodeP(Allocate)) --> Allocate" transformation
896         // to be able scalar replace the allocation.
897         if (field_val->is_EncodeP()) {
898           field_val = field_val->in(1);
899         } else {
900           field_val = transform_later(new DecodeNNode(field_val, field_val->get_ptr_type()));
901         }
902       }
903       sfpt->add_req(field_val);
904     }
905     JVMState *jvms = sfpt->jvms();
906     jvms->set_endoff(sfpt->req());
907     // Now make a pass over the debug information replacing any references
908     // to the allocated object with "sobj"
909     int start = jvms->debug_start();
910     int end   = jvms->debug_end();
911     sfpt->replace_edges_in_range(res, sobj, start, end);
912     _igvn._worklist.push(sfpt);
913     safepoints_done.append_if_missing(sfpt); // keep it for rollback
914   }
915   return true;
916 }
917 
disconnect_projections(MultiNode * n,PhaseIterGVN & igvn)918 static void disconnect_projections(MultiNode* n, PhaseIterGVN& igvn) {
919   Node* ctl_proj = n->proj_out_or_null(TypeFunc::Control);
920   Node* mem_proj = n->proj_out_or_null(TypeFunc::Memory);
921   if (ctl_proj != NULL) {
922     igvn.replace_node(ctl_proj, n->in(0));
923   }
924   if (mem_proj != NULL) {
925     igvn.replace_node(mem_proj, n->in(TypeFunc::Memory));
926   }
927 }
928 
929 // Process users of eliminated allocation.
process_users_of_allocation(CallNode * alloc)930 void PhaseMacroExpand::process_users_of_allocation(CallNode *alloc) {
931   Node* res = alloc->result_cast();
932   if (res != NULL) {
933     for (DUIterator_Last jmin, j = res->last_outs(jmin); j >= jmin; ) {
934       Node *use = res->last_out(j);
935       uint oc1 = res->outcnt();
936 
937       if (use->is_AddP()) {
938         for (DUIterator_Last kmin, k = use->last_outs(kmin); k >= kmin; ) {
939           Node *n = use->last_out(k);
940           uint oc2 = use->outcnt();
941           if (n->is_Store()) {
942 #ifdef ASSERT
943             // Verify that there is no dependent MemBarVolatile nodes,
944             // they should be removed during IGVN, see MemBarNode::Ideal().
945             for (DUIterator_Fast pmax, p = n->fast_outs(pmax);
946                                        p < pmax; p++) {
947               Node* mb = n->fast_out(p);
948               assert(mb->is_Initialize() || !mb->is_MemBar() ||
949                      mb->req() <= MemBarNode::Precedent ||
950                      mb->in(MemBarNode::Precedent) != n,
951                      "MemBarVolatile should be eliminated for non-escaping object");
952             }
953 #endif
954             _igvn.replace_node(n, n->in(MemNode::Memory));
955           } else if (n->is_ArrayCopy()) {
956             // Disconnect ArrayCopy node
957             ArrayCopyNode* ac = n->as_ArrayCopy();
958             assert(ac->is_clonebasic(), "unexpected array copy kind");
959             Node* membar_after = ac->proj_out(TypeFunc::Control)->unique_ctrl_out();
960             disconnect_projections(ac, _igvn);
961             assert(alloc->in(0)->is_Proj() && alloc->in(0)->in(0)->Opcode() == Op_MemBarCPUOrder, "mem barrier expected before allocation");
962             Node* membar_before = alloc->in(0)->in(0);
963             disconnect_projections(membar_before->as_MemBar(), _igvn);
964             if (membar_after->is_MemBar()) {
965               disconnect_projections(membar_after->as_MemBar(), _igvn);
966             }
967           } else {
968             eliminate_gc_barrier(n);
969           }
970           k -= (oc2 - use->outcnt());
971         }
972         _igvn.remove_dead_node(use);
973       } else if (use->is_ArrayCopy()) {
974         // Disconnect ArrayCopy node
975         ArrayCopyNode* ac = use->as_ArrayCopy();
976         assert(ac->is_arraycopy_validated() ||
977                ac->is_copyof_validated() ||
978                ac->is_copyofrange_validated(), "unsupported");
979         CallProjections callprojs;
980         ac->extract_projections(&callprojs, true);
981 
982         _igvn.replace_node(callprojs.fallthrough_ioproj, ac->in(TypeFunc::I_O));
983         _igvn.replace_node(callprojs.fallthrough_memproj, ac->in(TypeFunc::Memory));
984         _igvn.replace_node(callprojs.fallthrough_catchproj, ac->in(TypeFunc::Control));
985 
986         // Set control to top. IGVN will remove the remaining projections
987         ac->set_req(0, top());
988         ac->replace_edge(res, top());
989 
990         // Disconnect src right away: it can help find new
991         // opportunities for allocation elimination
992         Node* src = ac->in(ArrayCopyNode::Src);
993         ac->replace_edge(src, top());
994         // src can be top at this point if src and dest of the
995         // arraycopy were the same
996         if (src->outcnt() == 0 && !src->is_top()) {
997           _igvn.remove_dead_node(src);
998         }
999 
1000         _igvn._worklist.push(ac);
1001       } else {
1002         eliminate_gc_barrier(use);
1003       }
1004       j -= (oc1 - res->outcnt());
1005     }
1006     assert(res->outcnt() == 0, "all uses of allocated objects must be deleted");
1007     _igvn.remove_dead_node(res);
1008   }
1009 
1010   //
1011   // Process other users of allocation's projections
1012   //
1013   if (_resproj != NULL && _resproj->outcnt() != 0) {
1014     // First disconnect stores captured by Initialize node.
1015     // If Initialize node is eliminated first in the following code,
1016     // it will kill such stores and DUIterator_Last will assert.
1017     for (DUIterator_Fast jmax, j = _resproj->fast_outs(jmax);  j < jmax; j++) {
1018       Node *use = _resproj->fast_out(j);
1019       if (use->is_AddP()) {
1020         // raw memory addresses used only by the initialization
1021         _igvn.replace_node(use, C->top());
1022         --j; --jmax;
1023       }
1024     }
1025     for (DUIterator_Last jmin, j = _resproj->last_outs(jmin); j >= jmin; ) {
1026       Node *use = _resproj->last_out(j);
1027       uint oc1 = _resproj->outcnt();
1028       if (use->is_Initialize()) {
1029         // Eliminate Initialize node.
1030         InitializeNode *init = use->as_Initialize();
1031         assert(init->outcnt() <= 2, "only a control and memory projection expected");
1032         Node *ctrl_proj = init->proj_out_or_null(TypeFunc::Control);
1033         if (ctrl_proj != NULL) {
1034           _igvn.replace_node(ctrl_proj, init->in(TypeFunc::Control));
1035 #ifdef ASSERT
1036           BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
1037           Node* tmp = init->in(TypeFunc::Control);
1038           while (bs->is_gc_barrier_node(tmp)) {
1039             Node* tmp2 = bs->step_over_gc_barrier_ctrl(tmp);
1040             assert(tmp != tmp2, "Must make progress");
1041             tmp = tmp2;
1042           }
1043           assert(tmp == _fallthroughcatchproj, "allocation control projection");
1044 #endif
1045         }
1046         Node *mem_proj = init->proj_out_or_null(TypeFunc::Memory);
1047         if (mem_proj != NULL) {
1048           Node *mem = init->in(TypeFunc::Memory);
1049 #ifdef ASSERT
1050           if (mem->is_MergeMem()) {
1051             assert(mem->in(TypeFunc::Memory) == _memproj_fallthrough, "allocation memory projection");
1052           } else {
1053             assert(mem == _memproj_fallthrough, "allocation memory projection");
1054           }
1055 #endif
1056           _igvn.replace_node(mem_proj, mem);
1057         }
1058       } else  {
1059         assert(false, "only Initialize or AddP expected");
1060       }
1061       j -= (oc1 - _resproj->outcnt());
1062     }
1063   }
1064   if (_fallthroughcatchproj != NULL) {
1065     _igvn.replace_node(_fallthroughcatchproj, alloc->in(TypeFunc::Control));
1066   }
1067   if (_memproj_fallthrough != NULL) {
1068     _igvn.replace_node(_memproj_fallthrough, alloc->in(TypeFunc::Memory));
1069   }
1070   if (_memproj_catchall != NULL) {
1071     _igvn.replace_node(_memproj_catchall, C->top());
1072   }
1073   if (_ioproj_fallthrough != NULL) {
1074     _igvn.replace_node(_ioproj_fallthrough, alloc->in(TypeFunc::I_O));
1075   }
1076   if (_ioproj_catchall != NULL) {
1077     _igvn.replace_node(_ioproj_catchall, C->top());
1078   }
1079   if (_catchallcatchproj != NULL) {
1080     _igvn.replace_node(_catchallcatchproj, C->top());
1081   }
1082 }
1083 
eliminate_allocate_node(AllocateNode * alloc)1084 bool PhaseMacroExpand::eliminate_allocate_node(AllocateNode *alloc) {
1085   // Don't do scalar replacement if the frame can be popped by JVMTI:
1086   // if reallocation fails during deoptimization we'll pop all
1087   // interpreter frames for this compiled frame and that won't play
1088   // nice with JVMTI popframe.
1089   if (!EliminateAllocations || JvmtiExport::can_pop_frame() || !alloc->_is_non_escaping) {
1090     return false;
1091   }
1092   Node* klass = alloc->in(AllocateNode::KlassNode);
1093   const TypeKlassPtr* tklass = _igvn.type(klass)->is_klassptr();
1094   Node* res = alloc->result_cast();
1095   // Eliminate boxing allocations which are not used
1096   // regardless scalar replacable status.
1097   bool boxing_alloc = C->eliminate_boxing() &&
1098                       tklass->klass()->is_instance_klass()  &&
1099                       tklass->klass()->as_instance_klass()->is_box_klass();
1100   if (!alloc->_is_scalar_replaceable && (!boxing_alloc || (res != NULL))) {
1101     return false;
1102   }
1103 
1104   extract_call_projections(alloc);
1105 
1106   GrowableArray <SafePointNode *> safepoints;
1107   if (!can_eliminate_allocation(alloc, safepoints)) {
1108     return false;
1109   }
1110 
1111   if (!alloc->_is_scalar_replaceable) {
1112     assert(res == NULL, "sanity");
1113     // We can only eliminate allocation if all debug info references
1114     // are already replaced with SafePointScalarObject because
1115     // we can't search for a fields value without instance_id.
1116     if (safepoints.length() > 0) {
1117       return false;
1118     }
1119   }
1120 
1121   if (!scalar_replacement(alloc, safepoints)) {
1122     return false;
1123   }
1124 
1125   CompileLog* log = C->log();
1126   if (log != NULL) {
1127     log->head("eliminate_allocation type='%d'",
1128               log->identify(tklass->klass()));
1129     JVMState* p = alloc->jvms();
1130     while (p != NULL) {
1131       log->elem("jvms bci='%d' method='%d'", p->bci(), log->identify(p->method()));
1132       p = p->caller();
1133     }
1134     log->tail("eliminate_allocation");
1135   }
1136 
1137   process_users_of_allocation(alloc);
1138 
1139 #ifndef PRODUCT
1140   if (PrintEliminateAllocations) {
1141     if (alloc->is_AllocateArray())
1142       tty->print_cr("++++ Eliminated: %d AllocateArray", alloc->_idx);
1143     else
1144       tty->print_cr("++++ Eliminated: %d Allocate", alloc->_idx);
1145   }
1146 #endif
1147 
1148   return true;
1149 }
1150 
eliminate_boxing_node(CallStaticJavaNode * boxing)1151 bool PhaseMacroExpand::eliminate_boxing_node(CallStaticJavaNode *boxing) {
1152   // EA should remove all uses of non-escaping boxing node.
1153   if (!C->eliminate_boxing() || boxing->proj_out_or_null(TypeFunc::Parms) != NULL) {
1154     return false;
1155   }
1156 
1157   assert(boxing->result_cast() == NULL, "unexpected boxing node result");
1158 
1159   extract_call_projections(boxing);
1160 
1161   const TypeTuple* r = boxing->tf()->range();
1162   assert(r->cnt() > TypeFunc::Parms, "sanity");
1163   const TypeInstPtr* t = r->field_at(TypeFunc::Parms)->isa_instptr();
1164   assert(t != NULL, "sanity");
1165 
1166   CompileLog* log = C->log();
1167   if (log != NULL) {
1168     log->head("eliminate_boxing type='%d'",
1169               log->identify(t->klass()));
1170     JVMState* p = boxing->jvms();
1171     while (p != NULL) {
1172       log->elem("jvms bci='%d' method='%d'", p->bci(), log->identify(p->method()));
1173       p = p->caller();
1174     }
1175     log->tail("eliminate_boxing");
1176   }
1177 
1178   process_users_of_allocation(boxing);
1179 
1180 #ifndef PRODUCT
1181   if (PrintEliminateAllocations) {
1182     tty->print("++++ Eliminated: %d ", boxing->_idx);
1183     boxing->method()->print_short_name(tty);
1184     tty->cr();
1185   }
1186 #endif
1187 
1188   return true;
1189 }
1190 
1191 //---------------------------set_eden_pointers-------------------------
set_eden_pointers(Node * & eden_top_adr,Node * & eden_end_adr)1192 void PhaseMacroExpand::set_eden_pointers(Node* &eden_top_adr, Node* &eden_end_adr) {
1193   if (UseTLAB) {                // Private allocation: load from TLS
1194     Node* thread = transform_later(new ThreadLocalNode());
1195     int tlab_top_offset = in_bytes(JavaThread::tlab_top_offset());
1196     int tlab_end_offset = in_bytes(JavaThread::tlab_end_offset());
1197     eden_top_adr = basic_plus_adr(top()/*not oop*/, thread, tlab_top_offset);
1198     eden_end_adr = basic_plus_adr(top()/*not oop*/, thread, tlab_end_offset);
1199   } else {                      // Shared allocation: load from globals
1200     CollectedHeap* ch = Universe::heap();
1201     address top_adr = (address)ch->top_addr();
1202     address end_adr = (address)ch->end_addr();
1203     eden_top_adr = makecon(TypeRawPtr::make(top_adr));
1204     eden_end_adr = basic_plus_adr(eden_top_adr, end_adr - top_adr);
1205   }
1206 }
1207 
1208 
make_load(Node * ctl,Node * mem,Node * base,int offset,const Type * value_type,BasicType bt)1209 Node* PhaseMacroExpand::make_load(Node* ctl, Node* mem, Node* base, int offset, const Type* value_type, BasicType bt) {
1210   Node* adr = basic_plus_adr(base, offset);
1211   const TypePtr* adr_type = adr->bottom_type()->is_ptr();
1212   Node* value = LoadNode::make(_igvn, ctl, mem, adr, adr_type, value_type, bt, MemNode::unordered);
1213   transform_later(value);
1214   return value;
1215 }
1216 
1217 
make_store(Node * ctl,Node * mem,Node * base,int offset,Node * value,BasicType bt)1218 Node* PhaseMacroExpand::make_store(Node* ctl, Node* mem, Node* base, int offset, Node* value, BasicType bt) {
1219   Node* adr = basic_plus_adr(base, offset);
1220   mem = StoreNode::make(_igvn, ctl, mem, adr, NULL, value, bt, MemNode::unordered);
1221   transform_later(mem);
1222   return mem;
1223 }
1224 
1225 //=============================================================================
1226 //
1227 //                              A L L O C A T I O N
1228 //
1229 // Allocation attempts to be fast in the case of frequent small objects.
1230 // It breaks down like this:
1231 //
1232 // 1) Size in doublewords is computed.  This is a constant for objects and
1233 // variable for most arrays.  Doubleword units are used to avoid size
1234 // overflow of huge doubleword arrays.  We need doublewords in the end for
1235 // rounding.
1236 //
1237 // 2) Size is checked for being 'too large'.  Too-large allocations will go
1238 // the slow path into the VM.  The slow path can throw any required
1239 // exceptions, and does all the special checks for very large arrays.  The
1240 // size test can constant-fold away for objects.  For objects with
1241 // finalizers it constant-folds the otherway: you always go slow with
1242 // finalizers.
1243 //
1244 // 3) If NOT using TLABs, this is the contended loop-back point.
1245 // Load-Locked the heap top.  If using TLABs normal-load the heap top.
1246 //
1247 // 4) Check that heap top + size*8 < max.  If we fail go the slow ` route.
1248 // NOTE: "top+size*8" cannot wrap the 4Gig line!  Here's why: for largish
1249 // "size*8" we always enter the VM, where "largish" is a constant picked small
1250 // enough that there's always space between the eden max and 4Gig (old space is
1251 // there so it's quite large) and large enough that the cost of entering the VM
1252 // is dwarfed by the cost to initialize the space.
1253 //
1254 // 5) If NOT using TLABs, Store-Conditional the adjusted heap top back
1255 // down.  If contended, repeat at step 3.  If using TLABs normal-store
1256 // adjusted heap top back down; there is no contention.
1257 //
1258 // 6) If !ZeroTLAB then Bulk-clear the object/array.  Fill in klass & mark
1259 // fields.
1260 //
1261 // 7) Merge with the slow-path; cast the raw memory pointer to the correct
1262 // oop flavor.
1263 //
1264 //=============================================================================
1265 // FastAllocateSizeLimit value is in DOUBLEWORDS.
1266 // Allocations bigger than this always go the slow route.
1267 // This value must be small enough that allocation attempts that need to
1268 // trigger exceptions go the slow route.  Also, it must be small enough so
1269 // that heap_top + size_in_bytes does not wrap around the 4Gig limit.
1270 //=============================================================================j//
1271 // %%% Here is an old comment from parseHelper.cpp; is it outdated?
1272 // The allocator will coalesce int->oop copies away.  See comment in
1273 // coalesce.cpp about how this works.  It depends critically on the exact
1274 // code shape produced here, so if you are changing this code shape
1275 // make sure the GC info for the heap-top is correct in and around the
1276 // slow-path call.
1277 //
1278 
expand_allocate_common(AllocateNode * alloc,Node * length,const TypeFunc * slow_call_type,address slow_call_address)1279 void PhaseMacroExpand::expand_allocate_common(
1280             AllocateNode* alloc, // allocation node to be expanded
1281             Node* length,  // array length for an array allocation
1282             const TypeFunc* slow_call_type, // Type of slow call
1283             address slow_call_address  // Address of slow call
1284     )
1285 {
1286 
1287   Node* ctrl = alloc->in(TypeFunc::Control);
1288   Node* mem  = alloc->in(TypeFunc::Memory);
1289   Node* i_o  = alloc->in(TypeFunc::I_O);
1290   Node* size_in_bytes     = alloc->in(AllocateNode::AllocSize);
1291   Node* klass_node        = alloc->in(AllocateNode::KlassNode);
1292   Node* initial_slow_test = alloc->in(AllocateNode::InitialTest);
1293 
1294   assert(ctrl != NULL, "must have control");
1295   // We need a Region and corresponding Phi's to merge the slow-path and fast-path results.
1296   // they will not be used if "always_slow" is set
1297   enum { slow_result_path = 1, fast_result_path = 2 };
1298   Node *result_region = NULL;
1299   Node *result_phi_rawmem = NULL;
1300   Node *result_phi_rawoop = NULL;
1301   Node *result_phi_i_o = NULL;
1302 
1303   // The initial slow comparison is a size check, the comparison
1304   // we want to do is a BoolTest::gt
1305   bool always_slow = false;
1306   int tv = _igvn.find_int_con(initial_slow_test, -1);
1307   if (tv >= 0) {
1308     always_slow = (tv == 1);
1309     initial_slow_test = NULL;
1310   } else {
1311     initial_slow_test = BoolNode::make_predicate(initial_slow_test, &_igvn);
1312   }
1313 
1314   if (C->env()->dtrace_alloc_probes() ||
1315       (!UseTLAB && !Universe::heap()->supports_inline_contig_alloc())) {
1316     // Force slow-path allocation
1317     always_slow = true;
1318     initial_slow_test = NULL;
1319   }
1320 
1321 
1322   enum { too_big_or_final_path = 1, need_gc_path = 2 };
1323   Node *slow_region = NULL;
1324   Node *toobig_false = ctrl;
1325 
1326   assert (initial_slow_test == NULL || !always_slow, "arguments must be consistent");
1327   // generate the initial test if necessary
1328   if (initial_slow_test != NULL ) {
1329     slow_region = new RegionNode(3);
1330 
1331     // Now make the initial failure test.  Usually a too-big test but
1332     // might be a TRUE for finalizers or a fancy class check for
1333     // newInstance0.
1334     IfNode *toobig_iff = new IfNode(ctrl, initial_slow_test, PROB_MIN, COUNT_UNKNOWN);
1335     transform_later(toobig_iff);
1336     // Plug the failing-too-big test into the slow-path region
1337     Node *toobig_true = new IfTrueNode( toobig_iff );
1338     transform_later(toobig_true);
1339     slow_region    ->init_req( too_big_or_final_path, toobig_true );
1340     toobig_false = new IfFalseNode( toobig_iff );
1341     transform_later(toobig_false);
1342   } else {         // No initial test, just fall into next case
1343     toobig_false = ctrl;
1344     debug_only(slow_region = NodeSentinel);
1345   }
1346 
1347   Node *slow_mem = mem;  // save the current memory state for slow path
1348   // generate the fast allocation code unless we know that the initial test will always go slow
1349   if (!always_slow) {
1350     // Fast path modifies only raw memory.
1351     if (mem->is_MergeMem()) {
1352       mem = mem->as_MergeMem()->memory_at(Compile::AliasIdxRaw);
1353     }
1354 
1355     // allocate the Region and Phi nodes for the result
1356     result_region = new RegionNode(3);
1357     result_phi_rawmem = new PhiNode(result_region, Type::MEMORY, TypeRawPtr::BOTTOM);
1358     result_phi_rawoop = new PhiNode(result_region, TypeRawPtr::BOTTOM);
1359     result_phi_i_o    = new PhiNode(result_region, Type::ABIO); // I/O is used for Prefetch
1360 
1361     // Grab regular I/O before optional prefetch may change it.
1362     // Slow-path does no I/O so just set it to the original I/O.
1363     result_phi_i_o->init_req(slow_result_path, i_o);
1364 
1365     Node* needgc_ctrl = NULL;
1366     // Name successful fast-path variables
1367     Node* fast_oop_ctrl;
1368     Node* fast_oop_rawmem;
1369 
1370     intx prefetch_lines = length != NULL ? AllocatePrefetchLines : AllocateInstancePrefetchLines;
1371 
1372     BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
1373     Node* fast_oop = bs->obj_allocate(this, ctrl, mem, toobig_false, size_in_bytes, i_o, needgc_ctrl,
1374                                       fast_oop_ctrl, fast_oop_rawmem,
1375                                       prefetch_lines);
1376 
1377     if (initial_slow_test) {
1378       slow_region->init_req(need_gc_path, needgc_ctrl);
1379       // This completes all paths into the slow merge point
1380       transform_later(slow_region);
1381     } else {                      // No initial slow path needed!
1382       // Just fall from the need-GC path straight into the VM call.
1383       slow_region = needgc_ctrl;
1384     }
1385 
1386     InitializeNode* init = alloc->initialization();
1387     fast_oop_rawmem = initialize_object(alloc,
1388                                         fast_oop_ctrl, fast_oop_rawmem, fast_oop,
1389                                         klass_node, length, size_in_bytes);
1390 
1391     // If initialization is performed by an array copy, any required
1392     // MemBarStoreStore was already added. If the object does not
1393     // escape no need for a MemBarStoreStore. If the object does not
1394     // escape in its initializer and memory barrier (MemBarStoreStore or
1395     // stronger) is already added at exit of initializer, also no need
1396     // for a MemBarStoreStore. Otherwise we need a MemBarStoreStore
1397     // so that stores that initialize this object can't be reordered
1398     // with a subsequent store that makes this object accessible by
1399     // other threads.
1400     // Other threads include java threads and JVM internal threads
1401     // (for example concurrent GC threads). Current concurrent GC
1402     // implementation: CMS and G1 will not scan newly created object,
1403     // so it's safe to skip storestore barrier when allocation does
1404     // not escape.
1405     if (!alloc->does_not_escape_thread() &&
1406         !alloc->is_allocation_MemBar_redundant() &&
1407         (init == NULL || !init->is_complete_with_arraycopy())) {
1408       if (init == NULL || init->req() < InitializeNode::RawStores) {
1409         // No InitializeNode or no stores captured by zeroing
1410         // elimination. Simply add the MemBarStoreStore after object
1411         // initialization.
1412         MemBarNode* mb = MemBarNode::make(C, Op_MemBarStoreStore, Compile::AliasIdxBot);
1413         transform_later(mb);
1414 
1415         mb->init_req(TypeFunc::Memory, fast_oop_rawmem);
1416         mb->init_req(TypeFunc::Control, fast_oop_ctrl);
1417         fast_oop_ctrl = new ProjNode(mb,TypeFunc::Control);
1418         transform_later(fast_oop_ctrl);
1419         fast_oop_rawmem = new ProjNode(mb,TypeFunc::Memory);
1420         transform_later(fast_oop_rawmem);
1421       } else {
1422         // Add the MemBarStoreStore after the InitializeNode so that
1423         // all stores performing the initialization that were moved
1424         // before the InitializeNode happen before the storestore
1425         // barrier.
1426 
1427         Node* init_ctrl = init->proj_out_or_null(TypeFunc::Control);
1428         Node* init_mem = init->proj_out_or_null(TypeFunc::Memory);
1429 
1430         MemBarNode* mb = MemBarNode::make(C, Op_MemBarStoreStore, Compile::AliasIdxBot);
1431         transform_later(mb);
1432 
1433         Node* ctrl = new ProjNode(init,TypeFunc::Control);
1434         transform_later(ctrl);
1435         Node* mem = new ProjNode(init,TypeFunc::Memory);
1436         transform_later(mem);
1437 
1438         // The MemBarStoreStore depends on control and memory coming
1439         // from the InitializeNode
1440         mb->init_req(TypeFunc::Memory, mem);
1441         mb->init_req(TypeFunc::Control, ctrl);
1442 
1443         ctrl = new ProjNode(mb,TypeFunc::Control);
1444         transform_later(ctrl);
1445         mem = new ProjNode(mb,TypeFunc::Memory);
1446         transform_later(mem);
1447 
1448         // All nodes that depended on the InitializeNode for control
1449         // and memory must now depend on the MemBarNode that itself
1450         // depends on the InitializeNode
1451         if (init_ctrl != NULL) {
1452           _igvn.replace_node(init_ctrl, ctrl);
1453         }
1454         if (init_mem != NULL) {
1455           _igvn.replace_node(init_mem, mem);
1456         }
1457       }
1458     }
1459 
1460     if (C->env()->dtrace_extended_probes()) {
1461       // Slow-path call
1462       int size = TypeFunc::Parms + 2;
1463       CallLeafNode *call = new CallLeafNode(OptoRuntime::dtrace_object_alloc_Type(),
1464                                             CAST_FROM_FN_PTR(address, SharedRuntime::dtrace_object_alloc_base),
1465                                             "dtrace_object_alloc",
1466                                             TypeRawPtr::BOTTOM);
1467 
1468       // Get base of thread-local storage area
1469       Node* thread = new ThreadLocalNode();
1470       transform_later(thread);
1471 
1472       call->init_req(TypeFunc::Parms+0, thread);
1473       call->init_req(TypeFunc::Parms+1, fast_oop);
1474       call->init_req(TypeFunc::Control, fast_oop_ctrl);
1475       call->init_req(TypeFunc::I_O    , top()); // does no i/o
1476       call->init_req(TypeFunc::Memory , fast_oop_rawmem);
1477       call->init_req(TypeFunc::ReturnAdr, alloc->in(TypeFunc::ReturnAdr));
1478       call->init_req(TypeFunc::FramePtr, alloc->in(TypeFunc::FramePtr));
1479       transform_later(call);
1480       fast_oop_ctrl = new ProjNode(call,TypeFunc::Control);
1481       transform_later(fast_oop_ctrl);
1482       fast_oop_rawmem = new ProjNode(call,TypeFunc::Memory);
1483       transform_later(fast_oop_rawmem);
1484     }
1485 
1486     // Plug in the successful fast-path into the result merge point
1487     result_region    ->init_req(fast_result_path, fast_oop_ctrl);
1488     result_phi_rawoop->init_req(fast_result_path, fast_oop);
1489     result_phi_i_o   ->init_req(fast_result_path, i_o);
1490     result_phi_rawmem->init_req(fast_result_path, fast_oop_rawmem);
1491   } else {
1492     slow_region = ctrl;
1493     result_phi_i_o = i_o; // Rename it to use in the following code.
1494   }
1495 
1496   // Generate slow-path call
1497   CallNode *call = new CallStaticJavaNode(slow_call_type, slow_call_address,
1498                                OptoRuntime::stub_name(slow_call_address),
1499                                alloc->jvms()->bci(),
1500                                TypePtr::BOTTOM);
1501   call->init_req( TypeFunc::Control, slow_region );
1502   call->init_req( TypeFunc::I_O    , top() )     ;   // does no i/o
1503   call->init_req( TypeFunc::Memory , slow_mem ); // may gc ptrs
1504   call->init_req( TypeFunc::ReturnAdr, alloc->in(TypeFunc::ReturnAdr) );
1505   call->init_req( TypeFunc::FramePtr, alloc->in(TypeFunc::FramePtr) );
1506 
1507   call->init_req(TypeFunc::Parms+0, klass_node);
1508   if (length != NULL) {
1509     call->init_req(TypeFunc::Parms+1, length);
1510   }
1511 
1512   // Copy debug information and adjust JVMState information, then replace
1513   // allocate node with the call
1514   copy_call_debug_info((CallNode *) alloc,  call);
1515   if (!always_slow) {
1516     call->set_cnt(PROB_UNLIKELY_MAG(4));  // Same effect as RC_UNCOMMON.
1517   } else {
1518     // Hook i_o projection to avoid its elimination during allocation
1519     // replacement (when only a slow call is generated).
1520     call->set_req(TypeFunc::I_O, result_phi_i_o);
1521   }
1522   _igvn.replace_node(alloc, call);
1523   transform_later(call);
1524 
1525   // Identify the output projections from the allocate node and
1526   // adjust any references to them.
1527   // The control and io projections look like:
1528   //
1529   //        v---Proj(ctrl) <-----+   v---CatchProj(ctrl)
1530   //  Allocate                   Catch
1531   //        ^---Proj(io) <-------+   ^---CatchProj(io)
1532   //
1533   //  We are interested in the CatchProj nodes.
1534   //
1535   extract_call_projections(call);
1536 
1537   // An allocate node has separate memory projections for the uses on
1538   // the control and i_o paths. Replace the control memory projection with
1539   // result_phi_rawmem (unless we are only generating a slow call when
1540   // both memory projections are combined)
1541   if (!always_slow && _memproj_fallthrough != NULL) {
1542     for (DUIterator_Fast imax, i = _memproj_fallthrough->fast_outs(imax); i < imax; i++) {
1543       Node *use = _memproj_fallthrough->fast_out(i);
1544       _igvn.rehash_node_delayed(use);
1545       imax -= replace_input(use, _memproj_fallthrough, result_phi_rawmem);
1546       // back up iterator
1547       --i;
1548     }
1549   }
1550   // Now change uses of _memproj_catchall to use _memproj_fallthrough and delete
1551   // _memproj_catchall so we end up with a call that has only 1 memory projection.
1552   if (_memproj_catchall != NULL ) {
1553     if (_memproj_fallthrough == NULL) {
1554       _memproj_fallthrough = new ProjNode(call, TypeFunc::Memory);
1555       transform_later(_memproj_fallthrough);
1556     }
1557     for (DUIterator_Fast imax, i = _memproj_catchall->fast_outs(imax); i < imax; i++) {
1558       Node *use = _memproj_catchall->fast_out(i);
1559       _igvn.rehash_node_delayed(use);
1560       imax -= replace_input(use, _memproj_catchall, _memproj_fallthrough);
1561       // back up iterator
1562       --i;
1563     }
1564     assert(_memproj_catchall->outcnt() == 0, "all uses must be deleted");
1565     _igvn.remove_dead_node(_memproj_catchall);
1566   }
1567 
1568   // An allocate node has separate i_o projections for the uses on the control
1569   // and i_o paths. Always replace the control i_o projection with result i_o
1570   // otherwise incoming i_o become dead when only a slow call is generated
1571   // (it is different from memory projections where both projections are
1572   // combined in such case).
1573   if (_ioproj_fallthrough != NULL) {
1574     for (DUIterator_Fast imax, i = _ioproj_fallthrough->fast_outs(imax); i < imax; i++) {
1575       Node *use = _ioproj_fallthrough->fast_out(i);
1576       _igvn.rehash_node_delayed(use);
1577       imax -= replace_input(use, _ioproj_fallthrough, result_phi_i_o);
1578       // back up iterator
1579       --i;
1580     }
1581   }
1582   // Now change uses of _ioproj_catchall to use _ioproj_fallthrough and delete
1583   // _ioproj_catchall so we end up with a call that has only 1 i_o projection.
1584   if (_ioproj_catchall != NULL ) {
1585     if (_ioproj_fallthrough == NULL) {
1586       _ioproj_fallthrough = new ProjNode(call, TypeFunc::I_O);
1587       transform_later(_ioproj_fallthrough);
1588     }
1589     for (DUIterator_Fast imax, i = _ioproj_catchall->fast_outs(imax); i < imax; i++) {
1590       Node *use = _ioproj_catchall->fast_out(i);
1591       _igvn.rehash_node_delayed(use);
1592       imax -= replace_input(use, _ioproj_catchall, _ioproj_fallthrough);
1593       // back up iterator
1594       --i;
1595     }
1596     assert(_ioproj_catchall->outcnt() == 0, "all uses must be deleted");
1597     _igvn.remove_dead_node(_ioproj_catchall);
1598   }
1599 
1600   // if we generated only a slow call, we are done
1601   if (always_slow) {
1602     // Now we can unhook i_o.
1603     if (result_phi_i_o->outcnt() > 1) {
1604       call->set_req(TypeFunc::I_O, top());
1605     } else {
1606       assert(result_phi_i_o->unique_ctrl_out() == call, "");
1607       // Case of new array with negative size known during compilation.
1608       // AllocateArrayNode::Ideal() optimization disconnect unreachable
1609       // following code since call to runtime will throw exception.
1610       // As result there will be no users of i_o after the call.
1611       // Leave i_o attached to this call to avoid problems in preceding graph.
1612     }
1613     return;
1614   }
1615 
1616 
1617   if (_fallthroughcatchproj != NULL) {
1618     ctrl = _fallthroughcatchproj->clone();
1619     transform_later(ctrl);
1620     _igvn.replace_node(_fallthroughcatchproj, result_region);
1621   } else {
1622     ctrl = top();
1623   }
1624   Node *slow_result;
1625   if (_resproj == NULL) {
1626     // no uses of the allocation result
1627     slow_result = top();
1628   } else {
1629     slow_result = _resproj->clone();
1630     transform_later(slow_result);
1631     _igvn.replace_node(_resproj, result_phi_rawoop);
1632   }
1633 
1634   // Plug slow-path into result merge point
1635   result_region    ->init_req( slow_result_path, ctrl );
1636   result_phi_rawoop->init_req( slow_result_path, slow_result);
1637   result_phi_rawmem->init_req( slow_result_path, _memproj_fallthrough );
1638   transform_later(result_region);
1639   transform_later(result_phi_rawoop);
1640   transform_later(result_phi_rawmem);
1641   transform_later(result_phi_i_o);
1642   // This completes all paths into the result merge point
1643 }
1644 
1645 
1646 // Helper for PhaseMacroExpand::expand_allocate_common.
1647 // Initializes the newly-allocated storage.
1648 Node*
initialize_object(AllocateNode * alloc,Node * control,Node * rawmem,Node * object,Node * klass_node,Node * length,Node * size_in_bytes)1649 PhaseMacroExpand::initialize_object(AllocateNode* alloc,
1650                                     Node* control, Node* rawmem, Node* object,
1651                                     Node* klass_node, Node* length,
1652                                     Node* size_in_bytes) {
1653   InitializeNode* init = alloc->initialization();
1654   // Store the klass & mark bits
1655   Node* mark_node = NULL;
1656   // For now only enable fast locking for non-array types
1657   if (UseBiasedLocking && (length == NULL)) {
1658     mark_node = make_load(control, rawmem, klass_node, in_bytes(Klass::prototype_header_offset()), TypeRawPtr::BOTTOM, T_ADDRESS);
1659   } else {
1660     mark_node = makecon(TypeRawPtr::make((address)markOopDesc::prototype()));
1661   }
1662   rawmem = make_store(control, rawmem, object, oopDesc::mark_offset_in_bytes(), mark_node, T_ADDRESS);
1663 
1664   rawmem = make_store(control, rawmem, object, oopDesc::klass_offset_in_bytes(), klass_node, T_METADATA);
1665   int header_size = alloc->minimum_header_size();  // conservatively small
1666 
1667   // Array length
1668   if (length != NULL) {         // Arrays need length field
1669     rawmem = make_store(control, rawmem, object, arrayOopDesc::length_offset_in_bytes(), length, T_INT);
1670     // conservatively small header size:
1671     header_size = arrayOopDesc::base_offset_in_bytes(T_BYTE);
1672     ciKlass* k = _igvn.type(klass_node)->is_klassptr()->klass();
1673     if (k->is_array_klass())    // we know the exact header size in most cases:
1674       header_size = Klass::layout_helper_header_size(k->layout_helper());
1675   }
1676 
1677   // Clear the object body, if necessary.
1678   if (init == NULL) {
1679     // The init has somehow disappeared; be cautious and clear everything.
1680     //
1681     // This can happen if a node is allocated but an uncommon trap occurs
1682     // immediately.  In this case, the Initialize gets associated with the
1683     // trap, and may be placed in a different (outer) loop, if the Allocate
1684     // is in a loop.  If (this is rare) the inner loop gets unrolled, then
1685     // there can be two Allocates to one Initialize.  The answer in all these
1686     // edge cases is safety first.  It is always safe to clear immediately
1687     // within an Allocate, and then (maybe or maybe not) clear some more later.
1688     if (!(UseTLAB && ZeroTLAB)) {
1689       rawmem = ClearArrayNode::clear_memory(control, rawmem, object,
1690                                             header_size, size_in_bytes,
1691                                             &_igvn);
1692     }
1693   } else {
1694     if (!init->is_complete()) {
1695       // Try to win by zeroing only what the init does not store.
1696       // We can also try to do some peephole optimizations,
1697       // such as combining some adjacent subword stores.
1698       rawmem = init->complete_stores(control, rawmem, object,
1699                                      header_size, size_in_bytes, &_igvn);
1700     }
1701     // We have no more use for this link, since the AllocateNode goes away:
1702     init->set_req(InitializeNode::RawAddress, top());
1703     // (If we keep the link, it just confuses the register allocator,
1704     // who thinks he sees a real use of the address by the membar.)
1705   }
1706 
1707   return rawmem;
1708 }
1709 
1710 // Generate prefetch instructions for next allocations.
prefetch_allocation(Node * i_o,Node * & needgc_false,Node * & contended_phi_rawmem,Node * old_eden_top,Node * new_eden_top,intx lines)1711 Node* PhaseMacroExpand::prefetch_allocation(Node* i_o, Node*& needgc_false,
1712                                         Node*& contended_phi_rawmem,
1713                                         Node* old_eden_top, Node* new_eden_top,
1714                                         intx lines) {
1715    enum { fall_in_path = 1, pf_path = 2 };
1716    if( UseTLAB && AllocatePrefetchStyle == 2 ) {
1717       // Generate prefetch allocation with watermark check.
1718       // As an allocation hits the watermark, we will prefetch starting
1719       // at a "distance" away from watermark.
1720 
1721       Node *pf_region = new RegionNode(3);
1722       Node *pf_phi_rawmem = new PhiNode( pf_region, Type::MEMORY,
1723                                                 TypeRawPtr::BOTTOM );
1724       // I/O is used for Prefetch
1725       Node *pf_phi_abio = new PhiNode( pf_region, Type::ABIO );
1726 
1727       Node *thread = new ThreadLocalNode();
1728       transform_later(thread);
1729 
1730       Node *eden_pf_adr = new AddPNode( top()/*not oop*/, thread,
1731                    _igvn.MakeConX(in_bytes(JavaThread::tlab_pf_top_offset())) );
1732       transform_later(eden_pf_adr);
1733 
1734       Node *old_pf_wm = new LoadPNode(needgc_false,
1735                                    contended_phi_rawmem, eden_pf_adr,
1736                                    TypeRawPtr::BOTTOM, TypeRawPtr::BOTTOM,
1737                                    MemNode::unordered);
1738       transform_later(old_pf_wm);
1739 
1740       // check against new_eden_top
1741       Node *need_pf_cmp = new CmpPNode( new_eden_top, old_pf_wm );
1742       transform_later(need_pf_cmp);
1743       Node *need_pf_bol = new BoolNode( need_pf_cmp, BoolTest::ge );
1744       transform_later(need_pf_bol);
1745       IfNode *need_pf_iff = new IfNode( needgc_false, need_pf_bol,
1746                                        PROB_UNLIKELY_MAG(4), COUNT_UNKNOWN );
1747       transform_later(need_pf_iff);
1748 
1749       // true node, add prefetchdistance
1750       Node *need_pf_true = new IfTrueNode( need_pf_iff );
1751       transform_later(need_pf_true);
1752 
1753       Node *need_pf_false = new IfFalseNode( need_pf_iff );
1754       transform_later(need_pf_false);
1755 
1756       Node *new_pf_wmt = new AddPNode( top(), old_pf_wm,
1757                                     _igvn.MakeConX(AllocatePrefetchDistance) );
1758       transform_later(new_pf_wmt );
1759       new_pf_wmt->set_req(0, need_pf_true);
1760 
1761       Node *store_new_wmt = new StorePNode(need_pf_true,
1762                                        contended_phi_rawmem, eden_pf_adr,
1763                                        TypeRawPtr::BOTTOM, new_pf_wmt,
1764                                        MemNode::unordered);
1765       transform_later(store_new_wmt);
1766 
1767       // adding prefetches
1768       pf_phi_abio->init_req( fall_in_path, i_o );
1769 
1770       Node *prefetch_adr;
1771       Node *prefetch;
1772       uint step_size = AllocatePrefetchStepSize;
1773       uint distance = 0;
1774 
1775       for ( intx i = 0; i < lines; i++ ) {
1776         prefetch_adr = new AddPNode( old_pf_wm, new_pf_wmt,
1777                                             _igvn.MakeConX(distance) );
1778         transform_later(prefetch_adr);
1779         prefetch = new PrefetchAllocationNode( i_o, prefetch_adr );
1780         transform_later(prefetch);
1781         distance += step_size;
1782         i_o = prefetch;
1783       }
1784       pf_phi_abio->set_req( pf_path, i_o );
1785 
1786       pf_region->init_req( fall_in_path, need_pf_false );
1787       pf_region->init_req( pf_path, need_pf_true );
1788 
1789       pf_phi_rawmem->init_req( fall_in_path, contended_phi_rawmem );
1790       pf_phi_rawmem->init_req( pf_path, store_new_wmt );
1791 
1792       transform_later(pf_region);
1793       transform_later(pf_phi_rawmem);
1794       transform_later(pf_phi_abio);
1795 
1796       needgc_false = pf_region;
1797       contended_phi_rawmem = pf_phi_rawmem;
1798       i_o = pf_phi_abio;
1799    } else if( UseTLAB && AllocatePrefetchStyle == 3 ) {
1800       // Insert a prefetch instruction for each allocation.
1801       // This code is used to generate 1 prefetch instruction per cache line.
1802 
1803       // Generate several prefetch instructions.
1804       uint step_size = AllocatePrefetchStepSize;
1805       uint distance = AllocatePrefetchDistance;
1806 
1807       // Next cache address.
1808       Node *cache_adr = new AddPNode(old_eden_top, old_eden_top,
1809                                      _igvn.MakeConX(step_size + distance));
1810       transform_later(cache_adr);
1811       cache_adr = new CastP2XNode(needgc_false, cache_adr);
1812       transform_later(cache_adr);
1813       // Address is aligned to execute prefetch to the beginning of cache line size
1814       // (it is important when BIS instruction is used on SPARC as prefetch).
1815       Node* mask = _igvn.MakeConX(~(intptr_t)(step_size-1));
1816       cache_adr = new AndXNode(cache_adr, mask);
1817       transform_later(cache_adr);
1818       cache_adr = new CastX2PNode(cache_adr);
1819       transform_later(cache_adr);
1820 
1821       // Prefetch
1822       Node *prefetch = new PrefetchAllocationNode( contended_phi_rawmem, cache_adr );
1823       prefetch->set_req(0, needgc_false);
1824       transform_later(prefetch);
1825       contended_phi_rawmem = prefetch;
1826       Node *prefetch_adr;
1827       distance = step_size;
1828       for ( intx i = 1; i < lines; i++ ) {
1829         prefetch_adr = new AddPNode( cache_adr, cache_adr,
1830                                             _igvn.MakeConX(distance) );
1831         transform_later(prefetch_adr);
1832         prefetch = new PrefetchAllocationNode( contended_phi_rawmem, prefetch_adr );
1833         transform_later(prefetch);
1834         distance += step_size;
1835         contended_phi_rawmem = prefetch;
1836       }
1837    } else if( AllocatePrefetchStyle > 0 ) {
1838       // Insert a prefetch for each allocation only on the fast-path
1839       Node *prefetch_adr;
1840       Node *prefetch;
1841       // Generate several prefetch instructions.
1842       uint step_size = AllocatePrefetchStepSize;
1843       uint distance = AllocatePrefetchDistance;
1844       for ( intx i = 0; i < lines; i++ ) {
1845         prefetch_adr = new AddPNode( old_eden_top, new_eden_top,
1846                                             _igvn.MakeConX(distance) );
1847         transform_later(prefetch_adr);
1848         prefetch = new PrefetchAllocationNode( i_o, prefetch_adr );
1849         // Do not let it float too high, since if eden_top == eden_end,
1850         // both might be null.
1851         if( i == 0 ) { // Set control for first prefetch, next follows it
1852           prefetch->init_req(0, needgc_false);
1853         }
1854         transform_later(prefetch);
1855         distance += step_size;
1856         i_o = prefetch;
1857       }
1858    }
1859    return i_o;
1860 }
1861 
1862 
expand_allocate(AllocateNode * alloc)1863 void PhaseMacroExpand::expand_allocate(AllocateNode *alloc) {
1864   expand_allocate_common(alloc, NULL,
1865                          OptoRuntime::new_instance_Type(),
1866                          OptoRuntime::new_instance_Java());
1867 }
1868 
expand_allocate_array(AllocateArrayNode * alloc)1869 void PhaseMacroExpand::expand_allocate_array(AllocateArrayNode *alloc) {
1870   Node* length = alloc->in(AllocateNode::ALength);
1871   InitializeNode* init = alloc->initialization();
1872   Node* klass_node = alloc->in(AllocateNode::KlassNode);
1873   ciKlass* k = _igvn.type(klass_node)->is_klassptr()->klass();
1874   address slow_call_address;  // Address of slow call
1875   if (init != NULL && init->is_complete_with_arraycopy() &&
1876       k->is_type_array_klass()) {
1877     // Don't zero type array during slow allocation in VM since
1878     // it will be initialized later by arraycopy in compiled code.
1879     slow_call_address = OptoRuntime::new_array_nozero_Java();
1880   } else {
1881     slow_call_address = OptoRuntime::new_array_Java();
1882   }
1883   expand_allocate_common(alloc, length,
1884                          OptoRuntime::new_array_Type(),
1885                          slow_call_address);
1886 }
1887 
1888 //-------------------mark_eliminated_box----------------------------------
1889 //
1890 // During EA obj may point to several objects but after few ideal graph
1891 // transformations (CCP) it may point to only one non escaping object
1892 // (but still using phi), corresponding locks and unlocks will be marked
1893 // for elimination. Later obj could be replaced with a new node (new phi)
1894 // and which does not have escape information. And later after some graph
1895 // reshape other locks and unlocks (which were not marked for elimination
1896 // before) are connected to this new obj (phi) but they still will not be
1897 // marked for elimination since new obj has no escape information.
1898 // Mark all associated (same box and obj) lock and unlock nodes for
1899 // elimination if some of them marked already.
mark_eliminated_box(Node * oldbox,Node * obj)1900 void PhaseMacroExpand::mark_eliminated_box(Node* oldbox, Node* obj) {
1901   if (oldbox->as_BoxLock()->is_eliminated())
1902     return; // This BoxLock node was processed already.
1903 
1904   // New implementation (EliminateNestedLocks) has separate BoxLock
1905   // node for each locked region so mark all associated locks/unlocks as
1906   // eliminated even if different objects are referenced in one locked region
1907   // (for example, OSR compilation of nested loop inside locked scope).
1908   if (EliminateNestedLocks ||
1909       oldbox->as_BoxLock()->is_simple_lock_region(NULL, obj)) {
1910     // Box is used only in one lock region. Mark this box as eliminated.
1911     _igvn.hash_delete(oldbox);
1912     oldbox->as_BoxLock()->set_eliminated(); // This changes box's hash value
1913      _igvn.hash_insert(oldbox);
1914 
1915     for (uint i = 0; i < oldbox->outcnt(); i++) {
1916       Node* u = oldbox->raw_out(i);
1917       if (u->is_AbstractLock() && !u->as_AbstractLock()->is_non_esc_obj()) {
1918         AbstractLockNode* alock = u->as_AbstractLock();
1919         // Check lock's box since box could be referenced by Lock's debug info.
1920         if (alock->box_node() == oldbox) {
1921           // Mark eliminated all related locks and unlocks.
1922 #ifdef ASSERT
1923           alock->log_lock_optimization(C, "eliminate_lock_set_non_esc4");
1924 #endif
1925           alock->set_non_esc_obj();
1926         }
1927       }
1928     }
1929     return;
1930   }
1931 
1932   // Create new "eliminated" BoxLock node and use it in monitor debug info
1933   // instead of oldbox for the same object.
1934   BoxLockNode* newbox = oldbox->clone()->as_BoxLock();
1935 
1936   // Note: BoxLock node is marked eliminated only here and it is used
1937   // to indicate that all associated lock and unlock nodes are marked
1938   // for elimination.
1939   newbox->set_eliminated();
1940   transform_later(newbox);
1941 
1942   // Replace old box node with new box for all users of the same object.
1943   for (uint i = 0; i < oldbox->outcnt();) {
1944     bool next_edge = true;
1945 
1946     Node* u = oldbox->raw_out(i);
1947     if (u->is_AbstractLock()) {
1948       AbstractLockNode* alock = u->as_AbstractLock();
1949       if (alock->box_node() == oldbox && alock->obj_node()->eqv_uncast(obj)) {
1950         // Replace Box and mark eliminated all related locks and unlocks.
1951 #ifdef ASSERT
1952         alock->log_lock_optimization(C, "eliminate_lock_set_non_esc5");
1953 #endif
1954         alock->set_non_esc_obj();
1955         _igvn.rehash_node_delayed(alock);
1956         alock->set_box_node(newbox);
1957         next_edge = false;
1958       }
1959     }
1960     if (u->is_FastLock() && u->as_FastLock()->obj_node()->eqv_uncast(obj)) {
1961       FastLockNode* flock = u->as_FastLock();
1962       assert(flock->box_node() == oldbox, "sanity");
1963       _igvn.rehash_node_delayed(flock);
1964       flock->set_box_node(newbox);
1965       next_edge = false;
1966     }
1967 
1968     // Replace old box in monitor debug info.
1969     if (u->is_SafePoint() && u->as_SafePoint()->jvms()) {
1970       SafePointNode* sfn = u->as_SafePoint();
1971       JVMState* youngest_jvms = sfn->jvms();
1972       int max_depth = youngest_jvms->depth();
1973       for (int depth = 1; depth <= max_depth; depth++) {
1974         JVMState* jvms = youngest_jvms->of_depth(depth);
1975         int num_mon  = jvms->nof_monitors();
1976         // Loop over monitors
1977         for (int idx = 0; idx < num_mon; idx++) {
1978           Node* obj_node = sfn->monitor_obj(jvms, idx);
1979           Node* box_node = sfn->monitor_box(jvms, idx);
1980           if (box_node == oldbox && obj_node->eqv_uncast(obj)) {
1981             int j = jvms->monitor_box_offset(idx);
1982             _igvn.replace_input_of(u, j, newbox);
1983             next_edge = false;
1984           }
1985         }
1986       }
1987     }
1988     if (next_edge) i++;
1989   }
1990 }
1991 
1992 //-----------------------mark_eliminated_locking_nodes-----------------------
mark_eliminated_locking_nodes(AbstractLockNode * alock)1993 void PhaseMacroExpand::mark_eliminated_locking_nodes(AbstractLockNode *alock) {
1994   if (EliminateNestedLocks) {
1995     if (alock->is_nested()) {
1996        assert(alock->box_node()->as_BoxLock()->is_eliminated(), "sanity");
1997        return;
1998     } else if (!alock->is_non_esc_obj()) { // Not eliminated or coarsened
1999       // Only Lock node has JVMState needed here.
2000       // Not that preceding claim is documented anywhere else.
2001       if (alock->jvms() != NULL) {
2002         if (alock->as_Lock()->is_nested_lock_region()) {
2003           // Mark eliminated related nested locks and unlocks.
2004           Node* obj = alock->obj_node();
2005           BoxLockNode* box_node = alock->box_node()->as_BoxLock();
2006           assert(!box_node->is_eliminated(), "should not be marked yet");
2007           // Note: BoxLock node is marked eliminated only here
2008           // and it is used to indicate that all associated lock
2009           // and unlock nodes are marked for elimination.
2010           box_node->set_eliminated(); // Box's hash is always NO_HASH here
2011           for (uint i = 0; i < box_node->outcnt(); i++) {
2012             Node* u = box_node->raw_out(i);
2013             if (u->is_AbstractLock()) {
2014               alock = u->as_AbstractLock();
2015               if (alock->box_node() == box_node) {
2016                 // Verify that this Box is referenced only by related locks.
2017                 assert(alock->obj_node()->eqv_uncast(obj), "");
2018                 // Mark all related locks and unlocks.
2019 #ifdef ASSERT
2020                 alock->log_lock_optimization(C, "eliminate_lock_set_nested");
2021 #endif
2022                 alock->set_nested();
2023               }
2024             }
2025           }
2026         } else {
2027 #ifdef ASSERT
2028           alock->log_lock_optimization(C, "eliminate_lock_NOT_nested_lock_region");
2029           if (C->log() != NULL)
2030             alock->as_Lock()->is_nested_lock_region(C); // rerun for debugging output
2031 #endif
2032         }
2033       }
2034       return;
2035     }
2036     // Process locks for non escaping object
2037     assert(alock->is_non_esc_obj(), "");
2038   } // EliminateNestedLocks
2039 
2040   if (alock->is_non_esc_obj()) { // Lock is used for non escaping object
2041     // Look for all locks of this object and mark them and
2042     // corresponding BoxLock nodes as eliminated.
2043     Node* obj = alock->obj_node();
2044     for (uint j = 0; j < obj->outcnt(); j++) {
2045       Node* o = obj->raw_out(j);
2046       if (o->is_AbstractLock() &&
2047           o->as_AbstractLock()->obj_node()->eqv_uncast(obj)) {
2048         alock = o->as_AbstractLock();
2049         Node* box = alock->box_node();
2050         // Replace old box node with new eliminated box for all users
2051         // of the same object and mark related locks as eliminated.
2052         mark_eliminated_box(box, obj);
2053       }
2054     }
2055   }
2056 }
2057 
2058 // we have determined that this lock/unlock can be eliminated, we simply
2059 // eliminate the node without expanding it.
2060 //
2061 // Note:  The membar's associated with the lock/unlock are currently not
2062 //        eliminated.  This should be investigated as a future enhancement.
2063 //
eliminate_locking_node(AbstractLockNode * alock)2064 bool PhaseMacroExpand::eliminate_locking_node(AbstractLockNode *alock) {
2065 
2066   if (!alock->is_eliminated()) {
2067     return false;
2068   }
2069 #ifdef ASSERT
2070   if (!alock->is_coarsened()) {
2071     // Check that new "eliminated" BoxLock node is created.
2072     BoxLockNode* oldbox = alock->box_node()->as_BoxLock();
2073     assert(oldbox->is_eliminated(), "should be done already");
2074   }
2075 #endif
2076 
2077   alock->log_lock_optimization(C, "eliminate_lock");
2078 
2079 #ifndef PRODUCT
2080   if (PrintEliminateLocks) {
2081     if (alock->is_Lock()) {
2082       tty->print_cr("++++ Eliminated: %d Lock", alock->_idx);
2083     } else {
2084       tty->print_cr("++++ Eliminated: %d Unlock", alock->_idx);
2085     }
2086   }
2087 #endif
2088 
2089   Node* mem  = alock->in(TypeFunc::Memory);
2090   Node* ctrl = alock->in(TypeFunc::Control);
2091   guarantee(ctrl != NULL, "missing control projection, cannot replace_node() with NULL");
2092 
2093   extract_call_projections(alock);
2094   // There are 2 projections from the lock.  The lock node will
2095   // be deleted when its last use is subsumed below.
2096   assert(alock->outcnt() == 2 &&
2097          _fallthroughproj != NULL &&
2098          _memproj_fallthrough != NULL,
2099          "Unexpected projections from Lock/Unlock");
2100 
2101   Node* fallthroughproj = _fallthroughproj;
2102   Node* memproj_fallthrough = _memproj_fallthrough;
2103 
2104   // The memory projection from a lock/unlock is RawMem
2105   // The input to a Lock is merged memory, so extract its RawMem input
2106   // (unless the MergeMem has been optimized away.)
2107   if (alock->is_Lock()) {
2108     // Seach for MemBarAcquireLock node and delete it also.
2109     MemBarNode* membar = fallthroughproj->unique_ctrl_out()->as_MemBar();
2110     assert(membar != NULL && membar->Opcode() == Op_MemBarAcquireLock, "");
2111     Node* ctrlproj = membar->proj_out(TypeFunc::Control);
2112     Node* memproj = membar->proj_out(TypeFunc::Memory);
2113     _igvn.replace_node(ctrlproj, fallthroughproj);
2114     _igvn.replace_node(memproj, memproj_fallthrough);
2115 
2116     // Delete FastLock node also if this Lock node is unique user
2117     // (a loop peeling may clone a Lock node).
2118     Node* flock = alock->as_Lock()->fastlock_node();
2119     if (flock->outcnt() == 1) {
2120       assert(flock->unique_out() == alock, "sanity");
2121       _igvn.replace_node(flock, top());
2122     }
2123   }
2124 
2125   // Seach for MemBarReleaseLock node and delete it also.
2126   if (alock->is_Unlock() && ctrl->is_Proj() && ctrl->in(0)->is_MemBar()) {
2127     MemBarNode* membar = ctrl->in(0)->as_MemBar();
2128     assert(membar->Opcode() == Op_MemBarReleaseLock &&
2129            mem->is_Proj() && membar == mem->in(0), "");
2130     _igvn.replace_node(fallthroughproj, ctrl);
2131     _igvn.replace_node(memproj_fallthrough, mem);
2132     fallthroughproj = ctrl;
2133     memproj_fallthrough = mem;
2134     ctrl = membar->in(TypeFunc::Control);
2135     mem  = membar->in(TypeFunc::Memory);
2136   }
2137 
2138   _igvn.replace_node(fallthroughproj, ctrl);
2139   _igvn.replace_node(memproj_fallthrough, mem);
2140   return true;
2141 }
2142 
2143 
2144 //------------------------------expand_lock_node----------------------
expand_lock_node(LockNode * lock)2145 void PhaseMacroExpand::expand_lock_node(LockNode *lock) {
2146 
2147   Node* ctrl = lock->in(TypeFunc::Control);
2148   Node* mem = lock->in(TypeFunc::Memory);
2149   Node* obj = lock->obj_node();
2150   Node* box = lock->box_node();
2151   Node* flock = lock->fastlock_node();
2152 
2153   assert(!box->as_BoxLock()->is_eliminated(), "sanity");
2154 
2155   // Make the merge point
2156   Node *region;
2157   Node *mem_phi;
2158   Node *slow_path;
2159 
2160   if (UseOptoBiasInlining) {
2161     /*
2162      *  See the full description in MacroAssembler::biased_locking_enter().
2163      *
2164      *  if( (mark_word & biased_lock_mask) == biased_lock_pattern ) {
2165      *    // The object is biased.
2166      *    proto_node = klass->prototype_header;
2167      *    o_node = thread | proto_node;
2168      *    x_node = o_node ^ mark_word;
2169      *    if( (x_node & ~age_mask) == 0 ) { // Biased to the current thread ?
2170      *      // Done.
2171      *    } else {
2172      *      if( (x_node & biased_lock_mask) != 0 ) {
2173      *        // The klass's prototype header is no longer biased.
2174      *        cas(&mark_word, mark_word, proto_node)
2175      *        goto cas_lock;
2176      *      } else {
2177      *        // The klass's prototype header is still biased.
2178      *        if( (x_node & epoch_mask) != 0 ) { // Expired epoch?
2179      *          old = mark_word;
2180      *          new = o_node;
2181      *        } else {
2182      *          // Different thread or anonymous biased.
2183      *          old = mark_word & (epoch_mask | age_mask | biased_lock_mask);
2184      *          new = thread | old;
2185      *        }
2186      *        // Try to rebias.
2187      *        if( cas(&mark_word, old, new) == 0 ) {
2188      *          // Done.
2189      *        } else {
2190      *          goto slow_path; // Failed.
2191      *        }
2192      *      }
2193      *    }
2194      *  } else {
2195      *    // The object is not biased.
2196      *    cas_lock:
2197      *    if( FastLock(obj) == 0 ) {
2198      *      // Done.
2199      *    } else {
2200      *      slow_path:
2201      *      OptoRuntime::complete_monitor_locking_Java(obj);
2202      *    }
2203      *  }
2204      */
2205 
2206     region  = new RegionNode(5);
2207     // create a Phi for the memory state
2208     mem_phi = new PhiNode( region, Type::MEMORY, TypeRawPtr::BOTTOM);
2209 
2210     Node* fast_lock_region  = new RegionNode(3);
2211     Node* fast_lock_mem_phi = new PhiNode( fast_lock_region, Type::MEMORY, TypeRawPtr::BOTTOM);
2212 
2213     // First, check mark word for the biased lock pattern.
2214     Node* mark_node = make_load(ctrl, mem, obj, oopDesc::mark_offset_in_bytes(), TypeX_X, TypeX_X->basic_type());
2215 
2216     // Get fast path - mark word has the biased lock pattern.
2217     ctrl = opt_bits_test(ctrl, fast_lock_region, 1, mark_node,
2218                          markOopDesc::biased_lock_mask_in_place,
2219                          markOopDesc::biased_lock_pattern, true);
2220     // fast_lock_region->in(1) is set to slow path.
2221     fast_lock_mem_phi->init_req(1, mem);
2222 
2223     // Now check that the lock is biased to the current thread and has
2224     // the same epoch and bias as Klass::_prototype_header.
2225 
2226     // Special-case a fresh allocation to avoid building nodes:
2227     Node* klass_node = AllocateNode::Ideal_klass(obj, &_igvn);
2228     if (klass_node == NULL) {
2229       Node* k_adr = basic_plus_adr(obj, oopDesc::klass_offset_in_bytes());
2230       klass_node = transform_later(LoadKlassNode::make(_igvn, NULL, mem, k_adr, _igvn.type(k_adr)->is_ptr()));
2231 #ifdef _LP64
2232       if (UseCompressedClassPointers && klass_node->is_DecodeNKlass()) {
2233         assert(klass_node->in(1)->Opcode() == Op_LoadNKlass, "sanity");
2234         klass_node->in(1)->init_req(0, ctrl);
2235       } else
2236 #endif
2237       klass_node->init_req(0, ctrl);
2238     }
2239     Node *proto_node = make_load(ctrl, mem, klass_node, in_bytes(Klass::prototype_header_offset()), TypeX_X, TypeX_X->basic_type());
2240 
2241     Node* thread = transform_later(new ThreadLocalNode());
2242     Node* cast_thread = transform_later(new CastP2XNode(ctrl, thread));
2243     Node* o_node = transform_later(new OrXNode(cast_thread, proto_node));
2244     Node* x_node = transform_later(new XorXNode(o_node, mark_node));
2245 
2246     // Get slow path - mark word does NOT match the value.
2247     Node* not_biased_ctrl =  opt_bits_test(ctrl, region, 3, x_node,
2248                                       (~markOopDesc::age_mask_in_place), 0);
2249     // region->in(3) is set to fast path - the object is biased to the current thread.
2250     mem_phi->init_req(3, mem);
2251 
2252 
2253     // Mark word does NOT match the value (thread | Klass::_prototype_header).
2254 
2255 
2256     // First, check biased pattern.
2257     // Get fast path - _prototype_header has the same biased lock pattern.
2258     ctrl =  opt_bits_test(not_biased_ctrl, fast_lock_region, 2, x_node,
2259                           markOopDesc::biased_lock_mask_in_place, 0, true);
2260 
2261     not_biased_ctrl = fast_lock_region->in(2); // Slow path
2262     // fast_lock_region->in(2) - the prototype header is no longer biased
2263     // and we have to revoke the bias on this object.
2264     // We are going to try to reset the mark of this object to the prototype
2265     // value and fall through to the CAS-based locking scheme.
2266     Node* adr = basic_plus_adr(obj, oopDesc::mark_offset_in_bytes());
2267     Node* cas = new StoreXConditionalNode(not_biased_ctrl, mem, adr,
2268                                           proto_node, mark_node);
2269     transform_later(cas);
2270     Node* proj = transform_later(new SCMemProjNode(cas));
2271     fast_lock_mem_phi->init_req(2, proj);
2272 
2273 
2274     // Second, check epoch bits.
2275     Node* rebiased_region  = new RegionNode(3);
2276     Node* old_phi = new PhiNode( rebiased_region, TypeX_X);
2277     Node* new_phi = new PhiNode( rebiased_region, TypeX_X);
2278 
2279     // Get slow path - mark word does NOT match epoch bits.
2280     Node* epoch_ctrl =  opt_bits_test(ctrl, rebiased_region, 1, x_node,
2281                                       markOopDesc::epoch_mask_in_place, 0);
2282     // The epoch of the current bias is not valid, attempt to rebias the object
2283     // toward the current thread.
2284     rebiased_region->init_req(2, epoch_ctrl);
2285     old_phi->init_req(2, mark_node);
2286     new_phi->init_req(2, o_node);
2287 
2288     // rebiased_region->in(1) is set to fast path.
2289     // The epoch of the current bias is still valid but we know
2290     // nothing about the owner; it might be set or it might be clear.
2291     Node* cmask   = MakeConX(markOopDesc::biased_lock_mask_in_place |
2292                              markOopDesc::age_mask_in_place |
2293                              markOopDesc::epoch_mask_in_place);
2294     Node* old = transform_later(new AndXNode(mark_node, cmask));
2295     cast_thread = transform_later(new CastP2XNode(ctrl, thread));
2296     Node* new_mark = transform_later(new OrXNode(cast_thread, old));
2297     old_phi->init_req(1, old);
2298     new_phi->init_req(1, new_mark);
2299 
2300     transform_later(rebiased_region);
2301     transform_later(old_phi);
2302     transform_later(new_phi);
2303 
2304     // Try to acquire the bias of the object using an atomic operation.
2305     // If this fails we will go in to the runtime to revoke the object's bias.
2306     cas = new StoreXConditionalNode(rebiased_region, mem, adr, new_phi, old_phi);
2307     transform_later(cas);
2308     proj = transform_later(new SCMemProjNode(cas));
2309 
2310     // Get slow path - Failed to CAS.
2311     not_biased_ctrl = opt_bits_test(rebiased_region, region, 4, cas, 0, 0);
2312     mem_phi->init_req(4, proj);
2313     // region->in(4) is set to fast path - the object is rebiased to the current thread.
2314 
2315     // Failed to CAS.
2316     slow_path  = new RegionNode(3);
2317     Node *slow_mem = new PhiNode( slow_path, Type::MEMORY, TypeRawPtr::BOTTOM);
2318 
2319     slow_path->init_req(1, not_biased_ctrl); // Capture slow-control
2320     slow_mem->init_req(1, proj);
2321 
2322     // Call CAS-based locking scheme (FastLock node).
2323 
2324     transform_later(fast_lock_region);
2325     transform_later(fast_lock_mem_phi);
2326 
2327     // Get slow path - FastLock failed to lock the object.
2328     ctrl = opt_bits_test(fast_lock_region, region, 2, flock, 0, 0);
2329     mem_phi->init_req(2, fast_lock_mem_phi);
2330     // region->in(2) is set to fast path - the object is locked to the current thread.
2331 
2332     slow_path->init_req(2, ctrl); // Capture slow-control
2333     slow_mem->init_req(2, fast_lock_mem_phi);
2334 
2335     transform_later(slow_path);
2336     transform_later(slow_mem);
2337     // Reset lock's memory edge.
2338     lock->set_req(TypeFunc::Memory, slow_mem);
2339 
2340   } else {
2341     region  = new RegionNode(3);
2342     // create a Phi for the memory state
2343     mem_phi = new PhiNode( region, Type::MEMORY, TypeRawPtr::BOTTOM);
2344 
2345     // Optimize test; set region slot 2
2346     slow_path = opt_bits_test(ctrl, region, 2, flock, 0, 0);
2347     mem_phi->init_req(2, mem);
2348   }
2349 
2350   // Make slow path call
2351   CallNode *call = make_slow_call((CallNode *) lock, OptoRuntime::complete_monitor_enter_Type(),
2352                                   OptoRuntime::complete_monitor_locking_Java(), NULL, slow_path,
2353                                   obj, box, NULL);
2354 
2355   extract_call_projections(call);
2356 
2357   // Slow path can only throw asynchronous exceptions, which are always
2358   // de-opted.  So the compiler thinks the slow-call can never throw an
2359   // exception.  If it DOES throw an exception we would need the debug
2360   // info removed first (since if it throws there is no monitor).
2361   assert ( _ioproj_fallthrough == NULL && _ioproj_catchall == NULL &&
2362            _memproj_catchall == NULL && _catchallcatchproj == NULL, "Unexpected projection from Lock");
2363 
2364   // Capture slow path
2365   // disconnect fall-through projection from call and create a new one
2366   // hook up users of fall-through projection to region
2367   Node *slow_ctrl = _fallthroughproj->clone();
2368   transform_later(slow_ctrl);
2369   _igvn.hash_delete(_fallthroughproj);
2370   _fallthroughproj->disconnect_inputs(NULL, C);
2371   region->init_req(1, slow_ctrl);
2372   // region inputs are now complete
2373   transform_later(region);
2374   _igvn.replace_node(_fallthroughproj, region);
2375 
2376   Node *memproj = transform_later(new ProjNode(call, TypeFunc::Memory));
2377   mem_phi->init_req(1, memproj );
2378   transform_later(mem_phi);
2379   _igvn.replace_node(_memproj_fallthrough, mem_phi);
2380 }
2381 
2382 //------------------------------expand_unlock_node----------------------
expand_unlock_node(UnlockNode * unlock)2383 void PhaseMacroExpand::expand_unlock_node(UnlockNode *unlock) {
2384 
2385   Node* ctrl = unlock->in(TypeFunc::Control);
2386   Node* mem = unlock->in(TypeFunc::Memory);
2387   Node* obj = unlock->obj_node();
2388   Node* box = unlock->box_node();
2389 
2390   assert(!box->as_BoxLock()->is_eliminated(), "sanity");
2391 
2392   // No need for a null check on unlock
2393 
2394   // Make the merge point
2395   Node *region;
2396   Node *mem_phi;
2397 
2398   if (UseOptoBiasInlining) {
2399     // Check for biased locking unlock case, which is a no-op.
2400     // See the full description in MacroAssembler::biased_locking_exit().
2401     region  = new RegionNode(4);
2402     // create a Phi for the memory state
2403     mem_phi = new PhiNode( region, Type::MEMORY, TypeRawPtr::BOTTOM);
2404     mem_phi->init_req(3, mem);
2405 
2406     Node* mark_node = make_load(ctrl, mem, obj, oopDesc::mark_offset_in_bytes(), TypeX_X, TypeX_X->basic_type());
2407     ctrl = opt_bits_test(ctrl, region, 3, mark_node,
2408                          markOopDesc::biased_lock_mask_in_place,
2409                          markOopDesc::biased_lock_pattern);
2410   } else {
2411     region  = new RegionNode(3);
2412     // create a Phi for the memory state
2413     mem_phi = new PhiNode( region, Type::MEMORY, TypeRawPtr::BOTTOM);
2414   }
2415 
2416   FastUnlockNode *funlock = new FastUnlockNode( ctrl, obj, box );
2417   funlock = transform_later( funlock )->as_FastUnlock();
2418   // Optimize test; set region slot 2
2419   Node *slow_path = opt_bits_test(ctrl, region, 2, funlock, 0, 0);
2420   Node *thread = transform_later(new ThreadLocalNode());
2421 
2422   CallNode *call = make_slow_call((CallNode *) unlock, OptoRuntime::complete_monitor_exit_Type(),
2423                                   CAST_FROM_FN_PTR(address, SharedRuntime::complete_monitor_unlocking_C),
2424                                   "complete_monitor_unlocking_C", slow_path, obj, box, thread);
2425 
2426   extract_call_projections(call);
2427 
2428   assert ( _ioproj_fallthrough == NULL && _ioproj_catchall == NULL &&
2429            _memproj_catchall == NULL && _catchallcatchproj == NULL, "Unexpected projection from Lock");
2430 
2431   // No exceptions for unlocking
2432   // Capture slow path
2433   // disconnect fall-through projection from call and create a new one
2434   // hook up users of fall-through projection to region
2435   Node *slow_ctrl = _fallthroughproj->clone();
2436   transform_later(slow_ctrl);
2437   _igvn.hash_delete(_fallthroughproj);
2438   _fallthroughproj->disconnect_inputs(NULL, C);
2439   region->init_req(1, slow_ctrl);
2440   // region inputs are now complete
2441   transform_later(region);
2442   _igvn.replace_node(_fallthroughproj, region);
2443 
2444   Node *memproj = transform_later(new ProjNode(call, TypeFunc::Memory) );
2445   mem_phi->init_req(1, memproj );
2446   mem_phi->init_req(2, mem);
2447   transform_later(mem_phi);
2448   _igvn.replace_node(_memproj_fallthrough, mem_phi);
2449 }
2450 
2451 //---------------------------eliminate_macro_nodes----------------------
2452 // Eliminate scalar replaced allocations and associated locks.
eliminate_macro_nodes()2453 void PhaseMacroExpand::eliminate_macro_nodes() {
2454   if (C->macro_count() == 0)
2455     return;
2456 
2457   // First, attempt to eliminate locks
2458   int cnt = C->macro_count();
2459   for (int i=0; i < cnt; i++) {
2460     Node *n = C->macro_node(i);
2461     if (n->is_AbstractLock()) { // Lock and Unlock nodes
2462       // Before elimination mark all associated (same box and obj)
2463       // lock and unlock nodes.
2464       mark_eliminated_locking_nodes(n->as_AbstractLock());
2465     }
2466   }
2467   bool progress = true;
2468   while (progress) {
2469     progress = false;
2470     for (int i = C->macro_count(); i > 0; i--) {
2471       Node * n = C->macro_node(i-1);
2472       bool success = false;
2473       debug_only(int old_macro_count = C->macro_count(););
2474       if (n->is_AbstractLock()) {
2475         success = eliminate_locking_node(n->as_AbstractLock());
2476       }
2477       assert(success == (C->macro_count() < old_macro_count), "elimination reduces macro count");
2478       progress = progress || success;
2479     }
2480   }
2481   // Next, attempt to eliminate allocations
2482   _has_locks = false;
2483   progress = true;
2484   while (progress) {
2485     progress = false;
2486     for (int i = C->macro_count(); i > 0; i--) {
2487       Node * n = C->macro_node(i-1);
2488       bool success = false;
2489       debug_only(int old_macro_count = C->macro_count(););
2490       switch (n->class_id()) {
2491       case Node::Class_Allocate:
2492       case Node::Class_AllocateArray:
2493         success = eliminate_allocate_node(n->as_Allocate());
2494         break;
2495       case Node::Class_CallStaticJava:
2496         success = eliminate_boxing_node(n->as_CallStaticJava());
2497         break;
2498       case Node::Class_Lock:
2499       case Node::Class_Unlock:
2500         assert(!n->as_AbstractLock()->is_eliminated(), "sanity");
2501         _has_locks = true;
2502         break;
2503       case Node::Class_ArrayCopy:
2504         break;
2505       case Node::Class_OuterStripMinedLoop:
2506         break;
2507       default:
2508         assert(n->Opcode() == Op_LoopLimit ||
2509                n->Opcode() == Op_Opaque1   ||
2510                n->Opcode() == Op_Opaque2   ||
2511                n->Opcode() == Op_Opaque3   ||
2512                BarrierSet::barrier_set()->barrier_set_c2()->is_gc_barrier_node(n),
2513                "unknown node type in macro list");
2514       }
2515       assert(success == (C->macro_count() < old_macro_count), "elimination reduces macro count");
2516       progress = progress || success;
2517     }
2518   }
2519 }
2520 
2521 //------------------------------expand_macro_nodes----------------------
2522 //  Returns true if a failure occurred.
expand_macro_nodes()2523 bool PhaseMacroExpand::expand_macro_nodes() {
2524   // Last attempt to eliminate macro nodes.
2525   eliminate_macro_nodes();
2526 
2527   // Make sure expansion will not cause node limit to be exceeded.
2528   // Worst case is a macro node gets expanded into about 200 nodes.
2529   // Allow 50% more for optimization.
2530   if (C->check_node_count(C->macro_count() * 300, "out of nodes before macro expansion" ) )
2531     return true;
2532 
2533   // Eliminate Opaque and LoopLimit nodes. Do it after all loop optimizations.
2534   bool progress = true;
2535   while (progress) {
2536     progress = false;
2537     for (int i = C->macro_count(); i > 0; i--) {
2538       Node * n = C->macro_node(i-1);
2539       bool success = false;
2540       debug_only(int old_macro_count = C->macro_count(););
2541       if (n->Opcode() == Op_LoopLimit) {
2542         // Remove it from macro list and put on IGVN worklist to optimize.
2543         C->remove_macro_node(n);
2544         _igvn._worklist.push(n);
2545         success = true;
2546       } else if (n->Opcode() == Op_CallStaticJava) {
2547         // Remove it from macro list and put on IGVN worklist to optimize.
2548         C->remove_macro_node(n);
2549         _igvn._worklist.push(n);
2550         success = true;
2551       } else if (n->Opcode() == Op_Opaque1 || n->Opcode() == Op_Opaque2) {
2552         _igvn.replace_node(n, n->in(1));
2553         success = true;
2554 #if INCLUDE_RTM_OPT
2555       } else if ((n->Opcode() == Op_Opaque3) && ((Opaque3Node*)n)->rtm_opt()) {
2556         assert(C->profile_rtm(), "should be used only in rtm deoptimization code");
2557         assert((n->outcnt() == 1) && n->unique_out()->is_Cmp(), "");
2558         Node* cmp = n->unique_out();
2559 #ifdef ASSERT
2560         // Validate graph.
2561         assert((cmp->outcnt() == 1) && cmp->unique_out()->is_Bool(), "");
2562         BoolNode* bol = cmp->unique_out()->as_Bool();
2563         assert((bol->outcnt() == 1) && bol->unique_out()->is_If() &&
2564                (bol->_test._test == BoolTest::ne), "");
2565         IfNode* ifn = bol->unique_out()->as_If();
2566         assert((ifn->outcnt() == 2) &&
2567                ifn->proj_out(1)->is_uncommon_trap_proj(Deoptimization::Reason_rtm_state_change) != NULL, "");
2568 #endif
2569         Node* repl = n->in(1);
2570         if (!_has_locks) {
2571           // Remove RTM state check if there are no locks in the code.
2572           // Replace input to compare the same value.
2573           repl = (cmp->in(1) == n) ? cmp->in(2) : cmp->in(1);
2574         }
2575         _igvn.replace_node(n, repl);
2576         success = true;
2577 #endif
2578       } else if (n->Opcode() == Op_OuterStripMinedLoop) {
2579         n->as_OuterStripMinedLoop()->adjust_strip_mined_loop(&_igvn);
2580         C->remove_macro_node(n);
2581         success = true;
2582       }
2583       assert(success == (C->macro_count() < old_macro_count), "elimination reduces macro count");
2584       progress = progress || success;
2585     }
2586   }
2587 
2588   // expand arraycopy "macro" nodes first
2589   // For ReduceBulkZeroing, we must first process all arraycopy nodes
2590   // before the allocate nodes are expanded.
2591   int macro_idx = C->macro_count() - 1;
2592   while (macro_idx >= 0) {
2593     Node * n = C->macro_node(macro_idx);
2594     assert(n->is_macro(), "only macro nodes expected here");
2595     if (_igvn.type(n) == Type::TOP || (n->in(0) != NULL && n->in(0)->is_top())) {
2596       // node is unreachable, so don't try to expand it
2597       C->remove_macro_node(n);
2598     } else if (n->is_ArrayCopy()){
2599       int macro_count = C->macro_count();
2600       expand_arraycopy_node(n->as_ArrayCopy());
2601       assert(C->macro_count() < macro_count, "must have deleted a node from macro list");
2602     }
2603     if (C->failing())  return true;
2604     macro_idx --;
2605   }
2606 
2607   // expand "macro" nodes
2608   // nodes are removed from the macro list as they are processed
2609   while (C->macro_count() > 0) {
2610     int macro_count = C->macro_count();
2611     Node * n = C->macro_node(macro_count-1);
2612     assert(n->is_macro(), "only macro nodes expected here");
2613     if (_igvn.type(n) == Type::TOP || (n->in(0) != NULL && n->in(0)->is_top())) {
2614       // node is unreachable, so don't try to expand it
2615       C->remove_macro_node(n);
2616       continue;
2617     }
2618     switch (n->class_id()) {
2619     case Node::Class_Allocate:
2620       expand_allocate(n->as_Allocate());
2621       break;
2622     case Node::Class_AllocateArray:
2623       expand_allocate_array(n->as_AllocateArray());
2624       break;
2625     case Node::Class_Lock:
2626       expand_lock_node(n->as_Lock());
2627       break;
2628     case Node::Class_Unlock:
2629       expand_unlock_node(n->as_Unlock());
2630       break;
2631     default:
2632       assert(false, "unknown node type in macro list");
2633     }
2634     assert(C->macro_count() < macro_count, "must have deleted a node from macro list");
2635     if (C->failing())  return true;
2636   }
2637 
2638   _igvn.set_delay_transform(false);
2639   _igvn.optimize();
2640   if (C->failing())  return true;
2641   return false;
2642 }
2643