Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
PojavLauncherTeam
GitHub Repository: PojavLauncherTeam/mobile
Path: blob/master/src/hotspot/share/adlc/dfa.cpp
41144 views
1
/*
2
* Copyright (c) 1997, 2018, Oracle and/or its affiliates. All rights reserved.
3
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4
*
5
* This code is free software; you can redistribute it and/or modify it
6
* under the terms of the GNU General Public License version 2 only, as
7
* published by the Free Software Foundation.
8
*
9
* This code is distributed in the hope that it will be useful, but WITHOUT
10
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
12
* version 2 for more details (a copy is included in the LICENSE file that
13
* accompanied this code).
14
*
15
* You should have received a copy of the GNU General Public License version
16
* 2 along with this work; if not, write to the Free Software Foundation,
17
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18
*
19
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20
* or visit www.oracle.com if you need additional information or have any
21
* questions.
22
*
23
*/
24
25
// DFA.CPP - Method definitions for outputting the matcher DFA from ADLC
26
#include "adlc.hpp"
27
28
//---------------------------Switches for debugging output---------------------
29
static bool debug_output = false;
30
static bool debug_output1 = false; // top level chain rules
31
32
//---------------------------Production State----------------------------------
33
static const char *knownInvalid = "knownInvalid"; // The result does NOT have a rule defined
34
static const char *knownValid = "knownValid"; // The result must be produced by a rule
35
static const char *unknownValid = "unknownValid"; // Unknown (probably due to a child or predicate constraint)
36
37
static const char *noConstraint = "noConstraint"; // No constraints seen so far
38
static const char *hasConstraint = "hasConstraint"; // Within the first constraint
39
40
41
//------------------------------Production------------------------------------
42
// Track the status of productions for a particular result
43
class Production {
44
public:
45
const char *_result;
46
const char *_constraint;
47
const char *_valid;
48
Expr *_cost_lb; // Cost lower bound for this production
49
Expr *_cost_ub; // Cost upper bound for this production
50
51
public:
52
Production(const char *result, const char *constraint, const char *valid);
53
~Production() {};
54
55
void initialize(); // reset to be an empty container
56
57
const char *valid() const { return _valid; }
58
Expr *cost_lb() const { return (Expr *)_cost_lb; }
59
Expr *cost_ub() const { return (Expr *)_cost_ub; }
60
61
void print();
62
};
63
64
65
//------------------------------ProductionState--------------------------------
66
// Track the status of all production rule results
67
// Reset for each root opcode (e.g., Op_RegI, Op_AddI, ...)
68
class ProductionState {
69
private:
70
Dict _production; // map result of production, char*, to information or NULL
71
const char *_constraint;
72
73
public:
74
// cmpstr does string comparisions. hashstr computes a key.
75
ProductionState(Arena *arena) : _production(cmpstr, hashstr, arena) { initialize(); };
76
~ProductionState() { };
77
78
void initialize(); // reset local and dictionary state
79
80
const char *constraint();
81
void set_constraint(const char *constraint); // currently working inside of constraints
82
83
const char *valid(const char *result); // unknownValid, or status for this production
84
void set_valid(const char *result); // if not constrained, set status to knownValid
85
86
Expr *cost_lb(const char *result);
87
Expr *cost_ub(const char *result);
88
void set_cost_bounds(const char *result, const Expr *cost, bool has_state_check, bool has_cost_check);
89
90
// Return the Production associated with the result,
91
// or create a new Production and insert it into the dictionary.
92
Production *getProduction(const char *result);
93
94
void print();
95
96
private:
97
// Disable public use of constructor, copy-ctor, ...
98
ProductionState( ) : _production(cmpstr, hashstr, Form::arena) { assert( false, "NotImplemented"); };
99
ProductionState( const ProductionState & ) : _production(cmpstr, hashstr, Form::arena) { assert( false, "NotImplemented"); }; // Deep-copy
100
};
101
102
103
//---------------------------Helper Functions----------------------------------
104
// cost_check template:
105
// 1) if (STATE__NOT_YET_VALID(EBXREGI) || _cost[EBXREGI] > c) {
106
// 2) DFA_PRODUCTION(EBXREGI, cmovI_memu_rule, c)
107
// 3) }
108
//
109
static void cost_check(FILE *fp, const char *spaces,
110
const char *arrayIdx, const Expr *cost, const char *rule, ProductionState &status) {
111
bool state_check = false; // true if this production needs to check validity
112
bool cost_check = false; // true if this production needs to check cost
113
bool cost_is_above_upper_bound = false; // true if this production is unnecessary due to high cost
114
bool cost_is_below_lower_bound = false; // true if this production replaces a higher cost production
115
116
// Get information about this production
117
const Expr *previous_ub = status.cost_ub(arrayIdx);
118
if( !previous_ub->is_unknown() ) {
119
if( previous_ub->less_than_or_equal(cost) ) {
120
cost_is_above_upper_bound = true;
121
if( debug_output ) { fprintf(fp, "// Previous rule with lower cost than: %s === %s_rule costs %s\n", arrayIdx, rule, cost->as_string()); }
122
}
123
}
124
125
const Expr *previous_lb = status.cost_lb(arrayIdx);
126
if( !previous_lb->is_unknown() ) {
127
if( cost->less_than_or_equal(previous_lb) ) {
128
cost_is_below_lower_bound = true;
129
if( debug_output ) { fprintf(fp, "// Previous rule with higher cost\n"); }
130
}
131
}
132
133
// line 1)
134
// Check for validity and compare to other match costs
135
const char *validity_check = status.valid(arrayIdx);
136
if( validity_check == unknownValid ) {
137
fprintf(fp, "%sif (STATE__NOT_YET_VALID(%s) || _cost[%s] > %s) {\n", spaces, arrayIdx, arrayIdx, cost->as_string());
138
state_check = true;
139
cost_check = true;
140
}
141
else if( validity_check == knownInvalid ) {
142
if( debug_output ) { fprintf(fp, "%s// %s KNOWN_INVALID \n", spaces, arrayIdx); }
143
}
144
else if( validity_check == knownValid ) {
145
if( cost_is_above_upper_bound ) {
146
// production cost is known to be too high.
147
return;
148
} else if( cost_is_below_lower_bound ) {
149
// production will unconditionally overwrite a previous production that had higher cost
150
} else {
151
fprintf(fp, "%sif ( /* %s KNOWN_VALID || */ _cost[%s] > %s) {\n", spaces, arrayIdx, arrayIdx, cost->as_string());
152
cost_check = true;
153
}
154
}
155
156
// line 2)
157
fprintf(fp, "%s DFA_PRODUCTION(%s, %s_rule, %s)", spaces, arrayIdx, rule, cost->as_string() );
158
if (validity_check == knownValid) {
159
if (cost_is_below_lower_bound) {
160
fprintf(fp, "\t // overwrites higher cost rule");
161
}
162
}
163
fprintf(fp, "\n");
164
165
// line 3)
166
if( cost_check || state_check ) {
167
fprintf(fp, "%s}\n", spaces);
168
}
169
170
status.set_cost_bounds(arrayIdx, cost, state_check, cost_check);
171
172
// Update ProductionState
173
if( validity_check != knownValid ) {
174
// set State vector if not previously known
175
status.set_valid(arrayIdx);
176
}
177
}
178
179
180
//---------------------------child_test----------------------------------------
181
// Example:
182
// STATE__VALID_CHILD(_kids[0], FOO) && STATE__VALID_CHILD(_kids[1], BAR)
183
// Macro equivalent to: _kids[0]->valid(FOO) && _kids[1]->valid(BAR)
184
//
185
static void child_test(FILE *fp, MatchList &mList) {
186
if (mList._lchild) { // If left child, check it
187
const char* lchild_to_upper = ArchDesc::getMachOperEnum(mList._lchild);
188
fprintf(fp, "STATE__VALID_CHILD(_kids[0], %s)", lchild_to_upper);
189
delete[] lchild_to_upper;
190
}
191
if (mList._lchild && mList._rchild) { // If both, add the "&&"
192
fprintf(fp, " && ");
193
}
194
if (mList._rchild) { // If right child, check it
195
const char* rchild_to_upper = ArchDesc::getMachOperEnum(mList._rchild);
196
fprintf(fp, "STATE__VALID_CHILD(_kids[1], %s)", rchild_to_upper);
197
delete[] rchild_to_upper;
198
}
199
}
200
201
//---------------------------calc_cost-----------------------------------------
202
// Example:
203
// unsigned int c = _kids[0]->_cost[FOO] + _kids[1]->_cost[BAR] + 5;
204
//
205
Expr *ArchDesc::calc_cost(FILE *fp, const char *spaces, MatchList &mList, ProductionState &status) {
206
fprintf(fp, "%sunsigned int c = ", spaces);
207
Expr *c = new Expr("0");
208
if (mList._lchild) { // If left child, add it in
209
const char* lchild_to_upper = ArchDesc::getMachOperEnum(mList._lchild);
210
sprintf(Expr::buffer(), "_kids[0]->_cost[%s]", lchild_to_upper);
211
c->add(Expr::buffer());
212
delete[] lchild_to_upper;
213
}
214
if (mList._rchild) { // If right child, add it in
215
const char* rchild_to_upper = ArchDesc::getMachOperEnum(mList._rchild);
216
sprintf(Expr::buffer(), "_kids[1]->_cost[%s]", rchild_to_upper);
217
c->add(Expr::buffer());
218
delete[] rchild_to_upper;
219
}
220
// Add in cost of this rule
221
const char *mList_cost = mList.get_cost();
222
c->add(mList_cost, *this);
223
224
fprintf(fp, "%s;\n", c->as_string());
225
c->set_external_name("c");
226
return c;
227
}
228
229
230
//---------------------------gen_match-----------------------------------------
231
void ArchDesc::gen_match(FILE *fp, MatchList &mList, ProductionState &status, Dict &operands_chained_from) {
232
const char *spaces4 = " ";
233
const char *spaces6 = " ";
234
235
fprintf(fp, "%s", spaces4);
236
// Only generate child tests if this is not a leaf node
237
bool has_child_constraints = mList._lchild || mList._rchild;
238
const char *predicate_test = mList.get_pred();
239
if (has_child_constraints || predicate_test) {
240
// Open the child-and-predicate-test braces
241
fprintf(fp, "if( ");
242
status.set_constraint(hasConstraint);
243
child_test(fp, mList);
244
// Only generate predicate test if one exists for this match
245
if (predicate_test) {
246
if (has_child_constraints) {
247
fprintf(fp," &&\n");
248
}
249
fprintf(fp, "%s %s", spaces6, predicate_test);
250
}
251
// End of outer tests
252
fprintf(fp," ) ");
253
} else {
254
// No child or predicate test needed
255
status.set_constraint(noConstraint);
256
}
257
258
// End of outer tests
259
fprintf(fp,"{\n");
260
261
// Calculate cost of this match
262
const Expr *cost = calc_cost(fp, spaces6, mList, status);
263
// Check against other match costs, and update cost & rule vectors
264
cost_check(fp, spaces6, ArchDesc::getMachOperEnum(mList._resultStr), cost, mList._opcode, status);
265
266
// If this is a member of an operand class, update the class cost & rule
267
expand_opclass( fp, spaces6, cost, mList._resultStr, status);
268
269
// Check if this rule should be used to generate the chains as well.
270
const char *rule = /* set rule to "Invalid" for internal operands */
271
strcmp(mList._opcode, mList._resultStr) ? mList._opcode : "Invalid";
272
273
// If this rule produces an operand which has associated chain rules,
274
// update the operands with the chain rule + this rule cost & this rule.
275
chain_rule(fp, spaces6, mList._resultStr, cost, rule, operands_chained_from, status);
276
277
// Close the child-and-predicate-test braces
278
fprintf(fp, " }\n");
279
280
}
281
282
283
//---------------------------expand_opclass------------------------------------
284
// Chain from one result_type to all other members of its operand class
285
void ArchDesc::expand_opclass(FILE *fp, const char *indent, const Expr *cost,
286
const char *result_type, ProductionState &status) {
287
const Form *form = _globalNames[result_type];
288
OperandForm *op = form ? form->is_operand() : NULL;
289
if( op && op->_classes.count() > 0 ) {
290
if( debug_output ) { fprintf(fp, "// expand operand classes for operand: %s \n", (char *)op->_ident ); } // %%%%% Explanation
291
// Iterate through all operand classes which include this operand
292
op->_classes.reset();
293
const char *oclass;
294
// Expr *cCost = new Expr(cost);
295
while( (oclass = op->_classes.iter()) != NULL )
296
// Check against other match costs, and update cost & rule vectors
297
cost_check(fp, indent, ArchDesc::getMachOperEnum(oclass), cost, result_type, status);
298
}
299
}
300
301
//---------------------------chain_rule----------------------------------------
302
// Starting at 'operand', check if we know how to automatically generate other results
303
void ArchDesc::chain_rule(FILE *fp, const char *indent, const char *operand,
304
const Expr *icost, const char *irule, Dict &operands_chained_from, ProductionState &status) {
305
306
// Check if we have already generated chains from this starting point
307
if( operands_chained_from[operand] != NULL ) {
308
return;
309
} else {
310
operands_chained_from.Insert( operand, operand);
311
}
312
if( debug_output ) { fprintf(fp, "// chain rules starting from: %s and %s \n", (char *)operand, (char *)irule); } // %%%%% Explanation
313
314
ChainList *lst = (ChainList *)_chainRules[operand];
315
if (lst) {
316
// printf("\nChain from <%s> at cost #%s\n",operand, icost ? icost : "_");
317
const char *result, *cost, *rule;
318
for(lst->reset(); (lst->iter(result,cost,rule)) == true; ) {
319
// Do not generate operands that are already available
320
if( operands_chained_from[result] != NULL ) {
321
continue;
322
} else {
323
// Compute the cost for previous match + chain_rule_cost
324
// total_cost = icost + cost;
325
Expr *total_cost = icost->clone(); // icost + cost
326
total_cost->add(cost, *this);
327
328
// Check for transitive chain rules
329
Form *form = (Form *)_globalNames[rule];
330
if ( ! form->is_instruction()) {
331
// printf(" result=%s cost=%s rule=%s\n", result, total_cost, rule);
332
// Check against other match costs, and update cost & rule vectors
333
const char *reduce_rule = strcmp(irule,"Invalid") ? irule : rule;
334
cost_check(fp, indent, ArchDesc::getMachOperEnum(result), total_cost, reduce_rule, status);
335
chain_rule(fp, indent, result, total_cost, irule, operands_chained_from, status);
336
} else {
337
// printf(" result=%s cost=%s rule=%s\n", result, total_cost, rule);
338
// Check against other match costs, and update cost & rule vectors
339
cost_check(fp, indent, ArchDesc::getMachOperEnum(result), total_cost, rule, status);
340
chain_rule(fp, indent, result, total_cost, rule, operands_chained_from, status);
341
}
342
343
// If this is a member of an operand class, update class cost & rule
344
expand_opclass( fp, indent, total_cost, result, status );
345
}
346
}
347
}
348
}
349
350
//---------------------------prune_matchlist-----------------------------------
351
// Check for duplicate entries in a matchlist, and prune out the higher cost
352
// entry.
353
void ArchDesc::prune_matchlist(Dict &minimize, MatchList &mlist) {
354
355
}
356
357
//---------------------------buildDFA------------------------------------------
358
// DFA is a large switch with case statements for each ideal opcode encountered
359
// in any match rule in the ad file. Each case has a series of if's to handle
360
// the match or fail decisions. The matches test the cost function of that
361
// rule, and prune any cases which are higher cost for the same reduction.
362
// In order to generate the DFA we walk the table of ideal opcode/MatchList
363
// pairs generated by the ADLC front end to build the contents of the case
364
// statements (a series of if statements).
365
void ArchDesc::buildDFA(FILE* fp) {
366
int i;
367
// Remember operands that are the starting points for chain rules.
368
// Prevent cycles by checking if we have already generated chain.
369
Dict operands_chained_from(cmpstr, hashstr, Form::arena);
370
371
// Hash inputs to match rules so that final DFA contains only one entry for
372
// each match pattern which is the low cost entry.
373
Dict minimize(cmpstr, hashstr, Form::arena);
374
375
// Track status of dfa for each resulting production
376
// reset for each ideal root.
377
ProductionState status(Form::arena);
378
379
// Output the start of the DFA method into the output file
380
381
fprintf(fp, "\n");
382
fprintf(fp, "//------------------------- Source -----------------------------------------\n");
383
// Do not put random source code into the DFA.
384
// If there are constants which need sharing, put them in "source_hpp" forms.
385
// _source.output(fp);
386
fprintf(fp, "\n");
387
fprintf(fp, "//------------------------- Attributes -------------------------------------\n");
388
_attributes.output(fp);
389
fprintf(fp, "\n");
390
fprintf(fp, "//------------------------- Macros -----------------------------------------\n");
391
fprintf(fp, "#define DFA_PRODUCTION(result, rule, cost)\\\n");
392
fprintf(fp, " assert(rule < (1 << 15), \"too many rules\"); _cost[ (result) ] = cost; _rule[ (result) ] = (rule << 1) | 0x1;\n");
393
fprintf(fp, "\n");
394
395
fprintf(fp, "//------------------------- DFA --------------------------------------------\n");
396
397
fprintf(fp,
398
"// DFA is a large switch with case statements for each ideal opcode encountered\n"
399
"// in any match rule in the ad file. Each case has a series of if's to handle\n"
400
"// the match or fail decisions. The matches test the cost function of that\n"
401
"// rule, and prune any cases which are higher cost for the same reduction.\n"
402
"// In order to generate the DFA we walk the table of ideal opcode/MatchList\n"
403
"// pairs generated by the ADLC front end to build the contents of the case\n"
404
"// statements (a series of if statements).\n"
405
);
406
fprintf(fp, "\n");
407
fprintf(fp, "\n");
408
if (_dfa_small) {
409
// Now build the individual routines just like the switch entries in large version
410
// Iterate over the table of MatchLists, start at first valid opcode of 1
411
for (i = 1; i < _last_opcode; i++) {
412
if (_mlistab[i] == NULL) continue;
413
// Generate the routine header statement for this opcode
414
fprintf(fp, "void State::_sub_Op_%s(const Node *n){\n", NodeClassNames[i]);
415
// Generate body. Shared for both inline and out-of-line version
416
gen_dfa_state_body(fp, minimize, status, operands_chained_from, i);
417
// End of routine
418
fprintf(fp, "}\n");
419
}
420
}
421
fprintf(fp, "bool State::DFA");
422
fprintf(fp, "(int opcode, const Node *n) {\n");
423
fprintf(fp, " switch(opcode) {\n");
424
425
// Iterate over the table of MatchLists, start at first valid opcode of 1
426
for (i = 1; i < _last_opcode; i++) {
427
if (_mlistab[i] == NULL) continue;
428
// Generate the case statement for this opcode
429
if (_dfa_small) {
430
fprintf(fp, " case Op_%s: { _sub_Op_%s(n);\n", NodeClassNames[i], NodeClassNames[i]);
431
} else {
432
fprintf(fp, " case Op_%s: {\n", NodeClassNames[i]);
433
// Walk the list, compacting it
434
gen_dfa_state_body(fp, minimize, status, operands_chained_from, i);
435
}
436
// Print the "break"
437
fprintf(fp, " break;\n");
438
fprintf(fp, " }\n");
439
}
440
441
// Generate the default case for switch(opcode)
442
fprintf(fp, " \n");
443
fprintf(fp, " default:\n");
444
fprintf(fp, " tty->print(\"Default case invoked for: \\n\");\n");
445
fprintf(fp, " tty->print(\" opcode = %cd, \\\"%cs\\\"\\n\", opcode, NodeClassNames[opcode]);\n", '%', '%');
446
fprintf(fp, " return false;\n");
447
fprintf(fp, " }\n");
448
449
// Return status, indicating a successful match.
450
fprintf(fp, " return true;\n");
451
// Generate the closing brace for method Matcher::DFA
452
fprintf(fp, "}\n");
453
Expr::check_buffers();
454
}
455
456
457
class dfa_shared_preds {
458
enum { count = 3 IA32_ONLY( + 1 ) };
459
460
static bool _found[count];
461
static const char* _type [count];
462
static const char* _var [count];
463
static const char* _pred [count];
464
465
static void check_index(int index) { assert( 0 <= index && index < count, "Invalid index"); }
466
467
// Confirm that this is a separate sub-expression.
468
// Only need to catch common cases like " ... && shared ..."
469
// and avoid hazardous ones like "...->shared"
470
static bool valid_loc(char *pred, char *shared) {
471
// start of predicate is valid
472
if( shared == pred ) return true;
473
474
// Check previous character and recurse if needed
475
char *prev = shared - 1;
476
char c = *prev;
477
switch( c ) {
478
case ' ':
479
case '\n':
480
return dfa_shared_preds::valid_loc(pred, prev);
481
case '!':
482
case '(':
483
case '<':
484
case '=':
485
return true;
486
case '"': // such as: #line 10 "myfile.ad"\n mypredicate
487
return true;
488
case '|':
489
if (prev != pred && *(prev-1) == '|') return true;
490
break;
491
case '&':
492
if (prev != pred && *(prev-1) == '&') return true;
493
break;
494
default:
495
return false;
496
}
497
498
return false;
499
}
500
501
public:
502
503
static bool found(int index){ check_index(index); return _found[index]; }
504
static void set_found(int index, bool val) { check_index(index); _found[index] = val; }
505
static void reset_found() {
506
for( int i = 0; i < count; ++i ) { _found[i] = false; }
507
};
508
509
static const char* type(int index) { check_index(index); return _type[index]; }
510
static const char* var (int index) { check_index(index); return _var [index]; }
511
static const char* pred(int index) { check_index(index); return _pred[index]; }
512
513
// Check each predicate in the MatchList for common sub-expressions
514
static void cse_matchlist(MatchList *matchList) {
515
for( MatchList *mList = matchList; mList != NULL; mList = mList->get_next() ) {
516
Predicate* predicate = mList->get_pred_obj();
517
char* pred = mList->get_pred();
518
if( pred != NULL ) {
519
for(int index = 0; index < count; ++index ) {
520
const char *shared_pred = dfa_shared_preds::pred(index);
521
const char *shared_pred_var = dfa_shared_preds::var(index);
522
bool result = dfa_shared_preds::cse_predicate(predicate, shared_pred, shared_pred_var);
523
if( result ) dfa_shared_preds::set_found(index, true);
524
}
525
}
526
}
527
}
528
529
// If the Predicate contains a common sub-expression, replace the Predicate's
530
// string with one that uses the variable name.
531
static bool cse_predicate(Predicate* predicate, const char *shared_pred, const char *shared_pred_var) {
532
bool result = false;
533
char *pred = predicate->_pred;
534
if( pred != NULL ) {
535
char *new_pred = pred;
536
for( char *shared_pred_loc = strstr(new_pred, shared_pred);
537
shared_pred_loc != NULL && dfa_shared_preds::valid_loc(new_pred,shared_pred_loc);
538
shared_pred_loc = strstr(new_pred, shared_pred) ) {
539
// Do not modify the original predicate string, it is shared
540
if( new_pred == pred ) {
541
new_pred = strdup(pred);
542
shared_pred_loc = strstr(new_pred, shared_pred);
543
}
544
// Replace shared_pred with variable name
545
strncpy(shared_pred_loc, shared_pred_var, strlen(shared_pred_var));
546
}
547
// Install new predicate
548
if( new_pred != pred ) {
549
predicate->_pred = new_pred;
550
result = true;
551
}
552
}
553
return result;
554
}
555
556
// Output the hoisted common sub-expression if we found it in predicates
557
static void generate_cse(FILE *fp) {
558
for(int j = 0; j < count; ++j ) {
559
if( dfa_shared_preds::found(j) ) {
560
const char *shared_pred_type = dfa_shared_preds::type(j);
561
const char *shared_pred_var = dfa_shared_preds::var(j);
562
const char *shared_pred = dfa_shared_preds::pred(j);
563
fprintf(fp, " %s %s = %s;\n", shared_pred_type, shared_pred_var, shared_pred);
564
}
565
}
566
}
567
};
568
// shared predicates, _var and _pred entry should be the same length
569
bool dfa_shared_preds::_found[dfa_shared_preds::count] = { false, false, false IA32_ONLY(COMMA false) };
570
const char* dfa_shared_preds::_type [dfa_shared_preds::count] = { "int", "jlong", "intptr_t" IA32_ONLY(COMMA "bool") };
571
const char* dfa_shared_preds::_var [dfa_shared_preds::count] = { "_n_get_int__", "_n_get_long__", "_n_get_intptr_t__" IA32_ONLY(COMMA "Compile__current____select_24_bit_instr__") };
572
const char* dfa_shared_preds::_pred [dfa_shared_preds::count] = { "n->get_int()", "n->get_long()", "n->get_intptr_t()" IA32_ONLY(COMMA "Compile::current()->select_24_bit_instr()") };
573
574
void ArchDesc::gen_dfa_state_body(FILE* fp, Dict &minimize, ProductionState &status, Dict &operands_chained_from, int i) {
575
// Start the body of each Op_XXX sub-dfa with a clean state.
576
status.initialize();
577
578
// Walk the list, compacting it
579
MatchList* mList = _mlistab[i];
580
do {
581
// Hash each entry using inputs as key and pointer as data.
582
// If there is already an entry, keep the one with lower cost, and
583
// remove the other one from the list.
584
prune_matchlist(minimize, *mList);
585
// Iterate
586
mList = mList->get_next();
587
} while(mList != NULL);
588
589
// Hoist previously specified common sub-expressions out of predicates
590
dfa_shared_preds::reset_found();
591
dfa_shared_preds::cse_matchlist(_mlistab[i]);
592
dfa_shared_preds::generate_cse(fp);
593
594
mList = _mlistab[i];
595
596
// Walk the list again, generating code
597
do {
598
// Each match can generate its own chains
599
operands_chained_from.Clear();
600
gen_match(fp, *mList, status, operands_chained_from);
601
mList = mList->get_next();
602
} while(mList != NULL);
603
// Fill in any chain rules which add instructions
604
// These can generate their own chains as well.
605
operands_chained_from.Clear(); //
606
if( debug_output1 ) { fprintf(fp, "// top level chain rules for: %s \n", (char *)NodeClassNames[i]); } // %%%%% Explanation
607
const Expr *zeroCost = new Expr("0");
608
chain_rule(fp, " ", (char *)NodeClassNames[i], zeroCost, "Invalid",
609
operands_chained_from, status);
610
}
611
612
613
614
//------------------------------Expr------------------------------------------
615
Expr *Expr::_unknown_expr = NULL;
616
char Expr::string_buffer[STRING_BUFFER_LENGTH];
617
char Expr::external_buffer[STRING_BUFFER_LENGTH];
618
bool Expr::_init_buffers = Expr::init_buffers();
619
620
Expr::Expr() {
621
_external_name = NULL;
622
_expr = "Invalid_Expr";
623
_min_value = Expr::Max;
624
_max_value = Expr::Zero;
625
}
626
Expr::Expr(const char *cost) {
627
_external_name = NULL;
628
629
int intval = 0;
630
if( cost == NULL ) {
631
_expr = "0";
632
_min_value = Expr::Zero;
633
_max_value = Expr::Zero;
634
}
635
else if( ADLParser::is_int_token(cost, intval) ) {
636
_expr = cost;
637
_min_value = intval;
638
_max_value = intval;
639
}
640
else {
641
assert( strcmp(cost,"0") != 0, "Recognize string zero as an int");
642
_expr = cost;
643
_min_value = Expr::Zero;
644
_max_value = Expr::Max;
645
}
646
}
647
648
Expr::Expr(const char *name, const char *expression, int min_value, int max_value) {
649
_external_name = name;
650
_expr = expression ? expression : name;
651
_min_value = min_value;
652
_max_value = max_value;
653
assert(_min_value >= 0 && _min_value <= Expr::Max, "value out of range");
654
assert(_max_value >= 0 && _max_value <= Expr::Max, "value out of range");
655
}
656
657
Expr *Expr::clone() const {
658
Expr *cost = new Expr();
659
cost->_external_name = _external_name;
660
cost->_expr = _expr;
661
cost->_min_value = _min_value;
662
cost->_max_value = _max_value;
663
664
return cost;
665
}
666
667
void Expr::add(const Expr *c) {
668
// Do not update fields until all computation is complete
669
const char *external = compute_external(this, c);
670
const char *expr = compute_expr(this, c);
671
int min_value = compute_min (this, c);
672
int max_value = compute_max (this, c);
673
674
_external_name = external;
675
_expr = expr;
676
_min_value = min_value;
677
_max_value = max_value;
678
}
679
680
void Expr::add(const char *c) {
681
Expr *cost = new Expr(c);
682
add(cost);
683
}
684
685
void Expr::add(const char *c, ArchDesc &AD) {
686
const Expr *e = AD.globalDefs()[c];
687
if( e != NULL ) {
688
// use the value of 'c' defined in <arch>.ad
689
add(e);
690
} else {
691
Expr *cost = new Expr(c);
692
add(cost);
693
}
694
}
695
696
const char *Expr::compute_external(const Expr *c1, const Expr *c2) {
697
const char * result = NULL;
698
699
// Preserve use of external name which has a zero value
700
if( c1->_external_name != NULL ) {
701
if( c2->is_zero() ) {
702
snprintf(string_buffer, STRING_BUFFER_LENGTH, "%s", c1->as_string());
703
} else {
704
snprintf(string_buffer, STRING_BUFFER_LENGTH, "%s+%s", c1->as_string(), c2->as_string());
705
}
706
string_buffer[STRING_BUFFER_LENGTH - 1] = '\0';
707
result = strdup(string_buffer);
708
}
709
else if( c2->_external_name != NULL ) {
710
if( c1->is_zero() ) {
711
snprintf(string_buffer, STRING_BUFFER_LENGTH, "%s", c2->_external_name);
712
} else {
713
snprintf(string_buffer, STRING_BUFFER_LENGTH, "%s + %s", c1->as_string(), c2->as_string());
714
}
715
string_buffer[STRING_BUFFER_LENGTH - 1] = '\0';
716
result = strdup(string_buffer);
717
}
718
return result;
719
}
720
721
const char *Expr::compute_expr(const Expr *c1, const Expr *c2) {
722
if( !c1->is_zero() ) {
723
if( c2->is_zero() ) {
724
snprintf(string_buffer, STRING_BUFFER_LENGTH, "%s", c1->_expr);
725
} else {
726
snprintf(string_buffer, STRING_BUFFER_LENGTH, "%s+%s", c1->_expr, c2->_expr);
727
}
728
}
729
else if( !c2->is_zero() ) {
730
snprintf(string_buffer, STRING_BUFFER_LENGTH, "%s", c2->_expr);
731
}
732
else {
733
sprintf( string_buffer, "0");
734
}
735
string_buffer[STRING_BUFFER_LENGTH - 1] = '\0';
736
char *cost = strdup(string_buffer);
737
738
return cost;
739
}
740
741
int Expr::compute_min(const Expr *c1, const Expr *c2) {
742
int v1 = c1->_min_value;
743
int v2 = c2->_min_value;
744
assert(0 <= v2 && v2 <= Expr::Max, "sanity");
745
assert(v1 <= Expr::Max - v2, "Invalid cost computation");
746
747
return v1 + v2;
748
}
749
750
751
int Expr::compute_max(const Expr *c1, const Expr *c2) {
752
int v1 = c1->_max_value;
753
int v2 = c2->_max_value;
754
755
// Check for overflow without producing UB. If v2 is positive
756
// and not larger than Max, the subtraction cannot underflow.
757
assert(0 <= v2 && v2 <= Expr::Max, "sanity");
758
if (v1 > Expr::Max - v2) {
759
return Expr::Max;
760
}
761
762
return v1 + v2;
763
}
764
765
void Expr::print() const {
766
if( _external_name != NULL ) {
767
printf(" %s == (%s) === [%d, %d]\n", _external_name, _expr, _min_value, _max_value);
768
} else {
769
printf(" %s === [%d, %d]\n", _expr, _min_value, _max_value);
770
}
771
}
772
773
void Expr::print_define(FILE *fp) const {
774
assert( _external_name != NULL, "definition does not have a name");
775
assert( _min_value == _max_value, "Expect user definitions to have constant value");
776
fprintf(fp, "#define %s (%s) \n", _external_name, _expr);
777
fprintf(fp, "// value == %d \n", _min_value);
778
}
779
780
void Expr::print_assert(FILE *fp) const {
781
assert( _external_name != NULL, "definition does not have a name");
782
assert( _min_value == _max_value, "Expect user definitions to have constant value");
783
fprintf(fp, " assert( %s == %d, \"Expect (%s) to equal %d\");\n", _external_name, _min_value, _expr, _min_value);
784
}
785
786
Expr *Expr::get_unknown() {
787
if( Expr::_unknown_expr == NULL ) {
788
Expr::_unknown_expr = new Expr();
789
}
790
791
return Expr::_unknown_expr;
792
}
793
794
bool Expr::init_buffers() {
795
// Fill buffers with 0
796
for( int i = 0; i < STRING_BUFFER_LENGTH; ++i ) {
797
external_buffer[i] = '\0';
798
string_buffer[i] = '\0';
799
}
800
801
return true;
802
}
803
804
bool Expr::check_buffers() {
805
// returns 'true' if buffer use may have overflowed
806
bool ok = true;
807
for( int i = STRING_BUFFER_LENGTH - 100; i < STRING_BUFFER_LENGTH; ++i) {
808
if( external_buffer[i] != '\0' || string_buffer[i] != '\0' ) {
809
ok = false;
810
assert( false, "Expr:: Buffer overflow");
811
}
812
}
813
814
return ok;
815
}
816
817
818
//------------------------------ExprDict---------------------------------------
819
// Constructor
820
ExprDict::ExprDict( CmpKey cmp, Hash hash, Arena *arena )
821
: _expr(cmp, hash, arena), _defines() {
822
}
823
ExprDict::~ExprDict() {
824
}
825
826
// Return # of name-Expr pairs in dict
827
int ExprDict::Size(void) const {
828
return _expr.Size();
829
}
830
831
// define inserts the given key-value pair into the dictionary,
832
// and records the name in order for later output, ...
833
const Expr *ExprDict::define(const char *name, Expr *expr) {
834
const Expr *old_expr = (*this)[name];
835
assert(old_expr == NULL, "Implementation does not support redefinition");
836
837
_expr.Insert(name, expr);
838
_defines.addName(name);
839
840
return old_expr;
841
}
842
843
// Insert inserts the given key-value pair into the dictionary. The prior
844
// value of the key is returned; NULL if the key was not previously defined.
845
const Expr *ExprDict::Insert(const char *name, Expr *expr) {
846
return (Expr*)_expr.Insert((void*)name, (void*)expr);
847
}
848
849
// Finds the value of a given key; or NULL if not found.
850
// The dictionary is NOT changed.
851
const Expr *ExprDict::operator [](const char *name) const {
852
return (Expr*)_expr[name];
853
}
854
855
void ExprDict::print_defines(FILE *fp) {
856
fprintf(fp, "\n");
857
const char *name = NULL;
858
for( _defines.reset(); (name = _defines.iter()) != NULL; ) {
859
const Expr *expr = (const Expr*)_expr[name];
860
assert( expr != NULL, "name in ExprDict without matching Expr in dictionary");
861
expr->print_define(fp);
862
}
863
}
864
void ExprDict::print_asserts(FILE *fp) {
865
fprintf(fp, "\n");
866
fprintf(fp, " // Following assertions generated from definition section\n");
867
const char *name = NULL;
868
for( _defines.reset(); (name = _defines.iter()) != NULL; ) {
869
const Expr *expr = (const Expr*)_expr[name];
870
assert( expr != NULL, "name in ExprDict without matching Expr in dictionary");
871
expr->print_assert(fp);
872
}
873
}
874
875
// Print out the dictionary contents as key-value pairs
876
static void dumpekey(const void* key) { fprintf(stdout, "%s", (char*) key); }
877
static void dumpexpr(const void* expr) { fflush(stdout); ((Expr*)expr)->print(); }
878
879
void ExprDict::dump() {
880
_expr.print(dumpekey, dumpexpr);
881
}
882
883
884
//------------------------------ExprDict::private------------------------------
885
// Disable public use of constructor, copy-ctor, operator =, operator ==
886
ExprDict::ExprDict( ) : _expr(cmpkey,hashkey), _defines() {
887
assert( false, "NotImplemented");
888
}
889
ExprDict::ExprDict( const ExprDict & ) : _expr(cmpkey,hashkey), _defines() {
890
assert( false, "NotImplemented");
891
}
892
ExprDict &ExprDict::operator =( const ExprDict &rhs) {
893
assert( false, "NotImplemented");
894
_expr = rhs._expr;
895
return *this;
896
}
897
// == compares two dictionaries; they must have the same keys (their keys
898
// must match using CmpKey) and they must have the same values (pointer
899
// comparison). If so 1 is returned, if not 0 is returned.
900
bool ExprDict::operator ==(const ExprDict &d) const {
901
assert( false, "NotImplemented");
902
return false;
903
}
904
905
906
//------------------------------Production-------------------------------------
907
Production::Production(const char *result, const char *constraint, const char *valid) {
908
initialize();
909
_result = result;
910
_constraint = constraint;
911
_valid = valid;
912
}
913
914
void Production::initialize() {
915
_result = NULL;
916
_constraint = NULL;
917
_valid = knownInvalid;
918
_cost_lb = Expr::get_unknown();
919
_cost_ub = Expr::get_unknown();
920
}
921
922
void Production::print() {
923
printf("%s", (_result == NULL ? "NULL" : _result ) );
924
printf("%s", (_constraint == NULL ? "NULL" : _constraint ) );
925
printf("%s", (_valid == NULL ? "NULL" : _valid ) );
926
_cost_lb->print();
927
_cost_ub->print();
928
}
929
930
931
//------------------------------ProductionState--------------------------------
932
void ProductionState::initialize() {
933
_constraint = noConstraint;
934
935
// reset each Production currently in the dictionary
936
DictI iter( &_production );
937
const void *x, *y = NULL;
938
for( ; iter.test(); ++iter) {
939
x = iter._key;
940
y = iter._value;
941
Production *p = (Production*)y;
942
if( p != NULL ) {
943
p->initialize();
944
}
945
}
946
}
947
948
Production *ProductionState::getProduction(const char *result) {
949
Production *p = (Production *)_production[result];
950
if( p == NULL ) {
951
p = new Production(result, _constraint, knownInvalid);
952
_production.Insert(result, p);
953
}
954
955
return p;
956
}
957
958
void ProductionState::set_constraint(const char *constraint) {
959
_constraint = constraint;
960
}
961
962
const char *ProductionState::valid(const char *result) {
963
return getProduction(result)->valid();
964
}
965
966
void ProductionState::set_valid(const char *result) {
967
Production *p = getProduction(result);
968
969
// Update valid as allowed by current constraints
970
if( _constraint == noConstraint ) {
971
p->_valid = knownValid;
972
} else {
973
if( p->_valid != knownValid ) {
974
p->_valid = unknownValid;
975
}
976
}
977
}
978
979
Expr *ProductionState::cost_lb(const char *result) {
980
return getProduction(result)->cost_lb();
981
}
982
983
Expr *ProductionState::cost_ub(const char *result) {
984
return getProduction(result)->cost_ub();
985
}
986
987
void ProductionState::set_cost_bounds(const char *result, const Expr *cost, bool has_state_check, bool has_cost_check) {
988
Production *p = getProduction(result);
989
990
if( p->_valid == knownInvalid ) {
991
// Our cost bounds are not unknown, just not defined.
992
p->_cost_lb = cost->clone();
993
p->_cost_ub = cost->clone();
994
} else if (has_state_check || _constraint != noConstraint) {
995
// The production is protected by a condition, so
996
// the cost bounds may expand.
997
// _cost_lb = min(cost, _cost_lb)
998
if( cost->less_than_or_equal(p->_cost_lb) ) {
999
p->_cost_lb = cost->clone();
1000
}
1001
// _cost_ub = max(cost, _cost_ub)
1002
if( p->_cost_ub->less_than_or_equal(cost) ) {
1003
p->_cost_ub = cost->clone();
1004
}
1005
} else if (has_cost_check) {
1006
// The production has no condition check, but does
1007
// have a cost check that could reduce the upper
1008
// and/or lower bound.
1009
// _cost_lb = min(cost, _cost_lb)
1010
if( cost->less_than_or_equal(p->_cost_lb) ) {
1011
p->_cost_lb = cost->clone();
1012
}
1013
// _cost_ub = min(cost, _cost_ub)
1014
if( cost->less_than_or_equal(p->_cost_ub) ) {
1015
p->_cost_ub = cost->clone();
1016
}
1017
} else {
1018
// The costs are unconditionally set.
1019
p->_cost_lb = cost->clone();
1020
p->_cost_ub = cost->clone();
1021
}
1022
1023
}
1024
1025
// Print out the dictionary contents as key-value pairs
1026
static void print_key (const void* key) { fprintf(stdout, "%s", (char*) key); }
1027
static void print_production(const void* production) { fflush(stdout); ((Production*)production)->print(); }
1028
1029
void ProductionState::print() {
1030
_production.print(print_key, print_production);
1031
}
1032
1033