Path: blob/master/src/hotspot/share/c1/c1_ValueMap.cpp
40931 views
/*1* Copyright (c) 1999, 2020, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation.7*8* This code is distributed in the hope that it will be useful, but WITHOUT9* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or10* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License11* version 2 for more details (a copy is included in the LICENSE file that12* accompanied this code).13*14* You should have received a copy of the GNU General Public License version15* 2 along with this work; if not, write to the Free Software Foundation,16* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.17*18* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA19* or visit www.oracle.com if you need additional information or have any20* questions.21*22*/2324#include "precompiled.hpp"25#include "c1/c1_Canonicalizer.hpp"26#include "c1/c1_IR.hpp"27#include "c1/c1_ValueMap.hpp"28#include "c1/c1_ValueSet.inline.hpp"29#include "c1/c1_ValueStack.hpp"3031#ifndef PRODUCT3233int ValueMap::_number_of_finds = 0;34int ValueMap::_number_of_hits = 0;35int ValueMap::_number_of_kills = 0;3637#define TRACE_VALUE_NUMBERING(code) if (PrintValueNumbering) { code; }3839#else4041#define TRACE_VALUE_NUMBERING(code)4243#endif444546ValueMap::ValueMap()47: _nesting(0)48, _entries(ValueMapInitialSize, ValueMapInitialSize, NULL)49, _killed_values()50, _entry_count(0)51{52NOT_PRODUCT(reset_statistics());53}545556ValueMap::ValueMap(ValueMap* old)57: _nesting(old->_nesting + 1)58, _entries(old->_entries.length(), old->_entries.length(), NULL)59, _killed_values()60, _entry_count(old->_entry_count)61{62for (int i = size() - 1; i >= 0; i--) {63_entries.at_put(i, old->entry_at(i));64}65_killed_values.set_from(&old->_killed_values);66}676869void ValueMap::increase_table_size() {70int old_size = size();71int new_size = old_size * 2 + 1;7273ValueMapEntryList worklist(8);74ValueMapEntryArray new_entries(new_size, new_size, NULL);75int new_entry_count = 0;7677TRACE_VALUE_NUMBERING(tty->print_cr("increasing table size from %d to %d", old_size, new_size));7879for (int i = old_size - 1; i >= 0; i--) {80ValueMapEntry* entry;81for (entry = entry_at(i); entry != NULL; entry = entry->next()) {82if (!is_killed(entry->value())) {83worklist.push(entry);84}85}8687while (!worklist.is_empty()) {88entry = worklist.pop();89int new_index = entry_index(entry->hash(), new_size);9091if (entry->nesting() != nesting() && new_entries.at(new_index) != entry->next()) {92// changing entries with a lower nesting than the current nesting of the table93// is not allowed because then the same entry is contained in multiple value maps.94// clone entry when next-pointer must be changed95entry = new ValueMapEntry(entry->hash(), entry->value(), entry->nesting(), NULL);96}97entry->set_next(new_entries.at(new_index));98new_entries.at_put(new_index, entry);99new_entry_count++;100}101}102103_entries = new_entries;104_entry_count = new_entry_count;105}106107108Value ValueMap::find_insert(Value x) {109const intx hash = x->hash();110if (hash != 0) {111// 0 hash means: exclude from value numbering112NOT_PRODUCT(_number_of_finds++);113114for (ValueMapEntry* entry = entry_at(entry_index(hash, size())); entry != NULL; entry = entry->next()) {115if (entry->hash() == hash) {116Value f = entry->value();117118if (!is_killed(f) && f->is_equal(x)) {119NOT_PRODUCT(_number_of_hits++);120TRACE_VALUE_NUMBERING(tty->print_cr("Value Numbering: %s %c%d equal to %c%d (size %d, entries %d, nesting-diff %d)", x->name(), x->type()->tchar(), x->id(), f->type()->tchar(), f->id(), size(), entry_count(), nesting() - entry->nesting()));121122if (entry->nesting() != nesting() && f->as_Constant() == NULL) {123// non-constant values of of another block must be pinned,124// otherwise it is possible that they are not evaluated125f->pin(Instruction::PinGlobalValueNumbering);126}127assert(x->type()->tag() == f->type()->tag(), "should have same type");128129return f;130131}132}133}134135// x not found, so insert it136if (entry_count() >= size_threshold()) {137increase_table_size();138}139int idx = entry_index(hash, size());140_entries.at_put(idx, new ValueMapEntry(hash, x, nesting(), entry_at(idx)));141_entry_count++;142143TRACE_VALUE_NUMBERING(tty->print_cr("Value Numbering: insert %s %c%d (size %d, entries %d, nesting %d)", x->name(), x->type()->tchar(), x->id(), size(), entry_count(), nesting()));144}145146return x;147}148149150#define GENERIC_KILL_VALUE(must_kill_implementation) \151NOT_PRODUCT(_number_of_kills++); \152\153for (int i = size() - 1; i >= 0; i--) { \154ValueMapEntry* prev_entry = NULL; \155for (ValueMapEntry* entry = entry_at(i); entry != NULL; entry = entry->next()) { \156Value value = entry->value(); \157\158must_kill_implementation(must_kill, entry, value) \159\160if (must_kill) { \161kill_value(value); \162\163if (prev_entry == NULL) { \164_entries.at_put(i, entry->next()); \165_entry_count--; \166} else if (prev_entry->nesting() == nesting()) { \167prev_entry->set_next(entry->next()); \168_entry_count--; \169} else { \170prev_entry = entry; \171} \172\173TRACE_VALUE_NUMBERING(tty->print_cr("Value Numbering: killed %s %c%d (size %d, entries %d, nesting-diff %d)", value->name(), value->type()->tchar(), value->id(), size(), entry_count(), nesting() - entry->nesting())); \174} else { \175prev_entry = entry; \176} \177} \178} \179180#define MUST_KILL_MEMORY(must_kill, entry, value) \181bool must_kill = value->as_LoadField() != NULL || value->as_LoadIndexed() != NULL;182183#define MUST_KILL_ARRAY(must_kill, entry, value) \184bool must_kill = value->as_LoadIndexed() != NULL \185&& value->type()->tag() == type->tag();186187#define MUST_KILL_FIELD(must_kill, entry, value) \188/* ciField's are not unique; must compare their contents */ \189LoadField* lf = value->as_LoadField(); \190bool must_kill = lf != NULL \191&& lf->field()->holder() == field->holder() \192&& (all_offsets || lf->field()->offset() == field->offset());193194195void ValueMap::kill_memory() {196GENERIC_KILL_VALUE(MUST_KILL_MEMORY);197}198199void ValueMap::kill_array(ValueType* type) {200GENERIC_KILL_VALUE(MUST_KILL_ARRAY);201}202203void ValueMap::kill_field(ciField* field, bool all_offsets) {204GENERIC_KILL_VALUE(MUST_KILL_FIELD);205}206207void ValueMap::kill_map(ValueMap* map) {208assert(is_global_value_numbering(), "only for global value numbering");209_killed_values.set_union(&map->_killed_values);210}211212void ValueMap::kill_all() {213assert(is_local_value_numbering(), "only for local value numbering");214for (int i = size() - 1; i >= 0; i--) {215_entries.at_put(i, NULL);216}217_entry_count = 0;218}219220221#ifndef PRODUCT222223void ValueMap::print() {224tty->print_cr("(size %d, entries %d, nesting %d)", size(), entry_count(), nesting());225226int entries = 0;227for (int i = 0; i < size(); i++) {228if (entry_at(i) != NULL) {229tty->print(" %2d: ", i);230for (ValueMapEntry* entry = entry_at(i); entry != NULL; entry = entry->next()) {231Value value = entry->value();232tty->print("%s %c%d (%s%d) -> ", value->name(), value->type()->tchar(), value->id(), is_killed(value) ? "x" : "", entry->nesting());233entries++;234}235tty->print_cr("NULL");236}237}238239_killed_values.print();240assert(entry_count() == entries, "entry_count incorrect");241}242243void ValueMap::reset_statistics() {244_number_of_finds = 0;245_number_of_hits = 0;246_number_of_kills = 0;247}248249void ValueMap::print_statistics() {250float hit_rate = 0;251if (_number_of_finds != 0) {252hit_rate = (float)_number_of_hits / _number_of_finds;253}254255tty->print_cr("finds:%3d hits:%3d kills:%3d hit rate: %1.4f", _number_of_finds, _number_of_hits, _number_of_kills, hit_rate);256}257258#endif259260261262class ShortLoopOptimizer : public ValueNumberingVisitor {263private:264GlobalValueNumbering* _gvn;265BlockList _loop_blocks;266bool _too_complicated_loop;267bool _has_field_store[T_VOID];268bool _has_indexed_store[T_VOID];269270// simplified access to methods of GlobalValueNumbering271ValueMap* current_map() { return _gvn->current_map(); }272ValueMap* value_map_of(BlockBegin* block) { return _gvn->value_map_of(block); }273274// implementation for abstract methods of ValueNumberingVisitor275void kill_memory() { _too_complicated_loop = true; }276void kill_field(ciField* field, bool all_offsets) {277current_map()->kill_field(field, all_offsets);278assert(field->type()->basic_type() >= 0 && field->type()->basic_type() < T_VOID, "Invalid type");279_has_field_store[field->type()->basic_type()] = true;280}281void kill_array(ValueType* type) {282current_map()->kill_array(type);283BasicType basic_type = as_BasicType(type); assert(basic_type >= 0 && basic_type < T_VOID, "Invalid type");284_has_indexed_store[basic_type] = true;285}286287public:288ShortLoopOptimizer(GlobalValueNumbering* gvn)289: _gvn(gvn)290, _loop_blocks(ValueMapMaxLoopSize)291, _too_complicated_loop(false)292{293for (int i = 0; i < T_VOID; i++) {294_has_field_store[i] = false;295_has_indexed_store[i] = false;296}297}298299bool has_field_store(BasicType type) {300assert(type >= 0 && type < T_VOID, "Invalid type");301return _has_field_store[type];302}303304bool has_indexed_store(BasicType type) {305assert(type >= 0 && type < T_VOID, "Invalid type");306return _has_indexed_store[type];307}308309bool process(BlockBegin* loop_header);310};311312class LoopInvariantCodeMotion : public StackObj {313private:314GlobalValueNumbering* _gvn;315ShortLoopOptimizer* _short_loop_optimizer;316Instruction* _insertion_point;317ValueStack * _state;318bool _insert_is_pred;319320bool is_invariant(Value v) const { return _gvn->is_processed(v); }321322void process_block(BlockBegin* block);323324public:325LoopInvariantCodeMotion(ShortLoopOptimizer *slo, GlobalValueNumbering* gvn, BlockBegin* loop_header, BlockList* loop_blocks);326};327328LoopInvariantCodeMotion::LoopInvariantCodeMotion(ShortLoopOptimizer *slo, GlobalValueNumbering* gvn, BlockBegin* loop_header, BlockList* loop_blocks)329: _gvn(gvn), _short_loop_optimizer(slo), _insertion_point(NULL), _state(NULL), _insert_is_pred(false) {330331TRACE_VALUE_NUMBERING(tty->print_cr("using loop invariant code motion loop_header = %d", loop_header->block_id()));332TRACE_VALUE_NUMBERING(tty->print_cr("** loop invariant code motion for short loop B%d", loop_header->block_id()));333334BlockBegin* insertion_block = loop_header->dominator();335if (insertion_block->number_of_preds() == 0) {336return; // only the entry block does not have a predecessor337}338339assert(insertion_block->end()->as_Base() == NULL, "cannot insert into entry block");340_insertion_point = insertion_block->end()->prev();341_insert_is_pred = loop_header->is_predecessor(insertion_block);342343BlockEnd *block_end = insertion_block->end();344_state = block_end->state_before();345346if (!_state) {347// If, TableSwitch and LookupSwitch always have state_before when348// loop invariant code motion happens..349assert(block_end->as_Goto(), "Block has to be goto");350_state = block_end->state();351}352353// the loop_blocks are filled by going backward from the loop header, so this processing order is best354assert(loop_blocks->at(0) == loop_header, "loop header must be first loop block");355process_block(loop_header);356for (int i = loop_blocks->length() - 1; i >= 1; i--) {357process_block(loop_blocks->at(i));358}359}360361void LoopInvariantCodeMotion::process_block(BlockBegin* block) {362TRACE_VALUE_NUMBERING(tty->print_cr("processing block B%d", block->block_id()));363364Instruction* prev = block;365Instruction* cur = block->next();366367while (cur != NULL) {368// determine if cur instruction is loop invariant369// only selected instruction types are processed here370bool cur_invariant = false;371372if (cur->as_Constant() != NULL) {373cur_invariant = !cur->can_trap();374} else if (cur->as_ArithmeticOp() != NULL || cur->as_LogicOp() != NULL || cur->as_ShiftOp() != NULL) {375assert(cur->as_Op2() != NULL, "must be Op2");376Op2* op2 = (Op2*)cur;377cur_invariant = !op2->can_trap() && is_invariant(op2->x()) && is_invariant(op2->y());378} else if (cur->as_LoadField() != NULL) {379LoadField* lf = (LoadField*)cur;380// deoptimizes on NullPointerException381cur_invariant = !lf->needs_patching() && !lf->field()->is_volatile() && !_short_loop_optimizer->has_field_store(lf->field()->type()->basic_type()) && is_invariant(lf->obj()) && _insert_is_pred;382} else if (cur->as_ArrayLength() != NULL) {383ArrayLength *length = cur->as_ArrayLength();384cur_invariant = is_invariant(length->array());385} else if (cur->as_LoadIndexed() != NULL) {386LoadIndexed *li = (LoadIndexed *)cur->as_LoadIndexed();387cur_invariant = !_short_loop_optimizer->has_indexed_store(as_BasicType(cur->type())) && is_invariant(li->array()) && is_invariant(li->index()) && _insert_is_pred;388} else if (cur->as_NegateOp() != NULL) {389NegateOp* neg = (NegateOp*)cur->as_NegateOp();390cur_invariant = is_invariant(neg->x());391} else if (cur->as_Convert() != NULL) {392Convert* cvt = (Convert*)cur->as_Convert();393cur_invariant = is_invariant(cvt->value());394}395396if (cur_invariant) {397// perform value numbering and mark instruction as loop-invariant398_gvn->substitute(cur);399400if (cur->as_Constant() == NULL) {401// ensure that code for non-constant instructions is always generated402cur->pin();403}404405// remove cur instruction from loop block and append it to block before loop406Instruction* next = cur->next();407Instruction* in = _insertion_point->next();408_insertion_point = _insertion_point->set_next(cur);409cur->set_next(in);410411// Deoptimize on exception412cur->set_flag(Instruction::DeoptimizeOnException, true);413414// Clear exception handlers415cur->set_exception_handlers(NULL);416417TRACE_VALUE_NUMBERING(tty->print_cr("Instruction %c%d is loop invariant", cur->type()->tchar(), cur->id()));418TRACE_VALUE_NUMBERING(cur->print_line());419420if (cur->state_before() != NULL) {421cur->set_state_before(_state->copy());422}423if (cur->exception_state() != NULL) {424cur->set_exception_state(_state->copy());425}426427cur = prev->set_next(next);428} else {429prev = cur;430cur = cur->next();431}432}433}434435bool ShortLoopOptimizer::process(BlockBegin* loop_header) {436TRACE_VALUE_NUMBERING(tty->print_cr("** loop header block"));437438_too_complicated_loop = false;439_loop_blocks.clear();440_loop_blocks.append(loop_header);441442for (int i = 0; i < _loop_blocks.length(); i++) {443BlockBegin* block = _loop_blocks.at(i);444TRACE_VALUE_NUMBERING(tty->print_cr("processing loop block B%d", block->block_id()));445446if (block->is_set(BlockBegin::exception_entry_flag)) {447// this would be too complicated448return false;449}450451// add predecessors to worklist452for (int j = block->number_of_preds() - 1; j >= 0; j--) {453BlockBegin* pred = block->pred_at(j);454455if (pred->is_set(BlockBegin::osr_entry_flag)) {456return false;457}458459ValueMap* pred_map = value_map_of(pred);460if (pred_map != NULL) {461current_map()->kill_map(pred_map);462} else if (!_loop_blocks.contains(pred)) {463if (_loop_blocks.length() >= ValueMapMaxLoopSize) {464return false;465}466_loop_blocks.append(pred);467}468}469470// use the instruction visitor for killing values471for (Value instr = block->next(); instr != NULL; instr = instr->next()) {472instr->visit(this);473if (_too_complicated_loop) {474return false;475}476}477}478479bool optimistic = this->_gvn->compilation()->is_optimistic();480481if (UseLoopInvariantCodeMotion && optimistic) {482LoopInvariantCodeMotion code_motion(this, _gvn, loop_header, &_loop_blocks);483}484485TRACE_VALUE_NUMBERING(tty->print_cr("** loop successfully optimized"));486return true;487}488489490GlobalValueNumbering::GlobalValueNumbering(IR* ir)491: _compilation(ir->compilation())492, _current_map(NULL)493, _value_maps(ir->linear_scan_order()->length(), ir->linear_scan_order()->length(), NULL)494, _has_substitutions(false)495{496TRACE_VALUE_NUMBERING(tty->print_cr("****** start of global value numbering"));497498ShortLoopOptimizer short_loop_optimizer(this);499500BlockList* blocks = ir->linear_scan_order();501int num_blocks = blocks->length();502503BlockBegin* start_block = blocks->at(0);504assert(start_block == ir->start() && start_block->number_of_preds() == 0 && start_block->dominator() == NULL, "must be start block");505assert(start_block->next()->as_Base() != NULL && start_block->next()->next() == NULL, "start block must not have instructions");506507// method parameters are not linked in instructions list, so process them separateley508for_each_state_value(start_block->state(), value,509assert(value->as_Local() != NULL, "only method parameters allowed");510set_processed(value);511);512513// initial, empty value map with nesting 0514set_value_map_of(start_block, new ValueMap());515516for (int i = 1; i < num_blocks; i++) {517BlockBegin* block = blocks->at(i);518TRACE_VALUE_NUMBERING(tty->print_cr("**** processing block B%d", block->block_id()));519520int num_preds = block->number_of_preds();521assert(num_preds > 0, "block must have predecessors");522523BlockBegin* dominator = block->dominator();524assert(dominator != NULL, "dominator must exist");525assert(value_map_of(dominator) != NULL, "value map of dominator must exist");526527// create new value map with increased nesting528_current_map = new ValueMap(value_map_of(dominator));529530if (num_preds == 1 && !block->is_set(BlockBegin::exception_entry_flag)) {531assert(dominator == block->pred_at(0), "dominator must be equal to predecessor");532// nothing to do here533534} else if (block->is_set(BlockBegin::linear_scan_loop_header_flag)) {535// block has incoming backward branches -> try to optimize short loops536if (!short_loop_optimizer.process(block)) {537// loop is too complicated, so kill all memory loads because there might be538// stores to them in the loop539current_map()->kill_memory();540}541542} else {543// only incoming forward branches that are already processed544for (int j = 0; j < num_preds; j++) {545BlockBegin* pred = block->pred_at(j);546ValueMap* pred_map = value_map_of(pred);547548if (pred_map != NULL) {549// propagate killed values of the predecessor to this block550current_map()->kill_map(value_map_of(pred));551} else {552// kill all memory loads because predecessor not yet processed553// (this can happen with non-natural loops and OSR-compiles)554current_map()->kill_memory();555}556}557}558559// phi functions are not linked in instructions list, so process them separateley560for_each_phi_fun(block, phi,561set_processed(phi);562);563564TRACE_VALUE_NUMBERING(tty->print("value map before processing block: "); current_map()->print());565566// visit all instructions of this block567for (Value instr = block->next(); instr != NULL; instr = instr->next()) {568// check if instruction kills any values569instr->visit(this);570// perform actual value numbering571substitute(instr);572}573574// remember value map for successors575set_value_map_of(block, current_map());576}577578if (_has_substitutions) {579SubstitutionResolver resolver(ir);580}581582TRACE_VALUE_NUMBERING(tty->print("****** end of global value numbering. "); ValueMap::print_statistics());583}584585void GlobalValueNumbering::substitute(Instruction* instr) {586assert(!instr->has_subst(), "substitution already set");587Value subst = current_map()->find_insert(instr);588if (subst != instr) {589assert(!subst->has_subst(), "can't have a substitution");590591TRACE_VALUE_NUMBERING(tty->print_cr("substitution for %c%d set to %c%d", instr->type()->tchar(), instr->id(), subst->type()->tchar(), subst->id()));592instr->set_subst(subst);593_has_substitutions = true;594}595set_processed(instr);596}597598599