SkSLByteCodeGenerator.cpp 58 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544
  1. /*
  2. * Copyright 2019 Google LLC
  3. *
  4. * Use of this source code is governed by a BSD-style license that can be
  5. * found in the LICENSE file.
  6. */
  7. #include "src/sksl/SkSLByteCodeGenerator.h"
  8. #include <algorithm>
  9. namespace SkSL {
  10. ByteCodeGenerator::ByteCodeGenerator(const Context* context, const Program* program, ErrorReporter* errors,
  11. ByteCode* output)
  12. : INHERITED(program, errors, nullptr)
  13. , fContext(*context)
  14. , fOutput(output)
  15. , fIntrinsics {
  16. { "cos", ByteCodeInstruction::kCos },
  17. { "cross", ByteCodeInstruction::kCross },
  18. { "dot", SpecialIntrinsic::kDot },
  19. { "inverse", ByteCodeInstruction::kInverse2x2 },
  20. { "sin", ByteCodeInstruction::kSin },
  21. { "sqrt", ByteCodeInstruction::kSqrt },
  22. { "tan", ByteCodeInstruction::kTan },
  23. { "mix", ByteCodeInstruction::kMix },
  24. } {}
  25. int ByteCodeGenerator::SlotCount(const Type& type) {
  26. if (type.kind() == Type::kOther_Kind) {
  27. return 0;
  28. } else if (type.kind() == Type::kStruct_Kind) {
  29. int slots = 0;
  30. for (const auto& f : type.fields()) {
  31. slots += SlotCount(*f.fType);
  32. }
  33. SkASSERT(slots <= 255);
  34. return slots;
  35. } else if (type.kind() == Type::kArray_Kind) {
  36. int columns = type.columns();
  37. SkASSERT(columns >= 0);
  38. int slots = columns * SlotCount(type.componentType());
  39. SkASSERT(slots <= 255);
  40. return slots;
  41. } else {
  42. return type.columns() * type.rows();
  43. }
  44. }
  45. bool ByteCodeGenerator::generateCode() {
  46. for (const auto& e : fProgram) {
  47. switch (e.fKind) {
  48. case ProgramElement::kFunction_Kind: {
  49. std::unique_ptr<ByteCodeFunction> f = this->writeFunction((FunctionDefinition&) e);
  50. if (!f) {
  51. return false;
  52. }
  53. fOutput->fFunctions.push_back(std::move(f));
  54. fFunctions.push_back(&(FunctionDefinition&)e);
  55. break;
  56. }
  57. case ProgramElement::kVar_Kind: {
  58. VarDeclarations& decl = (VarDeclarations&) e;
  59. for (const auto& v : decl.fVars) {
  60. const Variable* declVar = ((VarDeclaration&) *v).fVar;
  61. if (declVar->fModifiers.fLayout.fBuiltin >= 0) {
  62. continue;
  63. }
  64. if (declVar->fModifiers.fFlags & Modifiers::kIn_Flag) {
  65. for (int i = SlotCount(declVar->fType); i > 0; --i) {
  66. fOutput->fInputSlots.push_back(fOutput->fGlobalCount++);
  67. }
  68. } else {
  69. fOutput->fGlobalCount += SlotCount(declVar->fType);
  70. }
  71. }
  72. break;
  73. }
  74. default:
  75. ; // ignore
  76. }
  77. }
  78. return 0 == fErrors.errorCount();
  79. }
  80. std::unique_ptr<ByteCodeFunction> ByteCodeGenerator::writeFunction(const FunctionDefinition& f) {
  81. fFunction = &f;
  82. std::unique_ptr<ByteCodeFunction> result(new ByteCodeFunction(&f.fDeclaration));
  83. fParameterCount = result->fParameterCount;
  84. fLoopCount = fMaxLoopCount = 0;
  85. fConditionCount = fMaxConditionCount = 0;
  86. fStackCount = fMaxStackCount = 0;
  87. fCode = &result->fCode;
  88. this->writeStatement(*f.fBody);
  89. if (0 == fErrors.errorCount()) {
  90. SkASSERT(fLoopCount == 0);
  91. SkASSERT(fConditionCount == 0);
  92. SkASSERT(fStackCount == 0);
  93. }
  94. this->write(ByteCodeInstruction::kReturn, 0);
  95. this->write8(0);
  96. result->fLocalCount = fLocals.size();
  97. result->fConditionCount = fMaxConditionCount;
  98. result->fLoopCount = fMaxLoopCount;
  99. result->fStackCount = fMaxStackCount;
  100. const Type& returnType = f.fDeclaration.fReturnType;
  101. if (returnType != *fContext.fVoid_Type) {
  102. result->fReturnCount = SlotCount(returnType);
  103. }
  104. fLocals.clear();
  105. fFunction = nullptr;
  106. return result;
  107. }
  108. enum class TypeCategory {
  109. kBool,
  110. kSigned,
  111. kUnsigned,
  112. kFloat,
  113. };
  114. static TypeCategory type_category(const Type& type) {
  115. switch (type.kind()) {
  116. case Type::Kind::kVector_Kind:
  117. case Type::Kind::kMatrix_Kind:
  118. return type_category(type.componentType());
  119. default:
  120. if (type.fName == "bool") {
  121. return TypeCategory::kBool;
  122. } else if (type.fName == "int" || type.fName == "short") {
  123. return TypeCategory::kSigned;
  124. } else if (type.fName == "uint" || type.fName == "ushort") {
  125. return TypeCategory::kUnsigned;
  126. } else {
  127. SkASSERT(type.fName == "float" || type.fName == "half");
  128. return TypeCategory::kFloat;
  129. }
  130. ABORT("unsupported type: %s\n", type.description().c_str());
  131. }
  132. }
  133. // A "simple" Swizzle is based on a variable (or a compound variable like a struct or array), and
  134. // that references consecutive values, such that it can be implemented using normal load/store ops
  135. // with an offset. Note that all single-component swizzles (of suitable base types) are simple.
  136. static bool swizzle_is_simple(const Swizzle& s) {
  137. switch (s.fBase->fKind) {
  138. case Expression::kFieldAccess_Kind:
  139. case Expression::kIndex_Kind:
  140. case Expression::kVariableReference_Kind:
  141. break;
  142. default:
  143. return false;
  144. }
  145. for (size_t i = 1; i < s.fComponents.size(); ++i) {
  146. if (s.fComponents[i] != s.fComponents[i - 1] + 1) {
  147. return false;
  148. }
  149. }
  150. return true;
  151. }
  152. int ByteCodeGenerator::StackUsage(ByteCodeInstruction inst, int count_) {
  153. // Ensures that we use count iff we're passed a non-default value. Most instructions have an
  154. // implicit count, so the caller shouldn't need to worry about it (or count makes no sense).
  155. // The asserts avoids callers thinking they're supplying useful information in that scenario,
  156. // or failing to supply necessary information for the ops that need a count.
  157. struct CountValue {
  158. operator int() {
  159. SkASSERT(val != ByteCodeGenerator::kUnusedStackCount);
  160. SkDEBUGCODE(used = true);
  161. return val;
  162. }
  163. ~CountValue() {
  164. SkASSERT(used || val == ByteCodeGenerator::kUnusedStackCount);
  165. }
  166. int val;
  167. SkDEBUGCODE(bool used = false;)
  168. } count = { count_ };
  169. switch (inst) {
  170. // Unary functions/operators that don't change stack depth at all:
  171. #define VECTOR_UNARY_OP(base) \
  172. case ByteCodeInstruction::base: \
  173. case ByteCodeInstruction::base ## 2: \
  174. case ByteCodeInstruction::base ## 3: \
  175. case ByteCodeInstruction::base ## 4: \
  176. return 0;
  177. VECTOR_UNARY_OP(kConvertFtoI)
  178. VECTOR_UNARY_OP(kConvertStoF)
  179. VECTOR_UNARY_OP(kConvertUtoF)
  180. VECTOR_UNARY_OP(kCos)
  181. VECTOR_UNARY_OP(kSin)
  182. VECTOR_UNARY_OP(kSqrt)
  183. VECTOR_UNARY_OP(kTan)
  184. VECTOR_UNARY_OP(kNegateF)
  185. VECTOR_UNARY_OP(kNegateI)
  186. case ByteCodeInstruction::kInverse2x2:
  187. case ByteCodeInstruction::kInverse3x3:
  188. case ByteCodeInstruction::kInverse4x4: return 0;
  189. case ByteCodeInstruction::kClampIndex: return 0;
  190. case ByteCodeInstruction::kNotB: return 0;
  191. case ByteCodeInstruction::kNegateFN: return 0;
  192. #undef VECTOR_UNARY_OP
  193. // Binary functions/operators that do a 2 -> 1 reduction (possibly N times)
  194. #define VECTOR_BINARY_OP(base) \
  195. case ByteCodeInstruction::base: return -1; \
  196. case ByteCodeInstruction::base ## 2: return -2; \
  197. case ByteCodeInstruction::base ## 3: return -3; \
  198. case ByteCodeInstruction::base ## 4: return -4;
  199. #define VECTOR_MATRIX_BINARY_OP(base) \
  200. VECTOR_BINARY_OP(base) \
  201. case ByteCodeInstruction::base ## N: return -count;
  202. case ByteCodeInstruction::kAndB: return -1;
  203. case ByteCodeInstruction::kOrB: return -1;
  204. case ByteCodeInstruction::kXorB: return -1;
  205. VECTOR_BINARY_OP(kAddI)
  206. VECTOR_MATRIX_BINARY_OP(kAddF)
  207. VECTOR_BINARY_OP(kCompareIEQ)
  208. VECTOR_MATRIX_BINARY_OP(kCompareFEQ)
  209. VECTOR_BINARY_OP(kCompareINEQ)
  210. VECTOR_MATRIX_BINARY_OP(kCompareFNEQ)
  211. VECTOR_BINARY_OP(kCompareSGT)
  212. VECTOR_BINARY_OP(kCompareUGT)
  213. VECTOR_BINARY_OP(kCompareFGT)
  214. VECTOR_BINARY_OP(kCompareSGTEQ)
  215. VECTOR_BINARY_OP(kCompareUGTEQ)
  216. VECTOR_BINARY_OP(kCompareFGTEQ)
  217. VECTOR_BINARY_OP(kCompareSLT)
  218. VECTOR_BINARY_OP(kCompareULT)
  219. VECTOR_BINARY_OP(kCompareFLT)
  220. VECTOR_BINARY_OP(kCompareSLTEQ)
  221. VECTOR_BINARY_OP(kCompareULTEQ)
  222. VECTOR_BINARY_OP(kCompareFLTEQ)
  223. VECTOR_BINARY_OP(kDivideS)
  224. VECTOR_BINARY_OP(kDivideU)
  225. VECTOR_MATRIX_BINARY_OP(kDivideF)
  226. VECTOR_BINARY_OP(kMultiplyI)
  227. VECTOR_MATRIX_BINARY_OP(kMultiplyF)
  228. VECTOR_BINARY_OP(kRemainderF)
  229. VECTOR_BINARY_OP(kRemainderS)
  230. VECTOR_BINARY_OP(kRemainderU)
  231. VECTOR_BINARY_OP(kSubtractI)
  232. VECTOR_MATRIX_BINARY_OP(kSubtractF)
  233. #undef VECTOR_BINARY_OP
  234. #undef VECTOR_MATRIX_BINARY_OP
  235. // Strange math operations with other behavior:
  236. case ByteCodeInstruction::kCross: return -3;
  237. // Binary, but also consumes T:
  238. case ByteCodeInstruction::kMix: return -2;
  239. case ByteCodeInstruction::kMix2: return -3;
  240. case ByteCodeInstruction::kMix3: return -4;
  241. case ByteCodeInstruction::kMix4: return -5;
  242. // Ops that push or load data to grow the stack:
  243. case ByteCodeInstruction::kDup:
  244. case ByteCodeInstruction::kLoad:
  245. case ByteCodeInstruction::kLoadGlobal:
  246. case ByteCodeInstruction::kReadExternal:
  247. case ByteCodeInstruction::kPushImmediate:
  248. return 1;
  249. case ByteCodeInstruction::kDup2:
  250. case ByteCodeInstruction::kLoad2:
  251. case ByteCodeInstruction::kLoadGlobal2:
  252. case ByteCodeInstruction::kReadExternal2:
  253. return 2;
  254. case ByteCodeInstruction::kDup3:
  255. case ByteCodeInstruction::kLoad3:
  256. case ByteCodeInstruction::kLoadGlobal3:
  257. case ByteCodeInstruction::kReadExternal3:
  258. return 3;
  259. case ByteCodeInstruction::kDup4:
  260. case ByteCodeInstruction::kLoad4:
  261. case ByteCodeInstruction::kLoadGlobal4:
  262. case ByteCodeInstruction::kReadExternal4:
  263. return 4;
  264. case ByteCodeInstruction::kDupN:
  265. case ByteCodeInstruction::kLoadSwizzle:
  266. case ByteCodeInstruction::kLoadSwizzleGlobal:
  267. return count;
  268. // Pushes 'count' values, minus one for the 'address' that's consumed first
  269. case ByteCodeInstruction::kLoadExtended:
  270. case ByteCodeInstruction::kLoadExtendedGlobal:
  271. return count - 1;
  272. // Ops that pop or store data to shrink the stack:
  273. case ByteCodeInstruction::kPop:
  274. case ByteCodeInstruction::kStore:
  275. case ByteCodeInstruction::kStoreGlobal:
  276. case ByteCodeInstruction::kWriteExternal:
  277. return -1;
  278. case ByteCodeInstruction::kPop2:
  279. case ByteCodeInstruction::kStore2:
  280. case ByteCodeInstruction::kStoreGlobal2:
  281. case ByteCodeInstruction::kWriteExternal2:
  282. return -2;
  283. case ByteCodeInstruction::kPop3:
  284. case ByteCodeInstruction::kStore3:
  285. case ByteCodeInstruction::kStoreGlobal3:
  286. case ByteCodeInstruction::kWriteExternal3:
  287. return -3;
  288. case ByteCodeInstruction::kPop4:
  289. case ByteCodeInstruction::kStore4:
  290. case ByteCodeInstruction::kStoreGlobal4:
  291. case ByteCodeInstruction::kWriteExternal4:
  292. return -4;
  293. case ByteCodeInstruction::kPopN:
  294. case ByteCodeInstruction::kStoreSwizzle:
  295. case ByteCodeInstruction::kStoreSwizzleGlobal:
  296. return -count;
  297. // Consumes 'count' values, plus one for the 'address'
  298. case ByteCodeInstruction::kStoreExtended:
  299. case ByteCodeInstruction::kStoreExtendedGlobal:
  300. case ByteCodeInstruction::kStoreSwizzleIndirect:
  301. case ByteCodeInstruction::kStoreSwizzleIndirectGlobal:
  302. return -count - 1;
  303. // Strange ops where the caller computes the delta for us:
  304. case ByteCodeInstruction::kCallExternal:
  305. case ByteCodeInstruction::kMatrixToMatrix:
  306. case ByteCodeInstruction::kMatrixMultiply:
  307. case ByteCodeInstruction::kReserve:
  308. case ByteCodeInstruction::kReturn:
  309. case ByteCodeInstruction::kScalarToMatrix:
  310. case ByteCodeInstruction::kSwizzle:
  311. return count;
  312. // Miscellaneous
  313. // kCall is net-zero. Max stack depth is adjusted in writeFunctionCall.
  314. case ByteCodeInstruction::kCall: return 0;
  315. case ByteCodeInstruction::kBranch: return 0;
  316. case ByteCodeInstruction::kBranchIfAllFalse: return 0;
  317. case ByteCodeInstruction::kMaskPush: return -1;
  318. case ByteCodeInstruction::kMaskPop: return 0;
  319. case ByteCodeInstruction::kMaskNegate: return 0;
  320. case ByteCodeInstruction::kMaskBlend: return -count;
  321. case ByteCodeInstruction::kLoopBegin: return 0;
  322. case ByteCodeInstruction::kLoopNext: return 0;
  323. case ByteCodeInstruction::kLoopMask: return -1;
  324. case ByteCodeInstruction::kLoopEnd: return 0;
  325. case ByteCodeInstruction::kLoopBreak: return 0;
  326. case ByteCodeInstruction::kLoopContinue: return 0;
  327. default:
  328. ABORT("unsupported instruction %d\n", (int)inst);
  329. return 0;
  330. }
  331. }
  332. int ByteCodeGenerator::getLocation(const Variable& var) {
  333. // given that we seldom have more than a couple of variables, linear search is probably the most
  334. // efficient way to handle lookups
  335. switch (var.fStorage) {
  336. case Variable::kLocal_Storage: {
  337. for (int i = fLocals.size() - 1; i >= 0; --i) {
  338. if (fLocals[i] == &var) {
  339. SkASSERT(fParameterCount + i <= 255);
  340. return fParameterCount + i;
  341. }
  342. }
  343. int result = fParameterCount + fLocals.size();
  344. fLocals.push_back(&var);
  345. for (int i = 0; i < SlotCount(var.fType) - 1; ++i) {
  346. fLocals.push_back(nullptr);
  347. }
  348. SkASSERT(result <= 255);
  349. return result;
  350. }
  351. case Variable::kParameter_Storage: {
  352. int offset = 0;
  353. for (const auto& p : fFunction->fDeclaration.fParameters) {
  354. if (p == &var) {
  355. SkASSERT(offset <= 255);
  356. return offset;
  357. }
  358. offset += SlotCount(p->fType);
  359. }
  360. SkASSERT(false);
  361. return 0;
  362. }
  363. case Variable::kGlobal_Storage: {
  364. int offset = 0;
  365. for (const auto& e : fProgram) {
  366. if (e.fKind == ProgramElement::kVar_Kind) {
  367. VarDeclarations& decl = (VarDeclarations&) e;
  368. for (const auto& v : decl.fVars) {
  369. const Variable* declVar = ((VarDeclaration&) *v).fVar;
  370. if (declVar->fModifiers.fLayout.fBuiltin >= 0) {
  371. continue;
  372. }
  373. if (declVar == &var) {
  374. SkASSERT(offset <= 255);
  375. return offset;
  376. }
  377. offset += SlotCount(declVar->fType);
  378. }
  379. }
  380. }
  381. SkASSERT(false);
  382. return 0;
  383. }
  384. default:
  385. SkASSERT(false);
  386. return 0;
  387. }
  388. }
  389. int ByteCodeGenerator::getLocation(const Expression& expr, Variable::Storage* storage) {
  390. switch (expr.fKind) {
  391. case Expression::kFieldAccess_Kind: {
  392. const FieldAccess& f = (const FieldAccess&)expr;
  393. int baseAddr = this->getLocation(*f.fBase, storage);
  394. int offset = 0;
  395. for (int i = 0; i < f.fFieldIndex; ++i) {
  396. offset += SlotCount(*f.fBase->fType.fields()[i].fType);
  397. }
  398. if (baseAddr < 0) {
  399. if (offset != 0) {
  400. this->write(ByteCodeInstruction::kPushImmediate);
  401. this->write32(offset);
  402. this->write(ByteCodeInstruction::kAddI);
  403. }
  404. return -1;
  405. } else {
  406. return baseAddr + offset;
  407. }
  408. }
  409. case Expression::kIndex_Kind: {
  410. const IndexExpression& i = (const IndexExpression&)expr;
  411. int stride = SlotCount(i.fType);
  412. int length = i.fBase->fType.columns();
  413. SkASSERT(length <= 255);
  414. int offset = -1;
  415. if (i.fIndex->isConstant()) {
  416. int64_t index = i.fIndex->getConstantInt();
  417. if (index < 0 || index >= length) {
  418. fErrors.error(i.fIndex->fOffset, "Array index out of bounds.");
  419. return 0;
  420. }
  421. offset = index * stride;
  422. } else {
  423. if (i.fIndex->hasSideEffects()) {
  424. // Having a side-effect in an indexer is technically safe for an rvalue,
  425. // but with lvalues we have to evaluate the indexer twice, so make it an error.
  426. fErrors.error(i.fIndex->fOffset,
  427. "Index expressions with side-effects not supported in byte code.");
  428. return 0;
  429. }
  430. this->writeExpression(*i.fIndex);
  431. this->write(ByteCodeInstruction::kClampIndex);
  432. this->write8(length);
  433. if (stride != 1) {
  434. this->write(ByteCodeInstruction::kPushImmediate);
  435. this->write32(stride);
  436. this->write(ByteCodeInstruction::kMultiplyI);
  437. }
  438. }
  439. int baseAddr = this->getLocation(*i.fBase, storage);
  440. // Are both components known statically?
  441. if (baseAddr >= 0 && offset >= 0) {
  442. return baseAddr + offset;
  443. }
  444. // At least one component is dynamic (and on the stack).
  445. // If the other component is zero, we're done
  446. if (baseAddr == 0 || offset == 0) {
  447. return -1;
  448. }
  449. // Push the non-dynamic component (if any) to the stack, then add the two
  450. if (baseAddr >= 0) {
  451. this->write(ByteCodeInstruction::kPushImmediate);
  452. this->write32(baseAddr);
  453. }
  454. if (offset >= 0) {
  455. this->write(ByteCodeInstruction::kPushImmediate);
  456. this->write32(offset);
  457. }
  458. this->write(ByteCodeInstruction::kAddI);
  459. return -1;
  460. }
  461. case Expression::kSwizzle_Kind: {
  462. const Swizzle& s = (const Swizzle&)expr;
  463. SkASSERT(swizzle_is_simple(s));
  464. int baseAddr = this->getLocation(*s.fBase, storage);
  465. int offset = s.fComponents[0];
  466. if (baseAddr < 0) {
  467. if (offset != 0) {
  468. this->write(ByteCodeInstruction::kPushImmediate);
  469. this->write32(offset);
  470. this->write(ByteCodeInstruction::kAddI);
  471. }
  472. return -1;
  473. } else {
  474. return baseAddr + offset;
  475. }
  476. }
  477. case Expression::kVariableReference_Kind: {
  478. const Variable& var = ((const VariableReference&)expr).fVariable;
  479. *storage = var.fStorage;
  480. return this->getLocation(var);
  481. }
  482. default:
  483. SkASSERT(false);
  484. return 0;
  485. }
  486. }
  487. void ByteCodeGenerator::write8(uint8_t b) {
  488. fCode->push_back(b);
  489. }
  490. void ByteCodeGenerator::write16(uint16_t i) {
  491. size_t n = fCode->size();
  492. fCode->resize(n+2);
  493. memcpy(fCode->data() + n, &i, 2);
  494. }
  495. void ByteCodeGenerator::write32(uint32_t i) {
  496. size_t n = fCode->size();
  497. fCode->resize(n+4);
  498. memcpy(fCode->data() + n, &i, 4);
  499. }
  500. void ByteCodeGenerator::write(ByteCodeInstruction i, int count) {
  501. switch (i) {
  502. case ByteCodeInstruction::kLoopBegin: this->enterLoop(); break;
  503. case ByteCodeInstruction::kLoopEnd: this->exitLoop(); break;
  504. case ByteCodeInstruction::kMaskPush: this->enterCondition(); break;
  505. case ByteCodeInstruction::kMaskPop:
  506. case ByteCodeInstruction::kMaskBlend: this->exitCondition(); break;
  507. default: /* Do nothing */ break;
  508. }
  509. this->write16((uint16_t)i);
  510. fStackCount += StackUsage(i, count);
  511. fMaxStackCount = std::max(fMaxStackCount, fStackCount);
  512. }
  513. static ByteCodeInstruction vector_instruction(ByteCodeInstruction base, int count) {
  514. SkASSERT(count >= 1 && count <= 4);
  515. return ((ByteCodeInstruction) ((int) base + count - 1));
  516. }
  517. void ByteCodeGenerator::writeTypedInstruction(const Type& type, ByteCodeInstruction s,
  518. ByteCodeInstruction u, ByteCodeInstruction f,
  519. int count) {
  520. switch (type_category(type)) {
  521. case TypeCategory::kSigned:
  522. this->write(vector_instruction(s, count));
  523. break;
  524. case TypeCategory::kUnsigned:
  525. this->write(vector_instruction(u, count));
  526. break;
  527. case TypeCategory::kFloat: {
  528. if (count > 4) {
  529. this->write((ByteCodeInstruction)((int)f + 4), count);
  530. this->write8(count);
  531. } else {
  532. this->write(vector_instruction(f, count));
  533. }
  534. break;
  535. }
  536. default:
  537. SkASSERT(false);
  538. }
  539. }
  540. bool ByteCodeGenerator::writeBinaryExpression(const BinaryExpression& b, bool discard) {
  541. if (b.fOperator == Token::Kind::EQ) {
  542. std::unique_ptr<LValue> lvalue = this->getLValue(*b.fLeft);
  543. this->writeExpression(*b.fRight);
  544. lvalue->store(discard);
  545. discard = false;
  546. return discard;
  547. }
  548. const Type& lType = b.fLeft->fType;
  549. const Type& rType = b.fRight->fType;
  550. bool lVecOrMtx = (lType.kind() == Type::kVector_Kind || lType.kind() == Type::kMatrix_Kind);
  551. bool rVecOrMtx = (rType.kind() == Type::kVector_Kind || rType.kind() == Type::kMatrix_Kind);
  552. Token::Kind op;
  553. std::unique_ptr<LValue> lvalue;
  554. if (is_assignment(b.fOperator)) {
  555. lvalue = this->getLValue(*b.fLeft);
  556. lvalue->load();
  557. op = remove_assignment(b.fOperator);
  558. } else {
  559. this->writeExpression(*b.fLeft);
  560. op = b.fOperator;
  561. if (!lVecOrMtx && rVecOrMtx) {
  562. for (int i = SlotCount(rType); i > 1; --i) {
  563. this->write(ByteCodeInstruction::kDup);
  564. }
  565. }
  566. }
  567. this->writeExpression(*b.fRight);
  568. if (lVecOrMtx && !rVecOrMtx) {
  569. for (int i = SlotCount(lType); i > 1; --i) {
  570. this->write(ByteCodeInstruction::kDup);
  571. }
  572. }
  573. // Special case for M*V, V*M, M*M (but not V*V!)
  574. if (op == Token::Kind::STAR && lVecOrMtx && rVecOrMtx &&
  575. !(lType.kind() == Type::kVector_Kind && rType.kind() == Type::kVector_Kind)) {
  576. this->write(ByteCodeInstruction::kMatrixMultiply,
  577. SlotCount(b.fType) - (SlotCount(lType) + SlotCount(rType)));
  578. int rCols = rType.columns(),
  579. rRows = rType.rows(),
  580. lCols = lType.columns(),
  581. lRows = lType.rows();
  582. // M*V treats the vector as a column
  583. if (rType.kind() == Type::kVector_Kind) {
  584. std::swap(rCols, rRows);
  585. }
  586. SkASSERT(lCols == rRows);
  587. SkASSERT(SlotCount(b.fType) == lRows * rCols);
  588. this->write8(lCols);
  589. this->write8(lRows);
  590. this->write8(rCols);
  591. } else {
  592. int count = std::max(SlotCount(lType), SlotCount(rType));
  593. switch (op) {
  594. case Token::Kind::EQEQ:
  595. this->writeTypedInstruction(lType, ByteCodeInstruction::kCompareIEQ,
  596. ByteCodeInstruction::kCompareIEQ,
  597. ByteCodeInstruction::kCompareFEQ,
  598. count);
  599. // Collapse to a single bool
  600. for (int i = count; i > 1; --i) {
  601. this->write(ByteCodeInstruction::kAndB);
  602. }
  603. break;
  604. case Token::Kind::GT:
  605. this->writeTypedInstruction(lType, ByteCodeInstruction::kCompareSGT,
  606. ByteCodeInstruction::kCompareUGT,
  607. ByteCodeInstruction::kCompareFGT,
  608. count);
  609. break;
  610. case Token::Kind::GTEQ:
  611. this->writeTypedInstruction(lType, ByteCodeInstruction::kCompareSGTEQ,
  612. ByteCodeInstruction::kCompareUGTEQ,
  613. ByteCodeInstruction::kCompareFGTEQ,
  614. count);
  615. break;
  616. case Token::Kind::LT:
  617. this->writeTypedInstruction(lType, ByteCodeInstruction::kCompareSLT,
  618. ByteCodeInstruction::kCompareULT,
  619. ByteCodeInstruction::kCompareFLT,
  620. count);
  621. break;
  622. case Token::Kind::LTEQ:
  623. this->writeTypedInstruction(lType, ByteCodeInstruction::kCompareSLTEQ,
  624. ByteCodeInstruction::kCompareULTEQ,
  625. ByteCodeInstruction::kCompareFLTEQ,
  626. count);
  627. break;
  628. case Token::Kind::MINUS:
  629. this->writeTypedInstruction(lType, ByteCodeInstruction::kSubtractI,
  630. ByteCodeInstruction::kSubtractI,
  631. ByteCodeInstruction::kSubtractF,
  632. count);
  633. break;
  634. case Token::Kind::NEQ:
  635. this->writeTypedInstruction(lType, ByteCodeInstruction::kCompareINEQ,
  636. ByteCodeInstruction::kCompareINEQ,
  637. ByteCodeInstruction::kCompareFNEQ,
  638. count);
  639. // Collapse to a single bool
  640. for (int i = count; i > 1; --i) {
  641. this->write(ByteCodeInstruction::kOrB);
  642. }
  643. break;
  644. case Token::Kind::PERCENT:
  645. this->writeTypedInstruction(lType, ByteCodeInstruction::kRemainderS,
  646. ByteCodeInstruction::kRemainderU,
  647. ByteCodeInstruction::kRemainderF,
  648. count);
  649. break;
  650. case Token::Kind::PLUS:
  651. this->writeTypedInstruction(lType, ByteCodeInstruction::kAddI,
  652. ByteCodeInstruction::kAddI,
  653. ByteCodeInstruction::kAddF,
  654. count);
  655. break;
  656. case Token::Kind::SLASH:
  657. this->writeTypedInstruction(lType, ByteCodeInstruction::kDivideS,
  658. ByteCodeInstruction::kDivideU,
  659. ByteCodeInstruction::kDivideF,
  660. count);
  661. break;
  662. case Token::Kind::STAR:
  663. this->writeTypedInstruction(lType, ByteCodeInstruction::kMultiplyI,
  664. ByteCodeInstruction::kMultiplyI,
  665. ByteCodeInstruction::kMultiplyF,
  666. count);
  667. break;
  668. case Token::Kind::LOGICALAND:
  669. SkASSERT(type_category(lType) == SkSL::TypeCategory::kBool && count == 1);
  670. this->write(ByteCodeInstruction::kAndB);
  671. break;
  672. case Token::Kind::LOGICALNOT:
  673. SkASSERT(type_category(lType) == SkSL::TypeCategory::kBool && count == 1);
  674. this->write(ByteCodeInstruction::kNotB);
  675. break;
  676. case Token::Kind::LOGICALOR:
  677. SkASSERT(type_category(lType) == SkSL::TypeCategory::kBool && count == 1);
  678. this->write(ByteCodeInstruction::kOrB);
  679. break;
  680. case Token::Kind::LOGICALXOR:
  681. SkASSERT(type_category(lType) == SkSL::TypeCategory::kBool && count == 1);
  682. this->write(ByteCodeInstruction::kXorB);
  683. break;
  684. default:
  685. SkASSERT(false);
  686. }
  687. }
  688. if (lvalue) {
  689. lvalue->store(discard);
  690. discard = false;
  691. }
  692. return discard;
  693. }
  694. void ByteCodeGenerator::writeBoolLiteral(const BoolLiteral& b) {
  695. this->write(ByteCodeInstruction::kPushImmediate);
  696. this->write32(b.fValue ? ~0 : 0);
  697. }
  698. void ByteCodeGenerator::writeConstructor(const Constructor& c) {
  699. for (const auto& arg : c.fArguments) {
  700. this->writeExpression(*arg);
  701. }
  702. if (c.fArguments.size() == 1) {
  703. const Type& inType = c.fArguments[0]->fType;
  704. const Type& outType = c.fType;
  705. TypeCategory inCategory = type_category(inType);
  706. TypeCategory outCategory = type_category(outType);
  707. int inCount = SlotCount(inType);
  708. int outCount = SlotCount(outType);
  709. if (inCategory != outCategory) {
  710. SkASSERT(inCount == outCount);
  711. if (inCategory == TypeCategory::kFloat) {
  712. SkASSERT(outCategory == TypeCategory::kSigned ||
  713. outCategory == TypeCategory::kUnsigned);
  714. this->write(vector_instruction(ByteCodeInstruction::kConvertFtoI, outCount));
  715. } else if (outCategory == TypeCategory::kFloat) {
  716. if (inCategory == TypeCategory::kSigned) {
  717. this->write(vector_instruction(ByteCodeInstruction::kConvertStoF, outCount));
  718. } else {
  719. SkASSERT(inCategory == TypeCategory::kUnsigned);
  720. this->write(vector_instruction(ByteCodeInstruction::kConvertUtoF, outCount));
  721. }
  722. } else {
  723. SkASSERT(false);
  724. }
  725. }
  726. if (inType.kind() == Type::kMatrix_Kind && outType.kind() == Type::kMatrix_Kind) {
  727. this->write(ByteCodeInstruction::kMatrixToMatrix,
  728. SlotCount(outType) - SlotCount(inType));
  729. this->write8(inType.columns());
  730. this->write8(inType.rows());
  731. this->write8(outType.columns());
  732. this->write8(outType.rows());
  733. } else if (inCount != outCount) {
  734. SkASSERT(inCount == 1);
  735. if (outType.kind() == Type::kMatrix_Kind) {
  736. this->write(ByteCodeInstruction::kScalarToMatrix, SlotCount(outType) - 1);
  737. this->write8(outType.columns());
  738. this->write8(outType.rows());
  739. } else {
  740. SkASSERT(outType.kind() == Type::kVector_Kind);
  741. for (; inCount != outCount; ++inCount) {
  742. this->write(ByteCodeInstruction::kDup);
  743. }
  744. }
  745. }
  746. }
  747. }
  748. void ByteCodeGenerator::writeExternalFunctionCall(const ExternalFunctionCall& f) {
  749. int argumentCount = 0;
  750. for (const auto& arg : f.fArguments) {
  751. this->writeExpression(*arg);
  752. argumentCount += SlotCount(arg->fType);
  753. }
  754. this->write(ByteCodeInstruction::kCallExternal, SlotCount(f.fType) - argumentCount);
  755. SkASSERT(argumentCount <= 255);
  756. this->write8(argumentCount);
  757. this->write8(SlotCount(f.fType));
  758. int index = fOutput->fExternalValues.size();
  759. fOutput->fExternalValues.push_back(f.fFunction);
  760. SkASSERT(index <= 255);
  761. this->write8(index);
  762. }
  763. void ByteCodeGenerator::writeExternalValue(const ExternalValueReference& e) {
  764. this->write(vector_instruction(ByteCodeInstruction::kReadExternal,
  765. SlotCount(e.fValue->type())));
  766. int index = fOutput->fExternalValues.size();
  767. fOutput->fExternalValues.push_back(e.fValue);
  768. SkASSERT(index <= 255);
  769. this->write8(index);
  770. }
  771. void ByteCodeGenerator::writeVariableExpression(const Expression& expr) {
  772. Variable::Storage storage = Variable::kLocal_Storage;
  773. int location = this->getLocation(expr, &storage);
  774. bool isGlobal = storage == Variable::kGlobal_Storage;
  775. int count = SlotCount(expr.fType);
  776. if (location < 0 || count > 4) {
  777. if (location >= 0) {
  778. this->write(ByteCodeInstruction::kPushImmediate);
  779. this->write32(location);
  780. }
  781. this->write(isGlobal ? ByteCodeInstruction::kLoadExtendedGlobal
  782. : ByteCodeInstruction::kLoadExtended,
  783. count);
  784. this->write8(count);
  785. } else {
  786. this->write(vector_instruction(isGlobal ? ByteCodeInstruction::kLoadGlobal
  787. : ByteCodeInstruction::kLoad,
  788. count));
  789. this->write8(location);
  790. }
  791. }
  792. static inline uint32_t float_to_bits(float x) {
  793. uint32_t u;
  794. memcpy(&u, &x, sizeof(uint32_t));
  795. return u;
  796. }
  797. void ByteCodeGenerator::writeFloatLiteral(const FloatLiteral& f) {
  798. this->write(ByteCodeInstruction::kPushImmediate);
  799. this->write32(float_to_bits(f.fValue));
  800. }
  801. void ByteCodeGenerator::writeIntrinsicCall(const FunctionCall& c) {
  802. auto found = fIntrinsics.find(c.fFunction.fName);
  803. if (found == fIntrinsics.end()) {
  804. fErrors.error(c.fOffset, "unsupported intrinsic function");
  805. return;
  806. }
  807. int count = SlotCount(c.fArguments[0]->fType);
  808. if (found->second.fIsSpecial) {
  809. SkASSERT(found->second.fValue.fSpecial == SpecialIntrinsic::kDot);
  810. SkASSERT(c.fArguments.size() == 2);
  811. SkASSERT(count == SlotCount(c.fArguments[1]->fType));
  812. this->write((ByteCodeInstruction)((int)ByteCodeInstruction::kMultiplyF + count - 1));
  813. for (int i = count; i > 1; --i) {
  814. this->write(ByteCodeInstruction::kAddF);
  815. }
  816. } else {
  817. switch (found->second.fValue.fInstruction) {
  818. case ByteCodeInstruction::kCos:
  819. case ByteCodeInstruction::kMix:
  820. case ByteCodeInstruction::kSin:
  821. case ByteCodeInstruction::kSqrt:
  822. case ByteCodeInstruction::kTan:
  823. SkASSERT(c.fArguments.size() > 0);
  824. this->write((ByteCodeInstruction) ((int) found->second.fValue.fInstruction +
  825. count - 1));
  826. break;
  827. case ByteCodeInstruction::kCross:
  828. this->write(found->second.fValue.fInstruction);
  829. break;
  830. case ByteCodeInstruction::kInverse2x2: {
  831. SkASSERT(c.fArguments.size() > 0);
  832. auto op = ByteCodeInstruction::kInverse2x2;
  833. switch (count) {
  834. case 4: break; // float2x2
  835. case 9: op = ByteCodeInstruction::kInverse3x3; break;
  836. case 16: op = ByteCodeInstruction::kInverse4x4; break;
  837. default: SkASSERT(false);
  838. }
  839. this->write(op);
  840. } break;
  841. default:
  842. SkASSERT(false);
  843. }
  844. }
  845. }
  846. void ByteCodeGenerator::writeFunctionCall(const FunctionCall& f) {
  847. // Builtins have simple signatures...
  848. if (f.fFunction.fBuiltin) {
  849. for (const auto& arg : f.fArguments) {
  850. this->writeExpression(*arg);
  851. }
  852. this->writeIntrinsicCall(f);
  853. return;
  854. }
  855. // Find the index of the function we're calling. We explicitly do not allow calls to functions
  856. // before they're defined. This is an easy-to-understand rule that prevents recursion.
  857. size_t idx;
  858. for (idx = 0; idx < fFunctions.size(); ++idx) {
  859. if (f.fFunction.matches(fFunctions[idx]->fDeclaration)) {
  860. break;
  861. }
  862. }
  863. if (idx > 255) {
  864. fErrors.error(f.fOffset, "Function count limit exceeded");
  865. return;
  866. } else if (idx >= fFunctions.size()) {
  867. fErrors.error(f.fOffset, "Call to undefined function");
  868. return;
  869. }
  870. // We may need to deal with out parameters, so the sequence is tricky
  871. if (int returnCount = SlotCount(f.fType)) {
  872. this->write(ByteCodeInstruction::kReserve, returnCount);
  873. this->write8(returnCount);
  874. }
  875. int argCount = f.fArguments.size();
  876. std::vector<std::unique_ptr<LValue>> lvalues;
  877. for (int i = 0; i < argCount; ++i) {
  878. const auto& param = f.fFunction.fParameters[i];
  879. const auto& arg = f.fArguments[i];
  880. if (param->fModifiers.fFlags & Modifiers::kOut_Flag) {
  881. lvalues.emplace_back(this->getLValue(*arg));
  882. lvalues.back()->load();
  883. } else {
  884. this->writeExpression(*arg);
  885. }
  886. }
  887. // The space used by the call is based on the callee, but it also unwinds all of that before
  888. // we continue execution. We adjust our max stack depths below.
  889. this->write(ByteCodeInstruction::kCall);
  890. this->write8(idx);
  891. const ByteCodeFunction* callee = fOutput->fFunctions[idx].get();
  892. fMaxLoopCount = std::max(fMaxLoopCount, fLoopCount + callee->fLoopCount);
  893. fMaxConditionCount = std::max(fMaxConditionCount, fConditionCount + callee->fConditionCount);
  894. fMaxStackCount = std::max(fMaxStackCount, fStackCount + callee->fLocalCount
  895. + callee->fStackCount);
  896. // After the called function returns, the stack will still contain our arguments. We have to
  897. // pop them (storing any out parameters back to their lvalues as we go). We glob together slot
  898. // counts for all parameters that aren't out-params, so we can pop them in one big chunk.
  899. int popCount = 0;
  900. auto pop = [&]() {
  901. if (popCount > 4) {
  902. this->write(ByteCodeInstruction::kPopN, popCount);
  903. this->write8(popCount);
  904. } else if (popCount > 0) {
  905. this->write(vector_instruction(ByteCodeInstruction::kPop, popCount));
  906. }
  907. popCount = 0;
  908. };
  909. for (int i = argCount - 1; i >= 0; --i) {
  910. const auto& param = f.fFunction.fParameters[i];
  911. const auto& arg = f.fArguments[i];
  912. if (param->fModifiers.fFlags & Modifiers::kOut_Flag) {
  913. pop();
  914. lvalues.back()->store(true);
  915. lvalues.pop_back();
  916. } else {
  917. popCount += SlotCount(arg->fType);
  918. }
  919. }
  920. pop();
  921. }
  922. void ByteCodeGenerator::writeIntLiteral(const IntLiteral& i) {
  923. this->write(ByteCodeInstruction::kPushImmediate);
  924. this->write32(i.fValue);
  925. }
  926. void ByteCodeGenerator::writeNullLiteral(const NullLiteral& n) {
  927. // not yet implemented
  928. abort();
  929. }
  930. bool ByteCodeGenerator::writePrefixExpression(const PrefixExpression& p, bool discard) {
  931. switch (p.fOperator) {
  932. case Token::Kind::PLUSPLUS: // fall through
  933. case Token::Kind::MINUSMINUS: {
  934. SkASSERT(SlotCount(p.fOperand->fType) == 1);
  935. std::unique_ptr<LValue> lvalue = this->getLValue(*p.fOperand);
  936. lvalue->load();
  937. this->write(ByteCodeInstruction::kPushImmediate);
  938. this->write32(type_category(p.fType) == TypeCategory::kFloat ? float_to_bits(1.0f) : 1);
  939. if (p.fOperator == Token::Kind::PLUSPLUS) {
  940. this->writeTypedInstruction(p.fType,
  941. ByteCodeInstruction::kAddI,
  942. ByteCodeInstruction::kAddI,
  943. ByteCodeInstruction::kAddF,
  944. 1);
  945. } else {
  946. this->writeTypedInstruction(p.fType,
  947. ByteCodeInstruction::kSubtractI,
  948. ByteCodeInstruction::kSubtractI,
  949. ByteCodeInstruction::kSubtractF,
  950. 1);
  951. }
  952. lvalue->store(discard);
  953. discard = false;
  954. break;
  955. }
  956. case Token::Kind::MINUS: {
  957. this->writeExpression(*p.fOperand);
  958. this->writeTypedInstruction(p.fType,
  959. ByteCodeInstruction::kNegateI,
  960. ByteCodeInstruction::kNegateI,
  961. ByteCodeInstruction::kNegateF,
  962. SlotCount(p.fOperand->fType));
  963. break;
  964. }
  965. default:
  966. SkASSERT(false);
  967. }
  968. return discard;
  969. }
  970. bool ByteCodeGenerator::writePostfixExpression(const PostfixExpression& p, bool discard) {
  971. switch (p.fOperator) {
  972. case Token::Kind::PLUSPLUS: // fall through
  973. case Token::Kind::MINUSMINUS: {
  974. SkASSERT(SlotCount(p.fOperand->fType) == 1);
  975. std::unique_ptr<LValue> lvalue = this->getLValue(*p.fOperand);
  976. lvalue->load();
  977. // If we're not supposed to discard the result, then make a copy *before* the +/-
  978. if (!discard) {
  979. this->write(ByteCodeInstruction::kDup);
  980. }
  981. this->write(ByteCodeInstruction::kPushImmediate);
  982. this->write32(type_category(p.fType) == TypeCategory::kFloat ? float_to_bits(1.0f) : 1);
  983. if (p.fOperator == Token::Kind::PLUSPLUS) {
  984. this->writeTypedInstruction(p.fType,
  985. ByteCodeInstruction::kAddI,
  986. ByteCodeInstruction::kAddI,
  987. ByteCodeInstruction::kAddF,
  988. 1);
  989. } else {
  990. this->writeTypedInstruction(p.fType,
  991. ByteCodeInstruction::kSubtractI,
  992. ByteCodeInstruction::kSubtractI,
  993. ByteCodeInstruction::kSubtractF,
  994. 1);
  995. }
  996. // Always consume the result as part of the store
  997. lvalue->store(true);
  998. discard = false;
  999. break;
  1000. }
  1001. default:
  1002. SkASSERT(false);
  1003. }
  1004. return discard;
  1005. }
  1006. void ByteCodeGenerator::writeSwizzle(const Swizzle& s) {
  1007. if (swizzle_is_simple(s)) {
  1008. this->writeVariableExpression(s);
  1009. return;
  1010. }
  1011. switch (s.fBase->fKind) {
  1012. case Expression::kVariableReference_Kind: {
  1013. const Variable& var = ((VariableReference&) *s.fBase).fVariable;
  1014. this->write(var.fStorage == Variable::kGlobal_Storage
  1015. ? ByteCodeInstruction::kLoadSwizzleGlobal
  1016. : ByteCodeInstruction::kLoadSwizzle,
  1017. s.fComponents.size());
  1018. this->write8(this->getLocation(var));
  1019. this->write8(s.fComponents.size());
  1020. for (int c : s.fComponents) {
  1021. this->write8(c);
  1022. }
  1023. break;
  1024. }
  1025. default:
  1026. this->writeExpression(*s.fBase);
  1027. this->write(ByteCodeInstruction::kSwizzle,
  1028. s.fComponents.size() - s.fBase->fType.columns());
  1029. this->write8(s.fBase->fType.columns());
  1030. this->write8(s.fComponents.size());
  1031. for (int c : s.fComponents) {
  1032. this->write8(c);
  1033. }
  1034. }
  1035. }
  1036. void ByteCodeGenerator::writeTernaryExpression(const TernaryExpression& t) {
  1037. int count = SlotCount(t.fType);
  1038. SkASSERT(count == SlotCount(t.fIfTrue->fType));
  1039. SkASSERT(count == SlotCount(t.fIfFalse->fType));
  1040. this->writeExpression(*t.fTest);
  1041. this->write(ByteCodeInstruction::kMaskPush);
  1042. this->writeExpression(*t.fIfTrue);
  1043. this->write(ByteCodeInstruction::kMaskNegate);
  1044. this->writeExpression(*t.fIfFalse);
  1045. this->write(ByteCodeInstruction::kMaskBlend, count);
  1046. this->write8(count);
  1047. }
  1048. void ByteCodeGenerator::writeExpression(const Expression& e, bool discard) {
  1049. switch (e.fKind) {
  1050. case Expression::kBinary_Kind:
  1051. discard = this->writeBinaryExpression((BinaryExpression&) e, discard);
  1052. break;
  1053. case Expression::kBoolLiteral_Kind:
  1054. this->writeBoolLiteral((BoolLiteral&) e);
  1055. break;
  1056. case Expression::kConstructor_Kind:
  1057. this->writeConstructor((Constructor&) e);
  1058. break;
  1059. case Expression::kExternalFunctionCall_Kind:
  1060. this->writeExternalFunctionCall((ExternalFunctionCall&) e);
  1061. break;
  1062. case Expression::kExternalValue_Kind:
  1063. this->writeExternalValue((ExternalValueReference&) e);
  1064. break;
  1065. case Expression::kFieldAccess_Kind:
  1066. case Expression::kIndex_Kind:
  1067. case Expression::kVariableReference_Kind:
  1068. this->writeVariableExpression(e);
  1069. break;
  1070. case Expression::kFloatLiteral_Kind:
  1071. this->writeFloatLiteral((FloatLiteral&) e);
  1072. break;
  1073. case Expression::kFunctionCall_Kind:
  1074. this->writeFunctionCall((FunctionCall&) e);
  1075. break;
  1076. case Expression::kIntLiteral_Kind:
  1077. this->writeIntLiteral((IntLiteral&) e);
  1078. break;
  1079. case Expression::kNullLiteral_Kind:
  1080. this->writeNullLiteral((NullLiteral&) e);
  1081. break;
  1082. case Expression::kPrefix_Kind:
  1083. discard = this->writePrefixExpression((PrefixExpression&) e, discard);
  1084. break;
  1085. case Expression::kPostfix_Kind:
  1086. discard = this->writePostfixExpression((PostfixExpression&) e, discard);
  1087. break;
  1088. case Expression::kSwizzle_Kind:
  1089. this->writeSwizzle((Swizzle&) e);
  1090. break;
  1091. case Expression::kTernary_Kind:
  1092. this->writeTernaryExpression((TernaryExpression&) e);
  1093. break;
  1094. default:
  1095. printf("unsupported expression %s\n", e.description().c_str());
  1096. SkASSERT(false);
  1097. }
  1098. if (discard) {
  1099. int count = SlotCount(e.fType);
  1100. if (count > 4) {
  1101. this->write(ByteCodeInstruction::kPopN, count);
  1102. this->write8(count);
  1103. } else if (count != 0) {
  1104. this->write(vector_instruction(ByteCodeInstruction::kPop, count));
  1105. }
  1106. discard = false;
  1107. }
  1108. }
  1109. class ByteCodeExternalValueLValue : public ByteCodeGenerator::LValue {
  1110. public:
  1111. ByteCodeExternalValueLValue(ByteCodeGenerator* generator, ExternalValue& value, int index)
  1112. : INHERITED(*generator)
  1113. , fCount(ByteCodeGenerator::SlotCount(value.type()))
  1114. , fIndex(index) {}
  1115. void load() override {
  1116. fGenerator.write(vector_instruction(ByteCodeInstruction::kReadExternal, fCount));
  1117. fGenerator.write8(fIndex);
  1118. }
  1119. void store(bool discard) override {
  1120. if (!discard) {
  1121. fGenerator.write(vector_instruction(ByteCodeInstruction::kDup, fCount));
  1122. }
  1123. fGenerator.write(vector_instruction(ByteCodeInstruction::kWriteExternal, fCount));
  1124. fGenerator.write8(fIndex);
  1125. }
  1126. private:
  1127. typedef LValue INHERITED;
  1128. int fCount;
  1129. int fIndex;
  1130. };
  1131. class ByteCodeSwizzleLValue : public ByteCodeGenerator::LValue {
  1132. public:
  1133. ByteCodeSwizzleLValue(ByteCodeGenerator* generator, const Swizzle& swizzle)
  1134. : INHERITED(*generator)
  1135. , fSwizzle(swizzle) {}
  1136. void load() override {
  1137. fGenerator.writeSwizzle(fSwizzle);
  1138. }
  1139. void store(bool discard) override {
  1140. int count = fSwizzle.fComponents.size();
  1141. if (!discard) {
  1142. fGenerator.write(vector_instruction(ByteCodeInstruction::kDup, count));
  1143. }
  1144. Variable::Storage storage = Variable::kLocal_Storage;
  1145. int location = fGenerator.getLocation(*fSwizzle.fBase, &storage);
  1146. bool isGlobal = storage == Variable::kGlobal_Storage;
  1147. if (location < 0) {
  1148. fGenerator.write(isGlobal ? ByteCodeInstruction::kStoreSwizzleIndirectGlobal
  1149. : ByteCodeInstruction::kStoreSwizzleIndirect,
  1150. count);
  1151. } else {
  1152. fGenerator.write(isGlobal ? ByteCodeInstruction::kStoreSwizzleGlobal
  1153. : ByteCodeInstruction::kStoreSwizzle,
  1154. count);
  1155. fGenerator.write8(location);
  1156. }
  1157. fGenerator.write8(count);
  1158. for (int c : fSwizzle.fComponents) {
  1159. fGenerator.write8(c);
  1160. }
  1161. }
  1162. private:
  1163. const Swizzle& fSwizzle;
  1164. typedef LValue INHERITED;
  1165. };
  1166. class ByteCodeExpressionLValue : public ByteCodeGenerator::LValue {
  1167. public:
  1168. ByteCodeExpressionLValue(ByteCodeGenerator* generator, const Expression& expr)
  1169. : INHERITED(*generator)
  1170. , fExpression(expr) {}
  1171. void load() override {
  1172. fGenerator.writeVariableExpression(fExpression);
  1173. }
  1174. void store(bool discard) override {
  1175. int count = ByteCodeGenerator::SlotCount(fExpression.fType);
  1176. if (!discard) {
  1177. if (count > 4) {
  1178. fGenerator.write(ByteCodeInstruction::kDupN, count);
  1179. fGenerator.write8(count);
  1180. } else {
  1181. fGenerator.write(vector_instruction(ByteCodeInstruction::kDup, count));
  1182. }
  1183. }
  1184. Variable::Storage storage = Variable::kLocal_Storage;
  1185. int location = fGenerator.getLocation(fExpression, &storage);
  1186. bool isGlobal = storage == Variable::kGlobal_Storage;
  1187. if (location < 0 || count > 4) {
  1188. if (location >= 0) {
  1189. fGenerator.write(ByteCodeInstruction::kPushImmediate);
  1190. fGenerator.write32(location);
  1191. }
  1192. fGenerator.write(isGlobal ? ByteCodeInstruction::kStoreExtendedGlobal
  1193. : ByteCodeInstruction::kStoreExtended,
  1194. count);
  1195. fGenerator.write8(count);
  1196. } else {
  1197. fGenerator.write(vector_instruction(isGlobal ? ByteCodeInstruction::kStoreGlobal
  1198. : ByteCodeInstruction::kStore,
  1199. count));
  1200. fGenerator.write8(location);
  1201. }
  1202. }
  1203. private:
  1204. typedef LValue INHERITED;
  1205. const Expression& fExpression;
  1206. };
  1207. std::unique_ptr<ByteCodeGenerator::LValue> ByteCodeGenerator::getLValue(const Expression& e) {
  1208. switch (e.fKind) {
  1209. case Expression::kExternalValue_Kind: {
  1210. ExternalValue* value = ((ExternalValueReference&) e).fValue;
  1211. int index = fOutput->fExternalValues.size();
  1212. fOutput->fExternalValues.push_back(value);
  1213. SkASSERT(index <= 255);
  1214. return std::unique_ptr<LValue>(new ByteCodeExternalValueLValue(this, *value, index));
  1215. }
  1216. case Expression::kFieldAccess_Kind:
  1217. case Expression::kIndex_Kind:
  1218. case Expression::kVariableReference_Kind:
  1219. return std::unique_ptr<LValue>(new ByteCodeExpressionLValue(this, e));
  1220. case Expression::kSwizzle_Kind: {
  1221. const Swizzle& s = (const Swizzle&) e;
  1222. return swizzle_is_simple(s)
  1223. ? std::unique_ptr<LValue>(new ByteCodeExpressionLValue(this, e))
  1224. : std::unique_ptr<LValue>(new ByteCodeSwizzleLValue(this, s));
  1225. }
  1226. case Expression::kTernary_Kind:
  1227. default:
  1228. printf("unsupported lvalue %s\n", e.description().c_str());
  1229. return nullptr;
  1230. }
  1231. }
  1232. void ByteCodeGenerator::writeBlock(const Block& b) {
  1233. for (const auto& s : b.fStatements) {
  1234. this->writeStatement(*s);
  1235. }
  1236. }
  1237. void ByteCodeGenerator::setBreakTargets() {
  1238. std::vector<DeferredLocation>& breaks = fBreakTargets.top();
  1239. for (DeferredLocation& b : breaks) {
  1240. b.set();
  1241. }
  1242. fBreakTargets.pop();
  1243. }
  1244. void ByteCodeGenerator::setContinueTargets() {
  1245. std::vector<DeferredLocation>& continues = fContinueTargets.top();
  1246. for (DeferredLocation& c : continues) {
  1247. c.set();
  1248. }
  1249. fContinueTargets.pop();
  1250. }
  1251. void ByteCodeGenerator::writeBreakStatement(const BreakStatement& b) {
  1252. // TODO: Include BranchIfAllFalse to top-most LoopNext
  1253. this->write(ByteCodeInstruction::kLoopBreak);
  1254. }
  1255. void ByteCodeGenerator::writeContinueStatement(const ContinueStatement& c) {
  1256. // TODO: Include BranchIfAllFalse to top-most LoopNext
  1257. this->write(ByteCodeInstruction::kLoopContinue);
  1258. }
  1259. void ByteCodeGenerator::writeDoStatement(const DoStatement& d) {
  1260. this->write(ByteCodeInstruction::kLoopBegin);
  1261. size_t start = fCode->size();
  1262. this->writeStatement(*d.fStatement);
  1263. this->write(ByteCodeInstruction::kLoopNext);
  1264. this->writeExpression(*d.fTest);
  1265. this->write(ByteCodeInstruction::kLoopMask);
  1266. // TODO: Could shorten this with kBranchIfAnyTrue
  1267. this->write(ByteCodeInstruction::kBranchIfAllFalse);
  1268. DeferredLocation endLocation(this);
  1269. this->write(ByteCodeInstruction::kBranch);
  1270. this->write16(start);
  1271. endLocation.set();
  1272. this->write(ByteCodeInstruction::kLoopEnd);
  1273. }
  1274. void ByteCodeGenerator::writeForStatement(const ForStatement& f) {
  1275. fContinueTargets.emplace();
  1276. fBreakTargets.emplace();
  1277. if (f.fInitializer) {
  1278. this->writeStatement(*f.fInitializer);
  1279. }
  1280. this->write(ByteCodeInstruction::kLoopBegin);
  1281. size_t start = fCode->size();
  1282. if (f.fTest) {
  1283. this->writeExpression(*f.fTest);
  1284. this->write(ByteCodeInstruction::kLoopMask);
  1285. }
  1286. this->write(ByteCodeInstruction::kBranchIfAllFalse);
  1287. DeferredLocation endLocation(this);
  1288. this->writeStatement(*f.fStatement);
  1289. this->write(ByteCodeInstruction::kLoopNext);
  1290. if (f.fNext) {
  1291. this->writeExpression(*f.fNext, true);
  1292. }
  1293. this->write(ByteCodeInstruction::kBranch);
  1294. this->write16(start);
  1295. endLocation.set();
  1296. this->write(ByteCodeInstruction::kLoopEnd);
  1297. }
  1298. void ByteCodeGenerator::writeIfStatement(const IfStatement& i) {
  1299. this->writeExpression(*i.fTest);
  1300. this->write(ByteCodeInstruction::kMaskPush);
  1301. this->write(ByteCodeInstruction::kBranchIfAllFalse);
  1302. DeferredLocation falseLocation(this);
  1303. this->writeStatement(*i.fIfTrue);
  1304. falseLocation.set();
  1305. if (i.fIfFalse) {
  1306. this->write(ByteCodeInstruction::kMaskNegate);
  1307. this->write(ByteCodeInstruction::kBranchIfAllFalse);
  1308. DeferredLocation endLocation(this);
  1309. this->writeStatement(*i.fIfFalse);
  1310. endLocation.set();
  1311. }
  1312. this->write(ByteCodeInstruction::kMaskPop);
  1313. }
  1314. void ByteCodeGenerator::writeReturnStatement(const ReturnStatement& r) {
  1315. if (fLoopCount || fConditionCount) {
  1316. fErrors.error(r.fOffset, "return not allowed inside conditional or loop");
  1317. return;
  1318. }
  1319. int count = SlotCount(r.fExpression->fType);
  1320. this->writeExpression(*r.fExpression);
  1321. // Technically, the kReturn also pops fOutput->fLocalCount values from the stack, too, but we
  1322. // haven't counted pushing those (they're outside the scope of our stack tracking). Instead,
  1323. // we account for those in writeFunction().
  1324. // This is all fine because we don't allow conditional returns, so we only return once anyway.
  1325. this->write(ByteCodeInstruction::kReturn, -count);
  1326. this->write8(count);
  1327. }
  1328. void ByteCodeGenerator::writeSwitchStatement(const SwitchStatement& r) {
  1329. // not yet implemented
  1330. abort();
  1331. }
  1332. void ByteCodeGenerator::writeVarDeclarations(const VarDeclarations& v) {
  1333. for (const auto& declStatement : v.fVars) {
  1334. const VarDeclaration& decl = (VarDeclaration&) *declStatement;
  1335. // we need to grab the location even if we don't use it, to ensure it
  1336. // has been allocated
  1337. int location = getLocation(*decl.fVar);
  1338. if (decl.fValue) {
  1339. this->writeExpression(*decl.fValue);
  1340. int count = SlotCount(decl.fValue->fType);
  1341. if (count > 4) {
  1342. this->write(ByteCodeInstruction::kPushImmediate);
  1343. this->write32(location);
  1344. this->write(ByteCodeInstruction::kStoreExtended, count);
  1345. this->write8(count);
  1346. } else {
  1347. this->write(vector_instruction(ByteCodeInstruction::kStore, count));
  1348. this->write8(location);
  1349. }
  1350. }
  1351. }
  1352. }
  1353. void ByteCodeGenerator::writeWhileStatement(const WhileStatement& w) {
  1354. this->write(ByteCodeInstruction::kLoopBegin);
  1355. size_t cond = fCode->size();
  1356. this->writeExpression(*w.fTest);
  1357. this->write(ByteCodeInstruction::kLoopMask);
  1358. this->write(ByteCodeInstruction::kBranchIfAllFalse);
  1359. DeferredLocation endLocation(this);
  1360. this->writeStatement(*w.fStatement);
  1361. this->write(ByteCodeInstruction::kLoopNext);
  1362. this->write(ByteCodeInstruction::kBranch);
  1363. this->write16(cond);
  1364. endLocation.set();
  1365. this->write(ByteCodeInstruction::kLoopEnd);
  1366. }
  1367. void ByteCodeGenerator::writeStatement(const Statement& s) {
  1368. switch (s.fKind) {
  1369. case Statement::kBlock_Kind:
  1370. this->writeBlock((Block&) s);
  1371. break;
  1372. case Statement::kBreak_Kind:
  1373. this->writeBreakStatement((BreakStatement&) s);
  1374. break;
  1375. case Statement::kContinue_Kind:
  1376. this->writeContinueStatement((ContinueStatement&) s);
  1377. break;
  1378. case Statement::kDiscard_Kind:
  1379. // not yet implemented
  1380. abort();
  1381. case Statement::kDo_Kind:
  1382. this->writeDoStatement((DoStatement&) s);
  1383. break;
  1384. case Statement::kExpression_Kind:
  1385. this->writeExpression(*((ExpressionStatement&) s).fExpression, true);
  1386. break;
  1387. case Statement::kFor_Kind:
  1388. this->writeForStatement((ForStatement&) s);
  1389. break;
  1390. case Statement::kIf_Kind:
  1391. this->writeIfStatement((IfStatement&) s);
  1392. break;
  1393. case Statement::kNop_Kind:
  1394. break;
  1395. case Statement::kReturn_Kind:
  1396. this->writeReturnStatement((ReturnStatement&) s);
  1397. break;
  1398. case Statement::kSwitch_Kind:
  1399. this->writeSwitchStatement((SwitchStatement&) s);
  1400. break;
  1401. case Statement::kVarDeclarations_Kind:
  1402. this->writeVarDeclarations(*((VarDeclarationsStatement&) s).fDeclaration);
  1403. break;
  1404. case Statement::kWhile_Kind:
  1405. this->writeWhileStatement((WhileStatement&) s);
  1406. break;
  1407. default:
  1408. SkASSERT(false);
  1409. }
  1410. }
  1411. ByteCodeFunction::ByteCodeFunction(const FunctionDeclaration* declaration)
  1412. : fName(declaration->fName) {
  1413. fParameterCount = 0;
  1414. for (const auto& p : declaration->fParameters) {
  1415. int slots = ByteCodeGenerator::SlotCount(p->fType);
  1416. fParameters.push_back({ slots, (bool)(p->fModifiers.fFlags & Modifiers::kOut_Flag) });
  1417. fParameterCount += slots;
  1418. }
  1419. }
  1420. }