compiler.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464
  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, S32 reg)
  175. {
  176. StringTableEntry funcLookupTableName = StringTable->insert(avar("%s::%s", namespaceName, functionName));
  177. localVarToRegister[funcLookupTableName].table[varName] = reg;
  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].table;
  186. auto varPosition = table.find(varName);
  187. if (varPosition != table.end())
  188. {
  189. return varPosition->second;
  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 std::move(table);
  201. }
  202. void CompilerLocalVariableToRegisterMappingTable::reset()
  203. {
  204. localVarToRegister.clear();
  205. }
  206. //------------------------------------------------------------
  207. U32 CompilerFloatTable::add(F64 value)
  208. {
  209. Entry **walk;
  210. U32 i = 0;
  211. for (walk = &list; *walk; walk = &((*walk)->next), i++)
  212. if (value == (*walk)->val)
  213. return i;
  214. Entry *newFloat = (Entry *)consoleAlloc(sizeof(Entry));
  215. newFloat->val = value;
  216. newFloat->next = NULL;
  217. count++;
  218. *walk = newFloat;
  219. return count - 1;
  220. }
  221. void CompilerFloatTable::reset()
  222. {
  223. list = NULL;
  224. count = 0;
  225. }
  226. F64 *CompilerFloatTable::build()
  227. {
  228. F64 *ret = new F64[count];
  229. U32 i = 0;
  230. for (Entry *walk = list; walk; walk = walk->next, i++)
  231. ret[i] = walk->val;
  232. return ret;
  233. }
  234. void CompilerFloatTable::write(Stream &st)
  235. {
  236. st.write(count);
  237. for (Entry *walk = list; walk; walk = walk->next)
  238. st.write(walk->val);
  239. }
  240. //------------------------------------------------------------
  241. void CompilerIdentTable::reset()
  242. {
  243. list = NULL;
  244. }
  245. void CompilerIdentTable::add(StringTableEntry ste, U32 ip)
  246. {
  247. U32 index = gGlobalStringTable.add(ste, false);
  248. Entry *newEntry = (Entry *)consoleAlloc(sizeof(Entry));
  249. newEntry->offset = index;
  250. newEntry->ip = ip;
  251. for (Entry *walk = list; walk; walk = walk->next)
  252. {
  253. if (walk->offset == index)
  254. {
  255. newEntry->nextIdent = walk->nextIdent;
  256. walk->nextIdent = newEntry;
  257. return;
  258. }
  259. }
  260. newEntry->next = list;
  261. list = newEntry;
  262. newEntry->nextIdent = NULL;
  263. }
  264. void CompilerIdentTable::write(Stream &st)
  265. {
  266. U32 count = 0;
  267. Entry * walk;
  268. for (walk = list; walk; walk = walk->next)
  269. count++;
  270. st.write(count);
  271. for (walk = list; walk; walk = walk->next)
  272. {
  273. U32 ec = 0;
  274. Entry * el;
  275. for (el = walk; el; el = el->nextIdent)
  276. ec++;
  277. st.write(walk->offset);
  278. st.write(ec);
  279. for (el = walk; el; el = el->nextIdent)
  280. st.write(el->ip);
  281. }
  282. }
  283. //-------------------------------------------------------------------------
  284. U8 *CodeStream::allocCode(U32 sz)
  285. {
  286. U8 *ptr = NULL;
  287. if (mCodeHead)
  288. {
  289. const U32 bytesLeft = BlockSize - mCodeHead->size;
  290. if (bytesLeft > sz)
  291. {
  292. ptr = mCodeHead->data + mCodeHead->size;
  293. mCodeHead->size += sz;
  294. return ptr;
  295. }
  296. }
  297. CodeData *data = new CodeData;
  298. data->data = (U8*)dMalloc(BlockSize);
  299. data->size = sz;
  300. data->next = NULL;
  301. if (mCodeHead)
  302. mCodeHead->next = data;
  303. mCodeHead = data;
  304. if (mCode == NULL)
  305. mCode = data;
  306. return data->data;
  307. }
  308. //-------------------------------------------------------------------------
  309. void CodeStream::fixLoop(U32 loopBlockStart, U32 breakPoint, U32 continuePoint)
  310. {
  311. AssertFatal(mFixStack.size() > 0, "Fix stack mismatch");
  312. U32 fixStart = mFixStack[mFixStack.size() - 1];
  313. for (U32 i = fixStart; i<mFixList.size(); i += 2)
  314. {
  315. FixType type = (FixType)mFixList[i + 1];
  316. U32 fixedIp = 0;
  317. bool valid = true;
  318. switch (type)
  319. {
  320. case FIXTYPE_LOOPBLOCKSTART:
  321. fixedIp = loopBlockStart;
  322. break;
  323. case FIXTYPE_BREAK:
  324. fixedIp = breakPoint;
  325. break;
  326. case FIXTYPE_CONTINUE:
  327. fixedIp = continuePoint;
  328. break;
  329. default:
  330. //Con::warnf("Address %u fixed as %u", mFixList[i], mFixList[i+1]);
  331. valid = false;
  332. break;
  333. }
  334. if (valid)
  335. {
  336. patch(mFixList[i], fixedIp);
  337. }
  338. }
  339. }
  340. //-------------------------------------------------------------------------
  341. void CodeStream::emitCodeStream(U32 *size, U32 **stream, U32 **lineBreaks)
  342. {
  343. // Alloc stream
  344. U32 numLineBreaks = getNumLineBreaks();
  345. *stream = new U32[mCodePos + (numLineBreaks * 2)];
  346. dMemset(*stream, '\0', mCodePos + (numLineBreaks * 2));
  347. *size = mCodePos;
  348. // Dump chunks & line breaks
  349. U32 outBytes = mCodePos * sizeof(U32);
  350. U8 *outPtr = *((U8**)stream);
  351. for (CodeData *itr = mCode; itr != NULL; itr = itr->next)
  352. {
  353. U32 bytesToCopy = itr->size > outBytes ? outBytes : itr->size;
  354. dMemcpy(outPtr, itr->data, bytesToCopy);
  355. outPtr += bytesToCopy;
  356. outBytes -= bytesToCopy;
  357. }
  358. *lineBreaks = *stream + mCodePos;
  359. dMemcpy(*lineBreaks, mBreakLines.address(), sizeof(U32) * mBreakLines.size());
  360. // Apply patches on top
  361. for (U32 i = 0; i<mPatchList.size(); i++)
  362. {
  363. PatchEntry &e = mPatchList[i];
  364. (*stream)[e.addr] = e.value;
  365. }
  366. }
  367. //-------------------------------------------------------------------------
  368. void CodeStream::reset()
  369. {
  370. mCodePos = 0;
  371. mFixStack.clear();
  372. mFixLoopStack.clear();
  373. mFixList.clear();
  374. mBreakLines.clear();
  375. // Pop down to one code block
  376. CodeData *itr = mCode ? mCode->next : NULL;
  377. while (itr != NULL)
  378. {
  379. CodeData *next = itr->next;
  380. dFree(itr->data);
  381. delete(itr);
  382. itr = next;
  383. }
  384. if (mCode)
  385. {
  386. mCode->size = 0;
  387. mCode->next = NULL;
  388. mCodeHead = mCode;
  389. }
  390. }