The title describes it all. I'm writing an LLVM IR module pass and need to know the absolute path to the source code corresponding to the current Module. I know how to extract the name of the source code (through getSourceFileName() in Module), but what I need is the full path to the source code including an absolute directory path. How can I find this one? If there's a workaround, that will work too.
Okay, I'm gonna answer my own question here. You can find how LLVM internally restores the absolute paths in IR/CodeGen/AsmWriter/AsmWriter.cpp:emitRemarksSection()
. It basically restores the path of the source code with the current path that clang is running on now. The API function that does this is provided by LLVM already.
Referring to this, let's convert a Module's file name to its full path.
std::string Filename = M.getSourceFileName();
char
vector.llvm::SmallString<128> FilenameVec = StringRef(Filename);
llvm::sys::fs::make_absolute(FilenameVec);
The file full path is stored right back to FilenameVec
. You'll need to include llvm/Support/FileSystem.h
to use make_absolute()
.
You can try it by sticking the following code (properly) to any working IR pass.
#include <string>
#include "llvm/Support/FileSystem.h"
...
std::string Filename = M.getSourceFileName(); // e.g., Filename = aaa.c
llvm::SmallString<128> FilenameVec = StringRef(Filename);
llvm::sys::fs::make_absolute(FilenameVec); // e.g., FilenameVec = /path/to/aaa.c