# 3.3 ALU

前面章节我们简单讨论了计算机系统最基础的一些模型：

* 布尔代数：数字电路的数学基础
* 逻辑门：数字电路的物理媒介基础
* 与非门：逻辑门的基础
* 加法器与补码：二进制计算能力的基础

基于这些知识，我们已经可以设计出一个具备算术、逻辑运算能力的电路组件了，该组件被称为 ALU(Arithmetic Logic Unit),  ALU 是 CPU 的核心部件，负责所有的计算工作。我们以位数来限定 ALU 的计算能力，下图是一个 16 位 ALU 的示意图：

![16 Bit ALU](https://4257267501-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-MdQXCtxb9g6w1DURwQ9%2F-MdQXJqxxZBTSPzE2swO%2F-MdWJOMG8AM4GSW0cTcJ%2F16bit_alu.png?alt=media\&token=40294e30-9f36-47a5-a7fb-2439a3855d06)

其中 x, y, out 是 16 位的整数，采用二进制补码进行编码，x 与 y 是输入，out 是输出。图下方的 zr, ng 是标记位（Flag），zr 表示结果为 0, ng 表示结果为负。

图上方的 zx, nx 等 6 位叫控制位（Controll Bits），用来告诉 ALU 执行何种操作，例如是执行 x + y 还是 x & y 。 注意，我们讨论过所有的逻辑运算都可以通过 NAND 来完成，而所有的算术运算都可以通过加法来完成，所以理论上 ALU 只需要提供这两种运算，这样的话控制位只需要一位就足够了，更复杂的运算可以让 ALU 反复执行基础运算来达成。但实际上 ALU 是一个粒度更大的复合组件，因此会封装更多的复合操作，例如可以让 ALU 直接完成 x & y 运算, 这样可以极大简化 CPU 指令集的设计。复合功能的总数受控制位数目的限制，图中 ALU 的控制位有 6 位，因此最多可以支持 2^6=64 种运算。如何设计这 64 种运算是 ALU 设计时需要考虑的重要课题，因为 ALU 功能的设计会直接影响到 CPU 指令集的设计。


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://s2.shizhz.me/s2e3/3.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
