Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Extract functions related to MPI from mpi.h
#include <llvm/Support/Host.h>
#include <clang/AST/ASTConsumer.h>
#include <clang/AST/Decl.h>
#include <clang/AST/DeclGroup.h>
#include <clang/Basic/TargetInfo.h>
#include <clang/Frontend/CompilerInstance.h>
#include <clang/Frontend/CompilerInvocation.h>
#include <clang/Parse/ParseAST.h>
#include <boost/algorithm/string.hpp>
#include <boost/range/iterator_range.hpp>
struct extractor : clang::ASTConsumer {
void HandleTopLevelDecl(clang::DeclGroupRef decls) {
for (auto& decl : decls) {
if (auto const* fd = llvm::dyn_cast<clang::FunctionDecl>(decl)) {
handle_functiondecl(fd);
}
}
}
private:
void handle_functiondecl(clang::FunctionDecl const* fd) const {
if (boost::starts_with(fd->getName(), "MPI_")) {
handle_mpi_functiondecl(fd);
}
}
void handle_mpi_functiondecl(clang::FunctionDecl const* fd) const {
std::vector<std::string> data;
data.push_back(fd->getName());
data.push_back(fd->getResultType().getAsString());
for (auto const& param : range(fd->param_begin(), fd->param_end())) {
data.push_back(param->getType().getAsString());
}
llvm::outs() << boost::join(data, ",") << '\n';
}
template <class Iterator>
static
boost::iterator_range<Iterator> range(Iterator b, Iterator e) {
return boost::make_iterator_range(b, e);
}
};
int main(int argc, char** argv) {
clang::CompilerInstance compiler;
compiler.createDiagnostics(argc, argv);
auto& diag = compiler.getDiagnostics();
auto& invocation = compiler.getInvocation();
invocation.setLangDefaults(clang::IK_C);
clang::CompilerInvocation::CreateFromArgs(invocation, argv + 1, argv + argc, diag);
compiler.setTarget(clang::TargetInfo::CreateTargetInfo(diag, compiler.getTargetOpts()));
compiler.createFileManager();
compiler.createSourceManager(compiler.getFileManager());
compiler.createPreprocessor();
compiler.createASTContext();
compiler.setASTConsumer(new extractor);
compiler.createSema(false, nullptr);
auto& inputs = compiler.getFrontendOpts().Inputs;
if (inputs.size() > 0) {
compiler.InitializeSourceManager(inputs[0].second);
clang::ParseAST(
compiler.getPreprocessor(),
&compiler.getASTConsumer(),
compiler.getASTContext()
);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment