GlslDecompiler.cs 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014
  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 static string[] ElemTypes = new string[] { "float", "vec2", "vec3", "vec4" };
  20. private GlslDecl Decl;
  21. private ShaderIrBlock[] Blocks;
  22. private StringBuilder SB;
  23. public GlslDecompiler()
  24. {
  25. InstsExpr = new Dictionary<ShaderIrInst, GetInstExpr>()
  26. {
  27. { ShaderIrInst.Abs, GetAbsExpr },
  28. { ShaderIrInst.Add, GetAddExpr },
  29. { ShaderIrInst.And, GetAndExpr },
  30. { ShaderIrInst.Asr, GetAsrExpr },
  31. { ShaderIrInst.Band, GetBandExpr },
  32. { ShaderIrInst.Bnot, GetBnotExpr },
  33. { ShaderIrInst.Bor, GetBorExpr },
  34. { ShaderIrInst.Bxor, GetBxorExpr },
  35. { ShaderIrInst.Ceil, GetCeilExpr },
  36. { ShaderIrInst.Ceq, GetCeqExpr },
  37. { ShaderIrInst.Cge, GetCgeExpr },
  38. { ShaderIrInst.Cgt, GetCgtExpr },
  39. { ShaderIrInst.Clamps, GetClampsExpr },
  40. { ShaderIrInst.Clampu, GetClampuExpr },
  41. { ShaderIrInst.Cle, GetCleExpr },
  42. { ShaderIrInst.Clt, GetCltExpr },
  43. { ShaderIrInst.Cne, GetCneExpr },
  44. { ShaderIrInst.Exit, GetExitExpr },
  45. { ShaderIrInst.Fabs, GetAbsExpr },
  46. { ShaderIrInst.Fadd, GetAddExpr },
  47. { ShaderIrInst.Fceq, GetCeqExpr },
  48. { ShaderIrInst.Fcequ, GetCequExpr },
  49. { ShaderIrInst.Fcge, GetCgeExpr },
  50. { ShaderIrInst.Fcgeu, GetCgeuExpr },
  51. { ShaderIrInst.Fcgt, GetCgtExpr },
  52. { ShaderIrInst.Fcgtu, GetCgtuExpr },
  53. { ShaderIrInst.Fclamp, GetFclampExpr },
  54. { ShaderIrInst.Fcle, GetCleExpr },
  55. { ShaderIrInst.Fcleu, GetCleuExpr },
  56. { ShaderIrInst.Fclt, GetCltExpr },
  57. { ShaderIrInst.Fcltu, GetCltuExpr },
  58. { ShaderIrInst.Fcnan, GetCnanExpr },
  59. { ShaderIrInst.Fcne, GetCneExpr },
  60. { ShaderIrInst.Fcneu, GetCneuExpr },
  61. { ShaderIrInst.Fcnum, GetCnumExpr },
  62. { ShaderIrInst.Fcos, GetFcosExpr },
  63. { ShaderIrInst.Fex2, GetFex2Expr },
  64. { ShaderIrInst.Ffma, GetFfmaExpr },
  65. { ShaderIrInst.Flg2, GetFlg2Expr },
  66. { ShaderIrInst.Floor, GetFloorExpr },
  67. { ShaderIrInst.Fmax, GetMaxExpr },
  68. { ShaderIrInst.Fmin, GetMinExpr },
  69. { ShaderIrInst.Fmul, GetMulExpr },
  70. { ShaderIrInst.Fneg, GetNegExpr },
  71. { ShaderIrInst.Frcp, GetFrcpExpr },
  72. { ShaderIrInst.Frsq, GetFrsqExpr },
  73. { ShaderIrInst.Fsin, GetFsinExpr },
  74. { ShaderIrInst.Fsqrt, GetFsqrtExpr },
  75. { ShaderIrInst.Ftos, GetFtosExpr },
  76. { ShaderIrInst.Ftou, GetFtouExpr },
  77. { ShaderIrInst.Ipa, GetIpaExpr },
  78. { ShaderIrInst.Kil, GetKilExpr },
  79. { ShaderIrInst.Lsl, GetLslExpr },
  80. { ShaderIrInst.Lsr, GetLsrExpr },
  81. { ShaderIrInst.Max, GetMaxExpr },
  82. { ShaderIrInst.Min, GetMinExpr },
  83. { ShaderIrInst.Mul, GetMulExpr },
  84. { ShaderIrInst.Neg, GetNegExpr },
  85. { ShaderIrInst.Not, GetNotExpr },
  86. { ShaderIrInst.Or, GetOrExpr },
  87. { ShaderIrInst.Stof, GetStofExpr },
  88. { ShaderIrInst.Sub, GetSubExpr },
  89. { ShaderIrInst.Texq, GetTexqExpr },
  90. { ShaderIrInst.Texs, GetTexsExpr },
  91. { ShaderIrInst.Trunc, GetTruncExpr },
  92. { ShaderIrInst.Txlf, GetTxlfExpr },
  93. { ShaderIrInst.Utof, GetUtofExpr },
  94. { ShaderIrInst.Xor, GetXorExpr }
  95. };
  96. }
  97. public GlslProgram Decompile(IGalMemory Memory, long Position, GalShaderType ShaderType)
  98. {
  99. Blocks = ShaderDecoder.Decode(Memory, Position);
  100. Decl = new GlslDecl(Blocks, ShaderType);
  101. SB = new StringBuilder();
  102. SB.AppendLine("#version 410 core");
  103. PrintDeclTextures();
  104. PrintDeclUniforms();
  105. PrintDeclInAttributes();
  106. PrintDeclOutAttributes();
  107. PrintDeclGprs();
  108. PrintDeclPreds();
  109. PrintBlockScope(Blocks[0], null, null, "void main()", IdentationStr);
  110. string GlslCode = SB.ToString();
  111. return new GlslProgram(
  112. GlslCode,
  113. Decl.Textures.Values,
  114. Decl.Uniforms.Values);
  115. }
  116. private void PrintDeclTextures()
  117. {
  118. PrintDecls(Decl.Textures, "uniform sampler2D");
  119. }
  120. private void PrintDeclUniforms()
  121. {
  122. if (Decl.ShaderType == GalShaderType.Vertex)
  123. {
  124. SB.AppendLine("uniform vec2 " + GlslDecl.FlipUniformName + ";");
  125. }
  126. foreach (ShaderDeclInfo DeclInfo in Decl.Uniforms.Values.OrderBy(DeclKeySelector))
  127. {
  128. SB.AppendLine($"uniform {GetDecl(DeclInfo)}[{DeclInfo.Index + 1}];");
  129. }
  130. if (Decl.Uniforms.Count > 0)
  131. {
  132. SB.AppendLine();
  133. }
  134. }
  135. private void PrintDeclInAttributes()
  136. {
  137. if (Decl.ShaderType == GalShaderType.Fragment)
  138. {
  139. SB.AppendLine("in vec4 " + GlslDecl.PositionOutAttrName + ";");
  140. }
  141. PrintDeclAttributes(Decl.InAttributes.Values, "in");
  142. }
  143. private void PrintDeclOutAttributes()
  144. {
  145. if (Decl.ShaderType == GalShaderType.Vertex)
  146. {
  147. SB.AppendLine("out vec4 " + GlslDecl.PositionOutAttrName + ";");
  148. }
  149. PrintDeclAttributes(Decl.OutAttributes.Values, "out");
  150. }
  151. private void PrintDeclAttributes(IEnumerable<ShaderDeclInfo> Decls, string InOut)
  152. {
  153. int Count = 0;
  154. foreach (ShaderDeclInfo DeclInfo in Decls.OrderBy(DeclKeySelector))
  155. {
  156. if (DeclInfo.Index >= 0)
  157. {
  158. SB.AppendLine("layout (location = " + DeclInfo.Index + ") " + InOut + " " + GetDecl(DeclInfo) + ";");
  159. Count++;
  160. }
  161. }
  162. if (Count > 0)
  163. {
  164. SB.AppendLine();
  165. }
  166. }
  167. private void PrintDeclGprs()
  168. {
  169. PrintDecls(Decl.Gprs);
  170. }
  171. private void PrintDeclPreds()
  172. {
  173. PrintDecls(Decl.Preds, "bool");
  174. }
  175. private void PrintDecls(IReadOnlyDictionary<int, ShaderDeclInfo> Dict, string CustomType = null)
  176. {
  177. foreach (ShaderDeclInfo DeclInfo in Dict.Values.OrderBy(DeclKeySelector))
  178. {
  179. string Name;
  180. if (CustomType != null)
  181. {
  182. Name = CustomType + " " + DeclInfo.Name + ";";
  183. }
  184. else if (DeclInfo.Name == GlslDecl.FragmentOutputName)
  185. {
  186. Name = "layout (location = 0) out " + GetDecl(DeclInfo) + ";" + Environment.NewLine;
  187. }
  188. else
  189. {
  190. Name = GetDecl(DeclInfo) + ";";
  191. }
  192. SB.AppendLine(Name);
  193. }
  194. if (Dict.Count > 0)
  195. {
  196. SB.AppendLine();
  197. }
  198. }
  199. private int DeclKeySelector(ShaderDeclInfo DeclInfo)
  200. {
  201. return DeclInfo.Cbuf << 24 | DeclInfo.Index;
  202. }
  203. private string GetDecl(ShaderDeclInfo DeclInfo)
  204. {
  205. return ElemTypes[DeclInfo.Size - 1] + " " + DeclInfo.Name;
  206. }
  207. private void PrintBlockScope(
  208. ShaderIrBlock Block,
  209. ShaderIrBlock EndBlock,
  210. ShaderIrBlock LoopBlock,
  211. string ScopeName,
  212. string Identation,
  213. bool IsDoWhile = false)
  214. {
  215. string UpIdent = Identation.Substring(0, Identation.Length - IdentationStr.Length);
  216. if (IsDoWhile)
  217. {
  218. SB.AppendLine(UpIdent + "do {");
  219. }
  220. else
  221. {
  222. SB.AppendLine(UpIdent + ScopeName + " {");
  223. }
  224. while (Block != null && Block != EndBlock)
  225. {
  226. ShaderIrNode[] Nodes = Block.GetNodes();
  227. Block = PrintNodes(Block, EndBlock, LoopBlock, Identation, Nodes);
  228. }
  229. if (IsDoWhile)
  230. {
  231. SB.AppendLine(UpIdent + "} " + ScopeName + ";");
  232. }
  233. else
  234. {
  235. SB.AppendLine(UpIdent + "}");
  236. }
  237. }
  238. private ShaderIrBlock PrintNodes(
  239. ShaderIrBlock Block,
  240. ShaderIrBlock EndBlock,
  241. ShaderIrBlock LoopBlock,
  242. string Identation,
  243. params ShaderIrNode[] Nodes)
  244. {
  245. /*
  246. * Notes about control flow and if-else/loop generation:
  247. * The code assumes that the program has sane control flow,
  248. * that is, there's no jumps to a location after another jump or
  249. * jump target (except for the end of an if-else block), and backwards
  250. * jumps to a location before the last loop dominator.
  251. * Such cases needs to be transformed on a step before the GLSL code
  252. * generation to ensure that we have sane graphs to work with.
  253. * TODO: Such transformation is not yet implemented.
  254. */
  255. string NewIdent = Identation + IdentationStr;
  256. ShaderIrBlock LoopTail = GetLoopTailBlock(Block);
  257. if (LoopTail != null && LoopBlock != Block)
  258. {
  259. //Shoock! kuma shock! We have a loop here!
  260. //The entire sequence needs to be inside a do-while block.
  261. ShaderIrBlock LoopEnd = GetDownBlock(LoopTail);
  262. PrintBlockScope(Block, LoopEnd, Block, "while (false)", NewIdent, IsDoWhile: true);
  263. return LoopEnd;
  264. }
  265. foreach (ShaderIrNode Node in Nodes)
  266. {
  267. if (Node is ShaderIrCond Cond)
  268. {
  269. string IfExpr = GetSrcExpr(Cond.Pred, true);
  270. if (Cond.Not)
  271. {
  272. IfExpr = "!(" + IfExpr + ")";
  273. }
  274. if (Cond.Child is ShaderIrOp Op && Op.Inst == ShaderIrInst.Bra)
  275. {
  276. //Branch is a loop branch and would result in infinite recursion.
  277. if (Block.Branch.Position <= Block.Position)
  278. {
  279. SB.AppendLine(Identation + "if (" + IfExpr + ") {");
  280. SB.AppendLine(Identation + IdentationStr + "continue;");
  281. SB.AppendLine(Identation + "}");
  282. continue;
  283. }
  284. string SubScopeName = "if (!" + IfExpr + ")";
  285. PrintBlockScope(Block.Next, Block.Branch, LoopBlock, SubScopeName, NewIdent);
  286. ShaderIrBlock IfElseEnd = GetUpBlock(Block.Branch).Branch;
  287. if (IfElseEnd?.Position > Block.Branch.Position)
  288. {
  289. PrintBlockScope(Block.Branch, IfElseEnd, LoopBlock, "else", NewIdent);
  290. return IfElseEnd;
  291. }
  292. return Block.Branch;
  293. }
  294. else
  295. {
  296. SB.AppendLine(Identation + "if (" + IfExpr + ") {");
  297. PrintNodes(Block, EndBlock, LoopBlock, NewIdent, Cond.Child);
  298. SB.AppendLine(Identation + "}");
  299. }
  300. }
  301. else if (Node is ShaderIrAsg Asg)
  302. {
  303. if (IsValidOutOper(Asg.Dst))
  304. {
  305. string Expr = GetSrcExpr(Asg.Src, true);
  306. Expr = GetExprWithCast(Asg.Dst, Asg.Src, Expr);
  307. SB.AppendLine(Identation + GetDstOperName(Asg.Dst) + " = " + Expr + ";");
  308. }
  309. }
  310. else if (Node is ShaderIrOp Op)
  311. {
  312. if (Op.Inst == ShaderIrInst.Bra)
  313. {
  314. if (Block.Branch.Position <= Block.Position)
  315. {
  316. SB.AppendLine(Identation + "continue;");
  317. }
  318. continue;
  319. }
  320. else if (Op.Inst == ShaderIrInst.Exit)
  321. {
  322. //Do everything that needs to be done before
  323. //the shader ends here.
  324. if (Decl.ShaderType == GalShaderType.Vertex)
  325. {
  326. SB.AppendLine(Identation + "gl_Position.xy *= flip;");
  327. SB.AppendLine(Identation + GlslDecl.PositionOutAttrName + " = gl_Position;");
  328. SB.AppendLine(Identation + GlslDecl.PositionOutAttrName + ".w = 1;");
  329. }
  330. }
  331. SB.AppendLine(Identation + GetSrcExpr(Op, true) + ";");
  332. }
  333. else if (Node is ShaderIrCmnt Cmnt)
  334. {
  335. SB.AppendLine(Identation + "// " + Cmnt.Comment);
  336. }
  337. else
  338. {
  339. throw new InvalidOperationException();
  340. }
  341. }
  342. return Block.Next;
  343. }
  344. private ShaderIrBlock GetUpBlock(ShaderIrBlock Block)
  345. {
  346. return Blocks.FirstOrDefault(x => x.EndPosition == Block.Position);
  347. }
  348. private ShaderIrBlock GetDownBlock(ShaderIrBlock Block)
  349. {
  350. return Blocks.FirstOrDefault(x => x.Position == Block.EndPosition);
  351. }
  352. private ShaderIrBlock GetLoopTailBlock(ShaderIrBlock LoopHead)
  353. {
  354. ShaderIrBlock Tail = null;
  355. foreach (ShaderIrBlock Block in LoopHead.Sources)
  356. {
  357. if (Block.Position >= LoopHead.Position)
  358. {
  359. if (Tail == null || Tail.Position < Block.Position)
  360. {
  361. Tail = Block;
  362. }
  363. }
  364. }
  365. return Tail;
  366. }
  367. private bool IsValidOutOper(ShaderIrNode Node)
  368. {
  369. if (Node is ShaderIrOperGpr Gpr && Gpr.IsConst)
  370. {
  371. return false;
  372. }
  373. else if (Node is ShaderIrOperPred Pred && Pred.IsConst)
  374. {
  375. return false;
  376. }
  377. return true;
  378. }
  379. private string GetDstOperName(ShaderIrNode Node)
  380. {
  381. if (Node is ShaderIrOperAbuf Abuf)
  382. {
  383. return GetOutAbufName(Abuf);
  384. }
  385. else if (Node is ShaderIrOperGpr Gpr)
  386. {
  387. return GetName(Gpr);
  388. }
  389. else if (Node is ShaderIrOperPred Pred)
  390. {
  391. return GetName(Pred);
  392. }
  393. throw new ArgumentException(nameof(Node));
  394. }
  395. private string GetSrcExpr(ShaderIrNode Node, bool Entry = false)
  396. {
  397. switch (Node)
  398. {
  399. case ShaderIrOperAbuf Abuf: return GetName (Abuf);
  400. case ShaderIrOperCbuf Cbuf: return GetName (Cbuf);
  401. case ShaderIrOperGpr Gpr: return GetName (Gpr);
  402. case ShaderIrOperImm Imm: return GetValue(Imm);
  403. case ShaderIrOperImmf Immf: return GetValue(Immf);
  404. case ShaderIrOperPred Pred: return GetName (Pred);
  405. case ShaderIrOp Op:
  406. string Expr;
  407. if (InstsExpr.TryGetValue(Op.Inst, out GetInstExpr GetExpr))
  408. {
  409. Expr = GetExpr(Op);
  410. }
  411. else
  412. {
  413. throw new NotImplementedException(Op.Inst.ToString());
  414. }
  415. if (!Entry && NeedsParentheses(Op))
  416. {
  417. Expr = "(" + Expr + ")";
  418. }
  419. return Expr;
  420. default: throw new ArgumentException(nameof(Node));
  421. }
  422. }
  423. private static bool NeedsParentheses(ShaderIrOp Op)
  424. {
  425. switch (Op.Inst)
  426. {
  427. case ShaderIrInst.Frcp:
  428. return true;
  429. case ShaderIrInst.Ipa:
  430. case ShaderIrInst.Texq:
  431. case ShaderIrInst.Texs:
  432. case ShaderIrInst.Txlf:
  433. return false;
  434. }
  435. return Op.OperandB != null ||
  436. Op.OperandC != null;
  437. }
  438. private string GetName(ShaderIrOperCbuf Cbuf)
  439. {
  440. if (!Decl.Uniforms.TryGetValue(Cbuf.Index, out ShaderDeclInfo DeclInfo))
  441. {
  442. throw new InvalidOperationException();
  443. }
  444. if (Cbuf.Offs != null)
  445. {
  446. //Note: We assume that the register value is always a multiple of 4.
  447. //This may not be aways the case.
  448. string Offset = "(floatBitsToInt(" + GetSrcExpr(Cbuf.Offs) + ") >> 2)";
  449. return DeclInfo.Name + "[" + Cbuf.Pos + " + " + Offset + "]";
  450. }
  451. else
  452. {
  453. return DeclInfo.Name + "[" + Cbuf.Pos + "]";
  454. }
  455. }
  456. private string GetOutAbufName(ShaderIrOperAbuf Abuf)
  457. {
  458. return GetName(Decl.OutAttributes, Abuf);
  459. }
  460. private string GetName(ShaderIrOperAbuf Abuf)
  461. {
  462. if (Decl.ShaderType == GalShaderType.Vertex)
  463. {
  464. switch (Abuf.Offs)
  465. {
  466. case GlslDecl.VertexIdAttr: return "gl_VertexID";
  467. case GlslDecl.InstanceIdAttr: return "gl_InstanceID";
  468. }
  469. }
  470. else if (Decl.ShaderType == GalShaderType.TessEvaluation)
  471. {
  472. switch (Abuf.Offs)
  473. {
  474. case GlslDecl.TessCoordAttrX: return "gl_TessCoord.x";
  475. case GlslDecl.TessCoordAttrY: return "gl_TessCoord.y";
  476. case GlslDecl.TessCoordAttrZ: return "gl_TessCoord.z";
  477. }
  478. }
  479. return GetName(Decl.InAttributes, Abuf);
  480. }
  481. private string GetName(IReadOnlyDictionary<int, ShaderDeclInfo> Dict, ShaderIrOperAbuf Abuf)
  482. {
  483. int Index = Abuf.Offs >> 4;
  484. int Elem = (Abuf.Offs >> 2) & 3;
  485. if (!Dict.TryGetValue(Index, out ShaderDeclInfo DeclInfo))
  486. {
  487. throw new InvalidOperationException();
  488. }
  489. return DeclInfo.Size > 1 ? DeclInfo.Name + "." + GetAttrSwizzle(Elem) : DeclInfo.Name;
  490. }
  491. private string GetName(ShaderIrOperGpr Gpr)
  492. {
  493. return Gpr.IsConst ? "0" : GetNameWithSwizzle(Decl.Gprs, Gpr.Index);
  494. }
  495. private string GetValue(ShaderIrOperImm Imm)
  496. {
  497. //Only use hex is the value is too big and would likely be hard to read as int.
  498. if (Imm.Value > 0xfff ||
  499. Imm.Value < -0xfff)
  500. {
  501. return "0x" + Imm.Value.ToString("x8", CultureInfo.InvariantCulture);
  502. }
  503. else
  504. {
  505. return Imm.Value.ToString(CultureInfo.InvariantCulture);
  506. }
  507. }
  508. private string GetValue(ShaderIrOperImmf Immf)
  509. {
  510. return Immf.Value.ToString(CultureInfo.InvariantCulture);
  511. }
  512. private string GetName(ShaderIrOperPred Pred)
  513. {
  514. return Pred.IsConst ? "true" : GetNameWithSwizzle(Decl.Preds, Pred.Index);
  515. }
  516. private string GetNameWithSwizzle(IReadOnlyDictionary<int, ShaderDeclInfo> Dict, int Index)
  517. {
  518. int VecIndex = Index >> 2;
  519. if (Dict.TryGetValue(VecIndex, out ShaderDeclInfo DeclInfo))
  520. {
  521. if (DeclInfo.Size > 1 && Index < VecIndex + DeclInfo.Size)
  522. {
  523. return DeclInfo.Name + "." + GetAttrSwizzle(Index & 3);
  524. }
  525. }
  526. if (!Dict.TryGetValue(Index, out DeclInfo))
  527. {
  528. throw new InvalidOperationException();
  529. }
  530. return DeclInfo.Name;
  531. }
  532. private string GetAttrSwizzle(int Elem)
  533. {
  534. return "xyzw".Substring(Elem, 1);
  535. }
  536. private string GetAbsExpr(ShaderIrOp Op) => GetUnaryCall(Op, "abs");
  537. private string GetAddExpr(ShaderIrOp Op) => GetBinaryExpr(Op, "+");
  538. private string GetAndExpr(ShaderIrOp Op) => GetBinaryExpr(Op, "&");
  539. private string GetAsrExpr(ShaderIrOp Op) => GetBinaryExpr(Op, ">>");
  540. private string GetBandExpr(ShaderIrOp Op) => GetBinaryExpr(Op, "&&");
  541. private string GetBnotExpr(ShaderIrOp Op) => GetUnaryExpr(Op, "!");
  542. private string GetBorExpr(ShaderIrOp Op) => GetBinaryExpr(Op, "||");
  543. private string GetBxorExpr(ShaderIrOp Op) => GetBinaryExpr(Op, "^^");
  544. private string GetCeilExpr(ShaderIrOp Op) => GetUnaryCall(Op, "ceil");
  545. private string GetClampsExpr(ShaderIrOp Op)
  546. {
  547. return "clamp(" + GetOperExpr(Op, Op.OperandA) + ", " +
  548. GetOperExpr(Op, Op.OperandB) + ", " +
  549. GetOperExpr(Op, Op.OperandC) + ")";
  550. }
  551. private string GetClampuExpr(ShaderIrOp Op)
  552. {
  553. return "int(clamp(uint(" + GetOperExpr(Op, Op.OperandA) + "), " +
  554. "uint(" + GetOperExpr(Op, Op.OperandB) + "), " +
  555. "uint(" + GetOperExpr(Op, Op.OperandC) + ")))";
  556. }
  557. private string GetCeqExpr(ShaderIrOp Op) => GetBinaryExpr(Op, "==");
  558. private string GetCequExpr(ShaderIrOp Op) => GetBinaryExprWithNaN(Op, "==");
  559. private string GetCgeExpr(ShaderIrOp Op) => GetBinaryExpr(Op, ">=");
  560. private string GetCgeuExpr(ShaderIrOp Op) => GetBinaryExprWithNaN(Op, ">=");
  561. private string GetCgtExpr(ShaderIrOp Op) => GetBinaryExpr(Op, ">");
  562. private string GetCgtuExpr(ShaderIrOp Op) => GetBinaryExprWithNaN(Op, ">");
  563. private string GetCleExpr(ShaderIrOp Op) => GetBinaryExpr(Op, "<=");
  564. private string GetCleuExpr(ShaderIrOp Op) => GetBinaryExprWithNaN(Op, "<=");
  565. private string GetCltExpr(ShaderIrOp Op) => GetBinaryExpr(Op, "<");
  566. private string GetCltuExpr(ShaderIrOp Op) => GetBinaryExprWithNaN(Op, "<");
  567. private string GetCnanExpr(ShaderIrOp Op) => GetUnaryCall(Op, "isnan");
  568. private string GetCneExpr(ShaderIrOp Op) => GetBinaryExpr(Op, "!=");
  569. private string GetCneuExpr(ShaderIrOp Op) => GetBinaryExprWithNaN(Op, "!=");
  570. private string GetCnumExpr(ShaderIrOp Op) => GetUnaryCall(Op, "!isnan");
  571. private string GetExitExpr(ShaderIrOp Op) => "return";
  572. private string GetFcosExpr(ShaderIrOp Op) => GetUnaryCall(Op, "cos");
  573. private string GetFex2Expr(ShaderIrOp Op) => GetUnaryCall(Op, "exp2");
  574. private string GetFfmaExpr(ShaderIrOp Op) => GetTernaryExpr(Op, "*", "+");
  575. private string GetFclampExpr(ShaderIrOp Op) => GetTernaryCall(Op, "clamp");
  576. private string GetFlg2Expr(ShaderIrOp Op) => GetUnaryCall(Op, "log2");
  577. private string GetFloorExpr(ShaderIrOp Op) => GetUnaryCall(Op, "floor");
  578. private string GetFrcpExpr(ShaderIrOp Op) => GetUnaryExpr(Op, "1 / ");
  579. private string GetFrsqExpr(ShaderIrOp Op) => GetUnaryCall(Op, "inversesqrt");
  580. private string GetFsinExpr(ShaderIrOp Op) => GetUnaryCall(Op, "sin");
  581. private string GetFsqrtExpr(ShaderIrOp Op) => GetUnaryCall(Op, "sqrt");
  582. private string GetFtosExpr(ShaderIrOp Op)
  583. {
  584. return "int(" + GetOperExpr(Op, Op.OperandA) + ")";
  585. }
  586. private string GetFtouExpr(ShaderIrOp Op)
  587. {
  588. return "int(uint(" + GetOperExpr(Op, Op.OperandA) + "))";
  589. }
  590. private string GetIpaExpr(ShaderIrOp Op) => GetSrcExpr(Op.OperandA);
  591. private string GetKilExpr(ShaderIrOp Op) => "discard";
  592. private string GetLslExpr(ShaderIrOp Op) => GetBinaryExpr(Op, "<<");
  593. private string GetLsrExpr(ShaderIrOp Op)
  594. {
  595. return "int(uint(" + GetOperExpr(Op, Op.OperandA) + ") >> " +
  596. GetOperExpr(Op, Op.OperandB) + ")";
  597. }
  598. private string GetMaxExpr(ShaderIrOp Op) => GetBinaryCall(Op, "max");
  599. private string GetMinExpr(ShaderIrOp Op) => GetBinaryCall(Op, "min");
  600. private string GetMulExpr(ShaderIrOp Op) => GetBinaryExpr(Op, "*");
  601. private string GetNegExpr(ShaderIrOp Op) => GetUnaryExpr(Op, "-");
  602. private string GetNotExpr(ShaderIrOp Op) => GetUnaryExpr(Op, "~");
  603. private string GetOrExpr(ShaderIrOp Op) => GetBinaryExpr(Op, "|");
  604. private string GetStofExpr(ShaderIrOp Op)
  605. {
  606. return "float(" + GetOperExpr(Op, Op.OperandA) + ")";
  607. }
  608. private string GetSubExpr(ShaderIrOp Op) => GetBinaryExpr(Op, "-");
  609. private string GetTexqExpr(ShaderIrOp Op)
  610. {
  611. ShaderIrMetaTexq Meta = (ShaderIrMetaTexq)Op.MetaData;
  612. string Ch = "xyzw".Substring(Meta.Elem, 1);
  613. if (Meta.Info == ShaderTexqInfo.Dimension)
  614. {
  615. string Sampler = GetTexSamplerName(Op);
  616. string Lod = GetOperExpr(Op, Op.OperandA); //???
  617. return "textureSize(" + Sampler + ", " + Lod + ")." + Ch;
  618. }
  619. else
  620. {
  621. throw new NotImplementedException(Meta.Info.ToString());
  622. }
  623. }
  624. private string GetTexsExpr(ShaderIrOp Op)
  625. {
  626. ShaderIrMetaTex Meta = (ShaderIrMetaTex)Op.MetaData;
  627. string Sampler = GetTexSamplerName(Op);
  628. string Coords = GetTexSamplerCoords(Op);
  629. string Ch = "rgba".Substring(Meta.Elem, 1);
  630. return "texture(" + Sampler + ", " + Coords + ")." + Ch;
  631. }
  632. private string GetTxlfExpr(ShaderIrOp Op)
  633. {
  634. ShaderIrMetaTex Meta = (ShaderIrMetaTex)Op.MetaData;
  635. string Sampler = GetTexSamplerName(Op);
  636. string Coords = GetITexSamplerCoords(Op);
  637. string Ch = "rgba".Substring(Meta.Elem, 1);
  638. return "texelFetch(" + Sampler + ", " + Coords + ", 0)." + Ch;
  639. }
  640. private string GetTruncExpr(ShaderIrOp Op) => GetUnaryCall(Op, "trunc");
  641. private string GetUtofExpr(ShaderIrOp Op)
  642. {
  643. return "float(uint(" + GetOperExpr(Op, Op.OperandA) + "))";
  644. }
  645. private string GetXorExpr(ShaderIrOp Op) => GetBinaryExpr(Op, "^");
  646. private string GetUnaryCall(ShaderIrOp Op, string FuncName)
  647. {
  648. return FuncName + "(" + GetOperExpr(Op, Op.OperandA) + ")";
  649. }
  650. private string GetBinaryCall(ShaderIrOp Op, string FuncName)
  651. {
  652. return FuncName + "(" + GetOperExpr(Op, Op.OperandA) + ", " +
  653. GetOperExpr(Op, Op.OperandB) + ")";
  654. }
  655. private string GetTernaryCall(ShaderIrOp Op, string FuncName)
  656. {
  657. return FuncName + "(" + GetOperExpr(Op, Op.OperandA) + ", " +
  658. GetOperExpr(Op, Op.OperandB) + ", " +
  659. GetOperExpr(Op, Op.OperandC) + ")";
  660. }
  661. private string GetUnaryExpr(ShaderIrOp Op, string Opr)
  662. {
  663. return Opr + GetOperExpr(Op, Op.OperandA);
  664. }
  665. private string GetBinaryExpr(ShaderIrOp Op, string Opr)
  666. {
  667. return GetOperExpr(Op, Op.OperandA) + " " + Opr + " " +
  668. GetOperExpr(Op, Op.OperandB);
  669. }
  670. private string GetBinaryExprWithNaN(ShaderIrOp Op, string Opr)
  671. {
  672. string A = GetOperExpr(Op, Op.OperandA);
  673. string B = GetOperExpr(Op, Op.OperandB);
  674. string NaNCheck =
  675. " || isnan(" + A + ")" +
  676. " || isnan(" + B + ")";
  677. return A + " " + Opr + " " + B + NaNCheck;
  678. }
  679. private string GetTernaryExpr(ShaderIrOp Op, string Opr1, string Opr2)
  680. {
  681. return GetOperExpr(Op, Op.OperandA) + " " + Opr1 + " " +
  682. GetOperExpr(Op, Op.OperandB) + " " + Opr2 + " " +
  683. GetOperExpr(Op, Op.OperandC);
  684. }
  685. private string GetTexSamplerName(ShaderIrOp Op)
  686. {
  687. ShaderIrOperImm Node = (ShaderIrOperImm)Op.OperandC;
  688. int Handle = ((ShaderIrOperImm)Op.OperandC).Value;
  689. if (!Decl.Textures.TryGetValue(Handle, out ShaderDeclInfo DeclInfo))
  690. {
  691. throw new InvalidOperationException();
  692. }
  693. return DeclInfo.Name;
  694. }
  695. private string GetTexSamplerCoords(ShaderIrOp Op)
  696. {
  697. return "vec2(" + GetOperExpr(Op, Op.OperandA) + ", " +
  698. GetOperExpr(Op, Op.OperandB) + ")";
  699. }
  700. private string GetITexSamplerCoords(ShaderIrOp Op)
  701. {
  702. return "ivec2(" + GetOperExpr(Op, Op.OperandA) + ", " +
  703. GetOperExpr(Op, Op.OperandB) + ")";
  704. }
  705. private string GetOperExpr(ShaderIrOp Op, ShaderIrNode Oper)
  706. {
  707. return GetExprWithCast(Op, Oper, GetSrcExpr(Oper));
  708. }
  709. private static string GetExprWithCast(ShaderIrNode Dst, ShaderIrNode Src, string Expr)
  710. {
  711. //Note: The "DstType" (of the cast) is the type that the operation
  712. //uses on the source operands, while the "SrcType" is the destination
  713. //type of the operand result (if it is a operation) or just the type
  714. //of the variable for registers/uniforms/attributes.
  715. OperType DstType = GetSrcNodeType(Dst);
  716. OperType SrcType = GetDstNodeType(Src);
  717. if (DstType != SrcType)
  718. {
  719. //Check for invalid casts
  720. //(like bool to int/float and others).
  721. if (SrcType != OperType.F32 &&
  722. SrcType != OperType.I32)
  723. {
  724. throw new InvalidOperationException();
  725. }
  726. switch (Src)
  727. {
  728. case ShaderIrOperGpr Gpr:
  729. {
  730. //When the Gpr is ZR, just return the 0 value directly,
  731. //since the float encoding for 0 is 0.
  732. if (Gpr.IsConst)
  733. {
  734. return "0";
  735. }
  736. break;
  737. }
  738. case ShaderIrOperImm Imm:
  739. {
  740. //For integer immediates being used as float,
  741. //it's better (for readability) to just return the float value.
  742. if (DstType == OperType.F32)
  743. {
  744. float Value = BitConverter.Int32BitsToSingle(Imm.Value);
  745. if (!float.IsNaN(Value) && !float.IsInfinity(Value))
  746. {
  747. return Value.ToString(CultureInfo.InvariantCulture);
  748. }
  749. }
  750. break;
  751. }
  752. }
  753. switch (DstType)
  754. {
  755. case OperType.F32: Expr = "intBitsToFloat(" + Expr + ")"; break;
  756. case OperType.I32: Expr = "floatBitsToInt(" + Expr + ")"; break;
  757. }
  758. }
  759. return Expr;
  760. }
  761. private static OperType GetDstNodeType(ShaderIrNode Node)
  762. {
  763. //Special case instructions with the result type different
  764. //from the input types (like integer <-> float conversion) here.
  765. if (Node is ShaderIrOp Op)
  766. {
  767. switch (Op.Inst)
  768. {
  769. case ShaderIrInst.Stof:
  770. case ShaderIrInst.Txlf:
  771. case ShaderIrInst.Utof:
  772. return OperType.F32;
  773. case ShaderIrInst.Ftos:
  774. case ShaderIrInst.Ftou:
  775. return OperType.I32;
  776. }
  777. }
  778. return GetSrcNodeType(Node);
  779. }
  780. private static OperType GetSrcNodeType(ShaderIrNode Node)
  781. {
  782. switch (Node)
  783. {
  784. case ShaderIrOperAbuf Abuf:
  785. return Abuf.Offs == GlslDecl.VertexIdAttr ||
  786. Abuf.Offs == GlslDecl.InstanceIdAttr
  787. ? OperType.I32
  788. : OperType.F32;
  789. case ShaderIrOperCbuf Cbuf: return OperType.F32;
  790. case ShaderIrOperGpr Gpr: return OperType.F32;
  791. case ShaderIrOperImm Imm: return OperType.I32;
  792. case ShaderIrOperImmf Immf: return OperType.F32;
  793. case ShaderIrOperPred Pred: return OperType.Bool;
  794. case ShaderIrOp Op:
  795. if (Op.Inst > ShaderIrInst.B_Start &&
  796. Op.Inst < ShaderIrInst.B_End)
  797. {
  798. return OperType.Bool;
  799. }
  800. else if (Op.Inst > ShaderIrInst.F_Start &&
  801. Op.Inst < ShaderIrInst.F_End)
  802. {
  803. return OperType.F32;
  804. }
  805. else if (Op.Inst > ShaderIrInst.I_Start &&
  806. Op.Inst < ShaderIrInst.I_End)
  807. {
  808. return OperType.I32;
  809. }
  810. break;
  811. }
  812. throw new ArgumentException(nameof(Node));
  813. }
  814. }
  815. }