(original) (raw)

Suppose a programmer wants to inject their own global label definition into the body of a function with some guarantee that it will not be removed by the compiler.

One way to do this is to define a global label with an asm statement knowing that the asm statement will not be invoked until after the compiler’s optimization passes have run, but the following case demonstrates that a label defined with an asm statement is still susceptible to being duplicated:

#include

uint32\_t f(uint32\_t x);

uint32\_t g(uint32\_t x);

uint32\_t f(uint32\_t x) {

uint32\_t returnValue = g(x);

if (returnValue > 0U) {

returnValue = 0x40000000;

}

else {

returnValue = 0x80000000;

}

\_\_asm \_\_volatile\_\_ ("\\t.global my\_hook\_fcn\\nmy\_hook\_fcn:\\n");

return returnValue;

}

uint32\_t g(uint32\_t x) {

return x >> 1U;

}

If the above definition of f() is compiled with optimization at level 1 or higher, the TailDuplication optimization pass will duplicate and move the asm statement and return up into the if block and the else block before the asm statement is invoked. When the now duplicate asm statements are later invoked, the compiler will detect a symbol redefinition error.

To address this situation, the asm statement functionality could be extended to comprehend whether it contains a label definition, and if it does, to disallow duplication of the asm statement.

There are a couple of different approaches that could be taken to implement this:

1. Parse the content of the assembly string argument to the asm statement in the compiler front-end (during EmitAsmStmt(), for example) to determine if it contains a label definition, and if it does set the isNotDuplicable flag on the INLINEASM record that is created to represent the asm statement in the IR. To date, there is no precedence for processing the content of the assembly string argument until the asm statement is invoked before the integrated assembler starts processing the generated machine code.

2. Add a label constraint to the input and output operand syntax for asm statements. i.e.

\_\_asm \_\_volatile\_\_ (“\\t.global\\t%0\\n%0:\\n” : “lbl” (my\_hook\_fcn));

The “lbl” constraint would tell the compiler to mark the asm statement as isNotDuplicable when an INLINEASM record is created to represent it

There are alternatives to using an asm statement for this purpose, but I wondered if such an extension would be useful/valuable to the wider community.

Thoughts? Opinions?

Todd Snider

Compiler Group

Texas Instruments Incorporated