# 循环优化

循环优化是一组编译器变换，通过重构程序中的循环来提高执行速度或资源利用率，主要手段是增加并行性、改善内存局部性和启用向量化。与标量优化不同——后者利用数据流分析减少执行的指令数量——循环优化通过循环依赖分析追踪数组的性质，面向超标量、向量和并行处理器。<sup>[1](https://psycnet.apa.org/doi/10.1145/197405.197406)</sup> 编译器在结构上将循环识别为控制流图中从某节点指向支配该节点的头节点的回边，并优先优化内层循环，因为它们执行得最频繁。<sup>[2](https://www.cs.cmu.edu/~janh/courses/411/24/lectures/19-loopopt.pdf)</sup> 生产级编译器提供专用编译遍，如循环展开、循环交换、循环分布和循环向量化。<sup>[3](https://llvm.org/devmtg/2018-10/slides/Kruse-LoopTransforms.pdf)</sup>

| 关键事实 | 详情 |
|---|---|
| 变换对象 | 携带数组访问的循环嵌套，使用依赖分析而非标量数据流<sup>[1](https://psycnet.apa.org/doi/10.1145/197405.197406)</sup> |
| 核心变换 | 展开、分块、融合、分解（分布）、交换、倾斜、反转、向量化<sup>[3](https://llvm.org/devmtg/2018-10/slides/Kruse-LoopTransforms.pdf)</sup> |
| 合法性检验 | 每个变换后的依赖向量必须保持字典序为正<sup>[4](https://www.cs.cmu.edu/~411/slides/s25-19-loop-trans.pdf)</sup> |
| 分块经验法则 | 对矩阵乘法，缓存容量为 \( C \) 时取块大小 \( B = \sqrt{C} \) 可使缺失率最小<sup>[5](https://engineering.purdue.edu/~milind/docs/ieee08.pdf)</sup> |
| 实测收益 | 在 PolyBench 上，多面体优化在无线程级并行时达到 14 倍加速，启用线程级并行时超过 100 倍<sup>[6](https://www.infosun.fim.uni-passau.de/publications/docs/GGL2012ppl.pdf)</sup> |
| 主要失效模式 | 过度展开导致寄存器压力和指令缓存溢出<sup>[7](https://www.eecis.udel.edu/~xli/publications/PLDI2003.pdf)</sup>；过度融合对寄存器和缓存造成压力<sup>[8](https://ar5iv.labs.arxiv.org/html/1205.1098)</sup> |
| 实际上限 | 对 BLAS 风格的循环嵌套，编译器可能只能达到手工优化性能的约四分之一<sup>[8](https://ar5iv.labs.arxiv.org/html/1205.1098)</sup> |

## 工作原理

若 S 可能在 T 之前执行、两者访问同一内存位置、且至少有一次访问是写操作，则存在数据依赖 S → T。两个数组引用是否可能别名到同一元素，一般无法在编译期精确判定；找出真实依赖在静态意义上是不可判定的，因此编译器计算保守的过近似，存疑时即假定存在依赖。<sup>[9](https://www.ida.liu.se/~chrke55/courses/ACC/PDF-2023/Depend-Opt-Parallelization.pdf)</sup>

重排序变换的合法性源自 约翰·R. 艾伦（John R. Allen）与肯·肯尼迪（Ken Kennedy）教科书中的经典结论：任何保持所有依赖的重排序变换都保持程序语义。<sup>[10](https://ctop.cs.utah.edu/papers/ACACES/acaces-hall-L3.pdf)</sup> 在操作层面，依赖的距离向量 \( d = I_{t} - I_{s} \) 乘以[变换矩阵](https://www.edgepedia.org/zh/transformation-matrix)，变换合法当且仅当对每个非零距离向量 \( d \)，\( T \cdot d \) 的字典序为正。<sup>[4](https://www.cs.cmu.edu/~411/slides/s25-19-loop-trans.pdf)</sup><sup> • </sup><sup>[11](https://perso.ens-lyon.fr/frederic.vivien/Publications/Chapter-LNCS.pdf)</sup> 多面体模型对此做了扩展：具有仿射边界的完美嵌套循环的迭代空间是 \( \mathbb{Z}^{d} \) 中多面体的整数点集，表示为 \( Ax \le b \)，调度是仿射的时空映射；当对每个依赖 \( i \to j \) 都有 \( i \prec_{S} j \) 时，调度合法。<sup>[9](https://www.ida.liu.se/~chrke55/courses/ACC/PDF-2023/Depend-Opt-Parallelization.pdf)</sup><sup> • </sup><sup>[10](https://ctop.cs.utah.edu/papers/ACACES/acaces-hall-L3.pdf)</sup><sup> • </sup><sup>[12](https://heco.estue.nl/courses/ASCI-schools/ASCI_springschool_2017/asci-polyhedral-slides.pdf)</sup> 判定两个引用是否可能触及同一元素可归约为整数规划，其复杂度在系数规模上是 NP 完全的，而为融合选择最优的语句交错同样是 NP 完全的，因此实用系统采用剪枝和近似。<sup>[10](https://ctop.cs.utah.edu/papers/ACACES/acaces-hall-L3.pdf)</sup><sup> • </sup><sup>[13](https://dl.acm.org/doi/10.1145/1926385.1926449)</sup>

## 实现方式

主要变换的工作方式如下。交换（置换）调换循环顺序，将携带依赖的循环推向外层，留下可并行化的内层循环，并使内层循环按布局顺序遍历内存。<sup>[14](https://symbolaris.com/course/Compilers11/24-cacheloop.pdf)</sup> 以因子 \( f \) 倾斜，即在内层循环边界上加上 \( f \cdot i_{1} \)、从数组访问中减去 \( f \cdot i_{1} \)，将依赖方向 \( d \) 变为 \( (d_{1}, f \cdot (d_{1} + d_{2})) \)；先倾斜再交换可使模板计算的内层循环并行。<sup>[14](https://symbolaris.com/course/Compilers11/24-cacheloop.pdf)</sup> 融合合并具有相同头节点的相邻循环，当两者都不携带反向依赖时是安全的；它让中间值立即复用，而不必写入并重新加载一个放不进缓存的数组。<sup>[9](https://www.ida.liu.se/~chrke55/courses/ACC/PDF-2023/Depend-Opt-Parallelization.pdf)</sup><sup> • </sup><sup>[12](https://heco.estue.nl/courses/ASCI-schools/ASCI_springschool_2017/asci-polyhedral-slides.pdf)</sup> 分块是对若干循环头节点做分块再加交换，使扫描一个块的循环成为最内层；当某个操作数否则会在每次外层迭代中被逐出并重新加载时，分块有帮助；对 \( O(n^{3}) \) 矩阵乘法和大小为 \( M \) 的快速内存，大小为 \( \Theta(M^{1/2}) \) 的方形块可达到 \( \Omega(n^{3}/M^{1/2}) \) 的通信下界。<sup>[9](https://www.ida.liu.se/~chrke55/courses/ACC/PDF-2023/Depend-Opt-Parallelization.pdf)</sup><sup> • </sup><sup>[12](https://heco.estue.nl/courses/ASCI-schools/ASCI_springschool_2017/asci-polyhedral-slides.pdf)</sup><sup> • </sup><sup>[15](https://drops.dagstuhl.de/storage/04dagstuhl-reports/volume08/issue03/18111/DagRep.8.3.39/DagRep.8.3.39.pdf)</sup> 分块沿一组维度合法，仅当依赖沿这些维度不是反向的；伊里戈因（Irigoin）与特里奥莱（Triolet）给出的调度 \( \Theta \) 和依赖锥 \( R \) 的可分块充分条件是 \( \Theta \cdot R \ge 0 \)。<sup>[13](https://dl.acm.org/doi/10.1145/1926385.1926449)</sup>

实践中，工程师用 pragma 引导这些变换：[Clang](https://www.edgepedia.org/zh/clang) 提供 `#pragma clang loop unroll/vectorize/interleave/distribute` 和 `#pragma unroll_and_jam`，GCC 提供 `#pragma GCC unroll` 和 `ivdep`，OpenMP 和 OpenACC 各有自己的指令集。<sup>[3](https://llvm.org/devmtg/2018-10/slides/Kruse-LoopTransforms.pdf)</sup> 在 MLIR 中，Transform 方言让工程师直接编写变换脚本，例如找出超过大小阈值的循环、只对这些循环分块，然后展开产生的内层循环。<sup>[16](https://mlir.llvm.org/docs/Dialects/Transform/)</sup>

## 起源

分析基础由基于区间的数据流分析过程奠定，它计算定义-使用和活跃信息，并在 PL/I 实验编译系统中实现。<sup>[17](https://amturing.acm.org/p137-allen.pdf)</sup> 莱斯利·兰波特（Leslie Lamport）1974 年发表于《Communications of the ACM》的论文《DO 循环的并行执行》是并行执行循环的早期相关工作。<sup>[18](https://doi.org/10.1145/360827.360844)</sup> 班纳吉（Banerjee）及其同事于 1979 年在《IEEE Transactions on Computers》上发表了类 Fortran 循环的边界。<sup>[19](https://doi.org/10.1109/tc.1979.1675434)</sup> J. J. 唐加拉（J. J. Dongarra）和 A. R. 海因兹（A. R. Hinds）同样于 1979 年在《Software Practice and Experience》上描述了 Fortran 中的循环展开。<sup>[20](https://doi.org/10.1002/spe.4380090307)</sup> 约翰·R. 艾伦（John R. Allen）和肯·肯尼迪（Ken Kennedy）于 1984 年在《ACM SIGPLAN Notices》上报告了自动循环交换。<sup>[21](https://doi.org/10.1145/502949.502897)</sup> 1991 年，迈克尔·E. 沃尔夫（Michael E. Wolf）和莫妮卡·S. 拉姆（Monica S. Lam）发表了数据局部性优化算法<sup>[22](https://doi.org/10.1145/113446.113449)</sup> 和最大化并行性的循环变换理论<sup>[23](https://doi.org/10.1109/71.97902)</sup>，而 德罗尔·E. 梅丹（Dror E. Maydan）、约翰·L. 亨尼西（John L. Hennessy）和莫妮卡·S. 拉姆（Monica S. Lam）给出了一种高效精确的依赖测试。<sup>[24](https://doi.org/10.1145/113446.113447)</sup> 凯瑟琳·S. 麦金利（Kathryn S. McKinley）、史蒂夫·卡尔（Steve Carr）和曾昭文（Chau-Wen Tseng）于 1996 年在《TOPLAS》上补充了代价模型驱动的局部性变换处理。<sup>[25](https://doi.org/10.1145/233561.233564)</sup>

## 变体

多面体方法有多个生产实现，包括 Graphite（GCC）、Polly（LLVM）、R-Stream、Omega、CLooG、PLUTO、ISL、piplib、PPL 和 LooPo。<sup>[10](https://ctop.cs.utah.edu/papers/ACACES/acaces-hall-L3.pdf)</sup> Polly 使用 isl 整数集直接在 LLVM-IR 上执行多面体优化，调度涵盖交换、分块、融合和分解。<sup>[6](https://www.infosun.fim.uni-passau.de/publications/docs/GGL2012ppl.pdf)</sup> 乌代·邦杜古拉（Uday Bondhugula）及其同事于 2008 年提出了 Pluto，一个实用的自动多面体并行器和局部性优化器。<sup>[26](https://doi.org/10.1145/1379022.1375595)</sup> 斯文·费尔多拉赫（Sven Verdoolaege）及其同事于 2013 年用 PPCG 将多面体代码生成扩展到 CUDA。<sup>[27](https://doi.org/10.1145/2400682.2400713)</sup> 托比亚斯·格罗瑟（Tobias Grosser）、斯文·费尔多拉赫（Sven Verdoolaege）和阿尔伯特·科恩（Albert Cohen）于 2015 年在《TOPLAS》上发表了 Polly 的调度树 AST 生成。<sup>[28](https://doi.org/10.1145/2743016)</sup> 陈天奇（Tianqi Chen）及其同事于 2018 年报告了 TVM，将自动化端到端优化引入深度学习。<sup>[29](https://doi.org/10.48550/arxiv.1802.04799)</sup> Halide 开创了将调度与程序分离的做法，这一思想后来由 TVM 和 TACO 推广，MLIR 的仿射机制将分块、交换、倾斜、缩放、平移、反转、融合和分解作为一等操作纳入。<sup>[30](https://steuwer.info/files/publications/2025/CGO-2025-2.pdf)</sup><sup> • </sup><sup>[31](https://mlir.llvm.org/docs/Rationale/Rationale/)</sup> PolyTOPS 是一个可配置调度器，其策略以 JSON 或 C++ 配置给出，Feautrier、Pluto、isl、Tensor 和 One-shot 调度器构成其周边格局。<sup>[32](http://icps.u-strasbg.fr/~bastoul/research/papers/CZRLTSAZBAB24.pdf)</sup>

## 应用

Polly 自动检测广义矩阵乘法 \( C \leftarrow \alpha \otimes C \oplus \beta \otimes A \otimes B \) 并生成 GotoBLAS 风格的专家级 GEMM 代码。<sup>[33](https://polly.llvm.org/)</sup> 在 PolyBench 2.0 上，Polly 配合 PLuTo 在无线程级并行时达到 14 倍加速，在线程级并行下超过 100 倍，gemm 内核配合 OpenMP 加 SIMD 超过 100 倍。<sup>[6](https://www.infosun.fim.uni-passau.de/publications/docs/GGL2012ppl.pdf)</sup> 仅 Polly 的循环分布就通过暴露向量化机会，将 SPEC 456.hmmer 的总执行时间相对 clang-3.8 -O3 削减了 28%。<sup>[34](https://pollylabs.org/publications/grosser-2017-Optimistic-Loop-Optimization.pdf)</sup>

## 局限与替代方案

展开过多会导致指令缓存溢出或寄存器溢出，展开过少则浪费处理器资源。<sup>[7](https://www.eecis.udel.edu/~xli/publications/PLDI2003.pdf)</sup> 过度融合对寄存器和缓存造成过大压力。<sup>[8](https://ar5iv.labs.arxiv.org/html/1205.1098)</sup> C 和 C++ 中可能的参数别名会抑制向量化，但静态别名分析或运行时不相交检查可确立安全性；运行时检查引入的开销未必高。Fortran 通常允许更强的非别名假设；许多 LLVM 变换如 LoopInterchange 和 LoopUnrollAndJam 仍作为实验性功能默认禁用，逐编译遍的代码版本化可产生多达 \( 2^{4} = 16 \) 份相同最内层循环的副本。<sup>[35](https://real.mtak.hu/111849/1/113_121_Kov%C3%A1cs.pdf)</sup><sup> • </sup><sup>[3](https://llvm.org/devmtg/2018-10/slides/Kruse-LoopTransforms.pdf)</sup><sup> • </sup><sup>[37](https://llvm.org/docs/Vectorizers.html)</sup> 多面体模型要求无别名、仿射下标和循环不变边界，<sup>[34](https://pollylabs.org/publications/grosser-2017-Optimistic-Loop-Optimization.pdf)</sup> 其优化器使用的简化性能模型与实际性能相关性差。<sup>[15](https://drops.dagstuhl.de/storage/04dagstuhl-reports/volume08/issue03/18111/DagRep.8.3.39/DagRep.8.3.39.pdf)</sup> 编译器缓存模型通常假定全相联缓存，而硬件使用有限组相联和伪 LRU；经验性库生成器 ATLAS、FFTW 和 SPIRAL 产生的代码优于模型驱动的编译器。<sup>[7](https://www.eecis.udel.edu/~xli/publications/PLDI2003.pdf)</sup><sup> • </sup><sup>[36](https://www.netlib.org/utk/people/JackDongarra/PAPERS/autotuning-ieeeproc-2018.pdf)</sup> 手工调优的代码仍然领先：Intel Itanium 2 编译器对三嵌套循环矩阵乘法达到峰值的约 92%，而手写 Goto BLAS 接近 99%，<sup>[5](https://engineering.purdue.edu/~milind/docs/ieee08.pdf)</sup> 在 BLAS 风格循环嵌套序列上编译器往往只能达到手工优化性能的四分之一，不过 BTO 领域专用编译器介于比手工优化代码慢 16% 到快 39% 之间。<sup>[8](https://ar5iv.labs.arxiv.org/html/1205.1098)</sup>

## References

1. [Compiler transformations for high-performance computing (Bacon, Graham, Sharp), ACM Computing Surveys](https://psycnet.apa.org/doi/10.1145/197405.197406)
2. [Lecture Notes on Loop Optimizations (CMU 15-411, Lecture 19)](https://www.cs.cmu.edu/~janh/courses/411/24/lectures/19-loopopt.pdf)
3. [Loop Optimizations in LLVM: The Good, The Bad, and The Ugly (Michael Kruse, LLVM Developers' Meeting 2018)](https://llvm.org/devmtg/2018-10/slides/Kruse-LoopTransforms.pdf)
4. [Loop Optimization slides (CMU 15-411/611)](https://www.cs.cmu.edu/~411/slides/s25-19-loop-trans.pdf)
5. [Self-Optimizing Dense Linear Algebra (Proceedings of the IEEE, 2008)](https://engineering.purdue.edu/~milind/docs/ieee08.pdf)
6. [Polly, Performing Polyhedral Optimizations on a Low-Level Intermediate Representation (Parallel Processing Letters 2012)](https://www.infosun.fim.uni-passau.de/publications/docs/GGL2012ppl.pdf)
7. [A Comparison of Empirical and Model-driven Optimization (PLDI 2003)](https://www.eecis.udel.edu/~xli/publications/PLDI2003.pdf)
8. [Reliable Generation of High-Performance Matrix Algebra (BTO)](https://ar5iv.labs.arxiv.org/html/1205.1098)
9. [Optimization and Parallelization of Sequential Programs (C. Kessler, Linköping University lecture notes)](https://www.ida.liu.se/~chrke55/courses/ACC/PDF-2023/Depend-Opt-Parallelization.pdf)
10. [Compiler-Based Autotuning Technology Lecture 3: A Closer Look at Polyhedral Compiler Technology (Mary Hall, University of Utah)](https://ctop.cs.utah.edu/papers/ACACES/acaces-hall-L3.pdf)
11. [Chapter 5. Loop Parallelization Algorithms (Darte, Robert, Vivien)](https://perso.ens-lyon.fr/frederic.vivien/Publications/Chapter-LNCS.pdf)
12. [High-Level Loop Transformations and Polyhedral Compilation (ASCI spring school slides, incl. PPCG)](https://heco.estue.nl/courses/ASCI-schools/ASCI_springschool_2017/asci-polyhedral-slides.pdf)
13. [Loop Transformations: Convexity, Pruning and Optimization (Pouchet et al., POPL 2011)](https://dl.acm.org/doi/10.1145/1926385.1926449)
14. [Lecture Notes on Loop Transformations for Cache Optimization (Platzer, CMU 15-411 Lecture 24)](https://symbolaris.com/course/Compilers11/24-cacheloop.pdf)
15. [Loop Optimization (Dagstuhl Seminar Report)](https://drops.dagstuhl.de/storage/04dagstuhl-reports/volume08/issue03/18111/DagRep.8.3.39/DagRep.8.3.39.pdf)
16. [Transform Dialect - MLIR (official documentation)](https://mlir.llvm.org/docs/Dialects/Transform/)
17. [A program data flow analysis procedure (Allen, Communications of the ACM, March 1976)](https://amturing.acm.org/p137-allen.pdf)
18. [Leslie Lamport (1974). The parallel execution of DO loops. Communications of the ACM.](https://doi.org/10.1145/360827.360844)
19. [Banerjee and colleagues (1979). Time and Parallel Processor Bounds for Fortran-Like Loops. IEEE Transactions on Computers.](https://doi.org/10.1109/tc.1979.1675434)
20. [J. J. Dongarra, A. R. Hinds (1979). Unrolling loops in fortran. Software Practice and Experience.](https://doi.org/10.1002/spe.4380090307)
21. [John R. Allen, Ken Kennedy (1984). Automatic loop interchange. ACM SIGPLAN Notices.](https://doi.org/10.1145/502949.502897)
22. [Michael E. Wolf, Monica S. Lam (1991). A data locality optimizing algorithm. ACM SIGPLAN Notices.](https://doi.org/10.1145/113446.113449)
23. [M.E. Wolf, M.S. Lam (1991). A loop transformation theory and an algorithm to maximize parallelism. IEEE Transactions on Parallel and Distributed Systems.](https://doi.org/10.1109/71.97902)
24. [Dror E. Maydan, John L. Hennessy, Monica S. Lam (1991). Efficient and exact data dependence analysis. ACM SIGPLAN Notices.](https://doi.org/10.1145/113446.113447)
25. [Kathryn S. McKinley, Steve Carr, Chau-Wen Tseng (1996). Improving data locality with loop transformations. ACM Transactions on Programming Languages and Systems.](https://doi.org/10.1145/233561.233564)
26. [Uday Bondhugula and colleagues (2008). A practical automatic polyhedral parallelizer and locality optimizer. ACM SIGPLAN Notices.](https://doi.org/10.1145/1379022.1375595)
27. [Sven Verdoolaege and colleagues (2013). Polyhedral parallel code generation for CUDA. ACM Transactions on Architecture and Code Optimization.](https://doi.org/10.1145/2400682.2400713)
28. [Tobias Grosser, Sven Verdoolaege, Albert Cohen (2015). Polyhedral AST Generation Is More Than Scanning Polyhedra. ACM Transactions on Programming Languages and Systems.](https://doi.org/10.1145/2743016)
29. [Chen, Tianqi and colleagues (2018). TVM: An Automated End-to-End Optimizing Compiler for Deep Learning. arXiv (Cornell University).](https://doi.org/10.48550/arxiv.1802.04799)
30. [The MLIR Transform Dialect: Your Compiler Is More Powerful Than You Think (CGO 2025)](https://steuwer.info/files/publications/2025/CGO-2025-2.pdf)
31. [MLIR Rationale (official documentation)](https://mlir.llvm.org/docs/Rationale/Rationale/)
32. [PolyTOPS: Reconfigurable and Flexible Polyhedral Scheduler](http://icps.u-strasbg.fr/~bastoul/research/papers/CZRLTSAZBAB24.pdf)
33. [Polly, Polyhedral optimizations for LLVM (official documentation)](https://polly.llvm.org/)
34. [Optimistic Loop Optimization (Grosser et al., CGO 2017)](https://pollylabs.org/publications/grosser-2017-Optimistic-Loop-Optimization.pdf)
35. [Loop optimizations in C and C++ compilers: an overview](https://real.mtak.hu/111849/1/113_121_Kov%C3%A1cs.pdf)
36. [Autotuning in High-Performance Computing Applications (IEEE Proceedings, 2018)](https://www.netlib.org/utk/people/JackDongarra/PAPERS/autotuning-ieeeproc-2018.pdf)
37. [Auto-Vectorization in LLVM - LLVM](https://llvm.org/docs/Vectorizers.html)

---
*Initially written Sep 29, 2026 · Edited: Oct 15, 2026*

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

Copyright 2026 Edgepedia

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

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

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