title: Self-Modifying MIPS Code
body: <p>I'm trying to write a program in MIPS that continuously prompts for two integers and prints the sum until the sum is 0. The trick is that if the sum is 13, I need to call a method to change the assembled MIPS code so that</p>
  
  <pre><code>add $t2, $t0, $t1
  </code></pre>
  
  <p>becomes</p>
  
  <pre><code>and $t2, $t0, $t1
  </code></pre>
  
  <p>and all subsequent runs of the loop use the and instruction.</p>
  
  <p>I have the summation loop working so that when 13 is the sum the method instMod is called which I want to modify the instruction. Unfortunately, I have no idea where to start and can't find any examples of this online. I assume I need to somehow get the hex code of the add out of the assembled code and replace it with the hex code for the and but I do not know how to do that or if that is the right course of action to take.</p>
  
  <pre><code># Nick Gilbert
  # MIPS Program to demonstrate self-modifying code
  
  .data
  num1Prompt:     .asciiz     "Enter num1: "
  num2Prompt:     .asciiz     "Enter num2: "
  num1:           .word       0
  num2:           .word       0
  addOut:         .asciiz     "ADD: "
  andOut:         .asciiz     "AND: "
  
  .text
  main:
  sumLoop:
      la $a0, num1Prompt  #Asking user for num1
      li $v0, 4       #Call code to print string
      syscall     
  
      li $v0, 5       #Call code to read an int
      syscall
      move $t0, $v0       #Moving read int to $t1
  
      la $a0, num2Prompt  #Asking user for num2
      li $v0, 4       #Call code to print string
      syscall
  
      li $v0, 5       #Call code to read an int
      syscall
      move $t1, $v0       #Moving read int to $t2
  
      add $t2, $t0, $t1   #Adding num1 and num2 together
  
      la $a0, addOut
      li $v0, 4
      syscall
  
      move $a0, $t2
      li $v0, 1
      syscall
  
      beq $t2, 13, instMod    #Calling method to modify add instruction if sum = 13
      bne $t2, 0, sumLoop #If result is not yet 0, ask for new sum
  
  endSumLoop:
      li $v0, 10
      syscall
  
  instMod: #Method to change add instruction to an and instruction
  </code></pre>