hctdb_instrhelp.py 45 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154
  1. # Copyright (C) Microsoft Corporation. All rights reserved.
  2. # This file is distributed under the University of Illinois Open Source License. See LICENSE.TXT for details.
  3. import argparse
  4. import functools
  5. import collections
  6. from hctdb import *
  7. # get db singletons
  8. g_db_dxil = None
  9. def get_db_dxil():
  10. global g_db_dxil
  11. if g_db_dxil is None:
  12. g_db_dxil = db_dxil()
  13. return g_db_dxil
  14. g_db_hlsl = None
  15. def get_db_hlsl():
  16. global g_db_hlsl
  17. if g_db_hlsl is None:
  18. thisdir = os.path.dirname(os.path.realpath(__file__))
  19. with open(os.path.join(thisdir, "gen_intrin_main.txt"), "r") as f:
  20. g_db_hlsl = db_hlsl(f)
  21. return g_db_hlsl
  22. def format_comment(prefix, val):
  23. "Formats a value with a line-comment prefix."
  24. result = ""
  25. line_width = 80
  26. content_width = line_width - len(prefix)
  27. l = len(val)
  28. while l:
  29. if l < content_width:
  30. result += prefix + val.strip()
  31. result += "\n"
  32. l = 0
  33. else:
  34. split_idx = val.rfind(" ", 0, content_width)
  35. result += prefix + val[:split_idx].strip()
  36. result += "\n"
  37. val = val[split_idx+1:]
  38. l = len(val)
  39. return result
  40. def format_rst_table(list_of_tuples):
  41. "Produces a reStructuredText simple table from the specified list of tuples."
  42. # Calculate widths.
  43. widths = None
  44. for t in list_of_tuples:
  45. if widths is None:
  46. widths = [0] * len(t)
  47. for i, v in enumerate(t):
  48. widths[i] = max(widths[i], len(str(v)))
  49. # Build banner line.
  50. banner = ""
  51. for i, w in enumerate(widths):
  52. if i > 0:
  53. banner += " "
  54. banner += "=" * w
  55. banner += "\n"
  56. # Build the result.
  57. result = banner
  58. for i, t in enumerate(list_of_tuples):
  59. for j, v in enumerate(t):
  60. if j > 0:
  61. result += " "
  62. result += str(v)
  63. result += " " * (widths[j] - len(str(v)))
  64. result = result.rstrip()
  65. result += "\n"
  66. if i == 0:
  67. result += banner
  68. result += banner
  69. return result
  70. def build_range_tuples(i):
  71. "Produces a list of tuples with contiguous ranges in the input list."
  72. i = sorted(i)
  73. low_bound = None
  74. high_bound = None
  75. for val in i:
  76. if low_bound is None:
  77. low_bound = val
  78. high_bound = val
  79. else:
  80. assert(not high_bound is None)
  81. if val == high_bound + 1:
  82. high_bound = val
  83. else:
  84. yield (low_bound, high_bound)
  85. low_bound = val
  86. high_bound = val
  87. if not low_bound is None:
  88. yield (low_bound, high_bound)
  89. def build_range_code(var, i):
  90. "Produces a fragment of code that tests whether the variable name matches values in the given range."
  91. ranges = build_range_tuples(i)
  92. result = ""
  93. for r in ranges:
  94. if r[0] == r[1]:
  95. cond = var + " == " + str(r[0])
  96. else:
  97. cond = "(%d <= %s && %s <= %d)" % (r[0], var, var, r[1])
  98. if result == "":
  99. result = cond
  100. else:
  101. result = result + " || " + cond
  102. return result
  103. class db_docsref_gen:
  104. "A generator of reference documentation."
  105. def __init__(self, db):
  106. self.db = db
  107. instrs = [i for i in self.db.instr if i.is_dxil_op]
  108. instrs = sorted(instrs, key=lambda v : ("" if v.category == None else v.category) + "." + v.name)
  109. self.instrs = instrs
  110. val_rules = sorted(db.val_rules, key=lambda v : ("" if v.category == None else v.category) + "." + v.name)
  111. self.val_rules = val_rules
  112. def print_content(self):
  113. self.print_header()
  114. self.print_body()
  115. self.print_footer()
  116. def print_header(self):
  117. print("<!DOCTYPE html>")
  118. print("<html><head><title>DXIL Reference</title>")
  119. print("<style>body { font-family: Verdana; font-size: small; }</style>")
  120. print("</head><body><h1>DXIL Reference</h1>")
  121. self.print_toc("Instructions", "i", self.instrs)
  122. self.print_toc("Rules", "r", self.val_rules)
  123. def print_body(self):
  124. self.print_instruction_details()
  125. self.print_valrule_details()
  126. def print_instruction_details(self):
  127. print("<h2>Instruction Details</h2>")
  128. for i in self.instrs:
  129. print("<h3><a name='i%s'>%s</a></h3>" % (i.name, i.name))
  130. print("<div>Opcode: %d. This instruction %s.</div>" % (i.dxil_opid, i.doc))
  131. if i.remarks:
  132. # This is likely a .rst fragment, but this will do for now.
  133. print("<div> " + i.remarks + "</div>")
  134. print("<div>Operands:</div>")
  135. print("<ul>")
  136. for o in i.ops:
  137. if o.pos == 0:
  138. print("<li>result: %s - %s</li>" % (o.llvm_type, o.doc))
  139. else:
  140. enum_desc = "" if o.enum_name == "" else " one of %s: %s" % (o.enum_name, ",".join(db.enum_idx[o.enum_name].value_names()))
  141. print("<li>%d - %s: %s%s%s</li>" % (o.pos - 1, o.name, o.llvm_type, "" if o.doc == "" else " - " + o.doc, enum_desc))
  142. print("</ul>")
  143. print("<div><a href='#Instructions'>(top)</a></div>")
  144. def print_valrule_details(self):
  145. print("<h2>Rule Details</h2>")
  146. for i in self.val_rules:
  147. print("<h3><a name='r%s'>%s</a></h3>" % (i.name, i.name))
  148. print("<div>" + i.doc + "</div>")
  149. print("<div><a href='#Rules'>(top)</a></div>")
  150. def print_toc(self, name, aprefix, values):
  151. print("<h2><a name='" + name + "'>" + name + "</a></h2>")
  152. last_category = ""
  153. for i in values:
  154. if i.category != last_category:
  155. if last_category != None:
  156. print("</ul>")
  157. print("<div><b>%s</b></div><ul>" % i.category)
  158. last_category = i.category
  159. print("<li><a href='#" + aprefix + "%s'>%s</a></li>" % (i.name, i.name))
  160. print("</ul>")
  161. def print_footer(self):
  162. print("</body></html>")
  163. class db_instrhelp_gen:
  164. "A generator of instruction helper classes."
  165. def __init__(self, db):
  166. self.db = db
  167. TypeInfo = collections.namedtuple("TypeInfo", "name bits")
  168. self.llvm_type_map = {
  169. "i1": TypeInfo("bool", 1),
  170. "i8": TypeInfo("int8_t", 8),
  171. "u8": TypeInfo("uint8_t", 8),
  172. "i32": TypeInfo("int32_t", 32),
  173. "u32": TypeInfo("uint32_t", 32)
  174. }
  175. self.IsDxilOpFuncCallInst = "hlsl::OP::IsDxilOpFuncCallInst"
  176. def print_content(self):
  177. self.print_header()
  178. self.print_body()
  179. self.print_footer()
  180. def print_header(self):
  181. print("///////////////////////////////////////////////////////////////////////////////")
  182. print("// //")
  183. print("// Copyright (C) Microsoft Corporation. All rights reserved. //")
  184. print("// DxilInstructions.h //")
  185. print("// //")
  186. print("// This file provides a library of instruction helper classes. //")
  187. print("// //")
  188. print("// MUCH WORK YET TO BE DONE - EXPECT THIS WILL CHANGE - GENERATED FILE //")
  189. print("// //")
  190. print("///////////////////////////////////////////////////////////////////////////////")
  191. print("")
  192. print("// TODO: add correct include directives")
  193. print("// TODO: add accessors with values")
  194. print("// TODO: add validation support code, including calling into right fn")
  195. print("// TODO: add type hierarchy")
  196. print("namespace hlsl {")
  197. def bool_lit(self, val):
  198. return "true" if val else "false";
  199. def op_type(self, o):
  200. if o.llvm_type in self.llvm_type_map:
  201. return self.llvm_type_map[o.llvm_type].name
  202. raise ValueError("Don't know how to describe type %s for operand %s." % (o.llvm_type, o.name))
  203. def op_size(self, o):
  204. if o.llvm_type in self.llvm_type_map:
  205. return self.llvm_type_map[o.llvm_type].bits
  206. raise ValueError("Don't know how to describe type %s for operand %s." % (o.llvm_type, o.name))
  207. def op_const_expr(self, o):
  208. return "(%s)(llvm::dyn_cast<llvm::ConstantInt>(Instr->getOperand(%d))->getZExtValue())" % (self.op_type(o), o.pos - 1)
  209. def op_set_const_expr(self, o):
  210. type_size = self.op_size(o)
  211. return "llvm::Constant::getIntegerValue(llvm::IntegerType::get(Instr->getContext(), %d), llvm::APInt(%d, (uint64_t)val))" % (type_size, type_size)
  212. def print_body(self):
  213. for i in self.db.instr:
  214. if i.is_reserved: continue
  215. if i.inst_helper_prefix:
  216. struct_name = "%s_%s" % (i.inst_helper_prefix, i.name)
  217. elif i.is_dxil_op:
  218. struct_name = "DxilInst_%s" % i.name
  219. else:
  220. struct_name = "LlvmInst_%s" % i.name
  221. if i.doc:
  222. print("/// This instruction %s" % i.doc)
  223. print("struct %s {" % struct_name)
  224. print(" llvm::Instruction *Instr;")
  225. print(" // Construction and identification")
  226. print(" %s(llvm::Instruction *pInstr) : Instr(pInstr) {}" % struct_name)
  227. print(" operator bool() const {")
  228. if i.is_dxil_op:
  229. op_name = i.fully_qualified_name()
  230. print(" return %s(Instr, %s);" % (self.IsDxilOpFuncCallInst, op_name))
  231. else:
  232. print(" return Instr->getOpcode() == llvm::Instruction::%s;" % i.name)
  233. print(" }")
  234. print(" // Validation support")
  235. print(" bool isAllowed() const { return %s; }" % self.bool_lit(i.is_allowed))
  236. if i.is_dxil_op:
  237. print(" bool isArgumentListValid() const {")
  238. print(" if (%d != llvm::dyn_cast<llvm::CallInst>(Instr)->getNumArgOperands()) return false;" % (len(i.ops) - 1))
  239. print(" return true;")
  240. # TODO - check operand types
  241. print(" }")
  242. print(" // Metadata")
  243. print(" bool requiresUniformInputs() const { return %s; }" % self.bool_lit(i.requires_uniform_inputs))
  244. EnumWritten = False
  245. for o in i.ops:
  246. if o.pos > 1: # 0 is return type, 1 is DXIL OP id
  247. if not EnumWritten:
  248. print(" // Operand indexes")
  249. print(" enum OperandIdx {")
  250. EnumWritten = True
  251. print(" arg_%s = %d," % (o.name, o.pos - 1))
  252. if EnumWritten:
  253. print(" };")
  254. AccessorsWritten = False
  255. for o in i.ops:
  256. if o.pos > 1: # 0 is return type, 1 is DXIL OP id
  257. if not AccessorsWritten:
  258. print(" // Accessors")
  259. AccessorsWritten = True
  260. print(" llvm::Value *get_%s() const { return Instr->getOperand(%d); }" % (o.name, o.pos - 1))
  261. print(" void set_%s(llvm::Value *val) { Instr->setOperand(%d, val); }" % (o.name, o.pos - 1))
  262. if o.is_const:
  263. print(" %s get_%s_val() const { return %s; }" % (self.op_type(o), o.name, self.op_const_expr(o)))
  264. print(" void set_%s_val(%s val) { Instr->setOperand(%d, %s); }" % (o.name, self.op_type(o), o.pos - 1, self.op_set_const_expr(o)))
  265. print("};")
  266. print("")
  267. def print_footer(self):
  268. print("} // namespace hlsl")
  269. class db_enumhelp_gen:
  270. "A generator of enumeration declarations."
  271. def __init__(self, db):
  272. self.db = db
  273. # Some enums should get a last enum marker.
  274. self.lastEnumNames = {
  275. "OpCode": "NumOpCodes",
  276. "OpCodeClass": "NumOpClasses"
  277. }
  278. def print_enum(self, e, **kwargs):
  279. print("// %s" % e.doc)
  280. print("enum class %s : unsigned {" % e.name)
  281. hide_val = kwargs.get("hide_val", False)
  282. sorted_values = e.values
  283. if kwargs.get("sort_val", True):
  284. sorted_values = sorted(e.values, key=lambda v : ("" if v.category == None else v.category) + "." + v.name)
  285. last_category = None
  286. for v in sorted_values:
  287. if v.category != last_category:
  288. if last_category != None:
  289. print("")
  290. print(" // %s" % v.category)
  291. last_category = v.category
  292. line_format = " {name}"
  293. if not e.is_internal and not hide_val:
  294. line_format += " = {value}"
  295. line_format += ","
  296. if v.doc:
  297. line_format += " // {doc}"
  298. print(line_format.format(name=v.name, value=v.value, doc=v.doc))
  299. if e.name in self.lastEnumNames:
  300. lastName = self.lastEnumNames[e.name]
  301. versioned = ["%s_Dxil_%d_%d = %d," % (lastName, major, minor, info[lastName])
  302. for (major, minor), info in sorted(self.db.dxil_version_info.items())
  303. if lastName in info]
  304. if versioned:
  305. print("")
  306. for val in versioned:
  307. print(" " + val)
  308. print("")
  309. print(" " + lastName + " = " + str(len(sorted_values)) + " // exclusive last value of enumeration")
  310. print("};")
  311. def print_content(self):
  312. for e in sorted(self.db.enums, key=lambda e : e.name):
  313. self.print_enum(e)
  314. class db_oload_gen:
  315. "A generator of overload tables."
  316. def __init__(self, db):
  317. self.db = db
  318. instrs = [i for i in self.db.instr if i.is_dxil_op]
  319. self.instrs = sorted(instrs, key=lambda i : i.dxil_opid)
  320. def print_content(self):
  321. self.print_opfunc_props()
  322. print("...")
  323. self.print_opfunc_table()
  324. def print_opfunc_props(self):
  325. print("const OP::OpCodeProperty OP::m_OpCodeProps[(unsigned)OP::OpCode::NumOpCodes] = {")
  326. print("// OpCode OpCode name, OpCodeClass OpCodeClass name, void, h, f, d, i1, i8, i16, i32, i64, udt, obj, function attribute")
  327. # Example formatted string:
  328. # { OC::TempRegLoad, "TempRegLoad", OCC::TempRegLoad, "tempRegLoad", false, true, true, false, true, false, true, true, false, Attribute::ReadOnly, },
  329. # 012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789
  330. # 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0
  331. last_category = None
  332. # overload types are a string of (v)oid, (h)alf, (f)loat, (d)ouble, (1)-bit, (8)-bit, (w)ord, (i)nt, (l)ong, u(dt)
  333. f = lambda i,c : "true" if i.oload_types.find(c) >= 0 else "false"
  334. lower_exceptions = { "CBufferLoad" : "cbufferLoad", "CBufferLoadLegacy" : "cbufferLoadLegacy", "GSInstanceID" : "gsInstanceID" }
  335. lower_fn = lambda t: lower_exceptions[t] if t in lower_exceptions else t[:1].lower() + t[1:]
  336. attr_dict = { "": "None", "ro": "ReadOnly", "rn": "ReadNone", "nd": "NoDuplicate", "nr": "NoReturn" }
  337. attr_fn = lambda i : "Attribute::" + attr_dict[i.fn_attr] + ","
  338. for i in self.instrs:
  339. if last_category != i.category:
  340. if last_category != None:
  341. print("")
  342. print(" // {category:118} void, h, f, d, i1, i8, i16, i32, i64, udt, obj , function attribute".format(category=i.category))
  343. last_category = i.category
  344. print(" {{ OC::{name:24} {quotName:27} OCC::{className:25} {classNameQuot:28} {{{v:>6},{h:>6},{f:>6},{d:>6},{b:>6},{e:>6},{w:>6},{i:>6},{l:>6},{u:>6},{o:>6}}}, {attr:20} }},".format(
  345. name=i.name+",", quotName='"'+i.name+'",', className=i.dxil_class+",", classNameQuot='"'+lower_fn(i.dxil_class)+'",',
  346. v=f(i,"v"), h=f(i,"h"), f=f(i,"f"), d=f(i,"d"), b=f(i,"1"), e=f(i,"8"), w=f(i,"w"), i=f(i,"i"), l=f(i,"l"), u=f(i,"u"), o=f(i,"o"), attr=attr_fn(i)))
  347. print("};")
  348. def print_opfunc_table(self):
  349. # Print the table for OP::GetOpFunc
  350. op_type_texts = {
  351. "$cb": "CBRT(pETy);",
  352. "$o": "A(pETy);",
  353. "$r": "RRT(pETy);",
  354. "d": "A(pF64);",
  355. "dims": "A(pDim);",
  356. "f": "A(pF32);",
  357. "h": "A(pF16);",
  358. "i1": "A(pI1);",
  359. "i16": "A(pI16);",
  360. "i32": "A(pI32);",
  361. "i32c": "A(pI32C);",
  362. "i64": "A(pI64);",
  363. "i8": "A(pI8);",
  364. "$u4": "A(pI4S);",
  365. "pf32": "A(pPF32);",
  366. "res": "A(pRes);",
  367. "splitdouble": "A(pSDT);",
  368. "twoi32": "A(p2I32);",
  369. "twof32": "A(p2F32);",
  370. "fouri32": "A(p4I32);",
  371. "fourf32": "A(p4F32);",
  372. "u32": "A(pI32);",
  373. "u64": "A(pI64);",
  374. "u8": "A(pI8);",
  375. "v": "A(pV);",
  376. "w": "A(pWav);",
  377. "SamplePos": "A(pPos);",
  378. "udt": "A(udt);",
  379. "obj": "A(obj);",
  380. }
  381. last_category = None
  382. for i in self.instrs:
  383. if last_category != i.category:
  384. if last_category != None:
  385. print("")
  386. print(" // %s" % i.category)
  387. last_category = i.category
  388. line = " case OpCode::{name:24}".format(name = i.name + ":")
  389. for index, o in enumerate(i.ops):
  390. assert o.llvm_type in op_type_texts, "llvm type %s in instruction %s is unknown" % (o.llvm_type, i.name)
  391. op_type_text = op_type_texts[o.llvm_type]
  392. if index == 0:
  393. line = line + "{val:13}".format(val=op_type_text)
  394. else:
  395. line = line + "{val:9}".format(val=op_type_text)
  396. line = line + "break;"
  397. print(line)
  398. def print_opfunc_oload_type(self):
  399. # Print the function for OP::GetOverloadType
  400. elt_ty = "$o"
  401. res_ret_ty = "$r"
  402. cb_ret_ty = "$cb"
  403. udt_ty = "udt"
  404. obj_ty = "obj"
  405. last_category = None
  406. index_dict = collections.OrderedDict()
  407. single_dict = collections.OrderedDict()
  408. struct_list = []
  409. for instr in self.instrs:
  410. ret_ty = instr.ops[0].llvm_type
  411. # Skip case return type is overload type
  412. if (ret_ty == elt_ty):
  413. continue
  414. if ret_ty == res_ret_ty:
  415. struct_list.append(instr.name)
  416. continue
  417. if ret_ty == cb_ret_ty:
  418. struct_list.append(instr.name)
  419. continue
  420. in_param_ty = False
  421. # Try to find elt_ty in parameter types.
  422. for index, op in enumerate(instr.ops):
  423. # Skip return type.
  424. if (op.pos == 0):
  425. continue
  426. # Skip dxil opcode.
  427. if (op.pos == 1):
  428. continue
  429. op_type = op.llvm_type
  430. if (op_type == elt_ty):
  431. # Skip return op
  432. index = index - 1
  433. if index not in index_dict:
  434. index_dict[index] = [instr.name]
  435. else:
  436. index_dict[index].append(instr.name)
  437. in_param_ty = True
  438. break
  439. if (op_type == udt_ty or op_type == obj_ty):
  440. # Skip return op
  441. index = index - 1
  442. if index not in index_dict:
  443. index_dict[index] = [instr.name]
  444. else:
  445. index_dict[index].append(instr.name)
  446. in_param_ty = True
  447. if in_param_ty:
  448. continue
  449. # No overload, just return the single oload_type.
  450. assert len(instr.oload_types)==1, "overload no elt_ty %s" % (instr.name)
  451. ty = instr.oload_types[0]
  452. type_code_texts = {
  453. "d": "Type::getDoubleTy(m_Ctx)",
  454. "f": "Type::getFloatTy(m_Ctx)",
  455. "h": "Type::getHalfTy",
  456. "1": "IntegerType::get(m_Ctx, 1)",
  457. "8": "IntegerType::get(m_Ctx, 8)",
  458. "w": "IntegerType::get(m_Ctx, 16)",
  459. "i": "IntegerType::get(m_Ctx, 32)",
  460. "l": "IntegerType::get(m_Ctx, 64)",
  461. "v": "Type::getVoidTy(m_Ctx)",
  462. "u": "Type::getInt32PtrTy(m_Ctx)",
  463. "o": "Type::getInt32PtrTy(m_Ctx)",
  464. }
  465. assert ty in type_code_texts, "llvm type %s is unknown" % (ty)
  466. ty_code = type_code_texts[ty]
  467. if ty_code not in single_dict:
  468. single_dict[ty_code] = [instr.name]
  469. else:
  470. single_dict[ty_code].append(instr.name)
  471. for index, opcodes in index_dict.items():
  472. line = ""
  473. for opcode in opcodes:
  474. line = line + "case OpCode::{name}".format(name = opcode + ":\n")
  475. line = line + " DXASSERT_NOMSG(FT->getNumParams() > " + str(index) + ");\n"
  476. line = line + " return FT->getParamType(" + str(index) + ");"
  477. print(line)
  478. for code, opcodes in single_dict.items():
  479. line = ""
  480. for opcode in opcodes:
  481. line = line + "case OpCode::{name}".format(name = opcode + ":\n")
  482. line = line + " return " + code + ";"
  483. print(line)
  484. line = ""
  485. for opcode in struct_list:
  486. line = line + "case OpCode::{name}".format(name = opcode + ":\n")
  487. line = line + "{\n"
  488. line = line + " StructType *ST = cast<StructType>(Ty);\n"
  489. line = line + " return ST->getElementType(0);\n"
  490. line = line + "}"
  491. print(line)
  492. class db_valfns_gen:
  493. "A generator of validation functions."
  494. def __init__(self, db):
  495. self.db = db
  496. def print_content(self):
  497. self.print_header()
  498. self.print_body()
  499. def print_header(self):
  500. print("///////////////////////////////////////////////////////////////////////////////")
  501. print("// Instruction validation functions. //")
  502. def bool_lit(self, val):
  503. return "true" if val else "false";
  504. def op_type(self, o):
  505. if o.llvm_type == "i8":
  506. return "int8_t"
  507. if o.llvm_type == "u8":
  508. return "uint8_t"
  509. raise ValueError("Don't know how to describe type %s for operand %s." % (o.llvm_type, o.name))
  510. def op_const_expr(self, o):
  511. if o.llvm_type == "i8" or o.llvm_type == "u8":
  512. return "(%s)(llvm::dyn_cast<llvm::ConstantInt>(Instr->getOperand(%d))->getZExtValue())" % (self.op_type(o), o.pos - 1)
  513. raise ValueError("Don't know how to describe type %s for operand %s." % (o.llvm_type, o.name))
  514. def print_body(self):
  515. llvm_instrs = [i for i in self.db.instr if i.is_allowed and not i.is_dxil_op]
  516. print("static bool IsLLVMInstructionAllowed(llvm::Instruction &I) {")
  517. self.print_comment(" // ", "Allow: %s" % ", ".join([i.name + "=" + str(i.llvm_id) for i in llvm_instrs]))
  518. print(" unsigned op = I.getOpcode();")
  519. print(" return %s;" % build_range_code("op", [i.llvm_id for i in llvm_instrs]))
  520. print("}")
  521. print("")
  522. def print_comment(self, prefix, val):
  523. print(format_comment(prefix, val))
  524. class macro_table_gen:
  525. "A generator for macro tables."
  526. def format_row(self, row, widths, sep=', '):
  527. frow = [str(item) + sep + (' ' * (width - len(item)))
  528. for item, width in list(zip(row, widths))[:-1]] + [str(row[-1])]
  529. return ''.join(frow)
  530. def format_table(self, table, *args, **kwargs):
  531. widths = [ functools.reduce(max, [ len(row[i])
  532. for row in table], 1)
  533. for i in range(len(table[0]))]
  534. formatted = []
  535. for row in table:
  536. formatted.append(self.format_row(row, widths, *args, **kwargs))
  537. return formatted
  538. def print_table(self, table, macro_name):
  539. formatted = self.format_table(table)
  540. print( '// %s\n' % formatted[0] +
  541. '#define %s(ROW) \\\n' % macro_name +
  542. ' \\\n'.join([' ROW(%s)' % frow for frow in formatted[1:]]))
  543. class db_sigpoint_gen(macro_table_gen):
  544. "A generator for SigPoint tables."
  545. def __init__(self, db):
  546. self.db = db
  547. def print_sigpoint_table(self):
  548. self.print_table(self.db.sigpoint_table, 'DO_SIGPOINTS')
  549. def print_interpretation_table(self):
  550. self.print_table(self.db.interpretation_table, 'DO_INTERPRETATION_TABLE')
  551. def print_content(self):
  552. self.print_sigpoint_table()
  553. self.print_interpretation_table()
  554. class string_output:
  555. def __init__(self):
  556. self.val = ""
  557. def write(self, text):
  558. self.val = self.val + str(text)
  559. def __str__(self):
  560. return self.val
  561. def run_with_stdout(fn):
  562. import sys
  563. _stdout_saved = sys.stdout
  564. so = string_output()
  565. try:
  566. sys.stdout = so
  567. fn()
  568. finally:
  569. sys.stdout = _stdout_saved
  570. return str(so)
  571. def get_hlsl_intrinsic_stats():
  572. db = get_db_hlsl()
  573. longest_fn = db.intrinsics[0]
  574. longest_param = None
  575. longest_arglist_fn = db.intrinsics[0]
  576. for i in sorted(db.intrinsics, key=lambda x: x.key):
  577. # Get some values for maximum lengths.
  578. if len(i.name) > len(longest_fn.name):
  579. longest_fn = i
  580. for p_idx, p in enumerate(i.params):
  581. if p_idx > 0 and (longest_param is None or len(p.name) > len(longest_param.name)):
  582. longest_param = p
  583. if len(i.params) > len(longest_arglist_fn.params):
  584. longest_arglist_fn = i
  585. result = ""
  586. for k in sorted(db.namespaces.keys()):
  587. v = db.namespaces[k]
  588. result += "static const UINT g_u%sCount = %d;\n" % (k, len(v.intrinsics))
  589. result += "\n"
  590. result += "static const int g_MaxIntrinsicName = %d; // Count of characters for longest intrinsic name - '%s'\n" % (len(longest_fn.name), longest_fn.name)
  591. result += "static const int g_MaxIntrinsicParamName = %d; // Count of characters for longest intrinsic parameter name - '%s'\n" % (len(longest_param.name), longest_param.name)
  592. result += "static const int g_MaxIntrinsicParamCount = %d; // Count of parameters (without return) for longest intrinsic argument list - '%s'\n" % (len(longest_arglist_fn.params) - 1, longest_arglist_fn.name)
  593. return result
  594. def get_hlsl_intrinsics():
  595. db = get_db_hlsl()
  596. result = ""
  597. last_ns = ""
  598. ns_table = ""
  599. is_vk_table = False # SPIRV Change
  600. id_prefix = ""
  601. arg_idx = 0
  602. opcode_namespace = db.opcode_namespace
  603. for i in sorted(db.intrinsics, key=lambda x: x.key):
  604. if last_ns != i.ns:
  605. last_ns = i.ns
  606. id_prefix = "IOP" if last_ns == "Intrinsics" else "MOP"
  607. if (len(ns_table)):
  608. result += ns_table + "};\n"
  609. # SPIRV Change Starts
  610. if is_vk_table:
  611. result += "\n#endif // ENABLE_SPIRV_CODEGEN\n"
  612. is_vk_table = False
  613. # SPIRV Change Ends
  614. result += "\n//\n// Start of %s\n//\n\n" % (last_ns)
  615. # This used to be qualified as __declspec(selectany), but that's no longer necessary.
  616. ns_table = "static const HLSL_INTRINSIC g_%s[] =\n{\n" % (last_ns)
  617. # SPIRV Change Starts
  618. if (i.vulkanSpecific):
  619. is_vk_table = True
  620. result += "#ifdef ENABLE_SPIRV_CODEGEN\n\n"
  621. # SPIRV Change Ends
  622. arg_idx = 0
  623. ns_table += " {(UINT)%s::%s_%s, %s, %s, %d, %d, g_%s_Args%s},\n" % (opcode_namespace, id_prefix, i.name, str(i.readonly).lower(), str(i.readnone).lower(), i.overload_param_index,len(i.params), last_ns, arg_idx)
  624. result += "static const HLSL_INTRINSIC_ARGUMENT g_%s_Args%s[] =\n{\n" % (last_ns, arg_idx)
  625. for p in i.params:
  626. result += " {\"%s\", %s, %s, %s, %s, %s, %s, %s},\n" % (
  627. p.name, p.param_qual, p.template_id, p.template_list,
  628. p.component_id, p.component_list, p.rows, p.cols)
  629. result += "};\n\n"
  630. arg_idx += 1
  631. result += ns_table + "};\n"
  632. result += "\n#endif // ENABLE_SPIRV_CODEGEN\n" if is_vk_table else "" # SPIRV Change
  633. return result
  634. # SPIRV Change Starts
  635. def wrap_with_ifdef_if_vulkan_specific(intrinsic, text):
  636. if intrinsic.vulkanSpecific:
  637. return "#ifdef ENABLE_SPIRV_CODEGEN\n" + text + "#endif // ENABLE_SPIRV_CODEGEN\n"
  638. return text
  639. # SPIRV Change Ends
  640. def enum_hlsl_intrinsics():
  641. db = get_db_hlsl()
  642. result = ""
  643. enumed = []
  644. for i in sorted(db.intrinsics, key=lambda x: x.key):
  645. if (i.enum_name not in enumed):
  646. enumerant = " %s,\n" % (i.enum_name)
  647. result += wrap_with_ifdef_if_vulkan_specific(i, enumerant) # SPIRV Change
  648. enumed.append(i.enum_name)
  649. # unsigned
  650. result += " // unsigned\n"
  651. for i in sorted(db.intrinsics, key=lambda x: x.key):
  652. if (i.unsigned_op != ""):
  653. if (i.unsigned_op not in enumed):
  654. result += " %s,\n" % (i.unsigned_op)
  655. enumed.append(i.unsigned_op)
  656. result += " Num_Intrinsics,\n"
  657. return result
  658. def has_unsigned_hlsl_intrinsics():
  659. db = get_db_hlsl()
  660. result = ""
  661. enumed = []
  662. # unsigned
  663. for i in sorted(db.intrinsics, key=lambda x: x.key):
  664. if (i.unsigned_op != ""):
  665. if (i.enum_name not in enumed):
  666. result += " case IntrinsicOp::%s:\n" % (i.enum_name)
  667. enumed.append(i.enum_name)
  668. return result
  669. def get_unsigned_hlsl_intrinsics():
  670. db = get_db_hlsl()
  671. result = ""
  672. enumed = []
  673. # unsigned
  674. for i in sorted(db.intrinsics, key=lambda x: x.key):
  675. if (i.unsigned_op != ""):
  676. if (i.enum_name not in enumed):
  677. enumed.append(i.enum_name)
  678. result += " case IntrinsicOp::%s:\n" % (i.enum_name)
  679. result += " return static_cast<unsigned>(IntrinsicOp::%s);\n" % (i.unsigned_op)
  680. return result
  681. def get_oloads_props():
  682. db = get_db_dxil()
  683. gen = db_oload_gen(db)
  684. return run_with_stdout(lambda: gen.print_opfunc_props())
  685. def get_oloads_funcs():
  686. db = get_db_dxil()
  687. gen = db_oload_gen(db)
  688. return run_with_stdout(lambda: gen.print_opfunc_table())
  689. def get_funcs_oload_type():
  690. db = get_db_dxil()
  691. gen = db_oload_gen(db)
  692. return run_with_stdout(lambda: gen.print_opfunc_oload_type())
  693. def get_enum_decl(name, **kwargs):
  694. db = get_db_dxil()
  695. gen = db_enumhelp_gen(db)
  696. return run_with_stdout(lambda: gen.print_enum(db.enum_idx[name], **kwargs))
  697. def get_valrule_enum():
  698. return get_enum_decl("ValidationRule", hide_val=True)
  699. def get_valrule_text():
  700. db = get_db_dxil()
  701. result = "switch(value) {\n"
  702. for v in db.enum_idx["ValidationRule"].values:
  703. result += " case hlsl::ValidationRule::" + v.name + ": return \"" + v.err_msg + "\";\n"
  704. result += "}\n"
  705. return result
  706. def get_instrhelper():
  707. db = get_db_dxil()
  708. gen = db_instrhelp_gen(db)
  709. return run_with_stdout(lambda: gen.print_body())
  710. def get_instrs_pred(varname, pred, attr_name="dxil_opid"):
  711. db = get_db_dxil()
  712. if type(pred) == str:
  713. pred_fn = lambda i: getattr(i, pred)
  714. else:
  715. pred_fn = pred
  716. llvm_instrs = [i for i in db.instr if pred_fn(i)]
  717. result = format_comment("// ", "Instructions: %s" % ", ".join([i.name + "=" + str(getattr(i, attr_name)) for i in llvm_instrs]))
  718. result += "return %s;" % build_range_code(varname, [getattr(i, attr_name) for i in llvm_instrs])
  719. result += "\n"
  720. return result
  721. def get_instrs_rst():
  722. "Create an rst table of allowed LLVM instructions."
  723. db = get_db_dxil()
  724. instrs = [i for i in db.instr if i.is_allowed and not i.is_dxil_op]
  725. instrs = sorted(instrs, key=lambda v : v.llvm_id)
  726. rows = []
  727. rows.append(["Instruction", "Action", "Operand overloads"])
  728. for i in instrs:
  729. rows.append([i.name, i.doc, i.oload_types])
  730. result = "\n\n" + format_rst_table(rows) + "\n\n"
  731. # Add detailed instruction information where available.
  732. for i in instrs:
  733. if i.remarks:
  734. result += i.name + "\n" + ("~" * len(i.name)) + "\n\n" + i.remarks + "\n\n"
  735. return result + "\n"
  736. def get_init_passes():
  737. "Create a series of statements to initialize passes in a registry."
  738. db = get_db_dxil()
  739. result = ""
  740. for p in sorted(db.passes, key=lambda p : p.type_name):
  741. result += "initialize%sPass(Registry);\n" % p.type_name
  742. return result
  743. def get_pass_arg_names():
  744. "Return an ArrayRef of argument names based on passName"
  745. db = get_db_dxil()
  746. decl_result = ""
  747. check_result = ""
  748. for p in sorted(db.passes, key=lambda p : p.type_name):
  749. if len(p.args):
  750. decl_result += "static const LPCSTR %sArgs[] = { " % p.type_name
  751. check_result += "if (strcmp(passName, \"%s\") == 0) return ArrayRef<LPCSTR>(%sArgs, _countof(%sArgs));\n" % (p.name, p.type_name, p.type_name)
  752. sep = ""
  753. for a in p.args:
  754. decl_result += sep + "\"%s\"" % a.name
  755. sep = ", "
  756. decl_result += " };\n"
  757. return decl_result + check_result
  758. def get_pass_arg_descs():
  759. "Return an ArrayRef of argument descriptions based on passName"
  760. db = get_db_dxil()
  761. decl_result = ""
  762. check_result = ""
  763. for p in sorted(db.passes, key=lambda p : p.type_name):
  764. if len(p.args):
  765. decl_result += "static const LPCSTR %sArgs[] = { " % p.type_name
  766. check_result += "if (strcmp(passName, \"%s\") == 0) return ArrayRef<LPCSTR>(%sArgs, _countof(%sArgs));\n" % (p.name, p.type_name, p.type_name)
  767. sep = ""
  768. for a in p.args:
  769. decl_result += sep + "\"%s\"" % a.doc
  770. sep = ", "
  771. decl_result += " };\n"
  772. return decl_result + check_result
  773. def get_is_pass_option_name():
  774. "Create a return expression to check whether a value 'S' is a pass option name."
  775. db = get_db_dxil()
  776. prefix = ""
  777. result = "return "
  778. for k in sorted(db.pass_idx_args):
  779. result += prefix + "S.equals(\"%s\")" % k
  780. prefix = "\n || "
  781. return result + ";"
  782. def get_opcodes_rst():
  783. "Create an rst table of opcodes"
  784. db = get_db_dxil()
  785. instrs = [i for i in db.instr if i.is_allowed and i.is_dxil_op]
  786. instrs = sorted(instrs, key=lambda v : v.dxil_opid)
  787. rows = []
  788. rows.append(["ID", "Name", "Description"])
  789. for i in instrs:
  790. op_name = i.dxil_op
  791. if i.remarks:
  792. op_name = op_name + "_" # append _ to enable internal hyperlink on rst files
  793. rows.append([i.dxil_opid, op_name, i.doc])
  794. result = "\n\n" + format_rst_table(rows) + "\n\n"
  795. # Add detailed instruction information where available.
  796. instrs = sorted(instrs, key=lambda v : v.name)
  797. for i in instrs:
  798. if i.remarks:
  799. result += i.name + "\n" + ("~" * len(i.name)) + "\n\n" + i.remarks + "\n\n"
  800. return result + "\n"
  801. def get_valrules_rst():
  802. "Create an rst table of validation rules instructions."
  803. db = get_db_dxil()
  804. rules = [i for i in db.val_rules if not i.is_disabled]
  805. rules = sorted(rules, key=lambda v : v.name)
  806. rows = []
  807. rows.append(["Rule Code", "Description"])
  808. for i in rules:
  809. rows.append([i.name, i.doc])
  810. return "\n\n" + format_rst_table(rows) + "\n\n"
  811. def get_opsigs():
  812. # Create a list of DXIL operation signatures, sorted by ID.
  813. db = get_db_dxil()
  814. instrs = [i for i in db.instr if i.is_dxil_op]
  815. instrs = sorted(instrs, key=lambda v : v.dxil_opid)
  816. # db_dxil already asserts that the numbering is dense.
  817. # Create the code to write out.
  818. code = "static const char *OpCodeSignatures[] = {\n"
  819. for inst_idx,i in enumerate(instrs):
  820. code += " \"("
  821. for operand in i.ops:
  822. if operand.pos > 1: # skip 0 (the return value) and 1 (the opcode itself)
  823. code += operand.name
  824. if operand.pos < len(i.ops) - 1:
  825. code += ","
  826. code += ")\""
  827. if inst_idx < len(instrs) - 1:
  828. code += ","
  829. code += " // " + i.name
  830. code += "\n"
  831. code += "};\n"
  832. return code
  833. shader_stage_to_ShaderKind = {
  834. 'vertex': 'Vertex',
  835. 'pixel': 'Pixel',
  836. 'geometry': 'Geometry',
  837. 'compute': 'Compute',
  838. 'hull': 'Hull',
  839. 'domain': 'Domain',
  840. 'library': 'Library',
  841. 'raygeneration': 'RayGeneration',
  842. 'intersection': 'Intersection',
  843. 'anyhit': 'AnyHit',
  844. 'closesthit': 'ClosestHit',
  845. 'miss': 'Miss',
  846. 'callable': 'Callable',
  847. }
  848. def get_min_sm_and_mask_text():
  849. db = get_db_dxil()
  850. instrs = [i for i in db.instr if i.is_dxil_op]
  851. instrs = sorted(instrs, key=lambda v : (v.shader_model, v.shader_model_translated, v.shader_stages, v.dxil_opid))
  852. last_model = None
  853. last_model_translated = None
  854. last_stage = None
  855. grouped_instrs = []
  856. code = ""
  857. def flush_instrs(grouped_instrs, last_model, last_model_translated, last_stage):
  858. if len(grouped_instrs) == 0:
  859. return ""
  860. result = format_comment("// ", "Instructions: %s" % ", ".join([i.name + "=" + str(i.dxil_opid) for i in grouped_instrs]))
  861. result += "if (" + build_range_code("op", [i.dxil_opid for i in grouped_instrs]) + ") {\n"
  862. default = True
  863. if last_model != (6,0):
  864. default = False
  865. if last_model_translated:
  866. result += " if (bWithTranslation) {\n"
  867. result += " major = %d; minor = %d;\n } else {\n " % last_model_translated
  868. result += " major = %d; minor = %d;\n" % last_model
  869. if last_model_translated:
  870. result += " }\n"
  871. if last_stage:
  872. default = False
  873. result += " mask = %s;\n" % ' | '.join([ 'SFLAG(%s)' % shader_stage_to_ShaderKind[c]
  874. for c in last_stage
  875. ])
  876. if default:
  877. # don't write these out, instead fall through
  878. return ""
  879. return result + " return;\n}\n"
  880. for i in instrs:
  881. if ((i.shader_model, i.shader_model_translated, i.shader_stages) !=
  882. (last_model, last_model_translated, last_stage)):
  883. code += flush_instrs(grouped_instrs, last_model, last_model_translated, last_stage)
  884. grouped_instrs = []
  885. last_model = i.shader_model
  886. last_model_translated = i.shader_model_translated
  887. last_stage = i.shader_stages
  888. grouped_instrs.append(i)
  889. code += flush_instrs(grouped_instrs, last_model, last_model_translated, last_stage)
  890. return code
  891. check_pSM_for_shader_stage = {
  892. 'vertex': 'SK == DXIL::ShaderKind::Vertex',
  893. 'pixel': 'SK == DXIL::ShaderKind::Pixel',
  894. 'geometry': 'SK == DXIL::ShaderKind::Geometry',
  895. 'compute': 'SK == DXIL::ShaderKind::Compute',
  896. 'hull': 'SK == DXIL::ShaderKind::Hull',
  897. 'domain': 'SK == DXIL::ShaderKind::Domain',
  898. 'library': 'SK == DXIL::ShaderKind::Library',
  899. 'raygeneration': 'SK == DXIL::ShaderKind::RayGeneration',
  900. 'intersection': 'SK == DXIL::ShaderKind::Intersection',
  901. 'anyhit': 'SK == DXIL::ShaderKind::AnyHit',
  902. 'closesthit': 'SK == DXIL::ShaderKind::ClosestHit',
  903. 'miss': 'SK == DXIL::ShaderKind::Miss',
  904. 'callable': 'SK == DXIL::ShaderKind::Callable',
  905. }
  906. def get_valopcode_sm_text():
  907. db = get_db_dxil()
  908. instrs = [i for i in db.instr if i.is_dxil_op]
  909. instrs = sorted(instrs, key=lambda v : (v.shader_model, v.shader_stages, v.dxil_opid))
  910. last_model = None
  911. last_stage = None
  912. grouped_instrs = []
  913. code = ""
  914. def flush_instrs(grouped_instrs, last_model, last_stage):
  915. if len(grouped_instrs) == 0:
  916. return ""
  917. result = format_comment("// ", "Instructions: %s" % ", ".join([i.name + "=" + str(i.dxil_opid) for i in grouped_instrs]))
  918. result += "if (" + build_range_code("op", [i.dxil_opid for i in grouped_instrs]) + ")\n"
  919. result += " return "
  920. model_cond = stage_cond = None
  921. if last_model != (6,0):
  922. model_cond = "major > %d || (major == %d && minor >= %d)" % (
  923. last_model[0], last_model[0], last_model[1])
  924. if last_stage:
  925. stage_cond = ' || '.join([check_pSM_for_shader_stage[c] for c in last_stage])
  926. if model_cond or stage_cond:
  927. result += '\n && '.join(
  928. ["(%s)" % expr for expr in (model_cond, stage_cond) if expr] )
  929. return result + ";\n"
  930. else:
  931. # don't write these out, instead fall through
  932. return ""
  933. for i in instrs:
  934. if (i.shader_model, i.shader_stages) != (last_model, last_stage):
  935. code += flush_instrs(grouped_instrs, last_model, last_stage)
  936. grouped_instrs = []
  937. last_model = i.shader_model
  938. last_stage = i.shader_stages
  939. grouped_instrs.append(i)
  940. code += flush_instrs(grouped_instrs, last_model, last_stage)
  941. code += "return true;\n"
  942. return code
  943. def get_sigpoint_table():
  944. db = get_db_dxil()
  945. gen = db_sigpoint_gen(db)
  946. return run_with_stdout(lambda: gen.print_sigpoint_table())
  947. def get_sigpoint_rst():
  948. "Create an rst table for SigPointKind."
  949. db = get_db_dxil()
  950. rows = [row[:] for row in db.sigpoint_table[:-1]] # Copy table
  951. e = dict([(v.name, v) for v in db.enum_idx['SigPointKind'].values])
  952. rows[0] = ['ID'] + rows[0] + ['Description']
  953. for i in range(1, len(rows)):
  954. row = rows[i]
  955. v = e[row[0]]
  956. rows[i] = [v.value] + row + [v.doc]
  957. return "\n\n" + format_rst_table(rows) + "\n\n"
  958. def get_sem_interpretation_enum_rst():
  959. db = get_db_dxil()
  960. rows = ([['ID', 'Name', 'Description']] +
  961. [[v.value, v.name, v.doc]
  962. for v in db.enum_idx['SemanticInterpretationKind'].values[:-1]])
  963. return "\n\n" + format_rst_table(rows) + "\n\n"
  964. def get_sem_interpretation_table_rst():
  965. db = get_db_dxil()
  966. return "\n\n" + format_rst_table(db.interpretation_table) + "\n\n"
  967. def get_interpretation_table():
  968. db = get_db_dxil()
  969. gen = db_sigpoint_gen(db)
  970. return run_with_stdout(lambda: gen.print_interpretation_table())
  971. def RunCodeTagUpdate(file_path):
  972. import os
  973. import CodeTags
  974. print(" ... updating " + file_path)
  975. args = [file_path, file_path + ".tmp"]
  976. result = CodeTags.main(args)
  977. if result != 0:
  978. print(" ... error: %d" % result)
  979. else:
  980. with open(file_path, 'rt') as f:
  981. before = f.read()
  982. with open(file_path + ".tmp", 'rt') as f:
  983. after = f.read()
  984. if before == after:
  985. print(" --- no changes found")
  986. else:
  987. print(" +++ changes found, updating file")
  988. with open(file_path, 'wt') as f:
  989. f.write(after)
  990. os.remove(file_path + ".tmp")
  991. if __name__ == "__main__":
  992. parser = argparse.ArgumentParser(description="Generate code to handle instructions.")
  993. parser.add_argument("-gen", choices=["docs-ref", "docs-spec", "inst-header", "enums", "oloads", "valfns"], help="Output type to generate.")
  994. parser.add_argument("-update-files", action="store_const", const=True)
  995. args = parser.parse_args()
  996. db = get_db_dxil() # used by all generators, also handy to have it run validation
  997. if args.gen == "docs-ref":
  998. gen = db_docsref_gen(db)
  999. gen.print_content()
  1000. if args.gen == "docs-spec":
  1001. import os, docutils.core
  1002. assert "HLSL_SRC_DIR" in os.environ, "Environment variable HLSL_SRC_DIR is not defined"
  1003. hlsl_src_dir = os.environ["HLSL_SRC_DIR"]
  1004. spec_file = os.path.abspath(os.path.join(hlsl_src_dir, "docs/DXIL.rst"))
  1005. with open(spec_file) as f:
  1006. s = docutils.core.publish_file(f, writer_name="html")
  1007. if args.gen == "inst-header":
  1008. gen = db_instrhelp_gen(db)
  1009. gen.print_content()
  1010. if args.gen == "enums":
  1011. gen = db_enumhelp_gen(db)
  1012. gen.print_content()
  1013. if args.gen == "oloads":
  1014. gen = db_oload_gen(db)
  1015. gen.print_content()
  1016. if args.gen == "valfns":
  1017. gen = db_valfns_gen(db)
  1018. gen.print_content()
  1019. if args.update_files:
  1020. print("Updating files ...")
  1021. import CodeTags
  1022. import os
  1023. assert "HLSL_SRC_DIR" in os.environ, "Environment variable HLSL_SRC_DIR is not defined"
  1024. hlsl_src_dir = os.environ["HLSL_SRC_DIR"]
  1025. pj = lambda *parts: os.path.abspath(os.path.join(*parts))
  1026. files = [
  1027. 'docs/DXIL.rst',
  1028. 'lib/HLSL/DXILOperations.cpp',
  1029. 'include/dxc/HLSL/DXILConstants.h',
  1030. 'include/dxc/HLSL/DxilValidation.h',
  1031. 'include/dxc/HLSL/DxilInstructions.h',
  1032. 'lib/HLSL/DxcOptimizer.cpp',
  1033. 'lib/HLSL/DxilValidation.cpp',
  1034. 'tools/clang/lib/Sema/gen_intrin_main_tables_15.h',
  1035. 'include/dxc/HlslIntrinsicOp.h',
  1036. 'tools/clang/tools/dxcompiler/dxcdisassembler.cpp',
  1037. 'include/dxc/HLSL/DxilSigPoint.inl',
  1038. ]
  1039. for relative_file_path in files:
  1040. RunCodeTagUpdate(pj(hlsl_src_dir, relative_file_path))