# 循环展开

循环展开是一种编译器优化技术，它将循环体复制若干次，并调整控制迭代次数的逻辑，使得每次经过循环时执行原本多次迭代的工作量。<sup>[1](https://www.sciencedirect.com/topics/computer-science/loop-unrolling)</sup> 编译器文献中将其描述为或许是最古老、最简单、最广为人知的循环变换。<sup>[1](https://www.sciencedirect.com/topics/computer-science/loop-unrolling)</sup>

| 关键事实 | 详情 |
|---|---|
| 变换方式 | 复制循环体并调整迭代控制逻辑；内层循环或外层循环均可展开。<sup>[1](https://www.sciencedirect.com/topics/computer-science/loop-unrolling)</sup> |
| 收益 | 减少循环分支开销，并为局部优化、向量化和指令调度提供更好的机会。<sup>[2](https://docs.nvidia.com/hpc-sdk/archive/26.1/compilers/hpc-compilers-user-guide/index.html)</sup> |
| 指令级并行 | 扩大可被有效调度的直线代码片段。<sup>[3](https://dpvipracollege.ac.in/wp-content/uploads/2023/01/Computer-Architecture-A-Quantitative-Approach-4th-Edition.pdf)</sup> |
| 主要代价 | 代码膨胀，可能通过缓存效应损害性能。<sup>[4](https://gnu.googlesource.com/gcc/%2B/refs/heads/releases/gcc-7/gcc/loop-unroll.c)</sup> |
| 形式 | 完全展开（需要已知的常量行程计数）、带余数循环的部分展开，以及编译时行程计数未知时的运行时展开。<sup>[5](https://llvm.org/docs/TransformMetadata.html)</sup> |
| 程序员控制 | Clang 和 CUDA 中的 `#pragma unroll`、`#pragma nounroll` 和 `#pragma unroll N`；GCC 中的 `-funroll-loops` 和 `-funroll-all-loops`。<sup>[6](https://clang.llvm.org/docs/AttributeReference.html)</sup><sup> • </sup><sup>[7](https://man7.org/linux/man-pages/man1/gcc.1.html)</sup> |
| 相关变换 | 展开并合并（unroll-and-jam）展开外层循环，并将由此产生的内层循环融合为一个。<sup>[8](https://llvm.org/docs/Passes.html?lang=en)</sup> |

## 变换的工作原理

展开一个循环，即由编译器复制其循环体并相应地修改迭代控制逻辑。循环嵌套中的内层循环或外层循环均可展开。<sup>[1](https://www.sciencedirect.com/topics/computer-science/loop-unrolling)</sup> 在 LLVM 的变换元数据模型中，对原始循环

    for (int i = 0; i < n; i+=1)
      Stmt(i);

以展开因子 4 进行部分展开或运行时展开，会生成一个每次迭代执行四条语句的展开后循环，随后是一个处理剩余迭代的余数循环：

    int i = 0;
    for (; i + 3 < n; i+=4) {
      Stmt(i);
      Stmt(i+1);
      Stmt(i+2);
      Stmt(i+3);
    }
    for (; i < n; i+=1)
      Stmt(i);

完全展开则彻底消除循环，因此在这种情况下不存在后续循环。<sup>[5](https://llvm.org/docs/TransformMetadata.html)</sup>

## 编译器为何展开循环

**更少的分支和退出测试。** 复制循环体减少了循环分支开销，并为后续遍次提供了更好的局部优化、向量化和指令调度机会。<sup>[2](https://docs.nvidia.com/hpc-sdk/archive/26.1/compilers/hpc-compilers-user-guide/index.html)</sup> GCC 的实现说明指出，展开执行次数为常量的循环几乎总是有益的，因为退出条件测试消失了，而且收益还来自代码顺序性的增强以及为后续优化遍次提供更好的代码。<sup>[4](https://gnu.googlesource.com/gcc/%2B/refs/heads/releases/gcc-7/gcc/loop-unroll.c)</sup>

**指令级并行。** 展开增加了可被有效调度的直线代码片段的大小，暴露出流水线或超标量处理器可以重叠执行的独立指令。<sup>[3](https://dpvipracollege.ac.in/wp-content/uploads/2023/01/Computer-Architecture-A-Quantitative-Approach-4th-Edition.pdf)</sup>

**代价。** 主要问题是代码膨胀，它通过影响缓存而对性能产生负面影响；因此 GCC 的展开器将自身限制在最内层循环上，因为那里性能影响最大，从而避免不必要的代码体积增长。<sup>[4](https://gnu.googlesource.com/gcc/%2B/refs/heads/releases/gcc-7/gcc/loop-unroll.c)</sup> 展开还会提高寄存器压力，即由于扩大后的循环体中更长的活跃区间而产生的对处理器寄存器的需求。<sup>[3](https://dpvipracollege.ac.in/wp-content/uploads/2023/01/Computer-Architecture-A-Quantitative-Approach-4th-Edition.pdf)</sup>

## 展开的形式

LLVM 区分三种形式：完全展开、对具有常量行程计数的循环进行部分展开，以及对编译时行程计数未知的循环进行运行时展开。<sup>[5](https://llvm.org/docs/TransformMetadata.html)</sup> 其 `loop-unroll` 遍次在循环已被 `indvars` 遍次规范化时效果最佳，因为规范化使行程计数易于确定；完全展开需要已知的常量行程计数。<sup>[8](https://llvm.org/docs/Passes.html?lang=en)</sup><sup> • </sup><sup>[9](https://llvm.org/devmtg/2023-05/slides/Tutorial-May10/01-Popov-AWhirlwindTour-oftheLLVMOptimizer.pdf)</sup>

## 展开并合并

将循环嵌套中的外层循环以展开因子 4 展开，会产生四个内层循环；将这些内层循环体组合起来——这一变换称为循环融合——通常被称为展开并合并。<sup>[1](https://www.sciencedirect.com/topics/computer-science/loop-unrolling)</sup> LLVM 的 `loop-unroll-and-jam` 遍次将

    for i.. i+= 1
      for j..
        code(i, j)

变换为一个包含 `code(i, j)`、`code(i+1, j)`、`code(i+2, j)` 和 `code(i+3, j)` 的单一内层循环，外加一个余数循环。当变量或加载可以在新的内层循环中共享时，这可以带来显著的性能提升，该遍次使用依赖分析来证明变换是安全的。<sup>[8](https://llvm.org/docs/Passes.html?lang=en)</sup>

## 程序员控制

**编译指示。** Clang 接受 `#pragma unroll` 和 `#pragma nounroll`，紧接在 for、while、do-while 或 C++11 基于范围的 for 循环之前，并支持 GCC 的 `#pragma GCC unroll` 和 `#pragma GCC nounroll`，语义相同。不带参数的 `#pragma unroll` 指示展开器在编译时已知行程计数的情况下完全展开循环，否则部分展开；`#pragma unroll 16` 请求展开因子为 16；`#pragma nounroll` 请求不展开。Clang 还提供 `unroll_and_jam` 和 `nounroll_and_jam` 提示。<sup>[6](https://clang.llvm.org/docs/AttributeReference.html)</sup> 在 CUDA 中，编译器默认展开行程计数已知的小循环；不带参数的 `#pragma unroll` 完全展开具有常量行程计数的循环，值为 0 或 1 时禁用展开，非正值或大于 `INT_MAX` 的值将被忽略并给出警告。<sup>[10](https://docs.nvidia.com/cuda/cuda-programming-guide/pdf/cuda-programming-guide.pdf)</sup>

**编译器标志和元数据。** GCC 的 `-funroll-loops` 展开迭代次数可在编译时或进入循环时确定的循环；它隐含启用 `-frerun-cse-after-loop`、`-fweb` 和 `-frename-registers`，开启完整的循环剥离，使代码变大，可能加快也可能不加快运行速度。`-funroll-all-loops` 即使迭代次数不确定也展开所有循环，这通常使程序运行更慢。<sup>[7](https://man7.org/linux/man-pages/man1/gcc.1.html)</sup> 在 x86 目标上，GCC 在 `-O2` 时默认启用 `-munroll-only-small-loops`，将少于 4 条指令的循环展开 1 次，以提高现代处理器上指令解码流水线的利用率。<sup>[11](https://gcc.sourceware.org/onlinedocs/gcc/x86-Options.html)</sup> 在 LLVM IR 中，`llvm.loop.unroll.count` 设置一个优先的展开因子，覆盖成本模型；`llvm.loop.unroll.disable` 即使循环在其他情况下允许展开也对其禁用展开。<sup>[12](https://www.llvm.org/devmtg/2016-11/Slides/Finkel-IntrinsicsMetadataAttributes.pdf)</sup> 由 `llvm.loop.unroll.enable` 元数据或 `llvm.loop.unroll.count`、`llvm.loop.unroll.full` 等选项指定的展开被视为强制性的，如果强制变换无法执行，必须发出优化未命中的警告。<sup>[5](https://llvm.org/docs/TransformMetadata.html)</sup>

## 实践中的调优与权衡

由于收益取决于代码大小、寄存器压力和缓存行为，最佳的展开因子是通过测量而非最大化来找到的。英伟达（NVIDIA）的一项案例研究在 GPU 上对史密斯-沃特曼（Smith-Waterman）DNA 序列比对代码的两个最外层循环扫描了 0 到 4 的展开因子：更重的展开扩大了指令内存占用，增加了指令缓存未命中，并导致编译器为每个线程分配更多寄存器，从而使得流式多处理器上可驻留的线程束（warp）更少。在不同工作负载大小下，最佳平均性能来自顶层循环不展开、第二层循环展开因子为 2 的配置，这使指令线程束停顿保持可忽略，同时减少了每线程寄存器数并改善了延迟隐藏。<sup>[13](https://developer.nvidia.com/blog/improving-gpu-performance-by-reducing-instruction-cache-misses-2/)</sup> 同一研究指出，总指令内存占用是指令缓存压力的不完美度量，因为它包含仅执行少数几次的代码；最热代码的总体大小是更好的指导指标。<sup>[13](https://developer.nvidia.com/blog/improving-gpu-performance-by-reducing-instruction-cache-misses-2/)</sup>

因此编译器默认依赖成本模型。LLVM 的展开器可以使用成本模型来确定展开循环是否有益，并且仅在优化器认为变换安全且有益时才应用提示。<sup>[14](https://llvm.org/doxygen/structllvm_1_1LoopUnrollOptions.html)</sup><sup> • </sup><sup>[15](https://app.readthedocs.org/projects/llvm/downloads/pdf/release_39/)</sup>

## References

1. [Loop Unrolling, ScienceDirect Topics (from Keith D. Cooper and Linda Torczon, *Engineering a Compiler*, Third Edition, 2023)](https://www.sciencedirect.com/topics/computer-science/loop-unrolling)
2. [NVIDIA HPC Compilers User's Guide, version 26.1](https://docs.nvidia.com/hpc-sdk/archive/26.1/compilers/hpc-compilers-user-guide/index.html)
3. [John L. Hennessy and David A. Patterson, *Computer Architecture: A Quantitative Approach*, 4th Edition, Chapter 2, Instruction-Level Parallelism and Its Exploitation](https://dpvipracollege.ac.in/wp-content/uploads/2023/01/Computer-Architecture-A-Quantitative-Approach-4th-Edition.pdf)
4. [gcc/loop-unroll.c, GCC source, release/gcc-7 branch](https://gnu.googlesource.com/gcc/%2B/refs/heads/releases/gcc-7/gcc/loop-unroll.c)
5. [Code Transformation Metadata, LLVM documentation](https://llvm.org/docs/TransformMetadata.html)
6. [Attributes in Clang, Clang documentation](https://clang.llvm.org/docs/AttributeReference.html)
7. [gcc(1) Linux manual page](https://man7.org/linux/man-pages/man1/gcc.1.html)
8. [LLVM's Analysis and Transform Passes, LLVM documentation](https://llvm.org/docs/Passes.html?lang=en)
9. [A Whirlwind Tour of the LLVM Optimizer, LLVM Developers' Meeting 2023 tutorial slides](https://llvm.org/devmtg/2023-05/slides/Tutorial-May10/01-Popov-AWhirlwindTour-oftheLLVMOptimizer.pdf)
10. [CUDA Programming Guide, Release 13.2, NVIDIA](https://docs.nvidia.com/cuda/cuda-programming-guide/pdf/cuda-programming-guide.pdf)
11. [x86 Options, Using the GNU Compiler Collection (GCC)](https://gcc.sourceware.org/onlinedocs/gcc/x86-Options.html)
12. [!llvm.loop.* Metadata Optimization Control, LLVM Developers' Meeting 2016 slides (Hal Finkel)](https://www.llvm.org/devmtg/2016-11/Slides/Finkel-IntrinsicsMetadataAttributes.pdf)
13. [Improving GPU Performance by Reducing Instruction Cache Misses, NVIDIA Technical Blog](https://developer.nvidia.com/blog/improving-gpu-performance-by-reducing-instruction-cache-misses-2/)
14. [llvm::LoopUnrollOptions Struct Reference, LLVM Doxygen](https://llvm.org/doxygen/structllvm_1_1LoopUnrollOptions.html)
15. [LLVM Documentation, release 3.9 PDF](https://app.readthedocs.org/projects/llvm/downloads/pdf/release_39/)

---
*Initially written Oct 15, 2026*

Topic: 技术与人造世界 › 计算技术与数字系统 › 软件与编程 › Compilers, interpreters, and toolchains › Loop and vectorizing optimizations

Copyright 2026 Edgepedia

License: Edgepedia Community License 1.0, https://www.edgepedia.org/edgepedia/license

Source: https://www.edgepedia.org/zh/loop-unrolling

English original: https://www.edgepedia.org/loop-unrolling
