[LLVMdev] Questions on writing a pass that adds instrumentation code

Evan Driscoll driscoll at cs.wisc.edu
Mon Jun 24 16:45:22 PDT 2013


I'm an LLVM newbie, trying to write a pass that adds instrumentation to
a program, and have a couple of questions.

For purposes of this discussion, suppose I'm trying to add a
per-function counter that is incremented each time a function is called.
At the end of the target program's execution, I would like to output the
value of each counter.

My questions are as follows:


1. What's the best way to insert instrumentation code at the "beginning"
of a function? I can add code before the function prologue easily enough
(i.e. insert before func.getEntryBlock().begin()), but is this always
correct, or could this overwrite stuff? (I never need to access local
variables, of course.) If not, how can I detect the end of the prologue
and put things at the "actual" start of the function?

(Even though my goal, as phrased above, would work if I put the
load/add/store instrumentation just before the terminator of the first
basic block, that doesn't serve my broader goal.)


2. I currently create the global variables holding the counter by
calling "module.getOrInsertGlobal(...)". Will this ensure that the
global starts with the value 0, or do I have to do this via other means?
(E.g. make an explicit GlobalVariable object instead of using that
convenience function)


3. How can I add code that is called when the program exits?


4. Suppose I want to call a function 'foo()' instead of incrementing a
counter, where 'foo()' is some instrumentation code that I would like to
insert rather than something in the target program. *Ideally*, what I'd
like to be able to do is write foo() in C or C++, compile it to LLVM
bytecode, and then somehow pull that into programs that run my pass. Is
there an easy way to do this (i.e. not using an IRBuilder to recreate
the bytecode or something silly like that), or should I just say "if you
want to use my thing, then compile foo.c into your program so the
definition of foo() is available".

Evan




More information about the llvm-dev mailing list