Deviation error in Assembly (MIPS)

Asked

Viewed 362 times

2

I need to transform the following c code to MIPS Assembly:

int i;
int vetor[8];
  for(i=0; i<8; i++) {

    if(i%2==0)
    vetor[i] = i * 2;

    else
    vetor[i] = vetor[i] + vetor[i-1];
}

By doing this I arrived at the following code:

.data
    .space 32 #reserva o espaço necessário pro vetor

.text
    #t0 = endereço inicial da memória de dados
    #t1 = divisor e multiplicador
    #t2 = contador
    #t3 = limite do contador
    #t4 = resto da divisão
    #t5 = resultado da multiplicação de i por 2
    #t6 = recupera o elemento da anterior da meméria para fazer a soma no else 

    lui $t0, 0x1001

    ori $t1, $zero, 2
    ori $t2, $zero, 0
    ori $t3, $zero, 8

    loop:       #faz o loop até 8(t3)
    beq $t2, $t3, exit

    div $t2, $t1        #divide i por 2
    mfhi $t4        #faz a a comparação do resto com $zero
    bne $t4 $zero, else #e pula para else caso seja impar

    mult $t1, $t2
    mfhi $t5 
    sw $t5, 0($t0)
    addi $t2, $t2, 1    #incrementa o contador
    addi $t0, $t0, 4    #incrementa o "ponteiro" para o vetor

    j loop

    else:

    lw $t6, 0($t0)
    add $t5, $t5, $t6   #reutiliza $t5 que está com o valor anterior e soma com a posição atual da memória 
    sw $t5, 0($t0)
    addi $t2, $t2, 1    #incrementa o contador
    addi $t0, $t0, 4    #incrementa o "ponteiro" para o vetor
    j loop

    exit:

But the loop only works for the first two iterations, after which it simply ignores the jump inside the label Else. But if I comment (delete) the lines on Else, and leave only the counter of the unreported loop it traverses the for to the end.

Else:

#lw $t6, 0($t0)
    #add $t5, $t5, $t6  #reutiliza $t5 que está com o valor anterior e soma com a posição atual da memória 
    #sw $t5, 0($t0)
    addi $t2, $t2, 1    #incrementa o contador
    #addi $t0, $t0, 4   #incrementa o "ponteiro" para o vetor
    j loop

But I didn’t understand why I’m not changing the variables related to the loop anywhere ($t2 and $T3), except in the incrementer. Can anyone identify where I’m going wrong?

1 answer

1


  • In the MIPS pipeline architecture, shunt instructions change the PC at a time in which the next instruction has already been sought and is about to be executed (Machine Cycle Step 3);

inserir a descrição da imagem aqui

  • Therefore, even if there is a deviation (jump or branch), the instruction to follow will be executed!
  • SOLUTION: always use a Nop instruction (no Operation) after instructions diversion.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.