AsmJs.cpp 43 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261
  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. // Portions of this file are copyright 2014 Mozilla Foundation, available under the Apache 2.0 license.
  5. //-------------------------------------------------------------------------------------------------------
  6. //-------------------------------------------------------------------------------------------------------
  7. // Copyright 2014 Mozilla Foundation
  8. //
  9. // Licensed under the Apache License, Version 2.0 (the "License");
  10. // you may not use this file except in compliance with the License.
  11. // You may obtain a copy of the License at
  12. //
  13. // http ://www.apache.org/licenses/LICENSE-2.0
  14. //
  15. // Unless required by applicable law or agreed to in writing, software
  16. // distributed under the License is distributed on an "AS IS" BASIS,
  17. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  18. // See the License for the specific language governing permissions and
  19. // limitations under the License.
  20. //-------------------------------------------------------------------------------------------------------
  21. #include "RuntimeLanguagePch.h"
  22. #ifdef ASMJS_PLAT
  23. #include "ByteCode/Symbol.h"
  24. #include "ByteCode/FuncInfo.h"
  25. #include "ByteCode/ByteCodeWriter.h"
  26. #include "ByteCode/ByteCodeGenerator.h"
  27. namespace Js
  28. {
  29. bool
  30. AsmJSCompiler::CheckIdentifier(AsmJsModuleCompiler &m, ParseNode *usepn, PropertyName name)
  31. {
  32. if (name == m.GetParser()->names()->arguments || name == m.GetParser()->names()->eval)
  33. {
  34. return m.FailName(usepn, _u("'%s' is not an allowed identifier"), name);
  35. }
  36. return true;
  37. }
  38. bool
  39. AsmJSCompiler::CheckModuleLevelName(AsmJsModuleCompiler &m, ParseNode *usepn, PropertyName name)
  40. {
  41. if (!CheckIdentifier(m, usepn, name))
  42. {
  43. return false;
  44. }
  45. if (name == m.GetModuleFunctionName())
  46. {
  47. return m.FailName(usepn, _u("duplicate name '%s' not allowed"), name);
  48. }
  49. //Check for all the duplicates here.
  50. return true;
  51. }
  52. bool
  53. AsmJSCompiler::CheckFunctionHead(AsmJsModuleCompiler &m, ParseNode *fn, bool isGlobal /*= true*/)
  54. {
  55. PnFnc fnc = fn->sxFnc;
  56. if (fnc.HasNonSimpleParameterList())
  57. {
  58. return m.Fail(fn, _u("default & rest args not allowed"));
  59. }
  60. if (fnc.IsStaticMember())
  61. {
  62. return m.Fail(fn, _u("static functions are not allowed"));
  63. }
  64. if (fnc.IsGenerator())
  65. {
  66. return m.Fail(fn, _u("generator functions are not allowed"));
  67. }
  68. if (fnc.IsAsync())
  69. {
  70. return m.Fail(fn, _u("async functions are not allowed"));
  71. }
  72. if (fnc.IsLambda())
  73. {
  74. return m.Fail(fn, _u("lambda functions are not allowed"));
  75. }
  76. if (!isGlobal && fnc.nestedCount != 0)
  77. {
  78. return m.Fail(fn, _u("closure functions are not allowed"));
  79. }
  80. return true;
  81. }
  82. bool AsmJSCompiler::CheckTypeAnnotation( AsmJsModuleCompiler &m, ParseNode *coercionNode, AsmJSCoercion *coercion,
  83. ParseNode **coercedExpr /*= nullptr */)
  84. {
  85. switch( coercionNode->nop )
  86. {
  87. case knopRsh:
  88. case knopLsh:
  89. case knopXor:
  90. case knopAnd:
  91. case knopOr: {
  92. ParseNode *rhs = ParserWrapper::GetBinaryRight( coercionNode );
  93. *coercion = AsmJS_ToInt32;
  94. if( coercedExpr )
  95. {
  96. if( rhs->nop == knopInt && rhs->sxInt.lw == 0 )
  97. {
  98. if( rhs->nop == knopAnd )
  99. {
  100. // X & 0 == 0;
  101. *coercedExpr = rhs;
  102. }
  103. else
  104. {
  105. // (X|0) == (X^0) == (X<<0) == (X>>0) == X
  106. *coercedExpr = ParserWrapper::GetBinaryLeft( coercionNode );
  107. }
  108. }
  109. else
  110. {
  111. *coercedExpr = coercionNode;
  112. }
  113. }
  114. return true;
  115. }
  116. case knopPos: {
  117. *coercion = AsmJS_ToNumber;
  118. if( coercedExpr )
  119. {
  120. *coercedExpr = ParserWrapper::GetUnaryNode( coercionNode );
  121. }
  122. return true;
  123. }
  124. case knopCall: {
  125. ParseNode* target;
  126. AsmJsFunctionDeclaration* sym;
  127. AsmJsSIMDFunction* simdSym;
  128. target = coercionNode->sxCall.pnodeTarget;
  129. if (!target || target->nop != knopName)
  130. {
  131. return m.Fail(coercionNode, _u("Call must be of the form id(...)"));
  132. }
  133. simdSym = m.LookupSimdTypeCheck(target->name());
  134. // var x = f4.check(ffi.field)
  135. if (simdSym)
  136. {
  137. if (coercionNode->sxCall.argCount == simdSym->GetArgCount())
  138. {
  139. switch (simdSym->GetSimdBuiltInFunction())
  140. {
  141. case AsmJsSIMDBuiltin_int32x4_check:
  142. *coercion = AsmJS_Int32x4;
  143. break;
  144. case AsmJsSIMDBuiltin_bool32x4_check:
  145. *coercion = AsmJS_Bool32x4;
  146. break;
  147. case AsmJsSIMDBuiltin_bool16x8_check:
  148. *coercion = AsmJS_Bool16x8;
  149. break;
  150. case AsmJsSIMDBuiltin_bool8x16_check:
  151. *coercion = AsmJS_Bool8x16;
  152. break;
  153. case AsmJsSIMDBuiltin_float32x4_check:
  154. *coercion = AsmJS_Float32x4;
  155. break;
  156. case AsmJsSIMDBuiltin_float64x2_check:
  157. *coercion = AsmJS_Float64x2;
  158. break;
  159. case AsmJsSIMDBuiltin_int16x8_check:
  160. *coercion = AsmJS_Int16x8;
  161. break;
  162. case AsmJsSIMDBuiltin_int8x16_check:
  163. *coercion = AsmJS_Int8x16;
  164. break;
  165. case AsmJsSIMDBuiltin_uint32x4_check:
  166. *coercion = AsmJS_Uint32x4;
  167. break;
  168. case AsmJsSIMDBuiltin_uint16x8_check:
  169. *coercion = AsmJS_Uint16x8;
  170. break;
  171. case AsmJsSIMDBuiltin_uint8x16_check:
  172. *coercion = AsmJS_Uint8x16;
  173. break;
  174. default:
  175. Assert(UNREACHED);
  176. }
  177. if (coercedExpr)
  178. {
  179. *coercedExpr = coercionNode->sxCall.pnodeArgs;
  180. }
  181. return true;
  182. }
  183. else
  184. {
  185. return m.Fail(coercionNode, _u("Invalid SIMD coercion"));
  186. }
  187. }
  188. // not a SIMD coercion, fall through
  189. *coercion = AsmJS_FRound;
  190. sym = m.LookupFunction(target->name());
  191. if (!AsmJsMathFunction::IsFround(sym))
  192. {
  193. return m.Fail( coercionNode, _u("call must be to fround coercion") );
  194. }
  195. if( coercedExpr )
  196. {
  197. *coercedExpr = coercionNode->sxCall.pnodeArgs;
  198. }
  199. return true;
  200. }
  201. case knopInt:{
  202. *coercion = AsmJS_ToInt32;
  203. if( coercedExpr )
  204. {
  205. *coercedExpr = coercionNode;
  206. }
  207. return true;
  208. }
  209. case knopFlt:{
  210. if (ParserWrapper::IsMinInt(coercionNode))
  211. {
  212. *coercion = AsmJS_ToInt32;
  213. }
  214. else if (coercionNode->sxFlt.maybeInt)
  215. {
  216. return m.Fail(coercionNode, _u("Integer literal in return must be in range [-2^31, 2^31)"));
  217. }
  218. else
  219. {
  220. *coercion = AsmJS_ToNumber;
  221. }
  222. if( coercedExpr )
  223. {
  224. *coercedExpr = coercionNode ;
  225. }
  226. return true;
  227. }
  228. case knopName:{
  229. // in this case we are returning a constant var from the global scope
  230. AsmJsSymbol * constSymSource = m.LookupIdentifier(coercionNode->name());
  231. if (!constSymSource)
  232. {
  233. return m.Fail(coercionNode, _u("Identifier not globally declared"));
  234. }
  235. AsmJsVar * constSrc = constSymSource->Cast<AsmJsVar>();
  236. if (constSymSource->GetSymbolType() != AsmJsSymbol::Variable || constSrc->isMutable())
  237. {
  238. return m.Fail(coercionNode, _u("Unannotated variables must be constant"));
  239. }
  240. if (constSrc->GetType().isSigned())
  241. {
  242. *coercion = AsmJS_ToInt32;
  243. }
  244. else if (constSrc->GetType().isDouble())
  245. {
  246. *coercion = AsmJS_ToNumber;
  247. }
  248. else
  249. {
  250. Assert(constSrc->GetType().isFloat());
  251. *coercion = AsmJS_FRound;
  252. }
  253. if (coercedExpr)
  254. {
  255. *coercedExpr = coercionNode;
  256. }
  257. return true;
  258. }
  259. default:;
  260. }
  261. return m.Fail( coercionNode, _u("must be of the form +x, fround(x) or x|0") );
  262. }
  263. bool
  264. AsmJSCompiler::CheckModuleArgument(AsmJsModuleCompiler &m, ParseNode *arg, PropertyName *name, AsmJsModuleArg::ArgType type)
  265. {
  266. if (!ParserWrapper::IsDefinition(arg))
  267. {
  268. return m.Fail(arg, _u("duplicate argument name not allowed"));
  269. }
  270. if (!CheckIdentifier(m, arg, arg->name()))
  271. {
  272. return false;
  273. }
  274. *name = arg->name();
  275. m.GetByteCodeGenerator()->AssignPropertyId(*name);
  276. AsmJsModuleArg * moduleArg = Anew(m.GetAllocator(), AsmJsModuleArg, *name, type);
  277. if (!m.DefineIdentifier(*name, moduleArg))
  278. {
  279. return m.Fail(arg, _u("duplicate argument name not allowed"));
  280. }
  281. if (!CheckModuleLevelName(m, arg, *name))
  282. {
  283. return false;
  284. }
  285. return true;
  286. }
  287. bool
  288. AsmJSCompiler::CheckModuleArguments(AsmJsModuleCompiler &m, ParseNode *fn)
  289. {
  290. ArgSlot numFormals = 0;
  291. ParseNode *arg1 = ParserWrapper::FunctionArgsList( fn, numFormals );
  292. ParseNode *arg2 = arg1 ? ParserWrapper::NextVar( arg1 ) : nullptr;
  293. ParseNode *arg3 = arg2 ? ParserWrapper::NextVar( arg2 ) : nullptr;
  294. if (numFormals > 3)
  295. {
  296. return m.Fail(fn, _u("asm.js modules takes at most 3 argument"));
  297. }
  298. PropertyName arg1Name = nullptr;
  299. if (numFormals >= 1 && !CheckModuleArgument(m, arg1, &arg1Name, AsmJsModuleArg::ArgType::StdLib))
  300. {
  301. return false;
  302. }
  303. m.InitStdLibArgName(arg1Name);
  304. PropertyName arg2Name = nullptr;
  305. if (numFormals >= 2 && !CheckModuleArgument(m, arg2, &arg2Name, AsmJsModuleArg::ArgType::Import))
  306. {
  307. return false;
  308. }
  309. m.InitForeignArgName(arg2Name);
  310. PropertyName arg3Name = nullptr;
  311. if (numFormals >= 3 && !CheckModuleArgument(m, arg3, &arg3Name, AsmJsModuleArg::ArgType::Heap))
  312. {
  313. return false;
  314. }
  315. m.InitBufferArgName(arg3Name);
  316. return true;
  317. }
  318. bool AsmJSCompiler::CheckGlobalVariableImportExpr( AsmJsModuleCompiler &m, PropertyName varName, AsmJSCoercion coercion, ParseNode *coercedExpr )
  319. {
  320. if( !ParserWrapper::IsDotMember(coercedExpr) )
  321. {
  322. return m.FailName( coercedExpr, _u("invalid import expression for global '%s'"), varName );
  323. }
  324. ParseNode *base = ParserWrapper::DotBase(coercedExpr);
  325. PropertyName field = ParserWrapper::DotMember(coercedExpr);
  326. PropertyName importName = m.GetForeignArgName();
  327. if (!importName || !field)
  328. {
  329. return m.Fail(coercedExpr, _u("cannot import without an asm.js foreign parameter"));
  330. }
  331. m.GetByteCodeGenerator()->AssignPropertyId(field);
  332. if ((base->name() != importName))
  333. {
  334. return m.FailName(coercedExpr, _u("base of import expression must be '%s'"), importName);
  335. }
  336. return m.AddGlobalVarImport(varName, field, coercion);
  337. }
  338. bool AsmJSCompiler::CheckGlobalVariableInitImport( AsmJsModuleCompiler &m, PropertyName varName, ParseNode *initNode, bool isMutable /*= true*/)
  339. {
  340. AsmJSCoercion coercion;
  341. ParseNode *coercedExpr = nullptr;
  342. if( !CheckTypeAnnotation( m, initNode, &coercion, &coercedExpr ) )
  343. {
  344. return false;
  345. }
  346. if ((ParserWrapper::IsFroundNumericLiteral(coercedExpr)) && coercion == AsmJSCoercion::AsmJS_FRound)
  347. {
  348. return m.AddNumericVar(varName, coercedExpr, true, isMutable);
  349. }
  350. return CheckGlobalVariableImportExpr( m, varName, coercion, coercedExpr );
  351. }
  352. bool AsmJSCompiler::CheckNewArrayView( AsmJsModuleCompiler &m, PropertyName varName, ParseNode *newExpr )
  353. {
  354. Assert( newExpr->nop == knopNew );
  355. ParseNode *ctorExpr = newExpr->sxCall.pnodeTarget;
  356. ArrayBufferView::ViewType type;
  357. if( ParserWrapper::IsDotMember(ctorExpr) )
  358. {
  359. ParseNode *base = ParserWrapper::DotBase(ctorExpr);
  360. PropertyName globalName = m.GetStdLibArgName();
  361. if (!globalName)
  362. {
  363. return m.Fail(base, _u("cannot create array view without an asm.js global parameter"));
  364. }
  365. if (!ParserWrapper::IsNameDeclaration(base) || base->name() != globalName)
  366. {
  367. return m.FailName(base, _u("expecting '%s.*Array"), globalName);
  368. }
  369. PropertyName fieldName = ParserWrapper::DotMember(ctorExpr);
  370. if (!fieldName)
  371. {
  372. return m.FailName(ctorExpr, _u("Failed to define array view to var %s"), varName);
  373. }
  374. PropertyId field = fieldName->GetPropertyId();
  375. switch (field)
  376. {
  377. case PropertyIds::Int8Array:
  378. type = ArrayBufferView::TYPE_INT8;
  379. m.AddArrayBuiltinUse(AsmJSTypedArrayBuiltin_Int8Array);
  380. break;
  381. case PropertyIds::Uint8Array:
  382. type = ArrayBufferView::TYPE_UINT8;
  383. m.AddArrayBuiltinUse(AsmJSTypedArrayBuiltin_Uint8Array);
  384. break;
  385. case PropertyIds::Int16Array:
  386. type = ArrayBufferView::TYPE_INT16;
  387. m.AddArrayBuiltinUse(AsmJSTypedArrayBuiltin_Int16Array);
  388. break;
  389. case PropertyIds::Uint16Array:
  390. type = ArrayBufferView::TYPE_UINT16;
  391. m.AddArrayBuiltinUse(AsmJSTypedArrayBuiltin_Uint16Array);
  392. break;
  393. case PropertyIds::Int32Array:
  394. type = ArrayBufferView::TYPE_INT32;
  395. m.AddArrayBuiltinUse(AsmJSTypedArrayBuiltin_Int32Array);
  396. break;
  397. case PropertyIds::Uint32Array:
  398. type = ArrayBufferView::TYPE_UINT32;
  399. m.AddArrayBuiltinUse(AsmJSTypedArrayBuiltin_Uint32Array);
  400. break;
  401. case PropertyIds::Float32Array:
  402. type = ArrayBufferView::TYPE_FLOAT32;
  403. m.AddArrayBuiltinUse(AsmJSTypedArrayBuiltin_Float32Array);
  404. break;
  405. case PropertyIds::Float64Array:
  406. type = ArrayBufferView::TYPE_FLOAT64;
  407. m.AddArrayBuiltinUse(AsmJSTypedArrayBuiltin_Float64Array);
  408. break;
  409. default:
  410. return m.Fail(ctorExpr, _u("could not match typed array name"));
  411. break;
  412. }
  413. }
  414. else if (ctorExpr->nop == knopName)
  415. {
  416. AsmJsSymbol * buffFunc = m.LookupIdentifier(ctorExpr->name());
  417. if (!buffFunc || buffFunc->GetSymbolType() != AsmJsSymbol::TypedArrayBuiltinFunction)
  418. {
  419. return m.Fail(ctorExpr, _u("invalid 'new' import"));
  420. }
  421. type = buffFunc->Cast<AsmJsTypedArrayFunction>()->GetViewType();
  422. if (type == ArrayBufferView::TYPE_COUNT)
  423. {
  424. return m.Fail(ctorExpr, _u("could not match typed array name"));
  425. }
  426. }
  427. else
  428. {
  429. return m.Fail(newExpr, _u("invalid 'new' import"));
  430. }
  431. ParseNode *bufArg = newExpr->sxCall.pnodeArgs;
  432. if( !bufArg || !ParserWrapper::IsNameDeclaration( bufArg ) )
  433. {
  434. return m.Fail( ctorExpr, _u("array view constructor takes exactly one argument") );
  435. }
  436. PropertyName bufferName = m.GetBufferArgName();
  437. if( !bufferName )
  438. {
  439. return m.Fail( bufArg, _u("cannot create array view without an asm.js heap parameter") );
  440. }
  441. if( bufferName != bufArg->name() )
  442. {
  443. return m.FailName( bufArg, _u("argument to array view constructor must be '%s'"), bufferName );
  444. }
  445. if( !m.AddArrayView( varName, type ) )
  446. {
  447. return m.FailName( ctorExpr, _u("Failed to define array view to var %s"), varName );
  448. }
  449. return true;
  450. }
  451. bool
  452. AsmJSCompiler::CheckGlobalDotImport(AsmJsModuleCompiler &m, PropertyName varName, ParseNode *initNode)
  453. {
  454. ParseNode *base = ParserWrapper::DotBase(initNode);
  455. PropertyName field = ParserWrapper::DotMember(initNode);
  456. if( !field )
  457. {
  458. return m.Fail( initNode, _u("Global import must be in the form c.x where c is stdlib or foreign and x is a string literal") );
  459. }
  460. m.GetByteCodeGenerator()->AssignPropertyId(field);
  461. PropertyName lib = nullptr;
  462. if (ParserWrapper::IsDotMember(base))
  463. {
  464. lib = ParserWrapper::DotMember(base);
  465. base = ParserWrapper::DotBase(base);
  466. #ifdef ENABLE_SIMDJS
  467. if (m.GetScriptContext()->GetConfig()->IsSimdjsEnabled())
  468. {
  469. if (!lib || (lib->GetPropertyId() != PropertyIds::Math && lib->GetPropertyId() != PropertyIds::SIMD))
  470. {
  471. return m.FailName(initNode, _u("'%s' should be Math or SIMD, as in global.Math.xxxx"), field);
  472. }
  473. }
  474. else
  475. #endif
  476. {
  477. if (!lib || lib->GetPropertyId() != PropertyIds::Math)
  478. {
  479. return m.FailName(initNode, _u("'%s' should be Math, as in global.Math.xxxx"), field);
  480. }
  481. }
  482. }
  483. if( ParserWrapper::IsNameDeclaration(base) && base->name() == m.GetStdLibArgName() )
  484. {
  485. #ifdef ENABLE_SIMDJS
  486. if (m.GetScriptContext()->GetConfig()->IsSimdjsEnabled())
  487. {
  488. if (lib && lib->GetPropertyId() == PropertyIds::SIMD)
  489. {
  490. // global.SIMD.xxx
  491. AsmJsSIMDFunction *simdFunc = nullptr;
  492. if (!m.LookupStdLibSIMDName(field->GetPropertyId(), field, &simdFunc))
  493. {
  494. return m.FailName(initNode, _u("'%s' is not standard SIMD builtin"), varName);
  495. }
  496. if (simdFunc->GetName() != nullptr)
  497. {
  498. OutputMessage(m.GetScriptContext(), DEIT_ASMJS_FAILED, _u("Warning: SIMD Builtin already defined for var %s"), simdFunc->GetName()->Psz());
  499. }
  500. simdFunc->SetName(varName);
  501. if (!m.DefineIdentifier(varName, simdFunc))
  502. {
  503. return m.FailName(initNode, _u("Failed to define SIMD builtin function to var %s"), varName);
  504. }
  505. m.AddSimdBuiltinUse(simdFunc->GetSimdBuiltInFunction());
  506. return true;
  507. }
  508. }
  509. #endif
  510. // global.Math.xxx
  511. MathBuiltin mathBuiltin;
  512. if (m.LookupStandardLibraryMathName(field, &mathBuiltin))
  513. {
  514. switch (mathBuiltin.kind)
  515. {
  516. case MathBuiltin::Function:{
  517. auto func = mathBuiltin.u.func;
  518. if (func->GetName() != nullptr)
  519. {
  520. OutputMessage(m.GetScriptContext(), DEIT_ASMJS_FAILED, _u("Warning: Math Builtin already defined for var %s"), func->GetName()->Psz());
  521. }
  522. func->SetName(varName);
  523. if (!m.DefineIdentifier(varName, func))
  524. {
  525. return m.FailName(initNode, _u("Failed to define math builtin function to var %s"), varName);
  526. }
  527. m.AddMathBuiltinUse(func->GetMathBuiltInFunction());
  528. }
  529. break;
  530. case MathBuiltin::Constant:
  531. if (!m.AddNumericConst(varName, mathBuiltin.u.cst))
  532. {
  533. return m.FailName(initNode, _u("Failed to define math constant to var %s"), varName);
  534. }
  535. m.AddMathBuiltinUse(mathBuiltin.mathLibFunctionName);
  536. break;
  537. default:
  538. Assume(UNREACHED);
  539. }
  540. return true;
  541. }
  542. TypedArrayBuiltin arrayBuiltin;
  543. if (m.LookupStandardLibraryArrayName(field, &arrayBuiltin))
  544. {
  545. if (arrayBuiltin.mFunc->GetName() != nullptr)
  546. {
  547. OutputMessage(m.GetScriptContext(), DEIT_ASMJS_FAILED, _u("Warning: Typed array builtin already defined for var %s"), arrayBuiltin.mFunc->GetName()->Psz());
  548. }
  549. arrayBuiltin.mFunc->SetName(varName);
  550. if (!m.DefineIdentifier(varName, arrayBuiltin.mFunc))
  551. {
  552. return m.FailName(initNode, _u("Failed to define typed array builtin function to var %s"), varName);
  553. }
  554. m.AddArrayBuiltinUse(arrayBuiltin.mFunc->GetArrayBuiltInFunction());
  555. return true;
  556. }
  557. return m.FailName(initNode, _u("'%s' is not a standard Math builtin"), field);
  558. }
  559. else if( ParserWrapper::IsNameDeclaration(base) && base->name() == m.GetForeignArgName() )
  560. {
  561. // foreign import
  562. return m.AddModuleFunctionImport( varName, field );
  563. }
  564. else if (ParserWrapper::IsNameDeclaration(base))
  565. {
  566. // Check if SIMD function import
  567. // e.g. var x = f4.add
  568. AsmJsSIMDFunction *simdFunc, *operation;
  569. simdFunc = m.LookupSimdConstructor(base->name());
  570. if (simdFunc == nullptr || !m.LookupStdLibSIMDName(simdFunc->GetSimdBuiltInFunction(), field, &operation))
  571. {
  572. return m.FailName(initNode, _u("Invalid dot expression import. %s is not a standard SIMD operation"), varName);
  573. }
  574. if (operation->GetName() != nullptr)
  575. {
  576. OutputMessage(m.GetScriptContext(), DEIT_ASMJS_FAILED, _u("Warning: SIMD Builtin already defined for var %s"), operation->GetName()->Psz());
  577. }
  578. // bind operation to var
  579. operation->SetName(varName);
  580. if (!m.DefineIdentifier(varName, operation))
  581. {
  582. return m.FailName(initNode, _u("Failed to define SIMD builtin function to var %s"), varName);
  583. }
  584. m.AddSimdBuiltinUse(operation->GetSimdBuiltInFunction());
  585. return true;
  586. }
  587. return m.Fail(initNode, _u("expecting c.y where c is either the global or foreign parameter"));
  588. }
  589. bool
  590. AsmJSCompiler::CheckModuleGlobal(AsmJsModuleCompiler &m, ParseNode *var)
  591. {
  592. Assert(var->nop == knopVarDecl || var->nop == knopConstDecl);
  593. bool isMutable = var->nop != knopConstDecl;
  594. PropertyName name = var->name();
  595. m.GetByteCodeGenerator()->AssignPropertyId(name);
  596. if (m.LookupIdentifier(name))
  597. {
  598. return m.FailName(var, _u("import variable %s names must be unique"), name);
  599. }
  600. if (!CheckModuleLevelName(m, var, name))
  601. {
  602. return false;
  603. }
  604. if (!var->sxVar.pnodeInit)
  605. {
  606. return m.Fail(var, _u("module import needs initializer"));
  607. }
  608. ParseNode *initNode = var->sxVar.pnodeInit;
  609. if( ParserWrapper::IsNumericLiteral( initNode ) )
  610. {
  611. if (m.AddNumericVar(name, initNode, false, isMutable))
  612. {
  613. return true;
  614. }
  615. else
  616. {
  617. return m.FailName(var, _u("Failed to declare numeric var %s"), name);
  618. }
  619. }
  620. if (initNode->nop == knopOr || initNode->nop == knopPos || initNode->nop == knopCall)
  621. {
  622. // SIMD_JS
  623. // e.g. var x = f4(1.0, 2.0, 3.0, 4.0)
  624. if (initNode->nop == knopCall)
  625. {
  626. AsmJsSIMDFunction* simdSym;
  627. // also checks if simd constructor
  628. simdSym = m.LookupSimdConstructor(initNode->sxCall.pnodeTarget->name());
  629. // call to simd constructor
  630. if (simdSym)
  631. {
  632. // validate args and define a SIMD symbol
  633. return m.AddSimdValueVar(name, initNode, simdSym);
  634. }
  635. // else it is FFI import: var x = f4check(FFI.field), handled in CheckGlobalVariableInitImport
  636. }
  637. return CheckGlobalVariableInitImport(m, name, initNode, isMutable );
  638. }
  639. if( initNode->nop == knopNew )
  640. {
  641. return CheckNewArrayView(m, var->name(), initNode);
  642. }
  643. if (ParserWrapper::IsDotMember(initNode))
  644. {
  645. return CheckGlobalDotImport(m, name, initNode);
  646. }
  647. return m.Fail( initNode, _u("Failed to recognize global variable") );
  648. }
  649. bool
  650. AsmJSCompiler::CheckModuleGlobals(AsmJsModuleCompiler &m)
  651. {
  652. ParseNode *varStmts;
  653. if( !ParserWrapper::ParseVarOrConstStatement( m.GetCurrentParserNode(), &varStmts ) )
  654. {
  655. return false;
  656. }
  657. if (!varStmts)
  658. {
  659. return true;
  660. }
  661. while (varStmts->nop == knopList)
  662. {
  663. ParseNode * pnode = ParserWrapper::GetBinaryLeft(varStmts);
  664. while (pnode && pnode->nop != knopEndCode)
  665. {
  666. ParseNode * decl;
  667. if (pnode->nop == knopList)
  668. {
  669. decl = ParserWrapper::GetBinaryLeft(pnode);
  670. pnode = ParserWrapper::GetBinaryRight(pnode);
  671. }
  672. else
  673. {
  674. decl = pnode;
  675. pnode = nullptr;
  676. }
  677. if (decl->nop == knopFncDecl)
  678. {
  679. goto varDeclEnd;
  680. }
  681. else if (decl->nop != knopConstDecl && decl->nop != knopVarDecl)
  682. {
  683. break;
  684. }
  685. if (decl->sxVar.pnodeInit && decl->sxVar.pnodeInit->nop == knopArray)
  686. {
  687. // Assume we reached func tables
  688. goto varDeclEnd;
  689. }
  690. if (!CheckModuleGlobal(m, decl))
  691. {
  692. return false;
  693. }
  694. }
  695. if (ParserWrapper::GetBinaryRight(varStmts)->nop == knopEndCode)
  696. {
  697. // this is an error condition, but CheckFunctionsSequential will figure it out
  698. goto varDeclEnd;
  699. }
  700. varStmts = ParserWrapper::GetBinaryRight(varStmts);
  701. }
  702. varDeclEnd:
  703. // we will collect information on the function tables now and come back to the functions themselves afterwards,
  704. // because function table information is used when processing function bodies
  705. ParseNode * fnNodes = varStmts;
  706. while (fnNodes->nop != knopEndCode && ParserWrapper::GetBinaryLeft(fnNodes)->nop == knopFncDecl)
  707. {
  708. fnNodes = ParserWrapper::GetBinaryRight(fnNodes);
  709. }
  710. if (fnNodes->nop == knopEndCode)
  711. {
  712. // if there are no function tables, we can just initialize count to 0
  713. m.SetFuncPtrTableCount(0);
  714. }
  715. else
  716. {
  717. m.SetCurrentParseNode(fnNodes);
  718. if (!CheckFunctionTables(m))
  719. {
  720. return false;
  721. }
  722. }
  723. // this will move us back to the beginning of the function declarations
  724. m.SetCurrentParseNode(varStmts);
  725. return true;
  726. }
  727. bool AsmJSCompiler::CheckFunction( AsmJsModuleCompiler &m, ParseNode* fncNode )
  728. {
  729. Assert( fncNode->nop == knopFncDecl );
  730. if( PHASE_TRACE1( Js::ByteCodePhase ) )
  731. {
  732. Output::Print( _u(" Checking Asm function: %s\n"), fncNode->sxFnc.funcInfo->name);
  733. }
  734. if( !CheckFunctionHead( m, fncNode, false ) )
  735. {
  736. return false;
  737. }
  738. AsmJsFunc* func = m.CreateNewFunctionEntry(fncNode);
  739. if (!func)
  740. {
  741. return m.Fail(fncNode, _u(" Error creating function entry"));
  742. }
  743. return true;
  744. }
  745. bool AsmJSCompiler::CheckFunctionsSequential( AsmJsModuleCompiler &m )
  746. {
  747. AsmJSParser& list = m.GetCurrentParserNode();
  748. Assert( list->nop == knopList );
  749. ParseNode* pnode = ParserWrapper::GetBinaryLeft(list);
  750. while (pnode->nop == knopFncDecl)
  751. {
  752. if( !CheckFunction( m, pnode ) )
  753. {
  754. return false;
  755. }
  756. if(ParserWrapper::GetBinaryRight(list)->nop == knopEndCode)
  757. {
  758. break;
  759. }
  760. list = ParserWrapper::GetBinaryRight(list);
  761. pnode = ParserWrapper::GetBinaryLeft(list);
  762. }
  763. m.SetCurrentParseNode( list );
  764. return true;
  765. }
  766. bool AsmJSCompiler::CheckFunctionTables(AsmJsModuleCompiler &m)
  767. {
  768. AsmJSParser& list = m.GetCurrentParserNode();
  769. Assert(list->nop == knopList);
  770. int32 funcPtrTableCount = 0;
  771. while (list->nop != knopEndCode)
  772. {
  773. ParseNode * varStmt = ParserWrapper::GetBinaryLeft(list);
  774. if (varStmt->nop != knopConstDecl && varStmt->nop != knopVarDecl)
  775. {
  776. break;
  777. }
  778. if (!varStmt->sxVar.pnodeInit || varStmt->sxVar.pnodeInit->nop != knopArray)
  779. {
  780. break;
  781. }
  782. const uint tableSize = varStmt->sxVar.pnodeInit->sxArrLit.count;
  783. if (!::Math::IsPow2(tableSize))
  784. {
  785. return m.FailName(varStmt, _u("Function table [%s] size must be a power of 2"), varStmt->name());
  786. }
  787. if (!m.AddFunctionTable(varStmt->name(), tableSize))
  788. {
  789. return m.FailName(varStmt, _u("Unable to create new function table %s"), varStmt->name());
  790. }
  791. AsmJsFunctionTable* ftable = (AsmJsFunctionTable*)m.LookupIdentifier(varStmt->name());
  792. Assert(ftable);
  793. ParseNode* pnode = varStmt->sxVar.pnodeInit->sxArrLit.pnode1;
  794. if (pnode->nop == knopList)
  795. {
  796. pnode = ParserWrapper::GetBinaryLeft(pnode);
  797. }
  798. if (!ParserWrapper::IsNameDeclaration(pnode))
  799. {
  800. return m.FailName(pnode, _u("Invalid element in function table %s"), varStmt->name());
  801. }
  802. ++funcPtrTableCount;
  803. list = ParserWrapper::GetBinaryRight(list);
  804. }
  805. m.SetFuncPtrTableCount(funcPtrTableCount);
  806. m.SetCurrentParseNode(list);
  807. return true;
  808. }
  809. bool AsmJSCompiler::CheckModuleReturn( AsmJsModuleCompiler& m )
  810. {
  811. ParseNode* endStmt = m.GetCurrentParserNode();
  812. if (endStmt->nop != knopList)
  813. {
  814. return m.Fail(endStmt, _u("Module must have a return"));
  815. }
  816. ParseNode* node = ParserWrapper::GetBinaryLeft( endStmt );
  817. ParseNode* endNode = ParserWrapper::GetBinaryRight( endStmt );
  818. if( node->nop != knopReturn || endNode->nop != knopEndCode )
  819. {
  820. return m.Fail( node, _u("Only expression after table functions must be a return") );
  821. }
  822. ParseNode* objNode = node->sxReturn.pnodeExpr;
  823. if ( !objNode )
  824. {
  825. return m.Fail( node, _u( "Module return must be an object or 1 function" ) );
  826. }
  827. if( objNode->nop != knopObject )
  828. {
  829. if( ParserWrapper::IsNameDeclaration( objNode ) )
  830. {
  831. PropertyName name = objNode->name();
  832. AsmJsSymbol* sym = m.LookupIdentifier( name );
  833. if( !sym )
  834. {
  835. return m.FailName( node, _u("Symbol %s not recognized inside module"), name );
  836. }
  837. if( sym->GetSymbolType() != AsmJsSymbol::ModuleFunction )
  838. {
  839. return m.FailName( node, _u("Symbol %s can only be a function of the module"), name );
  840. }
  841. AsmJsFunc* func = sym->Cast<AsmJsFunc>();
  842. if( !m.SetExportFunc( func ) )
  843. {
  844. return m.FailName( node, _u("Error adding return Symbol %s"), name );
  845. }
  846. return true;
  847. }
  848. return m.Fail( node, _u("Module return must be an object or 1 function") );
  849. }
  850. ParseNode* objectElement = ParserWrapper::GetUnaryNode(objNode);
  851. if (!objectElement)
  852. {
  853. return m.Fail(node, _u("Return object must not be empty"));
  854. }
  855. while( objectElement )
  856. {
  857. ParseNode* member = nullptr;
  858. if( objectElement->nop == knopList )
  859. {
  860. member = ParserWrapper::GetBinaryLeft( objectElement );
  861. objectElement = ParserWrapper::GetBinaryRight( objectElement );
  862. }
  863. else if( objectElement->nop == knopMember )
  864. {
  865. member = objectElement;
  866. objectElement = nullptr;
  867. }
  868. else
  869. {
  870. return m.Fail( node, _u("Return object must only contain members") );
  871. }
  872. if( member )
  873. {
  874. ParseNode* field = ParserWrapper::GetBinaryLeft( member );
  875. ParseNode* value = ParserWrapper::GetBinaryRight( member );
  876. if( !ParserWrapper::IsNameDeclaration( field ) || !ParserWrapper::IsNameDeclaration( value ) )
  877. {
  878. return m.Fail( node, _u("Return object member must be fields") );
  879. }
  880. AsmJsSymbol* sym = m.LookupIdentifier( value->name() );
  881. if( !sym )
  882. {
  883. return m.FailName( node, _u("Symbol %s not recognized inside module"), value->name() );
  884. }
  885. if( sym->GetSymbolType() != AsmJsSymbol::ModuleFunction )
  886. {
  887. return m.FailName( node, _u("Symbol %s can only be a function of the module"), value->name() );
  888. }
  889. AsmJsFunc* func = sym->Cast<AsmJsFunc>();
  890. if( !m.AddExport( field->name(), func->GetFunctionIndex() ) )
  891. {
  892. return m.FailName( node, _u("Error adding return Symbol %s"), value->name() );
  893. }
  894. }
  895. }
  896. return true;
  897. }
  898. bool AsmJSCompiler::CheckFuncPtrTables( AsmJsModuleCompiler &m )
  899. {
  900. ParseNode *list = m.GetCurrentParserNode();
  901. if (!list)
  902. {
  903. return true;
  904. }
  905. while (list->nop != knopEndCode)
  906. {
  907. ParseNode * varStmt = ParserWrapper::GetBinaryLeft(list);
  908. if (varStmt->nop != knopConstDecl && varStmt->nop != knopVarDecl)
  909. {
  910. break;
  911. }
  912. ParseNode* nodeInit = varStmt->sxVar.pnodeInit;
  913. if( !nodeInit || nodeInit->nop != knopArray )
  914. {
  915. return m.Fail( varStmt, _u("Invalid variable after function declaration") );
  916. }
  917. PropertyName tableName = varStmt->name();
  918. AsmJsSymbol* symFunctionTable = m.LookupIdentifier(tableName);
  919. if( !symFunctionTable)
  920. {
  921. // func table not used in functions disregard it
  922. }
  923. else
  924. {
  925. //Check name
  926. if(symFunctionTable->GetSymbolType() != AsmJsSymbol::FuncPtrTable )
  927. {
  928. return m.FailName( varStmt, _u("Variable %s is already defined"), tableName );
  929. }
  930. AsmJsFunctionTable* table = symFunctionTable->Cast<AsmJsFunctionTable>();
  931. if( table->IsDefined() )
  932. {
  933. return m.FailName( varStmt, _u("Multiple declaration of function table %s"), tableName );
  934. }
  935. // Check content of the array
  936. uint count = nodeInit->sxArrLit.count;
  937. if( table->GetSize() != count )
  938. {
  939. return m.FailName( varStmt, _u("Invalid size of function table %s"), tableName );
  940. }
  941. // Set the content of the array in the table
  942. ParseNode* node = nodeInit->sxArrLit.pnode1;
  943. uint i = 0;
  944. while( node )
  945. {
  946. ParseNode* funcNameNode = nullptr;
  947. if( node->nop == knopList )
  948. {
  949. funcNameNode = ParserWrapper::GetBinaryLeft( node );
  950. node = ParserWrapper::GetBinaryRight( node );
  951. }
  952. else
  953. {
  954. Assert( i + 1 == count );
  955. funcNameNode = node;
  956. node = nullptr;
  957. }
  958. if( ParserWrapper::IsNameDeclaration( funcNameNode ) )
  959. {
  960. AsmJsSymbol* sym = m.LookupIdentifier( funcNameNode->name() );
  961. if( !sym || sym->GetSymbolType() != AsmJsSymbol::ModuleFunction )
  962. {
  963. return m.FailName( varStmt, _u("Element in function table %s is not a function"), tableName );
  964. }
  965. AsmJsFunc* func = sym->Cast<AsmJsFunc>();
  966. AsmJsRetType retType;
  967. if (!table->SupportsArgCall(func->GetArgCount(), func->GetArgTypeArray(), retType))
  968. {
  969. return m.FailName(funcNameNode, _u("Function signatures in table %s do not match"), tableName);
  970. }
  971. if (!table->CheckAndSetReturnType(func->GetReturnType()))
  972. {
  973. return m.FailName(funcNameNode, _u("Function return types in table %s do not match"), tableName);
  974. }
  975. table->SetModuleFunctionIndex( func->GetFunctionIndex(), i );
  976. ++i;
  977. }
  978. else
  979. {
  980. return m.FailName(funcNameNode, _u("Element in function table %s is not a function name"), tableName);
  981. }
  982. }
  983. table->Define();
  984. }
  985. list = ParserWrapper::GetBinaryRight(list);
  986. }
  987. if( !m.AreAllFuncTableDefined() )
  988. {
  989. return m.Fail(list, _u("Some function table were used but not defined"));
  990. }
  991. m.SetCurrentParseNode(list);
  992. return true;
  993. }
  994. bool AsmJSCompiler::CheckModule( ExclusiveContext *cx, AsmJSParser &parser, ParseNode *stmtList )
  995. {
  996. AsmJsModuleCompiler m( cx, parser );
  997. if( !m.Init() )
  998. {
  999. return false;
  1000. }
  1001. if( PropertyName moduleFunctionName = ParserWrapper::FunctionName( m.GetModuleFunctionNode() ) )
  1002. {
  1003. if( !CheckModuleLevelName( m, m.GetModuleFunctionNode(), moduleFunctionName ) )
  1004. {
  1005. return false;
  1006. }
  1007. m.InitModuleName( moduleFunctionName );
  1008. if( PHASE_TRACE1( Js::ByteCodePhase ) )
  1009. {
  1010. Output::Print( _u("Asm.Js Module [%s] detected, trying to compile\n"), moduleFunctionName->Psz() );
  1011. }
  1012. }
  1013. m.AccumulateCompileTime(AsmJsCompilation::Module);
  1014. if( !CheckFunctionHead( m, m.GetModuleFunctionNode() ) )
  1015. {
  1016. goto AsmJsCompilationError;
  1017. }
  1018. if (!CheckModuleArguments(m, m.GetModuleFunctionNode()))
  1019. {
  1020. goto AsmJsCompilationError;
  1021. }
  1022. if (!CheckModuleGlobals(m))
  1023. {
  1024. goto AsmJsCompilationError;
  1025. }
  1026. m.AccumulateCompileTime(AsmJsCompilation::Module);
  1027. if (!CheckFunctionsSequential(m))
  1028. {
  1029. goto AsmJsCompilationError;
  1030. }
  1031. m.AccumulateCompileTime();
  1032. m.InitMemoryOffsets();
  1033. if( !m.CompileAllFunctions() )
  1034. {
  1035. return false;
  1036. }
  1037. m.AccumulateCompileTime(AsmJsCompilation::ByteCode);
  1038. if (!CheckFuncPtrTables(m))
  1039. {
  1040. m.RevertAllFunctions();
  1041. return false;
  1042. }
  1043. m.AccumulateCompileTime();
  1044. if (!CheckModuleReturn(m))
  1045. {
  1046. m.RevertAllFunctions();
  1047. return false;
  1048. }
  1049. m.CommitFunctions();
  1050. m.CommitModule();
  1051. m.AccumulateCompileTime(AsmJsCompilation::Module);
  1052. m.PrintCompileTrace();
  1053. return true;
  1054. AsmJsCompilationError:
  1055. ParseNode * moduleNode = m.GetModuleFunctionNode();
  1056. if( moduleNode )
  1057. {
  1058. FunctionBody* body = moduleNode->sxFnc.funcInfo->GetParsedFunctionBody();
  1059. body->ResetByteCodeGenState();
  1060. }
  1061. cx->byteCodeGenerator->Writer()->Reset();
  1062. return false;
  1063. }
  1064. bool AsmJSCompiler::Compile(ExclusiveContext *cx, AsmJSParser parser, ParseNode *stmtList)
  1065. {
  1066. if (!CheckModule(cx, parser, stmtList))
  1067. {
  1068. OutputError(cx->scriptContext, _u("Asm.js compilation failed."));
  1069. return false;
  1070. }
  1071. return true;
  1072. }
  1073. void AsmJSCompiler::OutputError(ScriptContext * scriptContext, const wchar * message, ...)
  1074. {
  1075. va_list argptr;
  1076. va_start(argptr, message);
  1077. VOutputMessage(scriptContext, DEIT_ASMJS_FAILED, message, argptr);
  1078. }
  1079. void AsmJSCompiler::OutputMessage(ScriptContext * scriptContext, const DEBUG_EVENT_INFO_TYPE messageType, const wchar * message, ...)
  1080. {
  1081. va_list argptr;
  1082. va_start(argptr, message);
  1083. VOutputMessage(scriptContext, messageType, message, argptr);
  1084. }
  1085. void AsmJSCompiler::VOutputMessage(ScriptContext * scriptContext, const DEBUG_EVENT_INFO_TYPE messageType, const wchar * message, va_list argptr)
  1086. {
  1087. char16 buf[2048];
  1088. size_t size;
  1089. size = _vsnwprintf_s(buf, _countof(buf), _TRUNCATE, message, argptr);
  1090. if (size == -1)
  1091. {
  1092. size = 2048;
  1093. }
  1094. scriptContext->RaiseMessageToDebugger(messageType, buf, scriptContext->GetUrl());
  1095. if (PHASE_TRACE1(AsmjsPhase) || PHASE_TESTTRACE1(AsmjsPhase))
  1096. {
  1097. Output::PrintBuffer(buf, size);
  1098. Output::Print(_u("\n"));
  1099. Output::Flush();
  1100. }
  1101. }
  1102. }
  1103. #endif