Search code examples
compiler-constructionintermediate-language

Intermediate Code Generation on Functions


I am following Compiler design and I found the following problem.

int fact(int n){
   if(n==0) return 1;
   else return (n*fact(n-l))
}

for the above code, following was given as the intermediate code,

1. func begin fact
2. if (n==0) goto L1
3. T1 = n-1
4. param T1
5. refparam result
6. call fact, 2
7. T3 = n*result
8. return T3
9. L1: return 1
10. func end

Is the above intermediate code correct? If so, why call on line 6 takes 2 parameters while the original function takes 1 parameter. And whats the difference of param and refparam.

Please clarify me the above.


Solution

  • There are many different ways to design intermediate languages, but the one you're looking at does not directly indicate where to store the return value of a function call as part of the call syntax (that is, it doesn't say result = call fact, 1 or anything like that).

    Instead the location where the return value should be stored is passed as another parameter. That's why there are two instead of one. That's also why it uses refparam instead of param for result: We want to pass the address of result, not its value (which it doesn't even have at that point), so the return value can be stored there.