This is a great question about compiler optimization, specifically about loop-invariant code motion (LICM). Let me provide a comprehensive explanation covering:
What loop invariant code is
How to identify it
How to move it outside the loop safely
What safety checks are needed
Examples
Practical considerations
Let me structure a detailed response.
Loop Invariant Code Motion (LICM)
Loop invariant code is code that produces the same result in every iteration. It can be safely moved outside the loop without changing program behavior.
Identification
Code is loop invariant if:
All operands are loop invariants (constants, loop-invariant values, or function results with no side effects)
The operation itself has no side effects
It doesn't depend on loop iteration count
Safety Checks
Dependency Analysis
Data dependencies: does the code depend on values that change in the loop?
Memory dependencies: does it read/write memory that's modified in the loop?
Control Flow Analysis
Does the code execute in every iteration?
Post-domination: is the loop exit guaranteed to happen?
Side Effects
Function calls with no side effects (pure functions)
I/O operations (cannot move)
Let me provide detailed examples with code.
Loop-Invariant Code Motion (LICM)
What is Loop-Invariant Code?
Code that computes the same value in every iteration and can be safely moved outside the loop.
Example
c
// BEFORE: Invariant code inside loop
for (int i = 0; i < n; i++) {
int result = a.length * 2; // Computed every iteration
array[i] = array[i] + result;
}
// AFTER: Moving invariant code outside
int result = a.length * 2; // Computed once
for (int i = 0; i < n; i++) {
array[i] = array[i] + result;
}
How to Identify Loop-Invariant Code
Criteria for Invariance
python
def is_loop_invariant(instruction, loop):
"""Check if instruction can be moved outside loop"""
# 1. All operands must be invariant
for operand in instruction.operands:
if operand in loop.loop_variables:
return False
# 2. No side effects
if has_side_effects(instruction):
return False
# 3. Reach-definitions analysis
if reaches_from_inside_loop(instruction):
return False
return True
Safety Checks: The 5-Point Strategy
1. Data Dependency Analysis
c
// UNSAFE - Depends on loop-changing value
for (int i = 0; i < n; i++) {
int val = i * 2; // ❌ Depends on i
sum += val;
}
// SAFE - No dependency on loop variable
for (int i = 0; i < n; i++) {
int val = x * 2; // ✓ x doesn't change
sum += val;
}
Implementation:
python
def has_loop_dependency(instruction, loop_vars):
"""Verify instruction doesn't use values modified in loop"""
for operand in instruction.operands:
if operand in loop_vars:
return True
return False
2. Control Flow Analysis: Domination Check
c
// UNSAFE - Not executed every iteration
for (int i = 0; i < n; i++) {
if (i % 2 == 0) {
int val = expensive_calc(); // ❌ Conditional
}
}
// SAFE - Always executes
for (int i = 0; i < n; i++) {
int val = expensive_calc(); // ✓ Unconditional
}
Algorithm:
python
def can_move_outside_loop(instruction, loop, cfg):
"""
Check if instruction dominates all loop exits
"""
# Get instruction's basic block
block = cfg.get_block(instruction)
# Must be in a block that dominates loop header
if not dominates(block, loop.header):
return False
# Must execute in every iteration path
for exit_block in loop.exit_blocks:
if not dominates(block, exit_block):
return False
return True
3. Anti-Dependency Check (Output Dependencies)
c
// UNSAFE - Value used after loop
int x = 0;
for (int i = 0; i < n; i++) {
int val = x + 1; // ❌ Can't move (x changes outside)
x = i;
}
use_value(x);
// SAFE - Local variable, not used after
for (int i = 0; i < n; i++) {
int val = (x + 1) * 2; // ✓ No external dependency
}
4. Memory Dependency Analysis
c
// UNSAFE - Array modified in loop
int a[10];
for (int i = 0; i < n; i++) {
int val = a[0]; // ❌ a[0] might change
a[i] = val + 1;
}
// SAFE - Disjoint memory access
int a[10];
for (int i = 0; i < n; i++) {
int val = b[0]; // ✓ b independent of loop
a[i] = val + 1;
}
Memory Analysis Algorithm:
python
def has_memory_conflict(instruction, loop):
"""Check if memory access conflicts with loop modifications"""
mem_accesses_in_loop = get_memory_accesses(loop)
instr_accesses = get_memory_accesses(instruction)
for instr_access in instr_accesses:
for loop_access in mem_accesses_in_loop:
# Check for read-write, write-read, write-write conflicts
if may_alias(instr_access, loop_access):
# Determine if truly conflicts
if instr_access.is_read and loop_access.is_write:
return True
if instr_access.is_write and loop_access.is_read:
return True
return False
5. Exception Safety
c
// UNSAFE - Exception during movement changes semantics
for (int i = 0; i < n; i++) {
int x = 1 / y; // ❌ Division by zero -
// moving changes when error occurs
array[i] = x;
}
// SAFE - No possible exceptions
for (int i = 0; i < n; i++) {
int x = 2 * y; // ✓ No exceptions
array[i] = x;
}
Complete LICM Algorithm
python
def hoist_loop_invariants(loop):
"""Main LICM algorithm"""
cfg = loop.get_cfg()
changed = True
while changed:
changed = False
for instruction in loop.get_all_instructions():
# Skip if already outside
if instruction not in loop.blocks:
continue
# Check all safety conditions
if (is_operand_invariant(instruction, loop) and
dominates_all_exits(instruction, loop) and
no_memory_conflicts(instruction, loop) and
no_side_effects(instruction) and
no_exception_issues(instruction)):
# Move to loop preheader
preheader = loop.get_preheader()
move_instruction(instruction, preheader)
changed = True
return loop
Practical Example: Real Compiler Transformation
c
// Original code
void process_matrix(int matrix[1000][1000], int n) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
// Multiple invariant expressions
int scale = matrix_size / 2; // Invariant
int offset = get_offset(); // Invariant
int factor = compute_factor(i); // i-invariant but j-invariant
matrix[i][j] = matrix[i][j] * scale
+ offset
+ factor * j;
}
}
}
// After LICM (outer loop)
void process_matrix(int matrix[1000][1000], int n) {
int scale = matrix_size / 2; // ← Moved out
int offset = get_offset(); // ← Moved out
for (int i = 0; i < n; i++) {
int factor = compute_factor(i); // ← Moved to outer preheader
for (int j = 0; j < n; j++) {
matrix[i][j] = matrix[i][j] * scale
+ offset
+ factor * j;
}
}
}
Compiler Implementation Checklist
python
LICM_SAFETY_CHECKS = {
"Operand Analysis": {
"All operands are loop-invariant": True,
"No loop variable dependencies": True,
},
"Control Flow": {
"Block dominates loop header": True,
"Executed in every iteration": True,
"Dominates all loop exits": True,
},
"Memory Safety": {
"No read-after-write aliases": True,
"No write-write conflicts": True,
"No memory escape": True,
},
"Side Effects": {
"No function calls with side effects": True,
"No I/O operations": True,
"No volatile accesses": True,
},
"Exceptions": {
"No throwing operations": True,
"Or exception safety preserved": True,
}
}
Performance Impact
Scenario
Speedup
Notes
Simple arithmetic
1.2-1.5x
Minimal overhead
Function calls
5-10x
Expensive functions
Memory access
1.1-1.3x
Cache benefits
Nested loops
2-3x
Compound effect
Key Takeaways
✅ Always verify all 5 safety conditions
✅ Use data flow and control flow analysis
✅ Consider memory aliasing carefully
✅ Preserve exception semantics
✅ Test with alias analysis tools