(*
TERRA Datentechnik, Technical Support Sheet                        
-------------------------------------------------------------------------

Ref: TZ-920619.1/Bj
Pri: 1

M2
4.0
Bad code generation


Bad code generation when fully optimized
----------------------------------------

Consider the following code:
*)

MODULE OptBug1;
(*/NOCHECK/OPT*)

FROM	SYSTEM		IMPORT
  (*P*) ADR;

FROM	Terminal	IMPORT
  (*P*)  WriteLn, WriteString;

TYPE
  Rec		= RECORD
  		    char1, char2 : CHAR;
  		  END;
VAR
  strPtr	: POINTER TO ARRAY [0..99] OF CHAR;
  recArr	: ARRAY [0..20] OF Rec;
  i		: CARDINAL;

BEGIN
  FOR i := 0 TO HIGH(recArr) DO
    recArr[i].char2 := CHR(50);
    
    (* code generated: 
    MOV     CX, 000A
    REP     
    STOSW   		; here is the fault, should be STOSB 
    STOSB   
    *)
    
  END; (* for *)
  
  FOR i := 0 TO HIGH(recArr) DO
    recArr[i].char1 := CHR(49);
    (* of course, when more statements follows here the compiler
       cannot optimize in the same way, therefore the bug does
       not appear.
    *)
    (* do something more *)
  END; (* for *)
  
  recArr[HIGH(recArr)].char2 := 0C;
  strPtr := ADR(recArr[0]);
  
  WriteString(strPtr^); (* you will see a messy output *)
  WriteLn;  
END OptBug1.
(*
When this code is compiled with full optimization e.g. as final version,
the compiler generates wrong code. The problem is that the compiler
accesses the ".char2" field in word width instead of byte width. This
destroys the value stored in ".char1". The problem can be workarounded
by enforcing the compiler not to optimize (switches /NOOPT or /CHECK).
*)