Fee
Fee

Reputation: 851

LLVM Find every instruction that allocates memory

I want to find every instruction that allocates memory in LLVM IR. For stack allocations I simply do:

Instruction* I;      

if (AllocaInst* AI = dyn_cast<AllocaInst>(I)) {
    //stack allocation
}

But what about heap and static (global) allocations? What else can allocate memory in LLVM IR?

If the LLVM version makes a difference please provide the version you are referring to.

Upvotes: 2

Views: 985

Answers (2)

DTharun
DTharun

Reputation: 796

Memory allocation can be either in stack and heap. For stack allocation what you are doing is right you need to check for alloca instruction. Heap allocation is done by malloc function calls there are no explicit IR instruction.

I din't do any experimentation with this but may be this is the way you can try.

    if(MemSetIntrinsic *MSI = dyn_cast<MemSetIntrinsic>(I))
           // This call instruction is a memory allocating instruciton  

Upvotes: 0

Colin LeMahieu
Colin LeMahieu

Reputation: 618

Ultimately you won't be able to perfectly detect this. Heap allocations boil down to operating system calls and someone could directly make these calls with inline assembly. There are also library calls you won't have visibility to that are linked in.

Keep this in mind with whatever you're working on.

Upvotes: 2

Related Questions