{"eip":663,"title":"SWAPN, DUPN and EXCHANGE instructions","description":"Introduce additional instructions for manipulating the stack which allow accessing the stack at higher depths","authors":["Alex Beregszaszi (@axic)","Charles Cooper (@charles-cooper)","Danno Ferrin (@shemnon)"],"status":"Stagnant","type":"Standards Track","category":"Core","created":"2017-07-03","requires":[3540,5450],"discussionsTo":"https://ethereum-magicians.org/t/eip-663-unlimited-swap-and-dup-instructions/3346","repo":"EIPs","label":"EIP-663","officialUrl":"https://eips.ethereum.org/EIPS/eip-663","sourceUrl":"https://github.com/ethereum/EIPs/blob/master/EIPS/eip-663.md","url":"https://eips.huatuo.xyz/eip-663/","tldr":{"en":"Proposed DUPN, SWAPN and EXCHANGE opcodes for EOF code, so compilers can reach stack items deeper than the current 16-slot limit of DUP and SWAP.","ja":"EOF コード向けに DUPN、SWAPN、EXCHANGE オペコードを提案し、コンパイラが DUP と SWAP の現行の 16 スロット制限より深いスタック項目にアクセスできるようにする。","ko":"EOF 코드를 위해 DUPN, SWAPN, EXCHANGE 오피코드를 제안해, 컴파일러가 DUP와 SWAP의 현재 16슬롯 한도보다 깊은 스택 항목에 접근할 수 있게 한다.","zh":"为 EOF 代码提出 DUPN、SWAPN 和 EXCHANGE 操作码，让编译器能够访问比 DUP 和 SWAP 当前 16 个槽位上限更深的栈项。"},"tags":["evm","eof","opcodes","stack","compilers"],"explainers":{"en":{"lang":"en","tldr":"Proposed DUPN, SWAPN and EXCHANGE opcodes for EOF code, so compilers can reach stack items deeper than the current 16-slot limit of DUP and SWAP.","tags":["evm","eof","opcodes","stack","compilers"],"related":[8024,3540,5450,7692,4200],"updated":"2026-10-19","url":"https://eips.huatuo.xyz/eip-663/","markdown":"## What problem does it solve?\n\nThe EVM stack holds up to 1,024 items, but `DUP1`–`DUP16` and `SWAP1`–`SWAP16` can only reach the top 16. When a function has many local variables, parameters and return values, compilers run out of reachable slots. This is Solidity's familiar \"stack too deep\" error. Today compilers work around it by moving values to memory, which makes code larger, slower and harder to optimize.\n\n## How it works\n\nThe proposal adds three instructions. Each takes a 1-byte **immediate** argument `imm` written into the code right after the opcode:\n\n| Opcode | Name | Effect (1-based depth) |\n| --- | --- | --- |\n| `0xe6` | `DUPN imm` | `n = imm + 1`; copy the `n`-th item to the top |\n| `0xe7` | `SWAPN imm` | `n = imm + 1`; swap the top with the `(n+1)`-th item |\n| `0xe8` | `EXCHANGE imm` | `n = (imm \u003e\u003e 4) + 1`, `m = (imm \u0026 0x0F) + 1`; swap items `n+1` and `n+m+1` |\n\nSo `DUPN` and `SWAPN` reach up to 256 items deep. `EXCHANGE` swaps two items below the top without touching the top. Normally that takes three instructions (for example `SWAP2 SWAP3 SWAP2`), and stack-scheduling compilers need it often. All three cost **3 gas**, the same as `DUP`/`SWAP`, because they are just pointer swaps.\n\nThe instructions are valid **only in EOF code** ([EIP-3540](/eip-3540/)). In legacy bytecode they remain undefined and halt. EOF's validation makes them safe:\n\n- Relative jumps ([EIP-4200](/eip-4200/)) may not land on an immediate byte.\n- Stack validation ([EIP-5450](/eip-5450/)) checks at deploy time that the stack is deep enough for each use.\n\nThe argument is a fixed immediate, not a value taken from the stack, so static analysis and auditing tools can still follow the stack.\n\n## Sample code\n\nIllustrative EOF assembly (each line is shown on its own, starting from the same stack):\n\n```\n// stack (top first): a b c d ... x(20th) ...\nDUPN 0x13        // n = 20 -\u003e copies x to the top\nSWAPN 0x13       // n = 20 -\u003e swaps top with the 21st item\nEXCHANGE 0x12    // n = 2, m = 3 -\u003e swaps the 3rd and 6th items\n```\n\nEncoded bytes: `e6 13  e7 13  e8 12`.\n\n## Things to know\n\n- This proposal is Stagnant. It depends on EOF, and EOF ([EIP-7692](/eip-7692/)) has not been activated on Ethereum mainnet.\n- [EIP-8024](/eip-8024/) is a follow-up that brings `SWAPN`, `DUPN` and `EXCHANGE` to **legacy** bytecode, with an encoding designed not to break existing jump destinations. Look there for the current direction.\n- For Solidity users, the practical fix for \"stack too deep\" today is still the IR-based pipeline (`--via-ir`), or restructuring code into structs or smaller functions.\n"},"ja":{"lang":"ja","tldr":"EOF コード向けに DUPN、SWAPN、EXCHANGE オペコードを提案し、コンパイラが DUP と SWAP の現行の 16 スロット制限より深いスタック項目にアクセスできるようにする。","tags":["evm","eof","opcodes","stack","compilers"],"related":[8024,3540,5450,7692,4200],"updated":"2026-10-19","url":"https://eips.huatuo.xyz/ja/eip-663/","markdown":"## 何を解決するのか\n\nEVM のスタックは最大 1,024 個の項目を保持できますが、`DUP1`〜`DUP16` と `SWAP1`〜`SWAP16` が届くのは上位 16 個だけです。関数にローカル変数、引数、戻り値が多いと、コンパイラは到達可能なスロットを使い切ってしまいます。これが Solidity でおなじみの「stack too deep」エラーです。現在のコンパイラは値をメモリに移すことで回避していますが、コードが大きく遅くなり、最適化も難しくなります。\n\n## 仕組み\n\nこの提案は 3 つの命令を追加します。各命令は、オペコードの直後にコード内へ書かれる 1 バイトの**即値**引数 `imm` を取ります。\n\n| オペコード | 名前 | 効果（深さは 1 始まり） |\n| --- | --- | --- |\n| `0xe6` | `DUPN imm` | `n = imm + 1`。`n` 番目の項目を先頭にコピーする |\n| `0xe7` | `SWAPN imm` | `n = imm + 1`。先頭と `(n+1)` 番目の項目を入れ替える |\n| `0xe8` | `EXCHANGE imm` | `n = (imm \u003e\u003e 4) + 1`、`m = (imm \u0026 0x0F) + 1`。`n+1` 番目と `n+m+1` 番目の項目を入れ替える |\n\nこのため、`DUPN` と `SWAPN` は最大 256 項目の深さまで届きます。`EXCHANGE` は先頭に触れずに、先頭より下の 2 つの項目を入れ替えます。通常これには 3 つの命令（たとえば `SWAP2 SWAP3 SWAP2`）が必要で、スタックスケジューリングを行うコンパイラはこれを頻繁に必要とします。3 つとも単なるポインタの入れ替えなので、コストは `DUP`/`SWAP` と同じ **3 ガス**です。\n\nこれらの命令が有効なのは **EOF コードでのみ**（[EIP-3540](/eip-3540/)）です。レガシーのバイトコードでは未定義のままで、実行が停止します。EOF の検証によって、これらは安全に使えます。\n\n- 相対ジャンプ（[EIP-4200](/eip-4200/)）は即値バイトに着地してはなりません。\n- スタック検証（[EIP-5450](/eip-5450/)）が、各使用箇所でスタックが十分な深さを持つことをデプロイ時に確認します。\n\n引数はスタックから取る値ではなく固定の即値なので、静的解析や監査ツールは引き続きスタックを追跡できます。\n\n## サンプルコード\n\nEOF アセンブリの例（各行は同じスタックから始めた場合を個別に示しています）:\n\n```\n// stack (top first): a b c d ... x(20th) ...\nDUPN 0x13        // n = 20 -\u003e copies x to the top\nSWAPN 0x13       // n = 20 -\u003e swaps top with the 21st item\nEXCHANGE 0x12    // n = 2, m = 3 -\u003e swaps the 3rd and 6th items\n```\n\nエンコードされたバイト列: `e6 13  e7 13  e8 12`。\n\n## 知っておくべきこと\n\n- この提案は Stagnant です。EOF に依存していますが、EOF（[EIP-7692](/eip-7692/)）は Ethereum メインネットで有効化されていません。\n- [EIP-8024](/eip-8024/) は、既存のジャンプ先を壊さないよう設計されたエンコーディングで、`SWAPN`、`DUPN`、`EXCHANGE` を**レガシー**のバイトコードに導入する後継の提案です。現在の方向性はそちらを参照してください。\n- Solidity ユーザーにとって、「stack too deep」への現実的な対処は、今でも IR ベースのパイプライン（`--via-ir`）を使うか、コードを構造体や小さな関数に再構成することです。\n"},"ko":{"lang":"ko","tldr":"EOF 코드를 위해 DUPN, SWAPN, EXCHANGE 오피코드를 제안해, 컴파일러가 DUP와 SWAP의 현재 16슬롯 한도보다 깊은 스택 항목에 접근할 수 있게 한다.","tags":["evm","eof","opcodes","stack","compilers"],"related":[8024,3540,5450,7692,4200],"updated":"2026-10-19","url":"https://eips.huatuo.xyz/ko/eip-663/","markdown":"## 어떤 문제를 해결하나요?\n\nEVM 스택은 최대 1,024개 항목을 담을 수 있지만, `DUP1`–`DUP16`과 `SWAP1`–`SWAP16`은 맨 위 16개에만 닿습니다. 함수에 지역 변수, 매개변수, 반환값이 많으면 컴파일러는 접근 가능한 슬롯을 다 써버립니다. Solidity에서 익숙한 \"stack too deep\" 오류가 바로 이것입니다. 오늘날 컴파일러는 값을 메모리로 옮겨 이를 우회하는데, 그러면 코드가 더 커지고 느려지며 최적화하기도 어려워집니다.\n\n## 어떻게 동작하나요?\n\n이 제안은 세 가지 명령어를 추가합니다. 각 명령어는 오피코드 바로 뒤 코드에 기록되는 1바이트 **즉치값(immediate)** 인자 `imm`을 받습니다.\n\n| 오피코드 | 이름 | 효과(깊이는 1부터 시작) |\n| --- | --- | --- |\n| `0xe6` | `DUPN imm` | `n = imm + 1`. `n`번째 항목을 맨 위로 복사 |\n| `0xe7` | `SWAPN imm` | `n = imm + 1`. 맨 위와 `(n+1)`번째 항목을 교환 |\n| `0xe8` | `EXCHANGE imm` | `n = (imm \u003e\u003e 4) + 1`, `m = (imm \u0026 0x0F) + 1`. `n+1`번째와 `n+m+1`번째 항목을 교환 |\n\n그래서 `DUPN`과 `SWAPN`은 최대 256개 깊이까지 닿습니다. `EXCHANGE`는 맨 위를 건드리지 않고 그 아래의 두 항목을 교환합니다. 보통은 명령어 세 개(예: `SWAP2 SWAP3 SWAP2`)가 필요하고, 스택 스케줄링을 하는 컴파일러는 이를 자주 필요로 합니다. 세 명령어 모두 단순한 포인터 교환이므로 `DUP`/`SWAP`과 같은 **3 가스**가 듭니다.\n\n이 명령어들은 **EOF 코드에서만**([EIP-3540](/eip-3540/)) 유효합니다. 레거시 바이트코드에서는 계속 정의되지 않은 상태이며 실행이 중단됩니다. EOF의 검증 덕분에 이들은 안전하게 쓸 수 있습니다.\n\n- 상대 점프([EIP-4200](/eip-4200/))는 즉치값 바이트에 착지할 수 없습니다.\n- 스택 검증([EIP-5450](/eip-5450/))은 배포 시점에 각 사용처에서 스택이 충분히 깊은지 확인합니다.\n\n인자는 스택에서 꺼낸 값이 아니라 고정된 즉치값이므로, 정적 분석과 감사 도구는 여전히 스택을 추적할 수 있습니다.\n\n## 샘플 코드\n\n설명용 EOF 어셈블리(각 줄은 같은 스택에서 시작한 경우를 개별적으로 보여줍니다):\n\n```\n// stack (top first): a b c d ... x(20th) ...\nDUPN 0x13        // n = 20 -\u003e copies x to the top\nSWAPN 0x13       // n = 20 -\u003e swaps top with the 21st item\nEXCHANGE 0x12    // n = 2, m = 3 -\u003e swaps the 3rd and 6th items\n```\n\n인코딩된 바이트: `e6 13  e7 13  e8 12`.\n\n## 알아둘 점\n\n- 이 제안은 Stagnant 상태입니다. EOF에 의존하는데, EOF([EIP-7692](/eip-7692/))는 이더리움 메인넷에서 활성화되지 않았습니다.\n- [EIP-8024](/eip-8024/)는 기존 점프 목적지를 깨뜨리지 않도록 설계한 인코딩으로 `SWAPN`, `DUPN`, `EXCHANGE`를 **레거시** 바이트코드에 도입하는 후속 제안입니다. 현재의 방향은 그쪽을 참고하세요.\n- Solidity 사용자에게 오늘날 \"stack too deep\"의 현실적인 해결책은 여전히 IR 기반 파이프라인(`--via-ir`)이나 코드를 구조체나 더 작은 함수로 재구성하는 것입니다.\n"},"zh":{"lang":"zh","tldr":"为 EOF 代码提出 DUPN、SWAPN 和 EXCHANGE 操作码，让编译器能够访问比 DUP 和 SWAP 当前 16 个槽位上限更深的栈项。","tags":["evm","eof","opcodes","stack","compilers"],"related":[8024,3540,5450,7692,4200],"updated":"2026-10-19","url":"https://eips.huatuo.xyz/zh/eip-663/","markdown":"## 它解决什么问题？\n\nEVM 栈最多可容纳 1,024 项，但 `DUP1`–`DUP16` 和 `SWAP1`–`SWAP16` 只能访问最上面的 16 项。当函数有很多局部变量、参数和返回值时，编译器就会用光可访问的槽位。这就是 Solidity 里常见的\"stack too deep\"错误。如今编译器通过把值挪到内存来绕过它，这会让代码更大、更慢，也更难优化。\n\n## 它如何运作\n\n该提案新增三条指令。每条指令带一个 1 字节的**立即数**参数 `imm`，写在操作码后面的代码中：\n\n| 操作码 | 名称 | 效果（深度从 1 开始） |\n| --- | --- | --- |\n| `0xe6` | `DUPN imm` | `n = imm + 1`；把第 `n` 项复制到栈顶 |\n| `0xe7` | `SWAPN imm` | `n = imm + 1`；交换栈顶与第 `(n+1)` 项 |\n| `0xe8` | `EXCHANGE imm` | `n = (imm \u003e\u003e 4) + 1`，`m = (imm \u0026 0x0F) + 1`；交换第 `n+1` 项与第 `n+m+1` 项 |\n\n因此 `DUPN` 和 `SWAPN` 最深可达 256 项。`EXCHANGE` 在不动栈顶的情况下交换栈顶以下的两项。通常这需要三条指令（例如 `SWAP2 SWAP3 SWAP2`），而做栈调度的编译器经常需要它。三者都只花费 **3 gas**，与 `DUP`/`SWAP` 相同，因为它们只是指针交换。\n\n这些指令**只在 EOF 代码中**有效（[EIP-3540](/eip-3540/)）。在传统字节码中它们仍然是未定义的，会导致执行中止。EOF 的验证让它们是安全的：\n\n- 相对跳转（[EIP-4200](/eip-4200/)）不能落在立即数字节上。\n- 栈验证（[EIP-5450](/eip-5450/)）在部署时检查每处使用时栈是否足够深。\n\n参数是固定的立即数，而不是从栈中取的值，所以静态分析和审计工具仍然可以跟踪栈。\n\n## 示例代码\n\nEOF 汇编示例（每一行都是从同一个栈开始、单独展示的）：\n\n```\n// stack (top first): a b c d ... x(20th) ...\nDUPN 0x13        // n = 20 -\u003e copies x to the top\nSWAPN 0x13       // n = 20 -\u003e swaps top with the 21st item\nEXCHANGE 0x12    // n = 2, m = 3 -\u003e swaps the 3rd and 6th items\n```\n\n编码后的字节：`e6 13  e7 13  e8 12`。\n\n## 需要注意\n\n- 该提案处于 Stagnant 状态。它依赖 EOF，而 EOF（[EIP-7692](/eip-7692/)）尚未在以太坊主网激活。\n- [EIP-8024](/eip-8024/) 是后续提案，它把 `SWAPN`、`DUPN` 和 `EXCHANGE` 带入**传统**字节码，其编码经过设计，不会破坏现有的跳转目标。当前的方向请看那里。\n- 对 Solidity 用户来说，如今解决\"stack too deep\"的实用办法仍然是基于 IR 的流水线（`--via-ir`），或者把代码重构为结构体或更小的函数。\n"}},"requiredBy":[7692]}
