edgepedia

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

综合 · Edgepedia阅读需 9 分钟

循环优化

阅读英文原文

循环优化是一组编译器变换,通过重构程序中的循环来提高执行速度或资源利用率,主要手段是增加并行性、改善内存局部性和启用向量化。与标量优化不同——后者利用数据流分析减少执行的指令数量——循环优化通过循环依赖分析追踪数组的性质,面向超标量、向量和并行处理器。1 编译器在结构上将循环识别为控制流图中从某节点指向支配该节点的头节点的回边,并优先优化内层循环,因为它们执行得最频繁。2 生产级编译器提供专用编译遍,如循环展开、循环交换、循环分布和循环向量化。3

关键事实详情
变换对象携带数组访问的循环嵌套,使用依赖分析而非标量数据流1
核心变换展开、分块、融合、分解(分布)、交换、倾斜、反转、向量化3
合法性检验每个变换后的依赖向量必须保持字典序为正4
分块经验法则对矩阵乘法,缓存容量为 C C 时取块大小 B=C B = \sqrt{C} 可使缺失率最小5
实测收益在 PolyBench 上,多面体优化在无线程级并行时达到 14 倍加速,启用线程级并行时超过 100 倍6
主要失效模式过度展开导致寄存器压力和指令缓存溢出7;过度融合对寄存器和缓存造成压力8
实际上限对 BLAS 风格的循环嵌套,编译器可能只能达到手工优化性能的约四分之一8

工作原理

若 S 可能在 T 之前执行、两者访问同一内存位置、且至少有一次访问是写操作,则存在数据依赖 S → T。两个数组引用是否可能别名到同一元素,一般无法在编译期精确判定;找出真实依赖在静态意义上是不可判定的,因此编译器计算保守的过近似,存疑时即假定存在依赖。9

重排序变换的合法性源自 约翰·R. 艾伦(John R. Allen)与肯·肯尼迪(Ken Kennedy)教科书中的经典结论:任何保持所有依赖的重排序变换都保持程序语义。10 在操作层面,依赖的距离向量 d=It−Is d = I_{t} - I_{s} 乘以变换矩阵,变换合法当且仅当对每个非零距离向量 d d ,T⋅d T \cdot d 的字典序为正。4 • 11 多面体模型对此做了扩展:具有仿射边界的完美嵌套循环的迭代空间是 Zd \mathbb{Z}^{d} 中多面体的整数点集,表示为 Ax≤b Ax \le b ,调度是仿射的时空映射;当对每个依赖 i→j i \to j 都有 i≺Sj i \prec_{S} j 时,调度合法。9 • 10 • 12 判定两个引用是否可能触及同一元素可归约为整数规划,其复杂度在系数规模上是 NP 完全的,而为融合选择最优的语句交错同样是 NP 完全的,因此实用系统采用剪枝和近似。10 • 13

实现方式

主要变换的工作方式如下。交换(置换)调换循环顺序,将携带依赖的循环推向外层,留下可并行化的内层循环,并使内层循环按布局顺序遍历内存。14 以因子 f f 倾斜,即在内层循环边界上加上 f⋅i1 f \cdot i_{1} 、从数组访问中减去 f⋅i1 f \cdot i_{1} ,将依赖方向 d d 变为 (d1,f⋅(d1+d2)) (d_{1}, f \cdot (d_{1} + d_{2})) ;先倾斜再交换可使模板计算的内层循环并行。14 融合合并具有相同头节点的相邻循环,当两者都不携带反向依赖时是安全的;它让中间值立即复用,而不必写入并重新加载一个放不进缓存的数组。9 • 12 分块是对若干循环头节点做分块再加交换,使扫描一个块的循环成为最内层;当某个操作数否则会在每次外层迭代中被逐出并重新加载时,分块有帮助;对 O(n3) O(n^{3}) 矩阵乘法和大小为 M M 的快速内存,大小为 Θ(M1/2) \Theta(M^{1/2}) 的方形块可达到 Ω(n3/M1/2) \Omega(n^{3}/M^{1/2}) 的通信下界。9 • 12 • 15 分块沿一组维度合法,仅当依赖沿这些维度不是反向的;伊里戈因(Irigoin)与特里奥莱(Triolet)给出的调度 Θ \Theta 和依赖锥 R R 的可分块充分条件是 Θ⋅R≥0 \Theta \cdot R \ge 0 。13

实践中,工程师用 pragma 引导这些变换:Clang 提供 #pragma clang loop unroll/vectorize/interleave/distribute 和 #pragma unroll_and_jam,GCC 提供 #pragma GCC unroll 和 ivdep,OpenMP 和 OpenACC 各有自己的指令集。3 在 MLIR 中,Transform 方言让工程师直接编写变换脚本,例如找出超过大小阈值的循环、只对这些循环分块,然后展开产生的内层循环。16

起源

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

变体

多面体方法有多个生产实现,包括 Graphite(GCC)、Polly(LLVM)、R-Stream、Omega、CLooG、PLUTO、ISL、piplib、PPL 和 LooPo。10 Polly 使用 isl 整数集直接在 LLVM-IR 上执行多面体优化,调度涵盖交换、分块、融合和分解。6 乌代·邦杜古拉(Uday Bondhugula)及其同事于 2008 年提出了 Pluto,一个实用的自动多面体并行器和局部性优化器。26 斯文·费尔多拉赫(Sven Verdoolaege)及其同事于 2013 年用 PPCG 将多面体代码生成扩展到 CUDA。27 托比亚斯·格罗瑟(Tobias Grosser)、斯文·费尔多拉赫(Sven Verdoolaege)和阿尔伯特·科恩(Albert Cohen)于 2015 年在《TOPLAS》上发表了 Polly 的调度树 AST 生成。28 陈天奇(Tianqi Chen)及其同事于 2018 年报告了 TVM,将自动化端到端优化引入深度学习。29 Halide 开创了将调度与程序分离的做法,这一思想后来由 TVM 和 TACO 推广,MLIR 的仿射机制将分块、交换、倾斜、缩放、平移、反转、融合和分解作为一等操作纳入。30 • 31 PolyTOPS 是一个可配置调度器,其策略以 JSON 或 C++ 配置给出,Feautrier、Pluto、isl、Tensor 和 One-shot 调度器构成其周边格局。32

应用

Polly 自动检测广义矩阵乘法 C←α⊗C⊕β⊗A⊗B C \leftarrow \alpha \otimes C \oplus \beta \otimes A \otimes B 并生成 GotoBLAS 风格的专家级 GEMM 代码。33 在 PolyBench 2.0 上,Polly 配合 PLuTo 在无线程级并行时达到 14 倍加速,在线程级并行下超过 100 倍,gemm 内核配合 OpenMP 加 SIMD 超过 100 倍。6 仅 Polly 的循环分布就通过暴露向量化机会,将 SPEC 456.hmmer 的总执行时间相对 clang-3.8 -O3 削减了 28%。34

局限与替代方案

展开过多会导致指令缓存溢出或寄存器溢出,展开过少则浪费处理器资源。7 过度融合对寄存器和缓存造成过大压力。8 C 和 C++ 中可能的参数别名会抑制向量化,但静态别名分析或运行时不相交检查可确立安全性;运行时检查引入的开销未必高。Fortran 通常允许更强的非别名假设;许多 LLVM 变换如 LoopInterchange 和 LoopUnrollAndJam 仍作为实验性功能默认禁用,逐编译遍的代码版本化可产生多达 24=16 2^{4} = 16 份相同最内层循环的副本。35 • 3 • 37 多面体模型要求无别名、仿射下标和循环不变边界,34 其优化器使用的简化性能模型与实际性能相关性差。15 编译器缓存模型通常假定全相联缓存,而硬件使用有限组相联和伪 LRU;经验性库生成器 ATLAS、FFTW 和 SPIRAL 产生的代码优于模型驱动的编译器。7 • 36 手工调优的代码仍然领先:Intel Itanium 2 编译器对三嵌套循环矩阵乘法达到峰值的约 92%,而手写 Goto BLAS 接近 99%,5 在 BLAS 风格循环嵌套序列上编译器往往只能达到手工优化性能的四分之一,不过 BTO 领域专用编译器介于比手工优化代码慢 16% 到快 39% 之间。8

References

  1. Compiler transformations for high-performance computing (Bacon, Graham, Sharp), ACM Computing Surveys
  2. Lecture Notes on Loop Optimizations (CMU 15-411, Lecture 19)
  3. Loop Optimizations in LLVM: The Good, The Bad, and The Ugly (Michael Kruse, LLVM Developers' Meeting 2018)
  4. Loop Optimization slides (CMU 15-411/611)
  5. Self-Optimizing Dense Linear Algebra (Proceedings of the IEEE, 2008)
  6. Polly, Performing Polyhedral Optimizations on a Low-Level Intermediate Representation (Parallel Processing Letters 2012)
  7. A Comparison of Empirical and Model-driven Optimization (PLDI 2003)
  8. Reliable Generation of High-Performance Matrix Algebra (BTO)
  9. Optimization and Parallelization of Sequential Programs (C. Kessler, Linköping University lecture notes)
  10. Compiler-Based Autotuning Technology Lecture 3: A Closer Look at Polyhedral Compiler Technology (Mary Hall, University of Utah)
  11. Chapter 5. Loop Parallelization Algorithms (Darte, Robert, Vivien)
  12. High-Level Loop Transformations and Polyhedral Compilation (ASCI spring school slides, incl. PPCG)
  13. Loop Transformations: Convexity, Pruning and Optimization (Pouchet et al., POPL 2011)
  14. Lecture Notes on Loop Transformations for Cache Optimization (Platzer, CMU 15-411 Lecture 24)
  15. Loop Optimization (Dagstuhl Seminar Report)
  16. Transform Dialect - MLIR (official documentation)
  17. A program data flow analysis procedure (Allen, Communications of the ACM, March 1976)
  18. Leslie Lamport (1974). The parallel execution of DO loops. Communications of the ACM.
  19. Banerjee and colleagues (1979). Time and Parallel Processor Bounds for Fortran-Like Loops. IEEE Transactions on Computers.
  20. J. J. Dongarra, A. R. Hinds (1979). Unrolling loops in fortran. Software Practice and Experience.
  21. John R. Allen, Ken Kennedy (1984). Automatic loop interchange. ACM SIGPLAN Notices.
  22. Michael E. Wolf, Monica S. Lam (1991). A data locality optimizing algorithm. ACM SIGPLAN Notices.
  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.
  24. Dror E. Maydan, John L. Hennessy, Monica S. Lam (1991). Efficient and exact data dependence analysis. ACM SIGPLAN Notices.
  25. Kathryn S. McKinley, Steve Carr, Chau-Wen Tseng (1996). Improving data locality with loop transformations. ACM Transactions on Programming Languages and Systems.
  26. Uday Bondhugula and colleagues (2008). A practical automatic polyhedral parallelizer and locality optimizer. ACM SIGPLAN Notices.
  27. Sven Verdoolaege and colleagues (2013). Polyhedral parallel code generation for CUDA. ACM Transactions on Architecture and Code Optimization.
  28. Tobias Grosser, Sven Verdoolaege, Albert Cohen (2015). Polyhedral AST Generation Is More Than Scanning Polyhedra. ACM Transactions on Programming Languages and Systems.
  29. Chen, Tianqi and colleagues (2018). TVM: An Automated End-to-End Optimizing Compiler for Deep Learning. arXiv (Cornell University).
  30. The MLIR Transform Dialect: Your Compiler Is More Powerful Than You Think (CGO 2025)
  31. MLIR Rationale (official documentation)
  32. PolyTOPS: Reconfigurable and Flexible Polyhedral Scheduler
  33. Polly, Polyhedral optimizations for LLVM (official documentation)
  34. Optimistic Loop Optimization (Grosser et al., CGO 2017)
  35. Loop optimizations in C and C++ compilers: an overview
  36. Autotuning in High-Performance Computing Applications (IEEE Proceedings, 2018)
  37. Auto-Vectorization in LLVM - LLVM

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

© 2026 Biostate AI。依据 Edgepedia Community License,注明出处即可免费使用。 嵌入参考卡片。

报告错误

循环优化

请至少选择一个原因。