Search code examples
code-generationjavacc

Code Generation jumps and marks


I only have this Code Fragment which is partly JavaCC.

My question is how does the jump and mark command work. In line 9 there is a conditional jump and in line 16 there is a regular one, which will always get executed in the else condition. But how do they know where to jump? The markByLable is always after the Jump (I really don't know what it's doing). And as in Line 20 there is another false label of Descriptor, but after the else Statement. So if Line 8 would jump to it in case the if condition is not true it would jump over the else condition.

Code as picture with some extra statements

I'd really appreciate the help.


Solution

  • The code in brackets is not JavaCC code; it's Java code. In other words, the classes Label, Descriptor, and the class of m_codeGen are just written in ordinary Java. If you don't have access to those classes, you will have to figure out what they do from how they are used and from your picture.

    The best strategy might be to ask the person you got the image from.

    For an if statement like say if( E ) C else D you can expect the generated code to look something like this

    [Code for E]
    JUMP_IF_FALSE to L1
    L0: NOP
    [Code for C]
    JUMP to L2
    L1: NOP
    [Code for D]
    L2: NOP
    

    So let's trace the code executed while parsing if( E ) C else D, for some expression E and statements C and D, and try to figure out/guess what's going on.

    1. desc = expr() parses and emits code for E.
    2. Based on your picture, you can see that the call m_codeGen.falseJump(desc) is doing two things. It's making a brand new label (L1 in our example) and then emitting an instruction to jump to it. I would guess that it does one more thing that is not shown in the picture, which is that it creates another new label (L0) and assigns it to desc.m_tLabel, since otherwise it's a mystery how that field is initialized. (Maybe that field is initialized in some other way.)
    3. The next command is m_codeGen.markByLabel(desc.m_tLabel). Based on your picture, this seems to do two things. (I'm really guessing here.) It emits (?) a NOP instruction and then it tells the label (L0) that it is labeling that instruction by setting the label's m_statement_field. (Since there is no branch, to L0, this step could probably be omitted and, if it were, then it wouldn't matter whether the desc.m_tLabel field is initialized or not.)
    4. stat() parses and emits code for C.
    5. Next is endifLabel = m_codeGen.createLabel(). Obviously this creates a new label (L2).
    6. Next is m_codeGen.jump(endifLabel); This must emit the unconditional jump (to L2).
    7. Next is m_codeGen.markByLabel(desc.m_fLabel);. This emits the second NOP and labels it (with L1).
    8. stat() parses and emits code for D.
    9. Finally is m_codeGen.markByLabel(endifLabel);. This emits the final NOP and labels it (with L2).