duke@435: /* duke@435: * Copyright 1997-2004 Sun Microsystems, Inc. All Rights Reserved. duke@435: * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. duke@435: * duke@435: * This code is free software; you can redistribute it and/or modify it duke@435: * under the terms of the GNU General Public License version 2 only, as duke@435: * published by the Free Software Foundation. duke@435: * duke@435: * This code is distributed in the hope that it will be useful, but WITHOUT duke@435: * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or duke@435: * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License duke@435: * version 2 for more details (a copy is included in the LICENSE file that duke@435: * accompanied this code). duke@435: * duke@435: * You should have received a copy of the GNU General Public License version duke@435: * 2 along with this work; if not, write to the Free Software Foundation, duke@435: * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. duke@435: * duke@435: * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, duke@435: * CA 95054 USA or visit www.sun.com if you need additional information or duke@435: * have any questions. duke@435: * duke@435: */ duke@435: duke@435: // DFA.CPP - Method definitions for outputting the matcher DFA from ADLC duke@435: #include "adlc.hpp" duke@435: duke@435: //---------------------------Switches for debugging output--------------------- duke@435: static bool debug_output = false; duke@435: static bool debug_output1 = false; // top level chain rules duke@435: duke@435: //---------------------------Access to internals of class State---------------- duke@435: static const char *sLeft = "_kids[0]"; duke@435: static const char *sRight = "_kids[1]"; duke@435: duke@435: //---------------------------DFA productions----------------------------------- duke@435: static const char *dfa_production = "DFA_PRODUCTION"; duke@435: static const char *dfa_production_set_valid = "DFA_PRODUCTION__SET_VALID"; duke@435: duke@435: //---------------------------Production State---------------------------------- duke@435: static const char *knownInvalid = "knownInvalid"; // The result does NOT have a rule defined duke@435: static const char *knownValid = "knownValid"; // The result must be produced by a rule duke@435: static const char *unknownValid = "unknownValid"; // Unknown (probably due to a child or predicate constraint) duke@435: duke@435: static const char *noConstraint = "noConstraint"; // No constraints seen so far duke@435: static const char *hasConstraint = "hasConstraint"; // Within the first constraint duke@435: duke@435: duke@435: //------------------------------Production------------------------------------ duke@435: // Track the status of productions for a particular result duke@435: class Production { duke@435: public: duke@435: const char *_result; duke@435: const char *_constraint; duke@435: const char *_valid; duke@435: Expr *_cost_lb; // Cost lower bound for this production duke@435: Expr *_cost_ub; // Cost upper bound for this production duke@435: duke@435: public: duke@435: Production(const char *result, const char *constraint, const char *valid); duke@435: ~Production() {}; duke@435: duke@435: void initialize(); // reset to be an empty container duke@435: duke@435: const char *valid() const { return _valid; } duke@435: Expr *cost_lb() const { return (Expr *)_cost_lb; } duke@435: Expr *cost_ub() const { return (Expr *)_cost_ub; } duke@435: duke@435: void print(); duke@435: }; duke@435: duke@435: duke@435: //------------------------------ProductionState-------------------------------- duke@435: // Track the status of all production rule results duke@435: // Reset for each root opcode (e.g., Op_RegI, Op_AddI, ...) duke@435: class ProductionState { duke@435: private: duke@435: Dict _production; // map result of production, char*, to information or NULL duke@435: const char *_constraint; duke@435: duke@435: public: duke@435: // cmpstr does string comparisions. hashstr computes a key. duke@435: ProductionState(Arena *arena) : _production(cmpstr, hashstr, arena) { initialize(); }; duke@435: ~ProductionState() { }; duke@435: duke@435: void initialize(); // reset local and dictionary state duke@435: duke@435: const char *constraint(); duke@435: void set_constraint(const char *constraint); // currently working inside of constraints duke@435: duke@435: const char *valid(const char *result); // unknownValid, or status for this production duke@435: void set_valid(const char *result); // if not constrained, set status to knownValid duke@435: duke@435: Expr *cost_lb(const char *result); duke@435: Expr *cost_ub(const char *result); duke@435: void set_cost_bounds(const char *result, const Expr *cost, bool has_state_check, bool has_cost_check); duke@435: duke@435: // Return the Production associated with the result, duke@435: // or create a new Production and insert it into the dictionary. duke@435: Production *getProduction(const char *result); duke@435: duke@435: void print(); duke@435: duke@435: private: duke@435: // Disable public use of constructor, copy-ctor, ... duke@435: ProductionState( ) : _production(cmpstr, hashstr, Form::arena) { assert( false, "NotImplemented"); }; duke@435: ProductionState( const ProductionState & ) : _production(cmpstr, hashstr, Form::arena) { assert( false, "NotImplemented"); }; // Deep-copy duke@435: }; duke@435: duke@435: duke@435: //---------------------------Helper Functions---------------------------------- duke@435: // cost_check template: duke@435: // 1) if (STATE__NOT_YET_VALID(EBXREGI) || _cost[EBXREGI] > c) { duke@435: // 2) DFA_PRODUCTION__SET_VALID(EBXREGI, cmovI_memu_rule, c) duke@435: // 3) } duke@435: // duke@435: static void cost_check(FILE *fp, const char *spaces, duke@435: const char *arrayIdx, const Expr *cost, const char *rule, ProductionState &status) { duke@435: bool state_check = false; // true if this production needs to check validity duke@435: bool cost_check = false; // true if this production needs to check cost duke@435: bool cost_is_above_upper_bound = false; // true if this production is unnecessary due to high cost duke@435: bool cost_is_below_lower_bound = false; // true if this production replaces a higher cost production duke@435: duke@435: // Get information about this production duke@435: const Expr *previous_ub = status.cost_ub(arrayIdx); duke@435: if( !previous_ub->is_unknown() ) { duke@435: if( previous_ub->less_than_or_equal(cost) ) { duke@435: cost_is_above_upper_bound = true; duke@435: if( debug_output ) { fprintf(fp, "// Previous rule with lower cost than: %s === %s_rule costs %s\n", arrayIdx, rule, cost->as_string()); } duke@435: } duke@435: } duke@435: duke@435: const Expr *previous_lb = status.cost_lb(arrayIdx); duke@435: if( !previous_lb->is_unknown() ) { duke@435: if( cost->less_than_or_equal(previous_lb) ) { duke@435: cost_is_below_lower_bound = true; duke@435: if( debug_output ) { fprintf(fp, "// Previous rule with higher cost\n"); } duke@435: } duke@435: } duke@435: duke@435: // line 1) duke@435: // Check for validity and compare to other match costs duke@435: const char *validity_check = status.valid(arrayIdx); duke@435: if( validity_check == unknownValid ) { duke@435: fprintf(fp, "%sif (STATE__NOT_YET_VALID(%s) || _cost[%s] > %s) {\n", spaces, arrayIdx, arrayIdx, cost->as_string()); duke@435: state_check = true; duke@435: cost_check = true; duke@435: } duke@435: else if( validity_check == knownInvalid ) { duke@435: if( debug_output ) { fprintf(fp, "%s// %s KNOWN_INVALID \n", spaces, arrayIdx); } duke@435: } duke@435: else if( validity_check == knownValid ) { duke@435: if( cost_is_above_upper_bound ) { duke@435: // production cost is known to be too high. duke@435: return; duke@435: } else if( cost_is_below_lower_bound ) { duke@435: // production will unconditionally overwrite a previous production that had higher cost duke@435: } else { duke@435: fprintf(fp, "%sif ( /* %s KNOWN_VALID || */ _cost[%s] > %s) {\n", spaces, arrayIdx, arrayIdx, cost->as_string()); duke@435: cost_check = true; duke@435: } duke@435: } duke@435: duke@435: // line 2) duke@435: // no need to set State vector if our state is knownValid duke@435: const char *production = (validity_check == knownValid) ? dfa_production : dfa_production_set_valid; duke@435: fprintf(fp, "%s %s(%s, %s_rule, %s)", spaces, production, arrayIdx, rule, cost->as_string() ); duke@435: if( validity_check == knownValid ) { duke@435: if( cost_is_below_lower_bound ) { fprintf(fp, "\t // overwrites higher cost rule"); } duke@435: } duke@435: fprintf(fp, "\n"); duke@435: duke@435: // line 3) duke@435: if( cost_check || state_check ) { duke@435: fprintf(fp, "%s}\n", spaces); duke@435: } duke@435: duke@435: status.set_cost_bounds(arrayIdx, cost, state_check, cost_check); duke@435: duke@435: // Update ProductionState duke@435: if( validity_check != knownValid ) { duke@435: // set State vector if not previously known duke@435: status.set_valid(arrayIdx); duke@435: } duke@435: } duke@435: duke@435: duke@435: //---------------------------child_test---------------------------------------- duke@435: // Example: duke@435: // STATE__VALID_CHILD(_kids[0], FOO) && STATE__VALID_CHILD(_kids[1], BAR) duke@435: // Macro equivalent to: _kids[0]->valid(FOO) && _kids[1]->valid(BAR) duke@435: // duke@435: static void child_test(FILE *fp, MatchList &mList) { duke@435: if( mList._lchild ) // If left child, check it duke@435: fprintf(fp, "STATE__VALID_CHILD(_kids[0], %s)", ArchDesc::getMachOperEnum(mList._lchild)); duke@435: if( mList._lchild && mList._rchild ) // If both, add the "&&" duke@435: fprintf(fp, " && " ); duke@435: if( mList._rchild ) // If right child, check it duke@435: fprintf(fp, "STATE__VALID_CHILD(_kids[1], %s)", ArchDesc::getMachOperEnum(mList._rchild)); duke@435: } duke@435: duke@435: //---------------------------calc_cost----------------------------------------- duke@435: // Example: duke@435: // unsigned int c = _kids[0]->_cost[FOO] + _kids[1]->_cost[BAR] + 5; duke@435: // duke@435: Expr *ArchDesc::calc_cost(FILE *fp, const char *spaces, MatchList &mList, ProductionState &status) { duke@435: fprintf(fp, "%sunsigned int c = ", spaces); duke@435: Expr *c = new Expr("0"); duke@435: if (mList._lchild ) { // If left child, add it in duke@435: sprintf(Expr::buffer(), "_kids[0]->_cost[%s]", ArchDesc::getMachOperEnum(mList._lchild)); duke@435: c->add(Expr::buffer()); duke@435: } duke@435: if (mList._rchild) { // If right child, add it in duke@435: sprintf(Expr::buffer(), "_kids[1]->_cost[%s]", ArchDesc::getMachOperEnum(mList._rchild)); duke@435: c->add(Expr::buffer()); duke@435: } duke@435: // Add in cost of this rule duke@435: const char *mList_cost = mList.get_cost(); duke@435: c->add(mList_cost, *this); duke@435: duke@435: fprintf(fp, "%s;\n", c->as_string()); duke@435: c->set_external_name("c"); duke@435: return c; duke@435: } duke@435: duke@435: duke@435: //---------------------------gen_match----------------------------------------- duke@435: void ArchDesc::gen_match(FILE *fp, MatchList &mList, ProductionState &status, Dict &operands_chained_from) { duke@435: const char *spaces4 = " "; duke@435: const char *spaces6 = " "; duke@435: duke@435: fprintf(fp, "%s", spaces4); duke@435: // Only generate child tests if this is not a leaf node duke@435: bool has_child_constraints = mList._lchild || mList._rchild; duke@435: const char *predicate_test = mList.get_pred(); duke@435: if( has_child_constraints || predicate_test ) { duke@435: // Open the child-and-predicate-test braces duke@435: fprintf(fp, "if( "); duke@435: status.set_constraint(hasConstraint); duke@435: child_test(fp, mList); duke@435: // Only generate predicate test if one exists for this match duke@435: if( predicate_test ) { duke@435: if( has_child_constraints ) { fprintf(fp," &&\n"); } duke@435: fprintf(fp, "%s %s", spaces6, predicate_test); duke@435: } duke@435: // End of outer tests duke@435: fprintf(fp," ) "); duke@435: } else { duke@435: // No child or predicate test needed duke@435: status.set_constraint(noConstraint); duke@435: } duke@435: duke@435: // End of outer tests duke@435: fprintf(fp,"{\n"); duke@435: duke@435: // Calculate cost of this match duke@435: const Expr *cost = calc_cost(fp, spaces6, mList, status); duke@435: // Check against other match costs, and update cost & rule vectors duke@435: cost_check(fp, spaces6, ArchDesc::getMachOperEnum(mList._resultStr), cost, mList._opcode, status); duke@435: duke@435: // If this is a member of an operand class, update the class cost & rule duke@435: expand_opclass( fp, spaces6, cost, mList._resultStr, status); duke@435: duke@435: // Check if this rule should be used to generate the chains as well. duke@435: const char *rule = /* set rule to "Invalid" for internal operands */ duke@435: strcmp(mList._opcode,mList._resultStr) ? mList._opcode : "Invalid"; duke@435: duke@435: // If this rule produces an operand which has associated chain rules, duke@435: // update the operands with the chain rule + this rule cost & this rule. duke@435: chain_rule(fp, spaces6, mList._resultStr, cost, rule, operands_chained_from, status); duke@435: duke@435: // Close the child-and-predicate-test braces duke@435: fprintf(fp, " }\n"); duke@435: duke@435: } duke@435: duke@435: duke@435: //---------------------------expand_opclass------------------------------------ duke@435: // Chain from one result_type to all other members of its operand class duke@435: void ArchDesc::expand_opclass(FILE *fp, const char *indent, const Expr *cost, duke@435: const char *result_type, ProductionState &status) { duke@435: const Form *form = _globalNames[result_type]; duke@435: OperandForm *op = form ? form->is_operand() : NULL; duke@435: if( op && op->_classes.count() > 0 ) { duke@435: if( debug_output ) { fprintf(fp, "// expand operand classes for operand: %s \n", (char *)op->_ident ); } // %%%%% Explanation duke@435: // Iterate through all operand classes which include this operand duke@435: op->_classes.reset(); duke@435: const char *oclass; duke@435: // Expr *cCost = new Expr(cost); duke@435: while( (oclass = op->_classes.iter()) != NULL ) duke@435: // Check against other match costs, and update cost & rule vectors duke@435: cost_check(fp, indent, ArchDesc::getMachOperEnum(oclass), cost, result_type, status); duke@435: } duke@435: } duke@435: duke@435: //---------------------------chain_rule---------------------------------------- duke@435: // Starting at 'operand', check if we know how to automatically generate other results duke@435: void ArchDesc::chain_rule(FILE *fp, const char *indent, const char *operand, duke@435: const Expr *icost, const char *irule, Dict &operands_chained_from, ProductionState &status) { duke@435: duke@435: // Check if we have already generated chains from this starting point duke@435: if( operands_chained_from[operand] != NULL ) { duke@435: return; duke@435: } else { duke@435: operands_chained_from.Insert( operand, operand); duke@435: } duke@435: if( debug_output ) { fprintf(fp, "// chain rules starting from: %s and %s \n", (char *)operand, (char *)irule); } // %%%%% Explanation duke@435: duke@435: ChainList *lst = (ChainList *)_chainRules[operand]; duke@435: if (lst) { duke@435: // printf("\nChain from <%s> at cost #%s\n",operand, icost ? icost : "_"); duke@435: const char *result, *cost, *rule; duke@435: for(lst->reset(); (lst->iter(result,cost,rule)) == true; ) { duke@435: // Do not generate operands that are already available duke@435: if( operands_chained_from[result] != NULL ) { duke@435: continue; duke@435: } else { duke@435: // Compute the cost for previous match + chain_rule_cost duke@435: // total_cost = icost + cost; duke@435: Expr *total_cost = icost->clone(); // icost + cost duke@435: total_cost->add(cost, *this); duke@435: duke@435: // Check for transitive chain rules duke@435: Form *form = (Form *)_globalNames[rule]; duke@435: if ( ! form->is_instruction()) { duke@435: // printf(" result=%s cost=%s rule=%s\n", result, total_cost, rule); duke@435: // Check against other match costs, and update cost & rule vectors duke@435: const char *reduce_rule = strcmp(irule,"Invalid") ? irule : rule; duke@435: cost_check(fp, indent, ArchDesc::getMachOperEnum(result), total_cost, reduce_rule, status); duke@435: chain_rule(fp, indent, result, total_cost, irule, operands_chained_from, status); duke@435: } else { duke@435: // printf(" result=%s cost=%s rule=%s\n", result, total_cost, rule); duke@435: // Check against other match costs, and update cost & rule vectors duke@435: cost_check(fp, indent, ArchDesc::getMachOperEnum(result), total_cost, rule, status); duke@435: chain_rule(fp, indent, result, total_cost, rule, operands_chained_from, status); duke@435: } duke@435: duke@435: // If this is a member of an operand class, update class cost & rule duke@435: expand_opclass( fp, indent, total_cost, result, status ); duke@435: } duke@435: } duke@435: } duke@435: } duke@435: duke@435: //---------------------------prune_matchlist----------------------------------- duke@435: // Check for duplicate entries in a matchlist, and prune out the higher cost duke@435: // entry. duke@435: void ArchDesc::prune_matchlist(Dict &minimize, MatchList &mlist) { duke@435: duke@435: } duke@435: duke@435: //---------------------------buildDFA------------------------------------------ duke@435: // DFA is a large switch with case statements for each ideal opcode encountered duke@435: // in any match rule in the ad file. Each case has a series of if's to handle duke@435: // the match or fail decisions. The matches test the cost function of that duke@435: // rule, and prune any cases which are higher cost for the same reduction. duke@435: // In order to generate the DFA we walk the table of ideal opcode/MatchList duke@435: // pairs generated by the ADLC front end to build the contents of the case duke@435: // statements (a series of if statements). duke@435: void ArchDesc::buildDFA(FILE* fp) { duke@435: int i; duke@435: // Remember operands that are the starting points for chain rules. duke@435: // Prevent cycles by checking if we have already generated chain. duke@435: Dict operands_chained_from(cmpstr, hashstr, Form::arena); duke@435: duke@435: // Hash inputs to match rules so that final DFA contains only one entry for duke@435: // each match pattern which is the low cost entry. duke@435: Dict minimize(cmpstr, hashstr, Form::arena); duke@435: duke@435: // Track status of dfa for each resulting production duke@435: // reset for each ideal root. duke@435: ProductionState status(Form::arena); duke@435: duke@435: // Output the start of the DFA method into the output file duke@435: duke@435: fprintf(fp, "\n"); duke@435: fprintf(fp, "//------------------------- Source -----------------------------------------\n"); duke@435: // Do not put random source code into the DFA. duke@435: // If there are constants which need sharing, put them in "source_hpp" forms. duke@435: // _source.output(fp); duke@435: fprintf(fp, "\n"); duke@435: fprintf(fp, "//------------------------- Attributes -------------------------------------\n"); duke@435: _attributes.output(fp); duke@435: fprintf(fp, "\n"); duke@435: fprintf(fp, "//------------------------- Macros -----------------------------------------\n"); duke@435: // #define DFA_PRODUCTION(result, rule, cost)\ duke@435: // _cost[ (result) ] = cost; _rule[ (result) ] = rule; duke@435: fprintf(fp, "#define %s(result, rule, cost)\\\n", dfa_production); duke@435: fprintf(fp, " _cost[ (result) ] = cost; _rule[ (result) ] = rule;\n"); duke@435: fprintf(fp, "\n"); duke@435: duke@435: // #define DFA_PRODUCTION__SET_VALID(result, rule, cost)\ duke@435: // DFA_PRODUCTION( (result), (rule), (cost) ); STATE__SET_VALID( (result) ); duke@435: fprintf(fp, "#define %s(result, rule, cost)\\\n", dfa_production_set_valid); duke@435: fprintf(fp, " %s( (result), (rule), (cost) ); STATE__SET_VALID( (result) );\n", dfa_production); duke@435: fprintf(fp, "\n"); duke@435: duke@435: fprintf(fp, "//------------------------- DFA --------------------------------------------\n"); duke@435: duke@435: fprintf(fp, duke@435: "// DFA is a large switch with case statements for each ideal opcode encountered\n" duke@435: "// in any match rule in the ad file. Each case has a series of if's to handle\n" duke@435: "// the match or fail decisions. The matches test the cost function of that\n" duke@435: "// rule, and prune any cases which are higher cost for the same reduction.\n" duke@435: "// In order to generate the DFA we walk the table of ideal opcode/MatchList\n" duke@435: "// pairs generated by the ADLC front end to build the contents of the case\n" duke@435: "// statements (a series of if statements).\n" duke@435: ); duke@435: fprintf(fp, "\n"); duke@435: fprintf(fp, "\n"); duke@435: if (_dfa_small) { duke@435: // Now build the individual routines just like the switch entries in large version duke@435: // Iterate over the table of MatchLists, start at first valid opcode of 1 duke@435: for (i = 1; i < _last_opcode; i++) { duke@435: if (_mlistab[i] == NULL) continue; duke@435: // Generate the routine header statement for this opcode duke@435: fprintf(fp, "void State::_sub_Op_%s(const Node *n){\n", NodeClassNames[i]); duke@435: // Generate body. Shared for both inline and out-of-line version duke@435: gen_dfa_state_body(fp, minimize, status, operands_chained_from, i); duke@435: // End of routine duke@435: fprintf(fp, "}\n"); duke@435: } duke@435: } duke@435: fprintf(fp, "bool State::DFA"); duke@435: fprintf(fp, "(int opcode, const Node *n) {\n"); duke@435: fprintf(fp, " switch(opcode) {\n"); duke@435: duke@435: // Iterate over the table of MatchLists, start at first valid opcode of 1 duke@435: for (i = 1; i < _last_opcode; i++) { duke@435: if (_mlistab[i] == NULL) continue; duke@435: // Generate the case statement for this opcode duke@435: if (_dfa_small) { duke@435: fprintf(fp, " case Op_%s: { _sub_Op_%s(n);\n", NodeClassNames[i], NodeClassNames[i]); duke@435: } else { duke@435: fprintf(fp, " case Op_%s: {\n", NodeClassNames[i]); duke@435: // Walk the list, compacting it duke@435: gen_dfa_state_body(fp, minimize, status, operands_chained_from, i); duke@435: } duke@435: // Print the "break" duke@435: fprintf(fp, " break;\n"); duke@435: fprintf(fp, " }\n"); duke@435: } duke@435: duke@435: // Generate the default case for switch(opcode) duke@435: fprintf(fp, " \n"); duke@435: fprintf(fp, " default:\n"); duke@435: fprintf(fp, " tty->print(\"Default case invoked for: \\n\");\n"); duke@435: fprintf(fp, " tty->print(\" opcode = %cd, \\\"%cs\\\"\\n\", opcode, NodeClassNames[opcode]);\n", '%', '%'); duke@435: fprintf(fp, " return false;\n"); duke@435: fprintf(fp, " }\n"); duke@435: duke@435: // Return status, indicating a successful match. duke@435: fprintf(fp, " return true;\n"); duke@435: // Generate the closing brace for method Matcher::DFA duke@435: fprintf(fp, "}\n"); duke@435: Expr::check_buffers(); duke@435: } duke@435: duke@435: duke@435: class dfa_shared_preds { jrose@910: enum { count = 4 }; duke@435: duke@435: static bool _found[count]; duke@435: static const char* _type [count]; duke@435: static const char* _var [count]; duke@435: static const char* _pred [count]; duke@435: duke@435: static void check_index(int index) { assert( 0 <= index && index < count, "Invalid index"); } duke@435: duke@435: // Confirm that this is a separate sub-expression. duke@435: // Only need to catch common cases like " ... && shared ..." duke@435: // and avoid hazardous ones like "...->shared" duke@435: static bool valid_loc(char *pred, char *shared) { duke@435: // start of predicate is valid duke@435: if( shared == pred ) return true; duke@435: duke@435: // Check previous character and recurse if needed duke@435: char *prev = shared - 1; duke@435: char c = *prev; duke@435: switch( c ) { duke@435: case ' ': jrose@910: case '\n': duke@435: return dfa_shared_preds::valid_loc(pred, prev); duke@435: case '!': duke@435: case '(': duke@435: case '<': duke@435: case '=': duke@435: return true; jrose@910: case '"': // such as: #line 10 "myfile.ad"\n mypredicate jrose@910: return true; duke@435: case '|': duke@435: if( prev != pred && *(prev-1) == '|' ) return true; duke@435: case '&': duke@435: if( prev != pred && *(prev-1) == '&' ) return true; duke@435: default: duke@435: return false; duke@435: } duke@435: duke@435: return false; duke@435: } duke@435: duke@435: public: duke@435: duke@435: static bool found(int index){ check_index(index); return _found[index]; } duke@435: static void set_found(int index, bool val) { check_index(index); _found[index] = val; } duke@435: static void reset_found() { duke@435: for( int i = 0; i < count; ++i ) { _found[i] = false; } duke@435: }; duke@435: duke@435: static const char* type(int index) { check_index(index); return _type[index]; } duke@435: static const char* var (int index) { check_index(index); return _var [index]; } duke@435: static const char* pred(int index) { check_index(index); return _pred[index]; } duke@435: duke@435: // Check each predicate in the MatchList for common sub-expressions duke@435: static void cse_matchlist(MatchList *matchList) { duke@435: for( MatchList *mList = matchList; mList != NULL; mList = mList->get_next() ) { duke@435: Predicate* predicate = mList->get_pred_obj(); duke@435: char* pred = mList->get_pred(); duke@435: if( pred != NULL ) { duke@435: for(int index = 0; index < count; ++index ) { duke@435: const char *shared_pred = dfa_shared_preds::pred(index); duke@435: const char *shared_pred_var = dfa_shared_preds::var(index); duke@435: bool result = dfa_shared_preds::cse_predicate(predicate, shared_pred, shared_pred_var); duke@435: if( result ) dfa_shared_preds::set_found(index, true); duke@435: } duke@435: } duke@435: } duke@435: } duke@435: duke@435: // If the Predicate contains a common sub-expression, replace the Predicate's duke@435: // string with one that uses the variable name. duke@435: static bool cse_predicate(Predicate* predicate, const char *shared_pred, const char *shared_pred_var) { duke@435: bool result = false; duke@435: char *pred = predicate->_pred; duke@435: if( pred != NULL ) { duke@435: char *new_pred = pred; duke@435: for( char *shared_pred_loc = strstr(new_pred, shared_pred); duke@435: shared_pred_loc != NULL && dfa_shared_preds::valid_loc(new_pred,shared_pred_loc); duke@435: shared_pred_loc = strstr(new_pred, shared_pred) ) { duke@435: // Do not modify the original predicate string, it is shared duke@435: if( new_pred == pred ) { duke@435: new_pred = strdup(pred); duke@435: shared_pred_loc = strstr(new_pred, shared_pred); duke@435: } duke@435: // Replace shared_pred with variable name duke@435: strncpy(shared_pred_loc, shared_pred_var, strlen(shared_pred_var)); duke@435: } duke@435: // Install new predicate duke@435: if( new_pred != pred ) { duke@435: predicate->_pred = new_pred; duke@435: result = true; duke@435: } duke@435: } duke@435: return result; duke@435: } duke@435: duke@435: // Output the hoisted common sub-expression if we found it in predicates duke@435: static void generate_cse(FILE *fp) { duke@435: for(int j = 0; j < count; ++j ) { duke@435: if( dfa_shared_preds::found(j) ) { duke@435: const char *shared_pred_type = dfa_shared_preds::type(j); duke@435: const char *shared_pred_var = dfa_shared_preds::var(j); duke@435: const char *shared_pred = dfa_shared_preds::pred(j); duke@435: fprintf(fp, " %s %s = %s;\n", shared_pred_type, shared_pred_var, shared_pred); duke@435: } duke@435: } duke@435: } duke@435: }; duke@435: // shared predicates, _var and _pred entry should be the same length jrose@910: bool dfa_shared_preds::_found[dfa_shared_preds::count] jrose@910: = { false, false, false, false }; jrose@910: const char* dfa_shared_preds::_type[dfa_shared_preds::count] jrose@910: = { "int", "jlong", "intptr_t", "bool" }; jrose@910: const char* dfa_shared_preds::_var [dfa_shared_preds::count] jrose@910: = { "_n_get_int__", "_n_get_long__", "_n_get_intptr_t__", "Compile__current____select_24_bit_instr__" }; jrose@910: const char* dfa_shared_preds::_pred[dfa_shared_preds::count] jrose@910: = { "n->get_int()", "n->get_long()", "n->get_intptr_t()", "Compile::current()->select_24_bit_instr()" }; duke@435: duke@435: duke@435: void ArchDesc::gen_dfa_state_body(FILE* fp, Dict &minimize, ProductionState &status, Dict &operands_chained_from, int i) { duke@435: // Start the body of each Op_XXX sub-dfa with a clean state. duke@435: status.initialize(); duke@435: duke@435: // Walk the list, compacting it duke@435: MatchList* mList = _mlistab[i]; duke@435: do { duke@435: // Hash each entry using inputs as key and pointer as data. duke@435: // If there is already an entry, keep the one with lower cost, and duke@435: // remove the other one from the list. duke@435: prune_matchlist(minimize, *mList); duke@435: // Iterate duke@435: mList = mList->get_next(); duke@435: } while(mList != NULL); duke@435: duke@435: // Hoist previously specified common sub-expressions out of predicates duke@435: dfa_shared_preds::reset_found(); duke@435: dfa_shared_preds::cse_matchlist(_mlistab[i]); duke@435: dfa_shared_preds::generate_cse(fp); duke@435: duke@435: mList = _mlistab[i]; duke@435: duke@435: // Walk the list again, generating code duke@435: do { duke@435: // Each match can generate its own chains duke@435: operands_chained_from.Clear(); duke@435: gen_match(fp, *mList, status, operands_chained_from); duke@435: mList = mList->get_next(); duke@435: } while(mList != NULL); duke@435: // Fill in any chain rules which add instructions duke@435: // These can generate their own chains as well. duke@435: operands_chained_from.Clear(); // duke@435: if( debug_output1 ) { fprintf(fp, "// top level chain rules for: %s \n", (char *)NodeClassNames[i]); } // %%%%% Explanation duke@435: const Expr *zeroCost = new Expr("0"); duke@435: chain_rule(fp, " ", (char *)NodeClassNames[i], zeroCost, "Invalid", duke@435: operands_chained_from, status); duke@435: } duke@435: duke@435: duke@435: duke@435: //------------------------------Expr------------------------------------------ duke@435: Expr *Expr::_unknown_expr = NULL; duke@435: char Expr::string_buffer[STRING_BUFFER_LENGTH]; duke@435: char Expr::external_buffer[STRING_BUFFER_LENGTH]; duke@435: bool Expr::_init_buffers = Expr::init_buffers(); duke@435: duke@435: Expr::Expr() { duke@435: _external_name = NULL; duke@435: _expr = "Invalid_Expr"; duke@435: _min_value = Expr::Max; duke@435: _max_value = Expr::Zero; duke@435: } duke@435: Expr::Expr(const char *cost) { duke@435: _external_name = NULL; duke@435: duke@435: int intval = 0; duke@435: if( cost == NULL ) { duke@435: _expr = "0"; duke@435: _min_value = Expr::Zero; duke@435: _max_value = Expr::Zero; duke@435: } duke@435: else if( ADLParser::is_int_token(cost, intval) ) { duke@435: _expr = cost; duke@435: _min_value = intval; duke@435: _max_value = intval; duke@435: } duke@435: else { duke@435: assert( strcmp(cost,"0") != 0, "Recognize string zero as an int"); duke@435: _expr = cost; duke@435: _min_value = Expr::Zero; duke@435: _max_value = Expr::Max; duke@435: } duke@435: } duke@435: duke@435: Expr::Expr(const char *name, const char *expression, int min_value, int max_value) { duke@435: _external_name = name; duke@435: _expr = expression ? expression : name; duke@435: _min_value = min_value; duke@435: _max_value = max_value; duke@435: assert(_min_value >= 0 && _min_value <= Expr::Max, "value out of range"); duke@435: assert(_max_value >= 0 && _max_value <= Expr::Max, "value out of range"); duke@435: } duke@435: duke@435: Expr *Expr::clone() const { duke@435: Expr *cost = new Expr(); duke@435: cost->_external_name = _external_name; duke@435: cost->_expr = _expr; duke@435: cost->_min_value = _min_value; duke@435: cost->_max_value = _max_value; duke@435: duke@435: return cost; duke@435: } duke@435: duke@435: void Expr::add(const Expr *c) { duke@435: // Do not update fields until all computation is complete duke@435: const char *external = compute_external(this, c); duke@435: const char *expr = compute_expr(this, c); duke@435: int min_value = compute_min (this, c); duke@435: int max_value = compute_max (this, c); duke@435: duke@435: _external_name = external; duke@435: _expr = expr; duke@435: _min_value = min_value; duke@435: _max_value = max_value; duke@435: } duke@435: duke@435: void Expr::add(const char *c) { duke@435: Expr *cost = new Expr(c); duke@435: add(cost); duke@435: } duke@435: duke@435: void Expr::add(const char *c, ArchDesc &AD) { duke@435: const Expr *e = AD.globalDefs()[c]; duke@435: if( e != NULL ) { duke@435: // use the value of 'c' defined in .ad duke@435: add(e); duke@435: } else { duke@435: Expr *cost = new Expr(c); duke@435: add(cost); duke@435: } duke@435: } duke@435: duke@435: const char *Expr::compute_external(const Expr *c1, const Expr *c2) { duke@435: const char * result = NULL; duke@435: duke@435: // Preserve use of external name which has a zero value duke@435: if( c1->_external_name != NULL ) { duke@435: sprintf( string_buffer, "%s", c1->as_string()); duke@435: if( !c2->is_zero() ) { duke@435: strcat( string_buffer, "+"); duke@435: strcat( string_buffer, c2->as_string()); duke@435: } duke@435: result = strdup(string_buffer); duke@435: } duke@435: else if( c2->_external_name != NULL ) { duke@435: if( !c1->is_zero() ) { duke@435: sprintf( string_buffer, "%s", c1->as_string()); duke@435: strcat( string_buffer, " + "); duke@435: } else { duke@435: string_buffer[0] = '\0'; duke@435: } duke@435: strcat( string_buffer, c2->_external_name ); duke@435: result = strdup(string_buffer); duke@435: } duke@435: return result; duke@435: } duke@435: duke@435: const char *Expr::compute_expr(const Expr *c1, const Expr *c2) { duke@435: if( !c1->is_zero() ) { duke@435: sprintf( string_buffer, "%s", c1->_expr); duke@435: if( !c2->is_zero() ) { duke@435: strcat( string_buffer, "+"); duke@435: strcat( string_buffer, c2->_expr); duke@435: } duke@435: } duke@435: else if( !c2->is_zero() ) { duke@435: sprintf( string_buffer, "%s", c2->_expr); duke@435: } duke@435: else { duke@435: sprintf( string_buffer, "0"); duke@435: } duke@435: char *cost = strdup(string_buffer); duke@435: duke@435: return cost; duke@435: } duke@435: duke@435: int Expr::compute_min(const Expr *c1, const Expr *c2) { duke@435: int result = c1->_min_value + c2->_min_value; duke@435: assert( result >= 0, "Invalid cost computation"); duke@435: duke@435: return result; duke@435: } duke@435: duke@435: int Expr::compute_max(const Expr *c1, const Expr *c2) { duke@435: int result = c1->_max_value + c2->_max_value; duke@435: if( result < 0 ) { // check for overflow duke@435: result = Expr::Max; duke@435: } duke@435: duke@435: return result; duke@435: } duke@435: duke@435: void Expr::print() const { duke@435: if( _external_name != NULL ) { duke@435: printf(" %s == (%s) === [%d, %d]\n", _external_name, _expr, _min_value, _max_value); duke@435: } else { duke@435: printf(" %s === [%d, %d]\n", _expr, _min_value, _max_value); duke@435: } duke@435: } duke@435: duke@435: void Expr::print_define(FILE *fp) const { duke@435: assert( _external_name != NULL, "definition does not have a name"); duke@435: assert( _min_value == _max_value, "Expect user definitions to have constant value"); duke@435: fprintf(fp, "#define %s (%s) \n", _external_name, _expr); duke@435: fprintf(fp, "// value == %d \n", _min_value); duke@435: } duke@435: duke@435: void Expr::print_assert(FILE *fp) const { duke@435: assert( _external_name != NULL, "definition does not have a name"); duke@435: assert( _min_value == _max_value, "Expect user definitions to have constant value"); duke@435: fprintf(fp, " assert( %s == %d, \"Expect (%s) to equal %d\");\n", _external_name, _min_value, _expr, _min_value); duke@435: } duke@435: duke@435: Expr *Expr::get_unknown() { duke@435: if( Expr::_unknown_expr == NULL ) { duke@435: Expr::_unknown_expr = new Expr(); duke@435: } duke@435: duke@435: return Expr::_unknown_expr; duke@435: } duke@435: duke@435: bool Expr::init_buffers() { duke@435: // Fill buffers with 0 duke@435: for( int i = 0; i < STRING_BUFFER_LENGTH; ++i ) { duke@435: external_buffer[i] = '\0'; duke@435: string_buffer[i] = '\0'; duke@435: } duke@435: duke@435: return true; duke@435: } duke@435: duke@435: bool Expr::check_buffers() { duke@435: // returns 'true' if buffer use may have overflowed duke@435: bool ok = true; duke@435: for( int i = STRING_BUFFER_LENGTH - 100; i < STRING_BUFFER_LENGTH; ++i) { duke@435: if( external_buffer[i] != '\0' || string_buffer[i] != '\0' ) { duke@435: ok = false; duke@435: assert( false, "Expr:: Buffer overflow"); duke@435: } duke@435: } duke@435: duke@435: return ok; duke@435: } duke@435: duke@435: duke@435: //------------------------------ExprDict--------------------------------------- duke@435: // Constructor duke@435: ExprDict::ExprDict( CmpKey cmp, Hash hash, Arena *arena ) duke@435: : _expr(cmp, hash, arena), _defines() { duke@435: } duke@435: ExprDict::~ExprDict() { duke@435: } duke@435: duke@435: // Return # of name-Expr pairs in dict duke@435: int ExprDict::Size(void) const { duke@435: return _expr.Size(); duke@435: } duke@435: duke@435: // define inserts the given key-value pair into the dictionary, duke@435: // and records the name in order for later output, ... duke@435: const Expr *ExprDict::define(const char *name, Expr *expr) { duke@435: const Expr *old_expr = (*this)[name]; duke@435: assert(old_expr == NULL, "Implementation does not support redefinition"); duke@435: duke@435: _expr.Insert(name, expr); duke@435: _defines.addName(name); duke@435: duke@435: return old_expr; duke@435: } duke@435: duke@435: // Insert inserts the given key-value pair into the dictionary. The prior duke@435: // value of the key is returned; NULL if the key was not previously defined. duke@435: const Expr *ExprDict::Insert(const char *name, Expr *expr) { duke@435: return (Expr*)_expr.Insert((void*)name, (void*)expr); duke@435: } duke@435: duke@435: // Finds the value of a given key; or NULL if not found. duke@435: // The dictionary is NOT changed. duke@435: const Expr *ExprDict::operator [](const char *name) const { duke@435: return (Expr*)_expr[name]; duke@435: } duke@435: duke@435: void ExprDict::print_defines(FILE *fp) { duke@435: fprintf(fp, "\n"); duke@435: const char *name = NULL; duke@435: for( _defines.reset(); (name = _defines.iter()) != NULL; ) { duke@435: const Expr *expr = (const Expr*)_expr[name]; duke@435: assert( expr != NULL, "name in ExprDict without matching Expr in dictionary"); duke@435: expr->print_define(fp); duke@435: } duke@435: } duke@435: void ExprDict::print_asserts(FILE *fp) { duke@435: fprintf(fp, "\n"); duke@435: fprintf(fp, " // Following assertions generated from definition section\n"); duke@435: const char *name = NULL; duke@435: for( _defines.reset(); (name = _defines.iter()) != NULL; ) { duke@435: const Expr *expr = (const Expr*)_expr[name]; duke@435: assert( expr != NULL, "name in ExprDict without matching Expr in dictionary"); duke@435: expr->print_assert(fp); duke@435: } duke@435: } duke@435: duke@435: // Print out the dictionary contents as key-value pairs duke@435: static void dumpekey(const void* key) { fprintf(stdout, "%s", key); } duke@435: static void dumpexpr(const void* expr) { fflush(stdout); ((Expr*)expr)->print(); } duke@435: duke@435: void ExprDict::dump() { duke@435: _expr.print(dumpekey, dumpexpr); duke@435: } duke@435: duke@435: duke@435: //------------------------------ExprDict::private------------------------------ duke@435: // Disable public use of constructor, copy-ctor, operator =, operator == duke@435: ExprDict::ExprDict( ) : _expr(cmpkey,hashkey), _defines() { duke@435: assert( false, "NotImplemented"); duke@435: } duke@435: ExprDict::ExprDict( const ExprDict & ) : _expr(cmpkey,hashkey), _defines() { duke@435: assert( false, "NotImplemented"); duke@435: } duke@435: ExprDict &ExprDict::operator =( const ExprDict &rhs) { duke@435: assert( false, "NotImplemented"); duke@435: _expr = rhs._expr; duke@435: return *this; duke@435: } duke@435: // == compares two dictionaries; they must have the same keys (their keys duke@435: // must match using CmpKey) and they must have the same values (pointer duke@435: // comparison). If so 1 is returned, if not 0 is returned. duke@435: bool ExprDict::operator ==(const ExprDict &d) const { duke@435: assert( false, "NotImplemented"); duke@435: return false; duke@435: } duke@435: duke@435: duke@435: //------------------------------Production------------------------------------- duke@435: Production::Production(const char *result, const char *constraint, const char *valid) { duke@435: initialize(); duke@435: _result = result; duke@435: _constraint = constraint; duke@435: _valid = valid; duke@435: } duke@435: duke@435: void Production::initialize() { duke@435: _result = NULL; duke@435: _constraint = NULL; duke@435: _valid = knownInvalid; duke@435: _cost_lb = Expr::get_unknown(); duke@435: _cost_ub = Expr::get_unknown(); duke@435: } duke@435: duke@435: void Production::print() { duke@435: printf("%s", (_result == NULL ? "NULL" : _result ) ); duke@435: printf("%s", (_constraint == NULL ? "NULL" : _constraint ) ); duke@435: printf("%s", (_valid == NULL ? "NULL" : _valid ) ); duke@435: _cost_lb->print(); duke@435: _cost_ub->print(); duke@435: } duke@435: duke@435: duke@435: //------------------------------ProductionState-------------------------------- duke@435: void ProductionState::initialize() { duke@435: _constraint = noConstraint; duke@435: duke@435: // reset each Production currently in the dictionary duke@435: DictI iter( &_production ); duke@435: const void *x, *y = NULL; duke@435: for( ; iter.test(); ++iter) { duke@435: x = iter._key; duke@435: y = iter._value; duke@435: Production *p = (Production*)y; duke@435: if( p != NULL ) { duke@435: p->initialize(); duke@435: } duke@435: } duke@435: } duke@435: duke@435: Production *ProductionState::getProduction(const char *result) { duke@435: Production *p = (Production *)_production[result]; duke@435: if( p == NULL ) { duke@435: p = new Production(result, _constraint, knownInvalid); duke@435: _production.Insert(result, p); duke@435: } duke@435: duke@435: return p; duke@435: } duke@435: duke@435: void ProductionState::set_constraint(const char *constraint) { duke@435: _constraint = constraint; duke@435: } duke@435: duke@435: const char *ProductionState::valid(const char *result) { duke@435: return getProduction(result)->valid(); duke@435: } duke@435: duke@435: void ProductionState::set_valid(const char *result) { duke@435: Production *p = getProduction(result); duke@435: duke@435: // Update valid as allowed by current constraints duke@435: if( _constraint == noConstraint ) { duke@435: p->_valid = knownValid; duke@435: } else { duke@435: if( p->_valid != knownValid ) { duke@435: p->_valid = unknownValid; duke@435: } duke@435: } duke@435: } duke@435: duke@435: Expr *ProductionState::cost_lb(const char *result) { duke@435: return getProduction(result)->cost_lb(); duke@435: } duke@435: duke@435: Expr *ProductionState::cost_ub(const char *result) { duke@435: return getProduction(result)->cost_ub(); duke@435: } duke@435: duke@435: void ProductionState::set_cost_bounds(const char *result, const Expr *cost, bool has_state_check, bool has_cost_check) { duke@435: Production *p = getProduction(result); duke@435: duke@435: if( p->_valid == knownInvalid ) { duke@435: // Our cost bounds are not unknown, just not defined. duke@435: p->_cost_lb = cost->clone(); duke@435: p->_cost_ub = cost->clone(); duke@435: } else if (has_state_check || _constraint != noConstraint) { duke@435: // The production is protected by a condition, so duke@435: // the cost bounds may expand. duke@435: // _cost_lb = min(cost, _cost_lb) duke@435: if( cost->less_than_or_equal(p->_cost_lb) ) { duke@435: p->_cost_lb = cost->clone(); duke@435: } duke@435: // _cost_ub = max(cost, _cost_ub) duke@435: if( p->_cost_ub->less_than_or_equal(cost) ) { duke@435: p->_cost_ub = cost->clone(); duke@435: } duke@435: } else if (has_cost_check) { duke@435: // The production has no condition check, but does duke@435: // have a cost check that could reduce the upper duke@435: // and/or lower bound. duke@435: // _cost_lb = min(cost, _cost_lb) duke@435: if( cost->less_than_or_equal(p->_cost_lb) ) { duke@435: p->_cost_lb = cost->clone(); duke@435: } duke@435: // _cost_ub = min(cost, _cost_ub) duke@435: if( cost->less_than_or_equal(p->_cost_ub) ) { duke@435: p->_cost_ub = cost->clone(); duke@435: } duke@435: } else { duke@435: // The costs are unconditionally set. duke@435: p->_cost_lb = cost->clone(); duke@435: p->_cost_ub = cost->clone(); duke@435: } duke@435: duke@435: } duke@435: duke@435: // Print out the dictionary contents as key-value pairs duke@435: static void print_key (const void* key) { fprintf(stdout, "%s", key); } duke@435: static void print_production(const void* production) { fflush(stdout); ((Production*)production)->print(); } duke@435: duke@435: void ProductionState::print() { duke@435: _production.print(print_key, print_production); duke@435: }