shader_ir.h 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891
  1. // Copyright 2018 yuzu Emulator Project
  2. // Licensed under GPLv2 or any later version
  3. // Refer to the license.txt file included.
  4. #pragma once
  5. #include <array>
  6. #include <cstring>
  7. #include <map>
  8. #include <optional>
  9. #include <set>
  10. #include <string>
  11. #include <tuple>
  12. #include <variant>
  13. #include <vector>
  14. #include "common/common_types.h"
  15. #include "video_core/engines/maxwell_3d.h"
  16. #include "video_core/engines/shader_bytecode.h"
  17. #include "video_core/engines/shader_header.h"
  18. namespace VideoCommon::Shader {
  19. class OperationNode;
  20. class ConditionalNode;
  21. class GprNode;
  22. class ImmediateNode;
  23. class InternalFlagNode;
  24. class PredicateNode;
  25. class AbufNode; ///< Attribute buffer
  26. class CbufNode; ///< Constant buffer
  27. class LmemNode; ///< Local memory
  28. class GmemNode; ///< Global memory
  29. class CommentNode;
  30. using ProgramCode = std::vector<u64>;
  31. using NodeData =
  32. std::variant<OperationNode, ConditionalNode, GprNode, ImmediateNode, InternalFlagNode,
  33. PredicateNode, AbufNode, CbufNode, LmemNode, GmemNode, CommentNode>;
  34. using Node = const NodeData*;
  35. using Node4 = std::array<Node, 4>;
  36. using NodeBlock = std::vector<Node>;
  37. constexpr u32 MAX_PROGRAM_LENGTH = 0x1000;
  38. enum class OperationCode {
  39. Assign, /// (float& dest, float src) -> void
  40. Select, /// (MetaArithmetic, bool pred, float a, float b) -> float
  41. FAdd, /// (MetaArithmetic, float a, float b) -> float
  42. FMul, /// (MetaArithmetic, float a, float b) -> float
  43. FDiv, /// (MetaArithmetic, float a, float b) -> float
  44. FFma, /// (MetaArithmetic, float a, float b, float c) -> float
  45. FNegate, /// (MetaArithmetic, float a) -> float
  46. FAbsolute, /// (MetaArithmetic, float a) -> float
  47. FClamp, /// (MetaArithmetic, float value, float min, float max) -> float
  48. FMin, /// (MetaArithmetic, float a, float b) -> float
  49. FMax, /// (MetaArithmetic, float a, float b) -> float
  50. FCos, /// (MetaArithmetic, float a) -> float
  51. FSin, /// (MetaArithmetic, float a) -> float
  52. FExp2, /// (MetaArithmetic, float a) -> float
  53. FLog2, /// (MetaArithmetic, float a) -> float
  54. FInverseSqrt, /// (MetaArithmetic, float a) -> float
  55. FSqrt, /// (MetaArithmetic, float a) -> float
  56. FRoundEven, /// (MetaArithmetic, float a) -> float
  57. FFloor, /// (MetaArithmetic, float a) -> float
  58. FCeil, /// (MetaArithmetic, float a) -> float
  59. FTrunc, /// (MetaArithmetic, float a) -> float
  60. FCastInteger, /// (MetaArithmetic, int a) -> float
  61. FCastUInteger, /// (MetaArithmetic, uint a) -> float
  62. IAdd, /// (MetaArithmetic, int a, int b) -> int
  63. IMul, /// (MetaArithmetic, int a, int b) -> int
  64. IDiv, /// (MetaArithmetic, int a, int b) -> int
  65. INegate, /// (MetaArithmetic, int a) -> int
  66. IAbsolute, /// (MetaArithmetic, int a) -> int
  67. IMin, /// (MetaArithmetic, int a, int b) -> int
  68. IMax, /// (MetaArithmetic, int a, int b) -> int
  69. ICastFloat, /// (MetaArithmetic, float a) -> int
  70. ICastUnsigned, /// (MetaArithmetic, uint a) -> int
  71. ILogicalShiftLeft, /// (MetaArithmetic, int a, uint b) -> int
  72. ILogicalShiftRight, /// (MetaArithmetic, int a, uint b) -> int
  73. IArithmeticShiftRight, /// (MetaArithmetic, int a, uint b) -> int
  74. IBitwiseAnd, /// (MetaArithmetic, int a, int b) -> int
  75. IBitwiseOr, /// (MetaArithmetic, int a, int b) -> int
  76. IBitwiseXor, /// (MetaArithmetic, int a, int b) -> int
  77. IBitwiseNot, /// (MetaArithmetic, int a) -> int
  78. IBitfieldInsert, /// (MetaArithmetic, int base, int insert, int offset, int bits) -> int
  79. IBitfieldExtract, /// (MetaArithmetic, int value, int offset, int offset) -> int
  80. IBitCount, /// (MetaArithmetic, int) -> int
  81. UAdd, /// (MetaArithmetic, uint a, uint b) -> uint
  82. UMul, /// (MetaArithmetic, uint a, uint b) -> uint
  83. UDiv, /// (MetaArithmetic, uint a, uint b) -> uint
  84. UMin, /// (MetaArithmetic, uint a, uint b) -> uint
  85. UMax, /// (MetaArithmetic, uint a, uint b) -> uint
  86. UCastFloat, /// (MetaArithmetic, float a) -> uint
  87. UCastSigned, /// (MetaArithmetic, int a) -> uint
  88. ULogicalShiftLeft, /// (MetaArithmetic, uint a, uint b) -> uint
  89. ULogicalShiftRight, /// (MetaArithmetic, uint a, uint b) -> uint
  90. UArithmeticShiftRight, /// (MetaArithmetic, uint a, uint b) -> uint
  91. UBitwiseAnd, /// (MetaArithmetic, uint a, uint b) -> uint
  92. UBitwiseOr, /// (MetaArithmetic, uint a, uint b) -> uint
  93. UBitwiseXor, /// (MetaArithmetic, uint a, uint b) -> uint
  94. UBitwiseNot, /// (MetaArithmetic, uint a) -> uint
  95. UBitfieldInsert, /// (MetaArithmetic, uint base, uint insert, int offset, int bits) -> uint
  96. UBitfieldExtract, /// (MetaArithmetic, uint value, int offset, int offset) -> uint
  97. UBitCount, /// (MetaArithmetic, uint) -> uint
  98. HAdd, /// (MetaArithmetic, f16vec2 a, f16vec2 b) -> f16vec2
  99. HMul, /// (MetaArithmetic, f16vec2 a, f16vec2 b) -> f16vec2
  100. HFma, /// (MetaArithmetic, f16vec2 a, f16vec2 b, f16vec2 c) -> f16vec2
  101. HAbsolute, /// (f16vec2 a) -> f16vec2
  102. HNegate, /// (f16vec2 a, bool first, bool second) -> f16vec2
  103. HClamp, /// (f16vec2 src, float min, float max) -> f16vec2
  104. HUnpack, /// (Tegra::Shader::HalfType, T value) -> f16vec2
  105. HMergeF32, /// (f16vec2 src) -> float
  106. HMergeH0, /// (f16vec2 dest, f16vec2 src) -> f16vec2
  107. HMergeH1, /// (f16vec2 dest, f16vec2 src) -> f16vec2
  108. HPack2, /// (float a, float b) -> f16vec2
  109. LogicalAssign, /// (bool& dst, bool src) -> void
  110. LogicalAnd, /// (bool a, bool b) -> bool
  111. LogicalOr, /// (bool a, bool b) -> bool
  112. LogicalXor, /// (bool a, bool b) -> bool
  113. LogicalNegate, /// (bool a) -> bool
  114. LogicalPick2, /// (bool2 pair, uint index) -> bool
  115. LogicalAll2, /// (bool2 a) -> bool
  116. LogicalAny2, /// (bool2 a) -> bool
  117. LogicalFLessThan, /// (float a, float b) -> bool
  118. LogicalFEqual, /// (float a, float b) -> bool
  119. LogicalFLessEqual, /// (float a, float b) -> bool
  120. LogicalFGreaterThan, /// (float a, float b) -> bool
  121. LogicalFNotEqual, /// (float a, float b) -> bool
  122. LogicalFGreaterEqual, /// (float a, float b) -> bool
  123. LogicalFIsNan, /// (float a) -> bool
  124. LogicalILessThan, /// (int a, int b) -> bool
  125. LogicalIEqual, /// (int a, int b) -> bool
  126. LogicalILessEqual, /// (int a, int b) -> bool
  127. LogicalIGreaterThan, /// (int a, int b) -> bool
  128. LogicalINotEqual, /// (int a, int b) -> bool
  129. LogicalIGreaterEqual, /// (int a, int b) -> bool
  130. LogicalULessThan, /// (uint a, uint b) -> bool
  131. LogicalUEqual, /// (uint a, uint b) -> bool
  132. LogicalULessEqual, /// (uint a, uint b) -> bool
  133. LogicalUGreaterThan, /// (uint a, uint b) -> bool
  134. LogicalUNotEqual, /// (uint a, uint b) -> bool
  135. LogicalUGreaterEqual, /// (uint a, uint b) -> bool
  136. Logical2HLessThan, /// (MetaHalfArithmetic, f16vec2 a, f16vec2) -> bool2
  137. Logical2HEqual, /// (MetaHalfArithmetic, f16vec2 a, f16vec2) -> bool2
  138. Logical2HLessEqual, /// (MetaHalfArithmetic, f16vec2 a, f16vec2) -> bool2
  139. Logical2HGreaterThan, /// (MetaHalfArithmetic, f16vec2 a, f16vec2) -> bool2
  140. Logical2HNotEqual, /// (MetaHalfArithmetic, f16vec2 a, f16vec2) -> bool2
  141. Logical2HGreaterEqual, /// (MetaHalfArithmetic, f16vec2 a, f16vec2) -> bool2
  142. Logical2HLessThanWithNan, /// (MetaHalfArithmetic, f16vec2 a, f16vec2) -> bool2
  143. Logical2HEqualWithNan, /// (MetaHalfArithmetic, f16vec2 a, f16vec2) -> bool2
  144. Logical2HLessEqualWithNan, /// (MetaHalfArithmetic, f16vec2 a, f16vec2) -> bool2
  145. Logical2HGreaterThanWithNan, /// (MetaHalfArithmetic, f16vec2 a, f16vec2) -> bool2
  146. Logical2HNotEqualWithNan, /// (MetaHalfArithmetic, f16vec2 a, f16vec2) -> bool2
  147. Logical2HGreaterEqualWithNan, /// (MetaHalfArithmetic, f16vec2 a, f16vec2) -> bool2
  148. Texture, /// (MetaTexture, float[N] coords) -> float4
  149. TextureLod, /// (MetaTexture, float[N] coords) -> float4
  150. TextureGather, /// (MetaTexture, float[N] coords) -> float4
  151. TextureQueryDimensions, /// (MetaTexture, float a) -> float4
  152. TextureQueryLod, /// (MetaTexture, float[N] coords) -> float4
  153. TexelFetch, /// (MetaTexture, int[N], int) -> float4
  154. Branch, /// (uint branch_target) -> void
  155. PushFlowStack, /// (uint branch_target) -> void
  156. PopFlowStack, /// () -> void
  157. Exit, /// () -> void
  158. Discard, /// () -> void
  159. EmitVertex, /// () -> void
  160. EndPrimitive, /// () -> void
  161. YNegate, /// () -> float
  162. Amount,
  163. };
  164. enum class InternalFlag {
  165. Zero = 0,
  166. Sign = 1,
  167. Carry = 2,
  168. Overflow = 3,
  169. Amount = 4,
  170. };
  171. /// Describes the behaviour of code path of a given entry point and a return point.
  172. enum class ExitMethod {
  173. Undetermined, ///< Internal value. Only occur when analyzing JMP loop.
  174. AlwaysReturn, ///< All code paths reach the return point.
  175. Conditional, ///< Code path reaches the return point or an END instruction conditionally.
  176. AlwaysEnd, ///< All code paths reach a END instruction.
  177. };
  178. class Sampler {
  179. public:
  180. // Use this constructor for bounded Samplers
  181. explicit Sampler(std::size_t offset, std::size_t index, Tegra::Shader::TextureType type,
  182. bool is_array, bool is_shadow)
  183. : offset{offset}, index{index}, type{type}, is_array{is_array}, is_shadow{is_shadow},
  184. is_bindless{false} {}
  185. // Use this constructor for bindless Samplers
  186. explicit Sampler(u32 cbuf_index, u32 cbuf_offset, std::size_t index,
  187. Tegra::Shader::TextureType type, bool is_array, bool is_shadow)
  188. : offset{(static_cast<u64>(cbuf_index) << 32) | cbuf_offset}, index{index}, type{type},
  189. is_array{is_array}, is_shadow{is_shadow}, is_bindless{true} {}
  190. // Use this only for serialization/deserialization
  191. explicit Sampler(std::size_t offset, std::size_t index, Tegra::Shader::TextureType type,
  192. bool is_array, bool is_shadow, bool is_bindless)
  193. : offset{offset}, index{index}, type{type}, is_array{is_array}, is_shadow{is_shadow},
  194. is_bindless{is_bindless} {}
  195. std::size_t GetOffset() const {
  196. return offset;
  197. }
  198. std::size_t GetIndex() const {
  199. return index;
  200. }
  201. Tegra::Shader::TextureType GetType() const {
  202. return type;
  203. }
  204. bool IsArray() const {
  205. return is_array;
  206. }
  207. bool IsShadow() const {
  208. return is_shadow;
  209. }
  210. bool IsBindless() const {
  211. return is_bindless;
  212. }
  213. std::pair<u32, u32> GetBindlessCBuf() const {
  214. return {static_cast<u32>(offset >> 32), static_cast<u32>(offset)};
  215. }
  216. bool operator<(const Sampler& rhs) const {
  217. return std::tie(index, offset, type, is_array, is_shadow, is_bindless) <
  218. std::tie(rhs.index, rhs.offset, rhs.type, rhs.is_array, rhs.is_shadow,
  219. rhs.is_bindless);
  220. }
  221. private:
  222. /// Offset in TSC memory from which to read the sampler object, as specified by the sampling
  223. /// instruction.
  224. std::size_t offset{};
  225. std::size_t index{}; ///< Value used to index into the generated GLSL sampler array.
  226. Tegra::Shader::TextureType type{}; ///< The type used to sample this texture (Texture2D, etc)
  227. bool is_array{}; ///< Whether the texture is being sampled as an array texture or not.
  228. bool is_shadow{}; ///< Whether the texture is being sampled as a depth texture or not.
  229. bool is_bindless{}; ///< Whether this sampler belongs to a bindless texture or not.
  230. };
  231. class ConstBuffer {
  232. public:
  233. explicit ConstBuffer(u32 max_offset, bool is_indirect)
  234. : max_offset{max_offset}, is_indirect{is_indirect} {}
  235. ConstBuffer() = default;
  236. void MarkAsUsed(u64 offset) {
  237. max_offset = std::max(max_offset, static_cast<u32>(offset));
  238. }
  239. void MarkAsUsedIndirect() {
  240. is_indirect = true;
  241. }
  242. bool IsIndirect() const {
  243. return is_indirect;
  244. }
  245. u32 GetSize() const {
  246. return max_offset + sizeof(float);
  247. }
  248. u32 GetMaxOffset() const {
  249. return max_offset;
  250. }
  251. private:
  252. u32 max_offset{};
  253. bool is_indirect{};
  254. };
  255. struct GlobalMemoryBase {
  256. u32 cbuf_index{};
  257. u32 cbuf_offset{};
  258. bool operator<(const GlobalMemoryBase& rhs) const {
  259. return std::tie(cbuf_index, cbuf_offset) < std::tie(rhs.cbuf_index, rhs.cbuf_offset);
  260. }
  261. };
  262. struct GlobalMemoryUsage {
  263. bool is_read{};
  264. bool is_written{};
  265. };
  266. struct MetaArithmetic {
  267. bool precise{};
  268. };
  269. struct MetaTexture {
  270. const Sampler& sampler;
  271. Node array{};
  272. Node depth_compare{};
  273. std::vector<Node> aoffi;
  274. Node bias{};
  275. Node lod{};
  276. Node component{};
  277. u32 element{};
  278. };
  279. inline constexpr MetaArithmetic PRECISE = {true};
  280. inline constexpr MetaArithmetic NO_PRECISE = {false};
  281. using Meta = std::variant<MetaArithmetic, MetaTexture, Tegra::Shader::HalfType>;
  282. /// Holds any kind of operation that can be done in the IR
  283. class OperationNode final {
  284. public:
  285. template <typename... T>
  286. explicit constexpr OperationNode(OperationCode code) : code{code}, meta{} {}
  287. template <typename... T>
  288. explicit constexpr OperationNode(OperationCode code, Meta&& meta)
  289. : code{code}, meta{std::move(meta)} {}
  290. template <typename... T>
  291. explicit constexpr OperationNode(OperationCode code, const T*... operands)
  292. : OperationNode(code, {}, operands...) {}
  293. template <typename... T>
  294. explicit constexpr OperationNode(OperationCode code, Meta&& meta, const T*... operands_)
  295. : code{code}, meta{std::move(meta)} {
  296. auto operands_list = {operands_...};
  297. for (auto& operand : operands_list) {
  298. operands.push_back(operand);
  299. }
  300. }
  301. explicit OperationNode(OperationCode code, Meta&& meta, std::vector<Node>&& operands)
  302. : code{code}, meta{meta}, operands{std::move(operands)} {}
  303. explicit OperationNode(OperationCode code, std::vector<Node>&& operands)
  304. : code{code}, meta{}, operands{std::move(operands)} {}
  305. OperationCode GetCode() const {
  306. return code;
  307. }
  308. const Meta& GetMeta() const {
  309. return meta;
  310. }
  311. std::size_t GetOperandsCount() const {
  312. return operands.size();
  313. }
  314. Node operator[](std::size_t operand_index) const {
  315. return operands.at(operand_index);
  316. }
  317. private:
  318. const OperationCode code;
  319. const Meta meta;
  320. std::vector<Node> operands;
  321. };
  322. /// Encloses inside any kind of node that returns a boolean conditionally-executed code
  323. class ConditionalNode final {
  324. public:
  325. explicit ConditionalNode(Node condition, std::vector<Node>&& code)
  326. : condition{condition}, code{std::move(code)} {}
  327. Node GetCondition() const {
  328. return condition;
  329. }
  330. const std::vector<Node>& GetCode() const {
  331. return code;
  332. }
  333. private:
  334. const Node condition; ///< Condition to be satisfied
  335. std::vector<Node> code; ///< Code to execute
  336. };
  337. /// A general purpose register
  338. class GprNode final {
  339. public:
  340. explicit constexpr GprNode(Tegra::Shader::Register index) : index{index} {}
  341. u32 GetIndex() const {
  342. return static_cast<u32>(index);
  343. }
  344. private:
  345. const Tegra::Shader::Register index;
  346. };
  347. /// A 32-bits value that represents an immediate value
  348. class ImmediateNode final {
  349. public:
  350. explicit constexpr ImmediateNode(u32 value) : value{value} {}
  351. u32 GetValue() const {
  352. return value;
  353. }
  354. private:
  355. const u32 value;
  356. };
  357. /// One of Maxwell's internal flags
  358. class InternalFlagNode final {
  359. public:
  360. explicit constexpr InternalFlagNode(InternalFlag flag) : flag{flag} {}
  361. InternalFlag GetFlag() const {
  362. return flag;
  363. }
  364. private:
  365. const InternalFlag flag;
  366. };
  367. /// A predicate register, it can be negated without additional nodes
  368. class PredicateNode final {
  369. public:
  370. explicit constexpr PredicateNode(Tegra::Shader::Pred index, bool negated)
  371. : index{index}, negated{negated} {}
  372. Tegra::Shader::Pred GetIndex() const {
  373. return index;
  374. }
  375. bool IsNegated() const {
  376. return negated;
  377. }
  378. private:
  379. const Tegra::Shader::Pred index;
  380. const bool negated;
  381. };
  382. /// Attribute buffer memory (known as attributes or varyings in GLSL terms)
  383. class AbufNode final {
  384. public:
  385. explicit constexpr AbufNode(Tegra::Shader::Attribute::Index index, u32 element,
  386. const Tegra::Shader::IpaMode& input_mode, Node buffer = {})
  387. : input_mode{input_mode}, buffer{buffer}, index{index}, element{element} {}
  388. explicit constexpr AbufNode(Tegra::Shader::Attribute::Index index, u32 element,
  389. Node buffer = {})
  390. : input_mode{}, buffer{buffer}, index{index}, element{element} {}
  391. Tegra::Shader::IpaMode GetInputMode() const {
  392. return input_mode;
  393. }
  394. Tegra::Shader::Attribute::Index GetIndex() const {
  395. return index;
  396. }
  397. u32 GetElement() const {
  398. return element;
  399. }
  400. Node GetBuffer() const {
  401. return buffer;
  402. }
  403. private:
  404. const Tegra::Shader::IpaMode input_mode;
  405. const Node buffer;
  406. const Tegra::Shader::Attribute::Index index;
  407. const u32 element;
  408. };
  409. /// Constant buffer node, usually mapped to uniform buffers in GLSL
  410. class CbufNode final {
  411. public:
  412. explicit constexpr CbufNode(u32 index, Node offset) : index{index}, offset{offset} {}
  413. u32 GetIndex() const {
  414. return index;
  415. }
  416. Node GetOffset() const {
  417. return offset;
  418. }
  419. private:
  420. const u32 index;
  421. const Node offset;
  422. };
  423. /// Local memory node
  424. class LmemNode final {
  425. public:
  426. explicit constexpr LmemNode(Node address) : address{address} {}
  427. Node GetAddress() const {
  428. return address;
  429. }
  430. private:
  431. const Node address;
  432. };
  433. /// Global memory node
  434. class GmemNode final {
  435. public:
  436. explicit constexpr GmemNode(Node real_address, Node base_address,
  437. const GlobalMemoryBase& descriptor)
  438. : real_address{real_address}, base_address{base_address}, descriptor{descriptor} {}
  439. Node GetRealAddress() const {
  440. return real_address;
  441. }
  442. Node GetBaseAddress() const {
  443. return base_address;
  444. }
  445. const GlobalMemoryBase& GetDescriptor() const {
  446. return descriptor;
  447. }
  448. private:
  449. const Node real_address;
  450. const Node base_address;
  451. const GlobalMemoryBase descriptor;
  452. };
  453. /// Commentary, can be dropped
  454. class CommentNode final {
  455. public:
  456. explicit CommentNode(std::string text) : text{std::move(text)} {}
  457. const std::string& GetText() const {
  458. return text;
  459. }
  460. private:
  461. std::string text;
  462. };
  463. class ShaderIR final {
  464. public:
  465. explicit ShaderIR(const ProgramCode& program_code, u32 main_offset)
  466. : program_code{program_code}, main_offset{main_offset} {
  467. Decode();
  468. }
  469. const std::map<u32, NodeBlock>& GetBasicBlocks() const {
  470. return basic_blocks;
  471. }
  472. const std::set<u32>& GetRegisters() const {
  473. return used_registers;
  474. }
  475. const std::set<Tegra::Shader::Pred>& GetPredicates() const {
  476. return used_predicates;
  477. }
  478. const std::map<Tegra::Shader::Attribute::Index, std::set<Tegra::Shader::IpaMode>>&
  479. GetInputAttributes() const {
  480. return used_input_attributes;
  481. }
  482. const std::set<Tegra::Shader::Attribute::Index>& GetOutputAttributes() const {
  483. return used_output_attributes;
  484. }
  485. const std::map<u32, ConstBuffer>& GetConstantBuffers() const {
  486. return used_cbufs;
  487. }
  488. const std::set<Sampler>& GetSamplers() const {
  489. return used_samplers;
  490. }
  491. const std::array<bool, Tegra::Engines::Maxwell3D::Regs::NumClipDistances>& GetClipDistances()
  492. const {
  493. return used_clip_distances;
  494. }
  495. const std::map<GlobalMemoryBase, GlobalMemoryUsage>& GetGlobalMemory() const {
  496. return used_global_memory;
  497. }
  498. std::size_t GetLength() const {
  499. return static_cast<std::size_t>(coverage_end * sizeof(u64));
  500. }
  501. bool HasPhysicalAttributes() const {
  502. return use_physical_attributes;
  503. }
  504. const Tegra::Shader::Header& GetHeader() const {
  505. return header;
  506. }
  507. private:
  508. void Decode();
  509. ExitMethod Scan(u32 begin, u32 end, std::set<u32>& labels);
  510. NodeBlock DecodeRange(u32 begin, u32 end);
  511. /**
  512. * Decodes a single instruction from Tegra to IR.
  513. * @param bb Basic block where the nodes will be written to.
  514. * @param pc Program counter. Offset to decode.
  515. * @return Next address to decode.
  516. */
  517. u32 DecodeInstr(NodeBlock& bb, u32 pc);
  518. u32 DecodeArithmetic(NodeBlock& bb, u32 pc);
  519. u32 DecodeArithmeticImmediate(NodeBlock& bb, u32 pc);
  520. u32 DecodeBfe(NodeBlock& bb, u32 pc);
  521. u32 DecodeBfi(NodeBlock& bb, u32 pc);
  522. u32 DecodeShift(NodeBlock& bb, u32 pc);
  523. u32 DecodeArithmeticInteger(NodeBlock& bb, u32 pc);
  524. u32 DecodeArithmeticIntegerImmediate(NodeBlock& bb, u32 pc);
  525. u32 DecodeArithmeticHalf(NodeBlock& bb, u32 pc);
  526. u32 DecodeArithmeticHalfImmediate(NodeBlock& bb, u32 pc);
  527. u32 DecodeFfma(NodeBlock& bb, u32 pc);
  528. u32 DecodeHfma2(NodeBlock& bb, u32 pc);
  529. u32 DecodeConversion(NodeBlock& bb, u32 pc);
  530. u32 DecodeMemory(NodeBlock& bb, u32 pc);
  531. u32 DecodeTexture(NodeBlock& bb, u32 pc);
  532. u32 DecodeFloatSetPredicate(NodeBlock& bb, u32 pc);
  533. u32 DecodeIntegerSetPredicate(NodeBlock& bb, u32 pc);
  534. u32 DecodeHalfSetPredicate(NodeBlock& bb, u32 pc);
  535. u32 DecodePredicateSetRegister(NodeBlock& bb, u32 pc);
  536. u32 DecodePredicateSetPredicate(NodeBlock& bb, u32 pc);
  537. u32 DecodeRegisterSetPredicate(NodeBlock& bb, u32 pc);
  538. u32 DecodeFloatSet(NodeBlock& bb, u32 pc);
  539. u32 DecodeIntegerSet(NodeBlock& bb, u32 pc);
  540. u32 DecodeHalfSet(NodeBlock& bb, u32 pc);
  541. u32 DecodeVideo(NodeBlock& bb, u32 pc);
  542. u32 DecodeXmad(NodeBlock& bb, u32 pc);
  543. u32 DecodeOther(NodeBlock& bb, u32 pc);
  544. /// Internalizes node's data and returns a managed pointer to a clone of that node
  545. Node StoreNode(NodeData&& node_data);
  546. /// Creates a conditional node
  547. Node Conditional(Node condition, std::vector<Node>&& code);
  548. /// Creates a commentary
  549. Node Comment(const std::string& text);
  550. /// Creates an u32 immediate
  551. Node Immediate(u32 value);
  552. /// Creates a s32 immediate
  553. Node Immediate(s32 value) {
  554. return Immediate(static_cast<u32>(value));
  555. }
  556. /// Creates a f32 immediate
  557. Node Immediate(f32 value) {
  558. u32 integral;
  559. std::memcpy(&integral, &value, sizeof(u32));
  560. return Immediate(integral);
  561. }
  562. /// Generates a node for a passed register.
  563. Node GetRegister(Tegra::Shader::Register reg);
  564. /// Generates a node representing a 19-bit immediate value
  565. Node GetImmediate19(Tegra::Shader::Instruction instr);
  566. /// Generates a node representing a 32-bit immediate value
  567. Node GetImmediate32(Tegra::Shader::Instruction instr);
  568. /// Generates a node representing a constant buffer
  569. Node GetConstBuffer(u64 index, u64 offset);
  570. /// Generates a node representing a constant buffer with a variadic offset
  571. Node GetConstBufferIndirect(u64 index, u64 offset, Node node);
  572. /// Generates a node for a passed predicate. It can be optionally negated
  573. Node GetPredicate(u64 pred, bool negated = false);
  574. /// Generates a predicate node for an immediate true or false value
  575. Node GetPredicate(bool immediate);
  576. /// Generates a node representing an input attribute. Keeps track of used attributes.
  577. Node GetInputAttribute(Tegra::Shader::Attribute::Index index, u64 element,
  578. const Tegra::Shader::IpaMode& input_mode, Node buffer = {});
  579. /// Generates a node representing an output attribute. Keeps track of used attributes.
  580. Node GetOutputAttribute(Tegra::Shader::Attribute::Index index, u64 element, Node buffer);
  581. /// Generates a node representing an internal flag
  582. Node GetInternalFlag(InternalFlag flag, bool negated = false);
  583. /// Generates a node representing a local memory address
  584. Node GetLocalMemory(Node address);
  585. /// Generates a temporal, internally it uses a post-RZ register
  586. Node GetTemporal(u32 id);
  587. /// Sets a register. src value must be a number-evaluated node.
  588. void SetRegister(NodeBlock& bb, Tegra::Shader::Register dest, Node src);
  589. /// Sets a predicate. src value must be a bool-evaluated node
  590. void SetPredicate(NodeBlock& bb, u64 dest, Node src);
  591. /// Sets an internal flag. src value must be a bool-evaluated node
  592. void SetInternalFlag(NodeBlock& bb, InternalFlag flag, Node value);
  593. /// Sets a local memory address. address and value must be a number-evaluated node
  594. void SetLocalMemory(NodeBlock& bb, Node address, Node value);
  595. /// Sets a temporal. Internally it uses a post-RZ register
  596. void SetTemporal(NodeBlock& bb, u32 id, Node value);
  597. /// Sets internal flags from a float
  598. void SetInternalFlagsFromFloat(NodeBlock& bb, Node value, bool sets_cc = true);
  599. /// Sets internal flags from an integer
  600. void SetInternalFlagsFromInteger(NodeBlock& bb, Node value, bool sets_cc = true);
  601. /// Conditionally absolute/negated float. Absolute is applied first
  602. Node GetOperandAbsNegFloat(Node value, bool absolute, bool negate);
  603. /// Conditionally saturates a float
  604. Node GetSaturatedFloat(Node value, bool saturate = true);
  605. /// Converts an integer to different sizes.
  606. Node ConvertIntegerSize(Node value, Tegra::Shader::Register::Size size, bool is_signed);
  607. /// Conditionally absolute/negated integer. Absolute is applied first
  608. Node GetOperandAbsNegInteger(Node value, bool absolute, bool negate, bool is_signed);
  609. /// Unpacks a half immediate from an instruction
  610. Node UnpackHalfImmediate(Tegra::Shader::Instruction instr, bool has_negation);
  611. /// Unpacks a binary value into a half float pair with a type format
  612. Node UnpackHalfFloat(Node value, Tegra::Shader::HalfType type);
  613. /// Merges a half pair into another value
  614. Node HalfMerge(Node dest, Node src, Tegra::Shader::HalfMerge merge);
  615. /// Conditionally absolute/negated half float pair. Absolute is applied first
  616. Node GetOperandAbsNegHalf(Node value, bool absolute, bool negate);
  617. /// Conditionally saturates a half float pair
  618. Node GetSaturatedHalfFloat(Node value, bool saturate = true);
  619. /// Returns a predicate comparing two floats
  620. Node GetPredicateComparisonFloat(Tegra::Shader::PredCondition condition, Node op_a, Node op_b);
  621. /// Returns a predicate comparing two integers
  622. Node GetPredicateComparisonInteger(Tegra::Shader::PredCondition condition, bool is_signed,
  623. Node op_a, Node op_b);
  624. /// Returns a predicate comparing two half floats. meta consumes how both pairs will be compared
  625. Node GetPredicateComparisonHalf(Tegra::Shader::PredCondition condition, Node op_a, Node op_b);
  626. /// Returns a predicate combiner operation
  627. OperationCode GetPredicateCombiner(Tegra::Shader::PredOperation operation);
  628. /// Returns a condition code evaluated from internal flags
  629. Node GetConditionCode(Tegra::Shader::ConditionCode cc);
  630. /// Accesses a texture sampler
  631. const Sampler& GetSampler(const Tegra::Shader::Sampler& sampler,
  632. Tegra::Shader::TextureType type, bool is_array, bool is_shadow);
  633. // Accesses a texture sampler for a bindless texture.
  634. const Sampler& GetBindlessSampler(const Tegra::Shader::Register& reg,
  635. Tegra::Shader::TextureType type, bool is_array,
  636. bool is_shadow);
  637. /// Extracts a sequence of bits from a node
  638. Node BitfieldExtract(Node value, u32 offset, u32 bits);
  639. void WriteTexInstructionFloat(NodeBlock& bb, Tegra::Shader::Instruction instr,
  640. const Node4& components);
  641. void WriteTexsInstructionFloat(NodeBlock& bb, Tegra::Shader::Instruction instr,
  642. const Node4& components);
  643. void WriteTexsInstructionHalfFloat(NodeBlock& bb, Tegra::Shader::Instruction instr,
  644. const Node4& components);
  645. Node4 GetTexCode(Tegra::Shader::Instruction instr, Tegra::Shader::TextureType texture_type,
  646. Tegra::Shader::TextureProcessMode process_mode, bool depth_compare,
  647. bool is_array, bool is_aoffi,
  648. std::optional<Tegra::Shader::Register> bindless_reg);
  649. Node4 GetTexsCode(Tegra::Shader::Instruction instr, Tegra::Shader::TextureType texture_type,
  650. Tegra::Shader::TextureProcessMode process_mode, bool depth_compare,
  651. bool is_array);
  652. Node4 GetTld4Code(Tegra::Shader::Instruction instr, Tegra::Shader::TextureType texture_type,
  653. bool depth_compare, bool is_array, bool is_aoffi);
  654. Node4 GetTldsCode(Tegra::Shader::Instruction instr, Tegra::Shader::TextureType texture_type,
  655. bool is_array);
  656. std::tuple<std::size_t, std::size_t> ValidateAndGetCoordinateElement(
  657. Tegra::Shader::TextureType texture_type, bool depth_compare, bool is_array,
  658. bool lod_bias_enabled, std::size_t max_coords, std::size_t max_inputs);
  659. std::vector<Node> GetAoffiCoordinates(Node aoffi_reg, std::size_t coord_count, bool is_tld4);
  660. Node4 GetTextureCode(Tegra::Shader::Instruction instr, Tegra::Shader::TextureType texture_type,
  661. Tegra::Shader::TextureProcessMode process_mode, std::vector<Node> coords,
  662. Node array, Node depth_compare, u32 bias_offset, std::vector<Node> aoffi,
  663. std::optional<Tegra::Shader::Register> bindless_reg);
  664. Node GetVideoOperand(Node op, bool is_chunk, bool is_signed, Tegra::Shader::VideoType type,
  665. u64 byte_height);
  666. void WriteLogicOperation(NodeBlock& bb, Tegra::Shader::Register dest,
  667. Tegra::Shader::LogicOperation logic_op, Node op_a, Node op_b,
  668. Tegra::Shader::PredicateResultMode predicate_mode,
  669. Tegra::Shader::Pred predicate, bool sets_cc);
  670. void WriteLop3Instruction(NodeBlock& bb, Tegra::Shader::Register dest, Node op_a, Node op_b,
  671. Node op_c, Node imm_lut, bool sets_cc);
  672. Node TrackCbuf(Node tracked, const NodeBlock& code, s64 cursor);
  673. std::optional<u32> TrackImmediate(Node tracked, const NodeBlock& code, s64 cursor);
  674. std::pair<Node, s64> TrackRegister(const GprNode* tracked, const NodeBlock& code, s64 cursor);
  675. std::tuple<Node, Node, GlobalMemoryBase> TrackAndGetGlobalMemory(NodeBlock& bb,
  676. Node addr_register,
  677. u32 immediate_offset,
  678. bool is_write);
  679. template <typename... T>
  680. Node Operation(OperationCode code, const T*... operands) {
  681. return StoreNode(OperationNode(code, operands...));
  682. }
  683. template <typename... T>
  684. Node Operation(OperationCode code, Meta&& meta, const T*... operands) {
  685. return StoreNode(OperationNode(code, std::move(meta), operands...));
  686. }
  687. template <typename... T>
  688. Node Operation(OperationCode code, std::vector<Node>&& operands) {
  689. return StoreNode(OperationNode(code, std::move(operands)));
  690. }
  691. template <typename... T>
  692. Node Operation(OperationCode code, Meta&& meta, std::vector<Node>&& operands) {
  693. return StoreNode(OperationNode(code, std::move(meta), std::move(operands)));
  694. }
  695. template <typename... T>
  696. Node SignedOperation(OperationCode code, bool is_signed, const T*... operands) {
  697. return StoreNode(OperationNode(SignedToUnsignedCode(code, is_signed), operands...));
  698. }
  699. template <typename... T>
  700. Node SignedOperation(OperationCode code, bool is_signed, Meta&& meta, const T*... operands) {
  701. return StoreNode(
  702. OperationNode(SignedToUnsignedCode(code, is_signed), std::move(meta), operands...));
  703. }
  704. static OperationCode SignedToUnsignedCode(OperationCode operation_code, bool is_signed);
  705. const ProgramCode& program_code;
  706. const u32 main_offset;
  707. u32 coverage_begin{};
  708. u32 coverage_end{};
  709. std::map<std::pair<u32, u32>, ExitMethod> exit_method_map;
  710. std::map<u32, NodeBlock> basic_blocks;
  711. NodeBlock global_code;
  712. std::vector<std::unique_ptr<NodeData>> stored_nodes;
  713. std::set<u32> used_registers;
  714. std::set<Tegra::Shader::Pred> used_predicates;
  715. std::map<Tegra::Shader::Attribute::Index, std::set<Tegra::Shader::IpaMode>>
  716. used_input_attributes;
  717. std::set<Tegra::Shader::Attribute::Index> used_output_attributes;
  718. std::map<u32, ConstBuffer> used_cbufs;
  719. std::set<Sampler> used_samplers;
  720. std::array<bool, Tegra::Engines::Maxwell3D::Regs::NumClipDistances> used_clip_distances{};
  721. std::map<GlobalMemoryBase, GlobalMemoryUsage> used_global_memory;
  722. bool use_physical_attributes = true; // Shader uses AL2P
  723. Tegra::Shader::Header header;
  724. };
  725. } // namespace VideoCommon::Shader