user1890481
user1890481

Reputation: 21

Code generation for if statements

I am in the middle of writing the code generation section of a compiler for a simple (C-like) language. I am having a problem with "if" statements. I would like to generate corresponding jump instructions for each part of the condition, like GCC would do. The structure which holds the structure of boolean expressions is an Abstract Syntax Tree.

So far, I wrote a function who would generate corresponding labels for comparisons and also for logical and and logical negation. However, I have a huge problem when trying to make this function work for logical or as well.

For a simple statement, such as

if (25 < 19) then
  print 99
statements

I would like my code to look like this:

cmp 25, 19
jge label0
label1:
print 99
label0:
statements

(and my function does display something similar for this simple example).

When handling a negation, you just have to negate the tests for these conditions (transform jge into jl above). For logical and, you just generate the corresponding code for the left and right conjuncts sequentially, in a straightforward manner. But for OR, I have reached a number of challenging problems. Instead of jumping to the statements after the if (or the next else branch) if the condition fails, as for all the other cases, I would have to jump to the actual place where the code resides if either of the OR's operands hold. Then when you have two ORs, the situation gets even worse, as the AST represents ORs using binary nodes and the function who attempts to translate translates to our Intermediate Representation of choice uses this AST.

Could anyone please offer their help on this issue? I have also tried consulting 'Engineering a Compiler', but I haven't managed to find out anything useful from there.

Upvotes: 2

Views: 1065

Answers (1)

Mike Sandford
Mike Sandford

Reputation: 1365

I remember doing something similar to this when I was in school.

You should focus on having your compiler generate a result for every condition in these kinds of expressions and then use "and" or "or" instructions provided by the CPU to "merge" the results and then do your jump based on the "merged" result.

Upvotes: 1

Related Questions