汇编语言循环结构
系统讲解 LOOP/LOOPE/LOOPNE 指令家族与 ECX 计数器保护、WHILE 与 DO-WHILE 条件循环、嵌套循环栈保存技巧、循环展开优化及 1 到 100 求和。
学完这一章,你能够
- 系统讲解 LOOP/LOOPE/LOOPNE 指令家族与 ECX 计数器保护、WHILE 与 DO-WHILE 条件循环、嵌套循环栈保存技巧、循环展开优化及 1 到 100 求和。
LOOP 指令家族与 ECX 计数器保护
循环是重复计算的核心控制结构。x86 专用指令 `LOOP label` 默认以 `ECX`(16 位模式用 `CX`,64 位用 `RCX`)为计数器,每次执行先把 `ECX` 减 1,若结果不为 0 则跳回目标标签。由于系统调用(如 `sys_write` 需要用 `ECX` 传入字符串地址)会覆盖 `ECX`,在循环体内发起调用前必须 `push ecx`、调用后 `pop ecx` 以保护计数。
`LOOP` 还提供结合零标志 `ZF` 的条件变体(见下表):`LOOPE`/`LOOPZ` 在 `ECX != 0` 且 `ZF = 1` 时继续循环(例如在字节数组 `[0, 0, 0, 5, 0, 0]` 中跳过前导零定位首个非零元素 5);`LOOPNE`/`LOOPNZ` 则在 `ECX != 0` 且 `ZF = 0` 时继续循环,常用于查找第一个匹配项。
WHILE、DO-WHILE 与嵌套循环
除定次 `LOOP` 外,通用条件循环由 `CMP` 与条件跳转构建:`WHILE` 循环在头部先比较条件(如 `while (x < 100) x *= 2`,当 `x >= 100` 时 `jge while_end` 跳出,最终倍增到 128);`DO-WHILE` 循环则先执行一次循环体,再在尾部判断条件决定是否跳回,保证循环体至少运行一次。
编写双重及多层嵌套循环时,最常见的致命错误是内层循环直接重设 `ECX` 导致外层计数器丢失。标准做法是在外层循环刚进入内层前执行 `push ecx` 将外层计数暂存到栈上,待内层循环完全结束后再 `pop ecx` 恢复并执行外层 `loop`。
循环性能优化与 1 到 100 累加综合示例
现代 x86 处理器上,`dec ecx` + `jnz` 往往比微码实现的 `LOOP` 指令更快;进一步可采用 4 路循环展开(减少分支判断与指针递增频率)或从数组末尾倒计数减少显式上界比较。综合示例以 `ECX=100`、`EBX=1` 逐次 `add eax, ebx` 并 `inc ebx`,精准得到 `1+2+...+100 = 5050`;同样需注意 5050 是四位数,直接 `add al, '0'` 无法正确打印,完整的多位数转字符串算法见下一章“数字处理”。
x86 LOOP 指令及条件变体对照
| 指令 | 跳转条件 | 说明 |
|---|---|---|
| LOOP | ECX != 0 | 先将 ECX 减 1,若结果非零则跳转到目标标签。 |
| LOOPE / LOOPZ | ECX != 0 且 ZF = 1 | ECX 减 1 后仍非零且上次比较相等(ZF=1)时继续循环。 |
| LOOPNE / LOOPNZ | ECX != 0 且 ZF = 0 | ECX 减 1 后仍非零且上次比较不等(ZF=0)时继续循环。 |
离线模拟 LOOP/LOOPE/LOOPNE、WHILE/DO-WHILE、嵌套循环栈保护与 4 路展开求和
"""Offline x86/NASM semantic verification lab for Chapter 14 (loop)."""
import json
VERSION = "CPython 3.12.14 offline x86/NASM semantic verifier (nasm/ld/gdb absent)"
def case_loop_and_loope_loopne_variants():
# Basic LOOP 5 times with push/pop ECX around syscall
ecx = 5
outputs = []
stack = []
while True:
stack.append(ecx)
outputs.append("mbsky")
ecx = stack.pop()
ecx -= 1
if ecx == 0:
break
# LOOPE: scan [0, 0, 0, 5, 0, 0] for first non-zero
arr = [0, 0, 0, 5, 0, 0]
ecx_e = len(arr)
esi = -1
while True:
esi += 1
zf = 1 if arr[esi] == 0 else 0
ecx_e -= 1
if not (ecx_e != 0 and zf == 1):
break
# LOOPNE: scan [1, 2, 0, 4] until finding 0
arr2 = [1, 2, 0, 4]
ecx_ne = len(arr2)
edi = -1
while True:
edi += 1
zf2 = 1 if arr2[edi] == 0 else 0
ecx_ne -= 1
if not (ecx_ne != 0 and zf2 == 0):
break
expected = {
"loop_output_count": 5,
"loope_found_index": 3,
"loope_found_val": 5,
"loope_remaining_ecx": 2,
"loopne_zero_index": 2,
}
actual = {
"loop_output_count": len(outputs),
"loope_found_index": esi,
"loope_found_val": arr[esi],
"loope_remaining_ecx": ecx_e,
"loopne_zero_index": edi,
}
return {
"name": "loop_and_loope_loopne_variants",
"summary": "模拟标准 LOOP(带栈保护 ECX)、LOOPE 查找首个非零项与 LOOPNE 查找首个零值",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_while_and_do_while_control_flow():
# while (x < 100) x = x * 2
x = 1
while_trace = [x]
while x < 100:
x <<= 1
while_trace.append(x)
# do-while: executes at least once even if condition is already false
counter = 0
while True:
counter += 1
if not (counter < 5):
break
counter_already_high = 10
do_once_runs = 0
while True:
counter_already_high += 1
do_once_runs += 1
if not (counter_already_high < 5):
break
expected = {
"while_final_x": 128,
"while_steps": 7,
"do_while_counter": 5,
"do_while_executes_at_least_once": 1,
}
actual = {
"while_final_x": x,
"while_steps": len(while_trace) - 1,
"do_while_counter": counter,
"do_while_executes_at_least_once": do_once_runs,
}
return {
"name": "while_and_do_while_control_flow",
"summary": "验证先判后执 WHILE 倍增至 128 与先执后判 DO-WHILE 至少执行一次的控制流语义",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_nested_loop_and_unrolling_sum():
# Nested 3x3 loop saving outer ECX on stack
stack = []
outer_ecx = 3
grid = []
while True:
stack.append(outer_ecx)
row_idx = 4 - outer_ecx
inner_ecx = 3
row = []
while True:
col_idx = 4 - inner_ecx
row.append(row_idx * col_idx)
inner_ecx -= 1
if inner_ecx == 0:
break
grid.append(row)
outer_ecx = stack.pop()
outer_ecx -= 1
if outer_ecx == 0:
break
# Loop unrolling (factor 4) vs standard sum over 1..100
nums = list(range(1, 101))
sum_loop = sum(nums)
sum_unrolled = 0
for i in range(0, len(nums), 4):
sum_unrolled += nums[i] + nums[i + 1] + nums[i + 2] + nums[i + 3]
sum_reverse = 0
for idx in range(len(nums) - 1, -1, -1):
sum_reverse += nums[idx]
expected = {
"grid_3x3": [[1, 2, 3], [2, 4, 6], [3, 6, 9]],
"stack_balanced": True,
"sum_1_to_100": 5050,
"unrolled_matches": True,
"reverse_matches": True,
}
actual = {
"grid_3x3": grid,
"stack_balanced": len(stack) == 0,
"sum_1_to_100": sum_loop,
"unrolled_matches": sum_unrolled == 5050,
"reverse_matches": sum_reverse == 5050,
}
return {
"name": "nested_loop_and_unrolling_sum",
"summary": "验证嵌套循环压栈保护外层 ECX、4 路循环展开与倒序遍历累加 1..100 得 5050 的等价性",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def main():
cases = [
case_loop_and_loope_loopne_variants(),
case_while_and_do_while_control_flow(),
case_nested_loop_and_unrolling_sum(),
]
print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
- 验证 LOOPE 在下标 3 找到非零值 5、WHILE 倍增至 128、DO-WHILE 至少执行一次及 1..100 求和 5050。
所需环境:Windows x64、CPython 3.12.14 离线 x86/NASM 寄存器、标志位与内存语义验证器(本机未安装 nasm/ld/gdb)。
当前源码 SHA256:a0254609db219bc7425aaef2d9a57397cebdee1e82085616657d5de51f7173b6
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、CPython 3.12.14 离线 x86/NASM 寄存器、标志位与内存语义验证器(本机未安装 nasm/ld/gdb)。
ZIP SHA256:2b394ff1424dc7fbc81eb07bc6468430e641aa5f3060c08524e4ca155bdf05e6
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
如果把 `ECX` 初始化为 `0` 后直接进入 `loop repeat`(且无前置判断),32 位模式下循环体会被执行多少次?
展开参考解答
因为 `LOOP` 是先将 `ECX` 减 1 再判非零,`0 - 1` 会下溢回绕成 `0xFFFFFFFF`,导致循环异常执行 `2^32`(约 42.9 亿)次;因此当循环次数可能为 0 时应在循环前先用 `jecxz` 跳过。