Advertisement
lichenran1234

LLVM division - optimal

Apr 11th, 2021
194
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.34 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. %num = alloca i32
  7. %denom = alloca i32
  8.  
  9. store i32 25200, i32* %num
  10. store i32 2500, i32* %denom
  11.  
  12. %denom_val = load i32* %denom
  13.  
  14. ; check if the denom is zero
  15. %denom_is_zero = icmp eq i32 %denom_val, 0
  16. br i1 %denom_is_zero, label %if_denom_zero, label %if_denom_non_zero
  17.  
  18. if_denom_zero:
  19. %err_str = getelementptr inbounds [22 x i8]* @.err_str, i32 0, i32 0
  20. %call = call i32 (i8*, ...)* @printf(i8* %err_str)
  21.  
  22. ret i32 0
  23.  
  24. if_denom_non_zero:
  25. %quot = alloca i32
  26. store i32 0, i32* %quot
  27. %rem = alloca i32
  28. store i32 0, i32* %rem
  29.  
  30. %cur_denom_multiple = alloca i32
  31. %cur_quot = alloca i32
  32. br label %cond_is_finished
  33.  
  34. cond_is_finished:
  35. %temp1 = load i32* %num
  36. %finished = icmp ugt i32 %denom_val, %temp1
  37. br i1 %finished, label %finished_true, label %finished_false
  38.  
  39. finished_false:
  40. %temp2 = load i32* %denom
  41. store i32 %temp2, i32* %cur_denom_multiple
  42. store i32 1, i32* %cur_quot
  43. br label %cond_if_should_multiply_denom
  44.  
  45. cond_if_should_multiply_denom:
  46. %temp3 = load i32* %cur_denom_multiple
  47. %temp4 = add i32 %temp3, %temp3
  48. %temp5 = load i32* %num
  49.  
  50. %cond_not_should_multiply_denom = icmp ugt i32 %temp4, %temp5
  51. br i1 %cond_not_should_multiply_denom, label %if_not_should_multiply_denom, label %if_should_multiply_denom
  52.  
  53. if_should_multiply_denom:
  54. store i32 %temp4, i32* %cur_denom_multiple
  55. %temp6 = load i32* %cur_quot
  56. %temp7 = add i32 %temp6, %temp6
  57. store i32 %temp7, i32* %cur_quot
  58. br label %cond_if_should_multiply_denom
  59.  
  60. if_not_should_multiply_denom:
  61. %temp8 = load i32* %cur_quot
  62. %temp9 = load i32* %quot
  63. %temp10 = add i32 %temp8, %temp9
  64. store i32 %temp10, i32* %quot
  65.  
  66. %temp11 = load i32* %num
  67. %temp12 = load i32* %cur_denom_multiple
  68. %temp13 = sub i32 %temp11, %temp12
  69. store i32 %temp13, i32* %num
  70. br label %cond_is_finished
  71.  
  72. finished_true:
  73. %temp14 = load i32* %num
  74. store i32 %temp14, i32* %rem
  75. %temp15 = load i32* %quot
  76.  
  77. %output_str = getelementptr inbounds [12 x i8]* @.output_str, i32 0, i32 0
  78. %call2 = call i32 (i8*, ...)* @printf(i8* %output_str, i32 %temp15)
  79. %call3 = call i32 (i8*, ...)* @printf(i8* %output_str, i32 %temp14)
  80.  
  81. ret i32 0
  82. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement