compiler.h 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480
  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. #ifndef _COMPILER_H_
  23. #define _COMPILER_H_
  24. //#define DEBUG_CODESTREAM
  25. #ifdef DEBUG_CODESTREAM
  26. #include <stdio.h>
  27. #endif
  28. #include <string>
  29. #include <unordered_map>
  30. class CodeStream;
  31. struct StmtNode;
  32. class Stream;
  33. class DataChunker;
  34. #include "platform/platform.h"
  35. #include "ast.h"
  36. #include "codeBlock.h"
  37. #ifndef _TVECTOR_H_
  38. #include "core/util/tVector.h"
  39. #endif
  40. //------------------------------------------------------------
  41. namespace Compiler
  42. {
  43. /// The opcodes for the TorqueScript VM.
  44. enum CompiledInstructions
  45. {
  46. OP_FUNC_DECL,
  47. OP_CREATE_OBJECT,
  48. OP_ADD_OBJECT,
  49. OP_END_OBJECT,
  50. // Added to fix the stack issue [7/9/2007 Black]
  51. OP_FINISH_OBJECT,
  52. OP_JMPIFFNOT,
  53. OP_JMPIFNOT,
  54. OP_JMPIFF,
  55. OP_JMPIF,
  56. OP_JMPIFNOT_NP,
  57. OP_JMPIF_NP, // 10
  58. OP_JMP,
  59. OP_RETURN,
  60. // fixes a bug when not explicitly returning a value
  61. OP_RETURN_VOID,
  62. OP_RETURN_FLT,
  63. OP_RETURN_UINT,
  64. OP_CMPEQ,
  65. OP_CMPGR,
  66. OP_CMPGE,
  67. OP_CMPLT,
  68. OP_CMPLE,
  69. OP_CMPNE,
  70. OP_XOR, // 20
  71. OP_MOD,
  72. OP_BITAND,
  73. OP_BITOR,
  74. OP_NOT,
  75. OP_NOTF,
  76. OP_ONESCOMPLEMENT,
  77. OP_SHR,
  78. OP_SHL,
  79. OP_AND,
  80. OP_OR, // 30
  81. OP_ADD,
  82. OP_SUB,
  83. OP_MUL,
  84. OP_DIV,
  85. OP_NEG,
  86. OP_INC,
  87. OP_SETCURVAR,
  88. OP_SETCURVAR_CREATE,
  89. OP_SETCURVAR_ARRAY,
  90. OP_SETCURVAR_ARRAY_CREATE,
  91. OP_LOADVAR_UINT,// 40
  92. OP_LOADVAR_FLT,
  93. OP_LOADVAR_STR,
  94. OP_SAVEVAR_UINT,
  95. OP_SAVEVAR_FLT,
  96. OP_SAVEVAR_STR,
  97. OP_LOAD_LOCAL_VAR_UINT,
  98. OP_LOAD_LOCAL_VAR_FLT,
  99. OP_LOAD_LOCAL_VAR_STR,
  100. OP_SAVE_LOCAL_VAR_UINT,
  101. OP_SAVE_LOCAL_VAR_FLT,
  102. OP_SAVE_LOCAL_VAR_STR,
  103. OP_SETCUROBJECT,
  104. OP_SETCUROBJECT_NEW,
  105. OP_SETCUROBJECT_INTERNAL,
  106. OP_SETCURFIELD,
  107. OP_SETCURFIELD_ARRAY, // 50
  108. OP_SETCURFIELD_TYPE,
  109. OP_LOADFIELD_UINT,
  110. OP_LOADFIELD_FLT,
  111. OP_LOADFIELD_STR,
  112. OP_SAVEFIELD_UINT,
  113. OP_SAVEFIELD_FLT,
  114. OP_SAVEFIELD_STR,
  115. OP_POP_STK,
  116. OP_LOADIMMED_UINT,
  117. OP_LOADIMMED_FLT,
  118. OP_TAG_TO_STR,
  119. OP_LOADIMMED_STR, // 70
  120. OP_DOCBLOCK_STR, // 76
  121. OP_LOADIMMED_IDENT,
  122. OP_CALLFUNC,
  123. OP_ADVANCE_STR_APPENDCHAR,
  124. OP_REWIND_STR,
  125. OP_TERMINATE_REWIND_STR,
  126. OP_COMPARE_STR,
  127. OP_PUSH,
  128. OP_PUSH_FRAME,
  129. OP_ASSERT,
  130. OP_BREAK,
  131. OP_ITER_BEGIN, ///< Prepare foreach iterator.
  132. OP_ITER_BEGIN_STR, ///< Prepare foreach$ iterator.
  133. OP_ITER, ///< Enter foreach loop.
  134. OP_ITER_END, ///< End foreach loop.
  135. OP_INVALID, // 90
  136. MAX_OP_CODELEN ///< The amount of op codes.
  137. };
  138. //------------------------------------------------------------
  139. F64 consoleStringToNumber(const char *str, StringTableEntry file = 0, U32 line = 0);
  140. U32 compileBlock(StmtNode *block, CodeStream &codeStream, U32 ip);
  141. //------------------------------------------------------------
  142. struct CompilerIdentTable
  143. {
  144. struct Entry
  145. {
  146. U32 offset;
  147. U32 ip;
  148. Entry *next;
  149. Entry *nextIdent;
  150. };
  151. Entry *list;
  152. void add(StringTableEntry ste, U32 ip);
  153. void reset();
  154. void write(Stream &st);
  155. };
  156. //------------------------------------------------------------
  157. struct CompilerStringTable
  158. {
  159. U32 totalLen;
  160. struct Entry
  161. {
  162. char *string;
  163. U32 start;
  164. U32 len;
  165. bool tag;
  166. Entry *next;
  167. };
  168. Entry *list;
  169. char buf[256];
  170. std::unordered_map<std::string, Entry*> hashTable;
  171. U32 add(const char *str, bool caseSens = true, bool tag = false);
  172. U32 addIntString(U32 value);
  173. U32 addFloatString(F64 value);
  174. void reset();
  175. char *build();
  176. void write(Stream &st);
  177. };
  178. //------------------------------------------------------------
  179. struct CompilerFloatTable
  180. {
  181. struct Entry
  182. {
  183. F64 val;
  184. Entry *next;
  185. };
  186. U32 count;
  187. Entry *list;
  188. U32 add(F64 value);
  189. void reset();
  190. F64 *build();
  191. void write(Stream &st);
  192. };
  193. //------------------------------------------------------------
  194. inline StringTableEntry CodeToSTE(U32 *code, U32 ip)
  195. {
  196. #if defined(TORQUE_CPU_X64) || defined(TORQUE_CPU_ARM64)
  197. return (StringTableEntry)(*((U64*)(code + ip)));
  198. #else
  199. return (StringTableEntry)(*(code + ip));
  200. #endif
  201. }
  202. extern void(*STEtoCode)(StringTableEntry ste, U32 ip, U32 *ptr);
  203. void evalSTEtoCode(StringTableEntry ste, U32 ip, U32 *ptr);
  204. void compileSTEtoCode(StringTableEntry ste, U32 ip, U32 *ptr);
  205. CompilerStringTable *getCurrentStringTable();
  206. CompilerStringTable &getGlobalStringTable();
  207. CompilerStringTable &getFunctionStringTable();
  208. CompilerLocalVariableToRegisterMappingTable& getFunctionVariableMappingTable();
  209. void setCurrentStringTable(CompilerStringTable* cst);
  210. CompilerFloatTable *getCurrentFloatTable();
  211. CompilerFloatTable &getGlobalFloatTable();
  212. CompilerFloatTable &getFunctionFloatTable();
  213. void setCurrentFloatTable(CompilerFloatTable* cst);
  214. CompilerIdentTable &getIdentTable();
  215. void precompileIdent(StringTableEntry ident);
  216. /// Helper function to reset the float, string, and ident tables to a base
  217. /// starting state.
  218. void resetTables();
  219. void *consoleAlloc(U32 size);
  220. void consoleAllocReset();
  221. void scriptErrorHandler(const char* str);
  222. extern bool gSyntaxError;
  223. extern bool gIsEvalCompile;
  224. };
  225. class FuncVars
  226. {
  227. struct Var
  228. {
  229. S32 reg;
  230. TypeReq currentType;
  231. StringTableEntry name;
  232. bool isConstant;
  233. };
  234. public:
  235. S32 assign(StringTableEntry var, TypeReq currentType, S32 lineNumber, bool isConstant = false);
  236. S32 lookup(StringTableEntry var, S32 lineNumber);
  237. TypeReq lookupType(StringTableEntry var, S32 lineNumber);
  238. inline S32 count() { return counter; }
  239. std::unordered_map<S32, StringTableEntry> variableNameMap;
  240. void clear();
  241. private:
  242. std::unordered_map<StringTableEntry, Var> vars;
  243. S32 counter = 0;
  244. };
  245. /// Utility class to emit and patch bytecode
  246. class CodeStream
  247. {
  248. public:
  249. enum FixType
  250. {
  251. // For loops
  252. FIXTYPE_LOOPBLOCKSTART,
  253. FIXTYPE_BREAK,
  254. FIXTYPE_CONTINUE
  255. };
  256. enum Constants
  257. {
  258. BlockSize = 16384,
  259. };
  260. protected:
  261. typedef struct PatchEntry
  262. {
  263. U32 addr; ///< Address to patch
  264. U32 value; ///< Value to place at addr
  265. PatchEntry(): addr(0), value(0) { ; }
  266. PatchEntry(U32 a, U32 v) : addr(a), value(v) { ; }
  267. } PatchEntry;
  268. typedef struct CodeData
  269. {
  270. U8 *data; ///< Allocated data (size is BlockSize)
  271. U32 size; ///< Bytes used in data
  272. CodeData *next; ///< Next block
  273. } CodeData;
  274. /// @name Emitted code
  275. /// {
  276. CodeData *mCode;
  277. CodeData *mCodeHead;
  278. U32 mCodePos;
  279. /// }
  280. /// @name Code fixing stacks
  281. /// {
  282. Vector<U32> mFixList;
  283. Vector<U32> mFixStack;
  284. Vector<bool> mFixLoopStack;
  285. Vector<PatchEntry> mPatchList;
  286. /// }
  287. Vector<U32> mBreakLines; ///< Line numbers
  288. public:
  289. CodeStream() : mCode(0), mCodeHead(NULL), mCodePos(0)
  290. {
  291. }
  292. ~CodeStream()
  293. {
  294. reset();
  295. if (mCode)
  296. {
  297. dFree(mCode->data);
  298. delete mCode;
  299. }
  300. }
  301. U8 *allocCode(U32 sz);
  302. inline U32 emit(U32 code)
  303. {
  304. U32 *ptr = (U32*)allocCode(4);
  305. *ptr = code;
  306. #ifdef DEBUG_CODESTREAM
  307. printf("code[%u] = %u\n", mCodePos, code);
  308. #endif
  309. return mCodePos++;
  310. }
  311. inline void patch(U32 addr, U32 code)
  312. {
  313. #ifdef DEBUG_CODESTREAM
  314. printf("patch[%u] = %u\n", addr, code);
  315. #endif
  316. mPatchList.push_back(PatchEntry(addr, code));
  317. }
  318. inline U32 emitSTE(const char *code)
  319. {
  320. U64 *ptr = (U64*)allocCode(8);
  321. *ptr = 0;
  322. Compiler::STEtoCode(code, mCodePos, (U32*)ptr);
  323. #ifdef DEBUG_CODESTREAM
  324. printf("code[%u] = %s\n", mCodePos, code);
  325. #endif
  326. mCodePos += 2;
  327. return mCodePos - 2;
  328. }
  329. inline U32 tell()
  330. {
  331. return mCodePos;
  332. }
  333. inline bool inLoop()
  334. {
  335. for (U32 i = 0; i<mFixLoopStack.size(); i++)
  336. {
  337. if (mFixLoopStack[i])
  338. return true;
  339. }
  340. return false;
  341. }
  342. inline U32 emitFix(FixType type)
  343. {
  344. U32 *ptr = (U32*)allocCode(4);
  345. *ptr = (U32)type;
  346. #ifdef DEBUG_CODESTREAM
  347. printf("code[%u] = [FIX:%u]\n", mCodePos, (U32)type);
  348. #endif
  349. mFixList.push_back(mCodePos);
  350. mFixList.push_back((U32)type);
  351. return mCodePos++;
  352. }
  353. inline void pushFixScope(bool isLoop)
  354. {
  355. mFixStack.push_back(mFixList.size());
  356. mFixLoopStack.push_back(isLoop);
  357. }
  358. inline void popFixScope()
  359. {
  360. AssertFatal(mFixStack.size() > 0, "Fix stack mismatch");
  361. U32 newSize = mFixStack[mFixStack.size() - 1];
  362. while (mFixList.size() > newSize)
  363. mFixList.pop_back();
  364. mFixStack.pop_back();
  365. mFixLoopStack.pop_back();
  366. }
  367. void fixLoop(U32 loopBlockStart, U32 breakPoint, U32 continuePoint);
  368. inline void addBreakLine(U32 lineNumber, U32 ip)
  369. {
  370. mBreakLines.push_back(lineNumber);
  371. mBreakLines.push_back(ip);
  372. }
  373. inline U32 getNumLineBreaks()
  374. {
  375. return mBreakLines.size() / 2;
  376. }
  377. void emitCodeStream(U32 *size, U32 **stream, U32 **lineBreaks);
  378. void reset();
  379. };
  380. #endif