SpvBuilder.cpp 108 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238
  1. //
  2. // Copyright (C) 2014-2015 LunarG, Inc.
  3. // Copyright (C) 2015-2018 Google, Inc.
  4. // Modifications Copyright (C) 2020 Advanced Micro Devices, Inc. All rights reserved.
  5. //
  6. // All rights reserved.
  7. //
  8. // Redistribution and use in source and binary forms, with or without
  9. // modification, are permitted provided that the following conditions
  10. // are met:
  11. //
  12. // Redistributions of source code must retain the above copyright
  13. // notice, this list of conditions and the following disclaimer.
  14. //
  15. // Redistributions in binary form must reproduce the above
  16. // copyright notice, this list of conditions and the following
  17. // disclaimer in the documentation and/or other materials provided
  18. // with the distribution.
  19. //
  20. // Neither the name of 3Dlabs Inc. Ltd. nor the names of its
  21. // contributors may be used to endorse or promote products derived
  22. // from this software without specific prior written permission.
  23. //
  24. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  25. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  26. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
  27. // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
  28. // COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
  29. // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
  30. // BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  31. // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  32. // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  33. // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
  34. // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  35. // POSSIBILITY OF SUCH DAMAGE.
  36. //
  37. // Helper for making SPIR-V IR. Generally, this is documented in the header
  38. // SpvBuilder.h.
  39. //
  40. #include <cassert>
  41. #include <cstdlib>
  42. #include <unordered_set>
  43. #include <algorithm>
  44. #include "SpvBuilder.h"
  45. #ifndef GLSLANG_WEB
  46. #include "hex_float.h"
  47. #endif
  48. #ifndef _WIN32
  49. #include <cstdio>
  50. #endif
  51. namespace spv {
  52. Builder::Builder(unsigned int spvVersion, unsigned int magicNumber, SpvBuildLogger* buildLogger) :
  53. spvVersion(spvVersion),
  54. source(SourceLanguageUnknown),
  55. sourceVersion(0),
  56. sourceFileStringId(NoResult),
  57. currentLine(0),
  58. currentFile(nullptr),
  59. emitOpLines(false),
  60. addressModel(AddressingModelLogical),
  61. memoryModel(MemoryModelGLSL450),
  62. builderNumber(magicNumber),
  63. buildPoint(0),
  64. uniqueId(0),
  65. entryPointFunction(0),
  66. generatingOpCodeForSpecConst(false),
  67. logger(buildLogger)
  68. {
  69. clearAccessChain();
  70. }
  71. Builder::~Builder()
  72. {
  73. }
  74. Id Builder::import(const char* name)
  75. {
  76. Instruction* import = new Instruction(getUniqueId(), NoType, OpExtInstImport);
  77. import->addStringOperand(name);
  78. module.mapInstruction(import);
  79. imports.push_back(std::unique_ptr<Instruction>(import));
  80. return import->getResultId();
  81. }
  82. // Emit instruction for non-filename-based #line directives (ie. no filename
  83. // seen yet): emit an OpLine if we've been asked to emit OpLines and the line
  84. // number has changed since the last time, and is a valid line number.
  85. void Builder::setLine(int lineNum)
  86. {
  87. if (lineNum != 0 && lineNum != currentLine) {
  88. currentLine = lineNum;
  89. if (emitOpLines)
  90. addLine(sourceFileStringId, currentLine, 0);
  91. }
  92. }
  93. // If no filename, do non-filename-based #line emit. Else do filename-based emit.
  94. // Emit OpLine if we've been asked to emit OpLines and the line number or filename
  95. // has changed since the last time, and line number is valid.
  96. void Builder::setLine(int lineNum, const char* filename)
  97. {
  98. if (filename == nullptr) {
  99. setLine(lineNum);
  100. return;
  101. }
  102. if ((lineNum != 0 && lineNum != currentLine) || currentFile == nullptr ||
  103. strncmp(filename, currentFile, strlen(currentFile) + 1) != 0) {
  104. currentLine = lineNum;
  105. currentFile = filename;
  106. if (emitOpLines) {
  107. spv::Id strId = getStringId(filename);
  108. addLine(strId, currentLine, 0);
  109. }
  110. }
  111. }
  112. void Builder::addLine(Id fileName, int lineNum, int column)
  113. {
  114. Instruction* line = new Instruction(OpLine);
  115. line->addIdOperand(fileName);
  116. line->addImmediateOperand(lineNum);
  117. line->addImmediateOperand(column);
  118. buildPoint->addInstruction(std::unique_ptr<Instruction>(line));
  119. }
  120. // For creating new groupedTypes (will return old type if the requested one was already made).
  121. Id Builder::makeVoidType()
  122. {
  123. Instruction* type;
  124. if (groupedTypes[OpTypeVoid].size() == 0) {
  125. type = new Instruction(getUniqueId(), NoType, OpTypeVoid);
  126. groupedTypes[OpTypeVoid].push_back(type);
  127. constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(type));
  128. module.mapInstruction(type);
  129. } else
  130. type = groupedTypes[OpTypeVoid].back();
  131. return type->getResultId();
  132. }
  133. Id Builder::makeBoolType()
  134. {
  135. Instruction* type;
  136. if (groupedTypes[OpTypeBool].size() == 0) {
  137. type = new Instruction(getUniqueId(), NoType, OpTypeBool);
  138. groupedTypes[OpTypeBool].push_back(type);
  139. constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(type));
  140. module.mapInstruction(type);
  141. } else
  142. type = groupedTypes[OpTypeBool].back();
  143. return type->getResultId();
  144. }
  145. Id Builder::makeSamplerType()
  146. {
  147. Instruction* type;
  148. if (groupedTypes[OpTypeSampler].size() == 0) {
  149. type = new Instruction(getUniqueId(), NoType, OpTypeSampler);
  150. groupedTypes[OpTypeSampler].push_back(type);
  151. constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(type));
  152. module.mapInstruction(type);
  153. } else
  154. type = groupedTypes[OpTypeSampler].back();
  155. return type->getResultId();
  156. }
  157. Id Builder::makePointer(StorageClass storageClass, Id pointee)
  158. {
  159. // try to find it
  160. Instruction* type;
  161. for (int t = 0; t < (int)groupedTypes[OpTypePointer].size(); ++t) {
  162. type = groupedTypes[OpTypePointer][t];
  163. if (type->getImmediateOperand(0) == (unsigned)storageClass &&
  164. type->getIdOperand(1) == pointee)
  165. return type->getResultId();
  166. }
  167. // not found, make it
  168. type = new Instruction(getUniqueId(), NoType, OpTypePointer);
  169. type->addImmediateOperand(storageClass);
  170. type->addIdOperand(pointee);
  171. groupedTypes[OpTypePointer].push_back(type);
  172. constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(type));
  173. module.mapInstruction(type);
  174. return type->getResultId();
  175. }
  176. Id Builder::makeForwardPointer(StorageClass storageClass)
  177. {
  178. // Caching/uniquifying doesn't work here, because we don't know the
  179. // pointee type and there can be multiple forward pointers of the same
  180. // storage type. Somebody higher up in the stack must keep track.
  181. Instruction* type = new Instruction(getUniqueId(), NoType, OpTypeForwardPointer);
  182. type->addImmediateOperand(storageClass);
  183. constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(type));
  184. module.mapInstruction(type);
  185. return type->getResultId();
  186. }
  187. Id Builder::makePointerFromForwardPointer(StorageClass storageClass, Id forwardPointerType, Id pointee)
  188. {
  189. // try to find it
  190. Instruction* type;
  191. for (int t = 0; t < (int)groupedTypes[OpTypePointer].size(); ++t) {
  192. type = groupedTypes[OpTypePointer][t];
  193. if (type->getImmediateOperand(0) == (unsigned)storageClass &&
  194. type->getIdOperand(1) == pointee)
  195. return type->getResultId();
  196. }
  197. type = new Instruction(forwardPointerType, NoType, OpTypePointer);
  198. type->addImmediateOperand(storageClass);
  199. type->addIdOperand(pointee);
  200. groupedTypes[OpTypePointer].push_back(type);
  201. constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(type));
  202. module.mapInstruction(type);
  203. return type->getResultId();
  204. }
  205. Id Builder::makeIntegerType(int width, bool hasSign)
  206. {
  207. #ifdef GLSLANG_WEB
  208. assert(width == 32);
  209. width = 32;
  210. #endif
  211. // try to find it
  212. Instruction* type;
  213. for (int t = 0; t < (int)groupedTypes[OpTypeInt].size(); ++t) {
  214. type = groupedTypes[OpTypeInt][t];
  215. if (type->getImmediateOperand(0) == (unsigned)width &&
  216. type->getImmediateOperand(1) == (hasSign ? 1u : 0u))
  217. return type->getResultId();
  218. }
  219. // not found, make it
  220. type = new Instruction(getUniqueId(), NoType, OpTypeInt);
  221. type->addImmediateOperand(width);
  222. type->addImmediateOperand(hasSign ? 1 : 0);
  223. groupedTypes[OpTypeInt].push_back(type);
  224. constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(type));
  225. module.mapInstruction(type);
  226. // deal with capabilities
  227. switch (width) {
  228. case 8:
  229. case 16:
  230. // these are currently handled by storage-type declarations and post processing
  231. break;
  232. case 64:
  233. addCapability(CapabilityInt64);
  234. break;
  235. default:
  236. break;
  237. }
  238. return type->getResultId();
  239. }
  240. Id Builder::makeFloatType(int width)
  241. {
  242. #ifdef GLSLANG_WEB
  243. assert(width == 32);
  244. width = 32;
  245. #endif
  246. // try to find it
  247. Instruction* type;
  248. for (int t = 0; t < (int)groupedTypes[OpTypeFloat].size(); ++t) {
  249. type = groupedTypes[OpTypeFloat][t];
  250. if (type->getImmediateOperand(0) == (unsigned)width)
  251. return type->getResultId();
  252. }
  253. // not found, make it
  254. type = new Instruction(getUniqueId(), NoType, OpTypeFloat);
  255. type->addImmediateOperand(width);
  256. groupedTypes[OpTypeFloat].push_back(type);
  257. constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(type));
  258. module.mapInstruction(type);
  259. // deal with capabilities
  260. switch (width) {
  261. case 16:
  262. // currently handled by storage-type declarations and post processing
  263. break;
  264. case 64:
  265. addCapability(CapabilityFloat64);
  266. break;
  267. default:
  268. break;
  269. }
  270. return type->getResultId();
  271. }
  272. // Make a struct without checking for duplication.
  273. // See makeStructResultType() for non-decorated structs
  274. // needed as the result of some instructions, which does
  275. // check for duplicates.
  276. Id Builder::makeStructType(const std::vector<Id>& members, const char* name)
  277. {
  278. // Don't look for previous one, because in the general case,
  279. // structs can be duplicated except for decorations.
  280. // not found, make it
  281. Instruction* type = new Instruction(getUniqueId(), NoType, OpTypeStruct);
  282. for (int op = 0; op < (int)members.size(); ++op)
  283. type->addIdOperand(members[op]);
  284. groupedTypes[OpTypeStruct].push_back(type);
  285. constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(type));
  286. module.mapInstruction(type);
  287. addName(type->getResultId(), name);
  288. return type->getResultId();
  289. }
  290. // Make a struct for the simple results of several instructions,
  291. // checking for duplication.
  292. Id Builder::makeStructResultType(Id type0, Id type1)
  293. {
  294. // try to find it
  295. Instruction* type;
  296. for (int t = 0; t < (int)groupedTypes[OpTypeStruct].size(); ++t) {
  297. type = groupedTypes[OpTypeStruct][t];
  298. if (type->getNumOperands() != 2)
  299. continue;
  300. if (type->getIdOperand(0) != type0 ||
  301. type->getIdOperand(1) != type1)
  302. continue;
  303. return type->getResultId();
  304. }
  305. // not found, make it
  306. std::vector<spv::Id> members;
  307. members.push_back(type0);
  308. members.push_back(type1);
  309. return makeStructType(members, "ResType");
  310. }
  311. Id Builder::makeVectorType(Id component, int size)
  312. {
  313. // try to find it
  314. Instruction* type;
  315. for (int t = 0; t < (int)groupedTypes[OpTypeVector].size(); ++t) {
  316. type = groupedTypes[OpTypeVector][t];
  317. if (type->getIdOperand(0) == component &&
  318. type->getImmediateOperand(1) == (unsigned)size)
  319. return type->getResultId();
  320. }
  321. // not found, make it
  322. type = new Instruction(getUniqueId(), NoType, OpTypeVector);
  323. type->addIdOperand(component);
  324. type->addImmediateOperand(size);
  325. groupedTypes[OpTypeVector].push_back(type);
  326. constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(type));
  327. module.mapInstruction(type);
  328. return type->getResultId();
  329. }
  330. Id Builder::makeMatrixType(Id component, int cols, int rows)
  331. {
  332. assert(cols <= maxMatrixSize && rows <= maxMatrixSize);
  333. Id column = makeVectorType(component, rows);
  334. // try to find it
  335. Instruction* type;
  336. for (int t = 0; t < (int)groupedTypes[OpTypeMatrix].size(); ++t) {
  337. type = groupedTypes[OpTypeMatrix][t];
  338. if (type->getIdOperand(0) == column &&
  339. type->getImmediateOperand(1) == (unsigned)cols)
  340. return type->getResultId();
  341. }
  342. // not found, make it
  343. type = new Instruction(getUniqueId(), NoType, OpTypeMatrix);
  344. type->addIdOperand(column);
  345. type->addImmediateOperand(cols);
  346. groupedTypes[OpTypeMatrix].push_back(type);
  347. constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(type));
  348. module.mapInstruction(type);
  349. return type->getResultId();
  350. }
  351. Id Builder::makeCooperativeMatrixType(Id component, Id scope, Id rows, Id cols)
  352. {
  353. // try to find it
  354. Instruction* type;
  355. for (int t = 0; t < (int)groupedTypes[OpTypeCooperativeMatrixNV].size(); ++t) {
  356. type = groupedTypes[OpTypeCooperativeMatrixNV][t];
  357. if (type->getIdOperand(0) == component &&
  358. type->getIdOperand(1) == scope &&
  359. type->getIdOperand(2) == rows &&
  360. type->getIdOperand(3) == cols)
  361. return type->getResultId();
  362. }
  363. // not found, make it
  364. type = new Instruction(getUniqueId(), NoType, OpTypeCooperativeMatrixNV);
  365. type->addIdOperand(component);
  366. type->addIdOperand(scope);
  367. type->addIdOperand(rows);
  368. type->addIdOperand(cols);
  369. groupedTypes[OpTypeCooperativeMatrixNV].push_back(type);
  370. constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(type));
  371. module.mapInstruction(type);
  372. return type->getResultId();
  373. }
  374. // TODO: performance: track arrays per stride
  375. // If a stride is supplied (non-zero) make an array.
  376. // If no stride (0), reuse previous array types.
  377. // 'size' is an Id of a constant or specialization constant of the array size
  378. Id Builder::makeArrayType(Id element, Id sizeId, int stride)
  379. {
  380. Instruction* type;
  381. if (stride == 0) {
  382. // try to find existing type
  383. for (int t = 0; t < (int)groupedTypes[OpTypeArray].size(); ++t) {
  384. type = groupedTypes[OpTypeArray][t];
  385. if (type->getIdOperand(0) == element &&
  386. type->getIdOperand(1) == sizeId)
  387. return type->getResultId();
  388. }
  389. }
  390. // not found, make it
  391. type = new Instruction(getUniqueId(), NoType, OpTypeArray);
  392. type->addIdOperand(element);
  393. type->addIdOperand(sizeId);
  394. groupedTypes[OpTypeArray].push_back(type);
  395. constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(type));
  396. module.mapInstruction(type);
  397. return type->getResultId();
  398. }
  399. Id Builder::makeRuntimeArray(Id element)
  400. {
  401. Instruction* type = new Instruction(getUniqueId(), NoType, OpTypeRuntimeArray);
  402. type->addIdOperand(element);
  403. constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(type));
  404. module.mapInstruction(type);
  405. return type->getResultId();
  406. }
  407. Id Builder::makeFunctionType(Id returnType, const std::vector<Id>& paramTypes)
  408. {
  409. // try to find it
  410. Instruction* type;
  411. for (int t = 0; t < (int)groupedTypes[OpTypeFunction].size(); ++t) {
  412. type = groupedTypes[OpTypeFunction][t];
  413. if (type->getIdOperand(0) != returnType || (int)paramTypes.size() != type->getNumOperands() - 1)
  414. continue;
  415. bool mismatch = false;
  416. for (int p = 0; p < (int)paramTypes.size(); ++p) {
  417. if (paramTypes[p] != type->getIdOperand(p + 1)) {
  418. mismatch = true;
  419. break;
  420. }
  421. }
  422. if (! mismatch)
  423. return type->getResultId();
  424. }
  425. // not found, make it
  426. type = new Instruction(getUniqueId(), NoType, OpTypeFunction);
  427. type->addIdOperand(returnType);
  428. for (int p = 0; p < (int)paramTypes.size(); ++p)
  429. type->addIdOperand(paramTypes[p]);
  430. groupedTypes[OpTypeFunction].push_back(type);
  431. constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(type));
  432. module.mapInstruction(type);
  433. return type->getResultId();
  434. }
  435. Id Builder::makeImageType(Id sampledType, Dim dim, bool depth, bool arrayed, bool ms, unsigned sampled,
  436. ImageFormat format)
  437. {
  438. assert(sampled == 1 || sampled == 2);
  439. // try to find it
  440. Instruction* type;
  441. for (int t = 0; t < (int)groupedTypes[OpTypeImage].size(); ++t) {
  442. type = groupedTypes[OpTypeImage][t];
  443. if (type->getIdOperand(0) == sampledType &&
  444. type->getImmediateOperand(1) == (unsigned int)dim &&
  445. type->getImmediateOperand(2) == ( depth ? 1u : 0u) &&
  446. type->getImmediateOperand(3) == (arrayed ? 1u : 0u) &&
  447. type->getImmediateOperand(4) == ( ms ? 1u : 0u) &&
  448. type->getImmediateOperand(5) == sampled &&
  449. type->getImmediateOperand(6) == (unsigned int)format)
  450. return type->getResultId();
  451. }
  452. // not found, make it
  453. type = new Instruction(getUniqueId(), NoType, OpTypeImage);
  454. type->addIdOperand(sampledType);
  455. type->addImmediateOperand( dim);
  456. type->addImmediateOperand( depth ? 1 : 0);
  457. type->addImmediateOperand(arrayed ? 1 : 0);
  458. type->addImmediateOperand( ms ? 1 : 0);
  459. type->addImmediateOperand(sampled);
  460. type->addImmediateOperand((unsigned int)format);
  461. groupedTypes[OpTypeImage].push_back(type);
  462. constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(type));
  463. module.mapInstruction(type);
  464. #ifndef GLSLANG_WEB
  465. // deal with capabilities
  466. switch (dim) {
  467. case DimBuffer:
  468. if (sampled == 1)
  469. addCapability(CapabilitySampledBuffer);
  470. else
  471. addCapability(CapabilityImageBuffer);
  472. break;
  473. case Dim1D:
  474. if (sampled == 1)
  475. addCapability(CapabilitySampled1D);
  476. else
  477. addCapability(CapabilityImage1D);
  478. break;
  479. case DimCube:
  480. if (arrayed) {
  481. if (sampled == 1)
  482. addCapability(CapabilitySampledCubeArray);
  483. else
  484. addCapability(CapabilityImageCubeArray);
  485. }
  486. break;
  487. case DimRect:
  488. if (sampled == 1)
  489. addCapability(CapabilitySampledRect);
  490. else
  491. addCapability(CapabilityImageRect);
  492. break;
  493. case DimSubpassData:
  494. addCapability(CapabilityInputAttachment);
  495. break;
  496. default:
  497. break;
  498. }
  499. if (ms) {
  500. if (sampled == 2) {
  501. // Images used with subpass data are not storage
  502. // images, so don't require the capability for them.
  503. if (dim != Dim::DimSubpassData)
  504. addCapability(CapabilityStorageImageMultisample);
  505. if (arrayed)
  506. addCapability(CapabilityImageMSArray);
  507. }
  508. }
  509. #endif
  510. return type->getResultId();
  511. }
  512. Id Builder::makeSampledImageType(Id imageType)
  513. {
  514. // try to find it
  515. Instruction* type;
  516. for (int t = 0; t < (int)groupedTypes[OpTypeSampledImage].size(); ++t) {
  517. type = groupedTypes[OpTypeSampledImage][t];
  518. if (type->getIdOperand(0) == imageType)
  519. return type->getResultId();
  520. }
  521. // not found, make it
  522. type = new Instruction(getUniqueId(), NoType, OpTypeSampledImage);
  523. type->addIdOperand(imageType);
  524. groupedTypes[OpTypeSampledImage].push_back(type);
  525. constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(type));
  526. module.mapInstruction(type);
  527. return type->getResultId();
  528. }
  529. #ifndef GLSLANG_WEB
  530. Id Builder::makeAccelerationStructureType()
  531. {
  532. Instruction *type;
  533. if (groupedTypes[OpTypeAccelerationStructureKHR].size() == 0) {
  534. type = new Instruction(getUniqueId(), NoType, OpTypeAccelerationStructureKHR);
  535. groupedTypes[OpTypeAccelerationStructureKHR].push_back(type);
  536. constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(type));
  537. module.mapInstruction(type);
  538. } else {
  539. type = groupedTypes[OpTypeAccelerationStructureKHR].back();
  540. }
  541. return type->getResultId();
  542. }
  543. Id Builder::makeRayQueryType()
  544. {
  545. Instruction *type;
  546. if (groupedTypes[OpTypeRayQueryKHR].size() == 0) {
  547. type = new Instruction(getUniqueId(), NoType, OpTypeRayQueryKHR);
  548. groupedTypes[OpTypeRayQueryKHR].push_back(type);
  549. constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(type));
  550. module.mapInstruction(type);
  551. } else {
  552. type = groupedTypes[OpTypeRayQueryKHR].back();
  553. }
  554. return type->getResultId();
  555. }
  556. #endif
  557. Id Builder::getDerefTypeId(Id resultId) const
  558. {
  559. Id typeId = getTypeId(resultId);
  560. assert(isPointerType(typeId));
  561. return module.getInstruction(typeId)->getIdOperand(1);
  562. }
  563. Op Builder::getMostBasicTypeClass(Id typeId) const
  564. {
  565. Instruction* instr = module.getInstruction(typeId);
  566. Op typeClass = instr->getOpCode();
  567. switch (typeClass)
  568. {
  569. case OpTypeVector:
  570. case OpTypeMatrix:
  571. case OpTypeArray:
  572. case OpTypeRuntimeArray:
  573. return getMostBasicTypeClass(instr->getIdOperand(0));
  574. case OpTypePointer:
  575. return getMostBasicTypeClass(instr->getIdOperand(1));
  576. default:
  577. return typeClass;
  578. }
  579. }
  580. int Builder::getNumTypeConstituents(Id typeId) const
  581. {
  582. Instruction* instr = module.getInstruction(typeId);
  583. switch (instr->getOpCode())
  584. {
  585. case OpTypeBool:
  586. case OpTypeInt:
  587. case OpTypeFloat:
  588. case OpTypePointer:
  589. return 1;
  590. case OpTypeVector:
  591. case OpTypeMatrix:
  592. return instr->getImmediateOperand(1);
  593. case OpTypeArray:
  594. {
  595. Id lengthId = instr->getIdOperand(1);
  596. return module.getInstruction(lengthId)->getImmediateOperand(0);
  597. }
  598. case OpTypeStruct:
  599. return instr->getNumOperands();
  600. case OpTypeCooperativeMatrixNV:
  601. // has only one constituent when used with OpCompositeConstruct.
  602. return 1;
  603. default:
  604. assert(0);
  605. return 1;
  606. }
  607. }
  608. // Return the lowest-level type of scalar that an homogeneous composite is made out of.
  609. // Typically, this is just to find out if something is made out of ints or floats.
  610. // However, it includes returning a structure, if say, it is an array of structure.
  611. Id Builder::getScalarTypeId(Id typeId) const
  612. {
  613. Instruction* instr = module.getInstruction(typeId);
  614. Op typeClass = instr->getOpCode();
  615. switch (typeClass)
  616. {
  617. case OpTypeVoid:
  618. case OpTypeBool:
  619. case OpTypeInt:
  620. case OpTypeFloat:
  621. case OpTypeStruct:
  622. return instr->getResultId();
  623. case OpTypeVector:
  624. case OpTypeMatrix:
  625. case OpTypeArray:
  626. case OpTypeRuntimeArray:
  627. case OpTypePointer:
  628. return getScalarTypeId(getContainedTypeId(typeId));
  629. default:
  630. assert(0);
  631. return NoResult;
  632. }
  633. }
  634. // Return the type of 'member' of a composite.
  635. Id Builder::getContainedTypeId(Id typeId, int member) const
  636. {
  637. Instruction* instr = module.getInstruction(typeId);
  638. Op typeClass = instr->getOpCode();
  639. switch (typeClass)
  640. {
  641. case OpTypeVector:
  642. case OpTypeMatrix:
  643. case OpTypeArray:
  644. case OpTypeRuntimeArray:
  645. case OpTypeCooperativeMatrixNV:
  646. return instr->getIdOperand(0);
  647. case OpTypePointer:
  648. return instr->getIdOperand(1);
  649. case OpTypeStruct:
  650. return instr->getIdOperand(member);
  651. default:
  652. assert(0);
  653. return NoResult;
  654. }
  655. }
  656. // Return the immediately contained type of a given composite type.
  657. Id Builder::getContainedTypeId(Id typeId) const
  658. {
  659. return getContainedTypeId(typeId, 0);
  660. }
  661. // Returns true if 'typeId' is or contains a scalar type declared with 'typeOp'
  662. // of width 'width'. The 'width' is only consumed for int and float types.
  663. // Returns false otherwise.
  664. bool Builder::containsType(Id typeId, spv::Op typeOp, unsigned int width) const
  665. {
  666. const Instruction& instr = *module.getInstruction(typeId);
  667. Op typeClass = instr.getOpCode();
  668. switch (typeClass)
  669. {
  670. case OpTypeInt:
  671. case OpTypeFloat:
  672. return typeClass == typeOp && instr.getImmediateOperand(0) == width;
  673. case OpTypeStruct:
  674. for (int m = 0; m < instr.getNumOperands(); ++m) {
  675. if (containsType(instr.getIdOperand(m), typeOp, width))
  676. return true;
  677. }
  678. return false;
  679. case OpTypePointer:
  680. return false;
  681. case OpTypeVector:
  682. case OpTypeMatrix:
  683. case OpTypeArray:
  684. case OpTypeRuntimeArray:
  685. return containsType(getContainedTypeId(typeId), typeOp, width);
  686. default:
  687. return typeClass == typeOp;
  688. }
  689. }
  690. // return true if the type is a pointer to PhysicalStorageBufferEXT or an
  691. // array of such pointers. These require restrict/aliased decorations.
  692. bool Builder::containsPhysicalStorageBufferOrArray(Id typeId) const
  693. {
  694. const Instruction& instr = *module.getInstruction(typeId);
  695. Op typeClass = instr.getOpCode();
  696. switch (typeClass)
  697. {
  698. case OpTypePointer:
  699. return getTypeStorageClass(typeId) == StorageClassPhysicalStorageBufferEXT;
  700. case OpTypeArray:
  701. return containsPhysicalStorageBufferOrArray(getContainedTypeId(typeId));
  702. default:
  703. return false;
  704. }
  705. }
  706. // See if a scalar constant of this type has already been created, so it
  707. // can be reused rather than duplicated. (Required by the specification).
  708. Id Builder::findScalarConstant(Op typeClass, Op opcode, Id typeId, unsigned value)
  709. {
  710. Instruction* constant;
  711. for (int i = 0; i < (int)groupedConstants[typeClass].size(); ++i) {
  712. constant = groupedConstants[typeClass][i];
  713. if (constant->getOpCode() == opcode &&
  714. constant->getTypeId() == typeId &&
  715. constant->getImmediateOperand(0) == value)
  716. return constant->getResultId();
  717. }
  718. return 0;
  719. }
  720. // Version of findScalarConstant (see above) for scalars that take two operands (e.g. a 'double' or 'int64').
  721. Id Builder::findScalarConstant(Op typeClass, Op opcode, Id typeId, unsigned v1, unsigned v2)
  722. {
  723. Instruction* constant;
  724. for (int i = 0; i < (int)groupedConstants[typeClass].size(); ++i) {
  725. constant = groupedConstants[typeClass][i];
  726. if (constant->getOpCode() == opcode &&
  727. constant->getTypeId() == typeId &&
  728. constant->getImmediateOperand(0) == v1 &&
  729. constant->getImmediateOperand(1) == v2)
  730. return constant->getResultId();
  731. }
  732. return 0;
  733. }
  734. // Return true if consuming 'opcode' means consuming a constant.
  735. // "constant" here means after final transform to executable code,
  736. // the value consumed will be a constant, so includes specialization.
  737. bool Builder::isConstantOpCode(Op opcode) const
  738. {
  739. switch (opcode) {
  740. case OpUndef:
  741. case OpConstantTrue:
  742. case OpConstantFalse:
  743. case OpConstant:
  744. case OpConstantComposite:
  745. case OpConstantSampler:
  746. case OpConstantNull:
  747. case OpSpecConstantTrue:
  748. case OpSpecConstantFalse:
  749. case OpSpecConstant:
  750. case OpSpecConstantComposite:
  751. case OpSpecConstantOp:
  752. return true;
  753. default:
  754. return false;
  755. }
  756. }
  757. // Return true if consuming 'opcode' means consuming a specialization constant.
  758. bool Builder::isSpecConstantOpCode(Op opcode) const
  759. {
  760. switch (opcode) {
  761. case OpSpecConstantTrue:
  762. case OpSpecConstantFalse:
  763. case OpSpecConstant:
  764. case OpSpecConstantComposite:
  765. case OpSpecConstantOp:
  766. return true;
  767. default:
  768. return false;
  769. }
  770. }
  771. Id Builder::makeBoolConstant(bool b, bool specConstant)
  772. {
  773. Id typeId = makeBoolType();
  774. Instruction* constant;
  775. Op opcode = specConstant ? (b ? OpSpecConstantTrue : OpSpecConstantFalse) : (b ? OpConstantTrue : OpConstantFalse);
  776. // See if we already made it. Applies only to regular constants, because specialization constants
  777. // must remain distinct for the purpose of applying a SpecId decoration.
  778. if (! specConstant) {
  779. Id existing = 0;
  780. for (int i = 0; i < (int)groupedConstants[OpTypeBool].size(); ++i) {
  781. constant = groupedConstants[OpTypeBool][i];
  782. if (constant->getTypeId() == typeId && constant->getOpCode() == opcode)
  783. existing = constant->getResultId();
  784. }
  785. if (existing)
  786. return existing;
  787. }
  788. // Make it
  789. Instruction* c = new Instruction(getUniqueId(), typeId, opcode);
  790. constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(c));
  791. groupedConstants[OpTypeBool].push_back(c);
  792. module.mapInstruction(c);
  793. return c->getResultId();
  794. }
  795. Id Builder::makeIntConstant(Id typeId, unsigned value, bool specConstant)
  796. {
  797. Op opcode = specConstant ? OpSpecConstant : OpConstant;
  798. // See if we already made it. Applies only to regular constants, because specialization constants
  799. // must remain distinct for the purpose of applying a SpecId decoration.
  800. if (! specConstant) {
  801. Id existing = findScalarConstant(OpTypeInt, opcode, typeId, value);
  802. if (existing)
  803. return existing;
  804. }
  805. Instruction* c = new Instruction(getUniqueId(), typeId, opcode);
  806. c->addImmediateOperand(value);
  807. constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(c));
  808. groupedConstants[OpTypeInt].push_back(c);
  809. module.mapInstruction(c);
  810. return c->getResultId();
  811. }
  812. Id Builder::makeInt64Constant(Id typeId, unsigned long long value, bool specConstant)
  813. {
  814. Op opcode = specConstant ? OpSpecConstant : OpConstant;
  815. unsigned op1 = value & 0xFFFFFFFF;
  816. unsigned op2 = value >> 32;
  817. // See if we already made it. Applies only to regular constants, because specialization constants
  818. // must remain distinct for the purpose of applying a SpecId decoration.
  819. if (! specConstant) {
  820. Id existing = findScalarConstant(OpTypeInt, opcode, typeId, op1, op2);
  821. if (existing)
  822. return existing;
  823. }
  824. Instruction* c = new Instruction(getUniqueId(), typeId, opcode);
  825. c->addImmediateOperand(op1);
  826. c->addImmediateOperand(op2);
  827. constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(c));
  828. groupedConstants[OpTypeInt].push_back(c);
  829. module.mapInstruction(c);
  830. return c->getResultId();
  831. }
  832. Id Builder::makeFloatConstant(float f, bool specConstant)
  833. {
  834. Op opcode = specConstant ? OpSpecConstant : OpConstant;
  835. Id typeId = makeFloatType(32);
  836. union { float fl; unsigned int ui; } u;
  837. u.fl = f;
  838. unsigned value = u.ui;
  839. // See if we already made it. Applies only to regular constants, because specialization constants
  840. // must remain distinct for the purpose of applying a SpecId decoration.
  841. if (! specConstant) {
  842. Id existing = findScalarConstant(OpTypeFloat, opcode, typeId, value);
  843. if (existing)
  844. return existing;
  845. }
  846. Instruction* c = new Instruction(getUniqueId(), typeId, opcode);
  847. c->addImmediateOperand(value);
  848. constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(c));
  849. groupedConstants[OpTypeFloat].push_back(c);
  850. module.mapInstruction(c);
  851. return c->getResultId();
  852. }
  853. Id Builder::makeDoubleConstant(double d, bool specConstant)
  854. {
  855. #ifdef GLSLANG_WEB
  856. assert(0);
  857. return NoResult;
  858. #else
  859. Op opcode = specConstant ? OpSpecConstant : OpConstant;
  860. Id typeId = makeFloatType(64);
  861. union { double db; unsigned long long ull; } u;
  862. u.db = d;
  863. unsigned long long value = u.ull;
  864. unsigned op1 = value & 0xFFFFFFFF;
  865. unsigned op2 = value >> 32;
  866. // See if we already made it. Applies only to regular constants, because specialization constants
  867. // must remain distinct for the purpose of applying a SpecId decoration.
  868. if (! specConstant) {
  869. Id existing = findScalarConstant(OpTypeFloat, opcode, typeId, op1, op2);
  870. if (existing)
  871. return existing;
  872. }
  873. Instruction* c = new Instruction(getUniqueId(), typeId, opcode);
  874. c->addImmediateOperand(op1);
  875. c->addImmediateOperand(op2);
  876. constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(c));
  877. groupedConstants[OpTypeFloat].push_back(c);
  878. module.mapInstruction(c);
  879. return c->getResultId();
  880. #endif
  881. }
  882. Id Builder::makeFloat16Constant(float f16, bool specConstant)
  883. {
  884. #ifdef GLSLANG_WEB
  885. assert(0);
  886. return NoResult;
  887. #else
  888. Op opcode = specConstant ? OpSpecConstant : OpConstant;
  889. Id typeId = makeFloatType(16);
  890. spvutils::HexFloat<spvutils::FloatProxy<float>> fVal(f16);
  891. spvutils::HexFloat<spvutils::FloatProxy<spvutils::Float16>> f16Val(0);
  892. fVal.castTo(f16Val, spvutils::kRoundToZero);
  893. unsigned value = f16Val.value().getAsFloat().get_value();
  894. // See if we already made it. Applies only to regular constants, because specialization constants
  895. // must remain distinct for the purpose of applying a SpecId decoration.
  896. if (!specConstant) {
  897. Id existing = findScalarConstant(OpTypeFloat, opcode, typeId, value);
  898. if (existing)
  899. return existing;
  900. }
  901. Instruction* c = new Instruction(getUniqueId(), typeId, opcode);
  902. c->addImmediateOperand(value);
  903. constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(c));
  904. groupedConstants[OpTypeFloat].push_back(c);
  905. module.mapInstruction(c);
  906. return c->getResultId();
  907. #endif
  908. }
  909. Id Builder::makeFpConstant(Id type, double d, bool specConstant)
  910. {
  911. #ifdef GLSLANG_WEB
  912. const int width = 32;
  913. assert(width == getScalarTypeWidth(type));
  914. #else
  915. const int width = getScalarTypeWidth(type);
  916. #endif
  917. assert(isFloatType(type));
  918. switch (width) {
  919. case 16:
  920. return makeFloat16Constant((float)d, specConstant);
  921. case 32:
  922. return makeFloatConstant((float)d, specConstant);
  923. case 64:
  924. return makeDoubleConstant(d, specConstant);
  925. default:
  926. break;
  927. }
  928. assert(false);
  929. return NoResult;
  930. }
  931. Id Builder::findCompositeConstant(Op typeClass, Id typeId, const std::vector<Id>& comps)
  932. {
  933. Instruction* constant = 0;
  934. bool found = false;
  935. for (int i = 0; i < (int)groupedConstants[typeClass].size(); ++i) {
  936. constant = groupedConstants[typeClass][i];
  937. if (constant->getTypeId() != typeId)
  938. continue;
  939. // same contents?
  940. bool mismatch = false;
  941. for (int op = 0; op < constant->getNumOperands(); ++op) {
  942. if (constant->getIdOperand(op) != comps[op]) {
  943. mismatch = true;
  944. break;
  945. }
  946. }
  947. if (! mismatch) {
  948. found = true;
  949. break;
  950. }
  951. }
  952. return found ? constant->getResultId() : NoResult;
  953. }
  954. Id Builder::findStructConstant(Id typeId, const std::vector<Id>& comps)
  955. {
  956. Instruction* constant = 0;
  957. bool found = false;
  958. for (int i = 0; i < (int)groupedStructConstants[typeId].size(); ++i) {
  959. constant = groupedStructConstants[typeId][i];
  960. // same contents?
  961. bool mismatch = false;
  962. for (int op = 0; op < constant->getNumOperands(); ++op) {
  963. if (constant->getIdOperand(op) != comps[op]) {
  964. mismatch = true;
  965. break;
  966. }
  967. }
  968. if (! mismatch) {
  969. found = true;
  970. break;
  971. }
  972. }
  973. return found ? constant->getResultId() : NoResult;
  974. }
  975. // Comments in header
  976. Id Builder::makeCompositeConstant(Id typeId, const std::vector<Id>& members, bool specConstant)
  977. {
  978. Op opcode = specConstant ? OpSpecConstantComposite : OpConstantComposite;
  979. assert(typeId);
  980. Op typeClass = getTypeClass(typeId);
  981. switch (typeClass) {
  982. case OpTypeVector:
  983. case OpTypeArray:
  984. case OpTypeMatrix:
  985. case OpTypeCooperativeMatrixNV:
  986. if (! specConstant) {
  987. Id existing = findCompositeConstant(typeClass, typeId, members);
  988. if (existing)
  989. return existing;
  990. }
  991. break;
  992. case OpTypeStruct:
  993. if (! specConstant) {
  994. Id existing = findStructConstant(typeId, members);
  995. if (existing)
  996. return existing;
  997. }
  998. break;
  999. default:
  1000. assert(0);
  1001. return makeFloatConstant(0.0);
  1002. }
  1003. Instruction* c = new Instruction(getUniqueId(), typeId, opcode);
  1004. for (int op = 0; op < (int)members.size(); ++op)
  1005. c->addIdOperand(members[op]);
  1006. constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(c));
  1007. if (typeClass == OpTypeStruct)
  1008. groupedStructConstants[typeId].push_back(c);
  1009. else
  1010. groupedConstants[typeClass].push_back(c);
  1011. module.mapInstruction(c);
  1012. return c->getResultId();
  1013. }
  1014. Instruction* Builder::addEntryPoint(ExecutionModel model, Function* function, const char* name)
  1015. {
  1016. Instruction* entryPoint = new Instruction(OpEntryPoint);
  1017. entryPoint->addImmediateOperand(model);
  1018. entryPoint->addIdOperand(function->getId());
  1019. entryPoint->addStringOperand(name);
  1020. entryPoints.push_back(std::unique_ptr<Instruction>(entryPoint));
  1021. return entryPoint;
  1022. }
  1023. // Currently relying on the fact that all 'value' of interest are small non-negative values.
  1024. void Builder::addExecutionMode(Function* entryPoint, ExecutionMode mode, int value1, int value2, int value3)
  1025. {
  1026. Instruction* instr = new Instruction(OpExecutionMode);
  1027. instr->addIdOperand(entryPoint->getId());
  1028. instr->addImmediateOperand(mode);
  1029. if (value1 >= 0)
  1030. instr->addImmediateOperand(value1);
  1031. if (value2 >= 0)
  1032. instr->addImmediateOperand(value2);
  1033. if (value3 >= 0)
  1034. instr->addImmediateOperand(value3);
  1035. executionModes.push_back(std::unique_ptr<Instruction>(instr));
  1036. }
  1037. void Builder::addExecutionMode(Function* entryPoint, ExecutionMode mode, const std::vector<unsigned>& literals)
  1038. {
  1039. Instruction* instr = new Instruction(OpExecutionMode);
  1040. instr->addIdOperand(entryPoint->getId());
  1041. instr->addImmediateOperand(mode);
  1042. for (auto literal : literals)
  1043. instr->addImmediateOperand(literal);
  1044. executionModes.push_back(std::unique_ptr<Instruction>(instr));
  1045. }
  1046. void Builder::addExecutionModeId(Function* entryPoint, ExecutionMode mode, const std::vector<Id>& operandIds)
  1047. {
  1048. Instruction* instr = new Instruction(OpExecutionModeId);
  1049. instr->addIdOperand(entryPoint->getId());
  1050. instr->addImmediateOperand(mode);
  1051. for (auto operandId : operandIds)
  1052. instr->addIdOperand(operandId);
  1053. executionModes.push_back(std::unique_ptr<Instruction>(instr));
  1054. }
  1055. void Builder::addName(Id id, const char* string)
  1056. {
  1057. Instruction* name = new Instruction(OpName);
  1058. name->addIdOperand(id);
  1059. name->addStringOperand(string);
  1060. names.push_back(std::unique_ptr<Instruction>(name));
  1061. }
  1062. void Builder::addMemberName(Id id, int memberNumber, const char* string)
  1063. {
  1064. Instruction* name = new Instruction(OpMemberName);
  1065. name->addIdOperand(id);
  1066. name->addImmediateOperand(memberNumber);
  1067. name->addStringOperand(string);
  1068. names.push_back(std::unique_ptr<Instruction>(name));
  1069. }
  1070. void Builder::addDecoration(Id id, Decoration decoration, int num)
  1071. {
  1072. if (decoration == spv::DecorationMax)
  1073. return;
  1074. Instruction* dec = new Instruction(OpDecorate);
  1075. dec->addIdOperand(id);
  1076. dec->addImmediateOperand(decoration);
  1077. if (num >= 0)
  1078. dec->addImmediateOperand(num);
  1079. decorations.push_back(std::unique_ptr<Instruction>(dec));
  1080. }
  1081. void Builder::addDecoration(Id id, Decoration decoration, const char* s)
  1082. {
  1083. if (decoration == spv::DecorationMax)
  1084. return;
  1085. Instruction* dec = new Instruction(OpDecorateString);
  1086. dec->addIdOperand(id);
  1087. dec->addImmediateOperand(decoration);
  1088. dec->addStringOperand(s);
  1089. decorations.push_back(std::unique_ptr<Instruction>(dec));
  1090. }
  1091. void Builder::addDecoration(Id id, Decoration decoration, const std::vector<unsigned>& literals)
  1092. {
  1093. if (decoration == spv::DecorationMax)
  1094. return;
  1095. Instruction* dec = new Instruction(OpDecorate);
  1096. dec->addIdOperand(id);
  1097. dec->addImmediateOperand(decoration);
  1098. for (auto literal : literals)
  1099. dec->addImmediateOperand(literal);
  1100. decorations.push_back(std::unique_ptr<Instruction>(dec));
  1101. }
  1102. void Builder::addDecoration(Id id, Decoration decoration, const std::vector<const char*>& strings)
  1103. {
  1104. if (decoration == spv::DecorationMax)
  1105. return;
  1106. Instruction* dec = new Instruction(OpDecorateString);
  1107. dec->addIdOperand(id);
  1108. dec->addImmediateOperand(decoration);
  1109. for (auto string : strings)
  1110. dec->addStringOperand(string);
  1111. decorations.push_back(std::unique_ptr<Instruction>(dec));
  1112. }
  1113. void Builder::addDecorationId(Id id, Decoration decoration, Id idDecoration)
  1114. {
  1115. if (decoration == spv::DecorationMax)
  1116. return;
  1117. Instruction* dec = new Instruction(OpDecorateId);
  1118. dec->addIdOperand(id);
  1119. dec->addImmediateOperand(decoration);
  1120. dec->addIdOperand(idDecoration);
  1121. decorations.push_back(std::unique_ptr<Instruction>(dec));
  1122. }
  1123. void Builder::addDecorationId(Id id, Decoration decoration, const std::vector<Id>& operandIds)
  1124. {
  1125. if(decoration == spv::DecorationMax)
  1126. return;
  1127. Instruction* dec = new Instruction(OpDecorateId);
  1128. dec->addIdOperand(id);
  1129. dec->addImmediateOperand(decoration);
  1130. for (auto operandId : operandIds)
  1131. dec->addIdOperand(operandId);
  1132. decorations.push_back(std::unique_ptr<Instruction>(dec));
  1133. }
  1134. void Builder::addMemberDecoration(Id id, unsigned int member, Decoration decoration, int num)
  1135. {
  1136. if (decoration == spv::DecorationMax)
  1137. return;
  1138. Instruction* dec = new Instruction(OpMemberDecorate);
  1139. dec->addIdOperand(id);
  1140. dec->addImmediateOperand(member);
  1141. dec->addImmediateOperand(decoration);
  1142. if (num >= 0)
  1143. dec->addImmediateOperand(num);
  1144. decorations.push_back(std::unique_ptr<Instruction>(dec));
  1145. }
  1146. void Builder::addMemberDecoration(Id id, unsigned int member, Decoration decoration, const char *s)
  1147. {
  1148. if (decoration == spv::DecorationMax)
  1149. return;
  1150. Instruction* dec = new Instruction(OpMemberDecorateStringGOOGLE);
  1151. dec->addIdOperand(id);
  1152. dec->addImmediateOperand(member);
  1153. dec->addImmediateOperand(decoration);
  1154. dec->addStringOperand(s);
  1155. decorations.push_back(std::unique_ptr<Instruction>(dec));
  1156. }
  1157. void Builder::addMemberDecoration(Id id, unsigned int member, Decoration decoration, const std::vector<unsigned>& literals)
  1158. {
  1159. if (decoration == spv::DecorationMax)
  1160. return;
  1161. Instruction* dec = new Instruction(OpMemberDecorate);
  1162. dec->addIdOperand(id);
  1163. dec->addImmediateOperand(member);
  1164. dec->addImmediateOperand(decoration);
  1165. for (auto literal : literals)
  1166. dec->addImmediateOperand(literal);
  1167. decorations.push_back(std::unique_ptr<Instruction>(dec));
  1168. }
  1169. void Builder::addMemberDecoration(Id id, unsigned int member, Decoration decoration, const std::vector<const char*>& strings)
  1170. {
  1171. if (decoration == spv::DecorationMax)
  1172. return;
  1173. Instruction* dec = new Instruction(OpMemberDecorateString);
  1174. dec->addIdOperand(id);
  1175. dec->addImmediateOperand(member);
  1176. dec->addImmediateOperand(decoration);
  1177. for (auto string : strings)
  1178. dec->addStringOperand(string);
  1179. decorations.push_back(std::unique_ptr<Instruction>(dec));
  1180. }
  1181. // Comments in header
  1182. Function* Builder::makeEntryPoint(const char* entryPoint)
  1183. {
  1184. assert(! entryPointFunction);
  1185. Block* entry;
  1186. std::vector<Id> params;
  1187. std::vector<std::vector<Decoration>> decorations;
  1188. entryPointFunction = makeFunctionEntry(NoPrecision, makeVoidType(), entryPoint, params, decorations, &entry);
  1189. return entryPointFunction;
  1190. }
  1191. // Comments in header
  1192. Function* Builder::makeFunctionEntry(Decoration precision, Id returnType, const char* name,
  1193. const std::vector<Id>& paramTypes,
  1194. const std::vector<std::vector<Decoration>>& decorations, Block **entry)
  1195. {
  1196. // Make the function and initial instructions in it
  1197. Id typeId = makeFunctionType(returnType, paramTypes);
  1198. Id firstParamId = paramTypes.size() == 0 ? 0 : getUniqueIds((int)paramTypes.size());
  1199. Function* function = new Function(getUniqueId(), returnType, typeId, firstParamId, module);
  1200. // Set up the precisions
  1201. setPrecision(function->getId(), precision);
  1202. function->setReturnPrecision(precision);
  1203. for (unsigned p = 0; p < (unsigned)decorations.size(); ++p) {
  1204. for (int d = 0; d < (int)decorations[p].size(); ++d) {
  1205. addDecoration(firstParamId + p, decorations[p][d]);
  1206. function->addParamPrecision(p, decorations[p][d]);
  1207. }
  1208. }
  1209. // CFG
  1210. if (entry) {
  1211. *entry = new Block(getUniqueId(), *function);
  1212. function->addBlock(*entry);
  1213. setBuildPoint(*entry);
  1214. }
  1215. if (name)
  1216. addName(function->getId(), name);
  1217. functions.push_back(std::unique_ptr<Function>(function));
  1218. return function;
  1219. }
  1220. // Comments in header
  1221. void Builder::makeReturn(bool implicit, Id retVal)
  1222. {
  1223. if (retVal) {
  1224. Instruction* inst = new Instruction(NoResult, NoType, OpReturnValue);
  1225. inst->addIdOperand(retVal);
  1226. buildPoint->addInstruction(std::unique_ptr<Instruction>(inst));
  1227. } else
  1228. buildPoint->addInstruction(std::unique_ptr<Instruction>(new Instruction(NoResult, NoType, OpReturn)));
  1229. if (! implicit)
  1230. createAndSetNoPredecessorBlock("post-return");
  1231. }
  1232. // Comments in header
  1233. void Builder::leaveFunction()
  1234. {
  1235. Block* block = buildPoint;
  1236. Function& function = buildPoint->getParent();
  1237. assert(block);
  1238. // If our function did not contain a return, add a return void now.
  1239. if (! block->isTerminated()) {
  1240. if (function.getReturnType() == makeVoidType())
  1241. makeReturn(true);
  1242. else {
  1243. makeReturn(true, createUndefined(function.getReturnType()));
  1244. }
  1245. }
  1246. }
  1247. // Comments in header
  1248. void Builder::makeDiscard()
  1249. {
  1250. buildPoint->addInstruction(std::unique_ptr<Instruction>(new Instruction(OpKill)));
  1251. createAndSetNoPredecessorBlock("post-discard");
  1252. }
  1253. // Comments in header
  1254. void Builder::makeTerminateInvocation()
  1255. {
  1256. buildPoint->addInstruction(std::unique_ptr<Instruction>(new Instruction(OpTerminateInvocation)));
  1257. createAndSetNoPredecessorBlock("post-terminate-invocation");
  1258. }
  1259. // Comments in header
  1260. Id Builder::createVariable(Decoration precision, StorageClass storageClass, Id type, const char* name, Id initializer)
  1261. {
  1262. Id pointerType = makePointer(storageClass, type);
  1263. Instruction* inst = new Instruction(getUniqueId(), pointerType, OpVariable);
  1264. inst->addImmediateOperand(storageClass);
  1265. if (initializer != NoResult)
  1266. inst->addIdOperand(initializer);
  1267. switch (storageClass) {
  1268. case StorageClassFunction:
  1269. // Validation rules require the declaration in the entry block
  1270. buildPoint->getParent().addLocalVariable(std::unique_ptr<Instruction>(inst));
  1271. break;
  1272. default:
  1273. constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(inst));
  1274. module.mapInstruction(inst);
  1275. break;
  1276. }
  1277. if (name)
  1278. addName(inst->getResultId(), name);
  1279. setPrecision(inst->getResultId(), precision);
  1280. return inst->getResultId();
  1281. }
  1282. // Comments in header
  1283. Id Builder::createUndefined(Id type)
  1284. {
  1285. Instruction* inst = new Instruction(getUniqueId(), type, OpUndef);
  1286. buildPoint->addInstruction(std::unique_ptr<Instruction>(inst));
  1287. return inst->getResultId();
  1288. }
  1289. // av/vis/nonprivate are unnecessary and illegal for some storage classes.
  1290. spv::MemoryAccessMask Builder::sanitizeMemoryAccessForStorageClass(spv::MemoryAccessMask memoryAccess, StorageClass sc)
  1291. const
  1292. {
  1293. switch (sc) {
  1294. case spv::StorageClassUniform:
  1295. case spv::StorageClassWorkgroup:
  1296. case spv::StorageClassStorageBuffer:
  1297. case spv::StorageClassPhysicalStorageBufferEXT:
  1298. break;
  1299. default:
  1300. memoryAccess = spv::MemoryAccessMask(memoryAccess &
  1301. ~(spv::MemoryAccessMakePointerAvailableKHRMask |
  1302. spv::MemoryAccessMakePointerVisibleKHRMask |
  1303. spv::MemoryAccessNonPrivatePointerKHRMask));
  1304. break;
  1305. }
  1306. return memoryAccess;
  1307. }
  1308. // Comments in header
  1309. void Builder::createStore(Id rValue, Id lValue, spv::MemoryAccessMask memoryAccess, spv::Scope scope,
  1310. unsigned int alignment)
  1311. {
  1312. Instruction* store = new Instruction(OpStore);
  1313. store->addIdOperand(lValue);
  1314. store->addIdOperand(rValue);
  1315. memoryAccess = sanitizeMemoryAccessForStorageClass(memoryAccess, getStorageClass(lValue));
  1316. if (memoryAccess != MemoryAccessMaskNone) {
  1317. store->addImmediateOperand(memoryAccess);
  1318. if (memoryAccess & spv::MemoryAccessAlignedMask) {
  1319. store->addImmediateOperand(alignment);
  1320. }
  1321. if (memoryAccess & spv::MemoryAccessMakePointerAvailableKHRMask) {
  1322. store->addIdOperand(makeUintConstant(scope));
  1323. }
  1324. }
  1325. buildPoint->addInstruction(std::unique_ptr<Instruction>(store));
  1326. }
  1327. // Comments in header
  1328. Id Builder::createLoad(Id lValue, spv::Decoration precision, spv::MemoryAccessMask memoryAccess,
  1329. spv::Scope scope, unsigned int alignment)
  1330. {
  1331. Instruction* load = new Instruction(getUniqueId(), getDerefTypeId(lValue), OpLoad);
  1332. load->addIdOperand(lValue);
  1333. memoryAccess = sanitizeMemoryAccessForStorageClass(memoryAccess, getStorageClass(lValue));
  1334. if (memoryAccess != MemoryAccessMaskNone) {
  1335. load->addImmediateOperand(memoryAccess);
  1336. if (memoryAccess & spv::MemoryAccessAlignedMask) {
  1337. load->addImmediateOperand(alignment);
  1338. }
  1339. if (memoryAccess & spv::MemoryAccessMakePointerVisibleKHRMask) {
  1340. load->addIdOperand(makeUintConstant(scope));
  1341. }
  1342. }
  1343. buildPoint->addInstruction(std::unique_ptr<Instruction>(load));
  1344. setPrecision(load->getResultId(), precision);
  1345. return load->getResultId();
  1346. }
  1347. // Comments in header
  1348. Id Builder::createAccessChain(StorageClass storageClass, Id base, const std::vector<Id>& offsets)
  1349. {
  1350. // Figure out the final resulting type.
  1351. spv::Id typeId = getTypeId(base);
  1352. assert(isPointerType(typeId) && offsets.size() > 0);
  1353. typeId = getContainedTypeId(typeId);
  1354. for (int i = 0; i < (int)offsets.size(); ++i) {
  1355. if (isStructType(typeId)) {
  1356. assert(isConstantScalar(offsets[i]));
  1357. typeId = getContainedTypeId(typeId, getConstantScalar(offsets[i]));
  1358. } else
  1359. typeId = getContainedTypeId(typeId, offsets[i]);
  1360. }
  1361. typeId = makePointer(storageClass, typeId);
  1362. // Make the instruction
  1363. Instruction* chain = new Instruction(getUniqueId(), typeId, OpAccessChain);
  1364. chain->addIdOperand(base);
  1365. for (int i = 0; i < (int)offsets.size(); ++i)
  1366. chain->addIdOperand(offsets[i]);
  1367. buildPoint->addInstruction(std::unique_ptr<Instruction>(chain));
  1368. return chain->getResultId();
  1369. }
  1370. Id Builder::createArrayLength(Id base, unsigned int member)
  1371. {
  1372. spv::Id intType = makeUintType(32);
  1373. Instruction* length = new Instruction(getUniqueId(), intType, OpArrayLength);
  1374. length->addIdOperand(base);
  1375. length->addImmediateOperand(member);
  1376. buildPoint->addInstruction(std::unique_ptr<Instruction>(length));
  1377. return length->getResultId();
  1378. }
  1379. Id Builder::createCooperativeMatrixLength(Id type)
  1380. {
  1381. spv::Id intType = makeUintType(32);
  1382. // Generate code for spec constants if in spec constant operation
  1383. // generation mode.
  1384. if (generatingOpCodeForSpecConst) {
  1385. return createSpecConstantOp(OpCooperativeMatrixLengthNV, intType, std::vector<Id>(1, type), std::vector<Id>());
  1386. }
  1387. Instruction* length = new Instruction(getUniqueId(), intType, OpCooperativeMatrixLengthNV);
  1388. length->addIdOperand(type);
  1389. buildPoint->addInstruction(std::unique_ptr<Instruction>(length));
  1390. return length->getResultId();
  1391. }
  1392. Id Builder::createCompositeExtract(Id composite, Id typeId, unsigned index)
  1393. {
  1394. // Generate code for spec constants if in spec constant operation
  1395. // generation mode.
  1396. if (generatingOpCodeForSpecConst) {
  1397. return createSpecConstantOp(OpCompositeExtract, typeId, std::vector<Id>(1, composite),
  1398. std::vector<Id>(1, index));
  1399. }
  1400. Instruction* extract = new Instruction(getUniqueId(), typeId, OpCompositeExtract);
  1401. extract->addIdOperand(composite);
  1402. extract->addImmediateOperand(index);
  1403. buildPoint->addInstruction(std::unique_ptr<Instruction>(extract));
  1404. return extract->getResultId();
  1405. }
  1406. Id Builder::createCompositeExtract(Id composite, Id typeId, const std::vector<unsigned>& indexes)
  1407. {
  1408. // Generate code for spec constants if in spec constant operation
  1409. // generation mode.
  1410. if (generatingOpCodeForSpecConst) {
  1411. return createSpecConstantOp(OpCompositeExtract, typeId, std::vector<Id>(1, composite), indexes);
  1412. }
  1413. Instruction* extract = new Instruction(getUniqueId(), typeId, OpCompositeExtract);
  1414. extract->addIdOperand(composite);
  1415. for (int i = 0; i < (int)indexes.size(); ++i)
  1416. extract->addImmediateOperand(indexes[i]);
  1417. buildPoint->addInstruction(std::unique_ptr<Instruction>(extract));
  1418. return extract->getResultId();
  1419. }
  1420. Id Builder::createCompositeInsert(Id object, Id composite, Id typeId, unsigned index)
  1421. {
  1422. Instruction* insert = new Instruction(getUniqueId(), typeId, OpCompositeInsert);
  1423. insert->addIdOperand(object);
  1424. insert->addIdOperand(composite);
  1425. insert->addImmediateOperand(index);
  1426. buildPoint->addInstruction(std::unique_ptr<Instruction>(insert));
  1427. return insert->getResultId();
  1428. }
  1429. Id Builder::createCompositeInsert(Id object, Id composite, Id typeId, const std::vector<unsigned>& indexes)
  1430. {
  1431. Instruction* insert = new Instruction(getUniqueId(), typeId, OpCompositeInsert);
  1432. insert->addIdOperand(object);
  1433. insert->addIdOperand(composite);
  1434. for (int i = 0; i < (int)indexes.size(); ++i)
  1435. insert->addImmediateOperand(indexes[i]);
  1436. buildPoint->addInstruction(std::unique_ptr<Instruction>(insert));
  1437. return insert->getResultId();
  1438. }
  1439. Id Builder::createVectorExtractDynamic(Id vector, Id typeId, Id componentIndex)
  1440. {
  1441. Instruction* extract = new Instruction(getUniqueId(), typeId, OpVectorExtractDynamic);
  1442. extract->addIdOperand(vector);
  1443. extract->addIdOperand(componentIndex);
  1444. buildPoint->addInstruction(std::unique_ptr<Instruction>(extract));
  1445. return extract->getResultId();
  1446. }
  1447. Id Builder::createVectorInsertDynamic(Id vector, Id typeId, Id component, Id componentIndex)
  1448. {
  1449. Instruction* insert = new Instruction(getUniqueId(), typeId, OpVectorInsertDynamic);
  1450. insert->addIdOperand(vector);
  1451. insert->addIdOperand(component);
  1452. insert->addIdOperand(componentIndex);
  1453. buildPoint->addInstruction(std::unique_ptr<Instruction>(insert));
  1454. return insert->getResultId();
  1455. }
  1456. // An opcode that has no operands, no result id, and no type
  1457. void Builder::createNoResultOp(Op opCode)
  1458. {
  1459. Instruction* op = new Instruction(opCode);
  1460. buildPoint->addInstruction(std::unique_ptr<Instruction>(op));
  1461. }
  1462. // An opcode that has one id operand, no result id, and no type
  1463. void Builder::createNoResultOp(Op opCode, Id operand)
  1464. {
  1465. Instruction* op = new Instruction(opCode);
  1466. op->addIdOperand(operand);
  1467. buildPoint->addInstruction(std::unique_ptr<Instruction>(op));
  1468. }
  1469. // An opcode that has one or more operands, no result id, and no type
  1470. void Builder::createNoResultOp(Op opCode, const std::vector<Id>& operands)
  1471. {
  1472. Instruction* op = new Instruction(opCode);
  1473. for (auto it = operands.cbegin(); it != operands.cend(); ++it) {
  1474. op->addIdOperand(*it);
  1475. }
  1476. buildPoint->addInstruction(std::unique_ptr<Instruction>(op));
  1477. }
  1478. // An opcode that has multiple operands, no result id, and no type
  1479. void Builder::createNoResultOp(Op opCode, const std::vector<IdImmediate>& operands)
  1480. {
  1481. Instruction* op = new Instruction(opCode);
  1482. for (auto it = operands.cbegin(); it != operands.cend(); ++it) {
  1483. if (it->isId)
  1484. op->addIdOperand(it->word);
  1485. else
  1486. op->addImmediateOperand(it->word);
  1487. }
  1488. buildPoint->addInstruction(std::unique_ptr<Instruction>(op));
  1489. }
  1490. void Builder::createControlBarrier(Scope execution, Scope memory, MemorySemanticsMask semantics)
  1491. {
  1492. Instruction* op = new Instruction(OpControlBarrier);
  1493. op->addIdOperand(makeUintConstant(execution));
  1494. op->addIdOperand(makeUintConstant(memory));
  1495. op->addIdOperand(makeUintConstant(semantics));
  1496. buildPoint->addInstruction(std::unique_ptr<Instruction>(op));
  1497. }
  1498. void Builder::createMemoryBarrier(unsigned executionScope, unsigned memorySemantics)
  1499. {
  1500. Instruction* op = new Instruction(OpMemoryBarrier);
  1501. op->addIdOperand(makeUintConstant(executionScope));
  1502. op->addIdOperand(makeUintConstant(memorySemantics));
  1503. buildPoint->addInstruction(std::unique_ptr<Instruction>(op));
  1504. }
  1505. // An opcode that has one operands, a result id, and a type
  1506. Id Builder::createUnaryOp(Op opCode, Id typeId, Id operand)
  1507. {
  1508. // Generate code for spec constants if in spec constant operation
  1509. // generation mode.
  1510. if (generatingOpCodeForSpecConst) {
  1511. return createSpecConstantOp(opCode, typeId, std::vector<Id>(1, operand), std::vector<Id>());
  1512. }
  1513. Instruction* op = new Instruction(getUniqueId(), typeId, opCode);
  1514. op->addIdOperand(operand);
  1515. buildPoint->addInstruction(std::unique_ptr<Instruction>(op));
  1516. return op->getResultId();
  1517. }
  1518. Id Builder::createBinOp(Op opCode, Id typeId, Id left, Id right)
  1519. {
  1520. // Generate code for spec constants if in spec constant operation
  1521. // generation mode.
  1522. if (generatingOpCodeForSpecConst) {
  1523. std::vector<Id> operands(2);
  1524. operands[0] = left; operands[1] = right;
  1525. return createSpecConstantOp(opCode, typeId, operands, std::vector<Id>());
  1526. }
  1527. Instruction* op = new Instruction(getUniqueId(), typeId, opCode);
  1528. op->addIdOperand(left);
  1529. op->addIdOperand(right);
  1530. buildPoint->addInstruction(std::unique_ptr<Instruction>(op));
  1531. return op->getResultId();
  1532. }
  1533. Id Builder::createTriOp(Op opCode, Id typeId, Id op1, Id op2, Id op3)
  1534. {
  1535. // Generate code for spec constants if in spec constant operation
  1536. // generation mode.
  1537. if (generatingOpCodeForSpecConst) {
  1538. std::vector<Id> operands(3);
  1539. operands[0] = op1;
  1540. operands[1] = op2;
  1541. operands[2] = op3;
  1542. return createSpecConstantOp(
  1543. opCode, typeId, operands, std::vector<Id>());
  1544. }
  1545. Instruction* op = new Instruction(getUniqueId(), typeId, opCode);
  1546. op->addIdOperand(op1);
  1547. op->addIdOperand(op2);
  1548. op->addIdOperand(op3);
  1549. buildPoint->addInstruction(std::unique_ptr<Instruction>(op));
  1550. return op->getResultId();
  1551. }
  1552. Id Builder::createOp(Op opCode, Id typeId, const std::vector<Id>& operands)
  1553. {
  1554. Instruction* op = new Instruction(getUniqueId(), typeId, opCode);
  1555. for (auto it = operands.cbegin(); it != operands.cend(); ++it)
  1556. op->addIdOperand(*it);
  1557. buildPoint->addInstruction(std::unique_ptr<Instruction>(op));
  1558. return op->getResultId();
  1559. }
  1560. Id Builder::createOp(Op opCode, Id typeId, const std::vector<IdImmediate>& operands)
  1561. {
  1562. Instruction* op = new Instruction(getUniqueId(), typeId, opCode);
  1563. for (auto it = operands.cbegin(); it != operands.cend(); ++it) {
  1564. if (it->isId)
  1565. op->addIdOperand(it->word);
  1566. else
  1567. op->addImmediateOperand(it->word);
  1568. }
  1569. buildPoint->addInstruction(std::unique_ptr<Instruction>(op));
  1570. return op->getResultId();
  1571. }
  1572. Id Builder::createSpecConstantOp(Op opCode, Id typeId, const std::vector<Id>& operands,
  1573. const std::vector<unsigned>& literals)
  1574. {
  1575. Instruction* op = new Instruction(getUniqueId(), typeId, OpSpecConstantOp);
  1576. op->addImmediateOperand((unsigned) opCode);
  1577. for (auto it = operands.cbegin(); it != operands.cend(); ++it)
  1578. op->addIdOperand(*it);
  1579. for (auto it = literals.cbegin(); it != literals.cend(); ++it)
  1580. op->addImmediateOperand(*it);
  1581. module.mapInstruction(op);
  1582. constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(op));
  1583. return op->getResultId();
  1584. }
  1585. Id Builder::createFunctionCall(spv::Function* function, const std::vector<spv::Id>& args)
  1586. {
  1587. Instruction* op = new Instruction(getUniqueId(), function->getReturnType(), OpFunctionCall);
  1588. op->addIdOperand(function->getId());
  1589. for (int a = 0; a < (int)args.size(); ++a)
  1590. op->addIdOperand(args[a]);
  1591. buildPoint->addInstruction(std::unique_ptr<Instruction>(op));
  1592. return op->getResultId();
  1593. }
  1594. // Comments in header
  1595. Id Builder::createRvalueSwizzle(Decoration precision, Id typeId, Id source, const std::vector<unsigned>& channels)
  1596. {
  1597. if (channels.size() == 1)
  1598. return setPrecision(createCompositeExtract(source, typeId, channels.front()), precision);
  1599. if (generatingOpCodeForSpecConst) {
  1600. std::vector<Id> operands(2);
  1601. operands[0] = operands[1] = source;
  1602. return setPrecision(createSpecConstantOp(OpVectorShuffle, typeId, operands, channels), precision);
  1603. }
  1604. Instruction* swizzle = new Instruction(getUniqueId(), typeId, OpVectorShuffle);
  1605. assert(isVector(source));
  1606. swizzle->addIdOperand(source);
  1607. swizzle->addIdOperand(source);
  1608. for (int i = 0; i < (int)channels.size(); ++i)
  1609. swizzle->addImmediateOperand(channels[i]);
  1610. buildPoint->addInstruction(std::unique_ptr<Instruction>(swizzle));
  1611. return setPrecision(swizzle->getResultId(), precision);
  1612. }
  1613. // Comments in header
  1614. Id Builder::createLvalueSwizzle(Id typeId, Id target, Id source, const std::vector<unsigned>& channels)
  1615. {
  1616. if (channels.size() == 1 && getNumComponents(source) == 1)
  1617. return createCompositeInsert(source, target, typeId, channels.front());
  1618. Instruction* swizzle = new Instruction(getUniqueId(), typeId, OpVectorShuffle);
  1619. assert(isVector(target));
  1620. swizzle->addIdOperand(target);
  1621. assert(getNumComponents(source) == (int)channels.size());
  1622. assert(isVector(source));
  1623. swizzle->addIdOperand(source);
  1624. // Set up an identity shuffle from the base value to the result value
  1625. unsigned int components[4];
  1626. int numTargetComponents = getNumComponents(target);
  1627. for (int i = 0; i < numTargetComponents; ++i)
  1628. components[i] = i;
  1629. // Punch in the l-value swizzle
  1630. for (int i = 0; i < (int)channels.size(); ++i)
  1631. components[channels[i]] = numTargetComponents + i;
  1632. // finish the instruction with these components selectors
  1633. for (int i = 0; i < numTargetComponents; ++i)
  1634. swizzle->addImmediateOperand(components[i]);
  1635. buildPoint->addInstruction(std::unique_ptr<Instruction>(swizzle));
  1636. return swizzle->getResultId();
  1637. }
  1638. // Comments in header
  1639. void Builder::promoteScalar(Decoration precision, Id& left, Id& right)
  1640. {
  1641. int direction = getNumComponents(right) - getNumComponents(left);
  1642. if (direction > 0)
  1643. left = smearScalar(precision, left, makeVectorType(getTypeId(left), getNumComponents(right)));
  1644. else if (direction < 0)
  1645. right = smearScalar(precision, right, makeVectorType(getTypeId(right), getNumComponents(left)));
  1646. return;
  1647. }
  1648. // Comments in header
  1649. Id Builder::smearScalar(Decoration precision, Id scalar, Id vectorType)
  1650. {
  1651. assert(getNumComponents(scalar) == 1);
  1652. assert(getTypeId(scalar) == getScalarTypeId(vectorType));
  1653. int numComponents = getNumTypeComponents(vectorType);
  1654. if (numComponents == 1)
  1655. return scalar;
  1656. Instruction* smear = nullptr;
  1657. if (generatingOpCodeForSpecConst) {
  1658. auto members = std::vector<spv::Id>(numComponents, scalar);
  1659. // Sometime even in spec-constant-op mode, the temporary vector created by
  1660. // promoting a scalar might not be a spec constant. This should depend on
  1661. // the scalar.
  1662. // e.g.:
  1663. // const vec2 spec_const_result = a_spec_const_vec2 + a_front_end_const_scalar;
  1664. // In such cases, the temporary vector created from a_front_end_const_scalar
  1665. // is not a spec constant vector, even though the binary operation node is marked
  1666. // as 'specConstant' and we are in spec-constant-op mode.
  1667. auto result_id = makeCompositeConstant(vectorType, members, isSpecConstant(scalar));
  1668. smear = module.getInstruction(result_id);
  1669. } else {
  1670. smear = new Instruction(getUniqueId(), vectorType, OpCompositeConstruct);
  1671. for (int c = 0; c < numComponents; ++c)
  1672. smear->addIdOperand(scalar);
  1673. buildPoint->addInstruction(std::unique_ptr<Instruction>(smear));
  1674. }
  1675. return setPrecision(smear->getResultId(), precision);
  1676. }
  1677. // Comments in header
  1678. Id Builder::createBuiltinCall(Id resultType, Id builtins, int entryPoint, const std::vector<Id>& args)
  1679. {
  1680. Instruction* inst = new Instruction(getUniqueId(), resultType, OpExtInst);
  1681. inst->addIdOperand(builtins);
  1682. inst->addImmediateOperand(entryPoint);
  1683. for (int arg = 0; arg < (int)args.size(); ++arg)
  1684. inst->addIdOperand(args[arg]);
  1685. buildPoint->addInstruction(std::unique_ptr<Instruction>(inst));
  1686. return inst->getResultId();
  1687. }
  1688. // Accept all parameters needed to create a texture instruction.
  1689. // Create the correct instruction based on the inputs, and make the call.
  1690. Id Builder::createTextureCall(Decoration precision, Id resultType, bool sparse, bool fetch, bool proj, bool gather,
  1691. bool noImplicitLod, const TextureParameters& parameters, ImageOperandsMask signExtensionMask)
  1692. {
  1693. static const int maxTextureArgs = 10;
  1694. Id texArgs[maxTextureArgs] = {};
  1695. //
  1696. // Set up the fixed arguments
  1697. //
  1698. int numArgs = 0;
  1699. bool explicitLod = false;
  1700. texArgs[numArgs++] = parameters.sampler;
  1701. texArgs[numArgs++] = parameters.coords;
  1702. if (parameters.Dref != NoResult)
  1703. texArgs[numArgs++] = parameters.Dref;
  1704. if (parameters.component != NoResult)
  1705. texArgs[numArgs++] = parameters.component;
  1706. #ifndef GLSLANG_WEB
  1707. if (parameters.granularity != NoResult)
  1708. texArgs[numArgs++] = parameters.granularity;
  1709. if (parameters.coarse != NoResult)
  1710. texArgs[numArgs++] = parameters.coarse;
  1711. #endif
  1712. //
  1713. // Set up the optional arguments
  1714. //
  1715. int optArgNum = numArgs; // track which operand, if it exists, is the mask of optional arguments
  1716. ++numArgs; // speculatively make room for the mask operand
  1717. ImageOperandsMask mask = ImageOperandsMaskNone; // the mask operand
  1718. if (parameters.bias) {
  1719. mask = (ImageOperandsMask)(mask | ImageOperandsBiasMask);
  1720. texArgs[numArgs++] = parameters.bias;
  1721. }
  1722. if (parameters.lod) {
  1723. mask = (ImageOperandsMask)(mask | ImageOperandsLodMask);
  1724. texArgs[numArgs++] = parameters.lod;
  1725. explicitLod = true;
  1726. } else if (parameters.gradX) {
  1727. mask = (ImageOperandsMask)(mask | ImageOperandsGradMask);
  1728. texArgs[numArgs++] = parameters.gradX;
  1729. texArgs[numArgs++] = parameters.gradY;
  1730. explicitLod = true;
  1731. } else if (noImplicitLod && ! fetch && ! gather) {
  1732. // have to explicitly use lod of 0 if not allowed to have them be implicit, and
  1733. // we would otherwise be about to issue an implicit instruction
  1734. mask = (ImageOperandsMask)(mask | ImageOperandsLodMask);
  1735. texArgs[numArgs++] = makeFloatConstant(0.0);
  1736. explicitLod = true;
  1737. }
  1738. if (parameters.offset) {
  1739. if (isConstant(parameters.offset))
  1740. mask = (ImageOperandsMask)(mask | ImageOperandsConstOffsetMask);
  1741. else {
  1742. addCapability(CapabilityImageGatherExtended);
  1743. mask = (ImageOperandsMask)(mask | ImageOperandsOffsetMask);
  1744. }
  1745. texArgs[numArgs++] = parameters.offset;
  1746. }
  1747. if (parameters.offsets) {
  1748. addCapability(CapabilityImageGatherExtended);
  1749. mask = (ImageOperandsMask)(mask | ImageOperandsConstOffsetsMask);
  1750. texArgs[numArgs++] = parameters.offsets;
  1751. }
  1752. #ifndef GLSLANG_WEB
  1753. if (parameters.sample) {
  1754. mask = (ImageOperandsMask)(mask | ImageOperandsSampleMask);
  1755. texArgs[numArgs++] = parameters.sample;
  1756. }
  1757. if (parameters.lodClamp) {
  1758. // capability if this bit is used
  1759. addCapability(CapabilityMinLod);
  1760. mask = (ImageOperandsMask)(mask | ImageOperandsMinLodMask);
  1761. texArgs[numArgs++] = parameters.lodClamp;
  1762. }
  1763. if (parameters.nonprivate) {
  1764. mask = mask | ImageOperandsNonPrivateTexelKHRMask;
  1765. }
  1766. if (parameters.volatil) {
  1767. mask = mask | ImageOperandsVolatileTexelKHRMask;
  1768. }
  1769. #endif
  1770. mask = mask | signExtensionMask;
  1771. if (mask == ImageOperandsMaskNone)
  1772. --numArgs; // undo speculative reservation for the mask argument
  1773. else
  1774. texArgs[optArgNum] = mask;
  1775. //
  1776. // Set up the instruction
  1777. //
  1778. Op opCode = OpNop; // All paths below need to set this
  1779. if (fetch) {
  1780. if (sparse)
  1781. opCode = OpImageSparseFetch;
  1782. else
  1783. opCode = OpImageFetch;
  1784. #ifndef GLSLANG_WEB
  1785. } else if (parameters.granularity && parameters.coarse) {
  1786. opCode = OpImageSampleFootprintNV;
  1787. } else if (gather) {
  1788. if (parameters.Dref)
  1789. if (sparse)
  1790. opCode = OpImageSparseDrefGather;
  1791. else
  1792. opCode = OpImageDrefGather;
  1793. else
  1794. if (sparse)
  1795. opCode = OpImageSparseGather;
  1796. else
  1797. opCode = OpImageGather;
  1798. #endif
  1799. } else if (explicitLod) {
  1800. if (parameters.Dref) {
  1801. if (proj)
  1802. if (sparse)
  1803. opCode = OpImageSparseSampleProjDrefExplicitLod;
  1804. else
  1805. opCode = OpImageSampleProjDrefExplicitLod;
  1806. else
  1807. if (sparse)
  1808. opCode = OpImageSparseSampleDrefExplicitLod;
  1809. else
  1810. opCode = OpImageSampleDrefExplicitLod;
  1811. } else {
  1812. if (proj)
  1813. if (sparse)
  1814. opCode = OpImageSparseSampleProjExplicitLod;
  1815. else
  1816. opCode = OpImageSampleProjExplicitLod;
  1817. else
  1818. if (sparse)
  1819. opCode = OpImageSparseSampleExplicitLod;
  1820. else
  1821. opCode = OpImageSampleExplicitLod;
  1822. }
  1823. } else {
  1824. if (parameters.Dref) {
  1825. if (proj)
  1826. if (sparse)
  1827. opCode = OpImageSparseSampleProjDrefImplicitLod;
  1828. else
  1829. opCode = OpImageSampleProjDrefImplicitLod;
  1830. else
  1831. if (sparse)
  1832. opCode = OpImageSparseSampleDrefImplicitLod;
  1833. else
  1834. opCode = OpImageSampleDrefImplicitLod;
  1835. } else {
  1836. if (proj)
  1837. if (sparse)
  1838. opCode = OpImageSparseSampleProjImplicitLod;
  1839. else
  1840. opCode = OpImageSampleProjImplicitLod;
  1841. else
  1842. if (sparse)
  1843. opCode = OpImageSparseSampleImplicitLod;
  1844. else
  1845. opCode = OpImageSampleImplicitLod;
  1846. }
  1847. }
  1848. // See if the result type is expecting a smeared result.
  1849. // This happens when a legacy shadow*() call is made, which
  1850. // gets a vec4 back instead of a float.
  1851. Id smearedType = resultType;
  1852. if (! isScalarType(resultType)) {
  1853. switch (opCode) {
  1854. case OpImageSampleDrefImplicitLod:
  1855. case OpImageSampleDrefExplicitLod:
  1856. case OpImageSampleProjDrefImplicitLod:
  1857. case OpImageSampleProjDrefExplicitLod:
  1858. resultType = getScalarTypeId(resultType);
  1859. break;
  1860. default:
  1861. break;
  1862. }
  1863. }
  1864. Id typeId0 = 0;
  1865. Id typeId1 = 0;
  1866. if (sparse) {
  1867. typeId0 = resultType;
  1868. typeId1 = getDerefTypeId(parameters.texelOut);
  1869. resultType = makeStructResultType(typeId0, typeId1);
  1870. }
  1871. // Build the SPIR-V instruction
  1872. Instruction* textureInst = new Instruction(getUniqueId(), resultType, opCode);
  1873. for (int op = 0; op < optArgNum; ++op)
  1874. textureInst->addIdOperand(texArgs[op]);
  1875. if (optArgNum < numArgs)
  1876. textureInst->addImmediateOperand(texArgs[optArgNum]);
  1877. for (int op = optArgNum + 1; op < numArgs; ++op)
  1878. textureInst->addIdOperand(texArgs[op]);
  1879. setPrecision(textureInst->getResultId(), precision);
  1880. buildPoint->addInstruction(std::unique_ptr<Instruction>(textureInst));
  1881. Id resultId = textureInst->getResultId();
  1882. if (sparse) {
  1883. // set capability
  1884. addCapability(CapabilitySparseResidency);
  1885. // Decode the return type that was a special structure
  1886. createStore(createCompositeExtract(resultId, typeId1, 1), parameters.texelOut);
  1887. resultId = createCompositeExtract(resultId, typeId0, 0);
  1888. setPrecision(resultId, precision);
  1889. } else {
  1890. // When a smear is needed, do it, as per what was computed
  1891. // above when resultType was changed to a scalar type.
  1892. if (resultType != smearedType)
  1893. resultId = smearScalar(precision, resultId, smearedType);
  1894. }
  1895. return resultId;
  1896. }
  1897. // Comments in header
  1898. Id Builder::createTextureQueryCall(Op opCode, const TextureParameters& parameters, bool isUnsignedResult)
  1899. {
  1900. // Figure out the result type
  1901. Id resultType = 0;
  1902. switch (opCode) {
  1903. case OpImageQuerySize:
  1904. case OpImageQuerySizeLod:
  1905. {
  1906. int numComponents = 0;
  1907. switch (getTypeDimensionality(getImageType(parameters.sampler))) {
  1908. case Dim1D:
  1909. case DimBuffer:
  1910. numComponents = 1;
  1911. break;
  1912. case Dim2D:
  1913. case DimCube:
  1914. case DimRect:
  1915. case DimSubpassData:
  1916. numComponents = 2;
  1917. break;
  1918. case Dim3D:
  1919. numComponents = 3;
  1920. break;
  1921. default:
  1922. assert(0);
  1923. break;
  1924. }
  1925. if (isArrayedImageType(getImageType(parameters.sampler)))
  1926. ++numComponents;
  1927. Id intType = isUnsignedResult ? makeUintType(32) : makeIntType(32);
  1928. if (numComponents == 1)
  1929. resultType = intType;
  1930. else
  1931. resultType = makeVectorType(intType, numComponents);
  1932. break;
  1933. }
  1934. case OpImageQueryLod:
  1935. resultType = makeVectorType(getScalarTypeId(getTypeId(parameters.coords)), 2);
  1936. break;
  1937. case OpImageQueryLevels:
  1938. case OpImageQuerySamples:
  1939. resultType = isUnsignedResult ? makeUintType(32) : makeIntType(32);
  1940. break;
  1941. default:
  1942. assert(0);
  1943. break;
  1944. }
  1945. Instruction* query = new Instruction(getUniqueId(), resultType, opCode);
  1946. query->addIdOperand(parameters.sampler);
  1947. if (parameters.coords)
  1948. query->addIdOperand(parameters.coords);
  1949. if (parameters.lod)
  1950. query->addIdOperand(parameters.lod);
  1951. buildPoint->addInstruction(std::unique_ptr<Instruction>(query));
  1952. addCapability(CapabilityImageQuery);
  1953. return query->getResultId();
  1954. }
  1955. // External comments in header.
  1956. // Operates recursively to visit the composite's hierarchy.
  1957. Id Builder::createCompositeCompare(Decoration precision, Id value1, Id value2, bool equal)
  1958. {
  1959. Id boolType = makeBoolType();
  1960. Id valueType = getTypeId(value1);
  1961. Id resultId = NoResult;
  1962. int numConstituents = getNumTypeConstituents(valueType);
  1963. // Scalars and Vectors
  1964. if (isScalarType(valueType) || isVectorType(valueType)) {
  1965. assert(valueType == getTypeId(value2));
  1966. // These just need a single comparison, just have
  1967. // to figure out what it is.
  1968. Op op;
  1969. switch (getMostBasicTypeClass(valueType)) {
  1970. case OpTypeFloat:
  1971. op = equal ? OpFOrdEqual : OpFUnordNotEqual;
  1972. break;
  1973. case OpTypeInt:
  1974. default:
  1975. op = equal ? OpIEqual : OpINotEqual;
  1976. break;
  1977. case OpTypeBool:
  1978. op = equal ? OpLogicalEqual : OpLogicalNotEqual;
  1979. precision = NoPrecision;
  1980. break;
  1981. }
  1982. if (isScalarType(valueType)) {
  1983. // scalar
  1984. resultId = createBinOp(op, boolType, value1, value2);
  1985. } else {
  1986. // vector
  1987. resultId = createBinOp(op, makeVectorType(boolType, numConstituents), value1, value2);
  1988. setPrecision(resultId, precision);
  1989. // reduce vector compares...
  1990. resultId = createUnaryOp(equal ? OpAll : OpAny, boolType, resultId);
  1991. }
  1992. return setPrecision(resultId, precision);
  1993. }
  1994. // Only structs, arrays, and matrices should be left.
  1995. // They share in common the reduction operation across their constituents.
  1996. assert(isAggregateType(valueType) || isMatrixType(valueType));
  1997. // Compare each pair of constituents
  1998. for (int constituent = 0; constituent < numConstituents; ++constituent) {
  1999. std::vector<unsigned> indexes(1, constituent);
  2000. Id constituentType1 = getContainedTypeId(getTypeId(value1), constituent);
  2001. Id constituentType2 = getContainedTypeId(getTypeId(value2), constituent);
  2002. Id constituent1 = createCompositeExtract(value1, constituentType1, indexes);
  2003. Id constituent2 = createCompositeExtract(value2, constituentType2, indexes);
  2004. Id subResultId = createCompositeCompare(precision, constituent1, constituent2, equal);
  2005. if (constituent == 0)
  2006. resultId = subResultId;
  2007. else
  2008. resultId = setPrecision(createBinOp(equal ? OpLogicalAnd : OpLogicalOr, boolType, resultId, subResultId),
  2009. precision);
  2010. }
  2011. return resultId;
  2012. }
  2013. // OpCompositeConstruct
  2014. Id Builder::createCompositeConstruct(Id typeId, const std::vector<Id>& constituents)
  2015. {
  2016. assert(isAggregateType(typeId) || (getNumTypeConstituents(typeId) > 1 &&
  2017. getNumTypeConstituents(typeId) == (int)constituents.size()));
  2018. if (generatingOpCodeForSpecConst) {
  2019. // Sometime, even in spec-constant-op mode, the constant composite to be
  2020. // constructed may not be a specialization constant.
  2021. // e.g.:
  2022. // const mat2 m2 = mat2(a_spec_const, a_front_end_const, another_front_end_const, third_front_end_const);
  2023. // The first column vector should be a spec constant one, as a_spec_const is a spec constant.
  2024. // The second column vector should NOT be spec constant, as it does not contain any spec constants.
  2025. // To handle such cases, we check the constituents of the constant vector to determine whether this
  2026. // vector should be created as a spec constant.
  2027. return makeCompositeConstant(typeId, constituents,
  2028. std::any_of(constituents.begin(), constituents.end(),
  2029. [&](spv::Id id) { return isSpecConstant(id); }));
  2030. }
  2031. Instruction* op = new Instruction(getUniqueId(), typeId, OpCompositeConstruct);
  2032. for (int c = 0; c < (int)constituents.size(); ++c)
  2033. op->addIdOperand(constituents[c]);
  2034. buildPoint->addInstruction(std::unique_ptr<Instruction>(op));
  2035. return op->getResultId();
  2036. }
  2037. // Vector or scalar constructor
  2038. Id Builder::createConstructor(Decoration precision, const std::vector<Id>& sources, Id resultTypeId)
  2039. {
  2040. Id result = NoResult;
  2041. unsigned int numTargetComponents = getNumTypeComponents(resultTypeId);
  2042. unsigned int targetComponent = 0;
  2043. // Special case: when calling a vector constructor with a single scalar
  2044. // argument, smear the scalar
  2045. if (sources.size() == 1 && isScalar(sources[0]) && numTargetComponents > 1)
  2046. return smearScalar(precision, sources[0], resultTypeId);
  2047. // accumulate the arguments for OpCompositeConstruct
  2048. std::vector<Id> constituents;
  2049. Id scalarTypeId = getScalarTypeId(resultTypeId);
  2050. // lambda to store the result of visiting an argument component
  2051. const auto latchResult = [&](Id comp) {
  2052. if (numTargetComponents > 1)
  2053. constituents.push_back(comp);
  2054. else
  2055. result = comp;
  2056. ++targetComponent;
  2057. };
  2058. // lambda to visit a vector argument's components
  2059. const auto accumulateVectorConstituents = [&](Id sourceArg) {
  2060. unsigned int sourceSize = getNumComponents(sourceArg);
  2061. unsigned int sourcesToUse = sourceSize;
  2062. if (sourcesToUse + targetComponent > numTargetComponents)
  2063. sourcesToUse = numTargetComponents - targetComponent;
  2064. for (unsigned int s = 0; s < sourcesToUse; ++s) {
  2065. std::vector<unsigned> swiz;
  2066. swiz.push_back(s);
  2067. latchResult(createRvalueSwizzle(precision, scalarTypeId, sourceArg, swiz));
  2068. }
  2069. };
  2070. // lambda to visit a matrix argument's components
  2071. const auto accumulateMatrixConstituents = [&](Id sourceArg) {
  2072. unsigned int sourceSize = getNumColumns(sourceArg) * getNumRows(sourceArg);
  2073. unsigned int sourcesToUse = sourceSize;
  2074. if (sourcesToUse + targetComponent > numTargetComponents)
  2075. sourcesToUse = numTargetComponents - targetComponent;
  2076. int col = 0;
  2077. int row = 0;
  2078. for (unsigned int s = 0; s < sourcesToUse; ++s) {
  2079. if (row >= getNumRows(sourceArg)) {
  2080. row = 0;
  2081. col++;
  2082. }
  2083. std::vector<Id> indexes;
  2084. indexes.push_back(col);
  2085. indexes.push_back(row);
  2086. latchResult(createCompositeExtract(sourceArg, scalarTypeId, indexes));
  2087. row++;
  2088. }
  2089. };
  2090. // Go through the source arguments, each one could have either
  2091. // a single or multiple components to contribute.
  2092. for (unsigned int i = 0; i < sources.size(); ++i) {
  2093. if (isScalar(sources[i]) || isPointer(sources[i]))
  2094. latchResult(sources[i]);
  2095. else if (isVector(sources[i]))
  2096. accumulateVectorConstituents(sources[i]);
  2097. else if (isMatrix(sources[i]))
  2098. accumulateMatrixConstituents(sources[i]);
  2099. else
  2100. assert(0);
  2101. if (targetComponent >= numTargetComponents)
  2102. break;
  2103. }
  2104. // If the result is a vector, make it from the gathered constituents.
  2105. if (constituents.size() > 0)
  2106. result = createCompositeConstruct(resultTypeId, constituents);
  2107. return setPrecision(result, precision);
  2108. }
  2109. // Comments in header
  2110. Id Builder::createMatrixConstructor(Decoration precision, const std::vector<Id>& sources, Id resultTypeId)
  2111. {
  2112. Id componentTypeId = getScalarTypeId(resultTypeId);
  2113. int numCols = getTypeNumColumns(resultTypeId);
  2114. int numRows = getTypeNumRows(resultTypeId);
  2115. Instruction* instr = module.getInstruction(componentTypeId);
  2116. #ifdef GLSLANG_WEB
  2117. const unsigned bitCount = 32;
  2118. assert(bitCount == instr->getImmediateOperand(0));
  2119. #else
  2120. const unsigned bitCount = instr->getImmediateOperand(0);
  2121. #endif
  2122. // Optimize matrix constructed from a bigger matrix
  2123. if (isMatrix(sources[0]) && getNumColumns(sources[0]) >= numCols && getNumRows(sources[0]) >= numRows) {
  2124. // To truncate the matrix to a smaller number of rows/columns, we need to:
  2125. // 1. For each column, extract the column and truncate it to the required size using shuffle
  2126. // 2. Assemble the resulting matrix from all columns
  2127. Id matrix = sources[0];
  2128. Id columnTypeId = getContainedTypeId(resultTypeId);
  2129. Id sourceColumnTypeId = getContainedTypeId(getTypeId(matrix));
  2130. std::vector<unsigned> channels;
  2131. for (int row = 0; row < numRows; ++row)
  2132. channels.push_back(row);
  2133. std::vector<Id> matrixColumns;
  2134. for (int col = 0; col < numCols; ++col) {
  2135. std::vector<unsigned> indexes;
  2136. indexes.push_back(col);
  2137. Id colv = createCompositeExtract(matrix, sourceColumnTypeId, indexes);
  2138. setPrecision(colv, precision);
  2139. if (numRows != getNumRows(matrix)) {
  2140. matrixColumns.push_back(createRvalueSwizzle(precision, columnTypeId, colv, channels));
  2141. } else {
  2142. matrixColumns.push_back(colv);
  2143. }
  2144. }
  2145. return setPrecision(createCompositeConstruct(resultTypeId, matrixColumns), precision);
  2146. }
  2147. // Otherwise, will use a two step process
  2148. // 1. make a compile-time 2D array of values
  2149. // 2. construct a matrix from that array
  2150. // Step 1.
  2151. // initialize the array to the identity matrix
  2152. Id ids[maxMatrixSize][maxMatrixSize];
  2153. Id one = (bitCount == 64 ? makeDoubleConstant(1.0) : makeFloatConstant(1.0));
  2154. Id zero = (bitCount == 64 ? makeDoubleConstant(0.0) : makeFloatConstant(0.0));
  2155. for (int col = 0; col < 4; ++col) {
  2156. for (int row = 0; row < 4; ++row) {
  2157. if (col == row)
  2158. ids[col][row] = one;
  2159. else
  2160. ids[col][row] = zero;
  2161. }
  2162. }
  2163. // modify components as dictated by the arguments
  2164. if (sources.size() == 1 && isScalar(sources[0])) {
  2165. // a single scalar; resets the diagonals
  2166. for (int col = 0; col < 4; ++col)
  2167. ids[col][col] = sources[0];
  2168. } else if (isMatrix(sources[0])) {
  2169. // constructing from another matrix; copy over the parts that exist in both the argument and constructee
  2170. Id matrix = sources[0];
  2171. int minCols = std::min(numCols, getNumColumns(matrix));
  2172. int minRows = std::min(numRows, getNumRows(matrix));
  2173. for (int col = 0; col < minCols; ++col) {
  2174. std::vector<unsigned> indexes;
  2175. indexes.push_back(col);
  2176. for (int row = 0; row < minRows; ++row) {
  2177. indexes.push_back(row);
  2178. ids[col][row] = createCompositeExtract(matrix, componentTypeId, indexes);
  2179. indexes.pop_back();
  2180. setPrecision(ids[col][row], precision);
  2181. }
  2182. }
  2183. } else {
  2184. // fill in the matrix in column-major order with whatever argument components are available
  2185. int row = 0;
  2186. int col = 0;
  2187. for (int arg = 0; arg < (int)sources.size(); ++arg) {
  2188. Id argComp = sources[arg];
  2189. for (int comp = 0; comp < getNumComponents(sources[arg]); ++comp) {
  2190. if (getNumComponents(sources[arg]) > 1) {
  2191. argComp = createCompositeExtract(sources[arg], componentTypeId, comp);
  2192. setPrecision(argComp, precision);
  2193. }
  2194. ids[col][row++] = argComp;
  2195. if (row == numRows) {
  2196. row = 0;
  2197. col++;
  2198. }
  2199. }
  2200. }
  2201. }
  2202. // Step 2: Construct a matrix from that array.
  2203. // First make the column vectors, then make the matrix.
  2204. // make the column vectors
  2205. Id columnTypeId = getContainedTypeId(resultTypeId);
  2206. std::vector<Id> matrixColumns;
  2207. for (int col = 0; col < numCols; ++col) {
  2208. std::vector<Id> vectorComponents;
  2209. for (int row = 0; row < numRows; ++row)
  2210. vectorComponents.push_back(ids[col][row]);
  2211. Id column = createCompositeConstruct(columnTypeId, vectorComponents);
  2212. setPrecision(column, precision);
  2213. matrixColumns.push_back(column);
  2214. }
  2215. // make the matrix
  2216. return setPrecision(createCompositeConstruct(resultTypeId, matrixColumns), precision);
  2217. }
  2218. // Comments in header
  2219. Builder::If::If(Id cond, unsigned int ctrl, Builder& gb) :
  2220. builder(gb),
  2221. condition(cond),
  2222. control(ctrl),
  2223. elseBlock(0)
  2224. {
  2225. function = &builder.getBuildPoint()->getParent();
  2226. // make the blocks, but only put the then-block into the function,
  2227. // the else-block and merge-block will be added later, in order, after
  2228. // earlier code is emitted
  2229. thenBlock = new Block(builder.getUniqueId(), *function);
  2230. mergeBlock = new Block(builder.getUniqueId(), *function);
  2231. // Save the current block, so that we can add in the flow control split when
  2232. // makeEndIf is called.
  2233. headerBlock = builder.getBuildPoint();
  2234. function->addBlock(thenBlock);
  2235. builder.setBuildPoint(thenBlock);
  2236. }
  2237. // Comments in header
  2238. void Builder::If::makeBeginElse()
  2239. {
  2240. // Close out the "then" by having it jump to the mergeBlock
  2241. builder.createBranch(mergeBlock);
  2242. // Make the first else block and add it to the function
  2243. elseBlock = new Block(builder.getUniqueId(), *function);
  2244. function->addBlock(elseBlock);
  2245. // Start building the else block
  2246. builder.setBuildPoint(elseBlock);
  2247. }
  2248. // Comments in header
  2249. void Builder::If::makeEndIf()
  2250. {
  2251. // jump to the merge block
  2252. builder.createBranch(mergeBlock);
  2253. // Go back to the headerBlock and make the flow control split
  2254. builder.setBuildPoint(headerBlock);
  2255. builder.createSelectionMerge(mergeBlock, control);
  2256. if (elseBlock)
  2257. builder.createConditionalBranch(condition, thenBlock, elseBlock);
  2258. else
  2259. builder.createConditionalBranch(condition, thenBlock, mergeBlock);
  2260. // add the merge block to the function
  2261. function->addBlock(mergeBlock);
  2262. builder.setBuildPoint(mergeBlock);
  2263. }
  2264. // Comments in header
  2265. void Builder::makeSwitch(Id selector, unsigned int control, int numSegments, const std::vector<int>& caseValues,
  2266. const std::vector<int>& valueIndexToSegment, int defaultSegment,
  2267. std::vector<Block*>& segmentBlocks)
  2268. {
  2269. Function& function = buildPoint->getParent();
  2270. // make all the blocks
  2271. for (int s = 0; s < numSegments; ++s)
  2272. segmentBlocks.push_back(new Block(getUniqueId(), function));
  2273. Block* mergeBlock = new Block(getUniqueId(), function);
  2274. // make and insert the switch's selection-merge instruction
  2275. createSelectionMerge(mergeBlock, control);
  2276. // make the switch instruction
  2277. Instruction* switchInst = new Instruction(NoResult, NoType, OpSwitch);
  2278. switchInst->addIdOperand(selector);
  2279. auto defaultOrMerge = (defaultSegment >= 0) ? segmentBlocks[defaultSegment] : mergeBlock;
  2280. switchInst->addIdOperand(defaultOrMerge->getId());
  2281. defaultOrMerge->addPredecessor(buildPoint);
  2282. for (int i = 0; i < (int)caseValues.size(); ++i) {
  2283. switchInst->addImmediateOperand(caseValues[i]);
  2284. switchInst->addIdOperand(segmentBlocks[valueIndexToSegment[i]]->getId());
  2285. segmentBlocks[valueIndexToSegment[i]]->addPredecessor(buildPoint);
  2286. }
  2287. buildPoint->addInstruction(std::unique_ptr<Instruction>(switchInst));
  2288. // push the merge block
  2289. switchMerges.push(mergeBlock);
  2290. }
  2291. // Comments in header
  2292. void Builder::addSwitchBreak()
  2293. {
  2294. // branch to the top of the merge block stack
  2295. createBranch(switchMerges.top());
  2296. createAndSetNoPredecessorBlock("post-switch-break");
  2297. }
  2298. // Comments in header
  2299. void Builder::nextSwitchSegment(std::vector<Block*>& segmentBlock, int nextSegment)
  2300. {
  2301. int lastSegment = nextSegment - 1;
  2302. if (lastSegment >= 0) {
  2303. // Close out previous segment by jumping, if necessary, to next segment
  2304. if (! buildPoint->isTerminated())
  2305. createBranch(segmentBlock[nextSegment]);
  2306. }
  2307. Block* block = segmentBlock[nextSegment];
  2308. block->getParent().addBlock(block);
  2309. setBuildPoint(block);
  2310. }
  2311. // Comments in header
  2312. void Builder::endSwitch(std::vector<Block*>& /*segmentBlock*/)
  2313. {
  2314. // Close out previous segment by jumping, if necessary, to next segment
  2315. if (! buildPoint->isTerminated())
  2316. addSwitchBreak();
  2317. switchMerges.top()->getParent().addBlock(switchMerges.top());
  2318. setBuildPoint(switchMerges.top());
  2319. switchMerges.pop();
  2320. }
  2321. Block& Builder::makeNewBlock()
  2322. {
  2323. Function& function = buildPoint->getParent();
  2324. auto block = new Block(getUniqueId(), function);
  2325. function.addBlock(block);
  2326. return *block;
  2327. }
  2328. Builder::LoopBlocks& Builder::makeNewLoop()
  2329. {
  2330. // This verbosity is needed to simultaneously get the same behavior
  2331. // everywhere (id's in the same order), have a syntax that works
  2332. // across lots of versions of C++, have no warnings from pedantic
  2333. // compilation modes, and leave the rest of the code alone.
  2334. Block& head = makeNewBlock();
  2335. Block& body = makeNewBlock();
  2336. Block& merge = makeNewBlock();
  2337. Block& continue_target = makeNewBlock();
  2338. LoopBlocks blocks(head, body, merge, continue_target);
  2339. loops.push(blocks);
  2340. return loops.top();
  2341. }
  2342. void Builder::createLoopContinue()
  2343. {
  2344. createBranch(&loops.top().continue_target);
  2345. // Set up a block for dead code.
  2346. createAndSetNoPredecessorBlock("post-loop-continue");
  2347. }
  2348. void Builder::createLoopExit()
  2349. {
  2350. createBranch(&loops.top().merge);
  2351. // Set up a block for dead code.
  2352. createAndSetNoPredecessorBlock("post-loop-break");
  2353. }
  2354. void Builder::closeLoop()
  2355. {
  2356. loops.pop();
  2357. }
  2358. void Builder::clearAccessChain()
  2359. {
  2360. accessChain.base = NoResult;
  2361. accessChain.indexChain.clear();
  2362. accessChain.instr = NoResult;
  2363. accessChain.swizzle.clear();
  2364. accessChain.component = NoResult;
  2365. accessChain.preSwizzleBaseType = NoType;
  2366. accessChain.isRValue = false;
  2367. accessChain.coherentFlags.clear();
  2368. accessChain.alignment = 0;
  2369. }
  2370. // Comments in header
  2371. void Builder::accessChainPushSwizzle(std::vector<unsigned>& swizzle, Id preSwizzleBaseType,
  2372. AccessChain::CoherentFlags coherentFlags, unsigned int alignment)
  2373. {
  2374. accessChain.coherentFlags |= coherentFlags;
  2375. accessChain.alignment |= alignment;
  2376. // swizzles can be stacked in GLSL, but simplified to a single
  2377. // one here; the base type doesn't change
  2378. if (accessChain.preSwizzleBaseType == NoType)
  2379. accessChain.preSwizzleBaseType = preSwizzleBaseType;
  2380. // if needed, propagate the swizzle for the current access chain
  2381. if (accessChain.swizzle.size() > 0) {
  2382. std::vector<unsigned> oldSwizzle = accessChain.swizzle;
  2383. accessChain.swizzle.resize(0);
  2384. for (unsigned int i = 0; i < swizzle.size(); ++i) {
  2385. assert(swizzle[i] < oldSwizzle.size());
  2386. accessChain.swizzle.push_back(oldSwizzle[swizzle[i]]);
  2387. }
  2388. } else
  2389. accessChain.swizzle = swizzle;
  2390. // determine if we need to track this swizzle anymore
  2391. simplifyAccessChainSwizzle();
  2392. }
  2393. // Comments in header
  2394. void Builder::accessChainStore(Id rvalue, Decoration nonUniform, spv::MemoryAccessMask memoryAccess, spv::Scope scope, unsigned int alignment)
  2395. {
  2396. assert(accessChain.isRValue == false);
  2397. transferAccessChainSwizzle(true);
  2398. Id base = collapseAccessChain();
  2399. addDecoration(base, nonUniform);
  2400. Id source = rvalue;
  2401. // dynamic component should be gone
  2402. assert(accessChain.component == NoResult);
  2403. // If swizzle still exists, it is out-of-order or not full, we must load the target vector,
  2404. // extract and insert elements to perform writeMask and/or swizzle.
  2405. if (accessChain.swizzle.size() > 0) {
  2406. Id tempBaseId = createLoad(base, spv::NoPrecision);
  2407. source = createLvalueSwizzle(getTypeId(tempBaseId), tempBaseId, source, accessChain.swizzle);
  2408. }
  2409. // take LSB of alignment
  2410. alignment = alignment & ~(alignment & (alignment-1));
  2411. if (getStorageClass(base) == StorageClassPhysicalStorageBufferEXT) {
  2412. memoryAccess = (spv::MemoryAccessMask)(memoryAccess | spv::MemoryAccessAlignedMask);
  2413. }
  2414. createStore(source, base, memoryAccess, scope, alignment);
  2415. }
  2416. // Comments in header
  2417. Id Builder::accessChainLoad(Decoration precision, Decoration l_nonUniform,
  2418. Decoration r_nonUniform, Id resultType, spv::MemoryAccessMask memoryAccess,
  2419. spv::Scope scope, unsigned int alignment)
  2420. {
  2421. Id id;
  2422. if (accessChain.isRValue) {
  2423. // transfer access chain, but try to stay in registers
  2424. transferAccessChainSwizzle(false);
  2425. if (accessChain.indexChain.size() > 0) {
  2426. Id swizzleBase = accessChain.preSwizzleBaseType != NoType ? accessChain.preSwizzleBaseType : resultType;
  2427. // if all the accesses are constants, we can use OpCompositeExtract
  2428. std::vector<unsigned> indexes;
  2429. bool constant = true;
  2430. for (int i = 0; i < (int)accessChain.indexChain.size(); ++i) {
  2431. if (isConstantScalar(accessChain.indexChain[i]))
  2432. indexes.push_back(getConstantScalar(accessChain.indexChain[i]));
  2433. else {
  2434. constant = false;
  2435. break;
  2436. }
  2437. }
  2438. if (constant) {
  2439. id = createCompositeExtract(accessChain.base, swizzleBase, indexes);
  2440. setPrecision(id, precision);
  2441. } else {
  2442. Id lValue = NoResult;
  2443. if (spvVersion >= Spv_1_4 && isValidInitializer(accessChain.base)) {
  2444. // make a new function variable for this r-value, using an initializer,
  2445. // and mark it as NonWritable so that downstream it can be detected as a lookup
  2446. // table
  2447. lValue = createVariable(NoPrecision, StorageClassFunction, getTypeId(accessChain.base),
  2448. "indexable", accessChain.base);
  2449. addDecoration(lValue, DecorationNonWritable);
  2450. } else {
  2451. lValue = createVariable(NoPrecision, StorageClassFunction, getTypeId(accessChain.base),
  2452. "indexable");
  2453. // store into it
  2454. createStore(accessChain.base, lValue);
  2455. }
  2456. // move base to the new variable
  2457. accessChain.base = lValue;
  2458. accessChain.isRValue = false;
  2459. // load through the access chain
  2460. id = createLoad(collapseAccessChain(), precision);
  2461. }
  2462. } else
  2463. id = accessChain.base; // no precision, it was set when this was defined
  2464. } else {
  2465. transferAccessChainSwizzle(true);
  2466. // take LSB of alignment
  2467. alignment = alignment & ~(alignment & (alignment-1));
  2468. if (getStorageClass(accessChain.base) == StorageClassPhysicalStorageBufferEXT) {
  2469. memoryAccess = (spv::MemoryAccessMask)(memoryAccess | spv::MemoryAccessAlignedMask);
  2470. }
  2471. // load through the access chain
  2472. id = collapseAccessChain();
  2473. // Apply nonuniform both to the access chain and the loaded value.
  2474. // Buffer accesses need the access chain decorated, and this is where
  2475. // loaded image types get decorated. TODO: This should maybe move to
  2476. // createImageTextureFunctionCall.
  2477. addDecoration(id, l_nonUniform);
  2478. id = createLoad(id, precision, memoryAccess, scope, alignment);
  2479. addDecoration(id, r_nonUniform);
  2480. }
  2481. // Done, unless there are swizzles to do
  2482. if (accessChain.swizzle.size() == 0 && accessChain.component == NoResult)
  2483. return id;
  2484. // Do remaining swizzling
  2485. // Do the basic swizzle
  2486. if (accessChain.swizzle.size() > 0) {
  2487. Id swizzledType = getScalarTypeId(getTypeId(id));
  2488. if (accessChain.swizzle.size() > 1)
  2489. swizzledType = makeVectorType(swizzledType, (int)accessChain.swizzle.size());
  2490. id = createRvalueSwizzle(precision, swizzledType, id, accessChain.swizzle);
  2491. }
  2492. // Do the dynamic component
  2493. if (accessChain.component != NoResult)
  2494. id = setPrecision(createVectorExtractDynamic(id, resultType, accessChain.component), precision);
  2495. addDecoration(id, r_nonUniform);
  2496. return id;
  2497. }
  2498. Id Builder::accessChainGetLValue()
  2499. {
  2500. assert(accessChain.isRValue == false);
  2501. transferAccessChainSwizzle(true);
  2502. Id lvalue = collapseAccessChain();
  2503. // If swizzle exists, it is out-of-order or not full, we must load the target vector,
  2504. // extract and insert elements to perform writeMask and/or swizzle. This does not
  2505. // go with getting a direct l-value pointer.
  2506. assert(accessChain.swizzle.size() == 0);
  2507. assert(accessChain.component == NoResult);
  2508. return lvalue;
  2509. }
  2510. // comment in header
  2511. Id Builder::accessChainGetInferredType()
  2512. {
  2513. // anything to operate on?
  2514. if (accessChain.base == NoResult)
  2515. return NoType;
  2516. Id type = getTypeId(accessChain.base);
  2517. // do initial dereference
  2518. if (! accessChain.isRValue)
  2519. type = getContainedTypeId(type);
  2520. // dereference each index
  2521. for (auto it = accessChain.indexChain.cbegin(); it != accessChain.indexChain.cend(); ++it) {
  2522. if (isStructType(type))
  2523. type = getContainedTypeId(type, getConstantScalar(*it));
  2524. else
  2525. type = getContainedTypeId(type);
  2526. }
  2527. // dereference swizzle
  2528. if (accessChain.swizzle.size() == 1)
  2529. type = getContainedTypeId(type);
  2530. else if (accessChain.swizzle.size() > 1)
  2531. type = makeVectorType(getContainedTypeId(type), (int)accessChain.swizzle.size());
  2532. // dereference component selection
  2533. if (accessChain.component)
  2534. type = getContainedTypeId(type);
  2535. return type;
  2536. }
  2537. void Builder::dump(std::vector<unsigned int>& out) const
  2538. {
  2539. // Header, before first instructions:
  2540. out.push_back(MagicNumber);
  2541. out.push_back(spvVersion);
  2542. out.push_back(builderNumber);
  2543. out.push_back(uniqueId + 1);
  2544. out.push_back(0);
  2545. // Capabilities
  2546. for (auto it = capabilities.cbegin(); it != capabilities.cend(); ++it) {
  2547. Instruction capInst(0, 0, OpCapability);
  2548. capInst.addImmediateOperand(*it);
  2549. capInst.dump(out);
  2550. }
  2551. for (auto it = extensions.cbegin(); it != extensions.cend(); ++it) {
  2552. Instruction extInst(0, 0, OpExtension);
  2553. extInst.addStringOperand(it->c_str());
  2554. extInst.dump(out);
  2555. }
  2556. dumpInstructions(out, imports);
  2557. Instruction memInst(0, 0, OpMemoryModel);
  2558. memInst.addImmediateOperand(addressModel);
  2559. memInst.addImmediateOperand(memoryModel);
  2560. memInst.dump(out);
  2561. // Instructions saved up while building:
  2562. dumpInstructions(out, entryPoints);
  2563. dumpInstructions(out, executionModes);
  2564. // Debug instructions
  2565. dumpInstructions(out, strings);
  2566. dumpSourceInstructions(out);
  2567. for (int e = 0; e < (int)sourceExtensions.size(); ++e) {
  2568. Instruction sourceExtInst(0, 0, OpSourceExtension);
  2569. sourceExtInst.addStringOperand(sourceExtensions[e]);
  2570. sourceExtInst.dump(out);
  2571. }
  2572. dumpInstructions(out, names);
  2573. dumpModuleProcesses(out);
  2574. // Annotation instructions
  2575. dumpInstructions(out, decorations);
  2576. dumpInstructions(out, constantsTypesGlobals);
  2577. dumpInstructions(out, externals);
  2578. // The functions
  2579. module.dump(out);
  2580. }
  2581. //
  2582. // Protected methods.
  2583. //
  2584. // Turn the described access chain in 'accessChain' into an instruction(s)
  2585. // computing its address. This *cannot* include complex swizzles, which must
  2586. // be handled after this is called.
  2587. //
  2588. // Can generate code.
  2589. Id Builder::collapseAccessChain()
  2590. {
  2591. assert(accessChain.isRValue == false);
  2592. // did we already emit an access chain for this?
  2593. if (accessChain.instr != NoResult)
  2594. return accessChain.instr;
  2595. // If we have a dynamic component, we can still transfer
  2596. // that into a final operand to the access chain. We need to remap the
  2597. // dynamic component through the swizzle to get a new dynamic component to
  2598. // update.
  2599. //
  2600. // This was not done in transferAccessChainSwizzle() because it might
  2601. // generate code.
  2602. remapDynamicSwizzle();
  2603. if (accessChain.component != NoResult) {
  2604. // transfer the dynamic component to the access chain
  2605. accessChain.indexChain.push_back(accessChain.component);
  2606. accessChain.component = NoResult;
  2607. }
  2608. // note that non-trivial swizzling is left pending
  2609. // do we have an access chain?
  2610. if (accessChain.indexChain.size() == 0)
  2611. return accessChain.base;
  2612. // emit the access chain
  2613. StorageClass storageClass = (StorageClass)module.getStorageClass(getTypeId(accessChain.base));
  2614. accessChain.instr = createAccessChain(storageClass, accessChain.base, accessChain.indexChain);
  2615. return accessChain.instr;
  2616. }
  2617. // For a dynamic component selection of a swizzle.
  2618. //
  2619. // Turn the swizzle and dynamic component into just a dynamic component.
  2620. //
  2621. // Generates code.
  2622. void Builder::remapDynamicSwizzle()
  2623. {
  2624. // do we have a swizzle to remap a dynamic component through?
  2625. if (accessChain.component != NoResult && accessChain.swizzle.size() > 1) {
  2626. // build a vector of the swizzle for the component to map into
  2627. std::vector<Id> components;
  2628. for (int c = 0; c < (int)accessChain.swizzle.size(); ++c)
  2629. components.push_back(makeUintConstant(accessChain.swizzle[c]));
  2630. Id mapType = makeVectorType(makeUintType(32), (int)accessChain.swizzle.size());
  2631. Id map = makeCompositeConstant(mapType, components);
  2632. // use it
  2633. accessChain.component = createVectorExtractDynamic(map, makeUintType(32), accessChain.component);
  2634. accessChain.swizzle.clear();
  2635. }
  2636. }
  2637. // clear out swizzle if it is redundant, that is reselecting the same components
  2638. // that would be present without the swizzle.
  2639. void Builder::simplifyAccessChainSwizzle()
  2640. {
  2641. // If the swizzle has fewer components than the vector, it is subsetting, and must stay
  2642. // to preserve that fact.
  2643. if (getNumTypeComponents(accessChain.preSwizzleBaseType) > (int)accessChain.swizzle.size())
  2644. return;
  2645. // if components are out of order, it is a swizzle
  2646. for (unsigned int i = 0; i < accessChain.swizzle.size(); ++i) {
  2647. if (i != accessChain.swizzle[i])
  2648. return;
  2649. }
  2650. // otherwise, there is no need to track this swizzle
  2651. accessChain.swizzle.clear();
  2652. if (accessChain.component == NoResult)
  2653. accessChain.preSwizzleBaseType = NoType;
  2654. }
  2655. // To the extent any swizzling can become part of the chain
  2656. // of accesses instead of a post operation, make it so.
  2657. // If 'dynamic' is true, include transferring the dynamic component,
  2658. // otherwise, leave it pending.
  2659. //
  2660. // Does not generate code. just updates the access chain.
  2661. void Builder::transferAccessChainSwizzle(bool dynamic)
  2662. {
  2663. // non existent?
  2664. if (accessChain.swizzle.size() == 0 && accessChain.component == NoResult)
  2665. return;
  2666. // too complex?
  2667. // (this requires either a swizzle, or generating code for a dynamic component)
  2668. if (accessChain.swizzle.size() > 1)
  2669. return;
  2670. // single component, either in the swizzle and/or dynamic component
  2671. if (accessChain.swizzle.size() == 1) {
  2672. assert(accessChain.component == NoResult);
  2673. // handle static component selection
  2674. accessChain.indexChain.push_back(makeUintConstant(accessChain.swizzle.front()));
  2675. accessChain.swizzle.clear();
  2676. accessChain.preSwizzleBaseType = NoType;
  2677. } else if (dynamic && accessChain.component != NoResult) {
  2678. assert(accessChain.swizzle.size() == 0);
  2679. // handle dynamic component
  2680. accessChain.indexChain.push_back(accessChain.component);
  2681. accessChain.preSwizzleBaseType = NoType;
  2682. accessChain.component = NoResult;
  2683. }
  2684. }
  2685. // Utility method for creating a new block and setting the insert point to
  2686. // be in it. This is useful for flow-control operations that need a "dummy"
  2687. // block proceeding them (e.g. instructions after a discard, etc).
  2688. void Builder::createAndSetNoPredecessorBlock(const char* /*name*/)
  2689. {
  2690. Block* block = new Block(getUniqueId(), buildPoint->getParent());
  2691. block->setUnreachable();
  2692. buildPoint->getParent().addBlock(block);
  2693. setBuildPoint(block);
  2694. // if (name)
  2695. // addName(block->getId(), name);
  2696. }
  2697. // Comments in header
  2698. void Builder::createBranch(Block* block)
  2699. {
  2700. Instruction* branch = new Instruction(OpBranch);
  2701. branch->addIdOperand(block->getId());
  2702. buildPoint->addInstruction(std::unique_ptr<Instruction>(branch));
  2703. block->addPredecessor(buildPoint);
  2704. }
  2705. void Builder::createSelectionMerge(Block* mergeBlock, unsigned int control)
  2706. {
  2707. Instruction* merge = new Instruction(OpSelectionMerge);
  2708. merge->addIdOperand(mergeBlock->getId());
  2709. merge->addImmediateOperand(control);
  2710. buildPoint->addInstruction(std::unique_ptr<Instruction>(merge));
  2711. }
  2712. void Builder::createLoopMerge(Block* mergeBlock, Block* continueBlock, unsigned int control,
  2713. const std::vector<unsigned int>& operands)
  2714. {
  2715. Instruction* merge = new Instruction(OpLoopMerge);
  2716. merge->addIdOperand(mergeBlock->getId());
  2717. merge->addIdOperand(continueBlock->getId());
  2718. merge->addImmediateOperand(control);
  2719. for (int op = 0; op < (int)operands.size(); ++op)
  2720. merge->addImmediateOperand(operands[op]);
  2721. buildPoint->addInstruction(std::unique_ptr<Instruction>(merge));
  2722. }
  2723. void Builder::createConditionalBranch(Id condition, Block* thenBlock, Block* elseBlock)
  2724. {
  2725. Instruction* branch = new Instruction(OpBranchConditional);
  2726. branch->addIdOperand(condition);
  2727. branch->addIdOperand(thenBlock->getId());
  2728. branch->addIdOperand(elseBlock->getId());
  2729. buildPoint->addInstruction(std::unique_ptr<Instruction>(branch));
  2730. thenBlock->addPredecessor(buildPoint);
  2731. elseBlock->addPredecessor(buildPoint);
  2732. }
  2733. // OpSource
  2734. // [OpSourceContinued]
  2735. // ...
  2736. void Builder::dumpSourceInstructions(const spv::Id fileId, const std::string& text,
  2737. std::vector<unsigned int>& out) const
  2738. {
  2739. const int maxWordCount = 0xFFFF;
  2740. const int opSourceWordCount = 4;
  2741. const int nonNullBytesPerInstruction = 4 * (maxWordCount - opSourceWordCount) - 1;
  2742. if (source != SourceLanguageUnknown) {
  2743. // OpSource Language Version File Source
  2744. Instruction sourceInst(NoResult, NoType, OpSource);
  2745. sourceInst.addImmediateOperand(source);
  2746. sourceInst.addImmediateOperand(sourceVersion);
  2747. // File operand
  2748. if (fileId != NoResult) {
  2749. sourceInst.addIdOperand(fileId);
  2750. // Source operand
  2751. if (text.size() > 0) {
  2752. int nextByte = 0;
  2753. std::string subString;
  2754. while ((int)text.size() - nextByte > 0) {
  2755. subString = text.substr(nextByte, nonNullBytesPerInstruction);
  2756. if (nextByte == 0) {
  2757. // OpSource
  2758. sourceInst.addStringOperand(subString.c_str());
  2759. sourceInst.dump(out);
  2760. } else {
  2761. // OpSourcContinued
  2762. Instruction sourceContinuedInst(OpSourceContinued);
  2763. sourceContinuedInst.addStringOperand(subString.c_str());
  2764. sourceContinuedInst.dump(out);
  2765. }
  2766. nextByte += nonNullBytesPerInstruction;
  2767. }
  2768. } else
  2769. sourceInst.dump(out);
  2770. } else
  2771. sourceInst.dump(out);
  2772. }
  2773. }
  2774. // Dump an OpSource[Continued] sequence for the source and every include file
  2775. void Builder::dumpSourceInstructions(std::vector<unsigned int>& out) const
  2776. {
  2777. dumpSourceInstructions(sourceFileStringId, sourceText, out);
  2778. for (auto iItr = includeFiles.begin(); iItr != includeFiles.end(); ++iItr)
  2779. dumpSourceInstructions(iItr->first, *iItr->second, out);
  2780. }
  2781. void Builder::dumpInstructions(std::vector<unsigned int>& out,
  2782. const std::vector<std::unique_ptr<Instruction> >& instructions) const
  2783. {
  2784. for (int i = 0; i < (int)instructions.size(); ++i) {
  2785. instructions[i]->dump(out);
  2786. }
  2787. }
  2788. void Builder::dumpModuleProcesses(std::vector<unsigned int>& out) const
  2789. {
  2790. for (int i = 0; i < (int)moduleProcesses.size(); ++i) {
  2791. Instruction moduleProcessed(OpModuleProcessed);
  2792. moduleProcessed.addStringOperand(moduleProcesses[i]);
  2793. moduleProcessed.dump(out);
  2794. }
  2795. }
  2796. }; // end spv namespace