GlslDecompiler.cs 46 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Globalization;
  4. using System.Linq;
  5. using System.Text;
  6. namespace Ryujinx.Graphics.Gal.Shader
  7. {
  8. public class GlslDecompiler
  9. {
  10. private delegate string GetInstExpr(ShaderIrOp Op);
  11. private Dictionary<ShaderIrInst, GetInstExpr> InstsExpr;
  12. private enum OperType
  13. {
  14. Bool,
  15. F32,
  16. I32
  17. }
  18. private const string IdentationStr = " ";
  19. private const int MaxVertexInput = 3;
  20. private GlslDecl Decl;
  21. private ShaderHeader Header, HeaderB;
  22. private ShaderIrBlock[] Blocks, BlocksB;
  23. private StringBuilder SB;
  24. public int MaxUboSize { get; }
  25. public GlslDecompiler(int MaxUboSize)
  26. {
  27. InstsExpr = new Dictionary<ShaderIrInst, GetInstExpr>()
  28. {
  29. { ShaderIrInst.Abs, GetAbsExpr },
  30. { ShaderIrInst.Add, GetAddExpr },
  31. { ShaderIrInst.And, GetAndExpr },
  32. { ShaderIrInst.Asr, GetAsrExpr },
  33. { ShaderIrInst.Band, GetBandExpr },
  34. { ShaderIrInst.Bnot, GetBnotExpr },
  35. { ShaderIrInst.Bor, GetBorExpr },
  36. { ShaderIrInst.Bxor, GetBxorExpr },
  37. { ShaderIrInst.Ceil, GetCeilExpr },
  38. { ShaderIrInst.Ceq, GetCeqExpr },
  39. { ShaderIrInst.Cge, GetCgeExpr },
  40. { ShaderIrInst.Cgt, GetCgtExpr },
  41. { ShaderIrInst.Clamps, GetClampsExpr },
  42. { ShaderIrInst.Clampu, GetClampuExpr },
  43. { ShaderIrInst.Cle, GetCleExpr },
  44. { ShaderIrInst.Clt, GetCltExpr },
  45. { ShaderIrInst.Cne, GetCneExpr },
  46. { ShaderIrInst.Cut, GetCutExpr },
  47. { ShaderIrInst.Exit, GetExitExpr },
  48. { ShaderIrInst.Fabs, GetAbsExpr },
  49. { ShaderIrInst.Fadd, GetAddExpr },
  50. { ShaderIrInst.Fceq, GetCeqExpr },
  51. { ShaderIrInst.Fcequ, GetCequExpr },
  52. { ShaderIrInst.Fcge, GetCgeExpr },
  53. { ShaderIrInst.Fcgeu, GetCgeuExpr },
  54. { ShaderIrInst.Fcgt, GetCgtExpr },
  55. { ShaderIrInst.Fcgtu, GetCgtuExpr },
  56. { ShaderIrInst.Fclamp, GetFclampExpr },
  57. { ShaderIrInst.Fcle, GetCleExpr },
  58. { ShaderIrInst.Fcleu, GetCleuExpr },
  59. { ShaderIrInst.Fclt, GetCltExpr },
  60. { ShaderIrInst.Fcltu, GetCltuExpr },
  61. { ShaderIrInst.Fcnan, GetCnanExpr },
  62. { ShaderIrInst.Fcne, GetCneExpr },
  63. { ShaderIrInst.Fcneu, GetCneuExpr },
  64. { ShaderIrInst.Fcnum, GetCnumExpr },
  65. { ShaderIrInst.Fcos, GetFcosExpr },
  66. { ShaderIrInst.Fex2, GetFex2Expr },
  67. { ShaderIrInst.Ffma, GetFfmaExpr },
  68. { ShaderIrInst.Flg2, GetFlg2Expr },
  69. { ShaderIrInst.Floor, GetFloorExpr },
  70. { ShaderIrInst.Fmax, GetMaxExpr },
  71. { ShaderIrInst.Fmin, GetMinExpr },
  72. { ShaderIrInst.Fmul, GetMulExpr },
  73. { ShaderIrInst.Fneg, GetNegExpr },
  74. { ShaderIrInst.Frcp, GetFrcpExpr },
  75. { ShaderIrInst.Frsq, GetFrsqExpr },
  76. { ShaderIrInst.Fsin, GetFsinExpr },
  77. { ShaderIrInst.Fsqrt, GetFsqrtExpr },
  78. { ShaderIrInst.Ftos, GetFtosExpr },
  79. { ShaderIrInst.Ftou, GetFtouExpr },
  80. { ShaderIrInst.Ipa, GetIpaExpr },
  81. { ShaderIrInst.Kil, GetKilExpr },
  82. { ShaderIrInst.Lsl, GetLslExpr },
  83. { ShaderIrInst.Lsr, GetLsrExpr },
  84. { ShaderIrInst.Max, GetMaxExpr },
  85. { ShaderIrInst.Min, GetMinExpr },
  86. { ShaderIrInst.Mul, GetMulExpr },
  87. { ShaderIrInst.Neg, GetNegExpr },
  88. { ShaderIrInst.Not, GetNotExpr },
  89. { ShaderIrInst.Or, GetOrExpr },
  90. { ShaderIrInst.Stof, GetStofExpr },
  91. { ShaderIrInst.Sub, GetSubExpr },
  92. { ShaderIrInst.Texb, GetTexbExpr },
  93. { ShaderIrInst.Texq, GetTexqExpr },
  94. { ShaderIrInst.Texs, GetTexsExpr },
  95. { ShaderIrInst.Trunc, GetTruncExpr },
  96. { ShaderIrInst.Txlf, GetTxlfExpr },
  97. { ShaderIrInst.Utof, GetUtofExpr },
  98. { ShaderIrInst.Xor, GetXorExpr }
  99. };
  100. this.MaxUboSize = MaxUboSize / 16;
  101. }
  102. public GlslProgram Decompile(
  103. IGalMemory Memory,
  104. long VpAPosition,
  105. long VpBPosition,
  106. GalShaderType ShaderType)
  107. {
  108. Header = new ShaderHeader(Memory, VpAPosition);
  109. HeaderB = new ShaderHeader(Memory, VpBPosition);
  110. Blocks = ShaderDecoder.Decode(Memory, VpAPosition);
  111. BlocksB = ShaderDecoder.Decode(Memory, VpBPosition);
  112. GlslDecl DeclVpA = new GlslDecl(Blocks, ShaderType, Header);
  113. GlslDecl DeclVpB = new GlslDecl(BlocksB, ShaderType, HeaderB);
  114. Decl = GlslDecl.Merge(DeclVpA, DeclVpB);
  115. return Decompile();
  116. }
  117. public GlslProgram Decompile(IGalMemory Memory, long Position, GalShaderType ShaderType)
  118. {
  119. Header = new ShaderHeader(Memory, Position);
  120. HeaderB = null;
  121. Blocks = ShaderDecoder.Decode(Memory, Position);
  122. BlocksB = null;
  123. Decl = new GlslDecl(Blocks, ShaderType, Header);
  124. return Decompile();
  125. }
  126. private GlslProgram Decompile()
  127. {
  128. SB = new StringBuilder();
  129. SB.AppendLine("#version 410 core");
  130. PrintDeclHeader();
  131. PrintDeclTextures();
  132. PrintDeclUniforms();
  133. PrintDeclAttributes();
  134. PrintDeclInAttributes();
  135. PrintDeclOutAttributes();
  136. PrintDeclGprs();
  137. PrintDeclPreds();
  138. PrintDeclSsy();
  139. if (BlocksB != null)
  140. {
  141. PrintBlockScope(Blocks, GlslDecl.BasicBlockAName);
  142. SB.AppendLine();
  143. PrintBlockScope(BlocksB, GlslDecl.BasicBlockBName);
  144. }
  145. else
  146. {
  147. PrintBlockScope(Blocks, GlslDecl.BasicBlockName);
  148. }
  149. SB.AppendLine();
  150. PrintMain();
  151. string GlslCode = SB.ToString();
  152. List<ShaderDeclInfo> TextureInfo = new List<ShaderDeclInfo>();
  153. TextureInfo.AddRange(Decl.Textures.Values);
  154. TextureInfo.AddRange(IterateCbTextures());
  155. return new GlslProgram(GlslCode, TextureInfo, Decl.Uniforms.Values);
  156. }
  157. private void PrintDeclHeader()
  158. {
  159. if (Decl.ShaderType == GalShaderType.Geometry)
  160. {
  161. int MaxVertices = Header.MaxOutputVertexCount;
  162. string OutputTopology;
  163. switch (Header.OutputTopology)
  164. {
  165. case ShaderHeader.PointList: OutputTopology = "points"; break;
  166. case ShaderHeader.LineStrip: OutputTopology = "line_strip"; break;
  167. case ShaderHeader.TriangleStrip: OutputTopology = "triangle_strip"; break;
  168. default: throw new InvalidOperationException();
  169. }
  170. SB.AppendLine("#extension GL_ARB_enhanced_layouts : require");
  171. SB.AppendLine();
  172. SB.AppendLine("// Stubbed. Maxwell geometry shaders don't inform input geometry type");
  173. SB.AppendLine("layout(triangles) in;" + Environment.NewLine);
  174. SB.AppendLine($"layout({OutputTopology}, max_vertices = {MaxVertices}) out;");
  175. SB.AppendLine();
  176. }
  177. }
  178. private void PrintDeclTextures()
  179. {
  180. foreach (ShaderDeclInfo DeclInfo in IterateCbTextures())
  181. {
  182. SB.AppendLine("uniform sampler2D " + DeclInfo.Name + ";");
  183. }
  184. PrintDecls(Decl.Textures, "uniform sampler2D");
  185. }
  186. private IEnumerable<ShaderDeclInfo> IterateCbTextures()
  187. {
  188. HashSet<string> Names = new HashSet<string>();
  189. foreach (ShaderDeclInfo DeclInfo in Decl.CbTextures.Values.OrderBy(DeclKeySelector))
  190. {
  191. if (Names.Add(DeclInfo.Name))
  192. {
  193. yield return DeclInfo;
  194. }
  195. }
  196. }
  197. private void PrintDeclUniforms()
  198. {
  199. if (Decl.ShaderType == GalShaderType.Vertex)
  200. {
  201. //Memory layout here is [flip_x, flip_y, instance, unused]
  202. //It's using 4 bytes, not 8
  203. SB.AppendLine("layout (std140) uniform " + GlslDecl.ExtraUniformBlockName + " {");
  204. SB.AppendLine(IdentationStr + "vec2 " + GlslDecl.FlipUniformName + ";");
  205. SB.AppendLine(IdentationStr + "int " + GlslDecl.InstanceUniformName + ";");
  206. SB.AppendLine("};");
  207. SB.AppendLine();
  208. }
  209. foreach (ShaderDeclInfo DeclInfo in Decl.Uniforms.Values.OrderBy(DeclKeySelector))
  210. {
  211. SB.AppendLine($"layout (std140) uniform {DeclInfo.Name} {{");
  212. SB.AppendLine($"{IdentationStr}vec4 {DeclInfo.Name}_data[{MaxUboSize}];");
  213. SB.AppendLine("};");
  214. }
  215. if (Decl.Uniforms.Count > 0)
  216. {
  217. SB.AppendLine();
  218. }
  219. }
  220. private void PrintDeclAttributes()
  221. {
  222. string GeometryArray = (Decl.ShaderType == GalShaderType.Geometry) ? "[" + MaxVertexInput + "]" : "";
  223. PrintDecls(Decl.Attributes, Suffix: GeometryArray);
  224. }
  225. private void PrintDeclInAttributes()
  226. {
  227. if (Decl.ShaderType == GalShaderType.Fragment)
  228. {
  229. SB.AppendLine("layout (location = " + GlslDecl.PositionOutAttrLocation + ") in vec4 " + GlslDecl.PositionOutAttrName + ";");
  230. }
  231. if (Decl.ShaderType == GalShaderType.Geometry)
  232. {
  233. if (Decl.InAttributes.Count > 0)
  234. {
  235. SB.AppendLine("in Vertex {");
  236. foreach (ShaderDeclInfo DeclInfo in Decl.InAttributes.Values.OrderBy(DeclKeySelector))
  237. {
  238. if (DeclInfo.Index >= 0)
  239. {
  240. SB.AppendLine(IdentationStr + "layout (location = " + DeclInfo.Index + ") vec4 " + DeclInfo.Name + "; ");
  241. }
  242. }
  243. SB.AppendLine("} block_in[];" + Environment.NewLine);
  244. }
  245. }
  246. else
  247. {
  248. PrintDeclAttributes(Decl.InAttributes.Values, "in");
  249. }
  250. }
  251. private void PrintDeclOutAttributes()
  252. {
  253. if (Decl.ShaderType == GalShaderType.Fragment)
  254. {
  255. int Count = 0;
  256. for (int Attachment = 0; Attachment < 8; Attachment++)
  257. {
  258. if (Header.OmapTargets[Attachment].Enabled)
  259. {
  260. SB.AppendLine("layout (location = " + Attachment + ") out vec4 " + GlslDecl.FragmentOutputName + Attachment + ";");
  261. Count++;
  262. }
  263. }
  264. if (Count > 0)
  265. {
  266. SB.AppendLine();
  267. }
  268. }
  269. else
  270. {
  271. SB.AppendLine("layout (location = " + GlslDecl.PositionOutAttrLocation + ") out vec4 " + GlslDecl.PositionOutAttrName + ";");
  272. SB.AppendLine();
  273. }
  274. PrintDeclAttributes(Decl.OutAttributes.Values, "out");
  275. }
  276. private void PrintDeclAttributes(IEnumerable<ShaderDeclInfo> Decls, string InOut)
  277. {
  278. int Count = 0;
  279. foreach (ShaderDeclInfo DeclInfo in Decls.OrderBy(DeclKeySelector))
  280. {
  281. if (DeclInfo.Index >= 0)
  282. {
  283. SB.AppendLine("layout (location = " + DeclInfo.Index + ") " + InOut + " vec4 " + DeclInfo.Name + ";");
  284. Count++;
  285. }
  286. }
  287. if (Count > 0)
  288. {
  289. SB.AppendLine();
  290. }
  291. }
  292. private void PrintDeclGprs()
  293. {
  294. PrintDecls(Decl.Gprs);
  295. }
  296. private void PrintDeclPreds()
  297. {
  298. PrintDecls(Decl.Preds, "bool");
  299. }
  300. private void PrintDeclSsy()
  301. {
  302. SB.AppendLine("uint " + GlslDecl.SsyCursorName + " = 0;");
  303. SB.AppendLine("uint " + GlslDecl.SsyStackName + "[" + GlslDecl.SsyStackSize + "];" + Environment.NewLine);
  304. }
  305. private void PrintDecls(IReadOnlyDictionary<int, ShaderDeclInfo> Dict, string CustomType = null, string Suffix = "")
  306. {
  307. foreach (ShaderDeclInfo DeclInfo in Dict.Values.OrderBy(DeclKeySelector))
  308. {
  309. string Name;
  310. if (CustomType != null)
  311. {
  312. Name = CustomType + " " + DeclInfo.Name + Suffix + ";";
  313. }
  314. else if (DeclInfo.Name.Contains(GlslDecl.FragmentOutputName))
  315. {
  316. Name = "layout (location = " + DeclInfo.Index / 4 + ") out vec4 " + DeclInfo.Name + Suffix + ";";
  317. }
  318. else
  319. {
  320. Name = GetDecl(DeclInfo) + Suffix + ";";
  321. }
  322. SB.AppendLine(Name);
  323. }
  324. if (Dict.Count > 0)
  325. {
  326. SB.AppendLine();
  327. }
  328. }
  329. private int DeclKeySelector(ShaderDeclInfo DeclInfo)
  330. {
  331. return DeclInfo.Cbuf << 24 | DeclInfo.Index;
  332. }
  333. private string GetDecl(ShaderDeclInfo DeclInfo)
  334. {
  335. if (DeclInfo.Size == 4)
  336. {
  337. return "vec4 " + DeclInfo.Name;
  338. }
  339. else
  340. {
  341. return "float " + DeclInfo.Name;
  342. }
  343. }
  344. private void PrintMain()
  345. {
  346. SB.AppendLine("void main() {");
  347. foreach (KeyValuePair<int, ShaderDeclInfo> KV in Decl.InAttributes)
  348. {
  349. if (!Decl.Attributes.TryGetValue(KV.Key, out ShaderDeclInfo Attr))
  350. {
  351. continue;
  352. }
  353. ShaderDeclInfo DeclInfo = KV.Value;
  354. if (Decl.ShaderType == GalShaderType.Geometry)
  355. {
  356. for (int Vertex = 0; Vertex < MaxVertexInput; Vertex++)
  357. {
  358. string Dst = Attr.Name + "[" + Vertex + "]";
  359. string Src = "block_in[" + Vertex + "]." + DeclInfo.Name;
  360. SB.AppendLine(IdentationStr + Dst + " = " + Src + ";");
  361. }
  362. }
  363. else
  364. {
  365. SB.AppendLine(IdentationStr + Attr.Name + " = " + DeclInfo.Name + ";");
  366. }
  367. }
  368. SB.AppendLine(IdentationStr + "uint pc;");
  369. if (BlocksB != null)
  370. {
  371. PrintProgram(Blocks, GlslDecl.BasicBlockAName);
  372. PrintProgram(BlocksB, GlslDecl.BasicBlockBName);
  373. }
  374. else
  375. {
  376. PrintProgram(Blocks, GlslDecl.BasicBlockName);
  377. }
  378. if (Decl.ShaderType != GalShaderType.Geometry)
  379. {
  380. PrintAttrToOutput();
  381. }
  382. if (Decl.ShaderType == GalShaderType.Fragment)
  383. {
  384. if (Header.OmapDepth)
  385. {
  386. SB.AppendLine(IdentationStr + "gl_FragDepth = " + GlslDecl.GetGprName(Header.DepthRegister) + ";");
  387. }
  388. int GprIndex = 0;
  389. for (int Attachment = 0; Attachment < 8; Attachment++)
  390. {
  391. string Output = GlslDecl.FragmentOutputName + Attachment;
  392. OmapTarget Target = Header.OmapTargets[Attachment];
  393. for (int Component = 0; Component < 4; Component++)
  394. {
  395. if (Target.ComponentEnabled(Component))
  396. {
  397. SB.AppendLine(IdentationStr + Output + "[" + Component + "] = " + GlslDecl.GetGprName(GprIndex) + ";");
  398. GprIndex++;
  399. }
  400. }
  401. }
  402. }
  403. SB.AppendLine("}");
  404. }
  405. private void PrintProgram(ShaderIrBlock[] Blocks, string Name)
  406. {
  407. const string Ident1 = IdentationStr;
  408. const string Ident2 = Ident1 + IdentationStr;
  409. const string Ident3 = Ident2 + IdentationStr;
  410. const string Ident4 = Ident3 + IdentationStr;
  411. SB.AppendLine(Ident1 + "pc = " + GetBlockPosition(Blocks[0]) + ";");
  412. SB.AppendLine(Ident1 + "do {");
  413. SB.AppendLine(Ident2 + "switch (pc) {");
  414. foreach (ShaderIrBlock Block in Blocks)
  415. {
  416. string FunctionName = Block.Position.ToString("x8");
  417. SB.AppendLine(Ident3 + "case 0x" + FunctionName + ": pc = " + Name + "_" + FunctionName + "(); break;");
  418. }
  419. SB.AppendLine(Ident3 + "default:");
  420. SB.AppendLine(Ident4 + "pc = 0;");
  421. SB.AppendLine(Ident4 + "break;");
  422. SB.AppendLine(Ident2 + "}");
  423. SB.AppendLine(Ident1 + "} while (pc != 0);");
  424. }
  425. private void PrintAttrToOutput(string Identation = IdentationStr)
  426. {
  427. foreach (KeyValuePair<int, ShaderDeclInfo> KV in Decl.OutAttributes)
  428. {
  429. if (!Decl.Attributes.TryGetValue(KV.Key, out ShaderDeclInfo Attr))
  430. {
  431. continue;
  432. }
  433. ShaderDeclInfo DeclInfo = KV.Value;
  434. string Name = Attr.Name;
  435. if (Decl.ShaderType == GalShaderType.Geometry)
  436. {
  437. Name += "[0]";
  438. }
  439. SB.AppendLine(Identation + DeclInfo.Name + " = " + Name + ";");
  440. }
  441. if (Decl.ShaderType == GalShaderType.Vertex)
  442. {
  443. SB.AppendLine(Identation + "gl_Position.xy *= " + GlslDecl.FlipUniformName + ";");
  444. }
  445. if (Decl.ShaderType != GalShaderType.Fragment)
  446. {
  447. SB.AppendLine(Identation + GlslDecl.PositionOutAttrName + " = gl_Position;");
  448. SB.AppendLine(Identation + GlslDecl.PositionOutAttrName + ".w = 1;");
  449. }
  450. }
  451. private void PrintBlockScope(ShaderIrBlock[] Blocks, string Name)
  452. {
  453. foreach (ShaderIrBlock Block in Blocks)
  454. {
  455. SB.AppendLine("uint " + Name + "_" + Block.Position.ToString("x8") + "() {");
  456. PrintNodes(Block, Block.GetNodes());
  457. SB.AppendLine("}" + Environment.NewLine);
  458. }
  459. }
  460. private void PrintNodes(ShaderIrBlock Block, ShaderIrNode[] Nodes)
  461. {
  462. foreach (ShaderIrNode Node in Nodes)
  463. {
  464. PrintNode(Block, Node, IdentationStr);
  465. }
  466. if (Nodes.Length == 0)
  467. {
  468. SB.AppendLine(IdentationStr + "return 0u;");
  469. return;
  470. }
  471. ShaderIrNode Last = Nodes[Nodes.Length - 1];
  472. bool UnconditionalFlowChange = false;
  473. if (Last is ShaderIrOp Op)
  474. {
  475. switch (Op.Inst)
  476. {
  477. case ShaderIrInst.Bra:
  478. case ShaderIrInst.Exit:
  479. case ShaderIrInst.Sync:
  480. UnconditionalFlowChange = true;
  481. break;
  482. }
  483. }
  484. if (!UnconditionalFlowChange)
  485. {
  486. if (Block.Next != null)
  487. {
  488. SB.AppendLine(IdentationStr + "return " + GetBlockPosition(Block.Next) + ";");
  489. }
  490. else
  491. {
  492. SB.AppendLine(IdentationStr + "return 0u;");
  493. }
  494. }
  495. }
  496. private void PrintNode(ShaderIrBlock Block, ShaderIrNode Node, string Identation)
  497. {
  498. if (Node is ShaderIrCond Cond)
  499. {
  500. string IfExpr = GetSrcExpr(Cond.Pred, true);
  501. if (Cond.Not)
  502. {
  503. IfExpr = "!(" + IfExpr + ")";
  504. }
  505. SB.AppendLine(Identation + "if (" + IfExpr + ") {");
  506. PrintNode(Block, Cond.Child, Identation + IdentationStr);
  507. SB.AppendLine(Identation + "}");
  508. }
  509. else if (Node is ShaderIrAsg Asg)
  510. {
  511. if (IsValidOutOper(Asg.Dst))
  512. {
  513. string Expr = GetSrcExpr(Asg.Src, true);
  514. Expr = GetExprWithCast(Asg.Dst, Asg.Src, Expr);
  515. SB.AppendLine(Identation + GetDstOperName(Asg.Dst) + " = " + Expr + ";");
  516. }
  517. }
  518. else if (Node is ShaderIrOp Op)
  519. {
  520. switch (Op.Inst)
  521. {
  522. case ShaderIrInst.Bra:
  523. {
  524. SB.AppendLine(Identation + "return " + GetBlockPosition(Block.Branch) + ";");
  525. break;
  526. }
  527. case ShaderIrInst.Emit:
  528. {
  529. PrintAttrToOutput(Identation);
  530. SB.AppendLine(Identation + "EmitVertex();");
  531. break;
  532. }
  533. case ShaderIrInst.Ssy:
  534. {
  535. string StackIndex = GlslDecl.SsyStackName + "[" + GlslDecl.SsyCursorName + "]";
  536. int TargetPosition = (Op.OperandA as ShaderIrOperImm).Value;
  537. string Target = "0x" + TargetPosition.ToString("x8") + "u";
  538. SB.AppendLine(Identation + StackIndex + " = " + Target + ";");
  539. SB.AppendLine(Identation + GlslDecl.SsyCursorName + "++;");
  540. break;
  541. }
  542. case ShaderIrInst.Sync:
  543. {
  544. SB.AppendLine(Identation + GlslDecl.SsyCursorName + "--;");
  545. string Target = GlslDecl.SsyStackName + "[" + GlslDecl.SsyCursorName + "]";
  546. SB.AppendLine(Identation + "return " + Target + ";");
  547. break;
  548. }
  549. default:
  550. SB.AppendLine(Identation + GetSrcExpr(Op, true) + ";");
  551. break;
  552. }
  553. }
  554. else if (Node is ShaderIrCmnt Cmnt)
  555. {
  556. SB.AppendLine(Identation + "// " + Cmnt.Comment);
  557. }
  558. else
  559. {
  560. throw new InvalidOperationException();
  561. }
  562. }
  563. private bool IsValidOutOper(ShaderIrNode Node)
  564. {
  565. if (Node is ShaderIrOperGpr Gpr && Gpr.IsConst)
  566. {
  567. return false;
  568. }
  569. else if (Node is ShaderIrOperPred Pred && Pred.IsConst)
  570. {
  571. return false;
  572. }
  573. return true;
  574. }
  575. private string GetDstOperName(ShaderIrNode Node)
  576. {
  577. if (Node is ShaderIrOperAbuf Abuf)
  578. {
  579. return GetOutAbufName(Abuf);
  580. }
  581. else if (Node is ShaderIrOperGpr Gpr)
  582. {
  583. return GetName(Gpr);
  584. }
  585. else if (Node is ShaderIrOperPred Pred)
  586. {
  587. return GetName(Pred);
  588. }
  589. throw new ArgumentException(nameof(Node));
  590. }
  591. private string GetSrcExpr(ShaderIrNode Node, bool Entry = false)
  592. {
  593. switch (Node)
  594. {
  595. case ShaderIrOperAbuf Abuf: return GetName (Abuf);
  596. case ShaderIrOperCbuf Cbuf: return GetName (Cbuf);
  597. case ShaderIrOperGpr Gpr: return GetName (Gpr);
  598. case ShaderIrOperImm Imm: return GetValue(Imm);
  599. case ShaderIrOperImmf Immf: return GetValue(Immf);
  600. case ShaderIrOperPred Pred: return GetName (Pred);
  601. case ShaderIrOp Op:
  602. string Expr;
  603. if (InstsExpr.TryGetValue(Op.Inst, out GetInstExpr GetExpr))
  604. {
  605. Expr = GetExpr(Op);
  606. }
  607. else
  608. {
  609. throw new NotImplementedException(Op.Inst.ToString());
  610. }
  611. if (!Entry && NeedsParentheses(Op))
  612. {
  613. Expr = "(" + Expr + ")";
  614. }
  615. return Expr;
  616. default: throw new ArgumentException(nameof(Node));
  617. }
  618. }
  619. private static bool NeedsParentheses(ShaderIrOp Op)
  620. {
  621. switch (Op.Inst)
  622. {
  623. case ShaderIrInst.Ipa:
  624. case ShaderIrInst.Texq:
  625. case ShaderIrInst.Texs:
  626. case ShaderIrInst.Txlf:
  627. return false;
  628. }
  629. return true;
  630. }
  631. private string GetName(ShaderIrOperCbuf Cbuf)
  632. {
  633. if (!Decl.Uniforms.TryGetValue(Cbuf.Index, out ShaderDeclInfo DeclInfo))
  634. {
  635. throw new InvalidOperationException();
  636. }
  637. if (Cbuf.Offs != null)
  638. {
  639. string Offset = "floatBitsToInt(" + GetSrcExpr(Cbuf.Offs) + ")";
  640. string Index = "(" + Cbuf.Pos * 4 + " + " + Offset + ")";
  641. return $"{DeclInfo.Name}_data[{Index} / 16][({Index} / 4) % 4]";
  642. }
  643. else
  644. {
  645. return $"{DeclInfo.Name}_data[{Cbuf.Pos / 4}][{Cbuf.Pos % 4}]";
  646. }
  647. }
  648. private string GetOutAbufName(ShaderIrOperAbuf Abuf)
  649. {
  650. if (Decl.ShaderType == GalShaderType.Geometry)
  651. {
  652. switch (Abuf.Offs)
  653. {
  654. case GlslDecl.LayerAttr: return "gl_Layer";
  655. }
  656. }
  657. return GetAttrTempName(Abuf);
  658. }
  659. private string GetName(ShaderIrOperAbuf Abuf)
  660. {
  661. //Handle special scalar read-only attributes here.
  662. if (Decl.ShaderType == GalShaderType.Vertex)
  663. {
  664. switch (Abuf.Offs)
  665. {
  666. case GlslDecl.VertexIdAttr: return "gl_VertexID";
  667. case GlslDecl.InstanceIdAttr: return GlslDecl.InstanceUniformName;
  668. }
  669. }
  670. else if (Decl.ShaderType == GalShaderType.TessEvaluation)
  671. {
  672. switch (Abuf.Offs)
  673. {
  674. case GlslDecl.TessCoordAttrX: return "gl_TessCoord.x";
  675. case GlslDecl.TessCoordAttrY: return "gl_TessCoord.y";
  676. case GlslDecl.TessCoordAttrZ: return "gl_TessCoord.z";
  677. }
  678. }
  679. else if (Decl.ShaderType == GalShaderType.Fragment)
  680. {
  681. switch (Abuf.Offs)
  682. {
  683. case GlslDecl.PointCoordAttrX: return "gl_PointCoord.x";
  684. case GlslDecl.PointCoordAttrY: return "gl_PointCoord.y";
  685. //Note: It's a guess that Maxwell's face is 1 when gl_FrontFacing == true
  686. case GlslDecl.FaceAttr: return "(gl_FrontFacing ? 1 : 0)";
  687. }
  688. }
  689. return GetAttrTempName(Abuf);
  690. }
  691. private string GetAttrTempName(ShaderIrOperAbuf Abuf)
  692. {
  693. int Index = Abuf.Offs >> 4;
  694. int Elem = (Abuf.Offs >> 2) & 3;
  695. string Swizzle = "." + GetAttrSwizzle(Elem);
  696. if (!Decl.Attributes.TryGetValue(Index, out ShaderDeclInfo DeclInfo))
  697. {
  698. //Handle special vec4 attributes here
  699. //(for example, index 7 is always gl_Position).
  700. if (Index == GlslDecl.GlPositionVec4Index)
  701. {
  702. string Name =
  703. Decl.ShaderType != GalShaderType.Vertex &&
  704. Decl.ShaderType != GalShaderType.Geometry ? GlslDecl.PositionOutAttrName : "gl_Position";
  705. return Name + Swizzle;
  706. }
  707. else if (Abuf.Offs == GlslDecl.PointSizeAttr)
  708. {
  709. return "gl_PointSize";
  710. }
  711. }
  712. if (DeclInfo.Index >= 16)
  713. {
  714. throw new InvalidOperationException($"Shader attribute offset {Abuf.Offs} is invalid.");
  715. }
  716. if (Decl.ShaderType == GalShaderType.Geometry)
  717. {
  718. string Vertex = "floatBitsToInt(" + GetSrcExpr(Abuf.Vertex) + ")";
  719. return DeclInfo.Name + "[" + Vertex + "]" + Swizzle;
  720. }
  721. else
  722. {
  723. return DeclInfo.Name + Swizzle;
  724. }
  725. }
  726. private string GetName(ShaderIrOperGpr Gpr)
  727. {
  728. return Gpr.IsConst ? "0" : GetNameWithSwizzle(Decl.Gprs, Gpr.Index);
  729. }
  730. private string GetValue(ShaderIrOperImm Imm)
  731. {
  732. //Only use hex is the value is too big and would likely be hard to read as int.
  733. if (Imm.Value > 0xfff ||
  734. Imm.Value < -0xfff)
  735. {
  736. return "0x" + Imm.Value.ToString("x8", CultureInfo.InvariantCulture);
  737. }
  738. else
  739. {
  740. return GetIntConst(Imm.Value);
  741. }
  742. }
  743. private string GetValue(ShaderIrOperImmf Immf)
  744. {
  745. return GetFloatConst(Immf.Value);
  746. }
  747. private string GetName(ShaderIrOperPred Pred)
  748. {
  749. return Pred.IsConst ? "true" : GetNameWithSwizzle(Decl.Preds, Pred.Index);
  750. }
  751. private string GetNameWithSwizzle(IReadOnlyDictionary<int, ShaderDeclInfo> Dict, int Index)
  752. {
  753. int VecIndex = Index & ~3;
  754. if (Dict.TryGetValue(VecIndex, out ShaderDeclInfo DeclInfo))
  755. {
  756. if (DeclInfo.Size > 1 && Index < VecIndex + DeclInfo.Size)
  757. {
  758. return DeclInfo.Name + "." + GetAttrSwizzle(Index & 3);
  759. }
  760. }
  761. if (!Dict.TryGetValue(Index, out DeclInfo))
  762. {
  763. throw new InvalidOperationException();
  764. }
  765. return DeclInfo.Name;
  766. }
  767. private string GetAttrSwizzle(int Elem)
  768. {
  769. return "xyzw".Substring(Elem, 1);
  770. }
  771. private string GetAbsExpr(ShaderIrOp Op) => GetUnaryCall(Op, "abs");
  772. private string GetAddExpr(ShaderIrOp Op) => GetBinaryExpr(Op, "+");
  773. private string GetAndExpr(ShaderIrOp Op) => GetBinaryExpr(Op, "&");
  774. private string GetAsrExpr(ShaderIrOp Op) => GetBinaryExpr(Op, ">>");
  775. private string GetBandExpr(ShaderIrOp Op) => GetBinaryExpr(Op, "&&");
  776. private string GetBnotExpr(ShaderIrOp Op) => GetUnaryExpr(Op, "!");
  777. private string GetBorExpr(ShaderIrOp Op) => GetBinaryExpr(Op, "||");
  778. private string GetBxorExpr(ShaderIrOp Op) => GetBinaryExpr(Op, "^^");
  779. private string GetCeilExpr(ShaderIrOp Op) => GetUnaryCall(Op, "ceil");
  780. private string GetClampsExpr(ShaderIrOp Op)
  781. {
  782. return "clamp(" + GetOperExpr(Op, Op.OperandA) + ", " +
  783. GetOperExpr(Op, Op.OperandB) + ", " +
  784. GetOperExpr(Op, Op.OperandC) + ")";
  785. }
  786. private string GetClampuExpr(ShaderIrOp Op)
  787. {
  788. return "int(clamp(uint(" + GetOperExpr(Op, Op.OperandA) + "), " +
  789. "uint(" + GetOperExpr(Op, Op.OperandB) + "), " +
  790. "uint(" + GetOperExpr(Op, Op.OperandC) + ")))";
  791. }
  792. private string GetCeqExpr(ShaderIrOp Op) => GetBinaryExpr(Op, "==");
  793. private string GetCequExpr(ShaderIrOp Op) => GetBinaryExprWithNaN(Op, "==");
  794. private string GetCgeExpr(ShaderIrOp Op) => GetBinaryExpr(Op, ">=");
  795. private string GetCgeuExpr(ShaderIrOp Op) => GetBinaryExprWithNaN(Op, ">=");
  796. private string GetCgtExpr(ShaderIrOp Op) => GetBinaryExpr(Op, ">");
  797. private string GetCgtuExpr(ShaderIrOp Op) => GetBinaryExprWithNaN(Op, ">");
  798. private string GetCleExpr(ShaderIrOp Op) => GetBinaryExpr(Op, "<=");
  799. private string GetCleuExpr(ShaderIrOp Op) => GetBinaryExprWithNaN(Op, "<=");
  800. private string GetCltExpr(ShaderIrOp Op) => GetBinaryExpr(Op, "<");
  801. private string GetCltuExpr(ShaderIrOp Op) => GetBinaryExprWithNaN(Op, "<");
  802. private string GetCnanExpr(ShaderIrOp Op) => GetUnaryCall(Op, "isnan");
  803. private string GetCneExpr(ShaderIrOp Op) => GetBinaryExpr(Op, "!=");
  804. private string GetCutExpr(ShaderIrOp Op) => "EndPrimitive()";
  805. private string GetCneuExpr(ShaderIrOp Op) => GetBinaryExprWithNaN(Op, "!=");
  806. private string GetCnumExpr(ShaderIrOp Op) => GetUnaryCall(Op, "!isnan");
  807. private string GetExitExpr(ShaderIrOp Op) => "return 0u";
  808. private string GetFcosExpr(ShaderIrOp Op) => GetUnaryCall(Op, "cos");
  809. private string GetFex2Expr(ShaderIrOp Op) => GetUnaryCall(Op, "exp2");
  810. private string GetFfmaExpr(ShaderIrOp Op) => GetTernaryExpr(Op, "*", "+");
  811. private string GetFclampExpr(ShaderIrOp Op) => GetTernaryCall(Op, "clamp");
  812. private string GetFlg2Expr(ShaderIrOp Op) => GetUnaryCall(Op, "log2");
  813. private string GetFloorExpr(ShaderIrOp Op) => GetUnaryCall(Op, "floor");
  814. private string GetFrcpExpr(ShaderIrOp Op) => GetUnaryExpr(Op, "1 / ");
  815. private string GetFrsqExpr(ShaderIrOp Op) => GetUnaryCall(Op, "inversesqrt");
  816. private string GetFsinExpr(ShaderIrOp Op) => GetUnaryCall(Op, "sin");
  817. private string GetFsqrtExpr(ShaderIrOp Op) => GetUnaryCall(Op, "sqrt");
  818. private string GetFtosExpr(ShaderIrOp Op)
  819. {
  820. return "int(" + GetOperExpr(Op, Op.OperandA) + ")";
  821. }
  822. private string GetFtouExpr(ShaderIrOp Op)
  823. {
  824. return "int(uint(" + GetOperExpr(Op, Op.OperandA) + "))";
  825. }
  826. private string GetIpaExpr(ShaderIrOp Op)
  827. {
  828. ShaderIrMetaIpa Meta = (ShaderIrMetaIpa)Op.MetaData;
  829. ShaderIrOperAbuf Abuf = (ShaderIrOperAbuf)Op.OperandA;
  830. if (Meta.Mode == ShaderIpaMode.Pass)
  831. {
  832. int Index = Abuf.Offs >> 4;
  833. int Elem = (Abuf.Offs >> 2) & 3;
  834. if (Decl.ShaderType == GalShaderType.Fragment && Index == GlslDecl.GlPositionVec4Index)
  835. {
  836. switch (Elem)
  837. {
  838. case 0: return "gl_FragCoord.x";
  839. case 1: return "gl_FragCoord.y";
  840. case 2: return "gl_FragCoord.z";
  841. case 3: return "1";
  842. }
  843. }
  844. }
  845. return GetSrcExpr(Op.OperandA);
  846. }
  847. private string GetKilExpr(ShaderIrOp Op) => "discard";
  848. private string GetLslExpr(ShaderIrOp Op) => GetBinaryExpr(Op, "<<");
  849. private string GetLsrExpr(ShaderIrOp Op)
  850. {
  851. return "int(uint(" + GetOperExpr(Op, Op.OperandA) + ") >> " +
  852. GetOperExpr(Op, Op.OperandB) + ")";
  853. }
  854. private string GetMaxExpr(ShaderIrOp Op) => GetBinaryCall(Op, "max");
  855. private string GetMinExpr(ShaderIrOp Op) => GetBinaryCall(Op, "min");
  856. private string GetMulExpr(ShaderIrOp Op) => GetBinaryExpr(Op, "*");
  857. private string GetNegExpr(ShaderIrOp Op) => GetUnaryExpr(Op, "-");
  858. private string GetNotExpr(ShaderIrOp Op) => GetUnaryExpr(Op, "~");
  859. private string GetOrExpr(ShaderIrOp Op) => GetBinaryExpr(Op, "|");
  860. private string GetStofExpr(ShaderIrOp Op)
  861. {
  862. return "float(" + GetOperExpr(Op, Op.OperandA) + ")";
  863. }
  864. private string GetSubExpr(ShaderIrOp Op) => GetBinaryExpr(Op, "-");
  865. private string GetTexbExpr(ShaderIrOp Op)
  866. {
  867. ShaderIrMetaTex Meta = (ShaderIrMetaTex)Op.MetaData;
  868. if (!Decl.CbTextures.TryGetValue(Op, out ShaderDeclInfo DeclInfo))
  869. {
  870. throw new InvalidOperationException();
  871. }
  872. string Coords = GetTexSamplerCoords(Op);
  873. string Ch = "rgba".Substring(Meta.Elem, 1);
  874. return "texture(" + DeclInfo.Name + ", " + Coords + ")." + Ch;
  875. }
  876. private string GetTexqExpr(ShaderIrOp Op)
  877. {
  878. ShaderIrMetaTexq Meta = (ShaderIrMetaTexq)Op.MetaData;
  879. string Ch = "xyzw".Substring(Meta.Elem, 1);
  880. if (Meta.Info == ShaderTexqInfo.Dimension)
  881. {
  882. string Sampler = GetTexSamplerName(Op);
  883. string Lod = GetOperExpr(Op, Op.OperandA); //???
  884. return "textureSize(" + Sampler + ", " + Lod + ")." + Ch;
  885. }
  886. else
  887. {
  888. throw new NotImplementedException(Meta.Info.ToString());
  889. }
  890. }
  891. private string GetTexsExpr(ShaderIrOp Op)
  892. {
  893. ShaderIrMetaTex Meta = (ShaderIrMetaTex)Op.MetaData;
  894. string Sampler = GetTexSamplerName(Op);
  895. string Coords = GetTexSamplerCoords(Op);
  896. string Ch = "rgba".Substring(Meta.Elem, 1);
  897. return "texture(" + Sampler + ", " + Coords + ")." + Ch;
  898. }
  899. private string GetTxlfExpr(ShaderIrOp Op)
  900. {
  901. ShaderIrMetaTex Meta = (ShaderIrMetaTex)Op.MetaData;
  902. string Sampler = GetTexSamplerName(Op);
  903. string Coords = GetITexSamplerCoords(Op);
  904. string Ch = "rgba".Substring(Meta.Elem, 1);
  905. return "texelFetch(" + Sampler + ", " + Coords + ", 0)." + Ch;
  906. }
  907. private string GetTruncExpr(ShaderIrOp Op) => GetUnaryCall(Op, "trunc");
  908. private string GetUtofExpr(ShaderIrOp Op)
  909. {
  910. return "float(uint(" + GetOperExpr(Op, Op.OperandA) + "))";
  911. }
  912. private string GetXorExpr(ShaderIrOp Op) => GetBinaryExpr(Op, "^");
  913. private string GetUnaryCall(ShaderIrOp Op, string FuncName)
  914. {
  915. return FuncName + "(" + GetOperExpr(Op, Op.OperandA) + ")";
  916. }
  917. private string GetBinaryCall(ShaderIrOp Op, string FuncName)
  918. {
  919. return FuncName + "(" + GetOperExpr(Op, Op.OperandA) + ", " +
  920. GetOperExpr(Op, Op.OperandB) + ")";
  921. }
  922. private string GetTernaryCall(ShaderIrOp Op, string FuncName)
  923. {
  924. return FuncName + "(" + GetOperExpr(Op, Op.OperandA) + ", " +
  925. GetOperExpr(Op, Op.OperandB) + ", " +
  926. GetOperExpr(Op, Op.OperandC) + ")";
  927. }
  928. private string GetUnaryExpr(ShaderIrOp Op, string Opr)
  929. {
  930. return Opr + GetOperExpr(Op, Op.OperandA);
  931. }
  932. private string GetBinaryExpr(ShaderIrOp Op, string Opr)
  933. {
  934. return GetOperExpr(Op, Op.OperandA) + " " + Opr + " " +
  935. GetOperExpr(Op, Op.OperandB);
  936. }
  937. private string GetBinaryExprWithNaN(ShaderIrOp Op, string Opr)
  938. {
  939. string A = GetOperExpr(Op, Op.OperandA);
  940. string B = GetOperExpr(Op, Op.OperandB);
  941. string NaNCheck =
  942. " || isnan(" + A + ")" +
  943. " || isnan(" + B + ")";
  944. return A + " " + Opr + " " + B + NaNCheck;
  945. }
  946. private string GetTernaryExpr(ShaderIrOp Op, string Opr1, string Opr2)
  947. {
  948. return GetOperExpr(Op, Op.OperandA) + " " + Opr1 + " " +
  949. GetOperExpr(Op, Op.OperandB) + " " + Opr2 + " " +
  950. GetOperExpr(Op, Op.OperandC);
  951. }
  952. private string GetTexSamplerName(ShaderIrOp Op)
  953. {
  954. ShaderIrOperImm Node = (ShaderIrOperImm)Op.OperandC;
  955. int Handle = ((ShaderIrOperImm)Op.OperandC).Value;
  956. if (!Decl.Textures.TryGetValue(Handle, out ShaderDeclInfo DeclInfo))
  957. {
  958. throw new InvalidOperationException();
  959. }
  960. return DeclInfo.Name;
  961. }
  962. private string GetTexSamplerCoords(ShaderIrOp Op)
  963. {
  964. return "vec2(" + GetOperExpr(Op, Op.OperandA) + ", " +
  965. GetOperExpr(Op, Op.OperandB) + ")";
  966. }
  967. private string GetITexSamplerCoords(ShaderIrOp Op)
  968. {
  969. return "ivec2(" + GetOperExpr(Op, Op.OperandA) + ", " +
  970. GetOperExpr(Op, Op.OperandB) + ")";
  971. }
  972. private string GetOperExpr(ShaderIrOp Op, ShaderIrNode Oper)
  973. {
  974. return GetExprWithCast(Op, Oper, GetSrcExpr(Oper));
  975. }
  976. private static string GetExprWithCast(ShaderIrNode Dst, ShaderIrNode Src, string Expr)
  977. {
  978. //Note: The "DstType" (of the cast) is the type that the operation
  979. //uses on the source operands, while the "SrcType" is the destination
  980. //type of the operand result (if it is a operation) or just the type
  981. //of the variable for registers/uniforms/attributes.
  982. OperType DstType = GetSrcNodeType(Dst);
  983. OperType SrcType = GetDstNodeType(Src);
  984. if (DstType != SrcType)
  985. {
  986. //Check for invalid casts
  987. //(like bool to int/float and others).
  988. if (SrcType != OperType.F32 &&
  989. SrcType != OperType.I32)
  990. {
  991. throw new InvalidOperationException();
  992. }
  993. switch (Src)
  994. {
  995. case ShaderIrOperGpr Gpr:
  996. {
  997. //When the Gpr is ZR, just return the 0 value directly,
  998. //since the float encoding for 0 is 0.
  999. if (Gpr.IsConst)
  1000. {
  1001. return "0";
  1002. }
  1003. break;
  1004. }
  1005. case ShaderIrOperImm Imm:
  1006. {
  1007. //For integer immediates being used as float,
  1008. //it's better (for readability) to just return the float value.
  1009. if (DstType == OperType.F32)
  1010. {
  1011. float Value = BitConverter.Int32BitsToSingle(Imm.Value);
  1012. if (!float.IsNaN(Value) && !float.IsInfinity(Value))
  1013. {
  1014. return GetFloatConst(Value);
  1015. }
  1016. }
  1017. break;
  1018. }
  1019. }
  1020. switch (DstType)
  1021. {
  1022. case OperType.F32: Expr = "intBitsToFloat(" + Expr + ")"; break;
  1023. case OperType.I32: Expr = "floatBitsToInt(" + Expr + ")"; break;
  1024. }
  1025. }
  1026. return Expr;
  1027. }
  1028. private static string GetIntConst(int Value)
  1029. {
  1030. string Expr = Value.ToString(CultureInfo.InvariantCulture);
  1031. return Value < 0 ? "(" + Expr + ")" : Expr;
  1032. }
  1033. private static string GetFloatConst(float Value)
  1034. {
  1035. string Expr = Value.ToString(CultureInfo.InvariantCulture);
  1036. return Value < 0 ? "(" + Expr + ")" : Expr;
  1037. }
  1038. private static OperType GetDstNodeType(ShaderIrNode Node)
  1039. {
  1040. //Special case instructions with the result type different
  1041. //from the input types (like integer <-> float conversion) here.
  1042. if (Node is ShaderIrOp Op)
  1043. {
  1044. switch (Op.Inst)
  1045. {
  1046. case ShaderIrInst.Stof:
  1047. case ShaderIrInst.Txlf:
  1048. case ShaderIrInst.Utof:
  1049. return OperType.F32;
  1050. case ShaderIrInst.Ftos:
  1051. case ShaderIrInst.Ftou:
  1052. return OperType.I32;
  1053. }
  1054. }
  1055. return GetSrcNodeType(Node);
  1056. }
  1057. private static OperType GetSrcNodeType(ShaderIrNode Node)
  1058. {
  1059. switch (Node)
  1060. {
  1061. case ShaderIrOperAbuf Abuf:
  1062. return Abuf.Offs == GlslDecl.LayerAttr ||
  1063. Abuf.Offs == GlslDecl.InstanceIdAttr ||
  1064. Abuf.Offs == GlslDecl.VertexIdAttr ||
  1065. Abuf.Offs == GlslDecl.FaceAttr
  1066. ? OperType.I32
  1067. : OperType.F32;
  1068. case ShaderIrOperCbuf Cbuf: return OperType.F32;
  1069. case ShaderIrOperGpr Gpr: return OperType.F32;
  1070. case ShaderIrOperImm Imm: return OperType.I32;
  1071. case ShaderIrOperImmf Immf: return OperType.F32;
  1072. case ShaderIrOperPred Pred: return OperType.Bool;
  1073. case ShaderIrOp Op:
  1074. if (Op.Inst > ShaderIrInst.B_Start &&
  1075. Op.Inst < ShaderIrInst.B_End)
  1076. {
  1077. return OperType.Bool;
  1078. }
  1079. else if (Op.Inst > ShaderIrInst.F_Start &&
  1080. Op.Inst < ShaderIrInst.F_End)
  1081. {
  1082. return OperType.F32;
  1083. }
  1084. else if (Op.Inst > ShaderIrInst.I_Start &&
  1085. Op.Inst < ShaderIrInst.I_End)
  1086. {
  1087. return OperType.I32;
  1088. }
  1089. break;
  1090. }
  1091. throw new ArgumentException(nameof(Node));
  1092. }
  1093. private static string GetBlockPosition(ShaderIrBlock Block)
  1094. {
  1095. if (Block != null)
  1096. {
  1097. return "0x" + Block.Position.ToString("x8") + "u";
  1098. }
  1099. else
  1100. {
  1101. return "0u";
  1102. }
  1103. }
  1104. }
  1105. }