3 ms·
The "not grouped by parentheses" is already where things go wrong. Parentheses should determine the syntactic parse of the expression, not the order of evaluati
by kazinator 12y ago
The "not grouped by parentheses" is already where things go wrong. Parentheses should determine the syntactic parse of the expression, not the order of evaluation. Optimization works with an abstract representation of the program where the parenthesis tokens are long gone.
That is to say (a + b) + c should not have any influence relative to a + b + c, at least if addition is already left associative. Because then a + b + c already means (a + b) + c. Adding the parentheses to make (a + b) + c doesn't change the parse whatsoever.
If parentheses are needed to establish the precise meaning, it means that the compiler writer has neglected to document, and commit to, an associativity for the operator; the compiler writer has not specified whether a + b + c means (a + b) + c or a + (b + c). That is a mistake: a gratuitous ambiguity in the syntax of the programming language.
If there is such a mistake in the design, a stray ambiguity, then you cannot call the optimization wrong. If it is not specified whether a + b + c means (a + b) + c, or a + (b + c) or something else like add3_in_any_order(a, b, c), then the compiler is in fact free to use any of the possible parses as a guide for the operation order.
- Joky 12y agoIndeed: "The ANSI Fortran standard is less restrictive than the C standard: it requires the compiler to respect the order of evaluation specified by parentheses, but otherwise allows the compiler to reorder expressions as it sees fit."
- kazinator 12y agoThat piece of text, if taken literally and perhaps out of context, means that if we have a * b + c, the Fortran compiler is allowed to add b+c first, and then multiply by a, because there are no parentheses. It's just a question of whether the compiler writers "sees fit" such a thing. In C, the order of operations is not ambiguous, and is distinct from the evaluation order. In a * b + c, three operands a, b and c have to be evaluated (the variables be reduced to the operand values they hold). This evaluation takes place in an unspecified order (possibly leading to undefined behavior). On these values, however, the arithmetic order of operations is clear: multiplication takes precedence and so is done first. The evaluation order makes a difference if the expressions a, b and c themselves have side effects.