Consider these two functions and two statements S1 and S2 about them.
int work1(int *a, int i, int j)
{
int x = a[i+2];
a[j] = x+1;
return a[i+2] - 3;
} | int work2(int *a, int i, int j)
{
int t1 = i+2;
int t2 = a[t1];
a[j] = t2+1;
return t2 - 3;
} |
S1: The transformation form work1 to work2 is valid, i.e., for any program state and input arguments, work2 will compute the same output and have the same effect on program state as work1
S2: All the transformations applied to work1 to get work2 will always improve the performance (i.e reduce CPU time) of work2 compared to work1
View worked solution
Answer: A
To evaluate the statements, let us analyze the behavior of both functions under the condition of pointer aliasing, specifically when j == i + 2.
Statement S1:
Let the array be a = {10, 20, 30}, with i = 0 and j = 2 (so j == i + 2).
- In
work1:x = a[2] = 30a[2] = x + 1 = 31- The function returns
a[2] - 3 = 31 - 3 = 28.
- In
work2:t1 = 2t2 = a[2] = 30a[2] = t2 + 1 = 31- The function returns
t2 - 3 = 30 - 3 = 27.
Since the returned values are different (), the transformation is invalid. Thus, S1 is false.
Statement S2:
An invalid compiler optimization that alters the program's semantics cannot be considered a valid performance improvement. Furthermore, introducing additional local variables (like t1 and t2) increases register pressure. In resource-constrained environments, this can lead to register spilling to memory, which actually degrades performance. Thus, S2 is false.
Free practice · Your answers on this page are not saved.
