DEV Community

Lahari Tenneti
Lahari Tenneti

Posted on • Edited on

LLVM #9 — Finding Loops

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 the FAM, but haven't really used it. We merely printed the function name that we detected.
  • The FAM either 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);
Enter fullscreen mode Exit fullscreen mode
  • LI now 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";
}
Enter fullscreen mode Exit fullscreen mode
  • 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
Enter fullscreen mode Exit fullscreen mode
  • 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: Converts for.cond into for.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
Enter fullscreen mode Exit fullscreen mode

test_loop_canonical.ll

  • We then link this .ll file to our pass with opt to check if the loops have been detected or not.
opt -load-pass-plugin=./libMyPass.so -passes=my-pass -disable-output test_loop_canonical.ll
Enter fullscreen mode Exit fullscreen mode


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)