Which of the following best describes the purpose of loop-invariant code motion in compiler optimization?
Think about what can be done to avoid repeating the same calculation multiple times inside a loop.
Loop-invariant code motion moves computations that produce the same result on every iteration outside the loop. This reduces the number of times the calculation is performed, improving efficiency.
Consider the following loop:
for (int i = 0; i < n; i++) {
int x = a + b;
arr[i] = x * i;
}Which statement is loop-invariant and can be moved outside the loop?
Look for calculations that do not depend on the loop variable i.
The expression a + b does not depend on i and remains constant during the loop. So, int x = a + b; can be moved outside the loop.
Given a loop that executes 1,000,000 times, which of the following changes will most likely improve performance by applying loop-invariant code motion?
for (int i = 0; i < 1000000; i++) {
int y = 5 * 10;
process(y, i);
}Consider which calculation is repeated unnecessarily inside the loop.
Computing 5 * 10 inside the loop repeats the same calculation 1,000,000 times. Moving it outside the loop computes it once, reducing overhead and improving performance.
Which of the following statements correctly compares loop-invariant code motion with loop unrolling?
Think about what each optimization tries to reduce: repeated calculations or loop control overhead.
Loop-invariant code motion reduces repeated calculations by moving them outside the loop. Loop unrolling reduces the overhead of loop control by repeating the loop body multiple times inside a single iteration.
Consider the nested loops below:
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
int z = a + b;
arr[i][j] = z * i * j;
}
}Which is the safest and most effective loop-invariant code motion to optimize this code?
Check if the expression depends on loop variables i or j.
The expression a + b does not depend on either i or j. Moving it outside both loops computes it once, saving repeated calculations in all iterations.