boot2

Playing with the boostrap
git clone https://git.ryansepassi.com/git/boot2.git
Log | Files | Refs | README

040-array-index.scm (2066B)


      1 ;; tests/cc-cg/40-array-index.scm — array element access at non-zero
      2 ;; index. Models:
      3 ;;   int a[3]; a[0]=1; a[1]=2; a[2]=4; return a[0]+a[1]+a[2];  -> 7
      4 ;;
      5 ;; The cg API does the same dance the parser uses for a[i]:
      6 ;;   cg-push-sym sym-a   ; arr-typed lval
      7 ;;   cg-push-imm i       ; index rval
      8 ;;   cg-binop add        ; ptr arithmetic — `cg-load` decays array to
      9 ;;                       ; ptr, then add scales by elem size
     10 ;;   cg-push-deref       ; lval int through the computed pointer
     11 ;;
     12 ;; Wait — cg-binop pops both ops; for the lhs we need rval-of-arr,
     13 ;; not the array lval. We therefore call cg-load BEFORE the index
     14 ;; push, so the arr lval decays to a ptr-rval first.
     15 
     16 (let* ((cg     (cg-init))
     17        (arr-ty (%ctype 'arr 12 4 (cons %t-i32 3))))
     18   (cg-fn-begin cg "main" '() %t-i32)
     19   (let* ((off-a (cg-alloc-slot cg 12 4))
     20          (sym-a (%sym "a" 'var 'auto arr-ty off-a)))
     21     ;; a[0] = 1
     22     (cg-push-sym cg sym-a)
     23     (cg-load cg)                 ; arr lval -> ptr rval (decay)
     24     (cg-push-imm cg %t-i32 0)
     25     (cg-binop cg 'add)           ; ptr + 0
     26     (cg-push-deref cg)
     27     (cg-push-imm cg %t-i32 1)
     28     (cg-assign cg) (cg-pop cg)
     29     ;; a[1] = 2
     30     (cg-push-sym cg sym-a) (cg-load cg)
     31     (cg-push-imm cg %t-i32 1) (cg-binop cg 'add)
     32     (cg-push-deref cg)
     33     (cg-push-imm cg %t-i32 2)
     34     (cg-assign cg) (cg-pop cg)
     35     ;; a[2] = 4
     36     (cg-push-sym cg sym-a) (cg-load cg)
     37     (cg-push-imm cg %t-i32 2) (cg-binop cg 'add)
     38     (cg-push-deref cg)
     39     (cg-push-imm cg %t-i32 4)
     40     (cg-assign cg) (cg-pop cg)
     41     ;; return a[0] + a[1] + a[2]
     42     (cg-push-sym cg sym-a) (cg-load cg)
     43     (cg-push-imm cg %t-i32 0) (cg-binop cg 'add)
     44     (cg-push-deref cg) (cg-load cg)
     45     (cg-push-sym cg sym-a) (cg-load cg)
     46     (cg-push-imm cg %t-i32 1) (cg-binop cg 'add)
     47     (cg-push-deref cg) (cg-load cg)
     48     (cg-binop cg 'add)
     49     (cg-push-sym cg sym-a) (cg-load cg)
     50     (cg-push-imm cg %t-i32 2) (cg-binop cg 'add)
     51     (cg-push-deref cg) (cg-load cg)
     52     (cg-binop cg 'add)
     53     (cg-return cg))
     54   (cg-fn-end cg)
     55   (write-bv-fd 1 (cg-finish cg)))