compiler.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555
  1. //-----------------------------------------------------------------------------
  2. // Copyright (c) 2012 GarageGames, LLC
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to
  6. // deal in the Software without restriction, including without limitation the
  7. // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
  8. // sell copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  19. // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  20. // IN THE SOFTWARE.
  21. //-----------------------------------------------------------------------------
  22. #include "platform/platform.h"
  23. #include "console/console.h"
  24. #include "compiler.h"
  25. #include "console/simBase.h"
  26. extern FuncVars gEvalFuncVars;
  27. extern FuncVars gGlobalScopeFuncVars;
  28. extern FuncVars *gFuncVars;
  29. namespace Con
  30. {
  31. extern bool scriptWarningsAsAsserts;
  32. };
  33. namespace Compiler
  34. {
  35. F64 consoleStringToNumber(const char *str, StringTableEntry file, U32 line)
  36. {
  37. F64 val = dAtof(str);
  38. if (val != 0)
  39. return val;
  40. else if (!dStricmp(str, "true"))
  41. return 1;
  42. else if (!dStricmp(str, "false"))
  43. return 0;
  44. else if (file)
  45. {
  46. Con::warnf(ConsoleLogEntry::General, "%s (%d): string always evaluates to 0.", file, line);
  47. return 0;
  48. }
  49. return 0;
  50. }
  51. //------------------------------------------------------------
  52. CompilerStringTable *gCurrentStringTable, gGlobalStringTable, gFunctionStringTable;
  53. CompilerFloatTable *gCurrentFloatTable, gGlobalFloatTable, gFunctionFloatTable;
  54. DataChunker gConsoleAllocator;
  55. CompilerIdentTable gIdentTable;
  56. CompilerLocalVariableToRegisterMappingTable gFunctionVariableMappingTable;
  57. //------------------------------------------------------------
  58. void evalSTEtoCode(StringTableEntry ste, U32 ip, U32 *ptr)
  59. {
  60. #if defined(TORQUE_CPU_X64) || defined(TORQUE_CPU_ARM64)
  61. *(U64*)(ptr) = (U64)ste;
  62. #else
  63. *ptr = (U32)ste;
  64. #endif
  65. }
  66. void compileSTEtoCode(StringTableEntry ste, U32 ip, U32 *ptr)
  67. {
  68. if (ste)
  69. getIdentTable().add(ste, ip);
  70. *ptr = 0;
  71. *(ptr + 1) = 0;
  72. }
  73. void(*STEtoCode)(StringTableEntry ste, U32 ip, U32 *ptr) = evalSTEtoCode;
  74. //------------------------------------------------------------
  75. bool gSyntaxError = false;
  76. bool gIsEvalCompile = false;
  77. //------------------------------------------------------------
  78. CompilerStringTable *getCurrentStringTable() { return gCurrentStringTable; }
  79. CompilerStringTable &getGlobalStringTable() { return gGlobalStringTable; }
  80. CompilerStringTable &getFunctionStringTable() { return gFunctionStringTable; }
  81. CompilerLocalVariableToRegisterMappingTable& getFunctionVariableMappingTable() { return gFunctionVariableMappingTable; }
  82. void setCurrentStringTable(CompilerStringTable* cst) { gCurrentStringTable = cst; }
  83. CompilerFloatTable *getCurrentFloatTable() { return gCurrentFloatTable; }
  84. CompilerFloatTable &getGlobalFloatTable() { return gGlobalFloatTable; }
  85. CompilerFloatTable &getFunctionFloatTable() { return gFunctionFloatTable; }
  86. void setCurrentFloatTable(CompilerFloatTable* cst) { gCurrentFloatTable = cst; }
  87. CompilerIdentTable &getIdentTable() { return gIdentTable; }
  88. void precompileIdent(StringTableEntry ident)
  89. {
  90. if (ident)
  91. gGlobalStringTable.add(ident);
  92. }
  93. void resetTables()
  94. {
  95. setCurrentStringTable(&gGlobalStringTable);
  96. setCurrentFloatTable(&gGlobalFloatTable);
  97. getGlobalFloatTable().reset();
  98. getGlobalStringTable().reset();
  99. getFunctionFloatTable().reset();
  100. getFunctionStringTable().reset();
  101. getIdentTable().reset();
  102. getFunctionVariableMappingTable().reset();
  103. gGlobalScopeFuncVars.clear();
  104. gFuncVars = gIsEvalCompile ? &gEvalFuncVars : &gGlobalScopeFuncVars;
  105. }
  106. void *consoleAlloc(U32 size) { return gConsoleAllocator.alloc(size); }
  107. void consoleAllocReset() { gConsoleAllocator.freeBlocks(); }
  108. void scriptErrorHandler(const char* str)
  109. {
  110. if (Con::scriptWarningsAsAsserts)
  111. {
  112. AssertISV(false, str);
  113. }
  114. else
  115. {
  116. Con::warnf(ConsoleLogEntry::Type::Script, "%s", str);
  117. }
  118. }
  119. }
  120. //-------------------------------------------------------------------------
  121. using namespace Compiler;
  122. S32 FuncVars::assign(StringTableEntry var, TypeReq currentType, S32 lineNumber, bool isConstant)
  123. {
  124. std::unordered_map<StringTableEntry, Var>::iterator found = vars.find(var);
  125. if (found != vars.end())
  126. {
  127. if (found->second.isConstant)
  128. {
  129. const char* str = avar("Script Warning: Reassigning variable %s when it is a constant. File: %s Line : %d", var, CodeBlock::smCurrentParser->getCurrentFile(), lineNumber);
  130. scriptErrorHandler(str);
  131. }
  132. return found->second.reg;
  133. }
  134. S32 id = counter++;
  135. vars[var] = { id, currentType, var, isConstant };
  136. variableNameMap[id] = var;
  137. return id;
  138. }
  139. S32 FuncVars::lookup(StringTableEntry var, S32 lineNumber)
  140. {
  141. std::unordered_map<StringTableEntry, Var>::iterator found = vars.find(var);
  142. if (found == vars.end())
  143. {
  144. const char* str = avar("Script Warning: Variable %s referenced before used when compiling script. File: %s Line: %d", var, CodeBlock::smCurrentParser->getCurrentFile(), lineNumber);
  145. scriptErrorHandler(str);
  146. return assign(var, TypeReqString, lineNumber, false);
  147. }
  148. return found->second.reg;
  149. }
  150. TypeReq FuncVars::lookupType(StringTableEntry var, S32 lineNumber)
  151. {
  152. std::unordered_map<StringTableEntry, Var>::iterator found = vars.find(var);
  153. if (found == vars.end())
  154. {
  155. const char* str = avar("Script Warning: Variable %s referenced before used when compiling script. File: %s Line: %d", var, CodeBlock::smCurrentParser->getCurrentFile(), lineNumber);
  156. scriptErrorHandler(str);
  157. assign(var, TypeReqString, lineNumber, false);
  158. return vars.find(var)->second.currentType;
  159. }
  160. return found->second.currentType;
  161. }
  162. void FuncVars::clear()
  163. {
  164. vars.clear();
  165. variableNameMap.clear();
  166. counter = 0;
  167. }
  168. //-------------------------------------------------------------------------
  169. U32 CompilerStringTable::add(const char *str, bool caseSens, bool tag)
  170. {
  171. // Is it already in?
  172. Entry **walk;
  173. for (walk = &list; *walk; walk = &((*walk)->next))
  174. {
  175. if ((*walk)->tag != tag)
  176. continue;
  177. if (caseSens)
  178. {
  179. if (!String::compare((*walk)->string, str))
  180. return (*walk)->start;
  181. }
  182. else
  183. {
  184. if (!dStricmp((*walk)->string, str))
  185. return (*walk)->start;
  186. }
  187. }
  188. // Write it out.
  189. Entry *newStr = (Entry *)consoleAlloc(sizeof(Entry));
  190. *walk = newStr;
  191. newStr->next = NULL;
  192. newStr->start = totalLen;
  193. U32 len = dStrlen(str) + 1;
  194. if (tag && len < 7) // alloc space for the numeric tag 1 for tag, 5 for # and 1 for nul
  195. len = 7;
  196. totalLen += len;
  197. newStr->string = (char *)consoleAlloc(len);
  198. newStr->len = len;
  199. newStr->tag = tag;
  200. dStrcpy(newStr->string, str, len);
  201. // Put into the hash table.
  202. hashTable[str] = newStr;
  203. return newStr->start;
  204. }
  205. U32 CompilerStringTable::addIntString(U32 value)
  206. {
  207. dSprintf(buf, sizeof(buf), "%d", value);
  208. return add(buf);
  209. }
  210. U32 CompilerStringTable::addFloatString(F64 value)
  211. {
  212. dSprintf(buf, sizeof(buf), "%g", value);
  213. return add(buf);
  214. }
  215. void CompilerStringTable::reset()
  216. {
  217. list = NULL;
  218. totalLen = 0;
  219. }
  220. char *CompilerStringTable::build()
  221. {
  222. char *ret = new char[totalLen];
  223. dMemset(ret, 0, totalLen);
  224. for (Entry *walk = list; walk; walk = walk->next)
  225. dStrcpy(ret + walk->start, walk->string, totalLen - walk->start);
  226. return ret;
  227. }
  228. void CompilerStringTable::write(Stream &st)
  229. {
  230. st.write(totalLen);
  231. for (Entry *walk = list; walk; walk = walk->next)
  232. st.write(walk->len, walk->string);
  233. }
  234. //------------------------------------------------------------
  235. void CompilerLocalVariableToRegisterMappingTable::add(StringTableEntry functionName, StringTableEntry namespaceName, StringTableEntry varName)
  236. {
  237. StringTableEntry funcLookupTableName = StringTable->insert(avar("%s::%s", namespaceName, functionName));
  238. localVarToRegister[funcLookupTableName].varList.push_back(varName);;
  239. }
  240. S32 CompilerLocalVariableToRegisterMappingTable::lookup(StringTableEntry namespaceName, StringTableEntry functionName, StringTableEntry varName)
  241. {
  242. StringTableEntry funcLookupTableName = StringTable->insert(avar("%s::%s", namespaceName, functionName));
  243. auto functionPosition = localVarToRegister.find(funcLookupTableName);
  244. if (functionPosition != localVarToRegister.end())
  245. {
  246. const auto& table = localVarToRegister[funcLookupTableName].varList;
  247. auto varPosition = std::find(table.begin(), table.end(), varName);
  248. if (varPosition != table.end())
  249. {
  250. return std::distance(table.begin(), varPosition);
  251. }
  252. }
  253. Con::errorf("Unable to find local variable %s in function name %s", varName, funcLookupTableName);
  254. return -1;
  255. }
  256. CompilerLocalVariableToRegisterMappingTable CompilerLocalVariableToRegisterMappingTable::copy()
  257. {
  258. // Trivilly copyable as its all plain old data and using STL containers... (We want a deep copy though!)
  259. CompilerLocalVariableToRegisterMappingTable table;
  260. table.localVarToRegister = localVarToRegister;
  261. return table;
  262. }
  263. void CompilerLocalVariableToRegisterMappingTable::reset()
  264. {
  265. localVarToRegister.clear();
  266. }
  267. void CompilerLocalVariableToRegisterMappingTable::write(Stream& stream)
  268. {
  269. stream.write((U32)localVarToRegister.size());
  270. for (const auto& pair : localVarToRegister)
  271. {
  272. StringTableEntry functionName = pair.first;
  273. stream.writeString(functionName);
  274. const auto& localVariableTableForFunction = localVarToRegister[functionName].varList;
  275. stream.write((U32)localVariableTableForFunction.size());
  276. for (const StringTableEntry& varName : localVariableTableForFunction)
  277. {
  278. stream.writeString(varName);
  279. }
  280. }
  281. }
  282. //------------------------------------------------------------
  283. U32 CompilerFloatTable::add(F64 value)
  284. {
  285. Entry **walk;
  286. U32 i = 0;
  287. for (walk = &list; *walk; walk = &((*walk)->next), i++)
  288. if (value == (*walk)->val)
  289. return i;
  290. Entry *newFloat = (Entry *)consoleAlloc(sizeof(Entry));
  291. newFloat->val = value;
  292. newFloat->next = NULL;
  293. count++;
  294. *walk = newFloat;
  295. return count - 1;
  296. }
  297. void CompilerFloatTable::reset()
  298. {
  299. list = NULL;
  300. count = 0;
  301. }
  302. F64 *CompilerFloatTable::build()
  303. {
  304. F64 *ret = new F64[count];
  305. U32 i = 0;
  306. for (Entry *walk = list; walk; walk = walk->next, i++)
  307. ret[i] = walk->val;
  308. return ret;
  309. }
  310. void CompilerFloatTable::write(Stream &st)
  311. {
  312. st.write(count);
  313. for (Entry *walk = list; walk; walk = walk->next)
  314. st.write(walk->val);
  315. }
  316. //------------------------------------------------------------
  317. void CompilerIdentTable::reset()
  318. {
  319. list = NULL;
  320. }
  321. void CompilerIdentTable::add(StringTableEntry ste, U32 ip)
  322. {
  323. U32 index = gGlobalStringTable.add(ste, false);
  324. Entry *newEntry = (Entry *)consoleAlloc(sizeof(Entry));
  325. newEntry->offset = index;
  326. newEntry->ip = ip;
  327. for (Entry *walk = list; walk; walk = walk->next)
  328. {
  329. if (walk->offset == index)
  330. {
  331. newEntry->nextIdent = walk->nextIdent;
  332. walk->nextIdent = newEntry;
  333. return;
  334. }
  335. }
  336. newEntry->next = list;
  337. list = newEntry;
  338. newEntry->nextIdent = NULL;
  339. }
  340. void CompilerIdentTable::write(Stream &st)
  341. {
  342. U32 count = 0;
  343. Entry * walk;
  344. for (walk = list; walk; walk = walk->next)
  345. count++;
  346. st.write(count);
  347. for (walk = list; walk; walk = walk->next)
  348. {
  349. U32 ec = 0;
  350. Entry * el;
  351. for (el = walk; el; el = el->nextIdent)
  352. ec++;
  353. st.write(walk->offset);
  354. st.write(ec);
  355. for (el = walk; el; el = el->nextIdent)
  356. st.write(el->ip);
  357. }
  358. }
  359. //-------------------------------------------------------------------------
  360. U8 *CodeStream::allocCode(U32 sz)
  361. {
  362. U8 *ptr = NULL;
  363. if (mCodeHead)
  364. {
  365. const U32 bytesLeft = BlockSize - mCodeHead->size;
  366. if (bytesLeft > sz)
  367. {
  368. ptr = mCodeHead->data + mCodeHead->size;
  369. mCodeHead->size += sz;
  370. return ptr;
  371. }
  372. }
  373. CodeData *data = new CodeData;
  374. data->data = (U8*)dMalloc(BlockSize);
  375. data->size = sz;
  376. data->next = NULL;
  377. if (mCodeHead)
  378. mCodeHead->next = data;
  379. mCodeHead = data;
  380. if (mCode == NULL)
  381. mCode = data;
  382. return data->data;
  383. }
  384. //-------------------------------------------------------------------------
  385. void CodeStream::fixLoop(U32 loopBlockStart, U32 breakPoint, U32 continuePoint)
  386. {
  387. AssertFatal(mFixStack.size() > 0, "Fix stack mismatch");
  388. U32 fixStart = mFixStack[mFixStack.size() - 1];
  389. for (U32 i = fixStart; i<mFixList.size(); i += 2)
  390. {
  391. FixType type = (FixType)mFixList[i + 1];
  392. U32 fixedIp = 0;
  393. bool valid = true;
  394. switch (type)
  395. {
  396. case FIXTYPE_LOOPBLOCKSTART:
  397. fixedIp = loopBlockStart;
  398. break;
  399. case FIXTYPE_BREAK:
  400. fixedIp = breakPoint;
  401. break;
  402. case FIXTYPE_CONTINUE:
  403. fixedIp = continuePoint;
  404. break;
  405. default:
  406. //Con::warnf("Address %u fixed as %u", mFixList[i], mFixList[i+1]);
  407. valid = false;
  408. break;
  409. }
  410. if (valid)
  411. {
  412. patch(mFixList[i], fixedIp);
  413. }
  414. }
  415. }
  416. //-------------------------------------------------------------------------
  417. void CodeStream::emitCodeStream(U32 *size, U32 **stream, U32 **lineBreaks)
  418. {
  419. // Alloc stream
  420. U32 numLineBreaks = getNumLineBreaks();
  421. *stream = new U32[mCodePos + (numLineBreaks * 2)];
  422. dMemset(*stream, '\0', mCodePos + (numLineBreaks * 2));
  423. *size = mCodePos;
  424. // Dump chunks & line breaks
  425. U32 outBytes = mCodePos * sizeof(U32);
  426. U8 *outPtr = *((U8**)stream);
  427. for (CodeData *itr = mCode; itr != NULL; itr = itr->next)
  428. {
  429. U32 bytesToCopy = itr->size > outBytes ? outBytes : itr->size;
  430. dMemcpy(outPtr, itr->data, bytesToCopy);
  431. outPtr += bytesToCopy;
  432. outBytes -= bytesToCopy;
  433. }
  434. *lineBreaks = *stream + mCodePos;
  435. dMemcpy(*lineBreaks, mBreakLines.address(), sizeof(U32) * mBreakLines.size());
  436. // Apply patches on top
  437. for (U32 i = 0; i<mPatchList.size(); i++)
  438. {
  439. PatchEntry &e = mPatchList[i];
  440. (*stream)[e.addr] = e.value;
  441. }
  442. }
  443. //-------------------------------------------------------------------------
  444. void CodeStream::reset()
  445. {
  446. mCodePos = 0;
  447. mFixStack.clear();
  448. mFixLoopStack.clear();
  449. mFixList.clear();
  450. mBreakLines.clear();
  451. // Pop down to one code block
  452. CodeData *itr = mCode ? mCode->next : NULL;
  453. while (itr != NULL)
  454. {
  455. CodeData *next = itr->next;
  456. dFree(itr->data);
  457. delete(itr);
  458. itr = next;
  459. }
  460. if (mCode)
  461. {
  462. mCode->size = 0;
  463. mCode->next = NULL;
  464. mCodeHead = mCode;
  465. }
  466. }