blob: e79abac0c1947c2f9308e23a62a1cfd4c936a000 [file] [log] [blame]
J. Duke81537792007-12-01 00:00:00 +00001/*
Stefan Karlsson4913ad52015-02-13 14:37:35 +01002 * Copyright (c) 1997, 2015, Oracle and/or its affiliates. All rights reserved.
J. Duke81537792007-12-01 00:00:00 +00003 * 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 *
Erik Trimbleba7c1732010-05-27 19:08:38 -070019 * 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.
J. Duke81537792007-12-01 00:00:00 +000022 *
23 */
24
Stefan Karlsson8006fe82010-11-23 13:22:55 -080025#include "precompiled.hpp"
26#include "classfile/systemDictionary.hpp"
27#include "compiler/compileLog.hpp"
28#include "memory/allocation.inline.hpp"
29#include "oops/objArrayKlass.hpp"
30#include "opto/addnode.hpp"
Roland Westrelina9cdbd02015-05-12 10:27:50 +020031#include "opto/arraycopynode.hpp"
Stefan Karlsson8006fe82010-11-23 13:22:55 -080032#include "opto/cfgnode.hpp"
33#include "opto/compile.hpp"
34#include "opto/connode.hpp"
Morris Meyer6db303a2014-04-01 09:05:20 -070035#include "opto/convertnode.hpp"
Stefan Karlsson8006fe82010-11-23 13:22:55 -080036#include "opto/loopnode.hpp"
37#include "opto/machnode.hpp"
38#include "opto/matcher.hpp"
39#include "opto/memnode.hpp"
40#include "opto/mulnode.hpp"
Morris Meyer6db303a2014-04-01 09:05:20 -070041#include "opto/narrowptrnode.hpp"
Stefan Karlsson8006fe82010-11-23 13:22:55 -080042#include "opto/phaseX.hpp"
43#include "opto/regmask.hpp"
Stefan Karlsson4913ad52015-02-13 14:37:35 +010044#include "utilities/copy.hpp"
Stefan Karlsson8006fe82010-11-23 13:22:55 -080045
J. Duke81537792007-12-01 00:00:00 +000046// Portions of code courtesy of Clifford Click
47
48// Optimization - Graph Style
49
Vladimir Kozlovcdd27962008-03-20 15:11:44 -070050static Node *step_through_mergemem(PhaseGVN *phase, MergeMemNode *mmem, const TypePtr *tp, const TypePtr *adr_check, outputStream *st);
51
J. Duke81537792007-12-01 00:00:00 +000052//=============================================================================
53uint MemNode::size_of() const { return sizeof(*this); }
54
55const TypePtr *MemNode::adr_type() const {
56 Node* adr = in(Address);
Vladimir Ivanovf3d90962014-11-17 14:02:45 -080057 if (adr == NULL) return NULL; // node is dead
J. Duke81537792007-12-01 00:00:00 +000058 const TypePtr* cross_check = NULL;
59 DEBUG_ONLY(cross_check = _adr_type);
60 return calculate_adr_type(adr->bottom_type(), cross_check);
61}
62
63#ifndef PRODUCT
64void MemNode::dump_spec(outputStream *st) const {
65 if (in(Address) == NULL) return; // node is dead
66#ifndef ASSERT
67 // fake the missing field
68 const TypePtr* _adr_type = NULL;
69 if (in(Address) != NULL)
70 _adr_type = in(Address)->bottom_type()->isa_ptr();
71#endif
72 dump_adr_type(this, _adr_type, st);
73
74 Compile* C = Compile::current();
Roland Westrelin45b3ce82015-10-28 10:20:33 +010075 if (C->alias_type(_adr_type)->is_volatile()) {
J. Duke81537792007-12-01 00:00:00 +000076 st->print(" Volatile!");
Roland Westrelin45b3ce82015-10-28 10:20:33 +010077 }
78 if (_unaligned_access) {
79 st->print(" unaligned");
80 }
81 if (_mismatched_access) {
82 st->print(" mismatched");
83 }
J. Duke81537792007-12-01 00:00:00 +000084}
85
86void MemNode::dump_adr_type(const Node* mem, const TypePtr* adr_type, outputStream *st) {
87 st->print(" @");
88 if (adr_type == NULL) {
89 st->print("NULL");
90 } else {
91 adr_type->dump_on(st);
92 Compile* C = Compile::current();
93 Compile::AliasType* atp = NULL;
94 if (C->have_alias_type(adr_type)) atp = C->alias_type(adr_type);
95 if (atp == NULL)
96 st->print(", idx=?\?;");
97 else if (atp->index() == Compile::AliasIdxBot)
98 st->print(", idx=Bot;");
99 else if (atp->index() == Compile::AliasIdxTop)
100 st->print(", idx=Top;");
101 else if (atp->index() == Compile::AliasIdxRaw)
102 st->print(", idx=Raw;");
103 else {
104 ciField* field = atp->field();
105 if (field) {
106 st->print(", name=");
107 field->print_name_on(st);
108 }
109 st->print(", idx=%d;", atp->index());
110 }
111 }
112}
113
114extern void print_alias_types();
115
116#endif
117
Vladimir Kozlovb4977e82013-05-08 15:08:01 -0700118Node *MemNode::optimize_simple_memory_chain(Node *mchain, const TypeOopPtr *t_oop, Node *load, PhaseGVN *phase) {
119 assert((t_oop != NULL), "sanity");
120 bool is_instance = t_oop->is_known_instance_field();
121 bool is_boxed_value_load = t_oop->is_ptr_to_boxed_value() &&
122 (load != NULL) && load->is_Load() &&
123 (phase->is_IterGVN() != NULL);
124 if (!(is_instance || is_boxed_value_load))
Vladimir Kozlovcdd27962008-03-20 15:11:44 -0700125 return mchain; // don't try to optimize non-instance types
Vladimir Kozlovb4977e82013-05-08 15:08:01 -0700126 uint instance_id = t_oop->instance_id();
Vladimir Kozlov50c4a232008-07-28 17:12:52 -0700127 Node *start_mem = phase->C->start()->proj_out(TypeFunc::Memory);
Vladimir Kozlovcdd27962008-03-20 15:11:44 -0700128 Node *prev = NULL;
129 Node *result = mchain;
130 while (prev != result) {
131 prev = result;
Vladimir Kozlov50c4a232008-07-28 17:12:52 -0700132 if (result == start_mem)
Christian Thalinger05d1de72009-02-27 13:27:09 -0800133 break; // hit one of our sentinels
Vladimir Kozlovcdd27962008-03-20 15:11:44 -0700134 // skip over a call which does not affect this memory slice
135 if (result->is_Proj() && result->as_Proj()->_con == TypeFunc::Memory) {
136 Node *proj_in = result->in(0);
Vladimir Kozlov50c4a232008-07-28 17:12:52 -0700137 if (proj_in->is_Allocate() && proj_in->_idx == instance_id) {
Christian Thalinger05d1de72009-02-27 13:27:09 -0800138 break; // hit one of our sentinels
Vladimir Kozlov50c4a232008-07-28 17:12:52 -0700139 } else if (proj_in->is_Call()) {
Roland Westrelina9cdbd02015-05-12 10:27:50 +0200140 // ArrayCopyNodes processed here as well
Vladimir Kozlovcdd27962008-03-20 15:11:44 -0700141 CallNode *call = proj_in->as_Call();
Vladimir Kozlovb4977e82013-05-08 15:08:01 -0700142 if (!call->may_modify(t_oop, phase)) { // returns false for instances
Vladimir Kozlovcdd27962008-03-20 15:11:44 -0700143 result = call->in(TypeFunc::Memory);
144 }
145 } else if (proj_in->is_Initialize()) {
146 AllocateNode* alloc = proj_in->as_Initialize()->allocation();
147 // Stop if this is the initialization for the object instance which
Roland Westrelina9cdbd02015-05-12 10:27:50 +0200148 // contains this memory slice, otherwise skip over it.
Vladimir Kozlovb4977e82013-05-08 15:08:01 -0700149 if ((alloc == NULL) || (alloc->_idx == instance_id)) {
150 break;
151 }
152 if (is_instance) {
Vladimir Kozlovcdd27962008-03-20 15:11:44 -0700153 result = proj_in->in(TypeFunc::Memory);
Vladimir Kozlovb4977e82013-05-08 15:08:01 -0700154 } else if (is_boxed_value_load) {
155 Node* klass = alloc->in(AllocateNode::KlassNode);
156 const TypeKlassPtr* tklass = phase->type(klass)->is_klassptr();
157 if (tklass->klass_is_exact() && !tklass->klass()->equals(t_oop->klass())) {
158 result = proj_in->in(TypeFunc::Memory); // not related allocation
159 }
Vladimir Kozlovcdd27962008-03-20 15:11:44 -0700160 }
161 } else if (proj_in->is_MemBar()) {
Roland Westrelin0baf2f72015-08-15 02:54:18 +0200162 if (ArrayCopyNode::may_modify(t_oop, proj_in->as_MemBar(), phase)) {
Roland Westrelina9cdbd02015-05-12 10:27:50 +0200163 break;
164 }
Vladimir Kozlovcdd27962008-03-20 15:11:44 -0700165 result = proj_in->in(TypeFunc::Memory);
Vladimir Kozlov50c4a232008-07-28 17:12:52 -0700166 } else {
167 assert(false, "unexpected projection");
Vladimir Kozlovcdd27962008-03-20 15:11:44 -0700168 }
Vladimir Kozlov9f5ca022009-12-09 16:40:45 -0800169 } else if (result->is_ClearArray()) {
Vladimir Kozlovb4977e82013-05-08 15:08:01 -0700170 if (!is_instance || !ClearArrayNode::step_through(&result, instance_id, phase)) {
Vladimir Kozlov9f5ca022009-12-09 16:40:45 -0800171 // Can not bypass initialization of the instance
172 // we are looking for.
173 break;
174 }
175 // Otherwise skip it (the call updated 'result' value).
Vladimir Kozlovcdd27962008-03-20 15:11:44 -0700176 } else if (result->is_MergeMem()) {
Vladimir Kozlovb4977e82013-05-08 15:08:01 -0700177 result = step_through_mergemem(phase, result->as_MergeMem(), t_oop, NULL, tty);
Vladimir Kozlovcdd27962008-03-20 15:11:44 -0700178 }
179 }
180 return result;
181}
182
Vladimir Kozlovb4977e82013-05-08 15:08:01 -0700183Node *MemNode::optimize_memory_chain(Node *mchain, const TypePtr *t_adr, Node *load, PhaseGVN *phase) {
184 const TypeOopPtr* t_oop = t_adr->isa_oopptr();
185 if (t_oop == NULL)
186 return mchain; // don't try to optimize non-oop types
187 Node* result = optimize_simple_memory_chain(mchain, t_oop, load, phase);
188 bool is_instance = t_oop->is_known_instance_field();
Vladimir Kozlovcdd27962008-03-20 15:11:44 -0700189 PhaseIterGVN *igvn = phase->is_IterGVN();
Vladimir Kozlovcdd27962008-03-20 15:11:44 -0700190 if (is_instance && igvn != NULL && result->is_Phi()) {
191 PhiNode *mphi = result->as_Phi();
192 assert(mphi->bottom_type() == Type::MEMORY, "memory phi required");
193 const TypePtr *t = mphi->adr_type();
Vladimir Kozlov757229d2008-05-21 10:45:07 -0700194 if (t == TypePtr::BOTTOM || t == TypeRawPtr::BOTTOM ||
Vladimir Kozlov4213e622008-06-26 13:34:00 -0700195 t->isa_oopptr() && !t->is_oopptr()->is_known_instance() &&
Vladimir Kozlovfae39062008-07-16 16:04:39 -0700196 t->is_oopptr()->cast_to_exactness(true)
197 ->is_oopptr()->cast_to_ptr_type(t_oop->ptr())
198 ->is_oopptr()->cast_to_instance_id(t_oop->instance_id()) == t_oop) {
Vladimir Kozlovcdd27962008-03-20 15:11:44 -0700199 // clone the Phi with our address type
200 result = mphi->split_out_instance(t_adr, igvn);
201 } else {
202 assert(phase->C->get_alias_index(t) == phase->C->get_alias_index(t_adr), "correct memory chain");
203 }
204 }
205 return result;
206}
207
Vladimir Kozlov30dc0ed2008-03-13 16:31:32 -0700208static Node *step_through_mergemem(PhaseGVN *phase, MergeMemNode *mmem, const TypePtr *tp, const TypePtr *adr_check, outputStream *st) {
209 uint alias_idx = phase->C->get_alias_index(tp);
210 Node *mem = mmem;
211#ifdef ASSERT
212 {
213 // Check that current type is consistent with the alias index used during graph construction
214 assert(alias_idx >= Compile::AliasIdxRaw, "must not be a bad alias_idx");
215 bool consistent = adr_check == NULL || adr_check->empty() ||
216 phase->C->must_alias(adr_check, alias_idx );
217 // Sometimes dead array references collapse to a[-1], a[-2], or a[-3]
218 if( !consistent && adr_check != NULL && !adr_check->empty() &&
Chuck Rasbold2e672ac2008-05-29 16:22:09 -0700219 tp->isa_aryptr() && tp->offset() == Type::OffsetBot &&
Vladimir Kozlov30dc0ed2008-03-13 16:31:32 -0700220 adr_check->isa_aryptr() && adr_check->offset() != Type::OffsetBot &&
221 ( adr_check->offset() == arrayOopDesc::length_offset_in_bytes() ||
222 adr_check->offset() == oopDesc::klass_offset_in_bytes() ||
223 adr_check->offset() == oopDesc::mark_offset_in_bytes() ) ) {
224 // don't assert if it is dead code.
225 consistent = true;
226 }
227 if( !consistent ) {
228 st->print("alias_idx==%d, adr_check==", alias_idx);
229 if( adr_check == NULL ) {
230 st->print("NULL");
231 } else {
232 adr_check->dump();
233 }
234 st->cr();
235 print_alias_types();
236 assert(consistent, "adr_check must match alias idx");
237 }
238 }
239#endif
Tom Rodriguezf4b4eae2010-09-22 13:01:12 -0700240 // TypeOopPtr::NOTNULL+any is an OOP with unknown offset - generally
Vladimir Kozlov30dc0ed2008-03-13 16:31:32 -0700241 // means an array I have not precisely typed yet. Do not do any
242 // alias stuff with it any time soon.
Tom Rodriguezf4b4eae2010-09-22 13:01:12 -0700243 const TypeOopPtr *toop = tp->isa_oopptr();
Vladimir Kozlov30dc0ed2008-03-13 16:31:32 -0700244 if( tp->base() != Type::AnyPtr &&
Tom Rodriguezf4b4eae2010-09-22 13:01:12 -0700245 !(toop &&
246 toop->klass() != NULL &&
247 toop->klass()->is_java_lang_Object() &&
248 toop->offset() == Type::OffsetBot) ) {
Vladimir Kozlov30dc0ed2008-03-13 16:31:32 -0700249 // compress paths and change unreachable cycles to TOP
250 // If not, we can update the input infinitely along a MergeMem cycle
251 // Equivalent code in PhiNode::Ideal
252 Node* m = phase->transform(mmem);
Christian Thalinger05d1de72009-02-27 13:27:09 -0800253 // If transformed to a MergeMem, get the desired slice
Vladimir Kozlov30dc0ed2008-03-13 16:31:32 -0700254 // Otherwise the returned node represents memory for every slice
255 mem = (m->is_MergeMem())? m->as_MergeMem()->memory_at(alias_idx) : m;
256 // Update input if it is progress over what we have now
257 }
258 return mem;
259}
260
J. Duke81537792007-12-01 00:00:00 +0000261//--------------------------Ideal_common---------------------------------------
262// Look for degenerate control and memory inputs. Bypass MergeMem inputs.
263// Unhook non-raw memories from complete (macro-expanded) initializations.
264Node *MemNode::Ideal_common(PhaseGVN *phase, bool can_reshape) {
265 // If our control input is a dead region, kill all below the region
266 Node *ctl = in(MemNode::Control);
267 if (ctl && remove_dead_region(phase, can_reshape))
268 return this;
Vladimir Kozlov37306312008-08-27 09:15:46 -0700269 ctl = in(MemNode::Control);
270 // Don't bother trying to transform a dead node
Vladimir Kozlov010f6402013-03-06 12:25:57 -0800271 if (ctl && ctl->is_top()) return NodeSentinel;
J. Duke81537792007-12-01 00:00:00 +0000272
Vladimir Kozlovca3a3502009-04-07 19:04:24 -0700273 PhaseIterGVN *igvn = phase->is_IterGVN();
274 // Wait if control on the worklist.
275 if (ctl && can_reshape && igvn != NULL) {
276 Node* bol = NULL;
277 Node* cmp = NULL;
278 if (ctl->in(0)->is_If()) {
279 assert(ctl->is_IfTrue() || ctl->is_IfFalse(), "sanity");
280 bol = ctl->in(0)->in(1);
281 if (bol->is_Bool())
282 cmp = ctl->in(0)->in(1)->in(1);
283 }
284 if (igvn->_worklist.member(ctl) ||
285 (bol != NULL && igvn->_worklist.member(bol)) ||
286 (cmp != NULL && igvn->_worklist.member(cmp)) ) {
287 // This control path may be dead.
288 // Delay this memory node transformation until the control is processed.
289 phase->is_IterGVN()->_worklist.push(this);
290 return NodeSentinel; // caller will return NULL
291 }
292 }
J. Duke81537792007-12-01 00:00:00 +0000293 // Ignore if memory is dead, or self-loop
294 Node *mem = in(MemNode::Memory);
Vladimir Kozlov010f6402013-03-06 12:25:57 -0800295 if (phase->type( mem ) == Type::TOP) return NodeSentinel; // caller will return NULL
296 assert(mem != this, "dead loop in MemNode::Ideal");
J. Duke81537792007-12-01 00:00:00 +0000297
Vladimir Kozlov78034a32011-12-02 21:37:19 -0800298 if (can_reshape && igvn != NULL && igvn->_worklist.member(mem)) {
299 // This memory slice may be dead.
300 // Delay this mem node transformation until the memory is processed.
301 phase->is_IterGVN()->_worklist.push(this);
302 return NodeSentinel; // caller will return NULL
303 }
304
J. Duke81537792007-12-01 00:00:00 +0000305 Node *address = in(MemNode::Address);
Vladimir Kozlov010f6402013-03-06 12:25:57 -0800306 const Type *t_adr = phase->type(address);
307 if (t_adr == Type::TOP) return NodeSentinel; // caller will return NULL
J. Duke81537792007-12-01 00:00:00 +0000308
Vladimir Kozlov010f6402013-03-06 12:25:57 -0800309 if (can_reshape && igvn != NULL &&
Vladimir Kozlov7cc55732010-09-30 18:31:45 -0700310 (igvn->_worklist.member(address) ||
Vladimir Kozlov010f6402013-03-06 12:25:57 -0800311 igvn->_worklist.size() > 0 && (t_adr != adr_type())) ) {
Vladimir Kozlov7aae40a2008-11-07 09:29:38 -0800312 // The address's base and type may change when the address is processed.
313 // Delay this mem node transformation until the address is processed.
314 phase->is_IterGVN()->_worklist.push(this);
315 return NodeSentinel; // caller will return NULL
316 }
317
Vladimir Kozlovc5744bd2009-11-04 14:43:50 -0800318 // Do NOT remove or optimize the next lines: ensure a new alias index
319 // is allocated for an oop pointer type before Escape Analysis.
320 // Note: C++ will not remove it since the call has side effect.
Vladimir Kozlov010f6402013-03-06 12:25:57 -0800321 if (t_adr->isa_oopptr()) {
Vladimir Kozlovc5744bd2009-11-04 14:43:50 -0800322 int alias_idx = phase->C->get_alias_index(t_adr->is_ptr());
323 }
324
Vladimir Kozlovca3a3502009-04-07 19:04:24 -0700325 Node* base = NULL;
Vladimir Kozlovc909ac42014-05-02 16:44:54 -0700326 if (address->is_AddP()) {
Vladimir Kozlovca3a3502009-04-07 19:04:24 -0700327 base = address->in(AddPNode::Base);
Vladimir Kozlovc909ac42014-05-02 16:44:54 -0700328 }
Vladimir Kozlov010f6402013-03-06 12:25:57 -0800329 if (base != NULL && phase->type(base)->higher_equal(TypePtr::NULL_PTR) &&
330 !t_adr->isa_rawptr()) {
331 // Note: raw address has TOP base and top->higher_equal(TypePtr::NULL_PTR) is true.
Vladimir Kozlovc909ac42014-05-02 16:44:54 -0700332 // Skip this node optimization if its address has TOP base.
333 return NodeSentinel; // caller will return NULL
Vladimir Kozlov010f6402013-03-06 12:25:57 -0800334 }
Vladimir Kozlovca3a3502009-04-07 19:04:24 -0700335
J. Duke81537792007-12-01 00:00:00 +0000336 // Avoid independent memory operations
337 Node* old_mem = mem;
338
Vladimir Kozlovdc6ad192008-02-29 19:57:41 -0800339 // The code which unhooks non-raw memories from complete (macro-expanded)
340 // initializations was removed. After macro-expansion all stores catched
341 // by Initialize node became raw stores and there is no information
342 // which memory slices they modify. So it is unsafe to move any memory
343 // operation above these stores. Also in most cases hooked non-raw memories
344 // were already unhooked by using information from detect_ptr_independence()
345 // and find_previous_store().
J. Duke81537792007-12-01 00:00:00 +0000346
347 if (mem->is_MergeMem()) {
348 MergeMemNode* mmem = mem->as_MergeMem();
349 const TypePtr *tp = t_adr->is_ptr();
Vladimir Kozlov30dc0ed2008-03-13 16:31:32 -0700350
351 mem = step_through_mergemem(phase, mmem, tp, adr_type(), tty);
J. Duke81537792007-12-01 00:00:00 +0000352 }
353
354 if (mem != old_mem) {
355 set_req(MemNode::Memory, mem);
Roland Westrelinfe928622013-02-25 14:13:04 +0100356 if (can_reshape && old_mem->outcnt() == 0) {
357 igvn->_worklist.push(old_mem);
358 }
Vladimir Kozlov37306312008-08-27 09:15:46 -0700359 if (phase->type( mem ) == Type::TOP) return NodeSentinel;
J. Duke81537792007-12-01 00:00:00 +0000360 return this;
361 }
362
363 // let the subclass continue analyzing...
364 return NULL;
365}
366
367// Helper function for proving some simple control dominations.
Vladimir Kozlovdf8fc192008-04-16 19:19:48 -0700368// Attempt to prove that all control inputs of 'dom' dominate 'sub'.
J. Duke81537792007-12-01 00:00:00 +0000369// Already assumes that 'dom' is available at 'sub', and that 'sub'
370// is not a constant (dominated by the method's StartNode).
371// Used by MemNode::find_previous_store to prove that the
372// control input of a memory operation predates (dominates)
373// an allocation it wants to look past.
Vladimir Kozlovdf8fc192008-04-16 19:19:48 -0700374bool MemNode::all_controls_dominate(Node* dom, Node* sub) {
375 if (dom == NULL || dom->is_top() || sub == NULL || sub->is_top())
376 return false; // Conservative answer for dead code
377
Vladimir Kozlov6978df82008-06-13 15:08:56 -0700378 // Check 'dom'. Skip Proj and CatchProj nodes.
Vladimir Kozlovdf8fc192008-04-16 19:19:48 -0700379 dom = dom->find_exact_control(dom);
380 if (dom == NULL || dom->is_top())
381 return false; // Conservative answer for dead code
382
Vladimir Kozlov6978df82008-06-13 15:08:56 -0700383 if (dom == sub) {
384 // For the case when, for example, 'sub' is Initialize and the original
385 // 'dom' is Proj node of the 'sub'.
386 return false;
387 }
388
Vladimir Kozlov60c74ba2008-05-15 22:43:11 -0700389 if (dom->is_Con() || dom->is_Start() || dom->is_Root() || dom == sub)
Vladimir Kozlovdf8fc192008-04-16 19:19:48 -0700390 return true;
391
392 // 'dom' dominates 'sub' if its control edge and control edges
393 // of all its inputs dominate or equal to sub's control edge.
394
395 // Currently 'sub' is either Allocate, Initialize or Start nodes.
Vladimir Kozlov757229d2008-05-21 10:45:07 -0700396 // Or Region for the check in LoadNode::Ideal();
397 // 'sub' should have sub->in(0) != NULL.
398 assert(sub->is_Allocate() || sub->is_Initialize() || sub->is_Start() ||
Vladimir Kozlovb4977e82013-05-08 15:08:01 -0700399 sub->is_Region() || sub->is_Call(), "expecting only these nodes");
Vladimir Kozlovdf8fc192008-04-16 19:19:48 -0700400
401 // Get control edge of 'sub'.
Vladimir Kozlov6978df82008-06-13 15:08:56 -0700402 Node* orig_sub = sub;
Vladimir Kozlovdf8fc192008-04-16 19:19:48 -0700403 sub = sub->find_exact_control(sub->in(0));
404 if (sub == NULL || sub->is_top())
405 return false; // Conservative answer for dead code
406
407 assert(sub->is_CFG(), "expecting control");
408
409 if (sub == dom)
410 return true;
411
412 if (sub->is_Start() || sub->is_Root())
413 return false;
414
415 {
416 // Check all control edges of 'dom'.
417
418 ResourceMark rm;
419 Arena* arena = Thread::current()->resource_area();
420 Node_List nlist(arena);
421 Unique_Node_List dom_list(arena);
422
423 dom_list.push(dom);
424 bool only_dominating_controls = false;
425
426 for (uint next = 0; next < dom_list.size(); next++) {
427 Node* n = dom_list.at(next);
Vladimir Kozlov6978df82008-06-13 15:08:56 -0700428 if (n == orig_sub)
429 return false; // One of dom's inputs dominated by sub.
Vladimir Kozlovdf8fc192008-04-16 19:19:48 -0700430 if (!n->is_CFG() && n->pinned()) {
431 // Check only own control edge for pinned non-control nodes.
432 n = n->find_exact_control(n->in(0));
433 if (n == NULL || n->is_top())
434 return false; // Conservative answer for dead code
435 assert(n->is_CFG(), "expecting control");
Vladimir Kozlov6978df82008-06-13 15:08:56 -0700436 dom_list.push(n);
437 } else if (n->is_Con() || n->is_Start() || n->is_Root()) {
Vladimir Kozlovdf8fc192008-04-16 19:19:48 -0700438 only_dominating_controls = true;
439 } else if (n->is_CFG()) {
440 if (n->dominates(sub, nlist))
441 only_dominating_controls = true;
442 else
443 return false;
444 } else {
445 // First, own control edge.
446 Node* m = n->find_exact_control(n->in(0));
Vladimir Kozlov60c74ba2008-05-15 22:43:11 -0700447 if (m != NULL) {
448 if (m->is_top())
449 return false; // Conservative answer for dead code
450 dom_list.push(m);
451 }
Vladimir Kozlovdf8fc192008-04-16 19:19:48 -0700452 // Now, the rest of edges.
453 uint cnt = n->req();
454 for (uint i = 1; i < cnt; i++) {
455 m = n->find_exact_control(n->in(i));
456 if (m == NULL || m->is_top())
457 continue;
458 dom_list.push(m);
J. Duke81537792007-12-01 00:00:00 +0000459 }
460 }
461 }
Vladimir Kozlovdf8fc192008-04-16 19:19:48 -0700462 return only_dominating_controls;
J. Duke81537792007-12-01 00:00:00 +0000463 }
J. Duke81537792007-12-01 00:00:00 +0000464}
465
466//---------------------detect_ptr_independence---------------------------------
467// Used by MemNode::find_previous_store to prove that two base
468// pointers are never equal.
469// The pointers are accompanied by their associated allocations,
470// if any, which have been previously discovered by the caller.
471bool MemNode::detect_ptr_independence(Node* p1, AllocateNode* a1,
472 Node* p2, AllocateNode* a2,
473 PhaseTransform* phase) {
474 // Attempt to prove that these two pointers cannot be aliased.
475 // They may both manifestly be allocations, and they should differ.
476 // Or, if they are not both allocations, they can be distinct constants.
477 // Otherwise, one is an allocation and the other a pre-existing value.
478 if (a1 == NULL && a2 == NULL) { // neither an allocation
479 return (p1 != p2) && p1->is_Con() && p2->is_Con();
480 } else if (a1 != NULL && a2 != NULL) { // both allocations
481 return (a1 != a2);
482 } else if (a1 != NULL) { // one allocation a1
483 // (Note: p2->is_Con implies p2->in(0)->is_Root, which dominates.)
Vladimir Kozlovdf8fc192008-04-16 19:19:48 -0700484 return all_controls_dominate(p2, a1);
J. Duke81537792007-12-01 00:00:00 +0000485 } else { //(a2 != NULL) // one allocation a2
Vladimir Kozlovdf8fc192008-04-16 19:19:48 -0700486 return all_controls_dominate(p1, a2);
J. Duke81537792007-12-01 00:00:00 +0000487 }
488 return false;
489}
490
491
Roland Westrelina9cdbd02015-05-12 10:27:50 +0200492// Find an arraycopy that must have set (can_see_stored_value=true) or
493// could have set (can_see_stored_value=false) the value for this load
494Node* LoadNode::find_previous_arraycopy(PhaseTransform* phase, Node* ld_alloc, Node*& mem, bool can_see_stored_value) const {
495 if (mem->is_Proj() && mem->in(0) != NULL && (mem->in(0)->Opcode() == Op_MemBarStoreStore ||
496 mem->in(0)->Opcode() == Op_MemBarCPUOrder)) {
497 Node* mb = mem->in(0);
498 if (mb->in(0) != NULL && mb->in(0)->is_Proj() &&
499 mb->in(0)->in(0) != NULL && mb->in(0)->in(0)->is_ArrayCopy()) {
500 ArrayCopyNode* ac = mb->in(0)->in(0)->as_ArrayCopy();
501 if (ac->is_clonebasic()) {
502 intptr_t offset;
503 AllocateNode* alloc = AllocateNode::Ideal_allocation(ac->in(ArrayCopyNode::Dest), phase, offset);
504 assert(alloc != NULL && alloc->initialization()->is_complete_with_arraycopy(), "broken allocation");
505 if (alloc == ld_alloc) {
506 return ac;
507 }
508 }
509 }
510 } else if (mem->is_Proj() && mem->in(0) != NULL && mem->in(0)->is_ArrayCopy()) {
511 ArrayCopyNode* ac = mem->in(0)->as_ArrayCopy();
512
513 if (ac->is_arraycopy_validated() ||
514 ac->is_copyof_validated() ||
515 ac->is_copyofrange_validated()) {
516 Node* ld_addp = in(MemNode::Address);
517 if (ld_addp->is_AddP()) {
518 Node* ld_base = ld_addp->in(AddPNode::Address);
519 Node* ld_offs = ld_addp->in(AddPNode::Offset);
520
521 Node* dest = ac->in(ArrayCopyNode::Dest);
522
523 if (dest == ld_base) {
Roland Westrelina9cdbd02015-05-12 10:27:50 +0200524 const TypeX *ld_offs_t = phase->type(ld_offs)->isa_intptr_t();
Roland Westrelin0baf2f72015-08-15 02:54:18 +0200525 if (ac->modifies(ld_offs_t->_lo, ld_offs_t->_hi, phase, can_see_stored_value)) {
526 return ac;
527 }
528 if (!can_see_stored_value) {
529 mem = ac->in(TypeFunc::Memory);
Roland Westrelina9cdbd02015-05-12 10:27:50 +0200530 }
531 }
532 }
533 }
534 }
535 return NULL;
536}
537
J. Duke81537792007-12-01 00:00:00 +0000538// The logic for reordering loads and stores uses four steps:
539// (a) Walk carefully past stores and initializations which we
540// can prove are independent of this load.
541// (b) Observe that the next memory state makes an exact match
542// with self (load or store), and locate the relevant store.
543// (c) Ensure that, if we were to wire self directly to the store,
544// the optimizer would fold it up somehow.
545// (d) Do the rewiring, and return, depending on some other part of
546// the optimizer to fold up the load.
547// This routine handles steps (a) and (b). Steps (c) and (d) are
548// specific to loads and stores, so they are handled by the callers.
549// (Currently, only LoadNode::Ideal has steps (c), (d). More later.)
550//
551Node* MemNode::find_previous_store(PhaseTransform* phase) {
552 Node* ctrl = in(MemNode::Control);
553 Node* adr = in(MemNode::Address);
554 intptr_t offset = 0;
555 Node* base = AddPNode::Ideal_base_and_offset(adr, phase, offset);
556 AllocateNode* alloc = AllocateNode::Ideal_allocation(base, phase);
557
558 if (offset == Type::OffsetBot)
559 return NULL; // cannot unalias unless there are precise offsets
560
Vladimir Kozlovcdd27962008-03-20 15:11:44 -0700561 const TypeOopPtr *addr_t = adr->bottom_type()->isa_oopptr();
562
J. Duke81537792007-12-01 00:00:00 +0000563 intptr_t size_in_bytes = memory_size();
564
565 Node* mem = in(MemNode::Memory); // start searching here...
566
567 int cnt = 50; // Cycle limiter
568 for (;;) { // While we can dance past unrelated stores...
569 if (--cnt < 0) break; // Caught in cycle or a complicated dance?
570
Roland Westrelina9cdbd02015-05-12 10:27:50 +0200571 Node* prev = mem;
J. Duke81537792007-12-01 00:00:00 +0000572 if (mem->is_Store()) {
573 Node* st_adr = mem->in(MemNode::Address);
574 intptr_t st_offset = 0;
575 Node* st_base = AddPNode::Ideal_base_and_offset(st_adr, phase, st_offset);
576 if (st_base == NULL)
577 break; // inscrutable pointer
578 if (st_offset != offset && st_offset != Type::OffsetBot) {
579 const int MAX_STORE = BytesPerLong;
580 if (st_offset >= offset + size_in_bytes ||
581 st_offset <= offset - MAX_STORE ||
582 st_offset <= offset - mem->as_Store()->memory_size()) {
583 // Success: The offsets are provably independent.
584 // (You may ask, why not just test st_offset != offset and be done?
585 // The answer is that stores of different sizes can co-exist
586 // in the same sequence of RawMem effects. We sometimes initialize
587 // a whole 'tile' of array elements with a single jint or jlong.)
588 mem = mem->in(MemNode::Memory);
589 continue; // (a) advance through independent store memory
590 }
591 }
592 if (st_base != base &&
593 detect_ptr_independence(base, alloc,
594 st_base,
595 AllocateNode::Ideal_allocation(st_base, phase),
596 phase)) {
597 // Success: The bases are provably independent.
598 mem = mem->in(MemNode::Memory);
599 continue; // (a) advance through independent store memory
600 }
601
602 // (b) At this point, if the bases or offsets do not agree, we lose,
603 // since we have not managed to prove 'this' and 'mem' independent.
604 if (st_base == base && st_offset == offset) {
605 return mem; // let caller handle steps (c), (d)
606 }
607
608 } else if (mem->is_Proj() && mem->in(0)->is_Initialize()) {
609 InitializeNode* st_init = mem->in(0)->as_Initialize();
610 AllocateNode* st_alloc = st_init->allocation();
611 if (st_alloc == NULL)
612 break; // something degenerated
613 bool known_identical = false;
614 bool known_independent = false;
615 if (alloc == st_alloc)
616 known_identical = true;
617 else if (alloc != NULL)
618 known_independent = true;
Vladimir Kozlovdf8fc192008-04-16 19:19:48 -0700619 else if (all_controls_dominate(this, st_alloc))
J. Duke81537792007-12-01 00:00:00 +0000620 known_independent = true;
621
622 if (known_independent) {
623 // The bases are provably independent: Either they are
624 // manifestly distinct allocations, or else the control
625 // of this load dominates the store's allocation.
626 int alias_idx = phase->C->get_alias_index(adr_type());
627 if (alias_idx == Compile::AliasIdxRaw) {
628 mem = st_alloc->in(TypeFunc::Memory);
629 } else {
630 mem = st_init->memory(alias_idx);
631 }
632 continue; // (a) advance through independent store memory
633 }
634
635 // (b) at this point, if we are not looking at a store initializing
636 // the same allocation we are loading from, we lose.
637 if (known_identical) {
638 // From caller, can_see_stored_value will consult find_captured_store.
639 return mem; // let caller handle steps (c), (d)
640 }
641
Roland Westrelina9cdbd02015-05-12 10:27:50 +0200642 } else if (find_previous_arraycopy(phase, alloc, mem, false) != NULL) {
643 if (prev != mem) {
644 // Found an arraycopy but it doesn't affect that load
645 continue;
646 }
647 // Found an arraycopy that may affect that load
648 return mem;
Vladimir Kozlov4213e622008-06-26 13:34:00 -0700649 } else if (addr_t != NULL && addr_t->is_known_instance_field()) {
Vladimir Kozlovcdd27962008-03-20 15:11:44 -0700650 // Can't use optimize_simple_memory_chain() since it needs PhaseGVN.
651 if (mem->is_Proj() && mem->in(0)->is_Call()) {
Roland Westrelina9cdbd02015-05-12 10:27:50 +0200652 // ArrayCopyNodes processed here as well.
Vladimir Kozlovcdd27962008-03-20 15:11:44 -0700653 CallNode *call = mem->in(0)->as_Call();
654 if (!call->may_modify(addr_t, phase)) {
655 mem = call->in(TypeFunc::Memory);
656 continue; // (a) advance through independent call memory
657 }
658 } else if (mem->is_Proj() && mem->in(0)->is_MemBar()) {
Roland Westrelin0baf2f72015-08-15 02:54:18 +0200659 if (ArrayCopyNode::may_modify(addr_t, mem->in(0)->as_MemBar(), phase)) {
Roland Westrelina9cdbd02015-05-12 10:27:50 +0200660 break;
661 }
Vladimir Kozlovcdd27962008-03-20 15:11:44 -0700662 mem = mem->in(0)->in(TypeFunc::Memory);
663 continue; // (a) advance through independent MemBar memory
Vladimir Kozlov9f5ca022009-12-09 16:40:45 -0800664 } else if (mem->is_ClearArray()) {
665 if (ClearArrayNode::step_through(&mem, (uint)addr_t->instance_id(), phase)) {
666 // (the call updated 'mem' value)
667 continue; // (a) advance through independent allocation memory
668 } else {
669 // Can not bypass initialization of the instance
670 // we are looking for.
671 return mem;
672 }
Vladimir Kozlovcdd27962008-03-20 15:11:44 -0700673 } else if (mem->is_MergeMem()) {
674 int alias_idx = phase->C->get_alias_index(adr_type());
675 mem = mem->as_MergeMem()->memory_at(alias_idx);
676 continue; // (a) advance through independent MergeMem memory
677 }
J. Duke81537792007-12-01 00:00:00 +0000678 }
679
680 // Unless there is an explicit 'continue', we must bail out here,
681 // because 'mem' is an inscrutable memory state (e.g., a call).
682 break;
683 }
684
685 return NULL; // bail out
686}
687
688//----------------------calculate_adr_type-------------------------------------
689// Helper function. Notices when the given type of address hits top or bottom.
690// Also, asserts a cross-check of the type against the expected address type.
691const TypePtr* MemNode::calculate_adr_type(const Type* t, const TypePtr* cross_check) {
692 if (t == Type::TOP) return NULL; // does not touch memory any more?
693 #ifdef PRODUCT
694 cross_check = NULL;
695 #else
696 if (!VerifyAliases || is_error_reported() || Node::in_dump()) cross_check = NULL;
697 #endif
698 const TypePtr* tp = t->isa_ptr();
699 if (tp == NULL) {
700 assert(cross_check == NULL || cross_check == TypePtr::BOTTOM, "expected memory type must be wide");
701 return TypePtr::BOTTOM; // touches lots of memory
702 } else {
703 #ifdef ASSERT
704 // %%%% [phh] We don't check the alias index if cross_check is
705 // TypeRawPtr::BOTTOM. Needs to be investigated.
706 if (cross_check != NULL &&
707 cross_check != TypePtr::BOTTOM &&
708 cross_check != TypeRawPtr::BOTTOM) {
709 // Recheck the alias index, to see if it has changed (due to a bug).
710 Compile* C = Compile::current();
711 assert(C->get_alias_index(cross_check) == C->get_alias_index(tp),
712 "must stay in the original alias category");
713 // The type of the address must be contained in the adr_type,
714 // disregarding "null"-ness.
715 // (We make an exception for TypeRawPtr::BOTTOM, which is a bit bucket.)
716 const TypePtr* tp_notnull = tp->join(TypePtr::NOTNULL)->is_ptr();
Roland Westrelinc19a7e02014-01-24 09:31:53 +0100717 assert(cross_check->meet(tp_notnull) == cross_check->remove_speculative(),
J. Duke81537792007-12-01 00:00:00 +0000718 "real address must not escape from expected memory type");
719 }
720 #endif
721 return tp;
722 }
723}
724
J. Duke81537792007-12-01 00:00:00 +0000725//=============================================================================
Zoltan Majo49b224a2014-11-06 09:40:58 +0100726// Should LoadNode::Ideal() attempt to remove control edges?
727bool LoadNode::can_remove_control() const {
728 return true;
729}
J. Duke81537792007-12-01 00:00:00 +0000730uint LoadNode::size_of() const { return sizeof(*this); }
731uint LoadNode::cmp( const Node &n ) const
732{ return !Type::cmp( _type, ((LoadNode&)n)._type ); }
733const Type *LoadNode::bottom_type() const { return _type; }
734uint LoadNode::ideal_reg() const {
Jon Masamitsu5c58d272012-09-01 13:25:18 -0400735 return _type->ideal_reg();
J. Duke81537792007-12-01 00:00:00 +0000736}
737
738#ifndef PRODUCT
739void LoadNode::dump_spec(outputStream *st) const {
740 MemNode::dump_spec(st);
741 if( !Verbose && !WizardMode ) {
742 // standard dump does this in Verbose and WizardMode
743 st->print(" #"); _type->dump_on(st);
744 }
Vladimir Ivanov3d036102016-03-28 13:49:34 +0300745 if (!depends_only_on_test()) {
Roland Westrelina3c77df2015-05-21 13:54:07 +0200746 st->print(" (does not depend only on test)");
747 }
J. Duke81537792007-12-01 00:00:00 +0000748}
749#endif
750
Vladimir Kozlov21f481e2010-06-15 18:07:27 -0700751#ifdef ASSERT
752//----------------------------is_immutable_value-------------------------------
753// Helper function to allow a raw load without control edge for some cases
754bool LoadNode::is_immutable_value(Node* adr) {
755 return (adr->is_AddP() && adr->in(AddPNode::Base)->is_top() &&
756 adr->in(AddPNode::Address)->Opcode() == Op_ThreadLocal &&
757 (adr->in(AddPNode::Offset)->find_intptr_t_con(-1) ==
758 in_bytes(JavaThread::osthread_offset())));
759}
760#endif
J. Duke81537792007-12-01 00:00:00 +0000761
762//----------------------------LoadNode::make-----------------------------------
763// Polymorphic factory method:
Roland Westrelinc18a26c2015-11-17 12:00:16 +0100764Node *LoadNode::make(PhaseGVN& gvn, Node *ctl, Node *mem, Node *adr, const TypePtr* adr_type, const Type *rt, BasicType bt, MemOrd mo,
765 ControlDependency control_dependency, bool unaligned, bool mismatched) {
Coleen Phillimore4a831d42008-04-13 17:43:42 -0400766 Compile* C = gvn.C;
767
J. Duke81537792007-12-01 00:00:00 +0000768 // sanity check the alias category against the created node type
769 assert(!(adr_type->isa_oopptr() &&
770 adr_type->offset() == oopDesc::klass_offset_in_bytes()),
771 "use LoadKlassNode instead");
772 assert(!(adr_type->isa_aryptr() &&
773 adr_type->offset() == arrayOopDesc::length_offset_in_bytes()),
774 "use LoadRangeNode instead");
Vladimir Kozlov21f481e2010-06-15 18:07:27 -0700775 // Check control edge of raw loads
776 assert( ctl != NULL || C->get_alias_index(adr_type) != Compile::AliasIdxRaw ||
777 // oop will be recorded in oop map if load crosses safepoint
778 rt->isa_oopptr() || is_immutable_value(adr),
779 "raw memory operations should have control edge");
Roland Westrelinc18a26c2015-11-17 12:00:16 +0100780 LoadNode* load = NULL;
J. Duke81537792007-12-01 00:00:00 +0000781 switch (bt) {
Roland Westrelinc18a26c2015-11-17 12:00:16 +0100782 case T_BOOLEAN: load = new LoadUBNode(ctl, mem, adr, adr_type, rt->is_int(), mo, control_dependency); break;
783 case T_BYTE: load = new LoadBNode (ctl, mem, adr, adr_type, rt->is_int(), mo, control_dependency); break;
784 case T_INT: load = new LoadINode (ctl, mem, adr, adr_type, rt->is_int(), mo, control_dependency); break;
785 case T_CHAR: load = new LoadUSNode(ctl, mem, adr, adr_type, rt->is_int(), mo, control_dependency); break;
786 case T_SHORT: load = new LoadSNode (ctl, mem, adr, adr_type, rt->is_int(), mo, control_dependency); break;
787 case T_LONG: load = new LoadLNode (ctl, mem, adr, adr_type, rt->is_long(), mo, control_dependency); break;
788 case T_FLOAT: load = new LoadFNode (ctl, mem, adr, adr_type, rt, mo, control_dependency); break;
789 case T_DOUBLE: load = new LoadDNode (ctl, mem, adr, adr_type, rt, mo, control_dependency); break;
790 case T_ADDRESS: load = new LoadPNode (ctl, mem, adr, adr_type, rt->is_ptr(), mo, control_dependency); break;
Coleen Phillimore4a831d42008-04-13 17:43:42 -0400791 case T_OBJECT:
792#ifdef _LP64
Vladimir Kozlov757229d2008-05-21 10:45:07 -0700793 if (adr->bottom_type()->is_ptr_to_narrowoop()) {
Roland Westrelinc18a26c2015-11-17 12:00:16 +0100794 load = new LoadNNode(ctl, mem, adr, adr_type, rt->make_narrowoop(), mo, control_dependency);
Coleen Phillimore4a831d42008-04-13 17:43:42 -0400795 } else
796#endif
Vladimir Kozlov757229d2008-05-21 10:45:07 -0700797 {
Roland Westrelin61eb5a02012-10-09 10:11:38 +0200798 assert(!adr->bottom_type()->is_ptr_to_narrowoop() && !adr->bottom_type()->is_ptr_to_narrowklass(), "should have got back a narrow oop");
Roland Westrelinc18a26c2015-11-17 12:00:16 +0100799 load = new LoadPNode(ctl, mem, adr, adr_type, rt->is_oopptr(), mo, control_dependency);
Vladimir Kozlov757229d2008-05-21 10:45:07 -0700800 }
Roland Westrelinc18a26c2015-11-17 12:00:16 +0100801 break;
J. Duke81537792007-12-01 00:00:00 +0000802 }
Roland Westrelinc18a26c2015-11-17 12:00:16 +0100803 assert(load != NULL, "LoadNode should have been created");
804 if (unaligned) {
805 load->set_unaligned_access();
806 }
807 if (mismatched) {
808 load->set_mismatched_access();
809 }
810 if (load->Opcode() == Op_LoadN) {
811 Node* ld = gvn.transform(load);
812 return new DecodeNNode(ld, ld->bottom_type()->make_ptr());
813 }
814
815 return load;
J. Duke81537792007-12-01 00:00:00 +0000816}
817
Roland Westrelinc18a26c2015-11-17 12:00:16 +0100818LoadLNode* LoadLNode::make_atomic(Node* ctl, Node* mem, Node* adr, const TypePtr* adr_type, const Type* rt, MemOrd mo,
819 ControlDependency control_dependency, bool unaligned, bool mismatched) {
J. Duke81537792007-12-01 00:00:00 +0000820 bool require_atomic = true;
Roland Westrelinc18a26c2015-11-17 12:00:16 +0100821 LoadLNode* load = new LoadLNode(ctl, mem, adr, adr_type, rt->is_long(), mo, control_dependency, require_atomic);
822 if (unaligned) {
823 load->set_unaligned_access();
824 }
825 if (mismatched) {
826 load->set_mismatched_access();
827 }
828 return load;
J. Duke81537792007-12-01 00:00:00 +0000829}
830
Roland Westrelinc18a26c2015-11-17 12:00:16 +0100831LoadDNode* LoadDNode::make_atomic(Node* ctl, Node* mem, Node* adr, const TypePtr* adr_type, const Type* rt, MemOrd mo,
832 ControlDependency control_dependency, bool unaligned, bool mismatched) {
Tobias Hartmann85296fe2014-05-06 09:17:57 +0200833 bool require_atomic = true;
Roland Westrelinc18a26c2015-11-17 12:00:16 +0100834 LoadDNode* load = new LoadDNode(ctl, mem, adr, adr_type, rt, mo, control_dependency, require_atomic);
835 if (unaligned) {
836 load->set_unaligned_access();
837 }
838 if (mismatched) {
839 load->set_mismatched_access();
840 }
841 return load;
Tobias Hartmann85296fe2014-05-06 09:17:57 +0200842}
J. Duke81537792007-12-01 00:00:00 +0000843
844
845
846//------------------------------hash-------------------------------------------
847uint LoadNode::hash() const {
848 // unroll addition of interesting fields
849 return (uintptr_t)in(Control) + (uintptr_t)in(Memory) + (uintptr_t)in(Address);
850}
851
Vladimir Ivanovf0e77ac2013-09-10 14:51:48 -0700852static bool skip_through_membars(Compile::AliasType* atp, const TypeInstPtr* tp, bool eliminate_boxing) {
853 if ((atp != NULL) && (atp->index() >= Compile::AliasIdxRaw)) {
854 bool non_volatile = (atp->field() != NULL) && !atp->field()->is_volatile();
855 bool is_stable_ary = FoldStableValues &&
856 (tp != NULL) && (tp->isa_aryptr() != NULL) &&
857 tp->isa_aryptr()->is_stable();
858
859 return (eliminate_boxing && non_volatile) || is_stable_ary;
860 }
861
862 return false;
863}
864
Roland Westrelina9cdbd02015-05-12 10:27:50 +0200865// Is the value loaded previously stored by an arraycopy? If so return
866// a load node that reads from the source array so we may be able to
867// optimize out the ArrayCopy node later.
Roland Westrelin0baf2f72015-08-15 02:54:18 +0200868Node* LoadNode::can_see_arraycopy_value(Node* st, PhaseTransform* phase) const {
Roland Westrelina9cdbd02015-05-12 10:27:50 +0200869 Node* ld_adr = in(MemNode::Address);
870 intptr_t ld_off = 0;
871 AllocateNode* ld_alloc = AllocateNode::Ideal_allocation(ld_adr, phase, ld_off);
872 Node* ac = find_previous_arraycopy(phase, ld_alloc, st, true);
873 if (ac != NULL) {
874 assert(ac->is_ArrayCopy(), "what kind of node can this be?");
Roland Westrelina9cdbd02015-05-12 10:27:50 +0200875
Roland Westrelin0baf2f72015-08-15 02:54:18 +0200876 Node* ld = clone();
Roland Westrelina9cdbd02015-05-12 10:27:50 +0200877 if (ac->as_ArrayCopy()->is_clonebasic()) {
878 assert(ld_alloc != NULL, "need an alloc");
Roland Westrelina9cdbd02015-05-12 10:27:50 +0200879 Node* addp = in(MemNode::Address)->clone();
880 assert(addp->is_AddP(), "address must be addp");
881 assert(addp->in(AddPNode::Base) == ac->in(ArrayCopyNode::Dest)->in(AddPNode::Base), "strange pattern");
882 assert(addp->in(AddPNode::Address) == ac->in(ArrayCopyNode::Dest)->in(AddPNode::Address), "strange pattern");
883 addp->set_req(AddPNode::Base, ac->in(ArrayCopyNode::Src)->in(AddPNode::Base));
884 addp->set_req(AddPNode::Address, ac->in(ArrayCopyNode::Src)->in(AddPNode::Address));
885 ld->set_req(MemNode::Address, phase->transform(addp));
886 if (in(0) != NULL) {
887 assert(ld_alloc->in(0) != NULL, "alloc must have control");
888 ld->set_req(0, ld_alloc->in(0));
889 }
Roland Westrelina9cdbd02015-05-12 10:27:50 +0200890 } else {
Roland Westrelina9cdbd02015-05-12 10:27:50 +0200891 Node* addp = in(MemNode::Address)->clone();
892 assert(addp->in(AddPNode::Base) == addp->in(AddPNode::Address), "should be");
893 addp->set_req(AddPNode::Base, ac->in(ArrayCopyNode::Src));
894 addp->set_req(AddPNode::Address, ac->in(ArrayCopyNode::Src));
895
896 const TypeAryPtr* ary_t = phase->type(in(MemNode::Address))->isa_aryptr();
897 BasicType ary_elem = ary_t->klass()->as_array_klass()->element_type()->basic_type();
898 uint header = arrayOopDesc::base_offset_in_bytes(ary_elem);
899 uint shift = exact_log2(type2aelembytes(ary_elem));
900
901 Node* diff = phase->transform(new SubINode(ac->in(ArrayCopyNode::SrcPos), ac->in(ArrayCopyNode::DestPos)));
902#ifdef _LP64
903 diff = phase->transform(new ConvI2LNode(diff));
904#endif
905 diff = phase->transform(new LShiftXNode(diff, phase->intcon(shift)));
906
907 Node* offset = phase->transform(new AddXNode(addp->in(AddPNode::Offset), diff));
908 addp->set_req(AddPNode::Offset, offset);
909 ld->set_req(MemNode::Address, phase->transform(addp));
910
911 if (in(0) != NULL) {
912 assert(ac->in(0) != NULL, "alloc must have control");
913 ld->set_req(0, ac->in(0));
914 }
Roland Westrelina9cdbd02015-05-12 10:27:50 +0200915 }
Roland Westrelin0baf2f72015-08-15 02:54:18 +0200916 // load depends on the tests that validate the arraycopy
Vladimir Ivanov3d036102016-03-28 13:49:34 +0300917 ld->as_Load()->_control_dependency = Pinned;
Roland Westrelin0baf2f72015-08-15 02:54:18 +0200918 return ld;
Roland Westrelina9cdbd02015-05-12 10:27:50 +0200919 }
920 return NULL;
921}
922
923
J. Duke81537792007-12-01 00:00:00 +0000924//---------------------------can_see_stored_value------------------------------
925// This routine exists to make sure this set of tests is done the same
926// everywhere. We need to make a coordinated change: first LoadNode::Ideal
927// will change the graph shape in a way which makes memory alive twice at the
928// same time (uses the Oracle model of aliasing), then some
929// LoadXNode::Identity will fold things back to the equivalence-class model
930// of aliasing.
931Node* MemNode::can_see_stored_value(Node* st, PhaseTransform* phase) const {
932 Node* ld_adr = in(MemNode::Address);
Vladimir Kozlovb4977e82013-05-08 15:08:01 -0700933 intptr_t ld_off = 0;
934 AllocateNode* ld_alloc = AllocateNode::Ideal_allocation(ld_adr, phase, ld_off);
Tom Rodriguez10c473e2007-12-05 09:01:00 -0800935 const TypeInstPtr* tp = phase->type(ld_adr)->isa_instptr();
Vladimir Kozlovb4977e82013-05-08 15:08:01 -0700936 Compile::AliasType* atp = (tp != NULL) ? phase->C->alias_type(tp) : NULL;
937 // This is more general than load from boxing objects.
Vladimir Ivanovf0e77ac2013-09-10 14:51:48 -0700938 if (skip_through_membars(atp, tp, phase->C->eliminate_boxing())) {
Tom Rodriguez10c473e2007-12-05 09:01:00 -0800939 uint alias_idx = atp->index();
Vladimir Ivanovf0e77ac2013-09-10 14:51:48 -0700940 bool final = !atp->is_rewritable();
Tom Rodriguez10c473e2007-12-05 09:01:00 -0800941 Node* result = NULL;
942 Node* current = st;
943 // Skip through chains of MemBarNodes checking the MergeMems for
944 // new states for the slice of this load. Stop once any other
945 // kind of node is encountered. Loads from final memory can skip
946 // through any kind of MemBar but normal loads shouldn't skip
947 // through MemBarAcquire since the could allow them to move out of
948 // a synchronized region.
949 while (current->is_Proj()) {
950 int opc = current->in(0)->Opcode();
Goetz Lindenmaierfe897662013-11-26 18:38:19 -0800951 if ((final && (opc == Op_MemBarAcquire ||
952 opc == Op_MemBarAcquireLock ||
953 opc == Op_LoadFence)) ||
954 opc == Op_MemBarRelease ||
955 opc == Op_StoreFence ||
956 opc == Op_MemBarReleaseLock ||
Roland Westrelina9cdbd02015-05-12 10:27:50 +0200957 opc == Op_MemBarStoreStore ||
Goetz Lindenmaierfe897662013-11-26 18:38:19 -0800958 opc == Op_MemBarCPUOrder) {
Tom Rodriguez10c473e2007-12-05 09:01:00 -0800959 Node* mem = current->in(0)->in(TypeFunc::Memory);
960 if (mem->is_MergeMem()) {
961 MergeMemNode* merge = mem->as_MergeMem();
962 Node* new_st = merge->memory_at(alias_idx);
963 if (new_st == merge->base_memory()) {
964 // Keep searching
Vladimir Kozlovb4977e82013-05-08 15:08:01 -0700965 current = new_st;
Tom Rodriguez10c473e2007-12-05 09:01:00 -0800966 continue;
967 }
968 // Save the new memory state for the slice and fall through
969 // to exit.
970 result = new_st;
971 }
972 }
973 break;
974 }
975 if (result != NULL) {
976 st = result;
977 }
978 }
979
J. Duke81537792007-12-01 00:00:00 +0000980 // Loop around twice in the case Load -> Initialize -> Store.
981 // (See PhaseIterGVN::add_users_to_worklist, which knows about this case.)
982 for (int trip = 0; trip <= 1; trip++) {
983
984 if (st->is_Store()) {
985 Node* st_adr = st->in(MemNode::Address);
986 if (!phase->eqv(st_adr, ld_adr)) {
987 // Try harder before giving up... Match raw and non-raw pointers.
988 intptr_t st_off = 0;
989 AllocateNode* alloc = AllocateNode::Ideal_allocation(st_adr, phase, st_off);
990 if (alloc == NULL) return NULL;
Vladimir Kozlovb4977e82013-05-08 15:08:01 -0700991 if (alloc != ld_alloc) return NULL;
J. Duke81537792007-12-01 00:00:00 +0000992 if (ld_off != st_off) return NULL;
993 // At this point we have proven something like this setup:
994 // A = Allocate(...)
995 // L = LoadQ(, AddP(CastPP(, A.Parm),, #Off))
996 // S = StoreQ(, AddP(, A.Parm , #Off), V)
997 // (Actually, we haven't yet proven the Q's are the same.)
998 // In other words, we are loading from a casted version of
999 // the same pointer-and-offset that we stored to.
1000 // Thus, we are able to replace L by V.
1001 }
1002 // Now prove that we have a LoadQ matched to a StoreQ, for some Q.
1003 if (store_Opcode() != st->Opcode())
1004 return NULL;
1005 return st->in(MemNode::ValueIn);
1006 }
1007
J. Duke81537792007-12-01 00:00:00 +00001008 // A load from a freshly-created object always returns zero.
1009 // (This can happen after LoadNode::Ideal resets the load's memory input
1010 // to find_captured_store, which returned InitializeNode::zero_memory.)
1011 if (st->is_Proj() && st->in(0)->is_Allocate() &&
Vladimir Kozlovb4977e82013-05-08 15:08:01 -07001012 (st->in(0) == ld_alloc) &&
1013 (ld_off >= st->in(0)->as_Allocate()->minimum_header_size())) {
J. Duke81537792007-12-01 00:00:00 +00001014 // return a zero value for the load's basic type
1015 // (This is one of the few places where a generic PhaseTransform
1016 // can create new nodes. Think of it as lazily manifesting
1017 // virtually pre-existing constants.)
1018 return phase->zerocon(memory_type());
1019 }
1020
1021 // A load from an initialization barrier can match a captured store.
1022 if (st->is_Proj() && st->in(0)->is_Initialize()) {
1023 InitializeNode* init = st->in(0)->as_Initialize();
1024 AllocateNode* alloc = init->allocation();
Vladimir Kozlovb4977e82013-05-08 15:08:01 -07001025 if ((alloc != NULL) && (alloc == ld_alloc)) {
J. Duke81537792007-12-01 00:00:00 +00001026 // examine a captured store value
Vladimir Kozlovb4977e82013-05-08 15:08:01 -07001027 st = init->find_captured_store(ld_off, memory_size(), phase);
Roland Westrelina9cdbd02015-05-12 10:27:50 +02001028 if (st != NULL) {
J. Duke81537792007-12-01 00:00:00 +00001029 continue; // take one more trip around
Roland Westrelina9cdbd02015-05-12 10:27:50 +02001030 }
J. Duke81537792007-12-01 00:00:00 +00001031 }
1032 }
1033
Vladimir Kozlovb4977e82013-05-08 15:08:01 -07001034 // Load boxed value from result of valueOf() call is input parameter.
1035 if (this->is_Load() && ld_adr->is_AddP() &&
1036 (tp != NULL) && tp->is_ptr_to_boxed_value()) {
1037 intptr_t ignore = 0;
1038 Node* base = AddPNode::Ideal_base_and_offset(ld_adr, phase, ignore);
1039 if (base != NULL && base->is_Proj() &&
1040 base->as_Proj()->_con == TypeFunc::Parms &&
1041 base->in(0)->is_CallStaticJava() &&
1042 base->in(0)->as_CallStaticJava()->is_boxing_method()) {
1043 return base->in(0)->in(TypeFunc::Parms);
1044 }
1045 }
1046
J. Duke81537792007-12-01 00:00:00 +00001047 break;
1048 }
1049
1050 return NULL;
1051}
1052
Vladimir Kozlov30dc0ed2008-03-13 16:31:32 -07001053//----------------------is_instance_field_load_with_local_phi------------------
1054bool LoadNode::is_instance_field_load_with_local_phi(Node* ctrl) {
Vladimir Kozlovb4977e82013-05-08 15:08:01 -07001055 if( in(Memory)->is_Phi() && in(Memory)->in(0) == ctrl &&
1056 in(Address)->is_AddP() ) {
1057 const TypeOopPtr* t_oop = in(Address)->bottom_type()->isa_oopptr();
1058 // Only instances and boxed values.
1059 if( t_oop != NULL &&
1060 (t_oop->is_ptr_to_boxed_value() ||
1061 t_oop->is_known_instance_field()) &&
Vladimir Kozlov30dc0ed2008-03-13 16:31:32 -07001062 t_oop->offset() != Type::OffsetBot &&
1063 t_oop->offset() != Type::OffsetTop) {
1064 return true;
1065 }
1066 }
1067 return false;
1068}
1069
J. Duke81537792007-12-01 00:00:00 +00001070//------------------------------Identity---------------------------------------
1071// Loads are identity if previous store is to same address
Tobias Hartmann69b52aa2016-01-12 12:55:09 +01001072Node* LoadNode::Identity(PhaseGVN* phase) {
J. Duke81537792007-12-01 00:00:00 +00001073 // If the previous store-maker is the right kind of Store, and the store is
1074 // to the same address, then we are equal to the value stored.
Vladimir Kozlovb4977e82013-05-08 15:08:01 -07001075 Node* mem = in(Memory);
J. Duke81537792007-12-01 00:00:00 +00001076 Node* value = can_see_stored_value(mem, phase);
1077 if( value ) {
1078 // byte, short & char stores truncate naturally.
1079 // A load has to load the truncated value which requires
1080 // some sort of masking operation and that requires an
1081 // Ideal call instead of an Identity call.
1082 if (memory_size() < BytesPerInt) {
1083 // If the input to the store does not fit with the load's result type,
1084 // it must be truncated via an Ideal call.
1085 if (!phase->type(value)->higher_equal(phase->type(this)))
1086 return this;
1087 }
1088 // (This works even when value is a Con, but LoadNode::Value
1089 // usually runs first, producing the singleton type of the Con.)
1090 return value;
1091 }
Vladimir Kozlov30dc0ed2008-03-13 16:31:32 -07001092
1093 // Search for an existing data phi which was generated before for the same
Christian Thalinger05d1de72009-02-27 13:27:09 -08001094 // instance's field to avoid infinite generation of phis in a loop.
Vladimir Kozlov30dc0ed2008-03-13 16:31:32 -07001095 Node *region = mem->in(0);
1096 if (is_instance_field_load_with_local_phi(region)) {
Vladimir Kozlovb4977e82013-05-08 15:08:01 -07001097 const TypeOopPtr *addr_t = in(Address)->bottom_type()->isa_oopptr();
Vladimir Kozlov30dc0ed2008-03-13 16:31:32 -07001098 int this_index = phase->C->get_alias_index(addr_t);
1099 int this_offset = addr_t->offset();
Vladimir Kozlovb4977e82013-05-08 15:08:01 -07001100 int this_iid = addr_t->instance_id();
1101 if (!addr_t->is_known_instance() &&
1102 addr_t->is_ptr_to_boxed_value()) {
1103 // Use _idx of address base (could be Phi node) for boxed values.
1104 intptr_t ignore = 0;
1105 Node* base = AddPNode::Ideal_base_and_offset(in(Address), phase, ignore);
1106 this_iid = base->_idx;
1107 }
Vladimir Kozlov30dc0ed2008-03-13 16:31:32 -07001108 const Type* this_type = bottom_type();
1109 for (DUIterator_Fast imax, i = region->fast_outs(imax); i < imax; i++) {
1110 Node* phi = region->fast_out(i);
1111 if (phi->is_Phi() && phi != mem &&
Vladimir Kozlovb4977e82013-05-08 15:08:01 -07001112 phi->as_Phi()->is_same_inst_field(this_type, this_iid, this_index, this_offset)) {
Vladimir Kozlov30dc0ed2008-03-13 16:31:32 -07001113 return phi;
1114 }
1115 }
1116 }
1117
J. Duke81537792007-12-01 00:00:00 +00001118 return this;
1119}
1120
Vladimir Ivanov3d036102016-03-28 13:49:34 +03001121// Construct an equivalent unsigned load.
1122Node* LoadNode::convert_to_unsigned_load(PhaseGVN& gvn) {
1123 BasicType bt = T_ILLEGAL;
1124 const Type* rt = NULL;
1125 switch (Opcode()) {
1126 case Op_LoadUB: return this;
1127 case Op_LoadUS: return this;
1128 case Op_LoadB: bt = T_BOOLEAN; rt = TypeInt::UBYTE; break;
1129 case Op_LoadS: bt = T_CHAR; rt = TypeInt::CHAR; break;
1130 default:
1131 assert(false, "no unsigned variant: %s", Name());
1132 return NULL;
1133 }
1134 return LoadNode::make(gvn, in(MemNode::Control), in(MemNode::Memory), in(MemNode::Address),
Vladimir Ivanovd39c8472016-03-29 21:33:26 +03001135 raw_adr_type(), rt, bt, _mo, _control_dependency,
Vladimir Ivanov3d036102016-03-28 13:49:34 +03001136 is_unaligned_access(), is_mismatched_access());
1137}
1138
1139// Construct an equivalent signed load.
1140Node* LoadNode::convert_to_signed_load(PhaseGVN& gvn) {
1141 BasicType bt = T_ILLEGAL;
1142 const Type* rt = NULL;
1143 switch (Opcode()) {
1144 case Op_LoadUB: bt = T_BYTE; rt = TypeInt::BYTE; break;
1145 case Op_LoadUS: bt = T_SHORT; rt = TypeInt::SHORT; break;
1146 case Op_LoadB: // fall through
1147 case Op_LoadS: // fall through
1148 case Op_LoadI: // fall through
1149 case Op_LoadL: return this;
1150 default:
1151 assert(false, "no signed variant: %s", Name());
1152 return NULL;
1153 }
1154 return LoadNode::make(gvn, in(MemNode::Control), in(MemNode::Memory), in(MemNode::Address),
Vladimir Ivanovd39c8472016-03-29 21:33:26 +03001155 raw_adr_type(), rt, bt, _mo, _control_dependency,
Vladimir Ivanov3d036102016-03-28 13:49:34 +03001156 is_unaligned_access(), is_mismatched_access());
1157}
1158
Tom Rodriguez10c473e2007-12-05 09:01:00 -08001159// We're loading from an object which has autobox behaviour.
1160// If this object is result of a valueOf call we'll have a phi
1161// merging a newly allocated object and a load from the cache.
1162// We want to replace this load with the original incoming
1163// argument to the valueOf call.
1164Node* LoadNode::eliminate_autobox(PhaseGVN* phase) {
Vladimir Kozlovb4977e82013-05-08 15:08:01 -07001165 assert(phase->C->eliminate_boxing(), "sanity");
1166 intptr_t ignore = 0;
1167 Node* base = AddPNode::Ideal_base_and_offset(in(Address), phase, ignore);
1168 if ((base == NULL) || base->is_Phi()) {
1169 // Push the loads from the phi that comes from valueOf up
1170 // through it to allow elimination of the loads and the recovery
1171 // of the original value. It is done in split_through_phi().
1172 return NULL;
Vladimir Kozlov73e8e582009-02-18 13:53:42 -08001173 } else if (base->is_Load() ||
1174 base->is_DecodeN() && base->in(1)->is_Load()) {
Vladimir Kozlovb4977e82013-05-08 15:08:01 -07001175 // Eliminate the load of boxed value for integer types from the cache
Tom Rodriguez10c473e2007-12-05 09:01:00 -08001176 // array by deriving the value from the index into the array.
1177 // Capture the offset of the load and then reverse the computation.
Vladimir Kozlovb4977e82013-05-08 15:08:01 -07001178
1179 // Get LoadN node which loads a boxing object from 'cache' array.
1180 if (base->is_DecodeN()) {
1181 base = base->in(1);
Vladimir Kozlov73e8e582009-02-18 13:53:42 -08001182 }
Vladimir Kozlovb4977e82013-05-08 15:08:01 -07001183 if (!base->in(Address)->is_AddP()) {
1184 return NULL; // Complex address
1185 }
1186 AddPNode* address = base->in(Address)->as_AddP();
1187 Node* cache_base = address->in(AddPNode::Base);
1188 if ((cache_base != NULL) && cache_base->is_DecodeN()) {
1189 // Get ConP node which is static 'cache' field.
1190 cache_base = cache_base->in(1);
1191 }
1192 if ((cache_base != NULL) && cache_base->is_Con()) {
1193 const TypeAryPtr* base_type = cache_base->bottom_type()->isa_aryptr();
1194 if ((base_type != NULL) && base_type->is_autobox_cache()) {
Tom Rodriguez10c473e2007-12-05 09:01:00 -08001195 Node* elements[4];
Vladimir Kozlovb4977e82013-05-08 15:08:01 -07001196 int shift = exact_log2(type2aelembytes(T_OBJECT));
1197 int count = address->unpack_offsets(elements, ARRAY_SIZE(elements));
1198 if ((count > 0) && elements[0]->is_Con() &&
1199 ((count == 1) ||
1200 (count == 2) && elements[1]->Opcode() == Op_LShiftX &&
1201 elements[1]->in(2) == phase->intcon(shift))) {
1202 ciObjArray* array = base_type->const_oop()->as_obj_array();
1203 // Fetch the box object cache[0] at the base of the array and get its value
1204 ciInstance* box = array->obj_at(0)->as_instance();
1205 ciInstanceKlass* ik = box->klass()->as_instance_klass();
1206 assert(ik->is_box_klass(), "sanity");
1207 assert(ik->nof_nonstatic_fields() == 1, "change following code");
1208 if (ik->nof_nonstatic_fields() == 1) {
1209 // This should be true nonstatic_field_at requires calling
1210 // nof_nonstatic_fields so check it anyway
1211 ciConstant c = box->field_value(ik->nonstatic_field_at(0));
1212 BasicType bt = c.basic_type();
1213 // Only integer types have boxing cache.
1214 assert(bt == T_BOOLEAN || bt == T_CHAR ||
1215 bt == T_BYTE || bt == T_SHORT ||
David Lindholm1e71f672015-09-29 11:02:08 +02001216 bt == T_INT || bt == T_LONG, "wrong type = %s", type2name(bt));
Vladimir Kozlovb4977e82013-05-08 15:08:01 -07001217 jlong cache_low = (bt == T_LONG) ? c.as_long() : c.as_int();
1218 if (cache_low != (int)cache_low) {
1219 return NULL; // should not happen since cache is array indexed by value
1220 }
1221 jlong offset = arrayOopDesc::base_offset_in_bytes(T_OBJECT) - (cache_low << shift);
1222 if (offset != (int)offset) {
1223 return NULL; // should not happen since cache is array indexed by value
1224 }
1225 // Add up all the offsets making of the address of the load
1226 Node* result = elements[0];
1227 for (int i = 1; i < count; i++) {
Tobias Hartmann2a0815a2014-06-02 08:07:29 +02001228 result = phase->transform(new AddXNode(result, elements[i]));
Vladimir Kozlovb4977e82013-05-08 15:08:01 -07001229 }
1230 // Remove the constant offset from the address and then
Tobias Hartmann2a0815a2014-06-02 08:07:29 +02001231 result = phase->transform(new AddXNode(result, phase->MakeConX(-(int)offset)));
Vladimir Kozlovb4977e82013-05-08 15:08:01 -07001232 // remove the scaling of the offset to recover the original index.
1233 if (result->Opcode() == Op_LShiftX && result->in(2) == phase->intcon(shift)) {
1234 // Peel the shift off directly but wrap it in a dummy node
1235 // since Ideal can't return existing nodes
Tobias Hartmann2a0815a2014-06-02 08:07:29 +02001236 result = new RShiftXNode(result->in(1), phase->intcon(0));
Vladimir Kozlovb4977e82013-05-08 15:08:01 -07001237 } else if (result->is_Add() && result->in(2)->is_Con() &&
1238 result->in(1)->Opcode() == Op_LShiftX &&
1239 result->in(1)->in(2) == phase->intcon(shift)) {
1240 // We can't do general optimization: ((X<<Z) + Y) >> Z ==> X + (Y>>Z)
1241 // but for boxing cache access we know that X<<Z will not overflow
1242 // (there is range check) so we do this optimizatrion by hand here.
Tobias Hartmann2a0815a2014-06-02 08:07:29 +02001243 Node* add_con = new RShiftXNode(result->in(2), phase->intcon(shift));
1244 result = new AddXNode(result->in(1)->in(1), phase->transform(add_con));
Vladimir Kozlovb4977e82013-05-08 15:08:01 -07001245 } else {
Tobias Hartmann2a0815a2014-06-02 08:07:29 +02001246 result = new RShiftXNode(result, phase->intcon(shift));
Vladimir Kozlovb4977e82013-05-08 15:08:01 -07001247 }
Tom Rodriguez10c473e2007-12-05 09:01:00 -08001248#ifdef _LP64
Vladimir Kozlovb4977e82013-05-08 15:08:01 -07001249 if (bt != T_LONG) {
Tobias Hartmann2a0815a2014-06-02 08:07:29 +02001250 result = new ConvL2INode(phase->transform(result));
Vladimir Kozlovb4977e82013-05-08 15:08:01 -07001251 }
1252#else
1253 if (bt == T_LONG) {
Tobias Hartmann2a0815a2014-06-02 08:07:29 +02001254 result = new ConvI2LNode(phase->transform(result));
Vladimir Kozlovb4977e82013-05-08 15:08:01 -07001255 }
Tom Rodriguez10c473e2007-12-05 09:01:00 -08001256#endif
Vladimir Ivanov83181ef2014-10-24 09:13:12 -07001257 // Boxing/unboxing can be done from signed & unsigned loads (e.g. LoadUB -> ... -> LoadB pair).
1258 // Need to preserve unboxing load type if it is unsigned.
1259 switch(this->Opcode()) {
1260 case Op_LoadUB:
1261 result = new AndINode(phase->transform(result), phase->intcon(0xFF));
1262 break;
1263 case Op_LoadUS:
1264 result = new AndINode(phase->transform(result), phase->intcon(0xFFFF));
1265 break;
1266 }
Vladimir Kozlovb4977e82013-05-08 15:08:01 -07001267 return result;
1268 }
Tom Rodriguez10c473e2007-12-05 09:01:00 -08001269 }
1270 }
1271 }
1272 }
1273 return NULL;
1274}
1275
Vladimir Kozlovb4977e82013-05-08 15:08:01 -07001276static bool stable_phi(PhiNode* phi, PhaseGVN *phase) {
1277 Node* region = phi->in(0);
Vladimir Kozlov757229d2008-05-21 10:45:07 -07001278 if (region == NULL) {
Vladimir Kozlovb4977e82013-05-08 15:08:01 -07001279 return false; // Wait stable graph
Vladimir Kozlov757229d2008-05-21 10:45:07 -07001280 }
Vladimir Kozlovb4977e82013-05-08 15:08:01 -07001281 uint cnt = phi->req();
Vladimir Kozlovabc5f942011-04-20 18:29:35 -07001282 for (uint i = 1; i < cnt; i++) {
1283 Node* rc = region->in(i);
1284 if (rc == NULL || phase->type(rc) == Type::TOP)
Vladimir Kozlovb4977e82013-05-08 15:08:01 -07001285 return false; // Wait stable graph
1286 Node* in = phi->in(i);
1287 if (in == NULL || phase->type(in) == Type::TOP)
1288 return false; // Wait stable graph
1289 }
1290 return true;
1291}
1292//------------------------------split_through_phi------------------------------
1293// Split instance or boxed field load through Phi.
1294Node *LoadNode::split_through_phi(PhaseGVN *phase) {
1295 Node* mem = in(Memory);
1296 Node* address = in(Address);
1297 const TypeOopPtr *t_oop = phase->type(address)->isa_oopptr();
1298
1299 assert((t_oop != NULL) &&
1300 (t_oop->is_known_instance_field() ||
1301 t_oop->is_ptr_to_boxed_value()), "invalide conditions");
1302
1303 Compile* C = phase->C;
1304 intptr_t ignore = 0;
1305 Node* base = AddPNode::Ideal_base_and_offset(address, phase, ignore);
1306 bool base_is_phi = (base != NULL) && base->is_Phi();
1307 bool load_boxed_values = t_oop->is_ptr_to_boxed_value() && C->aggressive_unboxing() &&
1308 (base != NULL) && (base == address->in(AddPNode::Base)) &&
1309 phase->type(base)->higher_equal(TypePtr::NOTNULL);
1310
1311 if (!((mem->is_Phi() || base_is_phi) &&
1312 (load_boxed_values || t_oop->is_known_instance_field()))) {
1313 return NULL; // memory is not Phi
1314 }
1315
1316 if (mem->is_Phi()) {
1317 if (!stable_phi(mem->as_Phi(), phase)) {
Vladimir Kozlov757229d2008-05-21 10:45:07 -07001318 return NULL; // Wait stable graph
1319 }
Vladimir Kozlovb4977e82013-05-08 15:08:01 -07001320 uint cnt = mem->req();
1321 // Check for loop invariant memory.
1322 if (cnt == 3) {
1323 for (uint i = 1; i < cnt; i++) {
1324 Node* in = mem->in(i);
1325 Node* m = optimize_memory_chain(in, t_oop, this, phase);
1326 if (m == mem) {
1327 set_req(Memory, mem->in(cnt - i));
1328 return this; // made change
1329 }
Vladimir Kozlov757229d2008-05-21 10:45:07 -07001330 }
1331 }
1332 }
Vladimir Kozlovb4977e82013-05-08 15:08:01 -07001333 if (base_is_phi) {
1334 if (!stable_phi(base->as_Phi(), phase)) {
1335 return NULL; // Wait stable graph
1336 }
1337 uint cnt = base->req();
1338 // Check for loop invariant memory.
1339 if (cnt == 3) {
1340 for (uint i = 1; i < cnt; i++) {
1341 if (base->in(i) == base) {
1342 return NULL; // Wait stable graph
1343 }
1344 }
1345 }
1346 }
1347
1348 bool load_boxed_phi = load_boxed_values && base_is_phi && (base->in(0) == mem->in(0));
1349
Vladimir Kozlov757229d2008-05-21 10:45:07 -07001350 // Split through Phi (see original code in loopopts.cpp).
Vladimir Kozlovb4977e82013-05-08 15:08:01 -07001351 assert(C->have_alias_type(t_oop), "instance should have alias type");
Vladimir Kozlov757229d2008-05-21 10:45:07 -07001352
1353 // Do nothing here if Identity will find a value
1354 // (to avoid infinite chain of value phis generation).
Vladimir Kozlovabc5f942011-04-20 18:29:35 -07001355 if (!phase->eqv(this, this->Identity(phase)))
Vladimir Kozlov757229d2008-05-21 10:45:07 -07001356 return NULL;
1357
Vladimir Kozlovb4977e82013-05-08 15:08:01 -07001358 // Select Region to split through.
1359 Node* region;
1360 if (!base_is_phi) {
1361 assert(mem->is_Phi(), "sanity");
1362 region = mem->in(0);
1363 // Skip if the region dominates some control edge of the address.
1364 if (!MemNode::all_controls_dominate(address, region))
1365 return NULL;
1366 } else if (!mem->is_Phi()) {
1367 assert(base_is_phi, "sanity");
1368 region = base->in(0);
1369 // Skip if the region dominates some control edge of the memory.
1370 if (!MemNode::all_controls_dominate(mem, region))
1371 return NULL;
1372 } else if (base->in(0) != mem->in(0)) {
1373 assert(base_is_phi && mem->is_Phi(), "sanity");
1374 if (MemNode::all_controls_dominate(mem, base->in(0))) {
1375 region = base->in(0);
1376 } else if (MemNode::all_controls_dominate(address, mem->in(0))) {
1377 region = mem->in(0);
1378 } else {
1379 return NULL; // complex graph
1380 }
1381 } else {
1382 assert(base->in(0) == mem->in(0), "sanity");
1383 region = mem->in(0);
1384 }
Vladimir Kozlov757229d2008-05-21 10:45:07 -07001385
1386 const Type* this_type = this->bottom_type();
Vladimir Kozlovb4977e82013-05-08 15:08:01 -07001387 int this_index = C->get_alias_index(t_oop);
1388 int this_offset = t_oop->offset();
1389 int this_iid = t_oop->instance_id();
1390 if (!t_oop->is_known_instance() && load_boxed_values) {
1391 // Use _idx of address base for boxed values.
1392 this_iid = base->_idx;
1393 }
1394 PhaseIterGVN* igvn = phase->is_IterGVN();
Tobias Hartmann2a0815a2014-06-02 08:07:29 +02001395 Node* phi = new PhiNode(region, this_type, NULL, this_iid, this_index, this_offset);
Vladimir Kozlovabc5f942011-04-20 18:29:35 -07001396 for (uint i = 1; i < region->req(); i++) {
Vladimir Kozlovb4977e82013-05-08 15:08:01 -07001397 Node* x;
Vladimir Kozlov757229d2008-05-21 10:45:07 -07001398 Node* the_clone = NULL;
Vladimir Kozlovb4977e82013-05-08 15:08:01 -07001399 if (region->in(i) == C->top()) {
1400 x = C->top(); // Dead path? Use a dead data op
Vladimir Kozlov757229d2008-05-21 10:45:07 -07001401 } else {
1402 x = this->clone(); // Else clone up the data op
1403 the_clone = x; // Remember for possible deletion.
1404 // Alter data node to use pre-phi inputs
Vladimir Kozlovabc5f942011-04-20 18:29:35 -07001405 if (this->in(0) == region) {
1406 x->set_req(0, region->in(i));
Vladimir Kozlov757229d2008-05-21 10:45:07 -07001407 } else {
Vladimir Kozlovabc5f942011-04-20 18:29:35 -07001408 x->set_req(0, NULL);
Vladimir Kozlov757229d2008-05-21 10:45:07 -07001409 }
Vladimir Kozlovb4977e82013-05-08 15:08:01 -07001410 if (mem->is_Phi() && (mem->in(0) == region)) {
1411 x->set_req(Memory, mem->in(i)); // Use pre-Phi input for the clone.
1412 }
1413 if (address->is_Phi() && address->in(0) == region) {
1414 x->set_req(Address, address->in(i)); // Use pre-Phi input for the clone
1415 }
1416 if (base_is_phi && (base->in(0) == region)) {
1417 Node* base_x = base->in(i); // Clone address for loads from boxed objects.
Tobias Hartmann2a0815a2014-06-02 08:07:29 +02001418 Node* adr_x = phase->transform(new AddPNode(base_x,base_x,address->in(AddPNode::Offset)));
Vladimir Kozlovb4977e82013-05-08 15:08:01 -07001419 x->set_req(Address, adr_x);
Vladimir Kozlov757229d2008-05-21 10:45:07 -07001420 }
1421 }
1422 // Check for a 'win' on some paths
1423 const Type *t = x->Value(igvn);
1424
1425 bool singleton = t->singleton();
1426
1427 // See comments in PhaseIdealLoop::split_thru_phi().
Vladimir Kozlovabc5f942011-04-20 18:29:35 -07001428 if (singleton && t == Type::TOP) {
Vladimir Kozlov757229d2008-05-21 10:45:07 -07001429 singleton &= region->is_Loop() && (i != LoopNode::EntryControl);
1430 }
1431
Vladimir Kozlovabc5f942011-04-20 18:29:35 -07001432 if (singleton) {
Vladimir Kozlov757229d2008-05-21 10:45:07 -07001433 x = igvn->makecon(t);
1434 } else {
1435 // We now call Identity to try to simplify the cloned node.
1436 // Note that some Identity methods call phase->type(this).
1437 // Make sure that the type array is big enough for
1438 // our new node, even though we may throw the node away.
1439 // (This tweaking with igvn only works because x is a new node.)
1440 igvn->set_type(x, t);
Vladimir Kozlov897278f2008-08-01 10:06:45 -07001441 // If x is a TypeNode, capture any more-precise type permanently into Node
Christian Thalinger05d1de72009-02-27 13:27:09 -08001442 // otherwise it will be not updated during igvn->transform since
Vladimir Kozlov897278f2008-08-01 10:06:45 -07001443 // igvn->type(x) is set to x->Value() already.
1444 x->raise_bottom_type(t);
Vladimir Kozlov757229d2008-05-21 10:45:07 -07001445 Node *y = x->Identity(igvn);
Vladimir Kozlovabc5f942011-04-20 18:29:35 -07001446 if (y != x) {
Vladimir Kozlov757229d2008-05-21 10:45:07 -07001447 x = y;
1448 } else {
Vladimir Kozlovb4977e82013-05-08 15:08:01 -07001449 y = igvn->hash_find_insert(x);
Vladimir Kozlovabc5f942011-04-20 18:29:35 -07001450 if (y) {
Vladimir Kozlov757229d2008-05-21 10:45:07 -07001451 x = y;
1452 } else {
1453 // Else x is a new node we are keeping
1454 // We do not need register_new_node_with_optimizer
1455 // because set_type has already been called.
1456 igvn->_worklist.push(x);
1457 }
1458 }
1459 }
Vladimir Kozlovb4977e82013-05-08 15:08:01 -07001460 if (x != the_clone && the_clone != NULL) {
Vladimir Kozlov757229d2008-05-21 10:45:07 -07001461 igvn->remove_dead_node(the_clone);
Vladimir Kozlovb4977e82013-05-08 15:08:01 -07001462 }
Vladimir Kozlov757229d2008-05-21 10:45:07 -07001463 phi->set_req(i, x);
1464 }
Vladimir Kozlovabc5f942011-04-20 18:29:35 -07001465 // Record Phi
1466 igvn->register_new_node_with_optimizer(phi);
1467 return phi;
Vladimir Kozlov757229d2008-05-21 10:45:07 -07001468}
Tom Rodriguez10c473e2007-12-05 09:01:00 -08001469
J. Duke81537792007-12-01 00:00:00 +00001470//------------------------------Ideal------------------------------------------
Zoltan Majo49b224a2014-11-06 09:40:58 +01001471// If the load is from Field memory and the pointer is non-null, it might be possible to
J. Duke81537792007-12-01 00:00:00 +00001472// zero out the control input.
1473// If the offset is constant and the base is an object allocation,
1474// try to hook me up to the exact initializing store.
1475Node *LoadNode::Ideal(PhaseGVN *phase, bool can_reshape) {
1476 Node* p = MemNode::Ideal_common(phase, can_reshape);
1477 if (p) return (p == NodeSentinel) ? NULL : p;
1478
1479 Node* ctrl = in(MemNode::Control);
1480 Node* address = in(MemNode::Address);
Tobias Hartmann11eb4552014-07-25 10:06:17 +02001481 bool progress = false;
J. Duke81537792007-12-01 00:00:00 +00001482
1483 // Skip up past a SafePoint control. Cannot do this for Stores because
1484 // pointer stores & cardmarks must stay on the same side of a SafePoint.
1485 if( ctrl != NULL && ctrl->Opcode() == Op_SafePoint &&
1486 phase->C->get_alias_index(phase->type(address)->is_ptr()) != Compile::AliasIdxRaw ) {
1487 ctrl = ctrl->in(0);
1488 set_req(MemNode::Control,ctrl);
Tobias Hartmann11eb4552014-07-25 10:06:17 +02001489 progress = true;
J. Duke81537792007-12-01 00:00:00 +00001490 }
1491
Vladimir Kozlovca3a3502009-04-07 19:04:24 -07001492 intptr_t ignore = 0;
1493 Node* base = AddPNode::Ideal_base_and_offset(address, phase, ignore);
1494 if (base != NULL
1495 && phase->C->get_alias_index(phase->type(address)->is_ptr()) != Compile::AliasIdxRaw) {
1496 // Check for useless control edge in some common special cases
1497 if (in(MemNode::Control) != NULL
Zoltan Majo49b224a2014-11-06 09:40:58 +01001498 && can_remove_control()
J. Duke81537792007-12-01 00:00:00 +00001499 && phase->type(base)->higher_equal(TypePtr::NOTNULL)
Vladimir Kozlovdf8fc192008-04-16 19:19:48 -07001500 && all_controls_dominate(base, phase->C->start())) {
J. Duke81537792007-12-01 00:00:00 +00001501 // A method-invariant, non-null address (constant or 'this' argument).
1502 set_req(MemNode::Control, NULL);
Tobias Hartmann11eb4552014-07-25 10:06:17 +02001503 progress = true;
J. Duke81537792007-12-01 00:00:00 +00001504 }
Tom Rodriguez10c473e2007-12-05 09:01:00 -08001505 }
1506
Vladimir Kozlovcdd27962008-03-20 15:11:44 -07001507 Node* mem = in(MemNode::Memory);
1508 const TypePtr *addr_t = phase->type(address)->isa_ptr();
1509
Vladimir Kozlovb4977e82013-05-08 15:08:01 -07001510 if (can_reshape && (addr_t != NULL)) {
Vladimir Kozlovcdd27962008-03-20 15:11:44 -07001511 // try to optimize our memory input
Vladimir Kozlovb4977e82013-05-08 15:08:01 -07001512 Node* opt_mem = MemNode::optimize_memory_chain(mem, addr_t, this, phase);
Vladimir Kozlovcdd27962008-03-20 15:11:44 -07001513 if (opt_mem != mem) {
1514 set_req(MemNode::Memory, opt_mem);
Vladimir Kozlov37306312008-08-27 09:15:46 -07001515 if (phase->type( opt_mem ) == Type::TOP) return NULL;
Vladimir Kozlovcdd27962008-03-20 15:11:44 -07001516 return this;
1517 }
1518 const TypeOopPtr *t_oop = addr_t->isa_oopptr();
Vladimir Kozlovb4977e82013-05-08 15:08:01 -07001519 if ((t_oop != NULL) &&
1520 (t_oop->is_known_instance_field() ||
1521 t_oop->is_ptr_to_boxed_value())) {
Vladimir Kozlov09b79022011-11-09 07:25:51 -08001522 PhaseIterGVN *igvn = phase->is_IterGVN();
1523 if (igvn != NULL && igvn->_worklist.member(opt_mem)) {
1524 // Delay this transformation until memory Phi is processed.
1525 phase->is_IterGVN()->_worklist.push(this);
1526 return NULL;
1527 }
Vladimir Kozlov757229d2008-05-21 10:45:07 -07001528 // Split instance field load through Phi.
1529 Node* result = split_through_phi(phase);
1530 if (result != NULL) return result;
Vladimir Kozlovb4977e82013-05-08 15:08:01 -07001531
1532 if (t_oop->is_ptr_to_boxed_value()) {
1533 Node* result = eliminate_autobox(phase);
1534 if (result != NULL) return result;
1535 }
Vladimir Kozlovcdd27962008-03-20 15:11:44 -07001536 }
1537 }
1538
Roland Westrelina9cdbd02015-05-12 10:27:50 +02001539 // Is there a dominating load that loads the same value? Leave
1540 // anything that is not a load of a field/array element (like
1541 // barriers etc.) alone
1542 if (in(0) != NULL && adr_type() != TypeRawPtr::BOTTOM && can_reshape) {
1543 for (DUIterator_Fast imax, i = mem->fast_outs(imax); i < imax; i++) {
1544 Node *use = mem->fast_out(i);
1545 if (use != this &&
1546 use->Opcode() == Opcode() &&
1547 use->in(0) != NULL &&
1548 use->in(0) != in(0) &&
1549 use->in(Address) == in(Address)) {
1550 Node* ctl = in(0);
1551 for (int i = 0; i < 10 && ctl != NULL; i++) {
1552 ctl = IfNode::up_one_dom(ctl);
1553 if (ctl == use->in(0)) {
1554 set_req(0, use->in(0));
1555 return this;
1556 }
1557 }
1558 }
1559 }
1560 }
1561
J. Duke81537792007-12-01 00:00:00 +00001562 // Check for prior store with a different base or offset; make Load
1563 // independent. Skip through any number of them. Bail out if the stores
1564 // are in an endless dead cycle and report no progress. This is a key
1565 // transform for Reflection. However, if after skipping through the Stores
1566 // we can't then fold up against a prior store do NOT do the transform as
1567 // this amounts to using the 'Oracle' model of aliasing. It leaves the same
1568 // array memory alive twice: once for the hoisted Load and again after the
1569 // bypassed Store. This situation only works if EVERYBODY who does
1570 // anti-dependence work knows how to bypass. I.e. we need all
1571 // anti-dependence checks to ask the same Oracle. Right now, that Oracle is
1572 // the alias index stuff. So instead, peek through Stores and IFF we can
1573 // fold up, do so.
1574 Node* prev_mem = find_previous_store(phase);
Roland Westrelina9cdbd02015-05-12 10:27:50 +02001575 if (prev_mem != NULL) {
1576 Node* value = can_see_arraycopy_value(prev_mem, phase);
1577 if (value != NULL) {
1578 return value;
1579 }
1580 }
J. Duke81537792007-12-01 00:00:00 +00001581 // Steps (a), (b): Walk past independent stores to find an exact match.
1582 if (prev_mem != NULL && prev_mem != in(MemNode::Memory)) {
1583 // (c) See if we can fold up on the spot, but don't fold up here.
Christian Thalinger3b8452d2009-01-26 16:22:12 +01001584 // Fold-up might require truncation (for LoadB/LoadS/LoadUS) or
J. Duke81537792007-12-01 00:00:00 +00001585 // just return a prior value, which is done by Identity calls.
1586 if (can_see_stored_value(prev_mem, phase)) {
1587 // Make ready for step (d):
1588 set_req(MemNode::Memory, prev_mem);
1589 return this;
1590 }
1591 }
1592
Tobias Hartmann11eb4552014-07-25 10:06:17 +02001593 return progress ? this : NULL;
J. Duke81537792007-12-01 00:00:00 +00001594}
1595
1596// Helper to recognize certain Klass fields which are invariant across
1597// some group of array types (e.g., int[] or all T[] where T < Object).
1598const Type*
1599LoadNode::load_array_final_field(const TypeKlassPtr *tkls,
1600 ciKlass* klass) const {
Stefan Karlssone057d602011-12-07 11:35:03 +01001601 if (tkls->offset() == in_bytes(Klass::modifier_flags_offset())) {
J. Duke81537792007-12-01 00:00:00 +00001602 // The field is Klass::_modifier_flags. Return its (constant) value.
1603 // (Folds up the 2nd indirection in aClassConstant.getModifiers().)
1604 assert(this->Opcode() == Op_LoadI, "must load an int from _modifier_flags");
1605 return TypeInt::make(klass->modifier_flags());
1606 }
Stefan Karlssone057d602011-12-07 11:35:03 +01001607 if (tkls->offset() == in_bytes(Klass::access_flags_offset())) {
J. Duke81537792007-12-01 00:00:00 +00001608 // The field is Klass::_access_flags. Return its (constant) value.
1609 // (Folds up the 2nd indirection in Reflection.getClassAccessFlags(aClassConstant).)
1610 assert(this->Opcode() == Op_LoadI, "must load an int from _access_flags");
1611 return TypeInt::make(klass->access_flags());
1612 }
Stefan Karlssone057d602011-12-07 11:35:03 +01001613 if (tkls->offset() == in_bytes(Klass::layout_helper_offset())) {
J. Duke81537792007-12-01 00:00:00 +00001614 // The field is Klass::_layout_helper. Return its constant value if known.
1615 assert(this->Opcode() == Op_LoadI, "must load an int from _layout_helper");
1616 return TypeInt::make(klass->layout_helper());
1617 }
1618
1619 // No match.
1620 return NULL;
1621}
1622
Vladimir Ivanov661796f2016-03-28 13:49:34 +03001623static ciConstant check_mismatched_access(ciConstant con, BasicType loadbt, bool is_unsigned) {
Vladimir Ivanovabebc2d2016-02-26 01:58:26 +03001624 BasicType conbt = con.basic_type();
Vladimir Ivanovbb51ea72016-02-29 23:46:55 +03001625 switch (conbt) {
1626 case T_BOOLEAN: conbt = T_BYTE; break;
1627 case T_ARRAY: conbt = T_OBJECT; break;
1628 }
1629 switch (loadbt) {
1630 case T_BOOLEAN: loadbt = T_BYTE; break;
1631 case T_NARROWOOP: loadbt = T_OBJECT; break;
1632 case T_ARRAY: loadbt = T_OBJECT; break;
1633 case T_ADDRESS: loadbt = T_OBJECT; break;
Vladimir Ivanovabebc2d2016-02-26 01:58:26 +03001634 }
Vladimir Ivanov661796f2016-03-28 13:49:34 +03001635 if (conbt == loadbt) {
1636 if (is_unsigned && conbt == T_BYTE) {
1637 // LoadB (T_BYTE) with a small mask (<=8-bit) is converted to LoadUB (T_BYTE).
1638 return ciConstant(T_INT, con.as_int() & 0xFF);
1639 } else {
1640 return con;
1641 }
1642 }
1643 if (conbt == T_SHORT && loadbt == T_CHAR) {
1644 // LoadS (T_SHORT) with a small mask (<=16-bit) is converted to LoadUS (T_CHAR).
1645 return ciConstant(T_INT, con.as_int() & 0xFFFF);
1646 }
1647 return ciConstant(); // T_ILLEGAL
Vladimir Ivanovabebc2d2016-02-26 01:58:26 +03001648}
1649
Vladimir Ivanovf0e77ac2013-09-10 14:51:48 -07001650// Try to constant-fold a stable array element.
Vladimir Ivanov661796f2016-03-28 13:49:34 +03001651static const Type* fold_stable_ary_elem(const TypeAryPtr* ary, int off, bool is_unsigned_load, BasicType loadbt) {
Vladimir Ivanovbd8255e2014-03-06 09:53:14 -08001652 assert(ary->const_oop(), "array should be constant");
Vladimir Ivanovf0e77ac2013-09-10 14:51:48 -07001653 assert(ary->is_stable(), "array should be stable");
1654
Vladimir Ivanovbd8255e2014-03-06 09:53:14 -08001655 // Decode the results of GraphKit::array_element_address.
1656 ciArray* aobj = ary->const_oop()->as_array();
Vladimir Ivanov661796f2016-03-28 13:49:34 +03001657 ciConstant element_value = aobj->element_value_by_offset(off);
1658 if (element_value.basic_type() == T_ILLEGAL) {
1659 return NULL; // wrong offset
1660 }
1661 ciConstant con = check_mismatched_access(element_value, loadbt, is_unsigned_load);
1662 assert(con.basic_type() != T_ILLEGAL, "elembt=%s; loadbt=%s; unsigned=%d",
1663 type2name(element_value.basic_type()), type2name(loadbt), is_unsigned_load);
1664
1665 if (con.basic_type() != T_ILLEGAL && // not a mismatched access
1666 !con.is_null_or_zero()) { // not a default value
Vladimir Ivanovbd8255e2014-03-06 09:53:14 -08001667 const Type* con_type = Type::make_from_constant(con);
Vladimir Ivanov661796f2016-03-28 13:49:34 +03001668 if (con_type != NULL) {
Vladimir Ivanovbd8255e2014-03-06 09:53:14 -08001669 if (con_type->isa_aryptr()) {
1670 // Join with the array element type, in case it is also stable.
1671 int dim = ary->stable_dimension();
1672 con_type = con_type->is_aryptr()->cast_to_stable(true, dim-1);
Vladimir Ivanovf0e77ac2013-09-10 14:51:48 -07001673 }
Vladimir Ivanovbd8255e2014-03-06 09:53:14 -08001674 if (loadbt == T_NARROWOOP && con_type->isa_oopptr()) {
1675 con_type = con_type->make_narrowoop();
1676 }
1677#ifndef PRODUCT
1678 if (TraceIterativeGVN) {
1679 tty->print("FoldStableValues: array element [off=%d]: con_type=", off);
1680 con_type->dump(); tty->cr();
1681 }
1682#endif //PRODUCT
1683 return con_type;
Vladimir Ivanovf0e77ac2013-09-10 14:51:48 -07001684 }
1685 }
Vladimir Ivanovf0e77ac2013-09-10 14:51:48 -07001686 return NULL;
1687}
1688
J. Duke81537792007-12-01 00:00:00 +00001689//------------------------------Value-----------------------------------------
Tobias Hartmann69b52aa2016-01-12 12:55:09 +01001690const Type* LoadNode::Value(PhaseGVN* phase) const {
J. Duke81537792007-12-01 00:00:00 +00001691 // Either input is TOP ==> the result is TOP
1692 Node* mem = in(MemNode::Memory);
1693 const Type *t1 = phase->type(mem);
1694 if (t1 == Type::TOP) return Type::TOP;
1695 Node* adr = in(MemNode::Address);
1696 const TypePtr* tp = phase->type(adr)->isa_ptr();
1697 if (tp == NULL || tp->empty()) return Type::TOP;
1698 int off = tp->offset();
1699 assert(off != Type::OffsetTop, "case covered by TypePtr::empty");
Christian Thalinger1038fed2011-09-02 04:28:59 -07001700 Compile* C = phase->C;
J. Duke81537792007-12-01 00:00:00 +00001701
1702 // Try to guess loaded type from pointer type
Vladimir Ivanovf0e77ac2013-09-10 14:51:48 -07001703 if (tp->isa_aryptr()) {
1704 const TypeAryPtr* ary = tp->is_aryptr();
Vladimir Ivanovbd8255e2014-03-06 09:53:14 -08001705 const Type* t = ary->elem();
Vladimir Ivanovf0e77ac2013-09-10 14:51:48 -07001706
1707 // Determine whether the reference is beyond the header or not, by comparing
1708 // the offset against the offset of the start of the array's data.
1709 // Different array types begin at slightly different offsets (12 vs. 16).
1710 // We choose T_BYTE as an example base type that is least restrictive
1711 // as to alignment, which will therefore produce the smallest
1712 // possible base offset.
1713 const int min_base_off = arrayOopDesc::base_offset_in_bytes(T_BYTE);
1714 const bool off_beyond_header = ((uint)off >= (uint)min_base_off);
1715
1716 // Try to constant-fold a stable array element.
Vladimir Ivanovabebc2d2016-02-26 01:58:26 +03001717 if (FoldStableValues && !is_mismatched_access() && ary->is_stable() && ary->const_oop() != NULL) {
Vladimir Ivanovbd8255e2014-03-06 09:53:14 -08001718 // Make sure the reference is not into the header and the offset is constant
1719 if (off_beyond_header && adr->is_AddP() && off != Type::OffsetBot) {
Vladimir Ivanov661796f2016-03-28 13:49:34 +03001720 const Type* con_type = fold_stable_ary_elem(ary, off, is_unsigned(), memory_type());
Vladimir Ivanovf0e77ac2013-09-10 14:51:48 -07001721 if (con_type != NULL) {
1722 return con_type;
1723 }
1724 }
1725 }
1726
J. Duke81537792007-12-01 00:00:00 +00001727 // Don't do this for integer types. There is only potential profit if
1728 // the element type t is lower than _type; that is, for int types, if _type is
1729 // more restrictive than t. This only happens here if one is short and the other
1730 // char (both 16 bits), and in those cases we've made an intentional decision
1731 // to use one kind of load over the other. See AndINode::Ideal and 4965907.
1732 // Also, do not try to narrow the type for a LoadKlass, regardless of offset.
1733 //
1734 // Yes, it is possible to encounter an expression like (LoadKlass p1:(AddP x x 8))
1735 // where the _gvn.type of the AddP is wider than 8. This occurs when an earlier
1736 // copy p0 of (AddP x x 8) has been proven equal to p1, and the p0 has been
1737 // subsumed by p1. If p1 is on the worklist but has not yet been re-transformed,
1738 // it is possible that p1 will have a type like Foo*[int+]:NotNull*+any.
1739 // In fact, that could have been the original type of p1, and p1 could have
1740 // had an original form like p1:(AddP x x (LShiftL quux 3)), where the
1741 // expression (LShiftL quux 3) independently optimized to the constant 8.
1742 if ((t->isa_int() == NULL) && (t->isa_long() == NULL)
Vladimir Kozlovd1191bb2012-06-15 01:25:19 -07001743 && (_type->isa_vect() == NULL)
Vladimir Kozlov897278f2008-08-01 10:06:45 -07001744 && Opcode() != Op_LoadKlass && Opcode() != Op_LoadNKlass) {
J. Duke81537792007-12-01 00:00:00 +00001745 // t might actually be lower than _type, if _type is a unique
1746 // concrete subclass of abstract class t.
Vladimir Ivanovf0e77ac2013-09-10 14:51:48 -07001747 if (off_beyond_header) { // is the offset beyond the header?
Roland Westrelinc19a7e02014-01-24 09:31:53 +01001748 const Type* jt = t->join_speculative(_type);
J. Duke81537792007-12-01 00:00:00 +00001749 // In any case, do not allow the join, per se, to empty out the type.
1750 if (jt->empty() && !t->empty()) {
1751 // This can happen if a interface-typed array narrows to a class type.
1752 jt = _type;
1753 }
Vladimir Kozlovb4977e82013-05-08 15:08:01 -07001754#ifdef ASSERT
1755 if (phase->C->eliminate_boxing() && adr->is_AddP()) {
Tom Rodriguez10c473e2007-12-05 09:01:00 -08001756 // The pointers in the autobox arrays are always non-null
Vladimir Kozlovca3a3502009-04-07 19:04:24 -07001757 Node* base = adr->in(AddPNode::Base);
Vladimir Kozlovb4977e82013-05-08 15:08:01 -07001758 if ((base != NULL) && base->is_DecodeN()) {
1759 // Get LoadN node which loads IntegerCache.cache field
1760 base = base->in(1);
1761 }
1762 if ((base != NULL) && base->is_Con()) {
1763 const TypeAryPtr* base_type = base->bottom_type()->isa_aryptr();
1764 if ((base_type != NULL) && base_type->is_autobox_cache()) {
1765 // It could be narrow oop
1766 assert(jt->make_ptr()->ptr() == TypePtr::NotNull,"sanity");
Tom Rodriguez10c473e2007-12-05 09:01:00 -08001767 }
1768 }
1769 }
Vladimir Kozlovb4977e82013-05-08 15:08:01 -07001770#endif
J. Duke81537792007-12-01 00:00:00 +00001771 return jt;
1772 }
1773 }
1774 } else if (tp->base() == Type::InstPtr) {
Christian Thalinger1038fed2011-09-02 04:28:59 -07001775 ciEnv* env = C->env();
Tom Rodriguez9db20922009-11-12 09:24:21 -08001776 const TypeInstPtr* tinst = tp->is_instptr();
1777 ciKlass* klass = tinst->klass();
J. Duke81537792007-12-01 00:00:00 +00001778 assert( off != Type::OffsetBot ||
1779 // arrays can be cast to Objects
1780 tp->is_oopptr()->klass()->is_java_lang_Object() ||
1781 // unsafe field access may not have a constant offset
Christian Thalinger1038fed2011-09-02 04:28:59 -07001782 C->has_unsafe_access(),
J. Duke81537792007-12-01 00:00:00 +00001783 "Field accesses must be precise" );
Aleksey Shipilev03174f32016-02-15 23:45:15 +03001784 // For oop loads, we expect the _type to be precise.
Christian Thalinger1038fed2011-09-02 04:28:59 -07001785 // Optimizations for constant objects
1786 ciObject* const_oop = tinst->const_oop();
1787 if (const_oop != NULL) {
1788 // For constant CallSites treat the target field as a compile time constant.
1789 if (const_oop->is_call_site()) {
1790 ciCallSite* call_site = const_oop->as_call_site();
1791 ciField* field = call_site->klass()->as_instance_klass()->get_field_by_offset(off, /*is_static=*/ false);
1792 if (field != NULL && field->is_call_site_target()) {
1793 ciMethodHandle* target = call_site->get_target();
1794 if (target != NULL) { // just in case
1795 ciConstant constant(T_OBJECT, target);
1796 const Type* t;
1797 if (adr->bottom_type()->is_ptr_to_narrowoop()) {
1798 t = TypeNarrowOop::make_from_constant(constant.as_object(), true);
1799 } else {
1800 t = TypeOopPtr::make_from_constant(constant.as_object(), true);
1801 }
1802 // Add a dependence for invalidation of the optimization.
1803 if (!call_site->is_constant_call_site()) {
1804 C->dependencies()->assert_call_site_target_value(call_site, target);
1805 }
1806 return t;
1807 }
1808 }
1809 }
1810 }
J. Duke81537792007-12-01 00:00:00 +00001811 } else if (tp->base() == Type::KlassPtr) {
1812 assert( off != Type::OffsetBot ||
1813 // arrays can be cast to Objects
1814 tp->is_klassptr()->klass()->is_java_lang_Object() ||
1815 // also allow array-loading from the primary supertype
1816 // array during subtype checks
1817 Opcode() == Op_LoadKlass,
1818 "Field accesses must be precise" );
1819 // For klass/static loads, we expect the _type to be precise
1820 }
1821
1822 const TypeKlassPtr *tkls = tp->isa_klassptr();
1823 if (tkls != NULL && !StressReflectiveCode) {
1824 ciKlass* klass = tkls->klass();
1825 if (klass->is_loaded() && tkls->klass_is_exact()) {
1826 // We are loading a field from a Klass metaobject whose identity
1827 // is known at compile time (the type is "exact" or "precise").
1828 // Check for fields we know are maintained as constants by the VM.
Stefan Karlssone057d602011-12-07 11:35:03 +01001829 if (tkls->offset() == in_bytes(Klass::super_check_offset_offset())) {
J. Duke81537792007-12-01 00:00:00 +00001830 // The field is Klass::_super_check_offset. Return its (constant) value.
1831 // (Folds up type checking code.)
1832 assert(Opcode() == Op_LoadI, "must load an int from _super_check_offset");
1833 return TypeInt::make(klass->super_check_offset());
1834 }
1835 // Compute index into primary_supers array
Jon Masamitsu5c58d272012-09-01 13:25:18 -04001836 juint depth = (tkls->offset() - in_bytes(Klass::primary_supers_offset())) / sizeof(Klass*);
J. Duke81537792007-12-01 00:00:00 +00001837 // Check for overflowing; use unsigned compare to handle the negative case.
1838 if( depth < ciKlass::primary_super_limit() ) {
1839 // The field is an element of Klass::_primary_supers. Return its (constant) value.
1840 // (Folds up type checking code.)
1841 assert(Opcode() == Op_LoadKlass, "must load a klass from _primary_supers");
1842 ciKlass *ss = klass->super_of_depth(depth);
1843 return ss ? TypeKlassPtr::make(ss) : TypePtr::NULL_PTR;
1844 }
1845 const Type* aift = load_array_final_field(tkls, klass);
1846 if (aift != NULL) return aift;
Stefan Karlssone057d602011-12-07 11:35:03 +01001847 if (tkls->offset() == in_bytes(Klass::java_mirror_offset())) {
J. Duke81537792007-12-01 00:00:00 +00001848 // The field is Klass::_java_mirror. Return its (constant) value.
1849 // (Folds up the 2nd indirection in anObjConstant.getClass().)
1850 assert(Opcode() == Op_LoadP, "must load an oop from _java_mirror");
1851 return TypeInstPtr::make(klass->java_mirror());
1852 }
1853 }
1854
1855 // We can still check if we are loading from the primary_supers array at a
1856 // shallow enough depth. Even though the klass is not exact, entries less
1857 // than or equal to its super depth are correct.
1858 if (klass->is_loaded() ) {
Jon Masamitsu5c58d272012-09-01 13:25:18 -04001859 ciType *inner = klass;
J. Duke81537792007-12-01 00:00:00 +00001860 while( inner->is_obj_array_klass() )
1861 inner = inner->as_obj_array_klass()->base_element_type();
1862 if( inner->is_instance_klass() &&
1863 !inner->as_instance_klass()->flags().is_interface() ) {
1864 // Compute index into primary_supers array
Jon Masamitsu5c58d272012-09-01 13:25:18 -04001865 juint depth = (tkls->offset() - in_bytes(Klass::primary_supers_offset())) / sizeof(Klass*);
J. Duke81537792007-12-01 00:00:00 +00001866 // Check for overflowing; use unsigned compare to handle the negative case.
1867 if( depth < ciKlass::primary_super_limit() &&
1868 depth <= klass->super_depth() ) { // allow self-depth checks to handle self-check case
1869 // The field is an element of Klass::_primary_supers. Return its (constant) value.
1870 // (Folds up type checking code.)
1871 assert(Opcode() == Op_LoadKlass, "must load a klass from _primary_supers");
1872 ciKlass *ss = klass->super_of_depth(depth);
1873 return ss ? TypeKlassPtr::make(ss) : TypePtr::NULL_PTR;
1874 }
1875 }
1876 }
1877
1878 // If the type is enough to determine that the thing is not an array,
1879 // we can give the layout_helper a positive interval type.
1880 // This will help short-circuit some reflective code.
Stefan Karlssone057d602011-12-07 11:35:03 +01001881 if (tkls->offset() == in_bytes(Klass::layout_helper_offset())
J. Duke81537792007-12-01 00:00:00 +00001882 && !klass->is_array_klass() // not directly typed as an array
1883 && !klass->is_interface() // specifically not Serializable & Cloneable
1884 && !klass->is_java_lang_Object() // not the supertype of all T[]
1885 ) {
1886 // Note: When interfaces are reliable, we can narrow the interface
1887 // test to (klass != Serializable && klass != Cloneable).
1888 assert(Opcode() == Op_LoadI, "must load an int from _layout_helper");
1889 jint min_size = Klass::instance_layout_helper(oopDesc::header_size(), false);
1890 // The key property of this type is that it folds up tests
1891 // for array-ness, since it proves that the layout_helper is positive.
1892 // Thus, a generic value like the basic object layout helper works fine.
1893 return TypeInt::make(min_size, max_jint, Type::WidenMin);
1894 }
1895 }
1896
1897 // If we are loading from a freshly-allocated object, produce a zero,
1898 // if the load is provably beyond the header of the object.
1899 // (Also allow a variable load from a fresh array to produce zero.)
Vladimir Kozlovabc5f942011-04-20 18:29:35 -07001900 const TypeOopPtr *tinst = tp->isa_oopptr();
1901 bool is_instance = (tinst != NULL) && tinst->is_known_instance_field();
Vladimir Kozlovb4977e82013-05-08 15:08:01 -07001902 bool is_boxed_value = (tinst != NULL) && tinst->is_ptr_to_boxed_value();
1903 if (ReduceFieldZeroing || is_instance || is_boxed_value) {
J. Duke81537792007-12-01 00:00:00 +00001904 Node* value = can_see_stored_value(mem,phase);
Vladimir Kozlov5b3f2ef2012-01-20 09:43:06 -08001905 if (value != NULL && value->is_Con()) {
1906 assert(value->bottom_type()->higher_equal(_type),"sanity");
J. Duke81537792007-12-01 00:00:00 +00001907 return value->bottom_type();
Vladimir Kozlov5b3f2ef2012-01-20 09:43:06 -08001908 }
J. Duke81537792007-12-01 00:00:00 +00001909 }
1910
Vladimir Kozlovabc5f942011-04-20 18:29:35 -07001911 if (is_instance) {
Vladimir Kozlov30dc0ed2008-03-13 16:31:32 -07001912 // If we have an instance type and our memory input is the
1913 // programs's initial memory state, there is no matching store,
1914 // so just return a zero of the appropriate type
1915 Node *mem = in(MemNode::Memory);
1916 if (mem->is_Parm() && mem->in(0)->is_Start()) {
1917 assert(mem->as_Parm()->_con == TypeFunc::Memory, "must be memory Parm");
1918 return Type::get_zero_type(_type->basic_type());
1919 }
1920 }
J. Duke81537792007-12-01 00:00:00 +00001921 return _type;
1922}
1923
1924//------------------------------match_edge-------------------------------------
1925// Do we Match on this edge index or not? Match only the address.
1926uint LoadNode::match_edge(uint idx) const {
1927 return idx == MemNode::Address;
1928}
1929
1930//--------------------------LoadBNode::Ideal--------------------------------------
1931//
1932// If the previous store is to the same address as this load,
1933// and the value stored was larger than a byte, replace this load
1934// with the value stored truncated to a byte. If no truncation is
1935// needed, the replacement is done in LoadNode::Identity().
1936//
1937Node *LoadBNode::Ideal(PhaseGVN *phase, bool can_reshape) {
1938 Node* mem = in(MemNode::Memory);
1939 Node* value = can_see_stored_value(mem,phase);
1940 if( value && !phase->type(value)->higher_equal( _type ) ) {
Tobias Hartmann2a0815a2014-06-02 08:07:29 +02001941 Node *result = phase->transform( new LShiftINode(value, phase->intcon(24)) );
1942 return new RShiftINode(result, phase->intcon(24));
J. Duke81537792007-12-01 00:00:00 +00001943 }
1944 // Identity call will handle the case where truncation is not needed.
1945 return LoadNode::Ideal(phase, can_reshape);
1946}
1947
Tobias Hartmann69b52aa2016-01-12 12:55:09 +01001948const Type* LoadBNode::Value(PhaseGVN* phase) const {
Vladimir Kozlov5b3f2ef2012-01-20 09:43:06 -08001949 Node* mem = in(MemNode::Memory);
1950 Node* value = can_see_stored_value(mem,phase);
Vladimir Kozlov3770ece2012-01-24 17:04:51 -08001951 if (value != NULL && value->is_Con() &&
1952 !value->bottom_type()->higher_equal(_type)) {
Vladimir Kozlov5b3f2ef2012-01-20 09:43:06 -08001953 // If the input to the store does not fit with the load's result type,
1954 // it must be truncated. We can't delay until Ideal call since
1955 // a singleton Value is needed for split_thru_phi optimization.
1956 int con = value->get_int();
1957 return TypeInt::make((con << 24) >> 24);
1958 }
1959 return LoadNode::Value(phase);
1960}
1961
Christian Thalinger89cea912009-03-09 03:17:11 -07001962//--------------------------LoadUBNode::Ideal-------------------------------------
1963//
1964// If the previous store is to the same address as this load,
1965// and the value stored was larger than a byte, replace this load
1966// with the value stored truncated to a byte. If no truncation is
1967// needed, the replacement is done in LoadNode::Identity().
1968//
1969Node* LoadUBNode::Ideal(PhaseGVN* phase, bool can_reshape) {
1970 Node* mem = in(MemNode::Memory);
1971 Node* value = can_see_stored_value(mem, phase);
1972 if (value && !phase->type(value)->higher_equal(_type))
Tobias Hartmann2a0815a2014-06-02 08:07:29 +02001973 return new AndINode(value, phase->intcon(0xFF));
Christian Thalinger89cea912009-03-09 03:17:11 -07001974 // Identity call will handle the case where truncation is not needed.
1975 return LoadNode::Ideal(phase, can_reshape);
1976}
1977
Tobias Hartmann69b52aa2016-01-12 12:55:09 +01001978const Type* LoadUBNode::Value(PhaseGVN* phase) const {
Vladimir Kozlov5b3f2ef2012-01-20 09:43:06 -08001979 Node* mem = in(MemNode::Memory);
1980 Node* value = can_see_stored_value(mem,phase);
Vladimir Kozlov3770ece2012-01-24 17:04:51 -08001981 if (value != NULL && value->is_Con() &&
1982 !value->bottom_type()->higher_equal(_type)) {
Vladimir Kozlov5b3f2ef2012-01-20 09:43:06 -08001983 // If the input to the store does not fit with the load's result type,
1984 // it must be truncated. We can't delay until Ideal call since
1985 // a singleton Value is needed for split_thru_phi optimization.
1986 int con = value->get_int();
1987 return TypeInt::make(con & 0xFF);
1988 }
1989 return LoadNode::Value(phase);
1990}
1991
Christian Thalinger3b8452d2009-01-26 16:22:12 +01001992//--------------------------LoadUSNode::Ideal-------------------------------------
J. Duke81537792007-12-01 00:00:00 +00001993//
1994// If the previous store is to the same address as this load,
1995// and the value stored was larger than a char, replace this load
1996// with the value stored truncated to a char. If no truncation is
1997// needed, the replacement is done in LoadNode::Identity().
1998//
Christian Thalinger3b8452d2009-01-26 16:22:12 +01001999Node *LoadUSNode::Ideal(PhaseGVN *phase, bool can_reshape) {
J. Duke81537792007-12-01 00:00:00 +00002000 Node* mem = in(MemNode::Memory);
2001 Node* value = can_see_stored_value(mem,phase);
2002 if( value && !phase->type(value)->higher_equal( _type ) )
Tobias Hartmann2a0815a2014-06-02 08:07:29 +02002003 return new AndINode(value,phase->intcon(0xFFFF));
J. Duke81537792007-12-01 00:00:00 +00002004 // Identity call will handle the case where truncation is not needed.
2005 return LoadNode::Ideal(phase, can_reshape);
2006}
2007
Tobias Hartmann69b52aa2016-01-12 12:55:09 +01002008const Type* LoadUSNode::Value(PhaseGVN* phase) const {
Vladimir Kozlov5b3f2ef2012-01-20 09:43:06 -08002009 Node* mem = in(MemNode::Memory);
2010 Node* value = can_see_stored_value(mem,phase);
Vladimir Kozlov3770ece2012-01-24 17:04:51 -08002011 if (value != NULL && value->is_Con() &&
2012 !value->bottom_type()->higher_equal(_type)) {
Vladimir Kozlov5b3f2ef2012-01-20 09:43:06 -08002013 // If the input to the store does not fit with the load's result type,
2014 // it must be truncated. We can't delay until Ideal call since
2015 // a singleton Value is needed for split_thru_phi optimization.
2016 int con = value->get_int();
2017 return TypeInt::make(con & 0xFFFF);
2018 }
2019 return LoadNode::Value(phase);
2020}
2021
J. Duke81537792007-12-01 00:00:00 +00002022//--------------------------LoadSNode::Ideal--------------------------------------
2023//
2024// If the previous store is to the same address as this load,
2025// and the value stored was larger than a short, replace this load
2026// with the value stored truncated to a short. If no truncation is
2027// needed, the replacement is done in LoadNode::Identity().
2028//
2029Node *LoadSNode::Ideal(PhaseGVN *phase, bool can_reshape) {
2030 Node* mem = in(MemNode::Memory);
2031 Node* value = can_see_stored_value(mem,phase);
2032 if( value && !phase->type(value)->higher_equal( _type ) ) {
Tobias Hartmann2a0815a2014-06-02 08:07:29 +02002033 Node *result = phase->transform( new LShiftINode(value, phase->intcon(16)) );
2034 return new RShiftINode(result, phase->intcon(16));
J. Duke81537792007-12-01 00:00:00 +00002035 }
2036 // Identity call will handle the case where truncation is not needed.
2037 return LoadNode::Ideal(phase, can_reshape);
2038}
2039
Tobias Hartmann69b52aa2016-01-12 12:55:09 +01002040const Type* LoadSNode::Value(PhaseGVN* phase) const {
Vladimir Kozlov5b3f2ef2012-01-20 09:43:06 -08002041 Node* mem = in(MemNode::Memory);
2042 Node* value = can_see_stored_value(mem,phase);
Vladimir Kozlov3770ece2012-01-24 17:04:51 -08002043 if (value != NULL && value->is_Con() &&
2044 !value->bottom_type()->higher_equal(_type)) {
Vladimir Kozlov5b3f2ef2012-01-20 09:43:06 -08002045 // If the input to the store does not fit with the load's result type,
2046 // it must be truncated. We can't delay until Ideal call since
2047 // a singleton Value is needed for split_thru_phi optimization.
2048 int con = value->get_int();
2049 return TypeInt::make((con << 16) >> 16);
2050 }
2051 return LoadNode::Value(phase);
2052}
2053
J. Duke81537792007-12-01 00:00:00 +00002054//=============================================================================
Vladimir Kozlov76035422008-05-21 13:46:23 -07002055//----------------------------LoadKlassNode::make------------------------------
2056// Polymorphic factory method:
Zoltan Majo49b224a2014-11-06 09:40:58 +01002057Node* LoadKlassNode::make(PhaseGVN& gvn, Node* ctl, Node* mem, Node* adr, const TypePtr* at, const TypeKlassPtr* tk) {
Vladimir Kozlov76035422008-05-21 13:46:23 -07002058 // sanity check the alias category against the created node type
Jon Masamitsu5c58d272012-09-01 13:25:18 -04002059 const TypePtr *adr_type = adr->bottom_type()->isa_ptr();
2060 assert(adr_type != NULL, "expecting TypeKlassPtr");
Vladimir Kozlov76035422008-05-21 13:46:23 -07002061#ifdef _LP64
Roland Westrelin61eb5a02012-10-09 10:11:38 +02002062 if (adr_type->is_ptr_to_narrowklass()) {
Erik Helin30f059b2013-08-12 17:37:02 +02002063 assert(UseCompressedClassPointers, "no compressed klasses");
Tobias Hartmann2a0815a2014-06-02 08:07:29 +02002064 Node* load_klass = gvn.transform(new LoadNKlassNode(ctl, mem, adr, at, tk->make_narrowklass(), MemNode::unordered));
2065 return new DecodeNKlassNode(load_klass, load_klass->bottom_type()->make_ptr());
Vladimir Kozlov76035422008-05-21 13:46:23 -07002066 }
Vladimir Kozlova1f50992008-05-29 12:04:14 -07002067#endif
Roland Westrelin61eb5a02012-10-09 10:11:38 +02002068 assert(!adr_type->is_ptr_to_narrowklass() && !adr_type->is_ptr_to_narrowoop(), "should have got back a narrow oop");
Tobias Hartmann2a0815a2014-06-02 08:07:29 +02002069 return new LoadKlassNode(ctl, mem, adr, at, tk, MemNode::unordered);
Vladimir Kozlov76035422008-05-21 13:46:23 -07002070}
2071
J. Duke81537792007-12-01 00:00:00 +00002072//------------------------------Value------------------------------------------
Tobias Hartmann69b52aa2016-01-12 12:55:09 +01002073const Type* LoadKlassNode::Value(PhaseGVN* phase) const {
Vladimir Kozlov76035422008-05-21 13:46:23 -07002074 return klass_value_common(phase);
2075}
2076
Zoltan Majo49b224a2014-11-06 09:40:58 +01002077// In most cases, LoadKlassNode does not have the control input set. If the control
2078// input is set, it must not be removed (by LoadNode::Ideal()).
2079bool LoadKlassNode::can_remove_control() const {
2080 return false;
2081}
2082
Tobias Hartmann69b52aa2016-01-12 12:55:09 +01002083const Type* LoadNode::klass_value_common(PhaseGVN* phase) const {
J. Duke81537792007-12-01 00:00:00 +00002084 // Either input is TOP ==> the result is TOP
2085 const Type *t1 = phase->type( in(MemNode::Memory) );
2086 if (t1 == Type::TOP) return Type::TOP;
2087 Node *adr = in(MemNode::Address);
2088 const Type *t2 = phase->type( adr );
2089 if (t2 == Type::TOP) return Type::TOP;
2090 const TypePtr *tp = t2->is_ptr();
2091 if (TypePtr::above_centerline(tp->ptr()) ||
2092 tp->ptr() == TypePtr::Null) return Type::TOP;
2093
2094 // Return a more precise klass, if possible
2095 const TypeInstPtr *tinst = tp->isa_instptr();
2096 if (tinst != NULL) {
2097 ciInstanceKlass* ik = tinst->klass()->as_instance_klass();
2098 int offset = tinst->offset();
2099 if (ik == phase->C->env()->Class_klass()
2100 && (offset == java_lang_Class::klass_offset_in_bytes() ||
2101 offset == java_lang_Class::array_klass_offset_in_bytes())) {
2102 // We are loading a special hidden field from a Class mirror object,
2103 // the field which points to the VM's Klass metaobject.
2104 ciType* t = tinst->java_mirror_type();
2105 // java_mirror_type returns non-null for compile-time Class constants.
2106 if (t != NULL) {
2107 // constant oop => constant klass
2108 if (offset == java_lang_Class::array_klass_offset_in_bytes()) {
Christian Thalingere71c8df2013-12-06 16:43:56 -08002109 if (t->is_void()) {
2110 // We cannot create a void array. Since void is a primitive type return null
2111 // klass. Users of this result need to do a null check on the returned klass.
2112 return TypePtr::NULL_PTR;
2113 }
J. Duke81537792007-12-01 00:00:00 +00002114 return TypeKlassPtr::make(ciArrayKlass::make(t));
2115 }
2116 if (!t->is_klass()) {
2117 // a primitive Class (e.g., int.class) has NULL for a klass field
2118 return TypePtr::NULL_PTR;
2119 }
2120 // (Folds up the 1st indirection in aClassConstant.getModifiers().)
2121 return TypeKlassPtr::make(t->as_klass());
2122 }
2123 // non-constant mirror, so we can't tell what's going on
2124 }
2125 if( !ik->is_loaded() )
2126 return _type; // Bail out if not loaded
2127 if (offset == oopDesc::klass_offset_in_bytes()) {
2128 if (tinst->klass_is_exact()) {
2129 return TypeKlassPtr::make(ik);
2130 }
2131 // See if we can become precise: no subklasses and no interface
2132 // (Note: We need to support verified interfaces.)
2133 if (!ik->is_interface() && !ik->has_subklass()) {
2134 //assert(!UseExactTypes, "this code should be useless with exact types");
2135 // Add a dependence; if any subclass added we need to recompile
2136 if (!ik->is_final()) {
2137 // %%% should use stronger assert_unique_concrete_subtype instead
2138 phase->C->dependencies()->assert_leaf_type(ik);
2139 }
2140 // Return precise klass
2141 return TypeKlassPtr::make(ik);
2142 }
2143
2144 // Return root of possible klass
2145 return TypeKlassPtr::make(TypePtr::NotNull, ik, 0/*offset*/);
2146 }
2147 }
2148
2149 // Check for loading klass from an array
2150 const TypeAryPtr *tary = tp->isa_aryptr();
2151 if( tary != NULL ) {
2152 ciKlass *tary_klass = tary->klass();
2153 if (tary_klass != NULL // can be NULL when at BOTTOM or TOP
2154 && tary->offset() == oopDesc::klass_offset_in_bytes()) {
2155 if (tary->klass_is_exact()) {
2156 return TypeKlassPtr::make(tary_klass);
2157 }
2158 ciArrayKlass *ak = tary->klass()->as_array_klass();
2159 // If the klass is an object array, we defer the question to the
2160 // array component klass.
2161 if( ak->is_obj_array_klass() ) {
2162 assert( ak->is_loaded(), "" );
2163 ciKlass *base_k = ak->as_obj_array_klass()->base_element_klass();
2164 if( base_k->is_loaded() && base_k->is_instance_klass() ) {
2165 ciInstanceKlass* ik = base_k->as_instance_klass();
2166 // See if we can become precise: no subklasses and no interface
2167 if (!ik->is_interface() && !ik->has_subklass()) {
2168 //assert(!UseExactTypes, "this code should be useless with exact types");
2169 // Add a dependence; if any subclass added we need to recompile
2170 if (!ik->is_final()) {
2171 phase->C->dependencies()->assert_leaf_type(ik);
2172 }
2173 // Return precise array klass
2174 return TypeKlassPtr::make(ak);
2175 }
2176 }
2177 return TypeKlassPtr::make(TypePtr::NotNull, ak, 0/*offset*/);
2178 } else { // Found a type-array?
2179 //assert(!UseExactTypes, "this code should be useless with exact types");
2180 assert( ak->is_type_array_klass(), "" );
2181 return TypeKlassPtr::make(ak); // These are always precise
2182 }
2183 }
2184 }
2185
2186 // Check for loading klass from an array klass
2187 const TypeKlassPtr *tkls = tp->isa_klassptr();
2188 if (tkls != NULL && !StressReflectiveCode) {
2189 ciKlass* klass = tkls->klass();
2190 if( !klass->is_loaded() )
2191 return _type; // Bail out if not loaded
2192 if( klass->is_obj_array_klass() &&
Coleen Phillimore28047d62012-09-29 06:40:00 -04002193 tkls->offset() == in_bytes(ObjArrayKlass::element_klass_offset())) {
J. Duke81537792007-12-01 00:00:00 +00002194 ciKlass* elem = klass->as_obj_array_klass()->element_klass();
2195 // // Always returning precise element type is incorrect,
2196 // // e.g., element type could be object and array may contain strings
2197 // return TypeKlassPtr::make(TypePtr::Constant, elem, 0);
2198
2199 // The array's TypeKlassPtr was declared 'precise' or 'not precise'
2200 // according to the element type's subclassing.
2201 return TypeKlassPtr::make(tkls->ptr(), elem, 0/*offset*/);
2202 }
2203 if( klass->is_instance_klass() && tkls->klass_is_exact() &&
Stefan Karlssone057d602011-12-07 11:35:03 +01002204 tkls->offset() == in_bytes(Klass::super_offset())) {
J. Duke81537792007-12-01 00:00:00 +00002205 ciKlass* sup = klass->as_instance_klass()->super();
2206 // The field is Klass::_super. Return its (constant) value.
2207 // (Folds up the 2nd indirection in aClassConstant.getSuperClass().)
2208 return sup ? TypeKlassPtr::make(sup) : TypePtr::NULL_PTR;
2209 }
2210 }
2211
2212 // Bailout case
2213 return LoadNode::Value(phase);
2214}
2215
2216//------------------------------Identity---------------------------------------
2217// To clean up reflective code, simplify k.java_mirror.as_klass to plain k.
2218// Also feed through the klass in Allocate(...klass...)._klass.
Tobias Hartmann69b52aa2016-01-12 12:55:09 +01002219Node* LoadKlassNode::Identity(PhaseGVN* phase) {
Vladimir Kozlov76035422008-05-21 13:46:23 -07002220 return klass_identity_common(phase);
2221}
2222
Tobias Hartmann69b52aa2016-01-12 12:55:09 +01002223Node* LoadNode::klass_identity_common(PhaseGVN* phase) {
J. Duke81537792007-12-01 00:00:00 +00002224 Node* x = LoadNode::Identity(phase);
2225 if (x != this) return x;
2226
2227 // Take apart the address into an oop and and offset.
2228 // Return 'this' if we cannot.
2229 Node* adr = in(MemNode::Address);
2230 intptr_t offset = 0;
2231 Node* base = AddPNode::Ideal_base_and_offset(adr, phase, offset);
2232 if (base == NULL) return this;
2233 const TypeOopPtr* toop = phase->type(adr)->isa_oopptr();
2234 if (toop == NULL) return this;
2235
2236 // We can fetch the klass directly through an AllocateNode.
2237 // This works even if the klass is not constant (clone or newArray).
2238 if (offset == oopDesc::klass_offset_in_bytes()) {
2239 Node* allocated_klass = AllocateNode::Ideal_klass(base, phase);
2240 if (allocated_klass != NULL) {
2241 return allocated_klass;
2242 }
2243 }
2244
Jon Masamitsu5c58d272012-09-01 13:25:18 -04002245 // Simplify k.java_mirror.as_klass to plain k, where k is a Klass*.
J. Duke81537792007-12-01 00:00:00 +00002246 // See inline_native_Class_query for occurrences of these patterns.
2247 // Java Example: x.getClass().isAssignableFrom(y)
J. Duke81537792007-12-01 00:00:00 +00002248 //
2249 // This improves reflective code, often making the Class
2250 // mirror go completely dead. (Current exception: Class
2251 // mirrors may appear in debug info, but we could clean them out by
Jon Masamitsu5c58d272012-09-01 13:25:18 -04002252 // introducing a new debug info operator for Klass*.java_mirror).
J. Duke81537792007-12-01 00:00:00 +00002253 if (toop->isa_instptr() && toop->klass() == phase->C->env()->Class_klass()
Coleen Phillimore73d759e2014-08-28 11:29:09 -04002254 && offset == java_lang_Class::klass_offset_in_bytes()) {
J. Duke81537792007-12-01 00:00:00 +00002255 // We are loading a special hidden field from a Class mirror,
Coleen Phillimore28047d62012-09-29 06:40:00 -04002256 // the field which points to its Klass or ArrayKlass metaobject.
J. Duke81537792007-12-01 00:00:00 +00002257 if (base->is_Load()) {
2258 Node* adr2 = base->in(MemNode::Address);
2259 const TypeKlassPtr* tkls = phase->type(adr2)->isa_klassptr();
2260 if (tkls != NULL && !tkls->empty()
2261 && (tkls->klass()->is_instance_klass() ||
2262 tkls->klass()->is_array_klass())
2263 && adr2->is_AddP()
2264 ) {
Stefan Karlssone057d602011-12-07 11:35:03 +01002265 int mirror_field = in_bytes(Klass::java_mirror_offset());
Stefan Karlssone057d602011-12-07 11:35:03 +01002266 if (tkls->offset() == mirror_field) {
J. Duke81537792007-12-01 00:00:00 +00002267 return adr2->in(AddPNode::Base);
2268 }
2269 }
2270 }
2271 }
2272
2273 return this;
2274}
2275
Vladimir Kozlov76035422008-05-21 13:46:23 -07002276
2277//------------------------------Value------------------------------------------
Tobias Hartmann69b52aa2016-01-12 12:55:09 +01002278const Type* LoadNKlassNode::Value(PhaseGVN* phase) const {
Vladimir Kozlov76035422008-05-21 13:46:23 -07002279 const Type *t = klass_value_common(phase);
Vladimir Kozlova671e7c2008-06-24 10:43:29 -07002280 if (t == Type::TOP)
2281 return t;
Vladimir Kozlov76035422008-05-21 13:46:23 -07002282
Roland Westrelin61eb5a02012-10-09 10:11:38 +02002283 return t->make_narrowklass();
Vladimir Kozlov76035422008-05-21 13:46:23 -07002284}
2285
2286//------------------------------Identity---------------------------------------
2287// To clean up reflective code, simplify k.java_mirror.as_klass to narrow k.
2288// Also feed through the klass in Allocate(...klass...)._klass.
Tobias Hartmann69b52aa2016-01-12 12:55:09 +01002289Node* LoadNKlassNode::Identity(PhaseGVN* phase) {
Vladimir Kozlov76035422008-05-21 13:46:23 -07002290 Node *x = klass_identity_common(phase);
2291
2292 const Type *t = phase->type( x );
2293 if( t == Type::TOP ) return x;
Roland Westrelin61eb5a02012-10-09 10:11:38 +02002294 if( t->isa_narrowklass()) return x;
2295 assert (!t->isa_narrowoop(), "no narrow oop here");
Vladimir Kozlov76035422008-05-21 13:46:23 -07002296
Tobias Hartmann2a0815a2014-06-02 08:07:29 +02002297 return phase->transform(new EncodePKlassNode(x, t->make_narrowklass()));
Vladimir Kozlov76035422008-05-21 13:46:23 -07002298}
2299
J. Duke81537792007-12-01 00:00:00 +00002300//------------------------------Value-----------------------------------------
Tobias Hartmann69b52aa2016-01-12 12:55:09 +01002301const Type* LoadRangeNode::Value(PhaseGVN* phase) const {
J. Duke81537792007-12-01 00:00:00 +00002302 // Either input is TOP ==> the result is TOP
2303 const Type *t1 = phase->type( in(MemNode::Memory) );
2304 if( t1 == Type::TOP ) return Type::TOP;
2305 Node *adr = in(MemNode::Address);
2306 const Type *t2 = phase->type( adr );
2307 if( t2 == Type::TOP ) return Type::TOP;
2308 const TypePtr *tp = t2->is_ptr();
2309 if (TypePtr::above_centerline(tp->ptr())) return Type::TOP;
2310 const TypeAryPtr *tap = tp->isa_aryptr();
2311 if( !tap ) return _type;
2312 return tap->size();
2313}
2314
Chuck Rasboldeee15b12008-09-17 08:29:17 -07002315//-------------------------------Ideal---------------------------------------
2316// Feed through the length in AllocateArray(...length...)._length.
2317Node *LoadRangeNode::Ideal(PhaseGVN *phase, bool can_reshape) {
2318 Node* p = MemNode::Ideal_common(phase, can_reshape);
2319 if (p) return (p == NodeSentinel) ? NULL : p;
2320
2321 // Take apart the address into an oop and and offset.
2322 // Return 'this' if we cannot.
2323 Node* adr = in(MemNode::Address);
2324 intptr_t offset = 0;
2325 Node* base = AddPNode::Ideal_base_and_offset(adr, phase, offset);
2326 if (base == NULL) return NULL;
2327 const TypeAryPtr* tary = phase->type(adr)->isa_aryptr();
2328 if (tary == NULL) return NULL;
2329
2330 // We can fetch the length directly through an AllocateArrayNode.
2331 // This works even if the length is not constant (clone or newArray).
2332 if (offset == arrayOopDesc::length_offset_in_bytes()) {
2333 AllocateArrayNode* alloc = AllocateArrayNode::Ideal_array_allocation(base, phase);
2334 if (alloc != NULL) {
2335 Node* allocated_length = alloc->Ideal_length();
2336 Node* len = alloc->make_ideal_length(tary, phase);
2337 if (allocated_length != len) {
2338 // New CastII improves on this.
2339 return len;
2340 }
2341 }
2342 }
2343
2344 return NULL;
2345}
2346
J. Duke81537792007-12-01 00:00:00 +00002347//------------------------------Identity---------------------------------------
2348// Feed through the length in AllocateArray(...length...)._length.
Tobias Hartmann69b52aa2016-01-12 12:55:09 +01002349Node* LoadRangeNode::Identity(PhaseGVN* phase) {
J. Duke81537792007-12-01 00:00:00 +00002350 Node* x = LoadINode::Identity(phase);
2351 if (x != this) return x;
2352
2353 // Take apart the address into an oop and and offset.
2354 // Return 'this' if we cannot.
2355 Node* adr = in(MemNode::Address);
2356 intptr_t offset = 0;
2357 Node* base = AddPNode::Ideal_base_and_offset(adr, phase, offset);
2358 if (base == NULL) return this;
2359 const TypeAryPtr* tary = phase->type(adr)->isa_aryptr();
2360 if (tary == NULL) return this;
2361
2362 // We can fetch the length directly through an AllocateArrayNode.
2363 // This works even if the length is not constant (clone or newArray).
2364 if (offset == arrayOopDesc::length_offset_in_bytes()) {
Chuck Rasboldeee15b12008-09-17 08:29:17 -07002365 AllocateArrayNode* alloc = AllocateArrayNode::Ideal_array_allocation(base, phase);
2366 if (alloc != NULL) {
2367 Node* allocated_length = alloc->Ideal_length();
2368 // Do not allow make_ideal_length to allocate a CastII node.
2369 Node* len = alloc->make_ideal_length(tary, phase, false);
2370 if (allocated_length == len) {
2371 // Return allocated_length only if it would not be improved by a CastII.
2372 return allocated_length;
2373 }
J. Duke81537792007-12-01 00:00:00 +00002374 }
2375 }
2376
2377 return this;
2378
2379}
Chuck Rasboldeee15b12008-09-17 08:29:17 -07002380
J. Duke81537792007-12-01 00:00:00 +00002381//=============================================================================
2382//---------------------------StoreNode::make-----------------------------------
2383// Polymorphic factory method:
Goetz Lindenmaier13b13f52013-11-15 11:05:32 -08002384StoreNode* StoreNode::make(PhaseGVN& gvn, Node* ctl, Node* mem, Node* adr, const TypePtr* adr_type, Node* val, BasicType bt, MemOrd mo) {
2385 assert((mo == unordered || mo == release), "unexpected");
Coleen Phillimore4a831d42008-04-13 17:43:42 -04002386 Compile* C = gvn.C;
Goetz Lindenmaier13b13f52013-11-15 11:05:32 -08002387 assert(C->get_alias_index(adr_type) != Compile::AliasIdxRaw ||
2388 ctl != NULL, "raw memory operations should have control edge");
Coleen Phillimore4a831d42008-04-13 17:43:42 -04002389
J. Duke81537792007-12-01 00:00:00 +00002390 switch (bt) {
2391 case T_BOOLEAN:
Tobias Hartmann2a0815a2014-06-02 08:07:29 +02002392 case T_BYTE: return new StoreBNode(ctl, mem, adr, adr_type, val, mo);
2393 case T_INT: return new StoreINode(ctl, mem, adr, adr_type, val, mo);
J. Duke81537792007-12-01 00:00:00 +00002394 case T_CHAR:
Tobias Hartmann2a0815a2014-06-02 08:07:29 +02002395 case T_SHORT: return new StoreCNode(ctl, mem, adr, adr_type, val, mo);
2396 case T_LONG: return new StoreLNode(ctl, mem, adr, adr_type, val, mo);
2397 case T_FLOAT: return new StoreFNode(ctl, mem, adr, adr_type, val, mo);
2398 case T_DOUBLE: return new StoreDNode(ctl, mem, adr, adr_type, val, mo);
Jon Masamitsu5c58d272012-09-01 13:25:18 -04002399 case T_METADATA:
J. Duke81537792007-12-01 00:00:00 +00002400 case T_ADDRESS:
Coleen Phillimore4a831d42008-04-13 17:43:42 -04002401 case T_OBJECT:
2402#ifdef _LP64
Roland Westrelin61eb5a02012-10-09 10:11:38 +02002403 if (adr->bottom_type()->is_ptr_to_narrowoop()) {
Tobias Hartmann2a0815a2014-06-02 08:07:29 +02002404 val = gvn.transform(new EncodePNode(val, val->bottom_type()->make_narrowoop()));
2405 return new StoreNNode(ctl, mem, adr, adr_type, val, mo);
Roland Westrelin61eb5a02012-10-09 10:11:38 +02002406 } else if (adr->bottom_type()->is_ptr_to_narrowklass() ||
Erik Helin30f059b2013-08-12 17:37:02 +02002407 (UseCompressedClassPointers && val->bottom_type()->isa_klassptr() &&
Roland Westrelin61eb5a02012-10-09 10:11:38 +02002408 adr->bottom_type()->isa_rawptr())) {
Tobias Hartmann2a0815a2014-06-02 08:07:29 +02002409 val = gvn.transform(new EncodePKlassNode(val, val->bottom_type()->make_narrowklass()));
2410 return new StoreNKlassNode(ctl, mem, adr, adr_type, val, mo);
Roland Westrelin61eb5a02012-10-09 10:11:38 +02002411 }
Coleen Phillimore4a831d42008-04-13 17:43:42 -04002412#endif
Vladimir Kozlova671e7c2008-06-24 10:43:29 -07002413 {
Tobias Hartmann2a0815a2014-06-02 08:07:29 +02002414 return new StorePNode(ctl, mem, adr, adr_type, val, mo);
Vladimir Kozlova671e7c2008-06-24 10:43:29 -07002415 }
J. Duke81537792007-12-01 00:00:00 +00002416 }
2417 ShouldNotReachHere();
2418 return (StoreNode*)NULL;
2419}
2420
Tobias Hartmann70a55ea2014-08-05 09:58:52 +02002421StoreLNode* StoreLNode::make_atomic(Node* ctl, Node* mem, Node* adr, const TypePtr* adr_type, Node* val, MemOrd mo) {
J. Duke81537792007-12-01 00:00:00 +00002422 bool require_atomic = true;
Tobias Hartmann2a0815a2014-06-02 08:07:29 +02002423 return new StoreLNode(ctl, mem, adr, adr_type, val, mo, require_atomic);
J. Duke81537792007-12-01 00:00:00 +00002424}
2425
Tobias Hartmann70a55ea2014-08-05 09:58:52 +02002426StoreDNode* StoreDNode::make_atomic(Node* ctl, Node* mem, Node* adr, const TypePtr* adr_type, Node* val, MemOrd mo) {
Tobias Hartmann85296fe2014-05-06 09:17:57 +02002427 bool require_atomic = true;
Tobias Hartmann2a0815a2014-06-02 08:07:29 +02002428 return new StoreDNode(ctl, mem, adr, adr_type, val, mo, require_atomic);
Tobias Hartmann85296fe2014-05-06 09:17:57 +02002429}
2430
J. Duke81537792007-12-01 00:00:00 +00002431
2432//--------------------------bottom_type----------------------------------------
2433const Type *StoreNode::bottom_type() const {
2434 return Type::MEMORY;
2435}
2436
2437//------------------------------hash-------------------------------------------
2438uint StoreNode::hash() const {
2439 // unroll addition of interesting fields
2440 //return (uintptr_t)in(Control) + (uintptr_t)in(Memory) + (uintptr_t)in(Address) + (uintptr_t)in(ValueIn);
2441
2442 // Since they are not commoned, do not hash them:
2443 return NO_HASH;
2444}
2445
2446//------------------------------Ideal------------------------------------------
2447// Change back-to-back Store(, p, x) -> Store(m, p, y) to Store(m, p, x).
2448// When a store immediately follows a relevant allocation/initialization,
2449// try to capture it into the initialization, or hoist it above.
2450Node *StoreNode::Ideal(PhaseGVN *phase, bool can_reshape) {
2451 Node* p = MemNode::Ideal_common(phase, can_reshape);
2452 if (p) return (p == NodeSentinel) ? NULL : p;
2453
2454 Node* mem = in(MemNode::Memory);
2455 Node* address = in(MemNode::Address);
Tom Rodriguezaac46472011-04-05 19:14:03 -07002456 // Back-to-back stores to same address? Fold em up. Generally
2457 // unsafe if I have intervening uses... Also disallowed for StoreCM
2458 // since they must follow each StoreP operation. Redundant StoreCMs
2459 // are eliminated just before matching in final_graph_reshape.
Roland Westrelin96b004c2015-07-29 17:25:04 +02002460 {
2461 Node* st = mem;
2462 // If Store 'st' has more than one use, we cannot fold 'st' away.
2463 // For example, 'st' might be the final state at a conditional
2464 // return. Or, 'st' might be used by some node which is live at
2465 // the same time 'st' is live, which might be unschedulable. So,
2466 // require exactly ONE user until such time as we clone 'mem' for
2467 // each of 'mem's uses (thus making the exactly-1-user-rule hold
2468 // true).
2469 while (st->is_Store() && st->outcnt() == 1 && st->Opcode() != Op_StoreCM) {
2470 // Looking at a dead closed cycle of memory?
2471 assert(st != st->in(MemNode::Memory), "dead loop in StoreNode::Ideal");
2472 assert(Opcode() == st->Opcode() ||
2473 st->Opcode() == Op_StoreVector ||
2474 Opcode() == Op_StoreVector ||
2475 phase->C->get_alias_index(adr_type()) == Compile::AliasIdxRaw ||
Roland Westrelin45b3ce82015-10-28 10:20:33 +01002476 (Opcode() == Op_StoreL && st->Opcode() == Op_StoreI) || // expanded ClearArrayNode
2477 (is_mismatched_access() || st->as_Store()->is_mismatched_access()),
David Lindholm1e71f672015-09-29 11:02:08 +02002478 "no mismatched stores, except on raw memory: %s %s", NodeClassNames[Opcode()], NodeClassNames[st->Opcode()]);
J. Duke81537792007-12-01 00:00:00 +00002479
Roland Westrelin96b004c2015-07-29 17:25:04 +02002480 if (st->in(MemNode::Address)->eqv_uncast(address) &&
2481 st->as_Store()->memory_size() <= this->memory_size()) {
2482 Node* use = st->raw_out(0);
2483 phase->igvn_rehash_node_delayed(use);
2484 if (can_reshape) {
2485 use->set_req_X(MemNode::Memory, st->in(MemNode::Memory), phase->is_IterGVN());
2486 } else {
2487 // It's OK to do this in the parser, since DU info is always accurate,
2488 // and the parser always refers to nodes via SafePointNode maps.
2489 use->set_req(MemNode::Memory, st->in(MemNode::Memory));
2490 }
2491 return this;
J. Duke81537792007-12-01 00:00:00 +00002492 }
Roland Westrelin96b004c2015-07-29 17:25:04 +02002493 st = st->in(MemNode::Memory);
J. Duke81537792007-12-01 00:00:00 +00002494 }
2495 }
2496
Roland Westrelin96b004c2015-07-29 17:25:04 +02002497
J. Duke81537792007-12-01 00:00:00 +00002498 // Capture an unaliased, unconditional, simple store into an initializer.
2499 // Or, if it is independent of the allocation, hoist it above the allocation.
2500 if (ReduceFieldZeroing && /*can_reshape &&*/
2501 mem->is_Proj() && mem->in(0)->is_Initialize()) {
2502 InitializeNode* init = mem->in(0)->as_Initialize();
Roland Westrelinfe928622013-02-25 14:13:04 +01002503 intptr_t offset = init->can_capture_store(this, phase, can_reshape);
J. Duke81537792007-12-01 00:00:00 +00002504 if (offset > 0) {
Roland Westrelinfe928622013-02-25 14:13:04 +01002505 Node* moved = init->capture_store(this, offset, phase, can_reshape);
J. Duke81537792007-12-01 00:00:00 +00002506 // If the InitializeNode captured me, it made a raw copy of me,
2507 // and I need to disappear.
2508 if (moved != NULL) {
2509 // %%% hack to ensure that Ideal returns a new node:
Tobias Hartmann70a55ea2014-08-05 09:58:52 +02002510 mem = MergeMemNode::make(mem);
J. Duke81537792007-12-01 00:00:00 +00002511 return mem; // fold me away
2512 }
2513 }
2514 }
2515
2516 return NULL; // No further progress
2517}
2518
2519//------------------------------Value-----------------------------------------
Tobias Hartmann69b52aa2016-01-12 12:55:09 +01002520const Type* StoreNode::Value(PhaseGVN* phase) const {
J. Duke81537792007-12-01 00:00:00 +00002521 // Either input is TOP ==> the result is TOP
2522 const Type *t1 = phase->type( in(MemNode::Memory) );
2523 if( t1 == Type::TOP ) return Type::TOP;
2524 const Type *t2 = phase->type( in(MemNode::Address) );
2525 if( t2 == Type::TOP ) return Type::TOP;
2526 const Type *t3 = phase->type( in(MemNode::ValueIn) );
2527 if( t3 == Type::TOP ) return Type::TOP;
2528 return Type::MEMORY;
2529}
2530
2531//------------------------------Identity---------------------------------------
2532// Remove redundant stores:
2533// Store(m, p, Load(m, p)) changes to m.
2534// Store(, p, x) -> Store(m, p, x) changes to Store(m, p, x).
Tobias Hartmann69b52aa2016-01-12 12:55:09 +01002535Node* StoreNode::Identity(PhaseGVN* phase) {
J. Duke81537792007-12-01 00:00:00 +00002536 Node* mem = in(MemNode::Memory);
2537 Node* adr = in(MemNode::Address);
2538 Node* val = in(MemNode::ValueIn);
2539
2540 // Load then Store? Then the Store is useless
2541 if (val->is_Load() &&
Vladimir Kozlov791afc42012-01-10 18:05:38 -08002542 val->in(MemNode::Address)->eqv_uncast(adr) &&
2543 val->in(MemNode::Memory )->eqv_uncast(mem) &&
J. Duke81537792007-12-01 00:00:00 +00002544 val->as_Load()->store_Opcode() == Opcode()) {
2545 return mem;
2546 }
2547
2548 // Two stores in a row of the same value?
2549 if (mem->is_Store() &&
Vladimir Kozlov791afc42012-01-10 18:05:38 -08002550 mem->in(MemNode::Address)->eqv_uncast(adr) &&
2551 mem->in(MemNode::ValueIn)->eqv_uncast(val) &&
J. Duke81537792007-12-01 00:00:00 +00002552 mem->Opcode() == Opcode()) {
2553 return mem;
2554 }
2555
2556 // Store of zero anywhere into a freshly-allocated object?
2557 // Then the store is useless.
2558 // (It must already have been captured by the InitializeNode.)
2559 if (ReduceFieldZeroing && phase->type(val)->is_zero_type()) {
2560 // a newly allocated object is already all-zeroes everywhere
2561 if (mem->is_Proj() && mem->in(0)->is_Allocate()) {
2562 return mem;
2563 }
2564
2565 // the store may also apply to zero-bits in an earlier object
2566 Node* prev_mem = find_previous_store(phase);
2567 // Steps (a), (b): Walk past independent stores to find an exact match.
2568 if (prev_mem != NULL) {
2569 Node* prev_val = can_see_stored_value(prev_mem, phase);
2570 if (prev_val != NULL && phase->eqv(prev_val, val)) {
2571 // prev_val and val might differ by a cast; it would be good
2572 // to keep the more informative of the two.
2573 return mem;
2574 }
2575 }
2576 }
2577
2578 return this;
2579}
2580
2581//------------------------------match_edge-------------------------------------
2582// Do we Match on this edge index or not? Match only memory & value
2583uint StoreNode::match_edge(uint idx) const {
2584 return idx == MemNode::Address || idx == MemNode::ValueIn;
2585}
2586
2587//------------------------------cmp--------------------------------------------
2588// Do not common stores up together. They generally have to be split
2589// back up anyways, so do not bother.
2590uint StoreNode::cmp( const Node &n ) const {
2591 return (&n == this); // Always fail except on self
2592}
2593
2594//------------------------------Ideal_masked_input-----------------------------
2595// Check for a useless mask before a partial-word store
2596// (StoreB ... (AndI valIn conIa) )
2597// If (conIa & mask == mask) this simplifies to
2598// (StoreB ... (valIn) )
2599Node *StoreNode::Ideal_masked_input(PhaseGVN *phase, uint mask) {
2600 Node *val = in(MemNode::ValueIn);
2601 if( val->Opcode() == Op_AndI ) {
2602 const TypeInt *t = phase->type( val->in(2) )->isa_int();
2603 if( t && t->is_con() && (t->get_con() & mask) == mask ) {
2604 set_req(MemNode::ValueIn, val->in(1));
2605 return this;
2606 }
2607 }
2608 return NULL;
2609}
2610
2611
2612//------------------------------Ideal_sign_extended_input----------------------
2613// Check for useless sign-extension before a partial-word store
2614// (StoreB ... (RShiftI _ (LShiftI _ valIn conIL ) conIR) )
2615// If (conIL == conIR && conIR <= num_bits) this simplifies to
2616// (StoreB ... (valIn) )
2617Node *StoreNode::Ideal_sign_extended_input(PhaseGVN *phase, int num_bits) {
2618 Node *val = in(MemNode::ValueIn);
2619 if( val->Opcode() == Op_RShiftI ) {
2620 const TypeInt *t = phase->type( val->in(2) )->isa_int();
2621 if( t && t->is_con() && (t->get_con() <= num_bits) ) {
2622 Node *shl = val->in(1);
2623 if( shl->Opcode() == Op_LShiftI ) {
2624 const TypeInt *t2 = phase->type( shl->in(2) )->isa_int();
2625 if( t2 && t2->is_con() && (t2->get_con() == t->get_con()) ) {
2626 set_req(MemNode::ValueIn, shl->in(1));
2627 return this;
2628 }
2629 }
2630 }
2631 }
2632 return NULL;
2633}
2634
2635//------------------------------value_never_loaded-----------------------------------
2636// Determine whether there are any possible loads of the value stored.
2637// For simplicity, we actually check if there are any loads from the
2638// address stored to, not just for loads of the value stored by this node.
2639//
2640bool StoreNode::value_never_loaded( PhaseTransform *phase) const {
2641 Node *adr = in(Address);
2642 const TypeOopPtr *adr_oop = phase->type(adr)->isa_oopptr();
2643 if (adr_oop == NULL)
2644 return false;
Vladimir Kozlov4213e622008-06-26 13:34:00 -07002645 if (!adr_oop->is_known_instance_field())
J. Duke81537792007-12-01 00:00:00 +00002646 return false; // if not a distinct instance, there may be aliases of the address
2647 for (DUIterator_Fast imax, i = adr->fast_outs(imax); i < imax; i++) {
2648 Node *use = adr->fast_out(i);
J. Duke81537792007-12-01 00:00:00 +00002649 if (use->is_Load() || use->is_LoadStore()) {
2650 return false;
2651 }
2652 }
2653 return true;
2654}
2655
2656//=============================================================================
2657//------------------------------Ideal------------------------------------------
2658// If the store is from an AND mask that leaves the low bits untouched, then
2659// we can skip the AND operation. If the store is from a sign-extension
2660// (a left shift, then right shift) we can skip both.
2661Node *StoreBNode::Ideal(PhaseGVN *phase, bool can_reshape){
2662 Node *progress = StoreNode::Ideal_masked_input(phase, 0xFF);
2663 if( progress != NULL ) return progress;
2664
2665 progress = StoreNode::Ideal_sign_extended_input(phase, 24);
2666 if( progress != NULL ) return progress;
2667
2668 // Finally check the default case
2669 return StoreNode::Ideal(phase, can_reshape);
2670}
2671
2672//=============================================================================
2673//------------------------------Ideal------------------------------------------
2674// If the store is from an AND mask that leaves the low bits untouched, then
2675// we can skip the AND operation
2676Node *StoreCNode::Ideal(PhaseGVN *phase, bool can_reshape){
2677 Node *progress = StoreNode::Ideal_masked_input(phase, 0xFFFF);
2678 if( progress != NULL ) return progress;
2679
2680 progress = StoreNode::Ideal_sign_extended_input(phase, 16);
2681 if( progress != NULL ) return progress;
2682
2683 // Finally check the default case
2684 return StoreNode::Ideal(phase, can_reshape);
2685}
2686
2687//=============================================================================
2688//------------------------------Identity---------------------------------------
Tobias Hartmann69b52aa2016-01-12 12:55:09 +01002689Node* StoreCMNode::Identity(PhaseGVN* phase) {
J. Duke81537792007-12-01 00:00:00 +00002690 // No need to card mark when storing a null ptr
2691 Node* my_store = in(MemNode::OopStore);
2692 if (my_store->is_Store()) {
2693 const Type *t1 = phase->type( my_store->in(MemNode::ValueIn) );
2694 if( t1 == TypePtr::NULL_PTR ) {
2695 return in(MemNode::Memory);
2696 }
2697 }
2698 return this;
2699}
2700
Changpeng Fangc492f4c2009-09-14 09:49:54 -07002701//=============================================================================
2702//------------------------------Ideal---------------------------------------
2703Node *StoreCMNode::Ideal(PhaseGVN *phase, bool can_reshape){
2704 Node* progress = StoreNode::Ideal(phase, can_reshape);
2705 if (progress != NULL) return progress;
2706
2707 Node* my_store = in(MemNode::OopStore);
2708 if (my_store->is_MergeMem()) {
2709 Node* mem = my_store->as_MergeMem()->memory_at(oop_alias_idx());
2710 set_req(MemNode::OopStore, mem);
2711 return this;
2712 }
2713
2714 return NULL;
2715}
2716
J. Duke81537792007-12-01 00:00:00 +00002717//------------------------------Value-----------------------------------------
Tobias Hartmann69b52aa2016-01-12 12:55:09 +01002718const Type* StoreCMNode::Value(PhaseGVN* phase) const {
Vladimir Kozlov50708122008-03-11 11:04:40 -07002719 // Either input is TOP ==> the result is TOP
2720 const Type *t = phase->type( in(MemNode::Memory) );
2721 if( t == Type::TOP ) return Type::TOP;
2722 t = phase->type( in(MemNode::Address) );
2723 if( t == Type::TOP ) return Type::TOP;
2724 t = phase->type( in(MemNode::ValueIn) );
2725 if( t == Type::TOP ) return Type::TOP;
J. Duke81537792007-12-01 00:00:00 +00002726 // If extra input is TOP ==> the result is TOP
Vladimir Kozlov50708122008-03-11 11:04:40 -07002727 t = phase->type( in(MemNode::OopStore) );
2728 if( t == Type::TOP ) return Type::TOP;
J. Duke81537792007-12-01 00:00:00 +00002729
2730 return StoreNode::Value( phase );
2731}
2732
2733
2734//=============================================================================
2735//----------------------------------SCMemProjNode------------------------------
Tobias Hartmann69b52aa2016-01-12 12:55:09 +01002736const Type* SCMemProjNode::Value(PhaseGVN* phase) const
J. Duke81537792007-12-01 00:00:00 +00002737{
2738 return bottom_type();
2739}
2740
2741//=============================================================================
Roland Westrelin30254062012-09-20 16:49:17 +02002742//----------------------------------LoadStoreNode------------------------------
2743LoadStoreNode::LoadStoreNode( Node *c, Node *mem, Node *adr, Node *val, const TypePtr* at, const Type* rt, uint required )
2744 : Node(required),
2745 _type(rt),
2746 _adr_type(at)
2747{
J. Duke81537792007-12-01 00:00:00 +00002748 init_req(MemNode::Control, c );
2749 init_req(MemNode::Memory , mem);
2750 init_req(MemNode::Address, adr);
2751 init_req(MemNode::ValueIn, val);
J. Duke81537792007-12-01 00:00:00 +00002752 init_class_id(Class_LoadStore);
Roland Westrelin30254062012-09-20 16:49:17 +02002753}
J. Duke81537792007-12-01 00:00:00 +00002754
Roland Westrelin30254062012-09-20 16:49:17 +02002755uint LoadStoreNode::ideal_reg() const {
2756 return _type->ideal_reg();
2757}
2758
2759bool LoadStoreNode::result_not_used() const {
2760 for( DUIterator_Fast imax, i = fast_outs(imax); i < imax; i++ ) {
2761 Node *x = fast_out(i);
2762 if (x->Opcode() == Op_SCMemProj) continue;
2763 return false;
2764 }
2765 return true;
2766}
2767
2768uint LoadStoreNode::size_of() const { return sizeof(*this); }
2769
2770//=============================================================================
2771//----------------------------------LoadStoreConditionalNode--------------------
2772LoadStoreConditionalNode::LoadStoreConditionalNode( Node *c, Node *mem, Node *adr, Node *val, Node *ex ) : LoadStoreNode(c, mem, adr, val, NULL, TypeInt::BOOL, 5) {
2773 init_req(ExpectedIn, ex );
J. Duke81537792007-12-01 00:00:00 +00002774}
2775
2776//=============================================================================
2777//-------------------------------adr_type--------------------------------------
J. Duke81537792007-12-01 00:00:00 +00002778const TypePtr* ClearArrayNode::adr_type() const {
2779 Node *adr = in(3);
Vladimir Ivanovf3d90962014-11-17 14:02:45 -08002780 if (adr == NULL) return NULL; // node is dead
J. Duke81537792007-12-01 00:00:00 +00002781 return MemNode::calculate_adr_type(adr->bottom_type());
2782}
2783
2784//------------------------------match_edge-------------------------------------
2785// Do we Match on this edge index or not? Do not match memory
2786uint ClearArrayNode::match_edge(uint idx) const {
2787 return idx > 1;
2788}
2789
2790//------------------------------Identity---------------------------------------
2791// Clearing a zero length array does nothing
Tobias Hartmann69b52aa2016-01-12 12:55:09 +01002792Node* ClearArrayNode::Identity(PhaseGVN* phase) {
Tom Rodriguez8e1624d2008-03-18 23:44:46 -07002793 return phase->type(in(2))->higher_equal(TypeX::ZERO) ? in(1) : this;
J. Duke81537792007-12-01 00:00:00 +00002794}
2795
2796//------------------------------Idealize---------------------------------------
2797// Clearing a short array is faster with stores
2798Node *ClearArrayNode::Ideal(PhaseGVN *phase, bool can_reshape){
Aleksey Shipilev103aff32016-03-04 01:30:11 +03002799 // Already know this is a large node, do not try to ideal it
2800 if (_is_large) return NULL;
2801
J. Duke81537792007-12-01 00:00:00 +00002802 const int unit = BytesPerLong;
2803 const TypeX* t = phase->type(in(2))->isa_intptr_t();
2804 if (!t) return NULL;
2805 if (!t->is_con()) return NULL;
2806 intptr_t raw_count = t->get_con();
2807 intptr_t size = raw_count;
2808 if (!Matcher::init_array_count_is_in_bytes) size *= unit;
2809 // Clearing nothing uses the Identity call.
2810 // Negative clears are possible on dead ClearArrays
2811 // (see jck test stmt114.stmt11402.val).
2812 if (size <= 0 || size % unit != 0) return NULL;
2813 intptr_t count = size / unit;
Aleksey Shipilev103aff32016-03-04 01:30:11 +03002814 // Length too long; communicate this to matchers and assemblers.
2815 // Assemblers are responsible to produce fast hardware clears for it.
2816 if (size > InitArrayShortSize) {
2817 return new ClearArrayNode(in(0), in(1), in(2), in(3), true);
2818 }
J. Duke81537792007-12-01 00:00:00 +00002819 Node *mem = in(1);
2820 if( phase->type(mem)==Type::TOP ) return NULL;
2821 Node *adr = in(3);
2822 const Type* at = phase->type(adr);
2823 if( at==Type::TOP ) return NULL;
2824 const TypePtr* atp = at->isa_ptr();
2825 // adjust atp to be the correct array element address type
2826 if (atp == NULL) atp = TypePtr::BOTTOM;
2827 else atp = atp->add_offset(Type::OffsetBot);
2828 // Get base for derived pointer purposes
2829 if( adr->Opcode() != Op_AddP ) Unimplemented();
2830 Node *base = adr->in(1);
2831
2832 Node *zero = phase->makecon(TypeLong::ZERO);
2833 Node *off = phase->MakeConX(BytesPerLong);
Tobias Hartmann2a0815a2014-06-02 08:07:29 +02002834 mem = new StoreLNode(in(0),mem,adr,atp,zero,MemNode::unordered,false);
J. Duke81537792007-12-01 00:00:00 +00002835 count--;
2836 while( count-- ) {
2837 mem = phase->transform(mem);
Tobias Hartmann2a0815a2014-06-02 08:07:29 +02002838 adr = phase->transform(new AddPNode(base,adr,off));
2839 mem = new StoreLNode(in(0),mem,adr,atp,zero,MemNode::unordered,false);
J. Duke81537792007-12-01 00:00:00 +00002840 }
2841 return mem;
2842}
2843
Vladimir Kozlov9f5ca022009-12-09 16:40:45 -08002844//----------------------------step_through----------------------------------
2845// Return allocation input memory edge if it is different instance
2846// or itself if it is the one we are looking for.
2847bool ClearArrayNode::step_through(Node** np, uint instance_id, PhaseTransform* phase) {
2848 Node* n = *np;
2849 assert(n->is_ClearArray(), "sanity");
2850 intptr_t offset;
2851 AllocateNode* alloc = AllocateNode::Ideal_allocation(n->in(3), phase, offset);
Roland Westrelinfa270002014-08-29 16:32:29 +02002852 // This method is called only before Allocate nodes are expanded
2853 // during macro nodes expansion. Before that ClearArray nodes are
2854 // only generated in PhaseMacroExpand::generate_arraycopy() (before
2855 // Allocate nodes are expanded) which follows allocations.
Vladimir Kozlov9f5ca022009-12-09 16:40:45 -08002856 assert(alloc != NULL, "should have allocation");
2857 if (alloc->_idx == instance_id) {
2858 // Can not bypass initialization of the instance we are looking for.
2859 return false;
2860 }
2861 // Otherwise skip it.
2862 InitializeNode* init = alloc->initialization();
2863 if (init != NULL)
2864 *np = init->in(TypeFunc::Memory);
2865 else
2866 *np = alloc->in(TypeFunc::Memory);
2867 return true;
2868}
2869
J. Duke81537792007-12-01 00:00:00 +00002870//----------------------------clear_memory-------------------------------------
2871// Generate code to initialize object storage to zero.
2872Node* ClearArrayNode::clear_memory(Node* ctl, Node* mem, Node* dest,
2873 intptr_t start_offset,
2874 Node* end_offset,
2875 PhaseGVN* phase) {
J. Duke81537792007-12-01 00:00:00 +00002876 intptr_t offset = start_offset;
2877
2878 int unit = BytesPerLong;
2879 if ((offset % unit) != 0) {
Tobias Hartmann2a0815a2014-06-02 08:07:29 +02002880 Node* adr = new AddPNode(dest, dest, phase->MakeConX(offset));
J. Duke81537792007-12-01 00:00:00 +00002881 adr = phase->transform(adr);
2882 const TypePtr* atp = TypeRawPtr::BOTTOM;
Goetz Lindenmaier13b13f52013-11-15 11:05:32 -08002883 mem = StoreNode::make(*phase, ctl, mem, adr, atp, phase->zerocon(T_INT), T_INT, MemNode::unordered);
J. Duke81537792007-12-01 00:00:00 +00002884 mem = phase->transform(mem);
2885 offset += BytesPerInt;
2886 }
2887 assert((offset % unit) == 0, "");
2888
2889 // Initialize the remaining stuff, if any, with a ClearArray.
2890 return clear_memory(ctl, mem, dest, phase->MakeConX(offset), end_offset, phase);
2891}
2892
2893Node* ClearArrayNode::clear_memory(Node* ctl, Node* mem, Node* dest,
2894 Node* start_offset,
2895 Node* end_offset,
2896 PhaseGVN* phase) {
Tom Rodriguez8e1624d2008-03-18 23:44:46 -07002897 if (start_offset == end_offset) {
2898 // nothing to do
2899 return mem;
2900 }
2901
J. Duke81537792007-12-01 00:00:00 +00002902 int unit = BytesPerLong;
2903 Node* zbase = start_offset;
2904 Node* zend = end_offset;
2905
2906 // Scale to the unit required by the CPU:
2907 if (!Matcher::init_array_count_is_in_bytes) {
2908 Node* shift = phase->intcon(exact_log2(unit));
Tobias Hartmann2a0815a2014-06-02 08:07:29 +02002909 zbase = phase->transform(new URShiftXNode(zbase, shift) );
2910 zend = phase->transform(new URShiftXNode(zend, shift) );
J. Duke81537792007-12-01 00:00:00 +00002911 }
2912
J. Duke81537792007-12-01 00:00:00 +00002913 // Bulk clear double-words
Tobias Hartmann2a0815a2014-06-02 08:07:29 +02002914 Node* zsize = phase->transform(new SubXNode(zend, zbase) );
2915 Node* adr = phase->transform(new AddPNode(dest, dest, start_offset) );
Aleksey Shipilev103aff32016-03-04 01:30:11 +03002916 mem = new ClearArrayNode(ctl, mem, zsize, adr, false);
J. Duke81537792007-12-01 00:00:00 +00002917 return phase->transform(mem);
2918}
2919
2920Node* ClearArrayNode::clear_memory(Node* ctl, Node* mem, Node* dest,
2921 intptr_t start_offset,
2922 intptr_t end_offset,
2923 PhaseGVN* phase) {
Tom Rodriguez8e1624d2008-03-18 23:44:46 -07002924 if (start_offset == end_offset) {
2925 // nothing to do
2926 return mem;
2927 }
2928
J. Duke81537792007-12-01 00:00:00 +00002929 assert((end_offset % BytesPerInt) == 0, "odd end offset");
2930 intptr_t done_offset = end_offset;
2931 if ((done_offset % BytesPerLong) != 0) {
2932 done_offset -= BytesPerInt;
2933 }
2934 if (done_offset > start_offset) {
2935 mem = clear_memory(ctl, mem, dest,
2936 start_offset, phase->MakeConX(done_offset), phase);
2937 }
2938 if (done_offset < end_offset) { // emit the final 32-bit store
Tobias Hartmann2a0815a2014-06-02 08:07:29 +02002939 Node* adr = new AddPNode(dest, dest, phase->MakeConX(done_offset));
J. Duke81537792007-12-01 00:00:00 +00002940 adr = phase->transform(adr);
2941 const TypePtr* atp = TypeRawPtr::BOTTOM;
Goetz Lindenmaier13b13f52013-11-15 11:05:32 -08002942 mem = StoreNode::make(*phase, ctl, mem, adr, atp, phase->zerocon(T_INT), T_INT, MemNode::unordered);
J. Duke81537792007-12-01 00:00:00 +00002943 mem = phase->transform(mem);
2944 done_offset += BytesPerInt;
2945 }
2946 assert(done_offset == end_offset, "");
2947 return mem;
2948}
2949
2950//=============================================================================
J. Duke81537792007-12-01 00:00:00 +00002951MemBarNode::MemBarNode(Compile* C, int alias_idx, Node* precedent)
2952 : MultiNode(TypeFunc::Parms + (precedent == NULL? 0: 1)),
2953 _adr_type(C->get_adr_type(alias_idx))
2954{
2955 init_class_id(Class_MemBar);
2956 Node* top = C->top();
2957 init_req(TypeFunc::I_O,top);
2958 init_req(TypeFunc::FramePtr,top);
2959 init_req(TypeFunc::ReturnAdr,top);
2960 if (precedent != NULL)
2961 init_req(TypeFunc::Parms, precedent);
2962}
2963
2964//------------------------------cmp--------------------------------------------
2965uint MemBarNode::hash() const { return NO_HASH; }
2966uint MemBarNode::cmp( const Node &n ) const {
2967 return (&n == this); // Always fail except on self
2968}
2969
2970//------------------------------make-------------------------------------------
2971MemBarNode* MemBarNode::make(Compile* C, int opcode, int atp, Node* pn) {
J. Duke81537792007-12-01 00:00:00 +00002972 switch (opcode) {
Tobias Hartmann2a0815a2014-06-02 08:07:29 +02002973 case Op_MemBarAcquire: return new MemBarAcquireNode(C, atp, pn);
2974 case Op_LoadFence: return new LoadFenceNode(C, atp, pn);
2975 case Op_MemBarRelease: return new MemBarReleaseNode(C, atp, pn);
2976 case Op_StoreFence: return new StoreFenceNode(C, atp, pn);
2977 case Op_MemBarAcquireLock: return new MemBarAcquireLockNode(C, atp, pn);
2978 case Op_MemBarReleaseLock: return new MemBarReleaseLockNode(C, atp, pn);
2979 case Op_MemBarVolatile: return new MemBarVolatileNode(C, atp, pn);
2980 case Op_MemBarCPUOrder: return new MemBarCPUOrderNode(C, atp, pn);
2981 case Op_Initialize: return new InitializeNode(C, atp, pn);
2982 case Op_MemBarStoreStore: return new MemBarStoreStoreNode(C, atp, pn);
Goetz Lindenmaierfe897662013-11-26 18:38:19 -08002983 default: ShouldNotReachHere(); return NULL;
J. Duke81537792007-12-01 00:00:00 +00002984 }
2985}
2986
2987//------------------------------Ideal------------------------------------------
2988// Return a node which is more "ideal" than the current node. Strip out
2989// control copies
2990Node *MemBarNode::Ideal(PhaseGVN *phase, bool can_reshape) {
Vladimir Kozlov9f5ca022009-12-09 16:40:45 -08002991 if (remove_dead_region(phase, can_reshape)) return this;
Vladimir Kozlov8d2ee232011-11-16 09:13:57 -08002992 // Don't bother trying to transform a dead node
Niclas Adlertz556b4922013-06-19 00:41:56 +02002993 if (in(0) && in(0)->is_top()) {
2994 return NULL;
2995 }
Vladimir Kozlov9f5ca022009-12-09 16:40:45 -08002996
Tobias Hartmann11eb4552014-07-25 10:06:17 +02002997 bool progress = false;
Vladimir Kozlov9f5ca022009-12-09 16:40:45 -08002998 // Eliminate volatile MemBars for scalar replaced objects.
Vladimir Kozlovb4977e82013-05-08 15:08:01 -07002999 if (can_reshape && req() == (Precedent+1)) {
3000 bool eliminate = false;
3001 int opc = Opcode();
3002 if ((opc == Op_MemBarAcquire || opc == Op_MemBarVolatile)) {
3003 // Volatile field loads and stores.
3004 Node* my_mem = in(MemBarNode::Precedent);
Niclas Adlertz556b4922013-06-19 00:41:56 +02003005 // The MembarAquire may keep an unused LoadNode alive through the Precedent edge
3006 if ((my_mem != NULL) && (opc == Op_MemBarAcquire) && (my_mem->outcnt() == 1)) {
Niclas Adlertz19d56712013-06-25 12:07:07 -07003007 // if the Precedent is a decodeN and its input (a Load) is used at more than one place,
3008 // replace this Precedent (decodeN) with the Load instead.
3009 if ((my_mem->Opcode() == Op_DecodeN) && (my_mem->in(1)->outcnt() > 1)) {
3010 Node* load_node = my_mem->in(1);
3011 set_req(MemBarNode::Precedent, load_node);
3012 phase->is_IterGVN()->_worklist.push(my_mem);
3013 my_mem = load_node;
3014 } else {
3015 assert(my_mem->unique_out() == this, "sanity");
3016 del_req(Precedent);
3017 phase->is_IterGVN()->_worklist.push(my_mem); // remove dead node later
3018 my_mem = NULL;
3019 }
Tobias Hartmann11eb4552014-07-25 10:06:17 +02003020 progress = true;
Niclas Adlertz556b4922013-06-19 00:41:56 +02003021 }
Vladimir Kozlovb4977e82013-05-08 15:08:01 -07003022 if (my_mem != NULL && my_mem->is_Mem()) {
3023 const TypeOopPtr* t_oop = my_mem->in(MemNode::Address)->bottom_type()->isa_oopptr();
3024 // Check for scalar replaced object reference.
3025 if( t_oop != NULL && t_oop->is_known_instance_field() &&
3026 t_oop->offset() != Type::OffsetBot &&
3027 t_oop->offset() != Type::OffsetTop) {
3028 eliminate = true;
3029 }
Vladimir Kozlov9f5ca022009-12-09 16:40:45 -08003030 }
Vladimir Kozlovb4977e82013-05-08 15:08:01 -07003031 } else if (opc == Op_MemBarRelease) {
3032 // Final field stores.
3033 Node* alloc = AllocateNode::Ideal_allocation(in(MemBarNode::Precedent), phase);
3034 if ((alloc != NULL) && alloc->is_Allocate() &&
Hui Shi0f4b2482015-09-21 10:51:33 +02003035 alloc->as_Allocate()->does_not_escape_thread()) {
Vladimir Kozlovb4977e82013-05-08 15:08:01 -07003036 // The allocated object does not escape.
3037 eliminate = true;
3038 }
3039 }
3040 if (eliminate) {
3041 // Replace MemBar projections by its inputs.
3042 PhaseIterGVN* igvn = phase->is_IterGVN();
3043 igvn->replace_node(proj_out(TypeFunc::Memory), in(TypeFunc::Memory));
3044 igvn->replace_node(proj_out(TypeFunc::Control), in(TypeFunc::Control));
3045 // Must return either the original node (now dead) or a new node
3046 // (Do not return a top here, since that would break the uniqueness of top.)
Tobias Hartmann2a0815a2014-06-02 08:07:29 +02003047 return new ConINode(TypeInt::ZERO);
Vladimir Kozlov9f5ca022009-12-09 16:40:45 -08003048 }
3049 }
Tobias Hartmann11eb4552014-07-25 10:06:17 +02003050 return progress ? this : NULL;
J. Duke81537792007-12-01 00:00:00 +00003051}
3052
3053//------------------------------Value------------------------------------------
Tobias Hartmann69b52aa2016-01-12 12:55:09 +01003054const Type* MemBarNode::Value(PhaseGVN* phase) const {
J. Duke81537792007-12-01 00:00:00 +00003055 if( !in(0) ) return Type::TOP;
3056 if( phase->type(in(0)) == Type::TOP )
3057 return Type::TOP;
3058 return TypeTuple::MEMBAR;
3059}
3060
3061//------------------------------match------------------------------------------
3062// Construct projections for memory.
3063Node *MemBarNode::match( const ProjNode *proj, const Matcher *m ) {
3064 switch (proj->_con) {
3065 case TypeFunc::Control:
3066 case TypeFunc::Memory:
Tobias Hartmann2a0815a2014-06-02 08:07:29 +02003067 return new MachProjNode(this,proj->_con,RegMask::Empty,MachProjNode::unmatched_proj);
J. Duke81537792007-12-01 00:00:00 +00003068 }
3069 ShouldNotReachHere();
3070 return NULL;
3071}
3072
3073//===========================InitializeNode====================================
3074// SUMMARY:
3075// This node acts as a memory barrier on raw memory, after some raw stores.
3076// The 'cooked' oop value feeds from the Initialize, not the Allocation.
3077// The Initialize can 'capture' suitably constrained stores as raw inits.
3078// It can coalesce related raw stores into larger units (called 'tiles').
3079// It can avoid zeroing new storage for memory units which have raw inits.
3080// At macro-expansion, it is marked 'complete', and does not optimize further.
3081//
3082// EXAMPLE:
3083// The object 'new short[2]' occupies 16 bytes in a 32-bit machine.
3084// ctl = incoming control; mem* = incoming memory
3085// (Note: A star * on a memory edge denotes I/O and other standard edges.)
3086// First allocate uninitialized memory and fill in the header:
3087// alloc = (Allocate ctl mem* 16 #short[].klass ...)
3088// ctl := alloc.Control; mem* := alloc.Memory*
3089// rawmem = alloc.Memory; rawoop = alloc.RawAddress
3090// Then initialize to zero the non-header parts of the raw memory block:
3091// init = (Initialize alloc.Control alloc.Memory* alloc.RawAddress)
3092// ctl := init.Control; mem.SLICE(#short[*]) := init.Memory
3093// After the initialize node executes, the object is ready for service:
3094// oop := (CheckCastPP init.Control alloc.RawAddress #short[])
3095// Suppose its body is immediately initialized as {1,2}:
3096// store1 = (StoreC init.Control init.Memory (+ oop 12) 1)
3097// store2 = (StoreC init.Control store1 (+ oop 14) 2)
3098// mem.SLICE(#short[*]) := store2
3099//
3100// DETAILS:
3101// An InitializeNode collects and isolates object initialization after
3102// an AllocateNode and before the next possible safepoint. As a
3103// memory barrier (MemBarNode), it keeps critical stores from drifting
3104// down past any safepoint or any publication of the allocation.
3105// Before this barrier, a newly-allocated object may have uninitialized bits.
3106// After this barrier, it may be treated as a real oop, and GC is allowed.
3107//
3108// The semantics of the InitializeNode include an implicit zeroing of
3109// the new object from object header to the end of the object.
3110// (The object header and end are determined by the AllocateNode.)
3111//
3112// Certain stores may be added as direct inputs to the InitializeNode.
3113// These stores must update raw memory, and they must be to addresses
3114// derived from the raw address produced by AllocateNode, and with
3115// a constant offset. They must be ordered by increasing offset.
3116// The first one is at in(RawStores), the last at in(req()-1).
3117// Unlike most memory operations, they are not linked in a chain,
3118// but are displayed in parallel as users of the rawmem output of
3119// the allocation.
3120//
3121// (See comments in InitializeNode::capture_store, which continue
3122// the example given above.)
3123//
3124// When the associated Allocate is macro-expanded, the InitializeNode
3125// may be rewritten to optimize collected stores. A ClearArrayNode
3126// may also be created at that point to represent any required zeroing.
3127// The InitializeNode is then marked 'complete', prohibiting further
3128// capturing of nearby memory operations.
3129//
3130// During macro-expansion, all captured initializations which store
Christian Thalinger05d1de72009-02-27 13:27:09 -08003131// constant values of 32 bits or smaller are coalesced (if advantageous)
J. Duke81537792007-12-01 00:00:00 +00003132// into larger 'tiles' 32 or 64 bits. This allows an object to be
3133// initialized in fewer memory operations. Memory words which are
3134// covered by neither tiles nor non-constant stores are pre-zeroed
3135// by explicit stores of zero. (The code shape happens to do all
3136// zeroing first, then all other stores, with both sequences occurring
3137// in order of ascending offsets.)
3138//
3139// Alternatively, code may be inserted between an AllocateNode and its
3140// InitializeNode, to perform arbitrary initialization of the new object.
3141// E.g., the object copying intrinsics insert complex data transfers here.
3142// The initialization must then be marked as 'complete' disable the
3143// built-in zeroing semantics and the collection of initializing stores.
3144//
3145// While an InitializeNode is incomplete, reads from the memory state
3146// produced by it are optimizable if they match the control edge and
3147// new oop address associated with the allocation/initialization.
3148// They return a stored value (if the offset matches) or else zero.
3149// A write to the memory state, if it matches control and address,
3150// and if it is to a constant offset, may be 'captured' by the
3151// InitializeNode. It is cloned as a raw memory operation and rewired
3152// inside the initialization, to the raw oop produced by the allocation.
3153// Operations on addresses which are provably distinct (e.g., to
3154// other AllocateNodes) are allowed to bypass the initialization.
3155//
3156// The effect of all this is to consolidate object initialization
3157// (both arrays and non-arrays, both piecewise and bulk) into a
3158// single location, where it can be optimized as a unit.
3159//
3160// Only stores with an offset less than TrackedInitializationLimit words
3161// will be considered for capture by an InitializeNode. This puts a
3162// reasonable limit on the complexity of optimized initializations.
3163
3164//---------------------------InitializeNode------------------------------------
3165InitializeNode::InitializeNode(Compile* C, int adr_type, Node* rawoop)
Roland Westrelin97439fb2011-12-20 16:56:50 +01003166 : _is_complete(Incomplete), _does_not_escape(false),
J. Duke81537792007-12-01 00:00:00 +00003167 MemBarNode(C, adr_type, rawoop)
3168{
3169 init_class_id(Class_Initialize);
3170
3171 assert(adr_type == Compile::AliasIdxRaw, "only valid atp");
3172 assert(in(RawAddress) == rawoop, "proper init");
3173 // Note: allocation() can be NULL, for secondary initialization barriers
3174}
3175
3176// Since this node is not matched, it will be processed by the
3177// register allocator. Declare that there are no constraints
3178// on the allocation of the RawAddress edge.
3179const RegMask &InitializeNode::in_RegMask(uint idx) const {
3180 // This edge should be set to top, by the set_complete. But be conservative.
3181 if (idx == InitializeNode::RawAddress)
3182 return *(Compile::current()->matcher()->idealreg2spillmask[in(idx)->ideal_reg()]);
3183 return RegMask::Empty;
3184}
3185
3186Node* InitializeNode::memory(uint alias_idx) {
3187 Node* mem = in(Memory);
3188 if (mem->is_MergeMem()) {
3189 return mem->as_MergeMem()->memory_at(alias_idx);
3190 } else {
3191 // incoming raw memory is not split
3192 return mem;
3193 }
3194}
3195
3196bool InitializeNode::is_non_zero() {
3197 if (is_complete()) return false;
3198 remove_extra_zeroes();
3199 return (req() > RawStores);
3200}
3201
3202void InitializeNode::set_complete(PhaseGVN* phase) {
3203 assert(!is_complete(), "caller responsibility");
Vladimir Kozlov47e357e2011-09-26 10:24:05 -07003204 _is_complete = Complete;
J. Duke81537792007-12-01 00:00:00 +00003205
3206 // After this node is complete, it contains a bunch of
3207 // raw-memory initializations. There is no need for
3208 // it to have anything to do with non-raw memory effects.
3209 // Therefore, tell all non-raw users to re-optimize themselves,
3210 // after skipping the memory effects of this initialization.
3211 PhaseIterGVN* igvn = phase->is_IterGVN();
3212 if (igvn) igvn->add_users_to_worklist(this);
3213}
3214
3215// convenience function
3216// return false if the init contains any stores already
3217bool AllocateNode::maybe_set_complete(PhaseGVN* phase) {
3218 InitializeNode* init = initialization();
3219 if (init == NULL || init->is_complete()) return false;
3220 init->remove_extra_zeroes();
3221 // for now, if this allocation has already collected any inits, bail:
3222 if (init->is_non_zero()) return false;
3223 init->set_complete(phase);
3224 return true;
3225}
3226
3227void InitializeNode::remove_extra_zeroes() {
3228 if (req() == RawStores) return;
3229 Node* zmem = zero_memory();
3230 uint fill = RawStores;
3231 for (uint i = fill; i < req(); i++) {
3232 Node* n = in(i);
3233 if (n->is_top() || n == zmem) continue; // skip
3234 if (fill < i) set_req(fill, n); // compact
3235 ++fill;
3236 }
3237 // delete any empty spaces created:
3238 while (fill < req()) {
3239 del_req(fill);
3240 }
3241}
3242
3243// Helper for remembering which stores go with which offsets.
3244intptr_t InitializeNode::get_store_offset(Node* st, PhaseTransform* phase) {
3245 if (!st->is_Store()) return -1; // can happen to dead code via subsume_node
3246 intptr_t offset = -1;
3247 Node* base = AddPNode::Ideal_base_and_offset(st->in(MemNode::Address),
3248 phase, offset);
3249 if (base == NULL) return -1; // something is dead,
3250 if (offset < 0) return -1; // dead, dead
3251 return offset;
3252}
3253
3254// Helper for proving that an initialization expression is
3255// "simple enough" to be folded into an object initialization.
3256// Attempts to prove that a store's initial value 'n' can be captured
3257// within the initialization without creating a vicious cycle, such as:
3258// { Foo p = new Foo(); p.next = p; }
3259// True for constants and parameters and small combinations thereof.
Vladimir Kozlovb4977e82013-05-08 15:08:01 -07003260bool InitializeNode::detect_init_independence(Node* n, int& count) {
J. Duke81537792007-12-01 00:00:00 +00003261 if (n == NULL) return true; // (can this really happen?)
3262 if (n->is_Proj()) n = n->in(0);
3263 if (n == this) return false; // found a cycle
3264 if (n->is_Con()) return true;
3265 if (n->is_Start()) return true; // params, etc., are OK
3266 if (n->is_Root()) return true; // even better
3267
3268 Node* ctl = n->in(0);
3269 if (ctl != NULL && !ctl->is_top()) {
3270 if (ctl->is_Proj()) ctl = ctl->in(0);
3271 if (ctl == this) return false;
3272
3273 // If we already know that the enclosing memory op is pinned right after
3274 // the init, then any control flow that the store has picked up
3275 // must have preceded the init, or else be equal to the init.
3276 // Even after loop optimizations (which might change control edges)
3277 // a store is never pinned *before* the availability of its inputs.
Vladimir Kozlovdf8fc192008-04-16 19:19:48 -07003278 if (!MemNode::all_controls_dominate(n, this))
J. Duke81537792007-12-01 00:00:00 +00003279 return false; // failed to prove a good control
J. Duke81537792007-12-01 00:00:00 +00003280 }
3281
3282 // Check data edges for possible dependencies on 'this'.
3283 if ((count += 1) > 20) return false; // complexity limit
3284 for (uint i = 1; i < n->req(); i++) {
3285 Node* m = n->in(i);
3286 if (m == NULL || m == n || m->is_top()) continue;
3287 uint first_i = n->find_edge(m);
3288 if (i != first_i) continue; // process duplicate edge just once
Vladimir Kozlovb4977e82013-05-08 15:08:01 -07003289 if (!detect_init_independence(m, count)) {
J. Duke81537792007-12-01 00:00:00 +00003290 return false;
3291 }
3292 }
3293
3294 return true;
3295}
3296
3297// Here are all the checks a Store must pass before it can be moved into
3298// an initialization. Returns zero if a check fails.
3299// On success, returns the (constant) offset to which the store applies,
3300// within the initialized memory.
Roland Westrelinfe928622013-02-25 14:13:04 +01003301intptr_t InitializeNode::can_capture_store(StoreNode* st, PhaseTransform* phase, bool can_reshape) {
J. Duke81537792007-12-01 00:00:00 +00003302 const int FAIL = 0;
Roland Westrelin45b3ce82015-10-28 10:20:33 +01003303 if (st->is_unaligned_access()) {
3304 return FAIL;
3305 }
J. Duke81537792007-12-01 00:00:00 +00003306 if (st->req() != MemNode::ValueIn + 1)
3307 return FAIL; // an inscrutable StoreNode (card mark?)
3308 Node* ctl = st->in(MemNode::Control);
3309 if (!(ctl != NULL && ctl->is_Proj() && ctl->in(0) == this))
3310 return FAIL; // must be unconditional after the initialization
3311 Node* mem = st->in(MemNode::Memory);
3312 if (!(mem->is_Proj() && mem->in(0) == this))
3313 return FAIL; // must not be preceded by other stores
3314 Node* adr = st->in(MemNode::Address);
3315 intptr_t offset;
3316 AllocateNode* alloc = AllocateNode::Ideal_allocation(adr, phase, offset);
3317 if (alloc == NULL)
3318 return FAIL; // inscrutable address
3319 if (alloc != allocation())
3320 return FAIL; // wrong allocation! (store needs to float up)
3321 Node* val = st->in(MemNode::ValueIn);
3322 int complexity_count = 0;
Vladimir Kozlovb4977e82013-05-08 15:08:01 -07003323 if (!detect_init_independence(val, complexity_count))
J. Duke81537792007-12-01 00:00:00 +00003324 return FAIL; // stored value must be 'simple enough'
3325
Roland Westrelinfe928622013-02-25 14:13:04 +01003326 // The Store can be captured only if nothing after the allocation
3327 // and before the Store is using the memory location that the store
3328 // overwrites.
3329 bool failed = false;
3330 // If is_complete_with_arraycopy() is true the shape of the graph is
3331 // well defined and is safe so no need for extra checks.
3332 if (!is_complete_with_arraycopy()) {
3333 // We are going to look at each use of the memory state following
3334 // the allocation to make sure nothing reads the memory that the
3335 // Store writes.
3336 const TypePtr* t_adr = phase->type(adr)->isa_ptr();
3337 int alias_idx = phase->C->get_alias_index(t_adr);
3338 ResourceMark rm;
3339 Unique_Node_List mems;
3340 mems.push(mem);
3341 Node* unique_merge = NULL;
3342 for (uint next = 0; next < mems.size(); ++next) {
3343 Node *m = mems.at(next);
3344 for (DUIterator_Fast jmax, j = m->fast_outs(jmax); j < jmax; j++) {
3345 Node *n = m->fast_out(j);
3346 if (n->outcnt() == 0) {
3347 continue;
3348 }
3349 if (n == st) {
3350 continue;
3351 } else if (n->in(0) != NULL && n->in(0) != ctl) {
3352 // If the control of this use is different from the control
3353 // of the Store which is right after the InitializeNode then
3354 // this node cannot be between the InitializeNode and the
3355 // Store.
3356 continue;
3357 } else if (n->is_MergeMem()) {
3358 if (n->as_MergeMem()->memory_at(alias_idx) == m) {
3359 // We can hit a MergeMemNode (that will likely go away
3360 // later) that is a direct use of the memory state
3361 // following the InitializeNode on the same slice as the
3362 // store node that we'd like to capture. We need to check
3363 // the uses of the MergeMemNode.
3364 mems.push(n);
3365 }
3366 } else if (n->is_Mem()) {
3367 Node* other_adr = n->in(MemNode::Address);
3368 if (other_adr == adr) {
3369 failed = true;
3370 break;
3371 } else {
3372 const TypePtr* other_t_adr = phase->type(other_adr)->isa_ptr();
3373 if (other_t_adr != NULL) {
3374 int other_alias_idx = phase->C->get_alias_index(other_t_adr);
3375 if (other_alias_idx == alias_idx) {
3376 // A load from the same memory slice as the store right
3377 // after the InitializeNode. We check the control of the
3378 // object/array that is loaded from. If it's the same as
3379 // the store control then we cannot capture the store.
3380 assert(!n->is_Store(), "2 stores to same slice on same control?");
3381 Node* base = other_adr;
David Lindholm1e71f672015-09-29 11:02:08 +02003382 assert(base->is_AddP(), "should be addp but is %s", base->Name());
Roland Westrelinfe928622013-02-25 14:13:04 +01003383 base = base->in(AddPNode::Base);
3384 if (base != NULL) {
3385 base = base->uncast();
3386 if (base->is_Proj() && base->in(0) == alloc) {
3387 failed = true;
3388 break;
3389 }
3390 }
3391 }
3392 }
3393 }
3394 } else {
3395 failed = true;
3396 break;
3397 }
3398 }
3399 }
3400 }
3401 if (failed) {
3402 if (!can_reshape) {
3403 // We decided we couldn't capture the store during parsing. We
3404 // should try again during the next IGVN once the graph is
3405 // cleaner.
3406 phase->C->record_for_igvn(st);
3407 }
3408 return FAIL;
3409 }
3410
J. Duke81537792007-12-01 00:00:00 +00003411 return offset; // success
3412}
3413
3414// Find the captured store in(i) which corresponds to the range
3415// [start..start+size) in the initialized object.
3416// If there is one, return its index i. If there isn't, return the
3417// negative of the index where it should be inserted.
3418// Return 0 if the queried range overlaps an initialization boundary
3419// or if dead code is encountered.
3420// If size_in_bytes is zero, do not bother with overlap checks.
3421int InitializeNode::captured_store_insertion_point(intptr_t start,
3422 int size_in_bytes,
3423 PhaseTransform* phase) {
3424 const int FAIL = 0, MAX_STORE = BytesPerLong;
3425
3426 if (is_complete())
3427 return FAIL; // arraycopy got here first; punt
3428
3429 assert(allocation() != NULL, "must be present");
3430
3431 // no negatives, no header fields:
Coleen Phillimore4a831d42008-04-13 17:43:42 -04003432 if (start < (intptr_t) allocation()->minimum_header_size()) return FAIL;
J. Duke81537792007-12-01 00:00:00 +00003433
3434 // after a certain size, we bail out on tracking all the stores:
3435 intptr_t ti_limit = (TrackedInitializationLimit * HeapWordSize);
3436 if (start >= ti_limit) return FAIL;
3437
3438 for (uint i = InitializeNode::RawStores, limit = req(); ; ) {
3439 if (i >= limit) return -(int)i; // not found; here is where to put it
3440
3441 Node* st = in(i);
3442 intptr_t st_off = get_store_offset(st, phase);
3443 if (st_off < 0) {
3444 if (st != zero_memory()) {
3445 return FAIL; // bail out if there is dead garbage
3446 }
3447 } else if (st_off > start) {
3448 // ...we are done, since stores are ordered
3449 if (st_off < start + size_in_bytes) {
3450 return FAIL; // the next store overlaps
3451 }
3452 return -(int)i; // not found; here is where to put it
3453 } else if (st_off < start) {
3454 if (size_in_bytes != 0 &&
3455 start < st_off + MAX_STORE &&
3456 start < st_off + st->as_Store()->memory_size()) {
3457 return FAIL; // the previous store overlaps
3458 }
3459 } else {
3460 if (size_in_bytes != 0 &&
3461 st->as_Store()->memory_size() != size_in_bytes) {
3462 return FAIL; // mismatched store size
3463 }
3464 return i;
3465 }
3466
3467 ++i;
3468 }
3469}
3470
3471// Look for a captured store which initializes at the offset 'start'
3472// with the given size. If there is no such store, and no other
3473// initialization interferes, then return zero_memory (the memory
3474// projection of the AllocateNode).
3475Node* InitializeNode::find_captured_store(intptr_t start, int size_in_bytes,
3476 PhaseTransform* phase) {
3477 assert(stores_are_sane(phase), "");
3478 int i = captured_store_insertion_point(start, size_in_bytes, phase);
3479 if (i == 0) {
3480 return NULL; // something is dead
3481 } else if (i < 0) {
3482 return zero_memory(); // just primordial zero bits here
3483 } else {
3484 Node* st = in(i); // here is the store at this position
3485 assert(get_store_offset(st->as_Store(), phase) == start, "sanity");
3486 return st;
3487 }
3488}
3489
3490// Create, as a raw pointer, an address within my new object at 'offset'.
3491Node* InitializeNode::make_raw_address(intptr_t offset,
3492 PhaseTransform* phase) {
3493 Node* addr = in(RawAddress);
3494 if (offset != 0) {
3495 Compile* C = phase->C;
Tobias Hartmann2a0815a2014-06-02 08:07:29 +02003496 addr = phase->transform( new AddPNode(C->top(), addr,
J. Duke81537792007-12-01 00:00:00 +00003497 phase->MakeConX(offset)) );
3498 }
3499 return addr;
3500}
3501
3502// Clone the given store, converting it into a raw store
3503// initializing a field or element of my new object.
3504// Caller is responsible for retiring the original store,
3505// with subsume_node or the like.
3506//
3507// From the example above InitializeNode::InitializeNode,
3508// here are the old stores to be captured:
3509// store1 = (StoreC init.Control init.Memory (+ oop 12) 1)
3510// store2 = (StoreC init.Control store1 (+ oop 14) 2)
3511//
3512// Here is the changed code; note the extra edges on init:
3513// alloc = (Allocate ...)
3514// rawoop = alloc.RawAddress
3515// rawstore1 = (StoreC alloc.Control alloc.Memory (+ rawoop 12) 1)
3516// rawstore2 = (StoreC alloc.Control alloc.Memory (+ rawoop 14) 2)
3517// init = (Initialize alloc.Control alloc.Memory rawoop
3518// rawstore1 rawstore2)
3519//
3520Node* InitializeNode::capture_store(StoreNode* st, intptr_t start,
Roland Westrelinfe928622013-02-25 14:13:04 +01003521 PhaseTransform* phase, bool can_reshape) {
J. Duke81537792007-12-01 00:00:00 +00003522 assert(stores_are_sane(phase), "");
3523
3524 if (start < 0) return NULL;
Roland Westrelinfe928622013-02-25 14:13:04 +01003525 assert(can_capture_store(st, phase, can_reshape) == start, "sanity");
J. Duke81537792007-12-01 00:00:00 +00003526
3527 Compile* C = phase->C;
3528 int size_in_bytes = st->memory_size();
3529 int i = captured_store_insertion_point(start, size_in_bytes, phase);
3530 if (i == 0) return NULL; // bail out
3531 Node* prev_mem = NULL; // raw memory for the captured store
3532 if (i > 0) {
3533 prev_mem = in(i); // there is a pre-existing store under this one
3534 set_req(i, C->top()); // temporarily disconnect it
3535 // See StoreNode::Ideal 'st->outcnt() == 1' for the reason to disconnect.
3536 } else {
3537 i = -i; // no pre-existing store
3538 prev_mem = zero_memory(); // a slice of the newly allocated object
3539 if (i > InitializeNode::RawStores && in(i-1) == prev_mem)
3540 set_req(--i, C->top()); // reuse this edge; it has been folded away
3541 else
3542 ins_req(i, C->top()); // build a new edge
3543 }
3544 Node* new_st = st->clone();
3545 new_st->set_req(MemNode::Control, in(Control));
3546 new_st->set_req(MemNode::Memory, prev_mem);
3547 new_st->set_req(MemNode::Address, make_raw_address(start, phase));
3548 new_st = phase->transform(new_st);
3549
3550 // At this point, new_st might have swallowed a pre-existing store
3551 // at the same offset, or perhaps new_st might have disappeared,
3552 // if it redundantly stored the same value (or zero to fresh memory).
3553
3554 // In any case, wire it in:
Tobias Hartmann11eb4552014-07-25 10:06:17 +02003555 phase->igvn_rehash_node_delayed(this);
J. Duke81537792007-12-01 00:00:00 +00003556 set_req(i, new_st);
3557
3558 // The caller may now kill the old guy.
3559 DEBUG_ONLY(Node* check_st = find_captured_store(start, size_in_bytes, phase));
3560 assert(check_st == new_st || check_st == NULL, "must be findable");
3561 assert(!is_complete(), "");
3562 return new_st;
3563}
3564
3565static bool store_constant(jlong* tiles, int num_tiles,
3566 intptr_t st_off, int st_size,
3567 jlong con) {
3568 if ((st_off & (st_size-1)) != 0)
3569 return false; // strange store offset (assume size==2**N)
3570 address addr = (address)tiles + st_off;
3571 assert(st_off >= 0 && addr+st_size <= (address)&tiles[num_tiles], "oob");
3572 switch (st_size) {
3573 case sizeof(jbyte): *(jbyte*) addr = (jbyte) con; break;
3574 case sizeof(jchar): *(jchar*) addr = (jchar) con; break;
3575 case sizeof(jint): *(jint*) addr = (jint) con; break;
3576 case sizeof(jlong): *(jlong*) addr = (jlong) con; break;
3577 default: return false; // strange store size (detect size!=2**N here)
3578 }
3579 return true; // return success to caller
3580}
3581
3582// Coalesce subword constants into int constants and possibly
3583// into long constants. The goal, if the CPU permits,
3584// is to initialize the object with a small number of 64-bit tiles.
3585// Also, convert floating-point constants to bit patterns.
3586// Non-constants are not relevant to this pass.
3587//
3588// In terms of the running example on InitializeNode::InitializeNode
3589// and InitializeNode::capture_store, here is the transformation
3590// of rawstore1 and rawstore2 into rawstore12:
3591// alloc = (Allocate ...)
3592// rawoop = alloc.RawAddress
3593// tile12 = 0x00010002
3594// rawstore12 = (StoreI alloc.Control alloc.Memory (+ rawoop 12) tile12)
3595// init = (Initialize alloc.Control alloc.Memory rawoop rawstore12)
3596//
3597void
3598InitializeNode::coalesce_subword_stores(intptr_t header_size,
3599 Node* size_in_bytes,
3600 PhaseGVN* phase) {
3601 Compile* C = phase->C;
3602
3603 assert(stores_are_sane(phase), "");
3604 // Note: After this pass, they are not completely sane,
3605 // since there may be some overlaps.
3606
3607 int old_subword = 0, old_long = 0, new_int = 0, new_long = 0;
3608
3609 intptr_t ti_limit = (TrackedInitializationLimit * HeapWordSize);
3610 intptr_t size_limit = phase->find_intptr_t_con(size_in_bytes, ti_limit);
3611 size_limit = MIN2(size_limit, ti_limit);
3612 size_limit = align_size_up(size_limit, BytesPerLong);
3613 int num_tiles = size_limit / BytesPerLong;
3614
3615 // allocate space for the tile map:
3616 const int small_len = DEBUG_ONLY(true ? 3 :) 30; // keep stack frames small
3617 jlong tiles_buf[small_len];
3618 Node* nodes_buf[small_len];
3619 jlong inits_buf[small_len];
3620 jlong* tiles = ((num_tiles <= small_len) ? &tiles_buf[0]
3621 : NEW_RESOURCE_ARRAY(jlong, num_tiles));
3622 Node** nodes = ((num_tiles <= small_len) ? &nodes_buf[0]
3623 : NEW_RESOURCE_ARRAY(Node*, num_tiles));
3624 jlong* inits = ((num_tiles <= small_len) ? &inits_buf[0]
3625 : NEW_RESOURCE_ARRAY(jlong, num_tiles));
3626 // tiles: exact bitwise model of all primitive constants
3627 // nodes: last constant-storing node subsumed into the tiles model
3628 // inits: which bytes (in each tile) are touched by any initializations
3629
3630 //// Pass A: Fill in the tile model with any relevant stores.
3631
3632 Copy::zero_to_bytes(tiles, sizeof(tiles[0]) * num_tiles);
3633 Copy::zero_to_bytes(nodes, sizeof(nodes[0]) * num_tiles);
3634 Copy::zero_to_bytes(inits, sizeof(inits[0]) * num_tiles);
3635 Node* zmem = zero_memory(); // initially zero memory state
3636 for (uint i = InitializeNode::RawStores, limit = req(); i < limit; i++) {
3637 Node* st = in(i);
3638 intptr_t st_off = get_store_offset(st, phase);
3639
3640 // Figure out the store's offset and constant value:
3641 if (st_off < header_size) continue; //skip (ignore header)
3642 if (st->in(MemNode::Memory) != zmem) continue; //skip (odd store chain)
3643 int st_size = st->as_Store()->memory_size();
3644 if (st_off + st_size > size_limit) break;
3645
3646 // Record which bytes are touched, whether by constant or not.
3647 if (!store_constant(inits, num_tiles, st_off, st_size, (jlong) -1))
3648 continue; // skip (strange store size)
3649
3650 const Type* val = phase->type(st->in(MemNode::ValueIn));
3651 if (!val->singleton()) continue; //skip (non-con store)
3652 BasicType type = val->basic_type();
3653
3654 jlong con = 0;
3655 switch (type) {
3656 case T_INT: con = val->is_int()->get_con(); break;
3657 case T_LONG: con = val->is_long()->get_con(); break;
3658 case T_FLOAT: con = jint_cast(val->getf()); break;
3659 case T_DOUBLE: con = jlong_cast(val->getd()); break;
3660 default: continue; //skip (odd store type)
3661 }
3662
3663 if (type == T_LONG && Matcher::isSimpleConstant64(con) &&
3664 st->Opcode() == Op_StoreL) {
3665 continue; // This StoreL is already optimal.
3666 }
3667
3668 // Store down the constant.
3669 store_constant(tiles, num_tiles, st_off, st_size, con);
3670
3671 intptr_t j = st_off >> LogBytesPerLong;
3672
3673 if (type == T_INT && st_size == BytesPerInt
3674 && (st_off & BytesPerInt) == BytesPerInt) {
3675 jlong lcon = tiles[j];
3676 if (!Matcher::isSimpleConstant64(lcon) &&
3677 st->Opcode() == Op_StoreI) {
3678 // This StoreI is already optimal by itself.
3679 jint* intcon = (jint*) &tiles[j];
3680 intcon[1] = 0; // undo the store_constant()
3681
3682 // If the previous store is also optimal by itself, back up and
3683 // undo the action of the previous loop iteration... if we can.
3684 // But if we can't, just let the previous half take care of itself.
3685 st = nodes[j];
3686 st_off -= BytesPerInt;
3687 con = intcon[0];
3688 if (con != 0 && st != NULL && st->Opcode() == Op_StoreI) {
3689 assert(st_off >= header_size, "still ignoring header");
3690 assert(get_store_offset(st, phase) == st_off, "must be");
3691 assert(in(i-1) == zmem, "must be");
3692 DEBUG_ONLY(const Type* tcon = phase->type(st->in(MemNode::ValueIn)));
3693 assert(con == tcon->is_int()->get_con(), "must be");
3694 // Undo the effects of the previous loop trip, which swallowed st:
3695 intcon[0] = 0; // undo store_constant()
3696 set_req(i-1, st); // undo set_req(i, zmem)
3697 nodes[j] = NULL; // undo nodes[j] = st
3698 --old_subword; // undo ++old_subword
3699 }
3700 continue; // This StoreI is already optimal.
3701 }
3702 }
3703
3704 // This store is not needed.
3705 set_req(i, zmem);
3706 nodes[j] = st; // record for the moment
3707 if (st_size < BytesPerLong) // something has changed
3708 ++old_subword; // includes int/float, but who's counting...
3709 else ++old_long;
3710 }
3711
3712 if ((old_subword + old_long) == 0)
3713 return; // nothing more to do
3714
3715 //// Pass B: Convert any non-zero tiles into optimal constant stores.
3716 // Be sure to insert them before overlapping non-constant stores.
3717 // (E.g., byte[] x = { 1,2,y,4 } => x[int 0] = 0x01020004, x[2]=y.)
3718 for (int j = 0; j < num_tiles; j++) {
3719 jlong con = tiles[j];
3720 jlong init = inits[j];
3721 if (con == 0) continue;
3722 jint con0, con1; // split the constant, address-wise
3723 jint init0, init1; // split the init map, address-wise
3724 { union { jlong con; jint intcon[2]; } u;
3725 u.con = con;
3726 con0 = u.intcon[0];
3727 con1 = u.intcon[1];
3728 u.con = init;
3729 init0 = u.intcon[0];
3730 init1 = u.intcon[1];
3731 }
3732
3733 Node* old = nodes[j];
3734 assert(old != NULL, "need the prior store");
3735 intptr_t offset = (j * BytesPerLong);
3736
3737 bool split = !Matcher::isSimpleConstant64(con);
3738
3739 if (offset < header_size) {
3740 assert(offset + BytesPerInt >= header_size, "second int counts");
3741 assert(*(jint*)&tiles[j] == 0, "junk in header");
3742 split = true; // only the second word counts
3743 // Example: int a[] = { 42 ... }
3744 } else if (con0 == 0 && init0 == -1) {
3745 split = true; // first word is covered by full inits
3746 // Example: int a[] = { ... foo(), 42 ... }
3747 } else if (con1 == 0 && init1 == -1) {
3748 split = true; // second word is covered by full inits
3749 // Example: int a[] = { ... 42, foo() ... }
3750 }
3751
3752 // Here's a case where init0 is neither 0 nor -1:
3753 // byte a[] = { ... 0,0,foo(),0, 0,0,0,42 ... }
3754 // Assuming big-endian memory, init0, init1 are 0x0000FF00, 0x000000FF.
3755 // In this case the tile is not split; it is (jlong)42.
3756 // The big tile is stored down, and then the foo() value is inserted.
3757 // (If there were foo(),foo() instead of foo(),0, init0 would be -1.)
3758
3759 Node* ctl = old->in(MemNode::Control);
3760 Node* adr = make_raw_address(offset, phase);
3761 const TypePtr* atp = TypeRawPtr::BOTTOM;
3762
3763 // One or two coalesced stores to plop down.
3764 Node* st[2];
3765 intptr_t off[2];
3766 int nst = 0;
3767 if (!split) {
3768 ++new_long;
3769 off[nst] = offset;
Coleen Phillimore4a831d42008-04-13 17:43:42 -04003770 st[nst++] = StoreNode::make(*phase, ctl, zmem, adr, atp,
Goetz Lindenmaier13b13f52013-11-15 11:05:32 -08003771 phase->longcon(con), T_LONG, MemNode::unordered);
J. Duke81537792007-12-01 00:00:00 +00003772 } else {
3773 // Omit either if it is a zero.
3774 if (con0 != 0) {
3775 ++new_int;
3776 off[nst] = offset;
Coleen Phillimore4a831d42008-04-13 17:43:42 -04003777 st[nst++] = StoreNode::make(*phase, ctl, zmem, adr, atp,
Goetz Lindenmaier13b13f52013-11-15 11:05:32 -08003778 phase->intcon(con0), T_INT, MemNode::unordered);
J. Duke81537792007-12-01 00:00:00 +00003779 }
3780 if (con1 != 0) {
3781 ++new_int;
3782 offset += BytesPerInt;
3783 adr = make_raw_address(offset, phase);
3784 off[nst] = offset;
Coleen Phillimore4a831d42008-04-13 17:43:42 -04003785 st[nst++] = StoreNode::make(*phase, ctl, zmem, adr, atp,
Goetz Lindenmaier13b13f52013-11-15 11:05:32 -08003786 phase->intcon(con1), T_INT, MemNode::unordered);
J. Duke81537792007-12-01 00:00:00 +00003787 }
3788 }
3789
3790 // Insert second store first, then the first before the second.
3791 // Insert each one just before any overlapping non-constant stores.
3792 while (nst > 0) {
3793 Node* st1 = st[--nst];
3794 C->copy_node_notes_to(st1, old);
3795 st1 = phase->transform(st1);
3796 offset = off[nst];
3797 assert(offset >= header_size, "do not smash header");
3798 int ins_idx = captured_store_insertion_point(offset, /*size:*/0, phase);
3799 guarantee(ins_idx != 0, "must re-insert constant store");
3800 if (ins_idx < 0) ins_idx = -ins_idx; // never overlap
3801 if (ins_idx > InitializeNode::RawStores && in(ins_idx-1) == zmem)
3802 set_req(--ins_idx, st1);
3803 else
3804 ins_req(ins_idx, st1);
3805 }
3806 }
3807
3808 if (PrintCompilation && WizardMode)
3809 tty->print_cr("Changed %d/%d subword/long constants into %d/%d int/long",
3810 old_subword, old_long, new_int, new_long);
3811 if (C->log() != NULL)
3812 C->log()->elem("comment that='%d/%d subword/long to %d/%d int/long'",
3813 old_subword, old_long, new_int, new_long);
3814
3815 // Clean up any remaining occurrences of zmem:
3816 remove_extra_zeroes();
3817}
3818
3819// Explore forward from in(start) to find the first fully initialized
3820// word, and return its offset. Skip groups of subword stores which
3821// together initialize full words. If in(start) is itself part of a
3822// fully initialized word, return the offset of in(start). If there
3823// are no following full-word stores, or if something is fishy, return
3824// a negative value.
3825intptr_t InitializeNode::find_next_fullword_store(uint start, PhaseGVN* phase) {
3826 int int_map = 0;
3827 intptr_t int_map_off = 0;
3828 const int FULL_MAP = right_n_bits(BytesPerInt); // the int_map we hope for
3829
3830 for (uint i = start, limit = req(); i < limit; i++) {
3831 Node* st = in(i);
3832
3833 intptr_t st_off = get_store_offset(st, phase);
3834 if (st_off < 0) break; // return conservative answer
3835
3836 int st_size = st->as_Store()->memory_size();
3837 if (st_size >= BytesPerInt && (st_off % BytesPerInt) == 0) {
3838 return st_off; // we found a complete word init
3839 }
3840
3841 // update the map:
3842
3843 intptr_t this_int_off = align_size_down(st_off, BytesPerInt);
3844 if (this_int_off != int_map_off) {
3845 // reset the map:
3846 int_map = 0;
3847 int_map_off = this_int_off;
3848 }
3849
3850 int subword_off = st_off - this_int_off;
3851 int_map |= right_n_bits(st_size) << subword_off;
3852 if ((int_map & FULL_MAP) == FULL_MAP) {
3853 return this_int_off; // we found a complete word init
3854 }
3855
3856 // Did this store hit or cross the word boundary?
3857 intptr_t next_int_off = align_size_down(st_off + st_size, BytesPerInt);
3858 if (next_int_off == this_int_off + BytesPerInt) {
3859 // We passed the current int, without fully initializing it.
3860 int_map_off = next_int_off;
3861 int_map >>= BytesPerInt;
3862 } else if (next_int_off > this_int_off + BytesPerInt) {
3863 // We passed the current and next int.
3864 return this_int_off + BytesPerInt;
3865 }
3866 }
3867
3868 return -1;
3869}
3870
3871
3872// Called when the associated AllocateNode is expanded into CFG.
3873// At this point, we may perform additional optimizations.
3874// Linearize the stores by ascending offset, to make memory
3875// activity as coherent as possible.
3876Node* InitializeNode::complete_stores(Node* rawctl, Node* rawmem, Node* rawptr,
3877 intptr_t header_size,
3878 Node* size_in_bytes,
3879 PhaseGVN* phase) {
3880 assert(!is_complete(), "not already complete");
3881 assert(stores_are_sane(phase), "");
3882 assert(allocation() != NULL, "must be present");
3883
3884 remove_extra_zeroes();
3885
3886 if (ReduceFieldZeroing || ReduceBulkZeroing)
3887 // reduce instruction count for common initialization patterns
3888 coalesce_subword_stores(header_size, size_in_bytes, phase);
3889
3890 Node* zmem = zero_memory(); // initially zero memory state
3891 Node* inits = zmem; // accumulating a linearized chain of inits
3892 #ifdef ASSERT
Coleen Phillimore4a831d42008-04-13 17:43:42 -04003893 intptr_t first_offset = allocation()->minimum_header_size();
3894 intptr_t last_init_off = first_offset; // previous init offset
3895 intptr_t last_init_end = first_offset; // previous init offset+size
3896 intptr_t last_tile_end = first_offset; // previous tile offset+size
J. Duke81537792007-12-01 00:00:00 +00003897 #endif
3898 intptr_t zeroes_done = header_size;
3899
3900 bool do_zeroing = true; // we might give up if inits are very sparse
3901 int big_init_gaps = 0; // how many large gaps have we seen?
3902
Zoltan Majodfa65392016-01-12 09:19:09 +01003903 if (UseTLAB && ZeroTLAB) do_zeroing = false;
J. Duke81537792007-12-01 00:00:00 +00003904 if (!ReduceFieldZeroing && !ReduceBulkZeroing) do_zeroing = false;
3905
3906 for (uint i = InitializeNode::RawStores, limit = req(); i < limit; i++) {
3907 Node* st = in(i);
3908 intptr_t st_off = get_store_offset(st, phase);
3909 if (st_off < 0)
3910 break; // unknown junk in the inits
3911 if (st->in(MemNode::Memory) != zmem)
3912 break; // complicated store chains somehow in list
3913
3914 int st_size = st->as_Store()->memory_size();
3915 intptr_t next_init_off = st_off + st_size;
3916
3917 if (do_zeroing && zeroes_done < next_init_off) {
3918 // See if this store needs a zero before it or under it.
3919 intptr_t zeroes_needed = st_off;
3920
3921 if (st_size < BytesPerInt) {
3922 // Look for subword stores which only partially initialize words.
3923 // If we find some, we must lay down some word-level zeroes first,
3924 // underneath the subword stores.
3925 //
3926 // Examples:
3927 // byte[] a = { p,q,r,s } => a[0]=p,a[1]=q,a[2]=r,a[3]=s
3928 // byte[] a = { x,y,0,0 } => a[0..3] = 0, a[0]=x,a[1]=y
3929 // byte[] a = { 0,0,z,0 } => a[0..3] = 0, a[2]=z
3930 //
3931 // Note: coalesce_subword_stores may have already done this,
3932 // if it was prompted by constant non-zero subword initializers.
3933 // But this case can still arise with non-constant stores.
3934
3935 intptr_t next_full_store = find_next_fullword_store(i, phase);
3936
3937 // In the examples above:
3938 // in(i) p q r s x y z
3939 // st_off 12 13 14 15 12 13 14
3940 // st_size 1 1 1 1 1 1 1
3941 // next_full_s. 12 16 16 16 16 16 16
3942 // z's_done 12 16 16 16 12 16 12
3943 // z's_needed 12 16 16 16 16 16 16
3944 // zsize 0 0 0 0 4 0 4
3945 if (next_full_store < 0) {
3946 // Conservative tack: Zero to end of current word.
3947 zeroes_needed = align_size_up(zeroes_needed, BytesPerInt);
3948 } else {
3949 // Zero to beginning of next fully initialized word.
3950 // Or, don't zero at all, if we are already in that word.
3951 assert(next_full_store >= zeroes_needed, "must go forward");
3952 assert((next_full_store & (BytesPerInt-1)) == 0, "even boundary");
3953 zeroes_needed = next_full_store;
3954 }
3955 }
3956
3957 if (zeroes_needed > zeroes_done) {
3958 intptr_t zsize = zeroes_needed - zeroes_done;
3959 // Do some incremental zeroing on rawmem, in parallel with inits.
3960 zeroes_done = align_size_down(zeroes_done, BytesPerInt);
3961 rawmem = ClearArrayNode::clear_memory(rawctl, rawmem, rawptr,
3962 zeroes_done, zeroes_needed,
3963 phase);
3964 zeroes_done = zeroes_needed;
Aleksey Shipilev103aff32016-03-04 01:30:11 +03003965 if (zsize > InitArrayShortSize && ++big_init_gaps > 2)
J. Duke81537792007-12-01 00:00:00 +00003966 do_zeroing = false; // leave the hole, next time
3967 }
3968 }
3969
3970 // Collect the store and move on:
3971 st->set_req(MemNode::Memory, inits);
3972 inits = st; // put it on the linearized chain
3973 set_req(i, zmem); // unhook from previous position
3974
3975 if (zeroes_done == st_off)
3976 zeroes_done = next_init_off;
3977
3978 assert(!do_zeroing || zeroes_done >= next_init_off, "don't miss any");
3979
3980 #ifdef ASSERT
3981 // Various order invariants. Weaker than stores_are_sane because
3982 // a large constant tile can be filled in by smaller non-constant stores.
3983 assert(st_off >= last_init_off, "inits do not reverse");
3984 last_init_off = st_off;
3985 const Type* val = NULL;
3986 if (st_size >= BytesPerInt &&
3987 (val = phase->type(st->in(MemNode::ValueIn)))->singleton() &&
3988 (int)val->basic_type() < (int)T_OBJECT) {
3989 assert(st_off >= last_tile_end, "tiles do not overlap");
3990 assert(st_off >= last_init_end, "tiles do not overwrite inits");
3991 last_tile_end = MAX2(last_tile_end, next_init_off);
3992 } else {
3993 intptr_t st_tile_end = align_size_up(next_init_off, BytesPerLong);
3994 assert(st_tile_end >= last_tile_end, "inits stay with tiles");
3995 assert(st_off >= last_init_end, "inits do not overlap");
3996 last_init_end = next_init_off; // it's a non-tile
3997 }
3998 #endif //ASSERT
3999 }
4000
4001 remove_extra_zeroes(); // clear out all the zmems left over
4002 add_req(inits);
4003
Zoltan Majodfa65392016-01-12 09:19:09 +01004004 if (!(UseTLAB && ZeroTLAB)) {
J. Duke81537792007-12-01 00:00:00 +00004005 // If anything remains to be zeroed, zero it all now.
4006 zeroes_done = align_size_down(zeroes_done, BytesPerInt);
4007 // if it is the last unused 4 bytes of an instance, forget about it
4008 intptr_t size_limit = phase->find_intptr_t_con(size_in_bytes, max_jint);
4009 if (zeroes_done + BytesPerLong >= size_limit) {
4010 assert(allocation() != NULL, "");
Tom Rodriguez532dec32010-12-01 10:16:31 -08004011 if (allocation()->Opcode() == Op_Allocate) {
4012 Node* klass_node = allocation()->in(AllocateNode::KlassNode);
4013 ciKlass* k = phase->type(klass_node)->is_klassptr()->klass();
4014 if (zeroes_done == k->layout_helper())
4015 zeroes_done = size_limit;
4016 }
J. Duke81537792007-12-01 00:00:00 +00004017 }
4018 if (zeroes_done < size_limit) {
4019 rawmem = ClearArrayNode::clear_memory(rawctl, rawmem, rawptr,
4020 zeroes_done, size_in_bytes, phase);
4021 }
4022 }
4023
4024 set_complete(phase);
4025 return rawmem;
4026}
4027
4028
4029#ifdef ASSERT
4030bool InitializeNode::stores_are_sane(PhaseTransform* phase) {
4031 if (is_complete())
4032 return true; // stores could be anything at this point
Coleen Phillimore4a831d42008-04-13 17:43:42 -04004033 assert(allocation() != NULL, "must be present");
4034 intptr_t last_off = allocation()->minimum_header_size();
J. Duke81537792007-12-01 00:00:00 +00004035 for (uint i = InitializeNode::RawStores; i < req(); i++) {
4036 Node* st = in(i);
4037 intptr_t st_off = get_store_offset(st, phase);
4038 if (st_off < 0) continue; // ignore dead garbage
4039 if (last_off > st_off) {
David Chase305ec3b2014-05-09 16:50:54 -04004040 tty->print_cr("*** bad store offset at %d: " INTX_FORMAT " > " INTX_FORMAT, i, last_off, st_off);
J. Duke81537792007-12-01 00:00:00 +00004041 this->dump(2);
4042 assert(false, "ascending store offsets");
4043 return false;
4044 }
4045 last_off = st_off + st->as_Store()->memory_size();
4046 }
4047 return true;
4048}
4049#endif //ASSERT
4050
4051
4052
4053
4054//============================MergeMemNode=====================================
4055//
4056// SEMANTICS OF MEMORY MERGES: A MergeMem is a memory state assembled from several
4057// contributing store or call operations. Each contributor provides the memory
4058// state for a particular "alias type" (see Compile::alias_type). For example,
4059// if a MergeMem has an input X for alias category #6, then any memory reference
4060// to alias category #6 may use X as its memory state input, as an exact equivalent
4061// to using the MergeMem as a whole.
4062// Load<6>( MergeMem(<6>: X, ...), p ) <==> Load<6>(X,p)
4063//
4064// (Here, the <N> notation gives the index of the relevant adr_type.)
4065//
4066// In one special case (and more cases in the future), alias categories overlap.
4067// The special alias category "Bot" (Compile::AliasIdxBot) includes all memory
4068// states. Therefore, if a MergeMem has only one contributing input W for Bot,
4069// it is exactly equivalent to that state W:
4070// MergeMem(<Bot>: W) <==> W
4071//
4072// Usually, the merge has more than one input. In that case, where inputs
4073// overlap (i.e., one is Bot), the narrower alias type determines the memory
4074// state for that type, and the wider alias type (Bot) fills in everywhere else:
4075// Load<5>( MergeMem(<Bot>: W, <6>: X), p ) <==> Load<5>(W,p)
4076// Load<6>( MergeMem(<Bot>: W, <6>: X), p ) <==> Load<6>(X,p)
4077//
4078// A merge can take a "wide" memory state as one of its narrow inputs.
4079// This simply means that the merge observes out only the relevant parts of
4080// the wide input. That is, wide memory states arriving at narrow merge inputs
4081// are implicitly "filtered" or "sliced" as necessary. (This is rare.)
4082//
4083// These rules imply that MergeMem nodes may cascade (via their <Bot> links),
4084// and that memory slices "leak through":
4085// MergeMem(<Bot>: MergeMem(<Bot>: W, <7>: Y)) <==> MergeMem(<Bot>: W, <7>: Y)
4086//
4087// But, in such a cascade, repeated memory slices can "block the leak":
4088// MergeMem(<Bot>: MergeMem(<Bot>: W, <7>: Y), <7>: Y') <==> MergeMem(<Bot>: W, <7>: Y')
4089//
4090// In the last example, Y is not part of the combined memory state of the
4091// outermost MergeMem. The system must, of course, prevent unschedulable
4092// memory states from arising, so you can be sure that the state Y is somehow
4093// a precursor to state Y'.
4094//
4095//
4096// REPRESENTATION OF MEMORY MERGES: The indexes used to address the Node::in array
4097// of each MergeMemNode array are exactly the numerical alias indexes, including
4098// but not limited to AliasIdxTop, AliasIdxBot, and AliasIdxRaw. The functions
4099// Compile::alias_type (and kin) produce and manage these indexes.
4100//
4101// By convention, the value of in(AliasIdxTop) (i.e., in(1)) is always the top node.
4102// (Note that this provides quick access to the top node inside MergeMem methods,
4103// without the need to reach out via TLS to Compile::current.)
4104//
4105// As a consequence of what was just described, a MergeMem that represents a full
4106// memory state has an edge in(AliasIdxBot) which is a "wide" memory state,
4107// containing all alias categories.
4108//
4109// MergeMem nodes never (?) have control inputs, so in(0) is NULL.
4110//
4111// All other edges in(N) (including in(AliasIdxRaw), which is in(3)) are either
4112// a memory state for the alias type <N>, or else the top node, meaning that
4113// there is no particular input for that alias type. Note that the length of
4114// a MergeMem is variable, and may be extended at any time to accommodate new
4115// memory states at larger alias indexes. When merges grow, they are of course
4116// filled with "top" in the unused in() positions.
4117//
4118// This use of top is named "empty_memory()", or "empty_mem" (no-memory) as a variable.
4119// (Top was chosen because it works smoothly with passes like GCM.)
4120//
4121// For convenience, we hardwire the alias index for TypeRawPtr::BOTTOM. (It is
4122// the type of random VM bits like TLS references.) Since it is always the
4123// first non-Bot memory slice, some low-level loops use it to initialize an
4124// index variable: for (i = AliasIdxRaw; i < req(); i++).
4125//
4126//
4127// ACCESSORS: There is a special accessor MergeMemNode::base_memory which returns
4128// the distinguished "wide" state. The accessor MergeMemNode::memory_at(N) returns
4129// the memory state for alias type <N>, or (if there is no particular slice at <N>,
4130// it returns the base memory. To prevent bugs, memory_at does not accept <Top>
4131// or <Bot> indexes. The iterator MergeMemStream provides robust iteration over
4132// MergeMem nodes or pairs of such nodes, ensuring that the non-top edges are visited.
4133//
4134// %%%% We may get rid of base_memory as a separate accessor at some point; it isn't
4135// really that different from the other memory inputs. An abbreviation called
4136// "bot_memory()" for "memory_at(AliasIdxBot)" would keep code tidy.
4137//
4138//
4139// PARTIAL MEMORY STATES: During optimization, MergeMem nodes may arise that represent
4140// partial memory states. When a Phi splits through a MergeMem, the copy of the Phi
4141// that "emerges though" the base memory will be marked as excluding the alias types
4142// of the other (narrow-memory) copies which "emerged through" the narrow edges:
4143//
4144// Phi<Bot>(U, MergeMem(<Bot>: W, <8>: Y))
4145// ==Ideal=> MergeMem(<Bot>: Phi<Bot-8>(U, W), Phi<8>(U, Y))
4146//
4147// This strange "subtraction" effect is necessary to ensure IGVN convergence.
4148// (It is currently unimplemented.) As you can see, the resulting merge is
4149// actually a disjoint union of memory states, rather than an overlay.
4150//
4151
4152//------------------------------MergeMemNode-----------------------------------
4153Node* MergeMemNode::make_empty_memory() {
4154 Node* empty_memory = (Node*) Compile::current()->top();
4155 assert(empty_memory->is_top(), "correct sentinel identity");
4156 return empty_memory;
4157}
4158
4159MergeMemNode::MergeMemNode(Node *new_base) : Node(1+Compile::AliasIdxRaw) {
4160 init_class_id(Class_MergeMem);
4161 // all inputs are nullified in Node::Node(int)
4162 // set_input(0, NULL); // no control input
4163
4164 // Initialize the edges uniformly to top, for starters.
4165 Node* empty_mem = make_empty_memory();
4166 for (uint i = Compile::AliasIdxTop; i < req(); i++) {
4167 init_req(i,empty_mem);
4168 }
4169 assert(empty_memory() == empty_mem, "");
4170
4171 if( new_base != NULL && new_base->is_MergeMem() ) {
4172 MergeMemNode* mdef = new_base->as_MergeMem();
4173 assert(mdef->empty_memory() == empty_mem, "consistent sentinels");
4174 for (MergeMemStream mms(this, mdef); mms.next_non_empty2(); ) {
4175 mms.set_memory(mms.memory2());
4176 }
4177 assert(base_memory() == mdef->base_memory(), "");
4178 } else {
4179 set_base_memory(new_base);
4180 }
4181}
4182
4183// Make a new, untransformed MergeMem with the same base as 'mem'.
4184// If mem is itself a MergeMem, populate the result with the same edges.
Tobias Hartmann70a55ea2014-08-05 09:58:52 +02004185MergeMemNode* MergeMemNode::make(Node* mem) {
Tobias Hartmann2a0815a2014-06-02 08:07:29 +02004186 return new MergeMemNode(mem);
J. Duke81537792007-12-01 00:00:00 +00004187}
4188
4189//------------------------------cmp--------------------------------------------
4190uint MergeMemNode::hash() const { return NO_HASH; }
4191uint MergeMemNode::cmp( const Node &n ) const {
4192 return (&n == this); // Always fail except on self
4193}
4194
4195//------------------------------Identity---------------------------------------
Tobias Hartmann69b52aa2016-01-12 12:55:09 +01004196Node* MergeMemNode::Identity(PhaseGVN* phase) {
J. Duke81537792007-12-01 00:00:00 +00004197 // Identity if this merge point does not record any interesting memory
4198 // disambiguations.
4199 Node* base_mem = base_memory();
4200 Node* empty_mem = empty_memory();
4201 if (base_mem != empty_mem) { // Memory path is not dead?
4202 for (uint i = Compile::AliasIdxRaw; i < req(); i++) {
4203 Node* mem = in(i);
4204 if (mem != empty_mem && mem != base_mem) {
4205 return this; // Many memory splits; no change
4206 }
4207 }
4208 }
4209 return base_mem; // No memory splits; ID on the one true input
4210}
4211
4212//------------------------------Ideal------------------------------------------
4213// This method is invoked recursively on chains of MergeMem nodes
4214Node *MergeMemNode::Ideal(PhaseGVN *phase, bool can_reshape) {
4215 // Remove chain'd MergeMems
4216 //
4217 // This is delicate, because the each "in(i)" (i >= Raw) is interpreted
4218 // relative to the "in(Bot)". Since we are patching both at the same time,
4219 // we have to be careful to read each "in(i)" relative to the old "in(Bot)",
4220 // but rewrite each "in(i)" relative to the new "in(Bot)".
4221 Node *progress = NULL;
4222
4223
4224 Node* old_base = base_memory();
4225 Node* empty_mem = empty_memory();
4226 if (old_base == empty_mem)
4227 return NULL; // Dead memory path.
4228
4229 MergeMemNode* old_mbase;
4230 if (old_base != NULL && old_base->is_MergeMem())
4231 old_mbase = old_base->as_MergeMem();
4232 else
4233 old_mbase = NULL;
4234 Node* new_base = old_base;
4235
4236 // simplify stacked MergeMems in base memory
4237 if (old_mbase) new_base = old_mbase->base_memory();
4238
4239 // the base memory might contribute new slices beyond my req()
4240 if (old_mbase) grow_to_match(old_mbase);
4241
4242 // Look carefully at the base node if it is a phi.
4243 PhiNode* phi_base;
4244 if (new_base != NULL && new_base->is_Phi())
4245 phi_base = new_base->as_Phi();
4246 else
4247 phi_base = NULL;
4248
4249 Node* phi_reg = NULL;
4250 uint phi_len = (uint)-1;
4251 if (phi_base != NULL && !phi_base->is_copy()) {
4252 // do not examine phi if degraded to a copy
4253 phi_reg = phi_base->region();
4254 phi_len = phi_base->req();
4255 // see if the phi is unfinished
4256 for (uint i = 1; i < phi_len; i++) {
4257 if (phi_base->in(i) == NULL) {
4258 // incomplete phi; do not look at it yet!
4259 phi_reg = NULL;
4260 phi_len = (uint)-1;
4261 break;
4262 }
4263 }
4264 }
4265
4266 // Note: We do not call verify_sparse on entry, because inputs
4267 // can normalize to the base_memory via subsume_node or similar
4268 // mechanisms. This method repairs that damage.
4269
4270 assert(!old_mbase || old_mbase->is_empty_memory(empty_mem), "consistent sentinels");
4271
4272 // Look at each slice.
4273 for (uint i = Compile::AliasIdxRaw; i < req(); i++) {
4274 Node* old_in = in(i);
4275 // calculate the old memory value
4276 Node* old_mem = old_in;
4277 if (old_mem == empty_mem) old_mem = old_base;
4278 assert(old_mem == memory_at(i), "");
4279
4280 // maybe update (reslice) the old memory value
4281
4282 // simplify stacked MergeMems
4283 Node* new_mem = old_mem;
4284 MergeMemNode* old_mmem;
4285 if (old_mem != NULL && old_mem->is_MergeMem())
4286 old_mmem = old_mem->as_MergeMem();
4287 else
4288 old_mmem = NULL;
4289 if (old_mmem == this) {
4290 // This can happen if loops break up and safepoints disappear.
4291 // A merge of BotPtr (default) with a RawPtr memory derived from a
4292 // safepoint can be rewritten to a merge of the same BotPtr with
4293 // the BotPtr phi coming into the loop. If that phi disappears
4294 // also, we can end up with a self-loop of the mergemem.
4295 // In general, if loops degenerate and memory effects disappear,
4296 // a mergemem can be left looking at itself. This simply means
4297 // that the mergemem's default should be used, since there is
4298 // no longer any apparent effect on this slice.
4299 // Note: If a memory slice is a MergeMem cycle, it is unreachable
4300 // from start. Update the input to TOP.
4301 new_mem = (new_base == this || new_base == empty_mem)? empty_mem : new_base;
4302 }
4303 else if (old_mmem != NULL) {
4304 new_mem = old_mmem->memory_at(i);
4305 }
Christian Thalinger05d1de72009-02-27 13:27:09 -08004306 // else preceding memory was not a MergeMem
J. Duke81537792007-12-01 00:00:00 +00004307
4308 // replace equivalent phis (unfortunately, they do not GVN together)
4309 if (new_mem != NULL && new_mem != new_base &&
4310 new_mem->req() == phi_len && new_mem->in(0) == phi_reg) {
4311 if (new_mem->is_Phi()) {
4312 PhiNode* phi_mem = new_mem->as_Phi();
4313 for (uint i = 1; i < phi_len; i++) {
4314 if (phi_base->in(i) != phi_mem->in(i)) {
4315 phi_mem = NULL;
4316 break;
4317 }
4318 }
4319 if (phi_mem != NULL) {
4320 // equivalent phi nodes; revert to the def
4321 new_mem = new_base;
4322 }
4323 }
4324 }
4325
4326 // maybe store down a new value
4327 Node* new_in = new_mem;
4328 if (new_in == new_base) new_in = empty_mem;
4329
4330 if (new_in != old_in) {
4331 // Warning: Do not combine this "if" with the previous "if"
4332 // A memory slice might have be be rewritten even if it is semantically
4333 // unchanged, if the base_memory value has changed.
4334 set_req(i, new_in);
4335 progress = this; // Report progress
4336 }
4337 }
4338
4339 if (new_base != old_base) {
4340 set_req(Compile::AliasIdxBot, new_base);
4341 // Don't use set_base_memory(new_base), because we need to update du.
4342 assert(base_memory() == new_base, "");
4343 progress = this;
4344 }
4345
4346 if( base_memory() == this ) {
4347 // a self cycle indicates this memory path is dead
4348 set_req(Compile::AliasIdxBot, empty_mem);
4349 }
4350
4351 // Resolve external cycles by calling Ideal on a MergeMem base_memory
4352 // Recursion must occur after the self cycle check above
4353 if( base_memory()->is_MergeMem() ) {
4354 MergeMemNode *new_mbase = base_memory()->as_MergeMem();
4355 Node *m = phase->transform(new_mbase); // Rollup any cycles
4356 if( m != NULL && (m->is_top() ||
4357 m->is_MergeMem() && m->as_MergeMem()->base_memory() == empty_mem) ) {
4358 // propagate rollup of dead cycle to self
4359 set_req(Compile::AliasIdxBot, empty_mem);
4360 }
4361 }
4362
4363 if( base_memory() == empty_mem ) {
4364 progress = this;
4365 // Cut inputs during Parse phase only.
4366 // During Optimize phase a dead MergeMem node will be subsumed by Top.
4367 if( !can_reshape ) {
4368 for (uint i = Compile::AliasIdxRaw; i < req(); i++) {
4369 if( in(i) != empty_mem ) { set_req(i, empty_mem); }
4370 }
4371 }
4372 }
4373
4374 if( !progress && base_memory()->is_Phi() && can_reshape ) {
4375 // Check if PhiNode::Ideal's "Split phis through memory merges"
4376 // transform should be attempted. Look for this->phi->this cycle.
4377 uint merge_width = req();
4378 if (merge_width > Compile::AliasIdxRaw) {
4379 PhiNode* phi = base_memory()->as_Phi();
4380 for( uint i = 1; i < phi->req(); ++i ) {// For all paths in
4381 if (phi->in(i) == this) {
4382 phase->is_IterGVN()->_worklist.push(phi);
4383 break;
4384 }
4385 }
4386 }
4387 }
4388
Vladimir Kozlov30dc0ed2008-03-13 16:31:32 -07004389 assert(progress || verify_sparse(), "please, no dups of base");
J. Duke81537792007-12-01 00:00:00 +00004390 return progress;
4391}
4392
4393//-------------------------set_base_memory-------------------------------------
4394void MergeMemNode::set_base_memory(Node *new_base) {
4395 Node* empty_mem = empty_memory();
4396 set_req(Compile::AliasIdxBot, new_base);
4397 assert(memory_at(req()) == new_base, "must set default memory");
4398 // Clear out other occurrences of new_base:
4399 if (new_base != empty_mem) {
4400 for (uint i = Compile::AliasIdxRaw; i < req(); i++) {
4401 if (in(i) == new_base) set_req(i, empty_mem);
4402 }
4403 }
4404}
4405
4406//------------------------------out_RegMask------------------------------------
4407const RegMask &MergeMemNode::out_RegMask() const {
4408 return RegMask::Empty;
4409}
4410
4411//------------------------------dump_spec--------------------------------------
4412#ifndef PRODUCT
4413void MergeMemNode::dump_spec(outputStream *st) const {
4414 st->print(" {");
4415 Node* base_mem = base_memory();
4416 for( uint i = Compile::AliasIdxRaw; i < req(); i++ ) {
Vladimir Ivanov5fd1e542014-12-19 16:42:40 -08004417 Node* mem = (in(i) != NULL) ? memory_at(i) : base_mem;
J. Duke81537792007-12-01 00:00:00 +00004418 if (mem == base_mem) { st->print(" -"); continue; }
4419 st->print( " N%d:", mem->_idx );
4420 Compile::current()->get_adr_type(i)->dump_on(st);
4421 }
4422 st->print(" }");
4423}
4424#endif // !PRODUCT
4425
4426
4427#ifdef ASSERT
4428static bool might_be_same(Node* a, Node* b) {
4429 if (a == b) return true;
4430 if (!(a->is_Phi() || b->is_Phi())) return false;
4431 // phis shift around during optimization
4432 return true; // pretty stupid...
4433}
4434
4435// verify a narrow slice (either incoming or outgoing)
4436static void verify_memory_slice(const MergeMemNode* m, int alias_idx, Node* n) {
4437 if (!VerifyAliases) return; // don't bother to verify unless requested
4438 if (is_error_reported()) return; // muzzle asserts when debugging an error
4439 if (Node::in_dump()) return; // muzzle asserts when printing
4440 assert(alias_idx >= Compile::AliasIdxRaw, "must not disturb base_memory or sentinel");
4441 assert(n != NULL, "");
4442 // Elide intervening MergeMem's
4443 while (n->is_MergeMem()) {
4444 n = n->as_MergeMem()->memory_at(alias_idx);
4445 }
4446 Compile* C = Compile::current();
4447 const TypePtr* n_adr_type = n->adr_type();
4448 if (n == m->empty_memory()) {
4449 // Implicit copy of base_memory()
4450 } else if (n_adr_type != TypePtr::BOTTOM) {
4451 assert(n_adr_type != NULL, "new memory must have a well-defined adr_type");
4452 assert(C->must_alias(n_adr_type, alias_idx), "new memory must match selected slice");
4453 } else {
4454 // A few places like make_runtime_call "know" that VM calls are narrow,
4455 // and can be used to update only the VM bits stored as TypeRawPtr::BOTTOM.
4456 bool expected_wide_mem = false;
4457 if (n == m->base_memory()) {
4458 expected_wide_mem = true;
4459 } else if (alias_idx == Compile::AliasIdxRaw ||
4460 n == m->memory_at(Compile::AliasIdxRaw)) {
4461 expected_wide_mem = true;
4462 } else if (!C->alias_type(alias_idx)->is_rewritable()) {
4463 // memory can "leak through" calls on channels that
4464 // are write-once. Allow this also.
4465 expected_wide_mem = true;
4466 }
4467 assert(expected_wide_mem, "expected narrow slice replacement");
4468 }
4469}
4470#else // !ASSERT
Calvin Cheung53448fd2013-06-13 22:02:40 -07004471#define verify_memory_slice(m,i,n) (void)(0) // PRODUCT version is no-op
J. Duke81537792007-12-01 00:00:00 +00004472#endif
4473
4474
4475//-----------------------------memory_at---------------------------------------
4476Node* MergeMemNode::memory_at(uint alias_idx) const {
4477 assert(alias_idx >= Compile::AliasIdxRaw ||
4478 alias_idx == Compile::AliasIdxBot && Compile::current()->AliasLevel() == 0,
4479 "must avoid base_memory and AliasIdxTop");
4480
4481 // Otherwise, it is a narrow slice.
4482 Node* n = alias_idx < req() ? in(alias_idx) : empty_memory();
4483 Compile *C = Compile::current();
4484 if (is_empty_memory(n)) {
4485 // the array is sparse; empty slots are the "top" node
4486 n = base_memory();
4487 assert(Node::in_dump()
4488 || n == NULL || n->bottom_type() == Type::TOP
Vladimir Kozlovafa5d112011-02-24 10:28:20 -08004489 || n->adr_type() == NULL // address is TOP
J. Duke81537792007-12-01 00:00:00 +00004490 || n->adr_type() == TypePtr::BOTTOM
4491 || n->adr_type() == TypeRawPtr::BOTTOM
4492 || Compile::current()->AliasLevel() == 0,
4493 "must be a wide memory");
4494 // AliasLevel == 0 if we are organizing the memory states manually.
4495 // See verify_memory_slice for comments on TypeRawPtr::BOTTOM.
4496 } else {
4497 // make sure the stored slice is sane
4498 #ifdef ASSERT
4499 if (is_error_reported() || Node::in_dump()) {
4500 } else if (might_be_same(n, base_memory())) {
4501 // Give it a pass: It is a mostly harmless repetition of the base.
4502 // This can arise normally from node subsumption during optimization.
4503 } else {
4504 verify_memory_slice(this, alias_idx, n);
4505 }
4506 #endif
4507 }
4508 return n;
4509}
4510
4511//---------------------------set_memory_at-------------------------------------
4512void MergeMemNode::set_memory_at(uint alias_idx, Node *n) {
4513 verify_memory_slice(this, alias_idx, n);
4514 Node* empty_mem = empty_memory();
4515 if (n == base_memory()) n = empty_mem; // collapse default
4516 uint need_req = alias_idx+1;
4517 if (req() < need_req) {
4518 if (n == empty_mem) return; // already the default, so do not grow me
4519 // grow the sparse array
4520 do {
4521 add_req(empty_mem);
4522 } while (req() < need_req);
4523 }
4524 set_req( alias_idx, n );
4525}
4526
4527
4528
4529//--------------------------iteration_setup------------------------------------
4530void MergeMemNode::iteration_setup(const MergeMemNode* other) {
4531 if (other != NULL) {
4532 grow_to_match(other);
4533 // invariant: the finite support of mm2 is within mm->req()
4534 #ifdef ASSERT
4535 for (uint i = req(); i < other->req(); i++) {
4536 assert(other->is_empty_memory(other->in(i)), "slice left uncovered");
4537 }
4538 #endif
4539 }
4540 // Replace spurious copies of base_memory by top.
4541 Node* base_mem = base_memory();
4542 if (base_mem != NULL && !base_mem->is_top()) {
4543 for (uint i = Compile::AliasIdxBot+1, imax = req(); i < imax; i++) {
4544 if (in(i) == base_mem)
4545 set_req(i, empty_memory());
4546 }
4547 }
4548}
4549
4550//---------------------------grow_to_match-------------------------------------
4551void MergeMemNode::grow_to_match(const MergeMemNode* other) {
4552 Node* empty_mem = empty_memory();
4553 assert(other->is_empty_memory(empty_mem), "consistent sentinels");
4554 // look for the finite support of the other memory
4555 for (uint i = other->req(); --i >= req(); ) {
4556 if (other->in(i) != empty_mem) {
4557 uint new_len = i+1;
4558 while (req() < new_len) add_req(empty_mem);
4559 break;
4560 }
4561 }
4562}
4563
4564//---------------------------verify_sparse-------------------------------------
4565#ifndef PRODUCT
4566bool MergeMemNode::verify_sparse() const {
4567 assert(is_empty_memory(make_empty_memory()), "sane sentinel");
4568 Node* base_mem = base_memory();
4569 // The following can happen in degenerate cases, since empty==top.
4570 if (is_empty_memory(base_mem)) return true;
4571 for (uint i = Compile::AliasIdxRaw; i < req(); i++) {
4572 assert(in(i) != NULL, "sane slice");
4573 if (in(i) == base_mem) return false; // should have been the sentinel value!
4574 }
4575 return true;
4576}
4577
4578bool MergeMemStream::match_memory(Node* mem, const MergeMemNode* mm, int idx) {
4579 Node* n;
4580 n = mm->in(idx);
4581 if (mem == n) return true; // might be empty_memory()
4582 n = (idx == Compile::AliasIdxBot)? mm->base_memory(): mm->memory_at(idx);
4583 if (mem == n) return true;
4584 while (n->is_Phi() && (n = n->as_Phi()->is_copy()) != NULL) {
4585 if (mem == n) return true;
4586 if (n == NULL) break;
4587 }
4588 return false;
4589}
4590#endif // !PRODUCT