RFC: llvm::Module::getFunctionDefs to iterate over function definitions

Motivation
We often wish to iterate over all function definitions in a module to perform certain transformations. Such API doesn’t exists yet, so what people normally used is to iterate over all functions and skip the declarations:

for (auto& F: M) {
    if (F.isDeclaration()) {
        continue;
    }
}

A regex search of the following pattern shows 100+ hits inside llvm, let along other patterns (e.g. collect all definitions in a module into a work list):

for \(.*F.*\).*\n.*if \(F.isDeclaration\(\)\).*\n.*continue;

However, this pattern exhibits a few ergonomic issues. It is verbose and hard to review in a long loop. The intention is not very clear at a glance. What’s more, when function attribute / metadata are involved, this could be error prone: the developer could accidentally change the declarations’ attributes.

Solution

I am proposing a new API that iterate over functions definitions only. With this patch, you can do something like:

for (Function& F: M.getFunctionDefs()) {
    // Logic for definitions
}

When the PR lands, we can start simplify the codebase and erase those F.isDeclaration() checks

2 Likes