Now that we have the basic skeleton for the pass ready, we need to add loop-detecting logic to it.
What I built: Commits 432455d and ddc46b3
What I understood:
1) Using the FunctionAnalysisManager for detecting loops:
- In our
run()function, we've declared theFAM, but haven't really used it. We merely printed the function name that we detected. - The
FAMeither performs analyses fresh or fetches a cached result. - LLVM already knows about every loop (where a loop is, nested loops, loop headers, latches, etc.) in a function through
LoopInfo.
LoopInfo &LI = FAM.getResult<LoopAnalysis>(F);
-
LInow hols every loop in this function.
2) Fetching top-level loops:
- We iterate over the function to fetch top-level loops.
for ("Loop *L : LI) {
outs() << "Found a loop with header: " << L->getHeader()->getName() << "\n";
}
- Each
Loop*represents every top-level loop in the function. - We can later even fetch nested loops through
getSubloops()
3) Testing it:
- We can write a loop in C++.
test_loop.cpp
- Then, we convert it to LLVM IR (raw, unmodified).
clang -S -emit-llvm -O0 -Xclang -disable-O0-optnone -fno-discard-value-names test_loop.cpp -o test_loop_raw.ll
- We then run three canonicalisation passes:
-
mem2reg: To promote stack variables into SSA registers with phi nodes. -
loop-simplify: Guarantees that every loop has one preheader, one latch, and dedicated exit blocks. -
loop-rotate: Convertsfor.condintofor.body, which is the form the vectoriser needs.
-
opt -passes='mem2reg,loop-simplify,loop-rotate' test_loop_raw.ll -S -o test_loop_canonical.ll
test_loop_canonical.ll
- We then link this
.llfile to our pass withoptto check if the loops have been detected or not.
opt -load-pass-plugin=./libMyPass.so -passes=my-pass -disable-output test_loop_canonical.ll
What's next: Figuring out LLVM's metadata API.
Musings:
The weather is beauuuuutiful today. I absolutely love the monsoon. It's 700% worth waiting for after a long and testing summer. And nothing beats having some piping hot chai while enjoying the breeze. I'm in the company of two of favourite gals as I finish today's work and life couldn't get any better!




Top comments (0)