compiler.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479
  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 "console/telnetDebugger.h"
  25. #include "console/ast.h"
  26. #include "core/tAlgorithm.h"
  27. #include "core/strings/findMatch.h"
  28. #include "console/consoleInternal.h"
  29. #include "core/stream/fileStream.h"
  30. #include "console/compiler.h"
  31. #include "console/simBase.h"
  32. namespace Compiler
  33. {
  34. F64 consoleStringToNumber(const char *str, StringTableEntry file, U32 line)
  35. {
  36. F64 val = dAtof(str);
  37. if (val != 0)
  38. return val;
  39. else if (!dStricmp(str, "true"))
  40. return 1;
  41. else if (!dStricmp(str, "false"))
  42. return 0;
  43. else if (file)
  44. {
  45. Con::warnf(ConsoleLogEntry::General, "%s (%d): string always evaluates to 0.", file, line);
  46. return 0;
  47. }
  48. return 0;
  49. }
  50. //------------------------------------------------------------
  51. CompilerStringTable *gCurrentStringTable, gGlobalStringTable, gFunctionStringTable;
  52. CompilerFloatTable *gCurrentFloatTable, gGlobalFloatTable, gFunctionFloatTable;
  53. DataChunker gConsoleAllocator;
  54. CompilerIdentTable gIdentTable;
  55. CompilerLocalVariableToRegisterMappingTable gFunctionVariableMappingTable;
  56. //------------------------------------------------------------
  57. void evalSTEtoCode(StringTableEntry ste, U32 ip, U32 *ptr)
  58. {
  59. #if defined(TORQUE_CPU_X64) || defined(TORQUE_CPU_ARM64)
  60. *(U64*)(ptr) = (U64)ste;
  61. #else
  62. *ptr = (U32)ste;
  63. #endif
  64. }
  65. void compileSTEtoCode(StringTableEntry ste, U32 ip, U32 *ptr)
  66. {
  67. if (ste)
  68. getIdentTable().add(ste, ip);
  69. *ptr = 0;
  70. *(ptr + 1) = 0;
  71. }
  72. void(*STEtoCode)(StringTableEntry ste, U32 ip, U32 *ptr) = evalSTEtoCode;
  73. //------------------------------------------------------------
  74. bool gSyntaxError = false;
  75. //------------------------------------------------------------
  76. CompilerStringTable *getCurrentStringTable() { return gCurrentStringTable; }
  77. CompilerStringTable &getGlobalStringTable() { return gGlobalStringTable; }
  78. CompilerStringTable &getFunctionStringTable() { return gFunctionStringTable; }
  79. CompilerLocalVariableToRegisterMappingTable& getFunctionVariableMappingTable() { return gFunctionVariableMappingTable; }
  80. void setCurrentStringTable(CompilerStringTable* cst) { gCurrentStringTable = cst; }
  81. CompilerFloatTable *getCurrentFloatTable() { return gCurrentFloatTable; }
  82. CompilerFloatTable &getGlobalFloatTable() { return gGlobalFloatTable; }
  83. CompilerFloatTable &getFunctionFloatTable() { return gFunctionFloatTable; }
  84. void setCurrentFloatTable(CompilerFloatTable* cst) { gCurrentFloatTable = cst; }
  85. CompilerIdentTable &getIdentTable() { return gIdentTable; }
  86. void precompileIdent(StringTableEntry ident)
  87. {
  88. if (ident)
  89. gGlobalStringTable.add(ident);
  90. }
  91. void resetTables()
  92. {
  93. setCurrentStringTable(&gGlobalStringTable);
  94. setCurrentFloatTable(&gGlobalFloatTable);
  95. getGlobalFloatTable().reset();
  96. getGlobalStringTable().reset();
  97. getFunctionFloatTable().reset();
  98. getFunctionStringTable().reset();
  99. getIdentTable().reset();
  100. getFunctionVariableMappingTable().reset();
  101. }
  102. void *consoleAlloc(U32 size) { return gConsoleAllocator.alloc(size); }
  103. void consoleAllocReset() { gConsoleAllocator.freeBlocks(); }
  104. }
  105. //-------------------------------------------------------------------------
  106. using namespace Compiler;
  107. //-------------------------------------------------------------------------
  108. U32 CompilerStringTable::add(const char *str, bool caseSens, bool tag)
  109. {
  110. // Is it already in?
  111. Entry **walk;
  112. for (walk = &list; *walk; walk = &((*walk)->next))
  113. {
  114. if ((*walk)->tag != tag)
  115. continue;
  116. if (caseSens)
  117. {
  118. if (!String::compare((*walk)->string, str))
  119. return (*walk)->start;
  120. }
  121. else
  122. {
  123. if (!dStricmp((*walk)->string, str))
  124. return (*walk)->start;
  125. }
  126. }
  127. // Write it out.
  128. Entry *newStr = (Entry *)consoleAlloc(sizeof(Entry));
  129. *walk = newStr;
  130. newStr->next = NULL;
  131. newStr->start = totalLen;
  132. U32 len = dStrlen(str) + 1;
  133. if (tag && len < 7) // alloc space for the numeric tag 1 for tag, 5 for # and 1 for nul
  134. len = 7;
  135. totalLen += len;
  136. newStr->string = (char *)consoleAlloc(len);
  137. newStr->len = len;
  138. newStr->tag = tag;
  139. dStrcpy(newStr->string, str, len);
  140. // Put into the hash table.
  141. hashTable[str] = newStr;
  142. return newStr->start;
  143. }
  144. U32 CompilerStringTable::addIntString(U32 value)
  145. {
  146. dSprintf(buf, sizeof(buf), "%d", value);
  147. return add(buf);
  148. }
  149. U32 CompilerStringTable::addFloatString(F64 value)
  150. {
  151. dSprintf(buf, sizeof(buf), "%g", value);
  152. return add(buf);
  153. }
  154. void CompilerStringTable::reset()
  155. {
  156. list = NULL;
  157. totalLen = 0;
  158. }
  159. char *CompilerStringTable::build()
  160. {
  161. char *ret = new char[totalLen];
  162. dMemset(ret, 0, totalLen);
  163. for (Entry *walk = list; walk; walk = walk->next)
  164. dStrcpy(ret + walk->start, walk->string, totalLen - walk->start);
  165. return ret;
  166. }
  167. void CompilerStringTable::write(Stream &st)
  168. {
  169. st.write(totalLen);
  170. for (Entry *walk = list; walk; walk = walk->next)
  171. st.write(walk->len, walk->string);
  172. }
  173. //------------------------------------------------------------
  174. void CompilerLocalVariableToRegisterMappingTable::add(StringTableEntry functionName, StringTableEntry namespaceName, StringTableEntry varName)
  175. {
  176. StringTableEntry funcLookupTableName = StringTable->insert(avar("%s::%s", namespaceName, functionName));
  177. localVarToRegister[funcLookupTableName].varList.push_back(varName);;
  178. }
  179. S32 CompilerLocalVariableToRegisterMappingTable::lookup(StringTableEntry namespaceName, StringTableEntry functionName, StringTableEntry varName)
  180. {
  181. StringTableEntry funcLookupTableName = StringTable->insert(avar("%s::%s", namespaceName, functionName));
  182. auto functionPosition = localVarToRegister.find(funcLookupTableName);
  183. if (functionPosition != localVarToRegister.end())
  184. {
  185. const auto& table = localVarToRegister[funcLookupTableName].varList;
  186. auto varPosition = std::find(table.begin(), table.end(), varName);
  187. if (varPosition != table.end())
  188. {
  189. return std::distance(table.begin(), varPosition);
  190. }
  191. }
  192. Con::errorf("Unable to find local variable %s in function name %s", varName, funcLookupTableName);
  193. return -1;
  194. }
  195. CompilerLocalVariableToRegisterMappingTable CompilerLocalVariableToRegisterMappingTable::copy()
  196. {
  197. // Trivilly copyable as its all plain old data and using STL containers... (We want a deep copy though!)
  198. CompilerLocalVariableToRegisterMappingTable table;
  199. table.localVarToRegister = localVarToRegister;
  200. return table;
  201. }
  202. void CompilerLocalVariableToRegisterMappingTable::reset()
  203. {
  204. localVarToRegister.clear();
  205. }
  206. void CompilerLocalVariableToRegisterMappingTable::write(Stream& stream)
  207. {
  208. stream.write(localVarToRegister.size());
  209. for (const auto& pair : localVarToRegister)
  210. {
  211. StringTableEntry functionName = pair.first;
  212. stream.writeString(functionName);
  213. const auto& localVariableTableForFunction = localVarToRegister[functionName].varList;
  214. stream.write(localVariableTableForFunction.size());
  215. for (const StringTableEntry& varName : localVariableTableForFunction)
  216. stream.writeString(varName);
  217. }
  218. }
  219. //------------------------------------------------------------
  220. U32 CompilerFloatTable::add(F64 value)
  221. {
  222. Entry **walk;
  223. U32 i = 0;
  224. for (walk = &list; *walk; walk = &((*walk)->next), i++)
  225. if (value == (*walk)->val)
  226. return i;
  227. Entry *newFloat = (Entry *)consoleAlloc(sizeof(Entry));
  228. newFloat->val = value;
  229. newFloat->next = NULL;
  230. count++;
  231. *walk = newFloat;
  232. return count - 1;
  233. }
  234. void CompilerFloatTable::reset()
  235. {
  236. list = NULL;
  237. count = 0;
  238. }
  239. F64 *CompilerFloatTable::build()
  240. {
  241. F64 *ret = new F64[count];
  242. U32 i = 0;
  243. for (Entry *walk = list; walk; walk = walk->next, i++)
  244. ret[i] = walk->val;
  245. return ret;
  246. }
  247. void CompilerFloatTable::write(Stream &st)
  248. {
  249. st.write(count);
  250. for (Entry *walk = list; walk; walk = walk->next)
  251. st.write(walk->val);
  252. }
  253. //------------------------------------------------------------
  254. void CompilerIdentTable::reset()
  255. {
  256. list = NULL;
  257. }
  258. void CompilerIdentTable::add(StringTableEntry ste, U32 ip)
  259. {
  260. U32 index = gGlobalStringTable.add(ste, false);
  261. Entry *newEntry = (Entry *)consoleAlloc(sizeof(Entry));
  262. newEntry->offset = index;
  263. newEntry->ip = ip;
  264. for (Entry *walk = list; walk; walk = walk->next)
  265. {
  266. if (walk->offset == index)
  267. {
  268. newEntry->nextIdent = walk->nextIdent;
  269. walk->nextIdent = newEntry;
  270. return;
  271. }
  272. }
  273. newEntry->next = list;
  274. list = newEntry;
  275. newEntry->nextIdent = NULL;
  276. }
  277. void CompilerIdentTable::write(Stream &st)
  278. {
  279. U32 count = 0;
  280. Entry * walk;
  281. for (walk = list; walk; walk = walk->next)
  282. count++;
  283. st.write(count);
  284. for (walk = list; walk; walk = walk->next)
  285. {
  286. U32 ec = 0;
  287. Entry * el;
  288. for (el = walk; el; el = el->nextIdent)
  289. ec++;
  290. st.write(walk->offset);
  291. st.write(ec);
  292. for (el = walk; el; el = el->nextIdent)
  293. st.write(el->ip);
  294. }
  295. }
  296. //-------------------------------------------------------------------------
  297. U8 *CodeStream::allocCode(U32 sz)
  298. {
  299. U8 *ptr = NULL;
  300. if (mCodeHead)
  301. {
  302. const U32 bytesLeft = BlockSize - mCodeHead->size;
  303. if (bytesLeft > sz)
  304. {
  305. ptr = mCodeHead->data + mCodeHead->size;
  306. mCodeHead->size += sz;
  307. return ptr;
  308. }
  309. }
  310. CodeData *data = new CodeData;
  311. data->data = (U8*)dMalloc(BlockSize);
  312. data->size = sz;
  313. data->next = NULL;
  314. if (mCodeHead)
  315. mCodeHead->next = data;
  316. mCodeHead = data;
  317. if (mCode == NULL)
  318. mCode = data;
  319. return data->data;
  320. }
  321. //-------------------------------------------------------------------------
  322. void CodeStream::fixLoop(U32 loopBlockStart, U32 breakPoint, U32 continuePoint)
  323. {
  324. AssertFatal(mFixStack.size() > 0, "Fix stack mismatch");
  325. U32 fixStart = mFixStack[mFixStack.size() - 1];
  326. for (U32 i = fixStart; i<mFixList.size(); i += 2)
  327. {
  328. FixType type = (FixType)mFixList[i + 1];
  329. U32 fixedIp = 0;
  330. bool valid = true;
  331. switch (type)
  332. {
  333. case FIXTYPE_LOOPBLOCKSTART:
  334. fixedIp = loopBlockStart;
  335. break;
  336. case FIXTYPE_BREAK:
  337. fixedIp = breakPoint;
  338. break;
  339. case FIXTYPE_CONTINUE:
  340. fixedIp = continuePoint;
  341. break;
  342. default:
  343. //Con::warnf("Address %u fixed as %u", mFixList[i], mFixList[i+1]);
  344. valid = false;
  345. break;
  346. }
  347. if (valid)
  348. {
  349. patch(mFixList[i], fixedIp);
  350. }
  351. }
  352. }
  353. //-------------------------------------------------------------------------
  354. void CodeStream::emitCodeStream(U32 *size, U32 **stream, U32 **lineBreaks)
  355. {
  356. // Alloc stream
  357. U32 numLineBreaks = getNumLineBreaks();
  358. *stream = new U32[mCodePos + (numLineBreaks * 2)];
  359. dMemset(*stream, '\0', mCodePos + (numLineBreaks * 2));
  360. *size = mCodePos;
  361. // Dump chunks & line breaks
  362. U32 outBytes = mCodePos * sizeof(U32);
  363. U8 *outPtr = *((U8**)stream);
  364. for (CodeData *itr = mCode; itr != NULL; itr = itr->next)
  365. {
  366. U32 bytesToCopy = itr->size > outBytes ? outBytes : itr->size;
  367. dMemcpy(outPtr, itr->data, bytesToCopy);
  368. outPtr += bytesToCopy;
  369. outBytes -= bytesToCopy;
  370. }
  371. *lineBreaks = *stream + mCodePos;
  372. dMemcpy(*lineBreaks, mBreakLines.address(), sizeof(U32) * mBreakLines.size());
  373. // Apply patches on top
  374. for (U32 i = 0; i<mPatchList.size(); i++)
  375. {
  376. PatchEntry &e = mPatchList[i];
  377. (*stream)[e.addr] = e.value;
  378. }
  379. }
  380. //-------------------------------------------------------------------------
  381. void CodeStream::reset()
  382. {
  383. mCodePos = 0;
  384. mFixStack.clear();
  385. mFixLoopStack.clear();
  386. mFixList.clear();
  387. mBreakLines.clear();
  388. // Pop down to one code block
  389. CodeData *itr = mCode ? mCode->next : NULL;
  390. while (itr != NULL)
  391. {
  392. CodeData *next = itr->next;
  393. dFree(itr->data);
  394. delete(itr);
  395. itr = next;
  396. }
  397. if (mCode)
  398. {
  399. mCode->size = 0;
  400. mCode->next = NULL;
  401. mCodeHead = mCode;
  402. }
  403. }