0. 前言

联系一下南大程序分析课程(基于Java)的笔记。

LLVM

课程视频:https://www.youtube.com/playlist?list=PLDSTpI7ZVmVnvqtebWnnI8YeB8bJoGOyv

课程的GitHub仓库:https://github.com/lac-dcc/llvm-course/

1. 基础知识

clang-18 -S hello-world.c -emit-llvm -o hello-world.ll
opt-18 -passes=dot-cfg -disable-output ./hello-world.ll
dot -Tsvg .prefix_sum.dot > cfg.svg
dot -Tpdf .prefix_sum.dot -o prefix_sum.pdf

opt-18 --print-passes

# generate x86 assembly code
llc hello-world.ll -march=x86 -o file.x86

# Rust
rustc --emit llvm-ir hello-world.rs
rustc --emit asm hello-world.rs

2.

3. Pass编写实践:常量加法分析

include/AddConst.h:

#ifndef ADD_CONST_H
#define ADD_CONST_H
#include "llvm/IR/InstrTypes.h"
#include "llvm/IR/PassManager.h"

namespace addconst {
struct AddConstAnalysis : public llvm::AnalysisInfoMixin<AddConstAnalysis> {
    using Result = llvm::SmallVector<llvm::BinaryOperator *, 0>;
    Result run(llvm::Function &F, llvm::FunctionAnalysisManager &FAM);
    static llvm::AnalysisKey Key;
};

struct AddConstPrinterPass : public llvm::PassInfoMixin<AddConstPrinterPass> {
    explicit AddConstPrinterPass(llvm::raw_ostream &OS) : OS(OS) {}
    llvm::PreservedAnalyses run(llvm::Function &F,
                                llvm::FunctionAnalysisManager &FAM);
  private:
    llvm::raw_ostream &OS;
};

struct AddConstPass : public llvm::PassInfoMixin<AddConstPass> {
    llvm::PreservedAnalyses run(llvm::Function &F,
                                llvm::FunctionAnalysisManager &FAM);
};
}

#endif
; ModuleID = 'llvm-ir/foo.ll'
source_filename = "llvm-ir/foo.ll"

define i32 @foo(i32 %a, i32 %b) {
  %c = add i32 1, 2
  %d = add i32 3, 4
  %e = add i32 %a, %b
  %f = add i32 %c, %d
  %g = add i32 %e, %f
  ret i32 %g
}
export LLVM_INSTALL_DIR=/lib/llvm-18
cmake -G "Unix Makefiles" -B build/ .
cd build; make; cd ..
LLVM_OPT=$LLVM_INSTALL_DIR/bin/opt
$LLVM_OPT -load-pass-plugin build/lib/libAddConst.so -passes="print<add-const>" -disable-output examples/foo.ll
# Output:
# =============================================
# || foo ||
# =============================================
#   %c = add i32 1, 2
#   %d = add i32 3, 4
# =============================================

LLVM原初论文笔记

LLVM在安全研究中的应用

https://elmanto.github.io/posts/llvm_for_security_1_4

https://www.youtube.com/watch?v=JMXhmMQ0bNw

https://github.com/gmh5225/awesome-llvm-security

其他资料

  1. LLVM: A Compilation Framework for Lifelong Program Analysis & Transformation
  2. LLVM学习之基础编程+过程间分析
  3. LLVM in 100 Seconds
  4. 知乎专栏:LLVM每日谈
  5. GitHub: llvm-tutor
  6. Writing an LLVM Pass: 101
  7. 官方文档:Getting Started with the LLVM System
  8. 官方文档:Writing an LLVM Pass
  9. 官方文档:LLVM Programmer’s Manual
  10. 官方文档:LLVM Tutorial
  11. 一本较新的相关书籍:Learn LLVM 17, 2nd Edition
  12. 一本较新的相关书籍:LLVM Techniques, Tips, and Best Practices Clang and Middle-End Libraries
  13. 一篇讲解CMake、Ninja等构建工具的知乎文章