hctdb_instrhelp.py 55 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428
  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", "wv" : "None" }
  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. "twof16": "A(p2F16);",
  371. "twoi16": "A(p2I16);",
  372. "threei32": "A(p3I32);",
  373. "threef32": "A(p3F32);",
  374. "fouri32": "A(p4I32);",
  375. "fourf32": "A(p4F32);",
  376. "u32": "A(pI32);",
  377. "u64": "A(pI64);",
  378. "u8": "A(pI8);",
  379. "v": "A(pV);",
  380. "w": "A(pWav);",
  381. "SamplePos": "A(pPos);",
  382. "udt": "A(udt);",
  383. "obj": "A(obj);",
  384. "resproperty": "A(resProperty);",
  385. }
  386. last_category = None
  387. for i in self.instrs:
  388. if last_category != i.category:
  389. if last_category != None:
  390. print("")
  391. print(" // %s" % i.category)
  392. last_category = i.category
  393. line = " case OpCode::{name:24}".format(name = i.name + ":")
  394. for index, o in enumerate(i.ops):
  395. assert o.llvm_type in op_type_texts, "llvm type %s in instruction %s is unknown" % (o.llvm_type, i.name)
  396. op_type_text = op_type_texts[o.llvm_type]
  397. if index == 0:
  398. line = line + "{val:13}".format(val=op_type_text)
  399. else:
  400. line = line + "{val:9}".format(val=op_type_text)
  401. line = line + "break;"
  402. print(line)
  403. def print_opfunc_oload_type(self):
  404. # Print the function for OP::GetOverloadType
  405. elt_ty = "$o"
  406. res_ret_ty = "$r"
  407. cb_ret_ty = "$cb"
  408. udt_ty = "udt"
  409. obj_ty = "obj"
  410. last_category = None
  411. index_dict = collections.OrderedDict()
  412. single_dict = collections.OrderedDict()
  413. struct_list = []
  414. for instr in self.instrs:
  415. ret_ty = instr.ops[0].llvm_type
  416. # Skip case return type is overload type
  417. if (ret_ty == elt_ty):
  418. continue
  419. if ret_ty == res_ret_ty:
  420. struct_list.append(instr.name)
  421. continue
  422. if ret_ty == cb_ret_ty:
  423. struct_list.append(instr.name)
  424. continue
  425. in_param_ty = False
  426. # Try to find elt_ty in parameter types.
  427. for index, op in enumerate(instr.ops):
  428. # Skip return type.
  429. if (op.pos == 0):
  430. continue
  431. # Skip dxil opcode.
  432. if (op.pos == 1):
  433. continue
  434. op_type = op.llvm_type
  435. if (op_type == elt_ty):
  436. # Skip return op
  437. index = index - 1
  438. if index not in index_dict:
  439. index_dict[index] = [instr.name]
  440. else:
  441. index_dict[index].append(instr.name)
  442. in_param_ty = True
  443. break
  444. if (op_type == udt_ty or op_type == obj_ty):
  445. # Skip return op
  446. index = index - 1
  447. if index not in index_dict:
  448. index_dict[index] = [instr.name]
  449. else:
  450. index_dict[index].append(instr.name)
  451. in_param_ty = True
  452. if in_param_ty:
  453. continue
  454. # No overload, just return the single oload_type.
  455. assert len(instr.oload_types)==1, "overload no elt_ty %s" % (instr.name)
  456. ty = instr.oload_types[0]
  457. type_code_texts = {
  458. "d": "Type::getDoubleTy(m_Ctx)",
  459. "f": "Type::getFloatTy(m_Ctx)",
  460. "h": "Type::getHalfTy",
  461. "1": "IntegerType::get(m_Ctx, 1)",
  462. "8": "IntegerType::get(m_Ctx, 8)",
  463. "w": "IntegerType::get(m_Ctx, 16)",
  464. "i": "IntegerType::get(m_Ctx, 32)",
  465. "l": "IntegerType::get(m_Ctx, 64)",
  466. "v": "Type::getVoidTy(m_Ctx)",
  467. "u": "Type::getInt32PtrTy(m_Ctx)",
  468. "o": "Type::getInt32PtrTy(m_Ctx)",
  469. }
  470. assert ty in type_code_texts, "llvm type %s is unknown" % (ty)
  471. ty_code = type_code_texts[ty]
  472. if ty_code not in single_dict:
  473. single_dict[ty_code] = [instr.name]
  474. else:
  475. single_dict[ty_code].append(instr.name)
  476. for index, opcodes in index_dict.items():
  477. line = ""
  478. for opcode in opcodes:
  479. line = line + "case OpCode::{name}".format(name = opcode + ":\n")
  480. line = line + " DXASSERT_NOMSG(FT->getNumParams() > " + str(index) + ");\n"
  481. line = line + " return FT->getParamType(" + str(index) + ");"
  482. print(line)
  483. for code, opcodes in single_dict.items():
  484. line = ""
  485. for opcode in opcodes:
  486. line = line + "case OpCode::{name}".format(name = opcode + ":\n")
  487. line = line + " return " + code + ";"
  488. print(line)
  489. line = ""
  490. for opcode in struct_list:
  491. line = line + "case OpCode::{name}".format(name = opcode + ":\n")
  492. line = line + "{\n"
  493. line = line + " StructType *ST = cast<StructType>(Ty);\n"
  494. line = line + " return ST->getElementType(0);\n"
  495. line = line + "}"
  496. print(line)
  497. class db_valfns_gen:
  498. "A generator of validation functions."
  499. def __init__(self, db):
  500. self.db = db
  501. def print_content(self):
  502. self.print_header()
  503. self.print_body()
  504. def print_header(self):
  505. print("///////////////////////////////////////////////////////////////////////////////")
  506. print("// Instruction validation functions. //")
  507. def bool_lit(self, val):
  508. return "true" if val else "false";
  509. def op_type(self, o):
  510. if o.llvm_type == "i8":
  511. return "int8_t"
  512. if o.llvm_type == "u8":
  513. return "uint8_t"
  514. raise ValueError("Don't know how to describe type %s for operand %s." % (o.llvm_type, o.name))
  515. def op_const_expr(self, o):
  516. if o.llvm_type == "i8" or o.llvm_type == "u8":
  517. return "(%s)(llvm::dyn_cast<llvm::ConstantInt>(Instr->getOperand(%d))->getZExtValue())" % (self.op_type(o), o.pos - 1)
  518. raise ValueError("Don't know how to describe type %s for operand %s." % (o.llvm_type, o.name))
  519. def print_body(self):
  520. llvm_instrs = [i for i in self.db.instr if i.is_allowed and not i.is_dxil_op]
  521. print("static bool IsLLVMInstructionAllowed(llvm::Instruction &I) {")
  522. self.print_comment(" // ", "Allow: %s" % ", ".join([i.name + "=" + str(i.llvm_id) for i in llvm_instrs]))
  523. print(" unsigned op = I.getOpcode();")
  524. print(" return %s;" % build_range_code("op", [i.llvm_id for i in llvm_instrs]))
  525. print("}")
  526. print("")
  527. def print_comment(self, prefix, val):
  528. print(format_comment(prefix, val))
  529. class macro_table_gen:
  530. "A generator for macro tables."
  531. def format_row(self, row, widths, sep=', '):
  532. frow = [str(item) + sep + (' ' * (width - len(item)))
  533. for item, width in list(zip(row, widths))[:-1]] + [str(row[-1])]
  534. return ''.join(frow)
  535. def format_table(self, table, *args, **kwargs):
  536. widths = [ functools.reduce(max, [ len(row[i])
  537. for row in table], 1)
  538. for i in range(len(table[0]))]
  539. formatted = []
  540. for row in table:
  541. formatted.append(self.format_row(row, widths, *args, **kwargs))
  542. return formatted
  543. def print_table(self, table, macro_name):
  544. formatted = self.format_table(table)
  545. print( '// %s\n' % formatted[0] +
  546. '#define %s(ROW) \\\n' % macro_name +
  547. ' \\\n'.join([' ROW(%s)' % frow for frow in formatted[1:]]))
  548. class db_sigpoint_gen(macro_table_gen):
  549. "A generator for SigPoint tables."
  550. def __init__(self, db):
  551. self.db = db
  552. def print_sigpoint_table(self):
  553. self.print_table(self.db.sigpoint_table, 'DO_SIGPOINTS')
  554. def print_interpretation_table(self):
  555. self.print_table(self.db.interpretation_table, 'DO_INTERPRETATION_TABLE')
  556. def print_content(self):
  557. self.print_sigpoint_table()
  558. self.print_interpretation_table()
  559. class string_output:
  560. def __init__(self):
  561. self.val = ""
  562. def write(self, text):
  563. self.val = self.val + str(text)
  564. def __str__(self):
  565. return self.val
  566. def run_with_stdout(fn):
  567. import sys
  568. _stdout_saved = sys.stdout
  569. so = string_output()
  570. try:
  571. sys.stdout = so
  572. fn()
  573. finally:
  574. sys.stdout = _stdout_saved
  575. return str(so)
  576. def get_hlsl_intrinsic_stats():
  577. db = get_db_hlsl()
  578. longest_fn = db.intrinsics[0]
  579. longest_param = None
  580. longest_arglist_fn = db.intrinsics[0]
  581. for i in sorted(db.intrinsics, key=lambda x: x.key):
  582. # Get some values for maximum lengths.
  583. if len(i.name) > len(longest_fn.name):
  584. longest_fn = i
  585. for p_idx, p in enumerate(i.params):
  586. if p_idx > 0 and (longest_param is None or len(p.name) > len(longest_param.name)):
  587. longest_param = p
  588. if len(i.params) > len(longest_arglist_fn.params):
  589. longest_arglist_fn = i
  590. result = ""
  591. for k in sorted(db.namespaces.keys()):
  592. v = db.namespaces[k]
  593. result += "static const UINT g_u%sCount = %d;\n" % (k, len(v.intrinsics))
  594. result += "\n"
  595. result += "static const int g_MaxIntrinsicName = %d; // Count of characters for longest intrinsic name - '%s'\n" % (len(longest_fn.name), longest_fn.name)
  596. result += "static const int g_MaxIntrinsicParamName = %d; // Count of characters for longest intrinsic parameter name - '%s'\n" % (len(longest_param.name), longest_param.name)
  597. 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)
  598. return result
  599. def get_hlsl_intrinsics():
  600. db = get_db_hlsl()
  601. result = ""
  602. last_ns = ""
  603. ns_table = ""
  604. is_vk_table = False # SPIRV Change
  605. id_prefix = ""
  606. arg_idx = 0
  607. opcode_namespace = db.opcode_namespace
  608. for i in sorted(db.intrinsics, key=lambda x: x.key):
  609. if last_ns != i.ns:
  610. last_ns = i.ns
  611. id_prefix = "IOP" if last_ns == "Intrinsics" else "MOP"
  612. if (len(ns_table)):
  613. result += ns_table + "};\n"
  614. # SPIRV Change Starts
  615. if is_vk_table:
  616. result += "\n#endif // ENABLE_SPIRV_CODEGEN\n"
  617. is_vk_table = False
  618. # SPIRV Change Ends
  619. result += "\n//\n// Start of %s\n//\n\n" % (last_ns)
  620. # This used to be qualified as __declspec(selectany), but that's no longer necessary.
  621. ns_table = "static const HLSL_INTRINSIC g_%s[] =\n{\n" % (last_ns)
  622. # SPIRV Change Starts
  623. if (i.vulkanSpecific):
  624. is_vk_table = True
  625. result += "#ifdef ENABLE_SPIRV_CODEGEN\n\n"
  626. # SPIRV Change Ends
  627. arg_idx = 0
  628. ns_table += " {(UINT)%s::%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(), str(i.wave).lower(), i.overload_param_index,len(i.params), last_ns, arg_idx)
  629. result += "static const HLSL_INTRINSIC_ARGUMENT g_%s_Args%s[] =\n{\n" % (last_ns, arg_idx)
  630. for p in i.params:
  631. name = p.name
  632. if name == i.name and i.hidden:
  633. # First parameter defines intrinsic name for parsing in HLSL.
  634. # Prepend '$hidden$' for hidden intrinsic so it can't be used in HLSL.
  635. name = "$hidden$" + name
  636. result += " {\"%s\", %s, %s, %s, %s, %s, %s, %s},\n" % (
  637. name, p.param_qual, p.template_id, p.template_list,
  638. p.component_id, p.component_list, p.rows, p.cols)
  639. result += "};\n\n"
  640. arg_idx += 1
  641. result += ns_table + "};\n"
  642. result += "\n#endif // ENABLE_SPIRV_CODEGEN\n" if is_vk_table else "" # SPIRV Change
  643. return result
  644. # SPIRV Change Starts
  645. def wrap_with_ifdef_if_vulkan_specific(intrinsic, text):
  646. if intrinsic.vulkanSpecific:
  647. return "#ifdef ENABLE_SPIRV_CODEGEN\n" + text + "#endif // ENABLE_SPIRV_CODEGEN\n"
  648. return text
  649. # SPIRV Change Ends
  650. def enum_hlsl_intrinsics():
  651. db = get_db_hlsl()
  652. result = ""
  653. enumed = []
  654. for i in sorted(db.intrinsics, key=lambda x: x.key):
  655. if (i.enum_name not in enumed):
  656. enumerant = " %s,\n" % (i.enum_name)
  657. result += wrap_with_ifdef_if_vulkan_specific(i, enumerant) # SPIRV Change
  658. enumed.append(i.enum_name)
  659. # unsigned
  660. result += " // unsigned\n"
  661. for i in sorted(db.intrinsics, key=lambda x: x.key):
  662. if (i.unsigned_op != ""):
  663. if (i.unsigned_op not in enumed):
  664. result += " %s,\n" % (i.unsigned_op)
  665. enumed.append(i.unsigned_op)
  666. result += " Num_Intrinsics,\n"
  667. return result
  668. def has_unsigned_hlsl_intrinsics():
  669. db = get_db_hlsl()
  670. result = ""
  671. enumed = []
  672. # unsigned
  673. for i in sorted(db.intrinsics, key=lambda x: x.key):
  674. if (i.unsigned_op != ""):
  675. if (i.enum_name not in enumed):
  676. result += " case IntrinsicOp::%s:\n" % (i.enum_name)
  677. enumed.append(i.enum_name)
  678. return result
  679. def get_unsigned_hlsl_intrinsics():
  680. db = get_db_hlsl()
  681. result = ""
  682. enumed = []
  683. # unsigned
  684. for i in sorted(db.intrinsics, key=lambda x: x.key):
  685. if (i.unsigned_op != ""):
  686. if (i.enum_name not in enumed):
  687. enumed.append(i.enum_name)
  688. result += " case IntrinsicOp::%s:\n" % (i.enum_name)
  689. result += " return static_cast<unsigned>(IntrinsicOp::%s);\n" % (i.unsigned_op)
  690. return result
  691. def get_oloads_props():
  692. db = get_db_dxil()
  693. gen = db_oload_gen(db)
  694. return run_with_stdout(lambda: gen.print_opfunc_props())
  695. def get_oloads_funcs():
  696. db = get_db_dxil()
  697. gen = db_oload_gen(db)
  698. return run_with_stdout(lambda: gen.print_opfunc_table())
  699. def get_funcs_oload_type():
  700. db = get_db_dxil()
  701. gen = db_oload_gen(db)
  702. return run_with_stdout(lambda: gen.print_opfunc_oload_type())
  703. def get_enum_decl(name, **kwargs):
  704. db = get_db_dxil()
  705. gen = db_enumhelp_gen(db)
  706. return run_with_stdout(lambda: gen.print_enum(db.enum_idx[name], **kwargs))
  707. def get_valrule_enum():
  708. return get_enum_decl("ValidationRule", hide_val=True)
  709. def get_valrule_text():
  710. db = get_db_dxil()
  711. result = "switch(value) {\n"
  712. for v in db.enum_idx["ValidationRule"].values:
  713. result += " case hlsl::ValidationRule::" + v.name + ": return \"" + v.err_msg + "\";\n"
  714. result += "}\n"
  715. return result
  716. def get_instrhelper():
  717. db = get_db_dxil()
  718. gen = db_instrhelp_gen(db)
  719. return run_with_stdout(lambda: gen.print_body())
  720. def get_instrs_pred(varname, pred, attr_name="dxil_opid"):
  721. db = get_db_dxil()
  722. if type(pred) == str:
  723. pred_fn = lambda i: getattr(i, pred)
  724. else:
  725. pred_fn = pred
  726. llvm_instrs = [i for i in db.instr if pred_fn(i)]
  727. result = format_comment("// ", "Instructions: %s" % ", ".join([i.name + "=" + str(getattr(i, attr_name)) for i in llvm_instrs]))
  728. result += "return %s;" % build_range_code(varname, [getattr(i, attr_name) for i in llvm_instrs])
  729. result += "\n"
  730. return result
  731. def get_instrs_rst():
  732. "Create an rst table of allowed LLVM instructions."
  733. db = get_db_dxil()
  734. instrs = [i for i in db.instr if i.is_allowed and not i.is_dxil_op]
  735. instrs = sorted(instrs, key=lambda v : v.llvm_id)
  736. rows = []
  737. rows.append(["Instruction", "Action", "Operand overloads"])
  738. for i in instrs:
  739. rows.append([i.name, i.doc, i.oload_types])
  740. result = "\n\n" + format_rst_table(rows) + "\n\n"
  741. # Add detailed instruction information where available.
  742. for i in instrs:
  743. if i.remarks:
  744. result += i.name + "\n" + ("~" * len(i.name)) + "\n\n" + i.remarks + "\n\n"
  745. return result + "\n"
  746. def get_init_passes(category_libs):
  747. "Create a series of statements to initialize passes in a registry."
  748. db = get_db_dxil()
  749. result = ""
  750. for p in sorted(db.passes, key=lambda p : p.type_name):
  751. # Skip if not in target category.
  752. if (p.category_lib not in category_libs):
  753. continue
  754. result += "initialize%sPass(Registry);\n" % p.type_name
  755. return result
  756. def get_pass_arg_names():
  757. "Return an ArrayRef of argument names based on passName"
  758. db = get_db_dxil()
  759. decl_result = ""
  760. check_result = ""
  761. for p in sorted(db.passes, key=lambda p : p.type_name):
  762. if len(p.args):
  763. decl_result += "static const LPCSTR %sArgs[] = { " % p.type_name
  764. check_result += "if (strcmp(passName, \"%s\") == 0) return ArrayRef<LPCSTR>(%sArgs, _countof(%sArgs));\n" % (p.name, p.type_name, p.type_name)
  765. sep = ""
  766. for a in p.args:
  767. decl_result += sep + "\"%s\"" % a.name
  768. sep = ", "
  769. decl_result += " };\n"
  770. return decl_result + check_result
  771. def get_pass_arg_descs():
  772. "Return an ArrayRef of argument descriptions based on passName"
  773. db = get_db_dxil()
  774. decl_result = ""
  775. check_result = ""
  776. for p in sorted(db.passes, key=lambda p : p.type_name):
  777. if len(p.args):
  778. decl_result += "static const LPCSTR %sArgs[] = { " % p.type_name
  779. check_result += "if (strcmp(passName, \"%s\") == 0) return ArrayRef<LPCSTR>(%sArgs, _countof(%sArgs));\n" % (p.name, p.type_name, p.type_name)
  780. sep = ""
  781. for a in p.args:
  782. decl_result += sep + "\"%s\"" % a.doc
  783. sep = ", "
  784. decl_result += " };\n"
  785. return decl_result + check_result
  786. def get_is_pass_option_name():
  787. "Create a return expression to check whether a value 'S' is a pass option name."
  788. db = get_db_dxil()
  789. prefix = ""
  790. result = "return "
  791. for k in sorted(db.pass_idx_args):
  792. result += prefix + "S.equals(\"%s\")" % k
  793. prefix = "\n || "
  794. return result + ";"
  795. def get_opcodes_rst():
  796. "Create an rst table of opcodes"
  797. db = get_db_dxil()
  798. instrs = [i for i in db.instr if i.is_allowed and i.is_dxil_op]
  799. instrs = sorted(instrs, key=lambda v : v.dxil_opid)
  800. rows = []
  801. rows.append(["ID", "Name", "Description"])
  802. for i in instrs:
  803. op_name = i.dxil_op
  804. if i.remarks:
  805. op_name = op_name + "_" # append _ to enable internal hyperlink on rst files
  806. rows.append([i.dxil_opid, op_name, i.doc])
  807. result = "\n\n" + format_rst_table(rows) + "\n\n"
  808. # Add detailed instruction information where available.
  809. instrs = sorted(instrs, key=lambda v : v.name)
  810. for i in instrs:
  811. if i.remarks:
  812. result += i.name + "\n" + ("~" * len(i.name)) + "\n\n" + i.remarks + "\n\n"
  813. return result + "\n"
  814. def get_valrules_rst():
  815. "Create an rst table of validation rules instructions."
  816. db = get_db_dxil()
  817. rules = [i for i in db.val_rules if not i.is_disabled]
  818. rules = sorted(rules, key=lambda v : v.name)
  819. rows = []
  820. rows.append(["Rule Code", "Description"])
  821. for i in rules:
  822. rows.append([i.name, i.doc])
  823. return "\n\n" + format_rst_table(rows) + "\n\n"
  824. def get_opsigs():
  825. # Create a list of DXIL operation signatures, sorted by ID.
  826. db = get_db_dxil()
  827. instrs = [i for i in db.instr if i.is_dxil_op]
  828. instrs = sorted(instrs, key=lambda v : v.dxil_opid)
  829. # db_dxil already asserts that the numbering is dense.
  830. # Create the code to write out.
  831. code = "static const char *OpCodeSignatures[] = {\n"
  832. for inst_idx,i in enumerate(instrs):
  833. code += " \"("
  834. for operand in i.ops:
  835. if operand.pos > 1: # skip 0 (the return value) and 1 (the opcode itself)
  836. code += operand.name
  837. if operand.pos < len(i.ops) - 1:
  838. code += ","
  839. code += ")\""
  840. if inst_idx < len(instrs) - 1:
  841. code += ","
  842. code += " // " + i.name
  843. code += "\n"
  844. code += "};\n"
  845. return code
  846. shader_stage_to_ShaderKind = {
  847. 'vertex': 'Vertex',
  848. 'pixel': 'Pixel',
  849. 'geometry': 'Geometry',
  850. 'compute': 'Compute',
  851. 'hull': 'Hull',
  852. 'domain': 'Domain',
  853. 'library': 'Library',
  854. 'raygeneration': 'RayGeneration',
  855. 'intersection': 'Intersection',
  856. 'anyhit': 'AnyHit',
  857. 'closesthit': 'ClosestHit',
  858. 'miss': 'Miss',
  859. 'callable': 'Callable',
  860. 'mesh' : 'Mesh',
  861. 'amplification' : 'Amplification',
  862. }
  863. def get_min_sm_and_mask_text():
  864. db = get_db_dxil()
  865. instrs = [i for i in db.instr if i.is_dxil_op]
  866. instrs = sorted(instrs, key=lambda v : (v.shader_model, v.shader_model_translated, v.shader_stages, v.dxil_opid))
  867. last_model = None
  868. last_model_translated = None
  869. last_stage = None
  870. grouped_instrs = []
  871. code = ""
  872. def flush_instrs(grouped_instrs, last_model, last_model_translated, last_stage):
  873. if len(grouped_instrs) == 0:
  874. return ""
  875. result = format_comment("// ", "Instructions: %s" % ", ".join([i.name + "=" + str(i.dxil_opid) for i in grouped_instrs]))
  876. result += "if (" + build_range_code("op", [i.dxil_opid for i in grouped_instrs]) + ") {\n"
  877. default = True
  878. if last_model != (6,0):
  879. default = False
  880. if last_model_translated:
  881. result += " if (bWithTranslation) {\n"
  882. result += " major = %d; minor = %d;\n } else {\n " % last_model_translated
  883. result += " major = %d; minor = %d;\n" % last_model
  884. if last_model_translated:
  885. result += " }\n"
  886. if last_stage:
  887. default = False
  888. result += " mask = %s;\n" % ' | '.join([ 'SFLAG(%s)' % shader_stage_to_ShaderKind[c]
  889. for c in last_stage
  890. ])
  891. if default:
  892. # don't write these out, instead fall through
  893. return ""
  894. return result + " return;\n}\n"
  895. for i in instrs:
  896. if ((i.shader_model, i.shader_model_translated, i.shader_stages) !=
  897. (last_model, last_model_translated, last_stage)):
  898. code += flush_instrs(grouped_instrs, last_model, last_model_translated, last_stage)
  899. grouped_instrs = []
  900. last_model = i.shader_model
  901. last_model_translated = i.shader_model_translated
  902. last_stage = i.shader_stages
  903. grouped_instrs.append(i)
  904. code += flush_instrs(grouped_instrs, last_model, last_model_translated, last_stage)
  905. return code
  906. check_pSM_for_shader_stage = {
  907. 'vertex': 'SK == DXIL::ShaderKind::Vertex',
  908. 'pixel': 'SK == DXIL::ShaderKind::Pixel',
  909. 'geometry': 'SK == DXIL::ShaderKind::Geometry',
  910. 'compute': 'SK == DXIL::ShaderKind::Compute',
  911. 'hull': 'SK == DXIL::ShaderKind::Hull',
  912. 'domain': 'SK == DXIL::ShaderKind::Domain',
  913. 'library': 'SK == DXIL::ShaderKind::Library',
  914. 'raygeneration': 'SK == DXIL::ShaderKind::RayGeneration',
  915. 'intersection': 'SK == DXIL::ShaderKind::Intersection',
  916. 'anyhit': 'SK == DXIL::ShaderKind::AnyHit',
  917. 'closesthit': 'SK == DXIL::ShaderKind::ClosestHit',
  918. 'miss': 'SK == DXIL::ShaderKind::Miss',
  919. 'callable': 'SK == DXIL::ShaderKind::Callable',
  920. 'mesh': 'SK == DXIL::ShaderKind::Mesh',
  921. 'amplification': 'SK == DXIL::ShaderKind::Amplification',
  922. }
  923. def get_valopcode_sm_text():
  924. db = get_db_dxil()
  925. instrs = [i for i in db.instr if i.is_dxil_op]
  926. instrs = sorted(instrs, key=lambda v : (v.shader_model, v.shader_stages, v.dxil_opid))
  927. last_model = None
  928. last_stage = None
  929. grouped_instrs = []
  930. code = ""
  931. def flush_instrs(grouped_instrs, last_model, last_stage):
  932. if len(grouped_instrs) == 0:
  933. return ""
  934. result = format_comment("// ", "Instructions: %s" % ", ".join([i.name + "=" + str(i.dxil_opid) for i in grouped_instrs]))
  935. result += "if (" + build_range_code("op", [i.dxil_opid for i in grouped_instrs]) + ")\n"
  936. result += " return "
  937. model_cond = stage_cond = None
  938. if last_model != (6,0):
  939. model_cond = "major > %d || (major == %d && minor >= %d)" % (
  940. last_model[0], last_model[0], last_model[1])
  941. if last_stage:
  942. stage_cond = ' || '.join([check_pSM_for_shader_stage[c] for c in last_stage])
  943. if model_cond or stage_cond:
  944. result += '\n && '.join(
  945. ["(%s)" % expr for expr in (model_cond, stage_cond) if expr] )
  946. return result + ";\n"
  947. else:
  948. # don't write these out, instead fall through
  949. return ""
  950. for i in instrs:
  951. if (i.shader_model, i.shader_stages) != (last_model, last_stage):
  952. code += flush_instrs(grouped_instrs, last_model, last_stage)
  953. grouped_instrs = []
  954. last_model = i.shader_model
  955. last_stage = i.shader_stages
  956. grouped_instrs.append(i)
  957. code += flush_instrs(grouped_instrs, last_model, last_stage)
  958. code += "return true;\n"
  959. return code
  960. def get_sigpoint_table():
  961. db = get_db_dxil()
  962. gen = db_sigpoint_gen(db)
  963. return run_with_stdout(lambda: gen.print_sigpoint_table())
  964. def get_sigpoint_rst():
  965. "Create an rst table for SigPointKind."
  966. db = get_db_dxil()
  967. rows = [row[:] for row in db.sigpoint_table[:-1]] # Copy table
  968. e = dict([(v.name, v) for v in db.enum_idx['SigPointKind'].values])
  969. rows[0] = ['ID'] + rows[0] + ['Description']
  970. for i in range(1, len(rows)):
  971. row = rows[i]
  972. v = e[row[0]]
  973. rows[i] = [v.value] + row + [v.doc]
  974. return "\n\n" + format_rst_table(rows) + "\n\n"
  975. def get_sem_interpretation_enum_rst():
  976. db = get_db_dxil()
  977. rows = ([['ID', 'Name', 'Description']] +
  978. [[v.value, v.name, v.doc]
  979. for v in db.enum_idx['SemanticInterpretationKind'].values[:-1]])
  980. return "\n\n" + format_rst_table(rows) + "\n\n"
  981. def get_sem_interpretation_table_rst():
  982. db = get_db_dxil()
  983. return "\n\n" + format_rst_table(db.interpretation_table) + "\n\n"
  984. def get_interpretation_table():
  985. db = get_db_dxil()
  986. gen = db_sigpoint_gen(db)
  987. return run_with_stdout(lambda: gen.print_interpretation_table())
  988. highest_major = 6
  989. highest_minor = 6
  990. highest_shader_models = {4:1, 5:1, 6:highest_minor}
  991. def getShaderModels():
  992. shader_models = []
  993. for major, minor in highest_shader_models.items():
  994. for i in range(0, minor+1):
  995. shader_models.append(str(major) + "_" + str(i))
  996. return shader_models;
  997. def get_highest_shader_model():
  998. result = """static const unsigned kHighestMajor = %d;
  999. static const unsigned kHighestMinor = %d;"""%(highest_major, highest_minor)
  1000. return result
  1001. def get_dxil_version_minor():
  1002. return "const unsigned kDxilMinor = %d;"%highest_minor
  1003. def get_is_shader_model_plus():
  1004. result = ""
  1005. for i in range(0, highest_minor+1):
  1006. result += "bool IsSM%d%dPlus() const { return IsSMAtLeast(%d, %d); }\n"%(highest_major, i,highest_major, i)
  1007. return result
  1008. profile_to_kind = {"ps":"Kind::Pixel", "vs":"Kind::Vertex", "gs":"Kind::Geometry", "hs":"5_0", "ds":"5_0", "cs":"4_0", "lib":"6_1", "ms":"6_5", "as":"6_5"}
  1009. class shader_profile(object):
  1010. "The profile description for a DXIL instruction"
  1011. def __init__(self, kind, kind_name, enum_name, start_sm, input_size, output_size):
  1012. self.kind = kind # position in parameter list
  1013. self.kind_name = kind_name
  1014. self.enum_name = enum_name
  1015. self.start_sm = start_sm
  1016. self.input_size = input_size
  1017. self.output_size = output_size
  1018. # kind is from DXIL::ShaderKind.
  1019. shader_profiles = [ shader_profile(0, "ps", "Kind::Pixel", "4_0", 32, 8),
  1020. shader_profile(1, "vs", "Kind::Vertex", "4_0", 32, 32),
  1021. shader_profile(2, "gs", "Kind::Geometry", "4_0", 32, 32),
  1022. shader_profile(3, "hs", "Kind::Hull", "5_0", 32, 32),
  1023. shader_profile(4, "ds", "Kind::Domain", "5_0", 32, 32),
  1024. shader_profile(5, "cs", "Kind::Compute", "4_0", 0,0),
  1025. shader_profile(6, "lib", "Kind::Library", "6_1", 32,32),
  1026. shader_profile(13, "ms", "Kind::Mesh", "6_5", 0,0),
  1027. shader_profile(14, "as", "Kind::Amplification", "6_5", 0,0),
  1028. ]
  1029. def getShaderProfiles():
  1030. # order match DXIL::ShaderKind.
  1031. profiles = {"ps":"4_0", "vs":"4_0", "gs":"4_0", "hs":"5_0", "ds":"5_0", "cs":"4_0", "lib":"6_1", "ms":"6_5", "as":"6_5"}
  1032. return profiles;
  1033. def get_shader_models():
  1034. result = ""
  1035. for profile in shader_profiles:
  1036. min_sm = profile.start_sm
  1037. input_size = profile.input_size
  1038. output_size = profile.output_size
  1039. kind = profile.kind
  1040. kind_name = profile.kind_name
  1041. enum_name = profile.enum_name
  1042. for major, minor in highest_shader_models.items():
  1043. UAV_info = "true, true, UINT_MAX"
  1044. if major > 5:
  1045. pass
  1046. elif major == 4:
  1047. UAV_info = "false, false, 0"
  1048. if kind == "cs":
  1049. UAV_info = "true, false, 1"
  1050. elif major == 5:
  1051. UAV_info = "true, true, 64"
  1052. for i in range(0, minor+1):
  1053. sm = "%d_%d"%(major, i)
  1054. if (min_sm > sm):
  1055. continue
  1056. input_size = profile.input_size
  1057. output_size = profile.output_size
  1058. if major == 4:
  1059. if i == 0:
  1060. if kind_name == "gs":
  1061. input_size = 16
  1062. elif kind_name == "vs":
  1063. input_size = 16
  1064. output_size = 16
  1065. sm_name = "%s_%s"%(kind_name,sm)
  1066. result += "SM(%s, %d, %d, \"%s\", %d, %d, %s),\n" % (enum_name, major, i, sm_name, input_size, output_size, UAV_info)
  1067. if kind_name == "lib":
  1068. result += "// lib_6_x is for offline linking only, and relaxes restrictions\n"
  1069. result += "SM(Kind::Library, 6, kOfflineMinor, \"lib_6_x\", 32, 32, true, true, UINT_MAX),\n"
  1070. result += "// Values before Invalid must remain sorted by Kind, then Major, then Minor.\n"
  1071. result += "SM(Kind::Invalid, 0, 0, \"invalid\", 0, 0, false, false, 0),\n"
  1072. return result
  1073. def get_num_shader_models():
  1074. count = 0
  1075. for profile in shader_profiles:
  1076. min_sm = profile.start_sm
  1077. input_size = profile.input_size
  1078. output_size = profile.output_size
  1079. kind = profile.kind
  1080. kind_name = profile.kind_name
  1081. enum_name = profile.enum_name
  1082. for major, minor in highest_shader_models.items():
  1083. for i in range(0, minor+1):
  1084. sm = "%d_%d"%(major, i)
  1085. if (min_sm > sm):
  1086. continue
  1087. count += 1
  1088. if kind_name == "lib":
  1089. # for lib_6_x
  1090. count += 1
  1091. # for invalid shader_model.
  1092. count += 1
  1093. return "static const unsigned kNumShaderModels = %d;"%count
  1094. def build_shader_model_hash_idx_map():
  1095. #must match get_shader_models.
  1096. result = "const static std::unordered_map<unsigned, unsigned> hashToIdxMap = {\n"
  1097. count = 0
  1098. for profile in shader_profiles:
  1099. min_sm = profile.start_sm
  1100. kind = profile.kind
  1101. kind_name = profile.kind_name
  1102. for major, minor in highest_shader_models.items():
  1103. for i in range(0, minor+1):
  1104. sm = "%d_%d"%(major, i)
  1105. if (min_sm > sm):
  1106. continue
  1107. sm_name = "%s_%s"%(kind_name,sm)
  1108. hash_v = kind << 16 | major << 8 | i;
  1109. result += "{%d,%d}, //%s\n" % (hash_v, count, sm_name)
  1110. count += 1
  1111. if kind_name == "lib":
  1112. result += "// lib_6_x is for offline linking only, and relaxes restrictions\n"
  1113. major = 6
  1114. #static const unsigned kOfflineMinor = 0xF;
  1115. i = 15
  1116. hash_v = kind << 16 | major << 8 | i;
  1117. result += "{%d,%d},//%s\n" % (hash_v, count, "lib_6_x")
  1118. count += 1
  1119. result += "};\n"
  1120. return result
  1121. def get_validation_version():
  1122. result = """// 1.0 is the first validator.
  1123. // 1.1 adds:
  1124. // - ILDN container part support
  1125. // 1.2 adds:
  1126. // - Metadata for floating point denorm mode
  1127. // 1.3 adds:
  1128. // - Library support
  1129. // - Raytracing support
  1130. // - i64/f64 overloads for rawBufferLoad/Store
  1131. // 1.4 adds:
  1132. // - packed u8x4/i8x4 dot with accumulate to i32
  1133. // - half dot2 with accumulate to float
  1134. // 1.5 adds:
  1135. // - WaveMatch, WaveMultiPrefixOp, WaveMultiPrefixBitCount
  1136. // - HASH container part support
  1137. // - Mesh and Amplification shaders
  1138. // - DXR 1.1 & RayQuery support
  1139. *pMajor = 1;
  1140. *pMinor = %d;
  1141. """ % highest_minor
  1142. return result
  1143. def get_target_profiles():
  1144. result = "HelpText<\"Set target profile. \\n"
  1145. result += "\\t<profile>: "
  1146. profiles = getShaderProfiles()
  1147. shader_models = getShaderModels()
  1148. base_sm = "%d_0"%highest_major
  1149. for profile, min_sm in profiles.items():
  1150. for shader_model in shader_models:
  1151. if (base_sm > shader_model):
  1152. continue
  1153. if (min_sm > shader_model):
  1154. continue
  1155. result += "%s_%s, "%(profile,shader_model)
  1156. result += "\\n\\t\\t "
  1157. result += "\">;"
  1158. return result
  1159. def get_min_validator_version():
  1160. result = ""
  1161. for i in range(0, highest_minor+1):
  1162. result += "case %d:\n"%i
  1163. result += " ValMinor = %d;\n"%i
  1164. result += " break;\n"
  1165. return result
  1166. def get_dxil_version():
  1167. result = ""
  1168. for i in range(0, highest_minor+1):
  1169. result += "case %d:\n"%i
  1170. result += " DxilMinor = %d;\n"%i
  1171. result += " break;\n"
  1172. result += "case kOfflineMinor: // Always update this to highest dxil version\n"
  1173. result += " DxilMinor = %d;\n"%highest_minor
  1174. result += " break;\n"
  1175. return result
  1176. def get_shader_model_get():
  1177. # const static std::unordered_map<unsigned, unsigned> hashToIdxMap = {};
  1178. result = build_shader_model_hash_idx_map()
  1179. result += "unsigned hash = (unsigned)Kind << 16 | Major << 8 | Minor;\n"
  1180. result += "auto it = hashToIdxMap.find(hash);\n"
  1181. result += "if (it == hashToIdxMap.end())\n"
  1182. result += " return GetInvalid();\n"
  1183. result += "return &ms_ShaderModels[it->second];"
  1184. return result
  1185. def get_shader_model_by_name():
  1186. result = ""
  1187. for i in range(2, highest_minor+1):
  1188. result += "case '%d':\n"%i
  1189. result += " if (Major == %d) {\n"%highest_major
  1190. result += " Minor = %d;\n"%i
  1191. result += " break;\n"
  1192. result += " }\n"
  1193. result += "else return GetInvalid();\n"
  1194. return result
  1195. def get_is_valid_for_dxil():
  1196. result = ""
  1197. for i in range(0, highest_minor+1):
  1198. result += "case %d:\n"%i
  1199. return result
  1200. def RunCodeTagUpdate(file_path):
  1201. import os
  1202. import CodeTags
  1203. print(" ... updating " + file_path)
  1204. args = [file_path, file_path + ".tmp"]
  1205. result = CodeTags.main(args)
  1206. if result != 0:
  1207. print(" ... error: %d" % result)
  1208. else:
  1209. with open(file_path, 'rt') as f:
  1210. before = f.read()
  1211. with open(file_path + ".tmp", 'rt') as f:
  1212. after = f.read()
  1213. if before == after:
  1214. print(" --- no changes found")
  1215. else:
  1216. print(" +++ changes found, updating file")
  1217. with open(file_path, 'wt') as f:
  1218. f.write(after)
  1219. os.remove(file_path + ".tmp")
  1220. if __name__ == "__main__":
  1221. parser = argparse.ArgumentParser(description="Generate code to handle instructions.")
  1222. parser.add_argument("-gen", choices=["docs-ref", "docs-spec", "inst-header", "enums", "oloads", "valfns"], help="Output type to generate.")
  1223. parser.add_argument("-update-files", action="store_const", const=True)
  1224. args = parser.parse_args()
  1225. db = get_db_dxil() # used by all generators, also handy to have it run validation
  1226. if args.gen == "docs-ref":
  1227. gen = db_docsref_gen(db)
  1228. gen.print_content()
  1229. if args.gen == "docs-spec":
  1230. import os, docutils.core
  1231. assert "HLSL_SRC_DIR" in os.environ, "Environment variable HLSL_SRC_DIR is not defined"
  1232. hlsl_src_dir = os.environ["HLSL_SRC_DIR"]
  1233. spec_file = os.path.abspath(os.path.join(hlsl_src_dir, "docs/DXIL.rst"))
  1234. with open(spec_file) as f:
  1235. s = docutils.core.publish_file(f, writer_name="html")
  1236. if args.gen == "inst-header":
  1237. gen = db_instrhelp_gen(db)
  1238. gen.print_content()
  1239. if args.gen == "enums":
  1240. gen = db_enumhelp_gen(db)
  1241. gen.print_content()
  1242. if args.gen == "oloads":
  1243. gen = db_oload_gen(db)
  1244. gen.print_content()
  1245. if args.gen == "valfns":
  1246. gen = db_valfns_gen(db)
  1247. gen.print_content()
  1248. if args.update_files:
  1249. print("Updating files ...")
  1250. import CodeTags
  1251. import os
  1252. assert "HLSL_SRC_DIR" in os.environ, "Environment variable HLSL_SRC_DIR is not defined"
  1253. hlsl_src_dir = os.environ["HLSL_SRC_DIR"]
  1254. pj = lambda *parts: os.path.abspath(os.path.join(*parts))
  1255. files = [
  1256. 'docs/DXIL.rst',
  1257. 'lib/DXIL/DXILOperations.cpp',
  1258. 'lib/DXIL/DXILShaderModel.cpp',
  1259. 'include/dxc/DXIL/DXILConstants.h',
  1260. 'include/dxc/DXIL/DXILShaderModel.h',
  1261. 'include/dxc/HLSL/DxilValidation.h',
  1262. 'include/dxc/Support/HLSLOptions.td',
  1263. 'include/dxc/DXIL/DxilInstructions.h',
  1264. 'lib/HLSL/DxcOptimizer.cpp',
  1265. 'lib/DxilPIXPasses/DxilPIXPasses.cpp',
  1266. 'lib/HLSL/DxilValidation.cpp',
  1267. 'tools/clang/lib/Sema/gen_intrin_main_tables_15.h',
  1268. 'include/dxc/HlslIntrinsicOp.h',
  1269. 'tools/clang/tools/dxcompiler/dxcdisassembler.cpp',
  1270. 'include/dxc/DXIL/DxilSigPoint.inl',
  1271. ]
  1272. for relative_file_path in files:
  1273. RunCodeTagUpdate(pj(hlsl_src_dir, relative_file_path))