0

What should be the o/p in the following case? I have run it on different compilers, got different results in each.

module top;
    reg a,b;
    function int  f(string s);
        $display("%s", s);
        return 1;
    endfunction

    initial begin
        $display(" Experiment 1 ");
        if (  f("hello") & (1==0))  begin
            $display(" 1 : if 1 is true");
        end

        $display(" Experiment 2 ");
        if ( (1==0) & f("hello"))  begin
            $display(" 2 : if 2 is true");
        end
        $display(" Experiment 3 ");
        if (  f("hello") && (1==0))  begin
            $display(" 3 : if 3 is true");
        end
        $display(" Experiment 4 ");
        if ( (1==0) && f("hello"))  begin
            $display(" 4 : if 4 is true");
        end
    end
endmodule
subh
  • 23
  • 7
  • +1 for stressing the simulators. I have just a guess. Probably the execution order in an `if` condition is not standardized, so the result is indeterministic. –  Jul 30 '18 at 10:31
  • @ahmedus should function call happens in every if construct or only in case of bitwise operation? – subh Jul 30 '18 at 11:14
  • 1
    I tried 3 simulators on EDA Playground, all gave different results. VCS never printed "hello", Incisive printed at 3, and Riviera at 1, 2, 3. There is no clear pattern regarding the operators. –  Jul 30 '18 at 11:23

1 Answers1

1

From lrm 11.4.7 Logical operators

The && and || operators shall use short circuit evaluation as follows:

  • The first operand expression shall always be evaluated.
  • For &&, if the first operand value is logically false then the second operand shall not be evaluated.
  • For ||, if the first operand value is logically true then the second operand shall not be evaluated.

According to this, hello should not be printed in '4'. But should be printed in '3'.

cases 1 and 2 can be prone to optimization. I could not find anything in the standard which would prevent the functions from being optimized there. So, i believe that both, insisive and reviera behaved correctly.

Looks like synopsys violates the standard though. My guess is that they over-optimized case '3'.

Community
  • 1
  • 1
Serge
  • 11,616
  • 3
  • 18
  • 28