Advertisement
lichenran1234

LLVM division - simple

Apr 11th, 2021
1,637
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
LLVM 1.67 KB | None | 0 0
  1. @.output_str = private constant [12 x i8] c"Output: %d\0A\00"
  2. @.err_str = private constant [22 x i8] c"Error: zero division\0A\00"
  3. declare i32 @printf(i8*, ...)
  4.  
  5. define i32 @main() {
  6.   ; allocate stack space for numerator and denominator
  7.   %num = alloca i32
  8.   %denom = alloca i32
  9.  
  10.   ; assign values to them
  11.   store i32 21000, i32* %num
  12.   store i32 300, i32* %denom
  13.  
  14.   %denom_reg = load i32* %denom
  15.  
  16.   ; check if the denom is zero
  17.   %denom_is_zero = icmp eq i32 %denom_reg, 0
  18.   br i1 %denom_is_zero, label %if_denom_zero, label %if_denom_non_zero
  19.  
  20.   ; if the denom is zero, print error message and return
  21. if_denom_zero:
  22.  
  23.   %err_str = getelementptr inbounds [22 x i8]* @.err_str, i32 0, i32 0
  24.   %call = call i32 (i8*, ...)* @printf(i8* %err_str)
  25.  
  26.   ret i32 0
  27.  
  28.   ; else continue to calculate
  29. if_denom_non_zero:
  30.  
  31.   %quot = alloca i32
  32.   store i32 0, i32* %quot
  33.   %rem = alloca i32
  34.   store i32 0, i32* %rem
  35.   br label %cond
  36.  
  37. cond:
  38.   %1 = load i32* %num
  39.   %finished = icmp ugt i32 %denom_reg, %1
  40.   br i1 %finished, label %finished_true, label %finished_false
  41.  
  42. finished_false:
  43.   ; increment the quotient
  44.   %2 = load i32* %quot
  45.   %inc = add i32 %2, 1
  46.   store i32 %inc, i32* %quot
  47.  
  48.   ; num -= denom_reg
  49.   %3 = load i32* %num
  50.   %dec = sub i32 %3, %denom_reg
  51.   store i32 %dec, i32* %num
  52.   br label %cond
  53.  
  54. finished_true:
  55.   ; record the remainder (denom_reg - num)
  56.   %4 = load i32* %num
  57.   store i32 %4, i32* %rem
  58.   %5 = load i32* %quot
  59.  
  60.   %output_str = getelementptr inbounds [12 x i8]* @.output_str, i32 0, i32 0
  61.   %call2 = call i32 (i8*, ...)* @printf(i8* %output_str, i32 %5)
  62.   %call3 = call i32 (i8*, ...)* @printf(i8* %output_str, i32 %4)
  63.  
  64.   ret i32 0
  65. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement