How to count instructions in a function?

Hello,

I am trying to count IR instructions in a function for static analysis using llvm pass. In contrast with existing examples, I am trying to include instruction counts of all the callees of the function.

Counting the instructions of a function is easy using passes, but iterating through the module’s CallGraph is proving to be confusing. I believe I have to use CallGraphWrapperPass to get both module pass and its CallGraph. How do I iterate through the CallGraph in runOnModule()? A simple print callee names example would be highly appreciated.

Thanks,
Zubin

Dear Zubin,

If I were you, I would write a ModulePass that uses the CallGraph analysis to get a call graph. I would then iterate over the nodes in the call graph and propagate information from callees to callers.

Regards,

John Criswell

Thanks so much John! That works :slight_smile:

Previously I wrote a pass that inherited from CallGraphWrapperPass and used its getCallGraph() function within runOnModule() which resulted in segmentation faults for me. Not sure why that happened, perhaps callgraph wasn’t setup by the time runOnModule() was called internally. If you know why, kindly enlighten me and perhaps document the behavior for the benefit of others.

Your email was the best thing to happen to me all day. I really appreciate you taking out the time to help.

Sincerely,
Zubin

Dear Professor Criswell,

I was trying to do the same for higher levels of clang++ optimizations -O2 and above. I need the IR instruction counts of a specific function name but it seems the optimizations are in-lining the function code (or something else). Is there anyway to map optimized IR with un-optimized IR through some metadata class? All I really need is the original function name in a pass over optimized IR.

In addition, is there any existing way to detect cycles and infinite recursion in CallGraph? How I can fairly account instruction counts of a function and its callees in event of cycles/ infinite recursion (when the branch prediction can be done in static analysis).

Many Thanks,
Zubin