The same machine, two languages. How C compiles down to the instructions you already know. La misma máquina, dos lenguajes. Cómo C se compila a las instrucciones que ya conoces.
Santi Scagliusi, PhD
maximo(25, -3) in assemblymaximo(25, -3) en ensambladormov.w #25, R12 ; a mov.w #-3, R13 ; b call #maximo ; R12 = ? maximo: cmp.w R13, R12 jge maxFin mov.w R13, R12 maxFin: ret
What will R12 hold on return?¿Qué valor tendrá R12 al volver?
And with a = -7, b = -2?¿Y con a = -7, b = -2?
The compiler does not invent new operations. It emits the same MSP430 instructions you write by hand.El compilador no inventa operaciones nuevas. Emite las mismas instrucciones MSP430 que escribes a mano.
A C compiler reads this and produces an assembly file.Un compilador de C lee esto y produce un archivo en ensamblador.
Args in R12, R13. Result in R12.Argumentos en R12, R13. Resultado en R12.
One word is 16 bits. A type that fits in a word is cheap. Anything wider costs extra instructions and memory accesses.Una palabra son 16 bits. Un tipo que cabe en una palabra es barato. Lo más ancho cuesta instrucciones y accesos a memoria extra.
Small data model: a pointer is a 16-bit address. One register.Modelo de datos pequeño: un puntero es una dirección de 16 bits. Un registro.
No floating-point hardware: float and double run as software library calls.Sin hardware de coma flotante: float y double se ejecutan con llamadas a librería.
Pick the smallest type that holds your value. The width you choose becomes the number of instructions.Elige el tipo más pequeño que contenga tu valor. El ancho que elijas se convierte en número de instrucciones.
Every assembly program starts the same way: a code section, an entry label, stop the watchdog, set the stack, then run.Todo programa en ensamblador empieza igual: una sección de código, una etiqueta de entrada, parar el watchdog, fijar la pila y ejecutar.
.text lands the code in FRAM at 0x4400..text coloca el código en FRAM en 0x4400.
Stop the watchdog first, or it resets the chip mid-run.Para el watchdog primero, o reinicia el chip a mitad.
.intvec writes main into 0xFFFE: where the CPU starts..intvec escribe main en 0xFFFE: donde arranca la CPU.
CALL saves the address of the next instruction on the stack, then jumps. RET pops it back into PC.CALL guarda en la pila la dirección de la siguiente instrucción y salta. RET la recupera en el PC.
RET is just MOV @SP+, PC. The saved address goes straight back into the program counter.RET es simplemente MOV @SP+, PC. La dirección guardada vuelve directa al contador de programa.
mov.w #7, R12 call #doble ; [SP] = ? mov.w R12, R13 ; aquí vuelve RET doble: rla.w R12 ; R12 = 2 * R12 ret
Which address sits on top of the stack?¿Qué dirección queda en la cima de la pila?
Hint: the instruction after the CALL.Pista: la instrucción que sigue al CALL.
A subroutine that uses R6 must save and restore it. Every PUSH needs a matching POP before RET.Una subrutina que use R6 debe guardarlo y restaurarlo. Cada PUSH necesita su POP antes de RET.
When RET runs, the top of the stack must hold the return address, not your saved R6. PUSH and POP keep SP balanced.Cuando se ejecuta RET, la cima de la pila debe contener la dirección de retorno, no tu R6 guardado. PUSH y POP mantienen el SP equilibrado.
Low address at the bottom, near SP. CALL wrote 0x4414; PUSH put old R6 below it.Dirección baja abajo, junto a SP. CALL escribió 0x4414; PUSH puso el R6 antiguo debajo.
A shared contract so C and assembly can call each other. The TI and GCC compilers both follow the MSP430 EABI.Un contrato común para que C y ensamblador se llamen entre sí. Los compiladores de TI y GCC siguen el EABI del MSP430.
Args fill R12→R15 in order. The result comes back in R12: same register, dual role. Los argumentos llenan R12→R15 en orden. El resultado vuelve en R12: el mismo registro, doble función.
The convention splits the working registers in two, so neither side saves more than it must.La convención divide los registros de trabajo en dos, para que ningún lado guarde más de lo necesario.
mov.w #0x00AA, R10 call #suma3 ; R12 = 1+2+3 suma3: push.w R10 ; guardar mov.w R12, R10 add.w R13, R10 add.w R14, R10 mov.w R10, R12 pop.w R10 ; restaurar ret
Without PUSH/POP, what is R10?Sin PUSH/POP, ¿cuánto vale R10?
Comment them out and run it again.Coméntalos y vuelve a ejecutar.
A tiny C function and the assembly a compiler produces from it. Read it line by line, it is instructions you know.Una función pequeña en C y el ensamblador que un compilador genera de ella. Léela línea a línea, son instrucciones que conoces.
Arguments a and b were already in R12 and R13. The compiler only needed a compare, a jump, and a return.Los argumentos a y b ya estaban en R12 y R13. El compilador solo necesitó una comparación, un salto y un retorno.
Every C control structure becomes the same two-instruction idea: set the flags, then a conditional jump.Toda estructura de control de C se vuelve la misma idea de dos instrucciones: fija los flags y luego salta condicionalmente.
if-else, do-while, every loop: the same shape. Only the condition and the jump change.if-else, do-while, cualquier bucle: la misma forma. Solo cambian la condición y el salto.
Counting toward zero drops the compare entirely. DEC already sets the Zero flag.Contar hacia cero elimina la comparación por completo. DEC ya fija el flag Zero.
DEC updates the flags as a side effect, so JNZ reads them directly.DEC actualiza los flags como efecto secundario, así que JNZ los lee directamente.
C calls your assembly like any C function. .global plus the convention is the whole contract.C llama a tu ensamblador como a cualquier función. .global más la convención es todo el contrato.
Course setting: small code and data model, so call/ret and 16-bit pointers. The large model uses calla/reta.En el curso: modelo de código y datos pequeño, así que call/ret y punteros de 16 bits. El modelo grande usa calla/reta.
Dereferencing a C pointer and the indirect register mode are the same mechanism: a register holds the address.Desreferenciar un puntero de C y el modo registro indirecto son el mismo mecanismo: un registro guarda la dirección.
A 2-D table is stored row by row. The element address is a small offset calculation.Una tabla 2-D se guarda fila por fila. La dirección del elemento es un cálculo de desplazamiento pequeño.
Row 1, column 2 lands at byte +12: exactly what the arithmetic gives.Fila 1, columna 2 cae en el byte +12: justo lo que da la aritmética.
C and assembly share one machine and one contract.C y ensamblador comparten una máquina y un contrato.
The compiler emits MOV, ADD, CMP, jumps. Nothing you have not seen.El compilador emite MOV, ADD, CMP, saltos. Nada que no hayas visto.
The calling convention lets C and assembly call each other safely.La convención de llamada permite que C y ensamblador se llamen con seguridad.
A C pointer is a register holding an address: indirect addressing.Un puntero de C es un registro con una dirección: direccionamiento indirecto.