https://github.com/akkartik/mu/blob/master/406try-divide.mu
  1 # slow, iterative divide instruction
  2 # preconditions: _nr >= 0, _dr > 0
  3 fn try-divide _nr: int, _dr: int -> result/eax: int {
  4   # x = next power-of-2 multiple of _dr after _nr
  5   var x/ecx: int <- copy 1
  6   {
  7 #?     print-int32-hex 0, x
  8 #?     print-string 0, "\n"
  9     var tmp/edx: int <- copy _dr
 10     tmp <- multiply x
 11     compare tmp, _nr
 12     break-if->
 13     x <- shift-left 1
 14     loop
 15   }
 16 #?   print-string 0, "--\n"
 17   # min, max = x/2, x
 18   var max/ecx: int <- copy x
 19   var min/edx: int <- copy max
 20   min <- shift-right 1
 21   # narrow down result between min and max
 22   var i/eax: int <- copy min
 23   {
 24 #?     print-int32-hex 0, i
 25 #?     print-string 0, "\n"
 26     var foo/ebx: int <- copy _dr
 27     foo <- multiply i
 28     compare foo, _nr
 29     break-if->
 30     i <- increment
 31     loop
 32   }
 33   result <- copy i
 34   result <- decrement
 35 #?   print-string 0, "=> "
 36 #?   print-int32-hex 0, result
 37 #?   print-string 0, "\n"
 38 }
 39 
 40 fn test-try-divide-1 {
 41   var result/eax: int <- try-divide 0, 2
 42   check-ints-equal result, 0, "F - try-divide-1"
 43 }
 44 
 45 fn test-try-divide-2 {
 46   var result/eax: int <- try-divide 1, 2
 47   check-ints-equal result, 0, "F - try-divide-2"
 48 }
 49 
 50 fn test-try-divide-3 {
 51   var result/eax: int <- try-divide 2, 2
 52   check-ints-equal result, 1, "F - try-divide-3"
 53 }
 54 
 55 fn test-try-divide-4 {
 56   var result/eax: int <- try-divide 4, 2
 57   check-ints-equal result, 2, "F - try-divide-4"
 58 }
 59 
 60 fn test-try-divide-5 {
 61   var result/eax: int <- try-divide 6, 2
 62   check-ints-equal result, 3, "F - try-divide-5"
 63 }
 64 
 65 fn test-try-divide-6 {
 66   var result/eax: int <- try-divide 9, 3
 67   check-ints-equal result, 3, "F - try-divide-6"
 68 }
 69 
 70 fn test-try-divide-7 {
 71   var result/eax: int <- try-divide 0xc, 4
 72   check-ints-equal result, 3, "F - try-divide-7"
 73 }
 74 
 75 fn test-try-divide-8 {
 76   var result/eax: int <- try-divide 0x1b, 3  # 27/3
 77   check-ints-equal result, 9, "F - try-divide-8"
 78 }
 79 
 80 fn test-try-divide-9 {
 81   var result/eax: int <- try-divide 0x1c, 3  # 28/3
 82   check-ints-equal result, 9, "F - try-divide-9"
 83 }
 84 
 85 # only positive dr for now
 86 fn try-modulo nr: int, dr: int -> result/eax: int {
 87   var _positive-nr/eax: int <- abs nr
 88   var positive-nr/ecx: int <- copy _positive-nr
 89   var tmp/eax: int <- try-divide positive-nr, dr
 90   tmp <- multiply dr
 91   tmp <- subtract positive-nr
 92   result <- negate
 93 }
 94 
 95 fn test-try-modulo-negative-nr {
 96   var result/eax: int <- try-modulo -0xa, 7
 97   check-ints-equal result, 3, "F - test-try-modulo-negative-nr"
 98 }
 99 
100 fn abs n: int -> result/eax: int {
101   result <- copy n
102   compare n, 0
103   break-if->=
104   result <- negate
105 }