How to maintain the atomicity of the instrumentation code in LLVM

I used my own pass to insert some instructions into the basic block of the program. After the executable file was generated, disassembly could find that the order of some insert instructions was optimized, especially some inserting instructions were mixed with non-inserting instructions (the original instructions of the program). I would like to ask how can I disable the reordering of instructions and preserve the overall atomicity of my instrumentation code? Maybe optnone?
The instrumentation code like this:

/* Load */

      LoadInst *MapPtr = IRB.CreateLoad(MAP);
      MapPtr->setMetadata(M.getMDKindID("nosanitize"), MDNode::get(C, None));
/* Store */

      IRB.CreateStore(Num, MAP)
          ->setMetadata(M.getMDKindID("nosanitize"), MDNode::get(C, None));

Fence before/after?

1 Like

Why do you want to disable reordering?

If the reordering breaks your code, that suggests the IR doesn’t model the actual constraints (e.g. aliasing variables). That’d be the thing to fix.

FWIW, before you introduce N complex instructions consider to place calls and link in the object code or IR later. Attributes on calls allow you to model the effects to some degree and you can hide arbitrarily complex logic easily.

The reorder didn’t break the functionality of my code, but I would need to make subsequent changes to the executable binary, which might require that the order in which I inserted the code wouldn’t change. So I asked the question.

Thanks. I have also considered using the call or link approach, but this might introduce some overhead. So I would like to see if there is a more direct way ~ now, it may still need to use call or link.

It might be a good idea. I’ll try it right away!