Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

assembly - Understanding how `lw` and `sw` actually work in a MIPS program

I'm having bit of a difficulty understanding what sw and lw do in a MIPS program. My understanding of the topic is that we use lw to transfer data from the memory into the register and vice-versa for sw. But how is this exactly accomplished?

Let's say we have the following line of code:

lw Reg.Dest, Offset(Reg.Source)
sw Reg.Source, Offset(Reg.Dest)

If we concentrate on lw it's essentially storing the data from the memory, Reg.Source and multiplying the address of that data with the Offset, always a multiple of $4$ because the registers deal with $32$ bits and the memory uses $8$ bits, into a specific address in the register which is equal to Offset + Reg.Source - so if we say that Offset = 16, Reg.Source = $s1 = 12 then the register will store the data from the memory into the address $28$ in the register.

Assuming that my understanding of lw is correct, my question is then how does sw work?

PS: It would be great if the answers could also contain just a one liner example such as sw $t0, 32($s3).

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

lw (load word) loads a word from memory to a register.

lw $2, 4($4) # $2 <- mem($4+4)

$2 is the destination register and $4 the address register. And the source of information is the memory.

4 is an offset that is added (not multiplied) to the address register. This kind of memory access is called based addressing and is it quite useful in many situations. For instance, if $4 hold the address of a struct, the offset allows to pick the different fields of the struct. Or the next or previous element in a array, etc. offset does not have to be a multiple of 4, but (address register + offset) must and most of the time both are.

Sw is similar, but stores a register into memory.

 sw $5, 8($7) # mem[$7+8] <- $5

Again $7 is the register holding the memory address, 8 an offset and $5 is the source of the information that will be written in memory.

Note that contrary to others MIPS instructions, the first operand is the source, not the destination. Probably this is to enforce the fact that the address register plays a similar role in both instruction, while in lw it is used to compute the memory address of the source of data and in sw the memory destination address.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...