WasmByteCodeGenerator.cpp 78 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314
  1. //-------------------------------------------------------------------------------------------------------
  2. // Copyright (C) Microsoft Corporation and contributors. All rights reserved.
  3. // Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
  4. //-------------------------------------------------------------------------------------------------------
  5. #include "WasmReaderPch.h"
  6. #ifdef ENABLE_WASM
  7. #include "Language/WebAssemblySource.h"
  8. #include "ByteCode/WasmByteCodeWriter.h"
  9. #include "EmptyWasmByteCodeWriter.h"
  10. #include "ByteCode/ByteCodeDumper.h"
  11. #include "AsmJsByteCodeDumper.h"
  12. #include "Language/InterpreterStackFrame.h"
  13. #if DBG_DUMP
  14. #define DebugPrintOp(op) if (DO_WASM_TRACE_BYTECODE) { PrintOpBegin(op); }
  15. #define DebugPrintOpEnd() if (DO_WASM_TRACE_BYTECODE) { PrintOpEnd(); }
  16. #else
  17. #define DebugPrintOp(op)
  18. #define DebugPrintOpEnd()
  19. #endif
  20. namespace Wasm
  21. {
  22. #define WASM_SIGNATURE(id, nTypes, ...) const WasmTypes::WasmType WasmOpCodeSignatures::id[] = {__VA_ARGS__};
  23. #include "WasmBinaryOpCodes.h"
  24. template<typename WriteFn>
  25. void WasmBytecodeGenerator::WriteTypeStack(WriteFn writefn) const
  26. {
  27. writefn(_u("["));
  28. int i = 0;
  29. while (m_evalStack.Peek(i).type != WasmTypes::Limit)
  30. {
  31. ++i;
  32. }
  33. --i;
  34. bool isFirst = true;
  35. while (i >= 0)
  36. {
  37. EmitInfo info = m_evalStack.Peek(i--);
  38. if (!isFirst)
  39. {
  40. writefn(_u(", "));
  41. }
  42. isFirst = false;
  43. writefn(GetTypeName(info.type));
  44. }
  45. writefn(_u("]"));
  46. }
  47. uint32 WasmBytecodeGenerator::WriteTypeStackToString(_Out_writes_(maxlen) char16* out, uint32 maxlen) const
  48. {
  49. AssertOrFailFast(out != nullptr);
  50. uint32 numwritten = 0;
  51. WriteTypeStack([&] (const char16* msg)
  52. {
  53. numwritten += _snwprintf_s(out + numwritten, maxlen - numwritten, _TRUNCATE, msg);
  54. });
  55. if (numwritten >= maxlen - 5)
  56. {
  57. // null out the last 5 characters so we can properly end it
  58. for (int i = 1; i <= 5; i++)
  59. {
  60. *(out + maxlen - i) = 0;
  61. }
  62. numwritten -= 5;
  63. numwritten += _snwprintf_s(out + numwritten, maxlen - numwritten, _TRUNCATE, _u("...]"));
  64. }
  65. return numwritten;
  66. }
  67. #if DBG_DUMP
  68. void WasmBytecodeGenerator::PrintTypeStack() const
  69. {
  70. WriteTypeStack([](const char16* msg) { Output::Print(msg); });
  71. }
  72. void WasmBytecodeGenerator::PrintOpBegin(WasmOp op)
  73. {
  74. if (lastOpId == opId) Output::Print(_u("\r\n"));
  75. lastOpId = ++opId;
  76. const int depth = m_blockInfos.Count() - 1;
  77. if (depth > 0)
  78. {
  79. Output::SkipToColumn(depth);
  80. }
  81. const auto PrintSignature = [this](uint32 sigId)
  82. {
  83. if (sigId < m_module->GetSignatureCount())
  84. {
  85. Output::Print(_u(" "));
  86. WasmSignature* sig = m_module->GetSignature(sigId);
  87. sig->Dump(64);
  88. }
  89. else
  90. {
  91. Output::Print(_u(" invalid signature id %u"), sigId);
  92. }
  93. };
  94. switch (op)
  95. {
  96. #define WASM_OPCODE(opname, ...) \
  97. case wb##opname: \
  98. Output::Print(_u(#opname)); \
  99. break;
  100. #include "WasmBinaryOpCodes.h"
  101. }
  102. switch (op)
  103. {
  104. case wbIf:
  105. case wbLoop:
  106. case wbBlock:
  107. if (GetReader()->m_currentNode.block.IsSingleResult())
  108. {
  109. Output::Print(_u(" () -> %s"), GetTypeName(GetReader()->m_currentNode.block.GetSingleResult()));
  110. }
  111. else
  112. {
  113. PrintSignature(GetReader()->m_currentNode.block.GetSignatureId()); break;
  114. }
  115. break;
  116. case wbBr:
  117. case wbBrIf: Output::Print(_u(" depth: %u"), GetReader()->m_currentNode.br.depth); break;
  118. case wbBrTable: Output::Print(_u(" %u cases, default: %u"), GetReader()->m_currentNode.brTable.numTargets, GetReader()->m_currentNode.brTable.defaultTarget); break;
  119. case wbCallIndirect: PrintSignature(GetReader()->m_currentNode.call.num); break;
  120. case wbCall:
  121. {
  122. uint32 id = GetReader()->m_currentNode.call.num;
  123. if (id < m_module->GetWasmFunctionCount())
  124. {
  125. FunctionIndexTypes::Type funcType = GetReader()->m_currentNode.call.funcType;
  126. switch (funcType)
  127. {
  128. case Wasm::FunctionIndexTypes::Invalid: Output::Print(_u(" (invalid) ")); break;
  129. case Wasm::FunctionIndexTypes::ImportThunk: Output::Print(_u(" (thunk) ")); break;
  130. case Wasm::FunctionIndexTypes::Function: Output::Print(_u(" (func) ")); break;
  131. case Wasm::FunctionIndexTypes::Import: Output::Print(_u(" (import) ")); break;
  132. default: Output::Print(_u(" (unknown)")); break;
  133. }
  134. auto func = this->m_module->GetWasmFunctionInfo(id);
  135. func->GetBody()->DumpFullFunctionName();
  136. }
  137. else
  138. {
  139. Output::Print(_u(" invalid id %u"), id);
  140. }
  141. break;
  142. }
  143. case wbSetLocal:
  144. case wbGetLocal:
  145. case wbTeeLocal:
  146. case wbGetGlobal:
  147. case wbSetGlobal: Output::Print(_u(" (%d)"), GetReader()->m_currentNode.var.num); break;
  148. case wbI32Const: Output::Print(_u(" (%d, 0x%x)"), GetReader()->m_currentNode.cnst.i32, GetReader()->m_currentNode.cnst.i32); break;
  149. case wbI64Const: Output::Print(_u(" (%lld, 0x%llx)"), GetReader()->m_currentNode.cnst.i64, GetReader()->m_currentNode.cnst.i64); break;
  150. case wbF32Const: Output::Print(_u(" (%.4f)"), GetReader()->m_currentNode.cnst.f32); break;
  151. case wbF64Const: Output::Print(_u(" (%.4f)"), GetReader()->m_currentNode.cnst.f64); break;
  152. #define WASM_MEM_OPCODE(opname, ...) case wb##opname: // FallThrough
  153. #include "WasmBinaryOpCodes.h"
  154. {
  155. const uint8 alignment = GetReader()->m_currentNode.mem.alignment;
  156. const uint32 offset = GetReader()->m_currentNode.mem.offset;
  157. switch (((!!alignment) << 1) | (!!offset))
  158. {
  159. case 0: // no alignment, no offset
  160. Output::Print(_u(" [i]")); break;
  161. case 1: // no alignment, offset
  162. Output::Print(_u(" [i + %u (0x%x)]"), offset, offset); break;
  163. case 2: // alignment, no offset
  164. Output::Print(_u(" [i & ~0x%x]"), (1 << alignment) - 1); break;
  165. case 3: // alignment, offset
  166. Output::Print(_u(" [i + %u (0x%x) & ~0x%x]"), offset, offset, (1 << alignment) - 1); break;
  167. }
  168. break;
  169. }
  170. }
  171. Output::SkipToColumn(40);
  172. PrintTypeStack();
  173. }
  174. void WasmBytecodeGenerator::PrintOpEnd()
  175. {
  176. if (lastOpId == opId)
  177. {
  178. ++opId;
  179. Output::Print(_u(" -> "));
  180. PrintTypeStack();
  181. Output::Print(_u("\r\n"));
  182. }
  183. }
  184. #endif
  185. /* static */
  186. Js::AsmJsRetType WasmToAsmJs::GetAsmJsReturnType(WasmTypes::WasmType wasmType)
  187. {
  188. switch (wasmType)
  189. {
  190. case WasmTypes::I32: return Js::AsmJsRetType::Signed;
  191. case WasmTypes::I64: return Js::AsmJsRetType::Int64;
  192. case WasmTypes::F32: return Js::AsmJsRetType::Float;
  193. case WasmTypes::F64: return Js::AsmJsRetType::Double;
  194. case WasmTypes::Void: return Js::AsmJsRetType::Void;
  195. #ifdef ENABLE_WASM_SIMD
  196. case WasmTypes::V128:
  197. Simd::EnsureSimdIsEnabled();
  198. return Js::AsmJsRetType::Float32x4;
  199. #endif
  200. default:
  201. WasmTypes::CompileAssertCasesNoFailFast<WasmTypes::I32, WasmTypes::I64, WasmTypes::F32, WasmTypes::F64, WASM_V128_CHECK_TYPE>();
  202. throw WasmCompilationException(_u("Unknown return type %u"), wasmType);
  203. }
  204. }
  205. /* static */
  206. Js::AsmJsVarType WasmToAsmJs::GetAsmJsVarType(WasmTypes::WasmType wasmType)
  207. {
  208. Js::AsmJsVarType asmType = Js::AsmJsVarType::Int;
  209. switch (wasmType)
  210. {
  211. case WasmTypes::I32: return Js::AsmJsVarType::Int;
  212. case WasmTypes::I64: return Js::AsmJsVarType::Int64;
  213. case WasmTypes::F32: return Js::AsmJsVarType::Float;
  214. case WasmTypes::F64: return Js::AsmJsVarType::Double;
  215. #ifdef ENABLE_WASM_SIMD
  216. case WasmTypes::V128:
  217. Simd::EnsureSimdIsEnabled();
  218. return Js::AsmJsVarType::Float32x4;
  219. #endif
  220. default:
  221. WasmTypes::CompileAssertCasesNoFailFast<WasmTypes::I32, WasmTypes::I64, WasmTypes::F32, WasmTypes::F64, WASM_V128_CHECK_TYPE>();
  222. throw WasmCompilationException(_u("Unknown var type %u"), wasmType);
  223. }
  224. }
  225. typedef bool(*SectionProcessFunc)(WasmModuleGenerator*);
  226. typedef void(*AfterSectionCallback)(WasmModuleGenerator*);
  227. WasmModuleGenerator::WasmModuleGenerator(Js::ScriptContext* scriptContext, Js::WebAssemblySource* src) :
  228. m_sourceInfo(src->GetSourceInfo()),
  229. m_scriptContext(scriptContext),
  230. m_recycler(scriptContext->GetRecycler())
  231. {
  232. m_module = RecyclerNewFinalized(m_recycler, Js::WebAssemblyModule, scriptContext, src->GetBuffer(), src->GetBufferLength(), scriptContext->GetLibrary()->GetWebAssemblyModuleType());
  233. m_sourceInfo->EnsureInitialized(0);
  234. m_sourceInfo->GetSrcInfo()->sourceContextInfo->EnsureInitialized();
  235. }
  236. Js::WebAssemblyModule* WasmModuleGenerator::GenerateModule()
  237. {
  238. Js::AutoProfilingPhase wasmPhase(m_scriptContext, Js::WasmReaderPhase);
  239. Unused(wasmPhase);
  240. m_module->GetReader()->InitializeReader();
  241. BVStatic<bSectLimit + 1> visitedSections;
  242. SectionCode nextExpectedSection = bSectCustom;
  243. while (true)
  244. {
  245. SectionHeader sectionHeader = GetReader()->ReadNextSection();
  246. SectionCode sectionCode = sectionHeader.code;
  247. if (sectionCode == bSectLimit)
  248. {
  249. TRACE_WASM(PHASE_TRACE1(Js::WasmSectionPhase), _u("Done reading module's sections"));
  250. break;
  251. }
  252. // Make sure dependency for this section has been seen
  253. SectionCode precedent = SectionInfo::All[sectionCode].precedent;
  254. if (precedent != bSectLimit && !visitedSections.Test(precedent))
  255. {
  256. throw WasmCompilationException(_u("%s section missing before %s"),
  257. SectionInfo::All[precedent].name,
  258. sectionHeader.name);
  259. }
  260. visitedSections.Set(sectionCode);
  261. // Custom section are allowed in any order
  262. if (sectionCode != bSectCustom)
  263. {
  264. if (sectionCode < nextExpectedSection)
  265. {
  266. throw WasmCompilationException(_u("Invalid Section %s"), sectionHeader.name);
  267. }
  268. nextExpectedSection = SectionCode(sectionCode + 1);
  269. }
  270. if (!GetReader()->ProcessCurrentSection())
  271. {
  272. throw WasmCompilationException(_u("Error while reading section %s"), sectionHeader.name);
  273. }
  274. }
  275. uint32 funcCount = m_module->GetWasmFunctionCount();
  276. SourceContextInfo * sourceContextInfo = m_sourceInfo->GetSrcInfo()->sourceContextInfo;
  277. m_sourceInfo->EnsureInitialized(funcCount);
  278. sourceContextInfo->nextLocalFunctionId += funcCount;
  279. sourceContextInfo->EnsureInitialized();
  280. for (uint32 i = 0; i < funcCount; ++i)
  281. {
  282. GenerateFunctionHeader(i);
  283. }
  284. #if ENABLE_DEBUG_CONFIG_OPTIONS
  285. WasmFunctionInfo* firstThunk = nullptr, *lastThunk = nullptr;
  286. for (uint32 i = 0; i < funcCount; ++i)
  287. {
  288. WasmFunctionInfo* info = m_module->GetWasmFunctionInfo(i);
  289. Assert(info->GetBody());
  290. if (PHASE_TRACE(Js::WasmInOutPhase, info->GetBody()))
  291. {
  292. uint32 index = m_module->GetWasmFunctionCount();
  293. WasmFunctionInfo* newInfo = m_module->AddWasmFunctionInfo(info->GetSignature());
  294. if (!firstThunk)
  295. {
  296. firstThunk = newInfo;
  297. }
  298. lastThunk = newInfo;
  299. GenerateFunctionHeader(index);
  300. m_module->SwapWasmFunctionInfo(i, index);
  301. m_module->AttachCustomInOutTracingReader(newInfo, index);
  302. }
  303. }
  304. if (firstThunk)
  305. {
  306. int sourceId = (int)firstThunk->GetBody()->GetSourceContextId();
  307. char16 range[64];
  308. swprintf_s(range, 64, _u("%d.%d-%d.%d"),
  309. sourceId, firstThunk->GetBody()->GetLocalFunctionId(),
  310. sourceId, lastThunk->GetBody()->GetLocalFunctionId());
  311. char16 offFullJit[128];
  312. swprintf_s(offFullJit, 128, _u("-off:fulljit:%s"), range);
  313. char16 offSimpleJit[128];
  314. swprintf_s(offSimpleJit, 128, _u("-off:simplejit:%s"), range);
  315. char16 offLoopJit[128];
  316. swprintf_s(offLoopJit, 128, _u("-off:jitloopbody:%s"), range);
  317. char16* argv[] = { nullptr, offFullJit, offSimpleJit, offLoopJit };
  318. CmdLineArgsParser parser(nullptr);
  319. parser.Parse(ARRAYSIZE(argv), argv);
  320. }
  321. #endif
  322. // If we see a FunctionSignatures section we need to see a FunctionBodies section
  323. if (visitedSections.Test(bSectFunction) && !visitedSections.Test(bSectFunctionBodies))
  324. {
  325. throw WasmCompilationException(_u("Missing required section: %s"), SectionInfo::All[bSectFunctionBodies].name);
  326. }
  327. return m_module;
  328. }
  329. WasmBinaryReader* WasmModuleGenerator::GetReader() const
  330. {
  331. return m_module->GetReader();
  332. }
  333. void WasmModuleGenerator::GenerateFunctionHeader(uint32 index)
  334. {
  335. WasmFunctionInfo* wasmInfo = m_module->GetWasmFunctionInfo(index);
  336. if (!wasmInfo)
  337. {
  338. throw WasmCompilationException(_u("Invalid function index %u"), index);
  339. }
  340. const char16* functionName = nullptr;
  341. int nameLength = 0;
  342. if (wasmInfo->GetNameLength() > 0)
  343. {
  344. functionName = wasmInfo->GetName();
  345. nameLength = wasmInfo->GetNameLength();
  346. }
  347. else
  348. {
  349. for (uint32 iExport = 0; iExport < m_module->GetExportCount(); ++iExport)
  350. {
  351. Wasm::WasmExport* wasmExport = m_module->GetExport(iExport);
  352. if (wasmExport &&
  353. wasmExport->kind == ExternalKinds::Function &&
  354. wasmExport->nameLength > 0 &&
  355. m_module->GetFunctionIndexType(wasmExport->index) == FunctionIndexTypes::Function &&
  356. wasmExport->index == wasmInfo->GetNumber())
  357. {
  358. nameLength = wasmExport->nameLength + 16;
  359. char16 * autoName = RecyclerNewArrayLeafZ(m_recycler, char16, nameLength);
  360. nameLength = swprintf_s(autoName, nameLength, _u("%s[%u]"), wasmExport->name, wasmInfo->GetNumber());
  361. functionName = autoName;
  362. break;
  363. }
  364. }
  365. }
  366. if (!functionName)
  367. {
  368. char16* autoName = RecyclerNewArrayLeafZ(m_recycler, char16, 32);
  369. nameLength = swprintf_s(autoName, 32, _u("wasm-function[%u]"), wasmInfo->GetNumber());
  370. functionName = autoName;
  371. }
  372. Js::FunctionBody* body = Js::FunctionBody::NewFromRecycler(
  373. m_scriptContext,
  374. functionName,
  375. nameLength,
  376. 0,
  377. 0,
  378. m_sourceInfo,
  379. m_sourceInfo->GetSrcInfo()->sourceContextInfo->sourceContextId,
  380. wasmInfo->GetNumber(),
  381. Js::FunctionInfo::Attributes::ErrorOnNew,
  382. Js::FunctionBody::Flags_None
  383. #ifdef PERF_COUNTERS
  384. , false /* is function from deferred deserialized proxy */
  385. #endif
  386. );
  387. wasmInfo->SetBody(body);
  388. // TODO (michhol): numbering
  389. body->SetSourceInfo(0);
  390. body->AllocateAsmJsFunctionInfo();
  391. body->SetIsAsmJsFunction(true);
  392. body->SetIsAsmjsMode(true);
  393. body->SetIsWasmFunction(true);
  394. WasmReaderInfo* readerInfo = RecyclerNew(m_recycler, WasmReaderInfo);
  395. readerInfo->m_funcInfo = wasmInfo;
  396. readerInfo->m_module = m_module;
  397. Js::WasmLibrary::ResetFunctionBodyDefaultEntryPoint(body);
  398. Js::AsmJsFunctionInfo* info = body->GetAsmJsFunctionInfo();
  399. info->SetWasmReaderInfo(readerInfo);
  400. info->SetWebAssemblyModule(m_module);
  401. Js::ArgSlot paramCount = wasmInfo->GetParamCount();
  402. info->SetArgCount(paramCount);
  403. info->SetWasmSignature(wasmInfo->GetSignature());
  404. Js::ArgSlot argSizeLength = max(paramCount, 3ui16);
  405. info->SetArgSizeArrayLength(argSizeLength);
  406. uint32* argSizeArray = RecyclerNewArrayLeafZ(m_recycler, uint32, argSizeLength);
  407. info->SetArgsSizesArray(argSizeArray);
  408. if (paramCount > 0)
  409. {
  410. // +1 here because asm.js includes the this pointer
  411. body->SetInParamsCount(paramCount + 1);
  412. body->SetReportedInParamsCount(paramCount + 1);
  413. info->SetArgTypeArray(RecyclerNewArrayLeaf(m_recycler, Js::AsmJsVarType::Which, paramCount));
  414. }
  415. else
  416. {
  417. // overwrite default value in this case
  418. body->SetHasImplicitArgIns(false);
  419. }
  420. for (Js::ArgSlot i = 0; i < paramCount; ++i)
  421. {
  422. WasmTypes::WasmType type = wasmInfo->GetSignature()->GetParam(i);
  423. info->SetArgType(WasmToAsmJs::GetAsmJsVarType(type), i);
  424. argSizeArray[i] = wasmInfo->GetSignature()->GetParamSize(i);
  425. }
  426. info->SetArgByteSize(wasmInfo->GetSignature()->GetParamsSize());
  427. if (wasmInfo->GetSignature()->GetResultCount() <= 1)
  428. {
  429. WasmTypes::WasmType returnType = wasmInfo->GetSignature()->GetResultCount() == 1 ? wasmInfo->GetSignature()->GetResult(0) : WasmTypes::Void;
  430. info->SetReturnType(WasmToAsmJs::GetAsmJsReturnType(returnType));
  431. }
  432. else
  433. {
  434. throw WasmCompilationException(_u("Multi return values not supported"));
  435. }
  436. }
  437. WAsmJs::RegisterSpace* AllocateRegisterSpace(ArenaAllocator* alloc, WAsmJs::Types)
  438. {
  439. return Anew(alloc, WAsmJs::RegisterSpace, 1);
  440. }
  441. void WasmBytecodeGenerator::GenerateFunctionBytecode(Js::ScriptContext* scriptContext, WasmReaderInfo* readerinfo, bool validateOnly /*= false*/)
  442. {
  443. WasmBytecodeGenerator generator(scriptContext, readerinfo, validateOnly);
  444. generator.GenerateFunction();
  445. if (!generator.GetReader()->IsCurrentFunctionCompleted())
  446. {
  447. throw WasmCompilationException(_u("Invalid function format"));
  448. }
  449. }
  450. void WasmBytecodeGenerator::ValidateFunction(Js::ScriptContext* scriptContext, WasmReaderInfo* readerinfo)
  451. {
  452. GenerateFunctionBytecode(scriptContext, readerinfo, true);
  453. }
  454. WasmBytecodeGenerator::WasmBytecodeGenerator(Js::ScriptContext* scriptContext, WasmReaderInfo* readerInfo, bool validateOnly) :
  455. m_scriptContext(scriptContext),
  456. m_alloc(_u("WasmBytecodeGen"), scriptContext->GetThreadContext()->GetPageAllocator(), Js::Throw::OutOfMemory),
  457. m_evalStack(&m_alloc),
  458. mTypedRegisterAllocator(&m_alloc, AllocateRegisterSpace, Simd::IsEnabled() ? 0 : 1 << WAsmJs::SIMD),
  459. m_blockInfos(&m_alloc),
  460. currentProfileId(0),
  461. isUnreachable(false)
  462. {
  463. m_emptyWriter = Anew(&m_alloc, Js::EmptyWasmByteCodeWriter);
  464. m_writer = m_originalWriter = validateOnly ? m_emptyWriter : Anew(&m_alloc, Js::WasmByteCodeWriter);
  465. m_writer->Create();
  466. m_funcInfo = readerInfo->m_funcInfo;
  467. m_module = readerInfo->m_module;
  468. // Init reader to current func offset
  469. GetReader()->SeekToFunctionBody(m_funcInfo);
  470. const uint32 estimated = GetReader()->EstimateCurrentFunctionBytecodeSize();
  471. m_writer->InitData(&m_alloc, estimated);
  472. }
  473. void WasmBytecodeGenerator::GenerateFunction()
  474. {
  475. #ifdef ENABLE_DEBUG_CONFIG_OPTIONS
  476. if (DO_WASM_TRACE_BYTECODE)
  477. {
  478. Output::Print(_u("Generate WebAssembly Bytecode: "));
  479. GetFunctionBody()->DumpFullFunctionName();
  480. Output::Print(_u("\n"));
  481. }
  482. #endif
  483. if (PHASE_OFF(Js::WasmBytecodePhase, GetFunctionBody()))
  484. {
  485. throw WasmCompilationException(_u("Compilation skipped"));
  486. }
  487. Js::AutoProfilingPhase functionProfiler(m_scriptContext, Js::WasmBytecodePhase);
  488. Unused(functionProfiler);
  489. m_maxArgOutDepth = 0;
  490. m_writer->Begin(GetFunctionBody(), &m_alloc);
  491. struct AutoCleanupGeneratorState
  492. {
  493. WasmBytecodeGenerator* gen;
  494. AutoCleanupGeneratorState(WasmBytecodeGenerator* gen) : gen(gen) {}
  495. ~AutoCleanupGeneratorState()
  496. {
  497. if (gen)
  498. {
  499. TRACE_WASM(PHASE_TRACE(Js::WasmBytecodePhase, gen->GetFunctionBody()), _u("\nHad Compilation error!"));
  500. gen->GetReader()->FunctionEnd();
  501. gen->m_originalWriter->Reset();
  502. }
  503. }
  504. void Complete() { gen = nullptr; }
  505. };
  506. AutoCleanupGeneratorState autoCleanupGeneratorState(this);
  507. Js::ByteCodeLabel exitLabel = m_writer->DefineLabel();
  508. m_funcInfo->SetExitLabel(exitLabel);
  509. EnregisterLocals();
  510. // The function's yield type is the return type
  511. Js::ByteCodeLabel blockLabel = m_writer->DefineLabel();
  512. WasmBlock funcBlockData;
  513. funcBlockData.SetSignatureId(m_funcInfo->GetSignature()->GetSignatureId());
  514. m_funcBlock = PushLabel(funcBlockData, blockLabel, true, false);
  515. EnterEvalStackScope(m_funcBlock);
  516. EmitBlockCommon(m_funcBlock);
  517. m_writer->MarkAsmJsLabel(blockLabel);
  518. PolymorphicEmitInfo yieldInfo = PopLabel(blockLabel);
  519. if (yieldInfo.Count() > 0 || m_funcInfo->GetResultCount() == 0)
  520. {
  521. EmitReturnExpr(&yieldInfo);
  522. }
  523. DebugPrintOpEnd();
  524. ExitEvalStackScope(m_funcBlock);
  525. SetUnreachableState(false);
  526. m_writer->MarkAsmJsLabel(exitLabel);
  527. m_writer->EmptyAsm(Js::OpCodeAsmJs::Ret);
  528. m_writer->SetCallSiteCount(this->currentProfileId);
  529. m_writer->End();
  530. GetReader()->FunctionEnd();
  531. autoCleanupGeneratorState.Complete();
  532. // Make sure we don't have any unforeseen exceptions as we finalize the body
  533. AutoDisableInterrupt autoDisableInterrupt(m_scriptContext->GetThreadContext(), true);
  534. #if DBG_DUMP
  535. if ((
  536. PHASE_DUMP(Js::WasmBytecodePhase, GetFunctionBody()) ||
  537. PHASE_DUMP(Js::ByteCodePhase, GetFunctionBody())
  538. ) && !IsValidating())
  539. {
  540. Js::AsmJsByteCodeDumper::Dump(GetFunctionBody(), &mTypedRegisterAllocator, nullptr);
  541. }
  542. if (PHASE_DUMP(Js::WasmOpCodeDistributionPhase, GetFunctionBody()))
  543. {
  544. m_module->GetReader()->PrintOps();
  545. }
  546. #endif
  547. Js::AsmJsFunctionInfo* info = GetFunctionBody()->GetAsmJsFunctionInfo();
  548. mTypedRegisterAllocator.CommitToFunctionBody(GetFunctionBody());
  549. mTypedRegisterAllocator.CommitToFunctionInfo(info, GetFunctionBody());
  550. GetFunctionBody()->CheckAndSetOutParamMaxDepth(m_maxArgOutDepth);
  551. autoDisableInterrupt.Completed();
  552. }
  553. void WasmBytecodeGenerator::EnregisterLocals()
  554. {
  555. uint32 nLocals = m_funcInfo->GetLocalCount();
  556. m_locals = AnewArray(&m_alloc, WasmLocal, nLocals);
  557. m_funcInfo->GetBody()->SetFirstTmpReg(nLocals);
  558. for (uint32 i = 0; i < nLocals; ++i)
  559. {
  560. WasmTypes::WasmType type = m_funcInfo->GetLocal(i);
  561. WasmRegisterSpace* regSpace = GetRegisterSpace(type);
  562. m_locals[i] = WasmLocal(regSpace->AcquireRegister(), type);
  563. // Zero only the locals not corresponding to formal parameters.
  564. if (i >= m_funcInfo->GetParamCount()) {
  565. switch (type)
  566. {
  567. case WasmTypes::F32:
  568. m_writer->AsmFloat1Const1(Js::OpCodeAsmJs::Ld_FltConst, m_locals[i].location, 0.0f);
  569. break;
  570. case WasmTypes::F64:
  571. m_writer->AsmDouble1Const1(Js::OpCodeAsmJs::Ld_DbConst, m_locals[i].location, 0.0);
  572. break;
  573. case WasmTypes::I32:
  574. m_writer->AsmInt1Const1(Js::OpCodeAsmJs::Ld_IntConst, m_locals[i].location, 0);
  575. break;
  576. case WasmTypes::I64:
  577. m_writer->AsmLong1Const1(Js::OpCodeAsmJs::Ld_LongConst, m_locals[i].location, 0);
  578. break;
  579. #ifdef ENABLE_WASM_SIMD
  580. case WasmTypes::V128:
  581. {
  582. Simd::EnsureSimdIsEnabled();
  583. m_writer->WasmSimdConst(Js::OpCodeAsmJs::Simd128_LdC, m_locals[i].location, 0, 0, 0, 0);
  584. break;
  585. }
  586. #endif
  587. default:
  588. Assume(UNREACHED);
  589. }
  590. }
  591. }
  592. }
  593. template <size_t lanes>
  594. EmitInfo WasmBytecodeGenerator::EmitSimdBuildExpr(Js::OpCodeAsmJs op, const WasmTypes::WasmType* signature)
  595. {
  596. const WasmTypes::WasmType resultType = signature[0];
  597. const WasmTypes::WasmType type = signature[1];
  598. Js::RegSlot resultReg = GetRegisterSpace(resultType)->AcquireTmpRegister();
  599. EmitInfo args[lanes];
  600. for (uint i = 0; i < lanes; i++)
  601. {
  602. args[i] = PopEvalStack(type);
  603. }
  604. switch (lanes)
  605. {
  606. case 4:
  607. m_writer->AsmReg5(op, resultReg, args[3].location, args[2].location, args[1].location, args[0].location);
  608. break;
  609. case 8:
  610. m_writer->AsmReg9(op, resultReg, args[7].location, args[6].location, args[5].location, args[4].location, args[3].location, args[2].location, args[1].location, args[0].location);
  611. break;
  612. case 16:
  613. m_writer->AsmReg17(op, resultReg, args[15].location, args[14].location, args[13].location, args[12].location, args[11].location, args[10].location, args[9].location, args[8].location, args[7].location, args[6].location, args[5].location, args[4].location, args[3].location, args[2].location, args[1].location, args[0].location);
  614. break;
  615. default:
  616. Assert(UNREACHED);
  617. }
  618. for (uint i = 0; i < lanes; i++)
  619. {
  620. ReleaseLocation(&args[i]);
  621. }
  622. return EmitInfo(resultReg, resultType);
  623. }
  624. void WasmBytecodeGenerator::EmitExpr(WasmOp op)
  625. {
  626. DebugPrintOp(op);
  627. switch (op)
  628. {
  629. #define WASM_OPCODE(opname, opcode, sig, imp, wat) \
  630. case opcode: \
  631. if (!imp) throw WasmCompilationException(_u("Operator %s is Not Yet Implemented"), _u(wat)); break;
  632. #include "WasmBinaryOpCodes.h"
  633. default:
  634. break;
  635. }
  636. PolymorphicEmitInfo info;
  637. switch (op)
  638. {
  639. case wbGetGlobal:
  640. info = EmitGetGlobal();
  641. break;
  642. case wbSetGlobal:
  643. info = EmitSetGlobal();
  644. break;
  645. case wbGetLocal:
  646. info = EmitGetLocal();
  647. break;
  648. case wbSetLocal:
  649. info = EmitSetLocal(false);
  650. break;
  651. case wbTeeLocal:
  652. info = EmitSetLocal(true);
  653. break;
  654. case wbReturn:
  655. EmitReturnExpr();
  656. info = EmitInfo(WasmTypes::Any);
  657. break;
  658. case wbF32Const:
  659. info = EmitConst(WasmTypes::F32, GetReader()->m_currentNode.cnst);
  660. break;
  661. case wbF64Const:
  662. info = EmitConst(WasmTypes::F64, GetReader()->m_currentNode.cnst);
  663. break;
  664. case wbI32Const:
  665. info = EmitConst(WasmTypes::I32, GetReader()->m_currentNode.cnst);
  666. break;
  667. case wbI64Const:
  668. info = EmitConst(WasmTypes::I64, GetReader()->m_currentNode.cnst);
  669. break;
  670. #ifdef ENABLE_WASM_SIMD
  671. case wbV128Const:
  672. Simd::EnsureSimdIsEnabled();
  673. info = EmitConst(WasmTypes::V128, GetReader()->m_currentNode.cnst);
  674. break;
  675. #endif
  676. case wbBlock:
  677. info = EmitBlock();
  678. break;
  679. case wbLoop:
  680. info = EmitLoop();
  681. break;
  682. case wbCall:
  683. info = EmitCall<wbCall>();
  684. break;
  685. case wbCallIndirect:
  686. info = EmitCall<wbCallIndirect>();
  687. break;
  688. case wbIf:
  689. info = EmitIfElseExpr();
  690. break;
  691. case wbElse:
  692. throw WasmCompilationException(_u("Unexpected else opcode"));
  693. case wbEnd:
  694. throw WasmCompilationException(_u("Unexpected end opcode"));
  695. case wbBr:
  696. EmitBr();
  697. info = EmitInfo(WasmTypes::Any);
  698. break;
  699. case wbBrIf:
  700. info = EmitBrIf();
  701. break;
  702. case wbSelect:
  703. info = EmitSelect();
  704. break;
  705. case wbBrTable:
  706. EmitBrTable();
  707. info = EmitInfo(WasmTypes::Any);
  708. break;
  709. case wbDrop:
  710. info = EmitDrop();
  711. break;
  712. case wbNop:
  713. return;
  714. case wbMemorySize:
  715. {
  716. SetUsesMemory(0);
  717. Js::RegSlot tempReg = GetRegisterSpace(WasmTypes::I32)->AcquireTmpRegister();
  718. info = EmitInfo(tempReg, WasmTypes::I32);
  719. m_writer->AsmReg1(Js::OpCodeAsmJs::MemorySize_Int, tempReg);
  720. break;
  721. }
  722. case wbMemoryGrow:
  723. {
  724. info = EmitGrowMemory();
  725. break;
  726. }
  727. case wbUnreachable:
  728. m_writer->EmptyAsm(Js::OpCodeAsmJs::Unreachable_Void);
  729. SetUnreachableState(true);
  730. info = EmitInfo(WasmTypes::Any);
  731. break;
  732. #ifdef ENABLE_WASM_SIMD
  733. case wbV128Bitselect:
  734. Simd::EnsureSimdIsEnabled();
  735. info = EmitV128BitSelect();
  736. break;
  737. case wbV8X16Shuffle:
  738. Simd::EnsureSimdIsEnabled();
  739. info = EmitV8X16Shuffle();
  740. break;
  741. #define WASM_EXTRACTLANE_OPCODE(opname, opcode, sig, asmjsop, ...) \
  742. case wb##opname: \
  743. Simd::EnsureSimdIsEnabled();\
  744. info = EmitExtractLaneExpr(Js::OpCodeAsmJs::##asmjsop, WasmOpCodeSignatures::sig); \
  745. break;
  746. #define WASM_REPLACELANE_OPCODE(opname, opcode, sig, asmjsop, ...) \
  747. case wb##opname: \
  748. Simd::EnsureSimdIsEnabled();\
  749. info = EmitReplaceLaneExpr(Js::OpCodeAsmJs::##asmjsop, WasmOpCodeSignatures::sig); \
  750. break;
  751. #endif
  752. #define WASM_MEMREAD_OPCODE(opname, opcode, sig, imp, viewtype, wat) \
  753. case wb##opname: \
  754. Assert(WasmOpCodeSignatures::n##sig > 0);\
  755. info = EmitMemAccess<false, false>(wb##opname, WasmOpCodeSignatures::sig, viewtype); \
  756. break;
  757. #define WASM_ATOMICREAD_OPCODE(opname, opcode, sig, imp, viewtype, wat) \
  758. case wb##opname: \
  759. Assert(WasmOpCodeSignatures::n##sig > 0);\
  760. info = EmitMemAccess<false, true>(wb##opname, WasmOpCodeSignatures::sig, viewtype); \
  761. break;
  762. #define WASM_MEMSTORE_OPCODE(opname, opcode, sig, imp, viewtype, wat) \
  763. case wb##opname: \
  764. Assert(WasmOpCodeSignatures::n##sig > 0);\
  765. info = EmitMemAccess<true, false>(wb##opname, WasmOpCodeSignatures::sig, viewtype); \
  766. break;
  767. #define WASM_ATOMICSTORE_OPCODE(opname, opcode, sig, imp, viewtype, wat) \
  768. case wb##opname: \
  769. Assert(WasmOpCodeSignatures::n##sig > 0);\
  770. info = EmitMemAccess<true, true>(wb##opname, WasmOpCodeSignatures::sig, viewtype); \
  771. break;
  772. #define WASM_SIMD_MEMREAD_OPCODE(opname, opcode, sig, asmjsop, viewtype, dataWidth, ...) \
  773. case wb##opname: \
  774. Assert(WasmOpCodeSignatures::n##sig > 0);\
  775. info = EmitSimdMemAccess(Js::OpCodeAsmJs::##asmjsop, WasmOpCodeSignatures::sig, viewtype, dataWidth, false); \
  776. break;
  777. #define WASM_SIMD_MEMSTORE_OPCODE(opname, opcode, sig, asmjsop, viewtype, dataWidth, ...) \
  778. case wb##opname: \
  779. Assert(WasmOpCodeSignatures::n##sig > 0);\
  780. info = EmitSimdMemAccess(Js::OpCodeAsmJs::##asmjsop, WasmOpCodeSignatures::sig, viewtype, dataWidth, true); \
  781. break;
  782. #define WASM_BINARY_OPCODE(opname, opcode, sig, asmjsop, imp, wat) \
  783. case wb##opname: \
  784. Assert(WasmOpCodeSignatures::n##sig == 3);\
  785. info = EmitBinExpr(Js::OpCodeAsmJs::##asmjsop, WasmOpCodeSignatures::sig); \
  786. break;
  787. #define WASM_UNARY__OPCODE(opname, opcode, sig, asmjsop, imp, wat) \
  788. case wb##opname: \
  789. Assert(WasmOpCodeSignatures::n##sig == 2);\
  790. info = EmitUnaryExpr(Js::OpCodeAsmJs::##asmjsop, WasmOpCodeSignatures::sig); \
  791. break;
  792. #define WASM_SIMD_BUILD_OPCODE(opname, opcode, sig, asmjop, lanes, ...) \
  793. case wb##opname: \
  794. Assert(WasmOpCodeSignatures::n##sig == 2);\
  795. info = EmitSimdBuildExpr<lanes>(Js::OpCodeAsmJs::##asmjop, WasmOpCodeSignatures::sig); \
  796. break;
  797. #define WASM_EMPTY__OPCODE(opname, opcode, asmjsop, imp, wat) \
  798. case wb##opname: \
  799. m_writer->EmptyAsm(Js::OpCodeAsmJs::##asmjsop);\
  800. break;
  801. #include "WasmBinaryOpCodes.h"
  802. default:
  803. throw WasmCompilationException(_u("Unknown expression's op 0x%X"), op);
  804. }
  805. PushEvalStack(info);
  806. DebugPrintOpEnd();
  807. }
  808. EmitInfo WasmBytecodeGenerator::EmitGetGlobal()
  809. {
  810. uint32 globalIndex = GetReader()->m_currentNode.var.num;
  811. WasmGlobal* global = m_module->GetGlobal(globalIndex);
  812. WasmTypes::WasmType type = global->GetType();
  813. Js::RegSlot slot = m_module->GetOffsetForGlobal(global);
  814. CompileAssert(WasmTypes::I32 == 1);
  815. CompileAssert(WasmTypes::I64 == 2);
  816. CompileAssert(WasmTypes::F32 == 3);
  817. CompileAssert(WasmTypes::F64 == 4);
  818. static const Js::OpCodeAsmJs globalOpcodes[] = {
  819. Js::OpCodeAsmJs::LdSlot_Int,
  820. Js::OpCodeAsmJs::LdSlot_Long,
  821. Js::OpCodeAsmJs::LdSlot_Flt,
  822. Js::OpCodeAsmJs::LdSlot_Db
  823. };
  824. WasmRegisterSpace* regSpace = GetRegisterSpace(type);
  825. Js::RegSlot tmpReg = regSpace->AcquireTmpRegister();
  826. EmitInfo info(tmpReg, type);
  827. m_writer->AsmSlot(globalOpcodes[type - 1], tmpReg, WasmBytecodeGenerator::ModuleEnvRegister, slot);
  828. return info;
  829. }
  830. EmitInfo WasmBytecodeGenerator::EmitSetGlobal()
  831. {
  832. uint32 globalIndex = GetReader()->m_currentNode.var.num;
  833. WasmGlobal* global = m_module->GetGlobal(globalIndex);
  834. Js::RegSlot slot = m_module->GetOffsetForGlobal(global);
  835. WasmTypes::WasmType type = global->GetType();
  836. EmitInfo info = PopEvalStack(type);
  837. CompileAssert(WasmTypes::I32 == 1);
  838. CompileAssert(WasmTypes::I64 == 2);
  839. CompileAssert(WasmTypes::F32 == 3);
  840. CompileAssert(WasmTypes::F64 == 4);
  841. static const Js::OpCodeAsmJs globalOpcodes[] = {
  842. Js::OpCodeAsmJs::StSlot_Int,
  843. Js::OpCodeAsmJs::StSlot_Long,
  844. Js::OpCodeAsmJs::StSlot_Flt,
  845. Js::OpCodeAsmJs::StSlot_Db
  846. };
  847. m_writer->AsmSlot(globalOpcodes[type - 1], info.location, WasmBytecodeGenerator::ModuleEnvRegister, slot);
  848. ReleaseLocation(&info);
  849. return EmitInfo();
  850. }
  851. EmitInfo WasmBytecodeGenerator::EmitGetLocal()
  852. {
  853. uint32 localIndex = GetReader()->m_currentNode.var.num;
  854. if (m_funcInfo->GetLocalCount() <= localIndex)
  855. {
  856. throw WasmCompilationException(_u("%u is not a valid local"), localIndex);
  857. }
  858. WasmLocal local = m_locals[localIndex];
  859. Js::OpCodeAsmJs op = GetLoadOp(local.type);
  860. WasmRegisterSpace* regSpace = GetRegisterSpace(local.type);
  861. Js::RegSlot tmpReg = regSpace->AcquireTmpRegister();
  862. m_writer->AsmReg2(op, tmpReg, local.location);
  863. return EmitInfo(tmpReg, local.type);
  864. }
  865. EmitInfo WasmBytecodeGenerator::EmitSetLocal(bool tee)
  866. {
  867. uint32 localNum = GetReader()->m_currentNode.var.num;
  868. if (localNum >= m_funcInfo->GetLocalCount())
  869. {
  870. throw WasmCompilationException(_u("%u is not a valid local"), localNum);
  871. }
  872. WasmLocal local = m_locals[localNum];
  873. EmitInfo info = PopEvalStack(local.type);
  874. m_writer->AsmReg2(GetLoadOp(local.type), local.location, info.location);
  875. if (tee)
  876. {
  877. if (info.type == WasmTypes::Any)
  878. {
  879. throw WasmCompilationException(_u("Can't tee_local unreachable values"));
  880. }
  881. return info;
  882. }
  883. else
  884. {
  885. ReleaseLocation(&info);
  886. return EmitInfo();
  887. }
  888. }
  889. EmitInfo WasmBytecodeGenerator::EmitConst(WasmTypes::WasmType type, WasmConstLitNode cnst)
  890. {
  891. Js::RegSlot tmpReg = GetRegisterSpace(type)->AcquireTmpRegister();
  892. EmitInfo dst(tmpReg, type);
  893. EmitLoadConst(dst, cnst);
  894. return dst;
  895. }
  896. void WasmBytecodeGenerator::EmitLoadConst(EmitInfo dst, WasmConstLitNode cnst)
  897. {
  898. switch (dst.type)
  899. {
  900. case WasmTypes::F32:
  901. m_writer->AsmFloat1Const1(Js::OpCodeAsmJs::Ld_FltConst, dst.location, cnst.f32);
  902. break;
  903. case WasmTypes::F64:
  904. m_writer->AsmDouble1Const1(Js::OpCodeAsmJs::Ld_DbConst, dst.location, cnst.f64);
  905. break;
  906. case WasmTypes::I32:
  907. m_writer->AsmInt1Const1(Js::OpCodeAsmJs::Ld_IntConst, dst.location, cnst.i32);
  908. break;
  909. case WasmTypes::I64:
  910. m_writer->AsmLong1Const1(Js::OpCodeAsmJs::Ld_LongConst, dst.location, cnst.i64);
  911. break;
  912. #ifdef ENABLE_WASM_SIMD
  913. case WasmTypes::V128:
  914. {
  915. Simd::EnsureSimdIsEnabled();
  916. m_writer->WasmSimdConst(Js::OpCodeAsmJs::Simd128_LdC, dst.location, cnst.v128[0], cnst.v128[1], cnst.v128[2], cnst.v128[3]);
  917. break;
  918. }
  919. #endif
  920. default:
  921. WasmTypes::CompileAssertCasesNoFailFast<WasmTypes::I32, WasmTypes::I64, WasmTypes::F32, WasmTypes::F64, WASM_V128_CHECK_TYPE>();
  922. throw WasmCompilationException(_u("Unknown type %u"), dst.type);
  923. }
  924. }
  925. WasmConstLitNode WasmBytecodeGenerator::GetZeroCnst()
  926. {
  927. WasmConstLitNode cnst = {0};
  928. return cnst;
  929. }
  930. void WasmBytecodeGenerator::EnsureStackAvailable()
  931. {
  932. if (!ThreadContext::IsCurrentStackAvailable(Js::Constants::MinStackCompile))
  933. {
  934. throw WasmCompilationException(_u("Maximum supported nested blocks reached"));
  935. }
  936. }
  937. void WasmBytecodeGenerator::EmitBlockCommon(BlockInfo* blockInfo, bool* endOnElse /*= nullptr*/)
  938. {
  939. EnsureStackAvailable();
  940. bool canResetUnreachable = !IsUnreachable();
  941. WasmOp op;
  942. EnterEvalStackScope(blockInfo);
  943. if(endOnElse) *endOnElse = false;
  944. do {
  945. op = GetReader()->ReadExpr();
  946. if (op == wbEnd)
  947. {
  948. break;
  949. }
  950. if (endOnElse && op == wbElse)
  951. {
  952. *endOnElse = true;
  953. break;
  954. }
  955. EmitExpr(op);
  956. } while (true);
  957. DebugPrintOp(op);
  958. if (blockInfo->HasYield())
  959. {
  960. PolymorphicEmitInfo info = PopStackPolymorphic(blockInfo);
  961. YieldToBlock(blockInfo, info);
  962. ReleaseLocation(&info);
  963. }
  964. ExitEvalStackScope(blockInfo);
  965. if (canResetUnreachable)
  966. {
  967. SetUnreachableState(false);
  968. }
  969. }
  970. PolymorphicEmitInfo WasmBytecodeGenerator::EmitBlock()
  971. {
  972. Js::ByteCodeLabel blockLabel = m_writer->DefineLabel();
  973. BlockInfo* blockInfo = PushLabel(GetReader()->m_currentNode.block, blockLabel);
  974. EmitBlockCommon(blockInfo);
  975. m_writer->MarkAsmJsLabel(blockLabel);
  976. PolymorphicEmitInfo yieldInfo = PopLabel(blockLabel);
  977. // block yields last value
  978. return yieldInfo;
  979. }
  980. PolymorphicEmitInfo WasmBytecodeGenerator::EmitLoop()
  981. {
  982. Js::ByteCodeLabel loopTailLabel = m_writer->DefineLabel();
  983. Js::ByteCodeLabel loopHeadLabel = m_writer->DefineLabel();
  984. Js::ByteCodeLabel loopLandingPadLabel = m_writer->DefineLabel();
  985. // Push possibly yielding loop label before capturing all the yielding registers
  986. BlockInfo* implicitBlockInfo = PushLabel(GetReader()->m_currentNode.block, loopTailLabel);
  987. // Save the first tmp (per type) of this loop to discern a yield outside the loop in jitloopbody scenario
  988. Js::RegSlot curRegs[WAsmJs::LIMIT];
  989. for (WAsmJs::Types type = WAsmJs::Types(0); type != WAsmJs::LIMIT; type = WAsmJs::Types(type + 1))
  990. {
  991. uint32 minYield = 0;
  992. if (!mTypedRegisterAllocator.IsTypeExcluded(type))
  993. {
  994. CompileAssert(sizeof(minYield) == sizeof(Js::RegSlot));
  995. minYield = static_cast<uint32>(mTypedRegisterAllocator.GetRegisterSpace(type)->PeekNextTmpRegister());
  996. }
  997. curRegs[type] = minYield;
  998. }
  999. uint32 loopId = m_writer->WasmLoopStart(loopHeadLabel, curRegs);
  1000. // Internally we create a block for loop to exit, but semantically, they don't exist so pop it
  1001. m_blockInfos.Pop();
  1002. // We don't want nested block to jump directly to the loop header
  1003. // instead, jump to the landing pad and let it jump back to the loop header
  1004. PushLabel(GetReader()->m_currentNode.block, loopLandingPadLabel, false);
  1005. EmitBlockCommon(implicitBlockInfo);
  1006. PopLabel(loopLandingPadLabel);
  1007. // By default we don't loop, jump over the landing pad
  1008. m_writer->AsmBr(loopTailLabel);
  1009. m_writer->MarkAsmJsLabel(loopLandingPadLabel);
  1010. m_writer->AsmBr(loopHeadLabel);
  1011. // Put the implicit block back on the stack and yield the last expression to it
  1012. m_blockInfos.Push(implicitBlockInfo);
  1013. m_writer->MarkAsmJsLabel(loopTailLabel);
  1014. // Pop the implicit block to resolve the yield correctly
  1015. PolymorphicEmitInfo loopInfo = PopLabel(loopTailLabel);
  1016. m_writer->ExitLoop(loopId);
  1017. return loopInfo;
  1018. }
  1019. template<WasmOp wasmOp>
  1020. PolymorphicEmitInfo WasmBytecodeGenerator::EmitCall()
  1021. {
  1022. uint32 funcNum = Js::Constants::UninitializedValue;
  1023. uint32 signatureId = Js::Constants::UninitializedValue;
  1024. WasmSignature* calleeSignature = nullptr;
  1025. Js::ProfileId profileId = Js::Constants::NoProfileId;
  1026. EmitInfo indirectIndexInfo;
  1027. const bool isImportCall = GetReader()->m_currentNode.call.funcType == FunctionIndexTypes::Import;
  1028. Assert(isImportCall || GetReader()->m_currentNode.call.funcType == FunctionIndexTypes::Function || GetReader()->m_currentNode.call.funcType == FunctionIndexTypes::ImportThunk);
  1029. switch (wasmOp)
  1030. {
  1031. case wbCall:
  1032. {
  1033. funcNum = GetReader()->m_currentNode.call.num;
  1034. WasmFunctionInfo* calleeInfo = m_module->GetWasmFunctionInfo(funcNum);
  1035. calleeSignature = calleeInfo->GetSignature();
  1036. // currently only handle inlining internal function calls
  1037. // in future we can expand to all calls by adding checks in inliner and falling back to call in case ScriptFunction doesn't match
  1038. if (GetReader()->m_currentNode.call.funcType == FunctionIndexTypes::Function && !PHASE_TRACE1(Js::WasmInOutPhase))
  1039. {
  1040. profileId = GetNextProfileId();
  1041. }
  1042. break;
  1043. }
  1044. case wbCallIndirect:
  1045. indirectIndexInfo = PopEvalStack(WasmTypes::I32, _u("Indirect call index must be int type"));
  1046. signatureId = GetReader()->m_currentNode.call.num;
  1047. calleeSignature = m_module->GetSignature(signatureId);
  1048. break;
  1049. default:
  1050. Assume(UNREACHED);
  1051. }
  1052. const auto argOverflow = []
  1053. {
  1054. throw WasmCompilationException(_u("Argument size too big"));
  1055. };
  1056. // emit start call
  1057. Js::ArgSlot argSize;
  1058. Js::OpCodeAsmJs startCallOp;
  1059. if (isImportCall)
  1060. {
  1061. argSize = ArgSlotMath::Mul(calleeSignature->GetParamCount(), sizeof(Js::Var), argOverflow);
  1062. startCallOp = Js::OpCodeAsmJs::StartCall;
  1063. }
  1064. else
  1065. {
  1066. startCallOp = Js::OpCodeAsmJs::I_StartCall;
  1067. argSize = calleeSignature->GetParamsSize();
  1068. }
  1069. // Add return value
  1070. argSize = ArgSlotMath::Add(argSize, sizeof(Js::Var), argOverflow);
  1071. if (!Math::IsAligned<Js::ArgSlot>(argSize, sizeof(Js::Var)))
  1072. {
  1073. AssertMsg(UNREACHED, "Wasm argument size should always be Var aligned");
  1074. throw WasmCompilationException(_u("Internal Error"));
  1075. }
  1076. m_writer->AsmStartCall(startCallOp, argSize);
  1077. Js::ArgSlot nArgs = calleeSignature->GetParamCount();
  1078. // copy args into a list so they could be generated in the right order (FIFO)
  1079. EmitInfo* argsList = AnewArray(&m_alloc, EmitInfo, nArgs);
  1080. for (int i = int(nArgs) - 1; i >= 0; --i)
  1081. {
  1082. EmitInfo info = PopEvalStack(calleeSignature->GetParam((Js::ArgSlot)i), _u("Call argument does not match formal type"));
  1083. // We can release the location of the arguments now, because we won't create new temps between start/call
  1084. argsList[i] = info;
  1085. }
  1086. // Skip the this pointer (aka undefined)
  1087. uint32 argLoc = 1;
  1088. for (Js::ArgSlot i = 0; i < nArgs; ++i)
  1089. {
  1090. EmitInfo info = argsList[i];
  1091. Js::OpCodeAsmJs argOp = Js::OpCodeAsmJs::Nop;
  1092. switch (info.type)
  1093. {
  1094. case WasmTypes::F32:
  1095. argOp = isImportCall ? Js::OpCodeAsmJs::ArgOut_Flt : Js::OpCodeAsmJs::I_ArgOut_Flt;
  1096. break;
  1097. case WasmTypes::F64:
  1098. argOp = isImportCall ? Js::OpCodeAsmJs::ArgOut_Db : Js::OpCodeAsmJs::I_ArgOut_Db;
  1099. break;
  1100. case WasmTypes::I32:
  1101. argOp = isImportCall ? Js::OpCodeAsmJs::ArgOut_Int : Js::OpCodeAsmJs::I_ArgOut_Int;
  1102. break;
  1103. case WasmTypes::I64:
  1104. argOp = isImportCall ? Js::OpCodeAsmJs::ArgOut_Long : Js::OpCodeAsmJs::I_ArgOut_Long;
  1105. break;
  1106. #ifdef ENABLE_WASM_SIMD
  1107. case WasmTypes::V128:
  1108. Simd::EnsureSimdIsEnabled();
  1109. argOp = isImportCall ? Js::OpCodeAsmJs::Simd128_ArgOut_F4 : Js::OpCodeAsmJs::Simd128_I_ArgOut_F4;
  1110. break;
  1111. #endif
  1112. case WasmTypes::Any:
  1113. // In unreachable mode allow any type as argument since we won't actually emit the call
  1114. Assert(IsUnreachable());
  1115. if (IsUnreachable())
  1116. {
  1117. argOp = Js::OpCodeAsmJs::ArgOut_Int;
  1118. break;
  1119. }
  1120. // Fall through
  1121. default:
  1122. WasmTypes::CompileAssertCasesNoFailFast<WasmTypes::I32, WasmTypes::I64, WasmTypes::F32, WasmTypes::F64, WASM_V128_CHECK_TYPE>();
  1123. throw WasmCompilationException(_u("Unknown argument type %u"), info.type);
  1124. }
  1125. m_writer->AsmReg2(argOp, argLoc, info.location);
  1126. // Calculated next argument Js::Var location
  1127. if (isImportCall)
  1128. {
  1129. ++argLoc;
  1130. }
  1131. else
  1132. {
  1133. const Js::ArgSlot currentArgSize = calleeSignature->GetParamSize(i);
  1134. Assert(Math::IsAligned<Js::ArgSlot>(currentArgSize, sizeof(Js::Var)));
  1135. argLoc += currentArgSize / sizeof(Js::Var);
  1136. }
  1137. }
  1138. Js::RegSlot funcReg = GetRegisterSpace(WasmTypes::Ptr)->AcquireTmpRegister();
  1139. // emit call
  1140. switch (wasmOp)
  1141. {
  1142. case wbCall:
  1143. {
  1144. uint32 offset = isImportCall ? m_module->GetImportFuncOffset() : m_module->GetFuncOffset();
  1145. uint32 index = UInt32Math::Add(offset, funcNum);
  1146. m_writer->AsmSlot(Js::OpCodeAsmJs::LdSlot, funcReg, Js::AsmJsFunctionMemory::ModuleEnvRegister, index);
  1147. break;
  1148. }
  1149. case wbCallIndirect:
  1150. {
  1151. Js::RegSlot slotReg = GetRegisterSpace(WasmTypes::Ptr)->AcquireTmpRegister();
  1152. m_writer->AsmSlot(Js::OpCodeAsmJs::LdSlotArr, slotReg, Js::AsmJsFunctionMemory::ModuleEnvRegister, m_module->GetTableEnvironmentOffset());
  1153. m_writer->AsmSlot(Js::OpCodeAsmJs::LdArr_WasmFunc, funcReg, slotReg, indirectIndexInfo.location);
  1154. GetRegisterSpace(WasmTypes::Ptr)->ReleaseTmpRegister(slotReg);
  1155. m_writer->AsmReg1IntConst1(Js::OpCodeAsmJs::CheckSignature, funcReg, calleeSignature->GetSignatureId());
  1156. break;
  1157. }
  1158. default:
  1159. Assume(UNREACHED);
  1160. }
  1161. // calculate number of RegSlots(Js::Var) the call consumes
  1162. PolymorphicEmitInfo retInfo;
  1163. retInfo.Init(calleeSignature->GetResultCount(), &m_alloc);
  1164. for (uint32 i = 0; i < calleeSignature->GetResultCount(); ++i)
  1165. {
  1166. retInfo.SetInfo(EmitInfo(calleeSignature->GetResult(i)), i);
  1167. }
  1168. Js::ArgSlot args;
  1169. if (isImportCall)
  1170. {
  1171. args = calleeSignature->GetParamCount();
  1172. ArgSlotMath::Inc(args, argOverflow);
  1173. Js::RegSlot varRetReg = GetRegisterSpace(WasmTypes::Ptr)->AcquireTmpRegister();
  1174. AssertOrFailFastMsg(calleeSignature->GetResultCount() <= 1, "Multiple results from function imports not supported");
  1175. WasmTypes::WasmType singleResType = calleeSignature->GetResultCount() > 0 ? calleeSignature->GetResult(0) : WasmTypes::Void;
  1176. m_writer->AsmCall(Js::OpCodeAsmJs::Call, varRetReg, funcReg, args, WasmToAsmJs::GetAsmJsReturnType(singleResType), profileId);
  1177. GetRegisterSpace(WasmTypes::Ptr)->ReleaseTmpRegister(varRetReg);
  1178. GetRegisterSpace(WasmTypes::Ptr)->ReleaseTmpRegister(funcReg);
  1179. ReleaseLocation(&indirectIndexInfo);
  1180. //registers need to be released from higher ordinals to lower
  1181. for (uint32 i = nArgs; i > 0; --i)
  1182. {
  1183. ReleaseLocation(&(argsList[i - 1]));
  1184. }
  1185. // emit result coercion
  1186. if (calleeSignature->GetResultCount() > 0)
  1187. {
  1188. Js::OpCodeAsmJs convertOp = Js::OpCodeAsmJs::Nop;
  1189. switch (singleResType)
  1190. {
  1191. case WasmTypes::F32:
  1192. convertOp = Js::OpCodeAsmJs::Conv_VTF;
  1193. break;
  1194. case WasmTypes::F64:
  1195. convertOp = Js::OpCodeAsmJs::Conv_VTD;
  1196. break;
  1197. case WasmTypes::I32:
  1198. convertOp = Js::OpCodeAsmJs::Conv_VTI;
  1199. break;
  1200. case WasmTypes::I64:
  1201. convertOp = Js::OpCodeAsmJs::Conv_VTL;
  1202. break;
  1203. #ifdef ENABLE_WASM_SIMD
  1204. case WasmTypes::V128:
  1205. throw WasmCompilationException(_u("Return type: v128 not supported in import calls"));
  1206. #endif
  1207. default:
  1208. WasmTypes::CompileAssertCasesNoFailFast<WasmTypes::I32, WasmTypes::I64, WasmTypes::F32, WasmTypes::F64, WASM_V128_CHECK_TYPE>();
  1209. throw WasmCompilationException(_u("Unknown call return type %u"), singleResType);
  1210. }
  1211. Js::RegSlot location = GetRegisterSpace(singleResType)->AcquireTmpRegister();
  1212. retInfo.SetInfo(EmitInfo(location, singleResType), 0);
  1213. m_writer->AsmReg2(convertOp, location, varRetReg);
  1214. }
  1215. }
  1216. else
  1217. {
  1218. GetRegisterSpace(WasmTypes::Ptr)->ReleaseTmpRegister(funcReg);
  1219. ReleaseLocation(&indirectIndexInfo);
  1220. //registers need to be released from higher ordinals to lower
  1221. for (uint32 i = nArgs; i > 0; --i)
  1222. {
  1223. ReleaseLocation(&(argsList[i - 1]));
  1224. }
  1225. for (uint32 i = 0; i < calleeSignature->GetResultCount(); ++i)
  1226. {
  1227. EmitInfo info(calleeSignature->GetResult(i));
  1228. info.location = GetRegisterSpace(info.type)->AcquireTmpRegister();
  1229. retInfo.SetInfo(info, i);
  1230. }
  1231. EmitInfo singleResultInfo = retInfo.Count() > 0 ? retInfo.GetInfo(0) : EmitInfo(WasmTypes::Void);
  1232. args = (Js::ArgSlot)(::ceil((double)(argSize / sizeof(Js::Var))));
  1233. // todo:: add bytecode to call and set aside multi results
  1234. m_writer->AsmCall(Js::OpCodeAsmJs::I_Call, singleResultInfo.location, funcReg, args, WasmToAsmJs::GetAsmJsReturnType(singleResultInfo.type), profileId);
  1235. }
  1236. AdeleteArray(&m_alloc, nArgs, argsList);
  1237. // WebAssemblyArrayBuffer is not detachable, no need to check for detached state here
  1238. // track stack requirements for out params
  1239. // + 1 for return address
  1240. uint32 maxDepthForLevel = args + 1;
  1241. if (maxDepthForLevel > m_maxArgOutDepth)
  1242. {
  1243. m_maxArgOutDepth = maxDepthForLevel;
  1244. }
  1245. return retInfo;
  1246. }
  1247. PolymorphicEmitInfo WasmBytecodeGenerator::EmitIfElseExpr()
  1248. {
  1249. Js::ByteCodeLabel falseLabel = m_writer->DefineLabel();
  1250. Js::ByteCodeLabel endLabel = m_writer->DefineLabel();
  1251. EmitInfo checkExpr = PopEvalStack(WasmTypes::I32, _u("If expression must have type i32"));
  1252. ReleaseLocation(&checkExpr);
  1253. m_writer->AsmBrReg1(Js::OpCodeAsmJs::BrFalse_Int, falseLabel, checkExpr.location);
  1254. BlockInfo* blockInfo = PushLabel(GetReader()->m_currentNode.block, endLabel);
  1255. bool endOnElse = false;
  1256. EmitBlockCommon(blockInfo, &endOnElse);
  1257. EnsureYield(blockInfo);
  1258. m_writer->AsmBr(endLabel);
  1259. m_writer->MarkAsmJsLabel(falseLabel);
  1260. EmitInfo retInfo;
  1261. EmitInfo falseExpr;
  1262. if (endOnElse)
  1263. {
  1264. if (blockInfo->HasYield())
  1265. {
  1266. // Indicate that we need this block to yield a value
  1267. blockInfo->didYield = false;
  1268. }
  1269. EmitBlockCommon(blockInfo);
  1270. EnsureYield(blockInfo);
  1271. }
  1272. else if (blockInfo->HasYield())
  1273. {
  1274. throw WasmCompilationException(_u("Expected an else block when 'if' returns a value"));
  1275. }
  1276. m_writer->MarkAsmJsLabel(endLabel);
  1277. return PopLabel(endLabel);
  1278. }
  1279. void WasmBytecodeGenerator::EmitBrTable()
  1280. {
  1281. const uint32 numTargets = GetReader()->m_currentNode.brTable.numTargets;
  1282. const uint32* targetTable = GetReader()->m_currentNode.brTable.targetTable;
  1283. const uint32 defaultEntry = GetReader()->m_currentNode.brTable.defaultTarget;
  1284. // Compile scrutinee
  1285. EmitInfo scrutineeInfo = PopStackPolymorphic(EmitInfo(WasmTypes::I32), _u("br_table expression must be of type i32")).GetInfo(0);
  1286. m_writer->AsmReg2(Js::OpCodeAsmJs::BeginSwitch_Int, scrutineeInfo.location, scrutineeInfo.location);
  1287. PolymorphicEmitInfo yieldValue;
  1288. BlockInfo* defaultBlockInfo = GetBlockInfo(defaultEntry);
  1289. if (defaultBlockInfo->HasYield())
  1290. {
  1291. yieldValue = PopStackPolymorphic(defaultBlockInfo);
  1292. }
  1293. // Compile cases
  1294. for (uint32 i = 0; i < numTargets; i++)
  1295. {
  1296. uint32 target = targetTable[i];
  1297. BlockInfo* blockInfo = GetBlockInfo(target);
  1298. if (!defaultBlockInfo->IsEquivalent(blockInfo))
  1299. {
  1300. throw WasmCompilationException(_u("br_table target %u signature mismatch"));
  1301. }
  1302. YieldToBlock(blockInfo, yieldValue);
  1303. m_writer->AsmBrReg1Const1(Js::OpCodeAsmJs::Case_IntConst, blockInfo->label, scrutineeInfo.location, i);
  1304. }
  1305. YieldToBlock(defaultBlockInfo, yieldValue);
  1306. m_writer->AsmBr(defaultBlockInfo->label, Js::OpCodeAsmJs::EndSwitch_Int);
  1307. ReleaseLocation(&scrutineeInfo);
  1308. ReleaseLocation(&yieldValue);
  1309. SetUnreachableState(true);
  1310. }
  1311. EmitInfo WasmBytecodeGenerator::EmitGrowMemory()
  1312. {
  1313. SetUsesMemory(0);
  1314. EmitInfo info = PopEvalStack(WasmTypes::I32, _u("Invalid type for GrowMemory"));
  1315. m_writer->AsmReg2(Js::OpCodeAsmJs::GrowMemory, info.location, info.location);
  1316. return info;
  1317. }
  1318. EmitInfo WasmBytecodeGenerator::EmitDrop()
  1319. {
  1320. EmitInfo info = PopValuePolymorphic();
  1321. ReleaseLocation(&info);
  1322. return EmitInfo();
  1323. }
  1324. EmitInfo WasmBytecodeGenerator::EmitBinExpr(Js::OpCodeAsmJs op, const WasmTypes::WasmType* signature)
  1325. {
  1326. WasmTypes::WasmType resultType = signature[0];
  1327. WasmTypes::WasmType lhsType = signature[1];
  1328. WasmTypes::WasmType rhsType = signature[2];
  1329. EmitInfo rhs = PopEvalStack(rhsType);
  1330. EmitInfo lhs = PopEvalStack(lhsType);
  1331. ReleaseLocation(&rhs);
  1332. ReleaseLocation(&lhs);
  1333. Js::RegSlot resultReg = GetRegisterSpace(resultType)->AcquireTmpRegister();
  1334. m_writer->AsmReg3(op, resultReg, lhs.location, rhs.location);
  1335. return EmitInfo(resultReg, resultType);
  1336. }
  1337. EmitInfo WasmBytecodeGenerator::EmitUnaryExpr(Js::OpCodeAsmJs op, const WasmTypes::WasmType* signature)
  1338. {
  1339. WasmTypes::WasmType resultType = signature[0];
  1340. WasmTypes::WasmType inputType = signature[1];
  1341. EmitInfo info = PopEvalStack(inputType);
  1342. ReleaseLocation(&info);
  1343. if (resultType == WasmTypes::Void)
  1344. {
  1345. m_writer->AsmReg2(op, 0, info.location);
  1346. return EmitInfo();
  1347. }
  1348. Js::RegSlot resultReg = GetRegisterSpace(resultType)->AcquireTmpRegister();
  1349. m_writer->AsmReg2(op, resultReg, info.location);
  1350. return EmitInfo(resultReg, resultType);
  1351. }
  1352. #ifdef ENABLE_WASM_SIMD
  1353. void WasmBytecodeGenerator::CheckLaneIndex(Js::OpCodeAsmJs op, const uint index)
  1354. {
  1355. uint numLanes;
  1356. switch (op)
  1357. {
  1358. case Js::OpCodeAsmJs::Simd128_ExtractLane_I2:
  1359. case Js::OpCodeAsmJs::Simd128_ReplaceLane_I2:
  1360. case Js::OpCodeAsmJs::Simd128_ExtractLane_D2:
  1361. case Js::OpCodeAsmJs::Simd128_ReplaceLane_D2:
  1362. numLanes = 2;
  1363. break;
  1364. case Js::OpCodeAsmJs::Simd128_ExtractLane_I4:
  1365. case Js::OpCodeAsmJs::Simd128_ReplaceLane_I4:
  1366. case Js::OpCodeAsmJs::Simd128_ExtractLane_F4:
  1367. case Js::OpCodeAsmJs::Simd128_ReplaceLane_F4:
  1368. numLanes = 4;
  1369. break;
  1370. case Js::OpCodeAsmJs::Simd128_ExtractLane_I8:
  1371. case Js::OpCodeAsmJs::Simd128_ExtractLane_U8:
  1372. case Js::OpCodeAsmJs::Simd128_ReplaceLane_I8:
  1373. case Js::OpCodeAsmJs::Simd128_ReplaceLane_U8:
  1374. numLanes = 8;
  1375. break;
  1376. case Js::OpCodeAsmJs::Simd128_ExtractLane_I16:
  1377. case Js::OpCodeAsmJs::Simd128_ExtractLane_U16:
  1378. case Js::OpCodeAsmJs::Simd128_ReplaceLane_I16:
  1379. case Js::OpCodeAsmJs::Simd128_ReplaceLane_U16:
  1380. numLanes = 16;
  1381. break;
  1382. default:
  1383. Assert(UNREACHED);
  1384. numLanes = 0;
  1385. }
  1386. if (index >= numLanes)
  1387. {
  1388. throw WasmCompilationException(_u("index is out of range"));
  1389. }
  1390. }
  1391. EmitInfo WasmBytecodeGenerator::EmitLaneIndex(Js::OpCodeAsmJs op)
  1392. {
  1393. const uint index = GetReader()->m_currentNode.lane.index;
  1394. CheckLaneIndex(op, index);
  1395. WasmConstLitNode dummy;
  1396. dummy.i32 = index;
  1397. return EmitConst(WasmTypes::I32, dummy);
  1398. }
  1399. EmitInfo WasmBytecodeGenerator::EmitReplaceLaneExpr(Js::OpCodeAsmJs op, const WasmTypes::WasmType* signature) {
  1400. const WasmTypes::WasmType resultType = signature[0];
  1401. const WasmTypes::WasmType valueType = signature[1];
  1402. EmitInfo valueArg = PopEvalStack(valueType, _u("lane argument type mismatch"));
  1403. EmitInfo simdArg = PopEvalStack(WasmTypes::V128, _u("simd argument type mismatch"));
  1404. Assert(resultType == WasmTypes::V128);
  1405. EmitInfo indexInfo = EmitLaneIndex(op);
  1406. Js::RegSlot resultReg = GetRegisterSpace(resultType)->AcquireTmpRegister();
  1407. EmitInfo result(resultReg, resultType);
  1408. m_writer->AsmReg4(op, resultReg, simdArg.location, indexInfo.location, valueArg.location);
  1409. ReleaseLocation(&indexInfo);
  1410. ReleaseLocation(&valueArg);
  1411. return result;
  1412. }
  1413. EmitInfo WasmBytecodeGenerator::EmitV128BitSelect()
  1414. {
  1415. EmitInfo mask = PopEvalStack(WasmTypes::V128);
  1416. EmitInfo arg2Info = PopEvalStack(WasmTypes::V128);
  1417. EmitInfo arg1Info = PopEvalStack(WasmTypes::V128);
  1418. ReleaseLocation(&mask);
  1419. ReleaseLocation(&arg2Info);
  1420. ReleaseLocation(&arg1Info);
  1421. Js::RegSlot resultReg = GetRegisterSpace(WasmTypes::V128)->AcquireTmpRegister();
  1422. EmitInfo resultInfo(resultReg, WasmTypes::V128);
  1423. m_writer->AsmReg4(Js::OpCodeAsmJs::Simd128_BitSelect_I4, resultReg, arg1Info.location, arg2Info.location, mask.location);
  1424. return resultInfo;
  1425. }
  1426. EmitInfo WasmBytecodeGenerator::EmitV8X16Shuffle()
  1427. {
  1428. EmitInfo arg2Info = PopEvalStack(WasmTypes::V128);
  1429. EmitInfo arg1Info = PopEvalStack(WasmTypes::V128);
  1430. // FIXME Release arg2Info and arg1Info
  1431. Js::RegSlot resultReg = GetRegisterSpace(WasmTypes::V128)->AcquireTmpRegister();
  1432. EmitInfo resultInfo(resultReg, WasmTypes::V128);
  1433. uint8* indices = GetReader()->m_currentNode.shuffle.indices;
  1434. for (uint i = 0; i < Simd::MAX_LANES; i++)
  1435. {
  1436. if (indices[i] >= Simd::MAX_LANES * 2)
  1437. {
  1438. throw WasmCompilationException(_u("%u-th shuffle lane index is larger than %u"), i, (Simd::MAX_LANES * 2 -1));
  1439. }
  1440. }
  1441. m_writer->AsmShuffle(Js::OpCodeAsmJs::Simd128_Shuffle_V8X16, resultReg, arg1Info.location, arg2Info.location, indices);
  1442. return resultInfo;
  1443. }
  1444. EmitInfo WasmBytecodeGenerator::EmitExtractLaneExpr(Js::OpCodeAsmJs op, const WasmTypes::WasmType* signature)
  1445. {
  1446. WasmTypes::WasmType resultType = signature[0];
  1447. WasmTypes::WasmType simdArgType = signature[1];
  1448. EmitInfo simdArgInfo = PopEvalStack(simdArgType, _u("Argument should be of type V128"));
  1449. Js::RegSlot resultReg = GetRegisterSpace(resultType)->AcquireTmpRegister();
  1450. EmitInfo resultInfo(resultReg, resultType);
  1451. //put index into a register to reuse the existing infra in Interpreter and Compiler
  1452. EmitInfo indexInfo = EmitLaneIndex(op);
  1453. ReleaseLocation(&indexInfo);
  1454. m_writer->AsmReg3(op, resultReg, simdArgInfo.location, indexInfo.location);
  1455. return resultInfo;
  1456. }
  1457. EmitInfo WasmBytecodeGenerator::EmitSimdMemAccess(Js::OpCodeAsmJs op, const WasmTypes::WasmType* signature, Js::ArrayBufferView::ViewType viewType, uint8 dataWidth, bool isStore)
  1458. {
  1459. WasmTypes::WasmType type = signature[0];
  1460. SetUsesMemory(0);
  1461. const uint32 mask = Js::ArrayBufferView::ViewMask[viewType];
  1462. const uint alignment = GetReader()->m_currentNode.mem.alignment;
  1463. const uint offset = GetReader()->m_currentNode.mem.offset;
  1464. if ((mask << 1) & (1 << alignment))
  1465. {
  1466. throw WasmCompilationException(_u("alignment must not be larger than natural"));
  1467. }
  1468. EmitInfo rhsInfo;
  1469. if (isStore)
  1470. {
  1471. rhsInfo = PopEvalStack(type, _u("Invalid type for store op"));
  1472. }
  1473. EmitInfo exprInfo = PopEvalStack(WasmTypes::I32, _u("Index expression must be of type i32"));
  1474. if (isStore)
  1475. {
  1476. m_writer->AsmSimdTypedArr(op, rhsInfo.location, exprInfo.location, dataWidth, viewType, offset);
  1477. ReleaseLocation(&rhsInfo);
  1478. ReleaseLocation(&exprInfo);
  1479. return EmitInfo();
  1480. }
  1481. Js::RegSlot resultReg = GetRegisterSpace(type)->AcquireTmpRegister();
  1482. m_writer->AsmSimdTypedArr(op, resultReg, exprInfo.location, dataWidth, viewType, offset);
  1483. EmitInfo yieldInfo = EmitInfo(resultReg, type);
  1484. ReleaseLocation(&exprInfo);
  1485. return yieldInfo;
  1486. }
  1487. #endif
  1488. template<bool isStore, bool isAtomic>
  1489. EmitInfo WasmBytecodeGenerator::EmitMemAccess(WasmOp wasmOp, const WasmTypes::WasmType* signature, Js::ArrayBufferView::ViewType viewType)
  1490. {
  1491. Assert(!isAtomic || Wasm::Threads::IsEnabled());
  1492. WasmTypes::WasmType type = signature[0];
  1493. SetUsesMemory(0);
  1494. const uint32 naturalAlignment = Js::ArrayBufferView::NaturalAlignment[viewType];
  1495. const uint32 alignment = GetReader()->m_currentNode.mem.alignment;
  1496. const uint32 offset = GetReader()->m_currentNode.mem.offset;
  1497. if (alignment > naturalAlignment)
  1498. {
  1499. throw WasmCompilationException(_u("alignment must not be larger than natural"));
  1500. }
  1501. if (isAtomic && alignment != naturalAlignment)
  1502. {
  1503. throw WasmCompilationException(_u("invalid alignment for atomic RW. Expected %u, got %u"), naturalAlignment, alignment);
  1504. }
  1505. // Stores
  1506. if (isStore)
  1507. {
  1508. EmitInfo rhsInfo = PopEvalStack(type, _u("Invalid type for store op"));
  1509. EmitInfo exprInfo = PopEvalStack(WasmTypes::I32, _u("Index expression must be of type i32"));
  1510. Js::OpCodeAsmJs op = isAtomic ? Js::OpCodeAsmJs::StArrAtomic : Js::OpCodeAsmJs::StArrWasm;
  1511. m_writer->WasmMemAccess(op, rhsInfo.location, exprInfo.location, offset, viewType);
  1512. ReleaseLocation(&rhsInfo);
  1513. ReleaseLocation(&exprInfo);
  1514. return EmitInfo();
  1515. }
  1516. // Loads
  1517. EmitInfo exprInfo = PopEvalStack(WasmTypes::I32, _u("Index expression must be of type i32"));
  1518. ReleaseLocation(&exprInfo);
  1519. Js::RegSlot resultReg = GetRegisterSpace(type)->AcquireTmpRegister();
  1520. Js::OpCodeAsmJs op = isAtomic ? Js::OpCodeAsmJs::LdArrAtomic : Js::OpCodeAsmJs::LdArrWasm;
  1521. m_writer->WasmMemAccess(op, resultReg, exprInfo.location, offset, viewType);
  1522. return EmitInfo(resultReg, type);
  1523. }
  1524. void WasmBytecodeGenerator::EmitReturnExpr(PolymorphicEmitInfo* explicitRetInfo)
  1525. {
  1526. PolymorphicEmitInfo retExprInfo = explicitRetInfo ? *explicitRetInfo : PopStackPolymorphic(m_funcBlock);
  1527. for (uint32 i = 0; i < retExprInfo.Count(); ++i)
  1528. {
  1529. EmitInfo info = retExprInfo.GetInfo(i);
  1530. Js::OpCodeAsmJs retOp = GetReturnOp(info.type);
  1531. m_writer->Conv(retOp, 0, info.location);
  1532. ReleaseLocation(&info);
  1533. }
  1534. m_writer->AsmBr(m_funcInfo->GetExitLabel());
  1535. SetUnreachableState(true);
  1536. }
  1537. EmitInfo WasmBytecodeGenerator::EmitSelect()
  1538. {
  1539. EmitInfo conditionInfo = PopEvalStack(WasmTypes::I32, _u("select condition must have i32 type"));
  1540. EmitInfo falseInfo = PopValuePolymorphic();
  1541. EmitInfo trueInfo = PopEvalStack(falseInfo.type, _u("select operands must both have same type"));
  1542. ReleaseLocation(&conditionInfo);
  1543. ReleaseLocation(&falseInfo);
  1544. ReleaseLocation(&trueInfo);
  1545. if (IsUnreachable())
  1546. {
  1547. if (trueInfo.type == WasmTypes::Any)
  1548. {
  1549. // Report the type of falseInfo for type checking
  1550. return EmitInfo(falseInfo.type);
  1551. }
  1552. // Otherwise report the type of trueInfo for type checking
  1553. return EmitInfo(trueInfo.type);
  1554. }
  1555. WasmTypes::WasmType selectType = trueInfo.type;
  1556. EmitInfo resultInfo = EmitInfo(GetRegisterSpace(selectType)->AcquireTmpRegister(), selectType);
  1557. Js::ByteCodeLabel falseLabel = m_writer->DefineLabel();
  1558. Js::ByteCodeLabel doneLabel = m_writer->DefineLabel();
  1559. Js::OpCodeAsmJs loadOp = GetLoadOp(resultInfo.type);
  1560. // var result;
  1561. // if (!condition) goto:condFalse
  1562. // result = trueRes;
  1563. // goto:done;
  1564. //:condFalse
  1565. // result = falseRes;
  1566. //:done
  1567. m_writer->AsmBrReg1(Js::OpCodeAsmJs::BrFalse_Int, falseLabel, conditionInfo.location);
  1568. m_writer->AsmReg2(loadOp, resultInfo.location, trueInfo.location);
  1569. m_writer->AsmBr(doneLabel);
  1570. m_writer->MarkAsmJsLabel(falseLabel);
  1571. m_writer->AsmReg2(loadOp, resultInfo.location, falseInfo.location);
  1572. m_writer->MarkAsmJsLabel(doneLabel);
  1573. return resultInfo;
  1574. }
  1575. void WasmBytecodeGenerator::EmitBr()
  1576. {
  1577. uint32 depth = GetReader()->m_currentNode.br.depth;
  1578. BlockInfo* blockInfo = GetBlockInfo(depth);
  1579. if (blockInfo->HasYield())
  1580. {
  1581. PolymorphicEmitInfo info = PopStackPolymorphic(blockInfo);
  1582. YieldToBlock(blockInfo, info);
  1583. ReleaseLocation(&info);
  1584. }
  1585. m_writer->AsmBr(blockInfo->label);
  1586. SetUnreachableState(true);
  1587. }
  1588. PolymorphicEmitInfo WasmBytecodeGenerator::EmitBrIf()
  1589. {
  1590. uint32 depth = GetReader()->m_currentNode.br.depth;
  1591. EmitInfo conditionInfo = PopEvalStack(WasmTypes::I32, _u("br_if condition must have i32 type"));
  1592. ReleaseLocation(&conditionInfo);
  1593. PolymorphicEmitInfo info;
  1594. BlockInfo* blockInfo = GetBlockInfo(depth);
  1595. if (blockInfo->HasYield())
  1596. {
  1597. info = PopStackPolymorphic(blockInfo);
  1598. YieldToBlock(blockInfo, info);
  1599. if (info.IsUnreachable())
  1600. {
  1601. Assert(IsUnreachable());
  1602. Assert(info.Count() == blockInfo->yieldInfo.Count());
  1603. // Use the block's yield type to continue type check
  1604. for (uint32 i = 0; i < info.Count(); ++i)
  1605. {
  1606. info.SetInfo(EmitInfo(blockInfo->yieldInfo.GetInfo(i).type), i);
  1607. }
  1608. }
  1609. }
  1610. m_writer->AsmBrReg1(Js::OpCodeAsmJs::BrTrue_Int, blockInfo->label, conditionInfo.location);
  1611. return info;
  1612. }
  1613. Js::OpCodeAsmJs WasmBytecodeGenerator::GetLoadOp(WasmTypes::WasmType wasmType)
  1614. {
  1615. switch (wasmType)
  1616. {
  1617. case WasmTypes::F32:
  1618. return Js::OpCodeAsmJs::Ld_Flt;
  1619. case WasmTypes::F64:
  1620. return Js::OpCodeAsmJs::Ld_Db;
  1621. case WasmTypes::I32:
  1622. return Js::OpCodeAsmJs::Ld_Int;
  1623. case WasmTypes::I64:
  1624. return Js::OpCodeAsmJs::Ld_Long;
  1625. #ifdef ENABLE_WASM_SIMD
  1626. case WasmTypes::V128:
  1627. Simd::EnsureSimdIsEnabled();
  1628. return Js::OpCodeAsmJs::Simd128_Ld_F4;
  1629. #endif
  1630. case WasmTypes::Any:
  1631. // In unreachable mode load the any type like an int since we won't actually emit the load
  1632. Assert(IsUnreachable());
  1633. if (IsUnreachable())
  1634. {
  1635. return Js::OpCodeAsmJs::Ld_Int;
  1636. }
  1637. default:
  1638. WasmTypes::CompileAssertCasesNoFailFast<WasmTypes::I32, WasmTypes::I64, WasmTypes::F32, WasmTypes::F64, WASM_V128_CHECK_TYPE>();
  1639. throw WasmCompilationException(_u("Unknown load operator %u"), wasmType);
  1640. }
  1641. }
  1642. Js::OpCodeAsmJs WasmBytecodeGenerator::GetReturnOp(WasmTypes::WasmType type)
  1643. {
  1644. Js::OpCodeAsmJs retOp = Js::OpCodeAsmJs::Nop;
  1645. switch (type)
  1646. {
  1647. case WasmTypes::F32:
  1648. retOp = Js::OpCodeAsmJs::Return_Flt;
  1649. break;
  1650. case WasmTypes::F64:
  1651. retOp = Js::OpCodeAsmJs::Return_Db;
  1652. break;
  1653. case WasmTypes::I32:
  1654. retOp = Js::OpCodeAsmJs::Return_Int;
  1655. break;
  1656. case WasmTypes::I64:
  1657. retOp = Js::OpCodeAsmJs::Return_Long;
  1658. break;
  1659. #ifdef ENABLE_WASM_SIMD
  1660. case WasmTypes::V128:
  1661. Simd::EnsureSimdIsEnabled();
  1662. retOp = Js::OpCodeAsmJs::Simd128_Return_F4;
  1663. break;
  1664. #endif
  1665. case WasmTypes::Any:
  1666. // In unreachable mode load the any type like an int since we won't actually emit the load
  1667. Assert(IsUnreachable());
  1668. if (IsUnreachable())
  1669. {
  1670. return Js::OpCodeAsmJs::Return_Int;
  1671. }
  1672. default:
  1673. WasmTypes::CompileAssertCasesNoFailFast<WasmTypes::I32, WasmTypes::I64, WasmTypes::F32, WasmTypes::F64, WASM_V128_CHECK_TYPE>();
  1674. throw WasmCompilationException(_u("Unknown return type %u"), type);
  1675. }
  1676. return retOp;
  1677. }
  1678. void WasmBytecodeGenerator::ReleaseLocation(EmitInfo* info)
  1679. {
  1680. if (WasmTypes::IsLocalType(info->type))
  1681. {
  1682. GetRegisterSpace(info->type)->ReleaseLocation(info);
  1683. }
  1684. }
  1685. void WasmBytecodeGenerator::ReleaseLocation(PolymorphicEmitInfo* info)
  1686. {
  1687. for (uint32 i = 0; i < info->Count(); ++i)
  1688. {
  1689. ReleaseLocation(&info->GetInfo(i));
  1690. }
  1691. }
  1692. PolymorphicEmitInfo WasmBytecodeGenerator::EnsureYield(BlockInfo* blockInfo)
  1693. {
  1694. PolymorphicEmitInfo yieldEmitInfo;
  1695. if (blockInfo->HasYield())
  1696. {
  1697. yieldEmitInfo = blockInfo->yieldInfo;
  1698. if (!blockInfo->DidYield())
  1699. {
  1700. // Emit a load to the yield location to make sure we have a dest there
  1701. // Most likely we can't reach this code so the value doesn't matter
  1702. blockInfo->didYield = true;
  1703. for (uint32 i = 0; i < yieldEmitInfo.Count(); ++i)
  1704. {
  1705. EmitLoadConst(yieldEmitInfo.GetInfo(i), GetZeroCnst());
  1706. }
  1707. }
  1708. }
  1709. return yieldEmitInfo;
  1710. }
  1711. PolymorphicEmitInfo WasmBytecodeGenerator::PopLabel(Js::ByteCodeLabel labelValidation)
  1712. {
  1713. Assert(m_blockInfos.Count() > 0);
  1714. BlockInfo* blockInfo = m_blockInfos.Pop();
  1715. UNREFERENCED_PARAMETER(labelValidation);
  1716. Assert(blockInfo->label == labelValidation);
  1717. return EnsureYield(blockInfo);
  1718. }
  1719. BlockInfo* WasmBytecodeGenerator::PushLabel(WasmBlock blockData, Js::ByteCodeLabel label, bool addBlockYieldInfo, bool checkInParams)
  1720. {
  1721. BlockInfo* blockInfo = Anew(&m_alloc, BlockInfo);
  1722. blockInfo->label = label;
  1723. if (addBlockYieldInfo)
  1724. {
  1725. if (blockData.IsSingleResult())
  1726. {
  1727. if (blockData.GetSingleResult() != WasmTypes::Void)
  1728. {
  1729. blockInfo->yieldInfo.Init(EmitInfo(GetRegisterSpace(blockData.GetSingleResult())->AcquireTmpRegister(), blockData.GetSingleResult()));
  1730. }
  1731. }
  1732. else
  1733. {
  1734. uint32 sigId = blockData.GetSignatureId();
  1735. WasmSignature* signature = m_module->GetSignature(sigId);
  1736. Js::ArgSlot paramCount = signature->GetParamCount();
  1737. checkInParams = checkInParams && paramCount > 0;
  1738. PolymorphicEmitInfo inParams;
  1739. if (checkInParams)
  1740. {
  1741. inParams.Init(paramCount, &m_alloc);
  1742. // Pop the params in reverse order
  1743. for (int i = paramCount - 1; i >= 0; --i)
  1744. {
  1745. Js::ArgSlot iArg = (Js::ArgSlot)i;
  1746. EmitInfo param = PopEvalStack(signature->GetParam(iArg));
  1747. ReleaseLocation(&param);
  1748. inParams.SetInfo(param, iArg);
  1749. }
  1750. }
  1751. uint32 resultCount = signature->GetResultCount();
  1752. if (resultCount > 0)
  1753. {
  1754. blockInfo->yieldInfo.Init(resultCount, &m_alloc);
  1755. for (uint32 i = 0; i < resultCount; ++i)
  1756. {
  1757. WasmTypes::WasmType type = signature->GetResult(i);
  1758. blockInfo->yieldInfo.SetInfo(EmitInfo(GetRegisterSpace(type)->AcquireTmpRegister(), type), i);
  1759. }
  1760. }
  1761. if (checkInParams)
  1762. {
  1763. blockInfo->paramInfo.Init(paramCount, &m_alloc);
  1764. // Acquire tmp registers in order
  1765. for (uint32 i = 0; i < paramCount; ++i)
  1766. {
  1767. EmitInfo info = inParams.GetInfo(i);
  1768. EmitInfo newInfo = info;
  1769. newInfo.location = GetRegisterSpace(info.type)->AcquireTmpRegister();
  1770. blockInfo->paramInfo.SetInfo(newInfo, i);
  1771. }
  1772. // Todo:: Instead of moving inparams to new location,
  1773. // Treat inparams as local and bypass ReleaseLocation until we exit the scope
  1774. // Move in params to new location in reverse order
  1775. for (int i = paramCount - 1; i >= 0; --i)
  1776. {
  1777. Js::ArgSlot iArg = (Js::ArgSlot)i;
  1778. EmitInfo info = inParams.GetInfo(iArg);
  1779. EmitInfo newInfo = blockInfo->paramInfo.GetInfo(iArg);
  1780. m_writer->AsmReg2(GetLoadOp(newInfo.type), newInfo.location, info.location);
  1781. }
  1782. }
  1783. }
  1784. }
  1785. m_blockInfos.Push(blockInfo);
  1786. return blockInfo;
  1787. }
  1788. void WasmBytecodeGenerator::YieldToBlock(BlockInfo* blockInfo, PolymorphicEmitInfo polyExpr)
  1789. {
  1790. if (blockInfo->HasYield() && !polyExpr.IsUnreachable())
  1791. {
  1792. PolymorphicEmitInfo polyYieldInfo = blockInfo->yieldInfo;
  1793. if (!polyYieldInfo.IsEquivalent(polyExpr))
  1794. {
  1795. throw WasmCompilationException(_u("Invalid yield type"));
  1796. }
  1797. if (!IsUnreachable())
  1798. {
  1799. blockInfo->didYield = true;
  1800. for (uint32 i = 0; i < polyExpr.Count(); ++i)
  1801. {
  1802. EmitInfo expr = polyExpr.GetInfo(i);
  1803. EmitInfo yieldInfo = polyYieldInfo.GetInfo(i);
  1804. m_writer->AsmReg2(GetReturnOp(expr.type), yieldInfo.location, expr.location);
  1805. }
  1806. }
  1807. }
  1808. }
  1809. BlockInfo* WasmBytecodeGenerator::GetBlockInfo(uint32 relativeDepth) const
  1810. {
  1811. if (relativeDepth >= (uint32)m_blockInfos.Count())
  1812. {
  1813. throw WasmCompilationException(_u("Invalid branch target"));
  1814. }
  1815. return m_blockInfos.Peek(relativeDepth);
  1816. }
  1817. Js::ProfileId
  1818. WasmBytecodeGenerator::GetNextProfileId()
  1819. {
  1820. Js::ProfileId nextProfileId = this->currentProfileId;
  1821. UInt16Math::Inc(this->currentProfileId);
  1822. return nextProfileId;
  1823. }
  1824. WasmRegisterSpace* WasmBytecodeGenerator::GetRegisterSpace(WasmTypes::WasmType type)
  1825. {
  1826. switch (type)
  1827. {
  1828. #if TARGET_32
  1829. case WasmTypes::Ptr:
  1830. #endif
  1831. case WasmTypes::I32: return mTypedRegisterAllocator.GetRegisterSpace(WAsmJs::INT32);
  1832. #if TARGET_64
  1833. case WasmTypes::Ptr:
  1834. #endif
  1835. case WasmTypes::I64: return mTypedRegisterAllocator.GetRegisterSpace(WAsmJs::INT64);
  1836. case WasmTypes::F32: return mTypedRegisterAllocator.GetRegisterSpace(WAsmJs::FLOAT32);
  1837. case WasmTypes::F64: return mTypedRegisterAllocator.GetRegisterSpace(WAsmJs::FLOAT64);
  1838. #ifdef ENABLE_WASM_SIMD
  1839. case WasmTypes::V128:
  1840. Simd::EnsureSimdIsEnabled();
  1841. return mTypedRegisterAllocator.GetRegisterSpace(WAsmJs::SIMD);
  1842. #endif
  1843. default:
  1844. WasmTypes::CompileAssertCasesNoFailFast<WasmTypes::I32, WasmTypes::I64, WasmTypes::F32, WasmTypes::F64, WASM_V128_CHECK_TYPE>();
  1845. throw WasmCompilationException(_u("Unknown type %u"), type);
  1846. }
  1847. }
  1848. PolymorphicEmitInfo WasmBytecodeGenerator::PopStackPolymorphic(PolymorphicEmitInfo expectedTypes, const char16* mismatchMessage /*= nullptr*/)
  1849. {
  1850. PolymorphicEmitInfo info;
  1851. uint32 count = expectedTypes.Count();
  1852. info.Init(count, &m_alloc);
  1853. for (uint32 i = 0; i < count; ++i)
  1854. {
  1855. // Check the stack before popping, it is valid to yield nothing if we are Unreachable
  1856. if (IsUnreachable() && m_evalStack.Peek().type == WasmTypes::Limit)
  1857. {
  1858. info.SetInfo(EmitInfo(WasmTypes::Any), i);
  1859. }
  1860. else
  1861. {
  1862. info.SetInfo(PopEvalStack(expectedTypes.GetInfo(i).type, mismatchMessage), i);
  1863. }
  1864. }
  1865. return info;
  1866. }
  1867. PolymorphicEmitInfo WasmBytecodeGenerator::PopStackPolymorphic(const BlockInfo* blockInfo, const char16* mismatchMessage)
  1868. {
  1869. return PopStackPolymorphic(blockInfo->yieldInfo, mismatchMessage);
  1870. }
  1871. EmitInfo WasmBytecodeGenerator::PopEvalStack(WasmTypes::WasmType expectedType, const char16* mismatchMessage)
  1872. {
  1873. // The scope marker should at least be there
  1874. Assert(!m_evalStack.Empty());
  1875. EmitInfo info = m_evalStack.Pop();
  1876. if (info.type == WasmTypes::Limit)
  1877. {
  1878. throw WasmCompilationException(_u("Reached end of stack"));
  1879. }
  1880. if (expectedType != WasmTypes::Any &&
  1881. info.type != WasmTypes::Any &&
  1882. info.type != expectedType)
  1883. {
  1884. if (!mismatchMessage)
  1885. {
  1886. throw WasmCompilationException(_u("Type mismatch. Expected %s, got %s"), GetTypeName(expectedType), GetTypeName(info.type));
  1887. }
  1888. throw WasmCompilationException(mismatchMessage);
  1889. }
  1890. Assert(info.type != WasmTypes::Any || IsUnreachable());
  1891. return info;
  1892. }
  1893. void WasmBytecodeGenerator::PushEvalStack(PolymorphicEmitInfo info)
  1894. {
  1895. Assert(!m_evalStack.Empty());
  1896. for (uint32 i = 0; i < info.Count(); ++i)
  1897. {
  1898. m_evalStack.Push(info.GetInfo(i));
  1899. }
  1900. }
  1901. void WasmBytecodeGenerator::EnterEvalStackScope(const BlockInfo* blockInfo)
  1902. {
  1903. m_evalStack.Push(EmitInfo(WasmTypes::Limit));
  1904. // Push the in-params of the block upon entering the scope
  1905. for (uint32 i = 0; i < blockInfo->paramInfo.Count(); ++i)
  1906. {
  1907. m_evalStack.Push(blockInfo->paramInfo.GetInfo(i));
  1908. }
  1909. }
  1910. void WasmBytecodeGenerator::ExitEvalStackScope(const BlockInfo* blockInfo)
  1911. {
  1912. Assert(!m_evalStack.Empty());
  1913. EmitInfo info = m_evalStack.Pop();
  1914. // It is possible to have unconsumed Any type left on the stack, simply remove them
  1915. while (info.type == WasmTypes::Any)
  1916. {
  1917. Assert(!m_evalStack.Empty());
  1918. info = m_evalStack.Pop();
  1919. }
  1920. if (info.type != WasmTypes::Limit)
  1921. {
  1922. // Put info back on stack so we can write it to string
  1923. m_evalStack.Push(info);
  1924. char16 buf[512] = { 0 };
  1925. WriteTypeStackToString(buf, 512);
  1926. throw WasmCompilationException(_u("Expected stack to be empty, but has %s"), buf);
  1927. }
  1928. }
  1929. void WasmBytecodeGenerator::SetUnreachableState(bool isUnreachable)
  1930. {
  1931. m_writer = isUnreachable ? m_emptyWriter : m_originalWriter;
  1932. if (isUnreachable)
  1933. {
  1934. // Replace the current stack with the any type
  1935. Assert(!m_evalStack.Empty());
  1936. uint32 popped = 0;
  1937. while (m_evalStack.Top().type != WasmTypes::Limit)
  1938. {
  1939. EmitInfo info = m_evalStack.Pop();
  1940. ReleaseLocation(&info);
  1941. ++popped;
  1942. }
  1943. while (popped-- > 0)
  1944. {
  1945. m_evalStack.Push(EmitInfo(WasmTypes::Any));
  1946. }
  1947. }
  1948. this->isUnreachable = isUnreachable;
  1949. }
  1950. void WasmBytecodeGenerator::SetUsesMemory(uint32 memoryIndex)
  1951. {
  1952. // Only support one memory at this time
  1953. Assert(memoryIndex == 0);
  1954. if (!m_module->HasMemory() && !m_module->HasMemoryImport())
  1955. {
  1956. throw WasmCompilationException(_u("unknown memory"));
  1957. }
  1958. GetFunctionBody()->GetAsmJsFunctionInfo()->SetUsesHeapBuffer(true);
  1959. }
  1960. Wasm::WasmReaderBase* WasmBytecodeGenerator::GetReader() const
  1961. {
  1962. if (m_funcInfo->GetCustomReader())
  1963. {
  1964. return m_funcInfo->GetCustomReader();
  1965. }
  1966. return m_module->GetReader();
  1967. }
  1968. void WasmCompilationException::FormatError(const char16* _msg, va_list arglist)
  1969. {
  1970. char16 buf[2048];
  1971. _vsnwprintf_s(buf, _countof(buf), _TRUNCATE, _msg, arglist);
  1972. errorMsg = SysAllocString(buf);
  1973. }
  1974. WasmCompilationException::WasmCompilationException(const char16* _msg, ...) : errorMsg(nullptr)
  1975. {
  1976. va_list arglist;
  1977. va_start(arglist, _msg);
  1978. FormatError(_msg, arglist);
  1979. }
  1980. WasmCompilationException::WasmCompilationException(const char16* _msg, va_list arglist) : errorMsg(nullptr)
  1981. {
  1982. FormatError(_msg, arglist);
  1983. }
  1984. void PolymorphicEmitInfo::Init(EmitInfo info)
  1985. {
  1986. if (info.type != WasmTypes::Void)
  1987. {
  1988. count = 1;
  1989. singleInfo = info;
  1990. }
  1991. else
  1992. {
  1993. Assert(info.location == Js::Constants::NoRegister);
  1994. count = 0;
  1995. infos = nullptr;
  1996. }
  1997. }
  1998. void PolymorphicEmitInfo::Init(uint32 count, ArenaAllocator* alloc)
  1999. {
  2000. infos = nullptr;
  2001. if (count > 1)
  2002. {
  2003. infos = AnewArray(alloc, EmitInfo, count);
  2004. }
  2005. this->count = count;
  2006. }
  2007. void PolymorphicEmitInfo::SetInfo(EmitInfo info, uint32 index)
  2008. {
  2009. AssertOrFailFast(index < count);
  2010. if (count == 1)
  2011. {
  2012. singleInfo = info;
  2013. }
  2014. else
  2015. {
  2016. infos[index] = info;
  2017. }
  2018. }
  2019. Wasm::EmitInfo PolymorphicEmitInfo::GetInfo(uint32 index) const
  2020. {
  2021. AssertOrFailFast(index < count);
  2022. if (count == 1)
  2023. {
  2024. return singleInfo;
  2025. }
  2026. return infos[index];
  2027. }
  2028. bool PolymorphicEmitInfo::IsUnreachable() const
  2029. {
  2030. if (count == 0)
  2031. {
  2032. return false;
  2033. }
  2034. if (count == 1)
  2035. {
  2036. return singleInfo.type == WasmTypes::Any;
  2037. }
  2038. for (uint32 i = 0; i < count; ++i)
  2039. {
  2040. if (infos[i].type == WasmTypes::Any)
  2041. {
  2042. return true;
  2043. }
  2044. }
  2045. return false;
  2046. }
  2047. bool PolymorphicEmitInfo::IsEquivalent(PolymorphicEmitInfo other) const
  2048. {
  2049. if (Count() != other.Count())
  2050. {
  2051. return false;
  2052. }
  2053. for (uint32 i = 0; i < Count(); ++i)
  2054. {
  2055. if (GetInfo(i).type != other.GetInfo(i).type)
  2056. {
  2057. return false;
  2058. }
  2059. }
  2060. return true;
  2061. }
  2062. } // namespace Wasm
  2063. #endif // ENABLE_WASM