GlslDecompiler.cs 46 KB

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