LLVM

To quickly explore LLVM output, select any clang compiler on Compiler Explorer and add -emit-llvm option.

To see all optimization passes in Clang:

llvm-as < /dev/null | opt -disable-output -passes='default<O3>' -print-pipeline-passes

Result of each pass can be examined on Compiler Explorer through Add New > Opt Pipeline.

Some important passes:

  1. sroa - Scalar Replacement Of Aggregates, breaks up alloca instructions into smaller allocas
  2. mem2reg – optimizes loads and stores into SSA values
  3. simplifycfg – hoists common code from if/else, turn switch statement into a lookup table
  4. instcombine and instsimplify – peephole optimizations, constant folding, from x * 4 to x << 2

Useful articles

MLIR

YouTube

Books

Installing on macOS 13+

brew install llvm

Add to .zshrc:

export PATH="/opt/homebrew/opt/llvm/bin:$PATH"
export SDKROOT="$(xcrun --show-sdk-path)"
export LIBRARY_PATH="$LIBRARY_PATH:$SDKROOT/usr/lib"
export LDFLAGS="-L/opt/homebrew/opt/llvm/lib"
export CPPFLAGS="-I/opt/homebrew/opt/llvm/include"