Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Goのmapとheapを自作してみた / How to create your own map and heap in Go

DQNEO
February 25, 2019

Goのmapとheapを自作してみた / How to create your own map and heap in Go

Goコンパイラを自作するにあたって、mapとheapを自作してみたので、どうやって作ったのかを説明します。

DQNEO

February 25, 2019
Tweet

More Decks by DQNEO

Other Decks in Programming

Transcript

  1. m = map [int]int { 1: 2, 3: 4, }

    とにかくハードルを下げる 要素数も固定
  2. m = map [int]int { 1: 2, 3: 4, }

    map[int]int 1 2 3 4 メモリ上に8byteずつ値を並べる
  3. x = m[3] map get 1 2 3 4 keyを16byteずつホップしながら探索

    マッチしたらその右隣の値を返す
  4. Keyの探索 (X86-64の例) emit("mov %%r13, %%rax") // i emit("imul $16, %%rax")

    // i * 16 emit("mov %%r10, %%rcx") // head emit("add %%rax, %%rcx") // head + i * 16 emit("mov (%%rcx), %%rdx") // eval key value 16byteずつホップしながらkeyを探索
  5. マッチしたKey位置から Valueを取得 emit("mov 8(%%rcx), %%r15") // get value of value

    emit("jmp %s", labelEnd) key値がマッチしたら、 8bytes隣のvalue値を取り出して 探索ループを脱出する
  6. for range構文 for k,v := range m { ... }

    for i:=0, i<len(m), i++ { k := mData[ i * 16] v := m[v] } 構文木を書き換えて、普通のfor文に変換する
  7. 1 &s1 3 &s2 1 &i1 3 &i2 値のアドレスを格納する 値自体はheapに置き、そのアドレスをmap領域に書

    き込む。 valueのサイズは8bytesのままなので、今までの mapロジックをほぼそのまま使える