A) Insider jargon makes this a bit opaque. “optimization of the IR†where “IR†is what? Plz spell out first time referenced.
B) “we may be able to make the reference to x in table[x]†- meaning uncertain here. Do you mean ‘re-use the reference to x we develop in expression ‘table[x]’?
C) In any case, how far ahead is this optimizer looking? In the given example
int x = 3, y;
if (table[x] > 0) {
y = x * 3;
} else {
y = x * 6;
}
C1) Neither variable x or y bring external information at entry in to this code section.
C2) The variable ‘x’ is never used as a Left Hand Side (LHS) in other than the initial assignment.
C3) There is no indication that x is subject to async value changes.
Thus I suggest the optimization here is simple constant propagation (https://en.wikipedia.org/wiki/Constant_folding) giving the following re-write avoiding a register allocation for variable x within conditional code entirely:
int y;
if( table[ 3 ] > 0 ) {
# known at compile time
y = 3 * 3 ; # further re-write as y = 9 ;
} else {
# known at compile time
y = 3 * 6; # further re-write as y = 18 ;
}
int x ;
x = 3 ; # Only needed if value of x assigned here is used downstream as an Right Hand Side (RHS)
OTOH, if the code example is:
int x = some_earlier_or_outer_scope_type_cast_compatible_variable_FOO, y;
if (table[x] > 0) {
y = x * 3;
} else {
y = x * 6;
}
Then x is no longer a locally known constant at compile time so constant propagation is out. The next question then is the initialization of x a typecast on FOO? If FOO is defined as int FOO, then no, so since variable x is never locally used as a RHS then variable x is locally pointless and there may be advantage in re-writing as:
int y;
if (table[ FOO ] > 0) {
y = FOO * 3;
} else {
y = FOO * 6;
}
int x ;
# Only needed if value of x assigned here is used downstream as an Right Hand Side (RHS)
x = some_earlier_or_outer_scope_type_cast_compatible_variable_FOO;
If the assignment x = FOO IS as typecast, then for safety variable x or some object in that role must have allocated storage (register or otherwise) and be initialized per the “int x = FOO†assignment prior to entry in to the “table[ x ]†expression. Inverting this logic, from an optimization POV, entry in to the expression “table[ x ]†should be recognized as an optimizer barrier on object “xâ€, meaning regardless of how variable x is used after expression “table[ x ]â€, variable x must be fully realized as a variable RHS value in some way prior to expression “table[ x ]â€.