From C to the CPU: Compilers and the ISA

We use a higher-level language such as C to express our intentions, then use a compiler to translate those intentions into executable low-level operations. Layer 1: We express our intentions in a programming language and produce a C source file (using C as the example here). Layer 2: The compiler compiles the source code we provide. At this layer, it checks types, selects instructions for operations, implements conditions, arranges branches, handles data access, and so on. The compiler chooses an implementation here. A CPU may have several ways to achieve the same goal expressed in C source code, so the compiler selects an approach, and the CPU later executes the approach the compiler has provided. This layer produces an assembly representation or target machine code. Layer 3: Assembly and linking. The assembler encodes machine instructions, and the linker connects object files and the required libraries. This produces an executable file. Layer 4: The CPU executes machine instructions according to the ISA. Fetch → decode → execute → update state → continue. The results include changes to data, progress in execution, output, or other effects. From this, we can see that: 1. The programmer decides what behavior the program should implement. 2. The compiler decides how to use the target machine’s capabilities to implement that behavior. 3. The CPU executes the generated instructions at runtime. Take types as an example: types let programmers express their intentions in a higher-level language, and the compiler translates those intentions into executable low-level operations. At the lowest level, the CPU treats bits alike; they have no inherent meaning. The programmer defines types to express the rules they want the data to follow. The compiler understands the type rules, chooses an implementation the target machine can execute, and translates human instructions into machine instructions that let the CPU carry out human intentions. The CPU processes those machine instructions according to the ISA’s rules. Every concept in the upper layer (the C source file) must ultimately be expressed using ISA instructions. The compiler does that expressing, and the CPU ultimately processes those machine instructions according to the ISA’s rules. The ISA is the complete vocabulary this machine can understand, as well as the contract between the compiler and the CPU. Now let’s connect this to Week 1 of CS107E. CS107E involves bare-metal programming. We write a program on our own computer that we want to run on the Mango Pi, then use a cross-compiler on our computer to compile that source program into machine code the Mango Pi’s CPU can execute, following the ISA rules that CPU obeys. During compilation, the compiler has already chosen the implementation. The CPU then follows the ISA’s rules to carry out those instructions.