shuffle_select_fuzz_tester.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405
  1. #!/usr/bin/env python
  2. """A shuffle-select vector fuzz tester.
  3. This is a python program to fuzz test the LLVM shufflevector and select
  4. instructions. It generates a function with a random sequnece of shufflevectors
  5. while optionally attaching it with a select instruction (regular or zero merge),
  6. maintaining the element mapping accumulated across the function. It then
  7. generates a main function which calls it with a different value in each element
  8. and checks that the result matches the expected mapping.
  9. Take the output IR printed to stdout, compile it to an executable using whatever
  10. set of transforms you want to test, and run the program. If it crashes, it found
  11. a bug (an error message with the expected and actual result is printed).
  12. """
  13. from __future__ import print_function
  14. import random
  15. import uuid
  16. import argparse
  17. # Possibility of one undef index in generated mask for shufflevector instruction
  18. SHUF_UNDEF_POS = 0.15
  19. # Possibility of one undef index in generated mask for select instruction
  20. SEL_UNDEF_POS = 0.15
  21. # Possibility of adding a select instruction to the result of a shufflevector
  22. ADD_SEL_POS = 0.4
  23. # If we are adding a select instruction, this is the possibility of a
  24. # merge-select instruction (1 - MERGE_SEL_POS = possibility of zero-merge-select
  25. # instruction.
  26. MERGE_SEL_POS = 0.5
  27. test_template = r'''
  28. define internal fastcc {ty} @test({inputs}) noinline nounwind {{
  29. entry:
  30. {instructions}
  31. ret {ty} {last_name}
  32. }}
  33. '''
  34. error_template = r'''@error.{lane} = private unnamed_addr global [64 x i8] c"FAIL: lane {lane}, expected {exp}, found %d\0A{padding}"'''
  35. main_template = r'''
  36. define i32 @main() {{
  37. entry:
  38. ; Create a scratch space to print error messages.
  39. %str = alloca [64 x i8]
  40. %str.ptr = getelementptr inbounds [64 x i8], [64 x i8]* %str, i32 0, i32 0
  41. ; Build the input vector and call the test function.
  42. %v = call fastcc {ty} @test({inputs})
  43. br label %test.0
  44. {check_die}
  45. }}
  46. declare i32 @strlen(i8*)
  47. declare i32 @write(i32, i8*, i32)
  48. declare i32 @sprintf(i8*, i8*, ...)
  49. declare void @llvm.trap() noreturn nounwind
  50. '''
  51. check_template = r'''
  52. test.{lane}:
  53. %v.{lane} = extractelement {ty} %v, i32 {lane}
  54. %cmp.{lane} = {i_f}cmp {ordered}ne {scalar_ty} %v.{lane}, {exp}
  55. br i1 %cmp.{lane}, label %die.{lane}, label %test.{n_lane}
  56. '''
  57. undef_check_template = r'''
  58. test.{lane}:
  59. ; Skip this lane, its value is undef.
  60. br label %test.{n_lane}
  61. '''
  62. die_template = r'''
  63. die.{lane}:
  64. ; Capture the actual value and print an error message.
  65. call i32 (i8*, i8*, ...) @sprintf(i8* %str.ptr, i8* getelementptr inbounds ([64 x i8], [64 x i8]* @error.{lane}, i32 0, i32 0), {scalar_ty} %v.{lane})
  66. %length.{lane} = call i32 @strlen(i8* %str.ptr)
  67. call i32 @write(i32 2, i8* %str.ptr, i32 %length.{lane})
  68. call void @llvm.trap()
  69. unreachable
  70. '''
  71. class Type:
  72. def __init__(self, is_float, elt_width, elt_num):
  73. self.is_float = is_float # Boolean
  74. self.elt_width = elt_width # Integer
  75. self.elt_num = elt_num # Integer
  76. def dump(self):
  77. if self.is_float:
  78. str_elt = 'float' if self.elt_width == 32 else 'double'
  79. else:
  80. str_elt = 'i' + str(self.elt_width)
  81. if self.elt_num == 1:
  82. return str_elt
  83. else:
  84. return '<' + str(self.elt_num) + ' x ' + str_elt + '>'
  85. def get_scalar_type(self):
  86. return Type(self.is_float, self.elt_width, 1)
  87. # Class to represent any value (variable) that can be used.
  88. class Value:
  89. def __init__(self, name, ty, value = None):
  90. self.ty = ty # Type
  91. self.name = name # String
  92. self.value = value # list of integers or floating points
  93. # Class to represent an IR instruction (shuffle/select).
  94. class Instruction(Value):
  95. def __init__(self, name, ty, op0, op1, mask):
  96. Value.__init__(self, name, ty)
  97. self.op0 = op0 # Value
  98. self.op1 = op1 # Value
  99. self.mask = mask # list of integers
  100. def dump(self): pass
  101. def calc_value(self): pass
  102. # Class to represent an IR shuffle instruction
  103. class ShufInstr(Instruction):
  104. shuf_template = ' {name} = shufflevector {ty} {op0}, {ty} {op1}, <{num} x i32> {mask}\n'
  105. def __init__(self, name, ty, op0, op1, mask):
  106. Instruction.__init__(self, '%shuf' + name, ty, op0, op1, mask)
  107. def dump(self):
  108. str_mask = [('i32 ' + str(idx)) if idx != -1 else 'i32 undef' for idx in self.mask]
  109. str_mask = '<' + (', ').join(str_mask) + '>'
  110. return self.shuf_template.format(name = self.name, ty = self.ty.dump(), op0 = self.op0.name,
  111. op1 = self.op1.name, num = self.ty.elt_num, mask = str_mask)
  112. def calc_value(self):
  113. if self.value != None:
  114. print('Trying to calculate the value of a shuffle instruction twice')
  115. exit(1)
  116. result = []
  117. for i in range(len(self.mask)):
  118. index = self.mask[i]
  119. if index < self.ty.elt_num and index >= 0:
  120. result.append(self.op0.value[index])
  121. elif index >= self.ty.elt_num:
  122. index = index % self.ty.elt_num
  123. result.append(self.op1.value[index])
  124. else: # -1 => undef
  125. result.append(-1)
  126. self.value = result
  127. # Class to represent an IR select instruction
  128. class SelectInstr(Instruction):
  129. sel_template = ' {name} = select <{num} x i1> {mask}, {ty} {op0}, {ty} {op1}\n'
  130. def __init__(self, name, ty, op0, op1, mask):
  131. Instruction.__init__(self, '%sel' + name, ty, op0, op1, mask)
  132. def dump(self):
  133. str_mask = [('i1 ' + str(idx)) if idx != -1 else 'i1 undef' for idx in self.mask]
  134. str_mask = '<' + (', ').join(str_mask) + '>'
  135. return self.sel_template.format(name = self.name, ty = self.ty.dump(), op0 = self.op0.name,
  136. op1 = self.op1.name, num = self.ty.elt_num, mask = str_mask)
  137. def calc_value(self):
  138. if self.value != None:
  139. print('Trying to calculate the value of a select instruction twice')
  140. exit(1)
  141. result = []
  142. for i in range(len(self.mask)):
  143. index = self.mask[i]
  144. if index == 1:
  145. result.append(self.op0.value[i])
  146. elif index == 0:
  147. result.append(self.op1.value[i])
  148. else: # -1 => undef
  149. result.append(-1)
  150. self.value = result
  151. # Returns a list of Values initialized with actual numbers according to the
  152. # provided type
  153. def gen_inputs(ty, num):
  154. inputs = []
  155. for i in range(num):
  156. inp = []
  157. for j in range(ty.elt_num):
  158. if ty.is_float:
  159. inp.append(float(i*ty.elt_num + j))
  160. else:
  161. inp.append((i*ty.elt_num + j) % (1 << ty.elt_width))
  162. inputs.append(Value('%inp' + str(i), ty, inp))
  163. return inputs
  164. # Returns a random vector type to be tested
  165. # In case one of the dimensions (scalar type/number of elements) is provided,
  166. # fill the blank dimension and return appropriate Type object.
  167. def get_random_type(ty, num_elts):
  168. if ty != None:
  169. if ty == 'i8':
  170. is_float = False
  171. width = 8
  172. elif ty == 'i16':
  173. is_float = False
  174. width = 16
  175. elif ty == 'i32':
  176. is_float = False
  177. width = 32
  178. elif ty == 'i64':
  179. is_float = False
  180. width = 64
  181. elif ty == 'f32':
  182. is_float = True
  183. width = 32
  184. elif ty == 'f64':
  185. is_float = True
  186. width = 64
  187. int_elt_widths = [8, 16, 32, 64]
  188. float_elt_widths = [32, 64]
  189. if num_elts == None:
  190. num_elts = random.choice(range(2, 65))
  191. if ty == None:
  192. # 1 for integer type, 0 for floating-point
  193. if random.randint(0,1):
  194. is_float = False
  195. width = random.choice(int_elt_widths)
  196. else:
  197. is_float = True
  198. width = random.choice(float_elt_widths)
  199. return Type(is_float, width, num_elts)
  200. # Generate mask for shufflevector IR instruction, with SHUF_UNDEF_POS possibility
  201. # of one undef index.
  202. def gen_shuf_mask(ty):
  203. mask = []
  204. for i in range(ty.elt_num):
  205. if SHUF_UNDEF_POS/ty.elt_num > random.random():
  206. mask.append(-1)
  207. else:
  208. mask.append(random.randint(0, ty.elt_num*2 - 1))
  209. return mask
  210. # Generate mask for select IR instruction, with SEL_UNDEF_POS possibility
  211. # of one undef index.
  212. def gen_sel_mask(ty):
  213. mask = []
  214. for i in range(ty.elt_num):
  215. if SEL_UNDEF_POS/ty.elt_num > random.random():
  216. mask.append(-1)
  217. else:
  218. mask.append(random.randint(0, 1))
  219. return mask
  220. # Generate shuffle instructions with optional select instruction after.
  221. def gen_insts(inputs, ty):
  222. int_zero_init = Value('zeroinitializer', ty, [0]*ty.elt_num)
  223. float_zero_init = Value('zeroinitializer', ty, [0.0]*ty.elt_num)
  224. insts = []
  225. name_idx = 0
  226. while len(inputs) > 1:
  227. # Choose 2 available Values - remove them from inputs list.
  228. [idx0, idx1] = sorted(random.sample(range(len(inputs)), 2))
  229. op0 = inputs[idx0]
  230. op1 = inputs[idx1]
  231. # Create the shuffle instruction.
  232. shuf_mask = gen_shuf_mask(ty)
  233. shuf_inst = ShufInstr(str(name_idx), ty, op0, op1, shuf_mask)
  234. shuf_inst.calc_value()
  235. # Add the new shuffle instruction to the list of instructions.
  236. insts.append(shuf_inst)
  237. # Optionally, add select instruction with the result of the previous shuffle.
  238. if random.random() < ADD_SEL_POS:
  239. # Either blending with a random Value or with an all-zero vector.
  240. if random.random() < MERGE_SEL_POS:
  241. op2 = random.choice(inputs)
  242. else:
  243. op2 = float_zero_init if ty.is_float else int_zero_init
  244. select_mask = gen_sel_mask(ty)
  245. select_inst = SelectInstr(str(name_idx), ty, shuf_inst, op2, select_mask)
  246. select_inst.calc_value()
  247. # Add the select instructions to the list of instructions and to the available Values.
  248. insts.append(select_inst)
  249. inputs.append(select_inst)
  250. else:
  251. # If the shuffle instruction is not followed by select, add it to the available Values.
  252. inputs.append(shuf_inst)
  253. del inputs[idx1]
  254. del inputs[idx0]
  255. name_idx += 1
  256. return insts
  257. def main():
  258. parser = argparse.ArgumentParser(description=__doc__)
  259. parser.add_argument('--seed', default=str(uuid.uuid4()),
  260. help='A string used to seed the RNG')
  261. parser.add_argument('--max-num-inputs', type=int, default=20,
  262. help='Specify the maximum number of vector inputs for the test. (default: 20)')
  263. parser.add_argument('--min-num-inputs', type=int, default=10,
  264. help='Specify the minimum number of vector inputs for the test. (default: 10)')
  265. parser.add_argument('--type', default=None,
  266. help='''
  267. Choose specific type to be tested.
  268. i8, i16, i32, i64, f32 or f64.
  269. (default: random)''')
  270. parser.add_argument('--num-elts', default=None, type=int,
  271. help='Choose specific number of vector elements to be tested. (default: random)')
  272. args = parser.parse_args()
  273. print('; The seed used for this test is ' + args.seed)
  274. assert args.min_num_inputs < args.max_num_inputs , "Minimum value greater than maximum."
  275. assert args.type in [None, 'i8', 'i16', 'i32', 'i64', 'f32', 'f64'], "Illegal type."
  276. assert args.num_elts == None or args.num_elts > 0, "num_elts must be a positive integer."
  277. random.seed(args.seed)
  278. ty = get_random_type(args.type, args.num_elts)
  279. inputs = gen_inputs(ty, random.randint(args.min_num_inputs, args.max_num_inputs))
  280. inputs_str = (', ').join([inp.ty.dump() + ' ' + inp.name for inp in inputs])
  281. inputs_values = [inp.value for inp in inputs]
  282. insts = gen_insts(inputs, ty)
  283. assert len(inputs) == 1, "Only one value should be left after generating phase"
  284. res = inputs[0]
  285. # print the actual test function by dumping the generated instructions.
  286. insts_str = ''.join([inst.dump() for inst in insts])
  287. print(test_template.format(ty = ty.dump(), inputs = inputs_str,
  288. instructions = insts_str, last_name = res.name))
  289. # Print the error message templates as global strings
  290. for i in range(len(res.value)):
  291. pad = ''.join(['\\00']*(31 - len(str(i)) - len(str(res.value[i]))))
  292. print(error_template.format(lane = str(i), exp = str(res.value[i]),
  293. padding = pad))
  294. # Prepare the runtime checks and failure handlers.
  295. scalar_ty = ty.get_scalar_type()
  296. check_die = ''
  297. i_f = 'f' if ty.is_float else 'i'
  298. ordered = 'o' if ty.is_float else ''
  299. for i in range(len(res.value)):
  300. if res.value[i] != -1:
  301. # Emit runtime check for each non-undef expected value.
  302. check_die += check_template.format(lane = str(i), n_lane = str(i+1),
  303. ty = ty.dump(), i_f = i_f, scalar_ty = scalar_ty.dump(),
  304. exp = str(res.value[i]), ordered = ordered)
  305. # Emit failure handler for each runtime check with proper error message
  306. check_die += die_template.format(lane = str(i), scalar_ty = scalar_ty.dump())
  307. else:
  308. # Ignore lanes with undef result
  309. check_die += undef_check_template.format(lane = str(i), n_lane = str(i+1))
  310. check_die += '\ntest.' + str(len(res.value)) + ':\n'
  311. check_die += ' ret i32 0'
  312. # Prepare the input values passed to the test function.
  313. inputs_values = [', '.join([scalar_ty.dump() + ' ' + str(i) for i in inp]) for inp in inputs_values]
  314. inputs = ', '.join([ty.dump() + ' <' + inp + '>' for inp in inputs_values])
  315. print(main_template.format(ty = ty.dump(), inputs = inputs, check_die = check_die))
  316. if __name__ == '__main__':
  317. main()