Learning Log
Separating Source Intent, Machine Encoding, and CPU Execution
Today's most important takeaway: I realized that I often confuse the intent expressed by source code, the encoding of machine instructions, and how the CPU executes them.
For example:
addi t0, zero, -1My initial reasoning went roughly like this:
1. The negative number -1 should be represented in two's complement.
2. Its 12-bit two's-complement representation is 111111111111.
3. That bit pattern can also be written as 0xFFF.
4. So why can't I simply write addi t0, zero, 0xFFF?
More precisely, I had not yet built this mental model:
I had merged the first and second layers.
In source code, 0xFFF expresses the positive integer 4095. In an already-encoded 12-bit ADDI immediate field, however, the same bits represent -1.
Afterward, I reflected: had I been expecting the assembler to do too much?
Yes. More precisely, I had not clearly distinguished the responsibilities of the assembler, the instruction-encoding rules, and the CPU.
When the assembler sees 0xFFF in source code, it treats that literal as 4095. It does not first read it as 4095, then notice ADDI and discover that 4095 is outside the immediate's allowed range, and automatically reinterpret 0xFFF as the in-range value -1.
I had expected it to do that because I personally thought that 0xFFF and -1 had the same machine-code encoding. I need to be alert to this mistaken intuition.
今天最重要的收获是:发现自己经常把源代码表达的意图、机器指令的编码,以及 CPU 如何执行弄混。
例如:
addi t0, zero, -1我最初的认知链路大致是:
1. -1 这个负数应该用补码表示。
2. 12 位补码就是 111111111111。
3. 它也可以写成 0xFFF。
4. 那么,为什么不能直接写 addi t0, zero, 0xFFF?
准确地说,是我还没有建立起这个心智模型:
我把第一层和第二层合并了。
在源码中,0xFFF 表达的是正整数 4095;而在已经编码好的 12 位 ADDI 立即数字段中,相同的比特对应 -1。
后来我反思:是不是我把汇编器想得太全能了?
是的。更准确地说,我之前没有明确区分汇编器、指令编码规则和 CPU 各自负责什么。
汇编器看到源码里的 0xFFF 时,会把这个字面量理解为 4095。它不会先把它看作 4095,再因为看到 ADDI、发现 4095 不在它的立即数取值范围内,就自动把 0xFFF 重新理解为范围内的 -1。
我之所以期待它这样做,是因为我个人觉得 0xFFF 和 -1 在机器码中的编码一样。所以,要警惕自己这种错误的直觉。