emitbc.c 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901
  1. /*
  2. * This file is part of the MicroPython project, http://micropython.org/
  3. *
  4. * The MIT License (MIT)
  5. *
  6. * Copyright (c) 2013-2019 Damien P. George
  7. *
  8. * Permission is hereby granted, free of charge, to any person obtaining a copy
  9. * of this software and associated documentation files (the "Software"), to deal
  10. * in the Software without restriction, including without limitation the rights
  11. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  12. * copies of the Software, and to permit persons to whom the Software is
  13. * furnished to do so, subject to the following conditions:
  14. *
  15. * The above copyright notice and this permission notice shall be included in
  16. * all copies or substantial portions of the Software.
  17. *
  18. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  19. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  20. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  21. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  22. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  23. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  24. * THE SOFTWARE.
  25. */
  26. #include <stdbool.h>
  27. #include <stdint.h>
  28. #include <stdio.h>
  29. #include <string.h>
  30. #include <unistd.h>
  31. #include <assert.h>
  32. #include "py/mpstate.h"
  33. #include "py/smallint.h"
  34. #include "py/emit.h"
  35. #include "py/bc0.h"
  36. #if MICROPY_ENABLE_COMPILER
  37. #define DUMMY_DATA_SIZE (MP_ENCODE_UINT_MAX_BYTES)
  38. struct _emit_t {
  39. // Accessed as mp_obj_t, so must be aligned as such, and we rely on the
  40. // memory allocator returning a suitably aligned pointer.
  41. // Should work for cases when mp_obj_t is 64-bit on a 32-bit machine.
  42. byte dummy_data[DUMMY_DATA_SIZE];
  43. pass_kind_t pass : 8;
  44. // Set to true if the code generator should suppress emitted code due to it
  45. // being dead code. This can happen when opcodes immediately follow an
  46. // unconditional flow control (eg jump or raise).
  47. bool suppress;
  48. int stack_size;
  49. mp_emit_common_t *emit_common;
  50. scope_t *scope;
  51. mp_uint_t last_source_line_offset;
  52. mp_uint_t last_source_line;
  53. size_t max_num_labels;
  54. size_t *label_offsets;
  55. size_t code_info_offset;
  56. size_t code_info_size;
  57. size_t bytecode_offset;
  58. size_t bytecode_size;
  59. byte *code_base; // stores both byte code and code info
  60. bool overflow;
  61. size_t n_info;
  62. size_t n_cell;
  63. };
  64. emit_t *emit_bc_new(mp_emit_common_t *emit_common) {
  65. emit_t *emit = m_new0(emit_t, 1);
  66. emit->emit_common = emit_common;
  67. return emit;
  68. }
  69. void emit_bc_set_max_num_labels(emit_t *emit, mp_uint_t max_num_labels) {
  70. emit->max_num_labels = max_num_labels;
  71. emit->label_offsets = m_new(size_t, emit->max_num_labels);
  72. }
  73. void emit_bc_free(emit_t *emit) {
  74. m_del(size_t, emit->label_offsets, emit->max_num_labels);
  75. m_del_obj(emit_t, emit);
  76. }
  77. // all functions must go through this one to emit code info
  78. STATIC uint8_t *emit_get_cur_to_write_code_info(void *emit_in, size_t num_bytes_to_write) {
  79. emit_t *emit = emit_in;
  80. if (emit->pass < MP_PASS_EMIT) {
  81. emit->code_info_offset += num_bytes_to_write;
  82. return emit->dummy_data;
  83. } else {
  84. assert(emit->code_info_offset + num_bytes_to_write <= emit->code_info_size);
  85. byte *c = emit->code_base + emit->code_info_offset;
  86. emit->code_info_offset += num_bytes_to_write;
  87. return c;
  88. }
  89. }
  90. STATIC void emit_write_code_info_byte(emit_t *emit, byte val) {
  91. *emit_get_cur_to_write_code_info(emit, 1) = val;
  92. }
  93. STATIC void emit_write_code_info_qstr(emit_t *emit, qstr qst) {
  94. mp_encode_uint(emit, emit_get_cur_to_write_code_info, mp_emit_common_use_qstr(emit->emit_common, qst));
  95. }
  96. #if MICROPY_ENABLE_SOURCE_LINE
  97. STATIC void emit_write_code_info_bytes_lines(emit_t *emit, mp_uint_t bytes_to_skip, mp_uint_t lines_to_skip) {
  98. assert(bytes_to_skip > 0 || lines_to_skip > 0);
  99. while (bytes_to_skip > 0 || lines_to_skip > 0) {
  100. mp_uint_t b, l;
  101. if (lines_to_skip <= 6 || bytes_to_skip > 0xf) {
  102. // use 0b0LLBBBBB encoding
  103. b = MIN(bytes_to_skip, 0x1f);
  104. if (b < bytes_to_skip) {
  105. // we can't skip any lines until we skip all the bytes
  106. l = 0;
  107. } else {
  108. l = MIN(lines_to_skip, 0x3);
  109. }
  110. *emit_get_cur_to_write_code_info(emit, 1) = b | (l << 5);
  111. } else {
  112. // use 0b1LLLBBBB 0bLLLLLLLL encoding (l's LSB in second byte)
  113. b = MIN(bytes_to_skip, 0xf);
  114. l = MIN(lines_to_skip, 0x7ff);
  115. byte *ci = emit_get_cur_to_write_code_info(emit, 2);
  116. ci[0] = 0x80 | b | ((l >> 4) & 0x70);
  117. ci[1] = l;
  118. }
  119. bytes_to_skip -= b;
  120. lines_to_skip -= l;
  121. }
  122. }
  123. #endif
  124. // all functions must go through this one to emit byte code
  125. STATIC uint8_t *emit_get_cur_to_write_bytecode(void *emit_in, size_t num_bytes_to_write) {
  126. emit_t *emit = emit_in;
  127. if (emit->suppress) {
  128. return emit->dummy_data;
  129. }
  130. if (emit->pass < MP_PASS_EMIT) {
  131. emit->bytecode_offset += num_bytes_to_write;
  132. return emit->dummy_data;
  133. } else {
  134. assert(emit->bytecode_offset + num_bytes_to_write <= emit->bytecode_size);
  135. byte *c = emit->code_base + emit->code_info_size + emit->bytecode_offset;
  136. emit->bytecode_offset += num_bytes_to_write;
  137. return c;
  138. }
  139. }
  140. STATIC void emit_write_bytecode_raw_byte(emit_t *emit, byte b1) {
  141. byte *c = emit_get_cur_to_write_bytecode(emit, 1);
  142. c[0] = b1;
  143. }
  144. STATIC void emit_write_bytecode_byte(emit_t *emit, int stack_adj, byte b1) {
  145. mp_emit_bc_adjust_stack_size(emit, stack_adj);
  146. byte *c = emit_get_cur_to_write_bytecode(emit, 1);
  147. c[0] = b1;
  148. }
  149. // Similar to mp_encode_uint(), just some extra handling to encode sign
  150. STATIC void emit_write_bytecode_byte_int(emit_t *emit, int stack_adj, byte b1, mp_int_t num) {
  151. emit_write_bytecode_byte(emit, stack_adj, b1);
  152. // We store each 7 bits in a separate byte, and that's how many bytes needed
  153. byte buf[MP_ENCODE_UINT_MAX_BYTES];
  154. byte *p = buf + sizeof(buf);
  155. // We encode in little-ending order, but store in big-endian, to help decoding
  156. do {
  157. *--p = num & 0x7f;
  158. num >>= 7;
  159. } while (num != 0 && num != -1);
  160. // Make sure that highest bit we stored (mask 0x40) matches sign
  161. // of the number. If not, store extra byte just to encode sign
  162. if (num == -1 && (*p & 0x40) == 0) {
  163. *--p = 0x7f;
  164. } else if (num == 0 && (*p & 0x40) != 0) {
  165. *--p = 0;
  166. }
  167. byte *c = emit_get_cur_to_write_bytecode(emit, buf + sizeof(buf) - p);
  168. while (p != buf + sizeof(buf) - 1) {
  169. *c++ = *p++ | 0x80;
  170. }
  171. *c = *p;
  172. }
  173. STATIC void emit_write_bytecode_byte_uint(emit_t *emit, int stack_adj, byte b, mp_uint_t val) {
  174. emit_write_bytecode_byte(emit, stack_adj, b);
  175. mp_encode_uint(emit, emit_get_cur_to_write_bytecode, val);
  176. }
  177. STATIC void emit_write_bytecode_byte_const(emit_t *emit, int stack_adj, byte b, mp_uint_t n) {
  178. emit_write_bytecode_byte_uint(emit, stack_adj, b, n);
  179. }
  180. STATIC void emit_write_bytecode_byte_qstr(emit_t *emit, int stack_adj, byte b, qstr qst) {
  181. emit_write_bytecode_byte_uint(emit, stack_adj, b, mp_emit_common_use_qstr(emit->emit_common, qst));
  182. }
  183. STATIC void emit_write_bytecode_byte_obj(emit_t *emit, int stack_adj, byte b, mp_obj_t obj) {
  184. emit_write_bytecode_byte_const(emit, stack_adj, b, mp_emit_common_use_const_obj(emit->emit_common, obj));
  185. }
  186. STATIC void emit_write_bytecode_byte_child(emit_t *emit, int stack_adj, byte b, mp_raw_code_t *rc) {
  187. emit_write_bytecode_byte_const(emit, stack_adj, b,
  188. mp_emit_common_alloc_const_child(emit->emit_common, rc));
  189. #if MICROPY_PY_SYS_SETTRACE
  190. rc->line_of_definition = emit->last_source_line;
  191. #endif
  192. }
  193. // Emit a jump opcode to a destination label.
  194. // The offset to the label is relative to the ip following this instruction.
  195. // The offset is encoded as either 1 or 2 bytes, depending on how big it is.
  196. // The encoding of this jump opcode can change size from one pass to the next,
  197. // but it must only ever decrease in size on successive passes.
  198. STATIC void emit_write_bytecode_byte_label(emit_t *emit, int stack_adj, byte b1, mp_uint_t label) {
  199. mp_emit_bc_adjust_stack_size(emit, stack_adj);
  200. if (emit->suppress) {
  201. return;
  202. }
  203. // Determine if the jump offset is signed or unsigned, based on the opcode.
  204. const bool is_signed = b1 <= MP_BC_POP_JUMP_IF_FALSE;
  205. // Default to a 2-byte encoding (the largest) with an unknown jump offset.
  206. unsigned int jump_encoding_size = 1;
  207. ssize_t bytecode_offset = 0;
  208. // Compute the jump size and offset only when code size is known.
  209. if (emit->pass >= MP_PASS_CODE_SIZE) {
  210. // The -2 accounts for this jump opcode taking 2 bytes (at least).
  211. bytecode_offset = emit->label_offsets[label] - emit->bytecode_offset - 2;
  212. // Check if the bytecode_offset is small enough to use a 1-byte encoding.
  213. if ((is_signed && -64 <= bytecode_offset && bytecode_offset <= 63)
  214. || (!is_signed && (size_t)bytecode_offset <= 127)) {
  215. // Use a 1-byte jump offset.
  216. jump_encoding_size = 0;
  217. }
  218. // Adjust the offset depending on the size of the encoding of the offset.
  219. bytecode_offset -= jump_encoding_size;
  220. assert(is_signed || bytecode_offset >= 0);
  221. }
  222. // Emit the opcode.
  223. byte *c = emit_get_cur_to_write_bytecode(emit, 2 + jump_encoding_size);
  224. c[0] = b1;
  225. if (jump_encoding_size == 0) {
  226. if (is_signed) {
  227. bytecode_offset += 0x40;
  228. }
  229. assert(0 <= bytecode_offset && bytecode_offset <= 0x7f);
  230. c[1] = bytecode_offset;
  231. } else {
  232. if (is_signed) {
  233. bytecode_offset += 0x4000;
  234. }
  235. if (emit->pass == MP_PASS_EMIT && !(0 <= bytecode_offset && bytecode_offset <= 0x7fff)) {
  236. emit->overflow = true;
  237. }
  238. c[1] = 0x80 | (bytecode_offset & 0x7f);
  239. c[2] = bytecode_offset >> 7;
  240. }
  241. }
  242. void mp_emit_bc_start_pass(emit_t *emit, pass_kind_t pass, scope_t *scope) {
  243. emit->pass = pass;
  244. emit->stack_size = 0;
  245. emit->suppress = false;
  246. emit->scope = scope;
  247. emit->last_source_line_offset = 0;
  248. emit->last_source_line = 1;
  249. emit->bytecode_offset = 0;
  250. emit->code_info_offset = 0;
  251. emit->overflow = false;
  252. // Write local state size, exception stack size, scope flags and number of arguments
  253. {
  254. mp_uint_t n_state = scope->num_locals + scope->stack_size;
  255. if (n_state == 0) {
  256. // Need at least 1 entry in the state, in the case an exception is
  257. // propagated through this function, the exception is returned in
  258. // the highest slot in the state (fastn[0], see vm.c).
  259. n_state = 1;
  260. }
  261. #if MICROPY_DEBUG_VM_STACK_OVERFLOW
  262. // An extra slot in the stack is needed to detect VM stack overflow
  263. n_state += 1;
  264. #endif
  265. size_t n_exc_stack = scope->exc_stack_size;
  266. MP_BC_PRELUDE_SIG_ENCODE(n_state, n_exc_stack, scope, emit_write_code_info_byte, emit);
  267. }
  268. // Write number of cells and size of the source code info
  269. if (emit->pass >= MP_PASS_CODE_SIZE) {
  270. size_t n_info = emit->n_info;
  271. size_t n_cell = emit->n_cell;
  272. MP_BC_PRELUDE_SIZE_ENCODE(n_info, n_cell, emit_write_code_info_byte, emit);
  273. }
  274. emit->n_info = emit->code_info_offset;
  275. // Write the name of this function.
  276. emit_write_code_info_qstr(emit, scope->simple_name);
  277. // Write argument names, needed to resolve positional args passed as keywords.
  278. {
  279. // For a given argument position (indexed by i) we need to find the
  280. // corresponding id_info which is a parameter, as it has the correct
  281. // qstr name to use as the argument name. Note that it's not a simple
  282. // 1-1 mapping (ie i!=j in general) because of possible closed-over
  283. // variables. In the case that the argument i has no corresponding
  284. // parameter we use "*" as its name (since no argument can ever be named
  285. // "*"). We could use a blank qstr but "*" is better for debugging.
  286. // Note: there is some wasted RAM here for the case of storing a qstr
  287. // for each closed-over variable, and maybe there is a better way to do
  288. // it, but that would require changes to mp_setup_code_state.
  289. for (int i = 0; i < scope->num_pos_args + scope->num_kwonly_args; i++) {
  290. qstr qst = MP_QSTR__star_;
  291. for (int j = 0; j < scope->id_info_len; ++j) {
  292. id_info_t *id = &scope->id_info[j];
  293. if ((id->flags & ID_FLAG_IS_PARAM) && id->local_num == i) {
  294. qst = id->qst;
  295. break;
  296. }
  297. }
  298. emit_write_code_info_qstr(emit, qst);
  299. }
  300. }
  301. }
  302. bool mp_emit_bc_end_pass(emit_t *emit) {
  303. if (emit->pass == MP_PASS_SCOPE) {
  304. return true;
  305. }
  306. // check stack is back to zero size
  307. assert(emit->stack_size == 0);
  308. // Calculate size of source code info section
  309. emit->n_info = emit->code_info_offset - emit->n_info;
  310. // Emit closure section of prelude
  311. emit->n_cell = 0;
  312. for (size_t i = 0; i < emit->scope->id_info_len; ++i) {
  313. id_info_t *id = &emit->scope->id_info[i];
  314. if (id->kind == ID_INFO_KIND_CELL) {
  315. assert(id->local_num <= 255);
  316. emit_write_code_info_byte(emit, id->local_num); // write the local which should be converted to a cell
  317. ++emit->n_cell;
  318. }
  319. }
  320. if (emit->pass == MP_PASS_CODE_SIZE) {
  321. // calculate size of total code-info + bytecode, in bytes
  322. emit->code_info_size = emit->code_info_offset;
  323. emit->bytecode_size = emit->bytecode_offset;
  324. emit->code_base = m_new0(byte, emit->code_info_size + emit->bytecode_size);
  325. } else if (emit->pass == MP_PASS_EMIT) {
  326. // Code info and/or bytecode can shrink during this pass.
  327. assert(emit->code_info_offset <= emit->code_info_size);
  328. assert(emit->bytecode_offset <= emit->bytecode_size);
  329. if (emit->code_info_offset != emit->code_info_size
  330. || emit->bytecode_offset != emit->bytecode_size) {
  331. // Code info and/or bytecode changed size in this pass, so request the
  332. // compiler to do another pass with these updated sizes.
  333. emit->code_info_size = emit->code_info_offset;
  334. emit->bytecode_size = emit->bytecode_offset;
  335. return false;
  336. }
  337. if (emit->overflow) {
  338. mp_raise_msg(&mp_type_RuntimeError, MP_ERROR_TEXT("bytecode overflow"));
  339. }
  340. // Bytecode is finalised, assign it to the raw code object.
  341. mp_emit_glue_assign_bytecode(emit->scope->raw_code, emit->code_base,
  342. #if MICROPY_PERSISTENT_CODE_SAVE || MICROPY_DEBUG_PRINTERS
  343. emit->code_info_size + emit->bytecode_size,
  344. #endif
  345. emit->emit_common->children,
  346. #if MICROPY_PERSISTENT_CODE_SAVE
  347. emit->emit_common->ct_cur_child,
  348. #endif
  349. emit->scope->scope_flags);
  350. }
  351. return true;
  352. }
  353. void mp_emit_bc_adjust_stack_size(emit_t *emit, mp_int_t delta) {
  354. if (emit->pass == MP_PASS_SCOPE) {
  355. return;
  356. }
  357. assert((mp_int_t)emit->stack_size + delta >= 0);
  358. emit->stack_size += delta;
  359. if (emit->stack_size > emit->scope->stack_size) {
  360. emit->scope->stack_size = emit->stack_size;
  361. }
  362. }
  363. void mp_emit_bc_set_source_line(emit_t *emit, mp_uint_t source_line) {
  364. #if MICROPY_ENABLE_SOURCE_LINE
  365. if (MP_STATE_VM(mp_optimise_value) >= 3) {
  366. // If we compile with -O3, don't store line numbers.
  367. return;
  368. }
  369. if (source_line > emit->last_source_line) {
  370. mp_uint_t bytes_to_skip = emit->bytecode_offset - emit->last_source_line_offset;
  371. mp_uint_t lines_to_skip = source_line - emit->last_source_line;
  372. emit_write_code_info_bytes_lines(emit, bytes_to_skip, lines_to_skip);
  373. emit->last_source_line_offset = emit->bytecode_offset;
  374. emit->last_source_line = source_line;
  375. }
  376. #else
  377. (void)emit;
  378. (void)source_line;
  379. #endif
  380. }
  381. void mp_emit_bc_label_assign(emit_t *emit, mp_uint_t l) {
  382. // Assigning a label ends any dead-code region, and all following opcodes
  383. // should be emitted (until another unconditional flow control).
  384. emit->suppress = false;
  385. mp_emit_bc_adjust_stack_size(emit, 0);
  386. if (emit->pass == MP_PASS_SCOPE) {
  387. return;
  388. }
  389. // Label offsets can change from one pass to the next, but they must only
  390. // decrease (ie code can only shrink). There will be multiple MP_PASS_EMIT
  391. // stages until the labels no longer change, which is when the code size
  392. // stays constant after a MP_PASS_EMIT.
  393. assert(l < emit->max_num_labels);
  394. assert(emit->pass == MP_PASS_STACK_SIZE || emit->bytecode_offset <= emit->label_offsets[l]);
  395. // Assign label offset.
  396. emit->label_offsets[l] = emit->bytecode_offset;
  397. }
  398. void mp_emit_bc_import(emit_t *emit, qstr qst, int kind) {
  399. MP_STATIC_ASSERT(MP_BC_IMPORT_NAME + MP_EMIT_IMPORT_NAME == MP_BC_IMPORT_NAME);
  400. MP_STATIC_ASSERT(MP_BC_IMPORT_NAME + MP_EMIT_IMPORT_FROM == MP_BC_IMPORT_FROM);
  401. int stack_adj = kind == MP_EMIT_IMPORT_FROM ? 1 : -1;
  402. if (kind == MP_EMIT_IMPORT_STAR) {
  403. emit_write_bytecode_byte(emit, stack_adj, MP_BC_IMPORT_STAR);
  404. } else {
  405. emit_write_bytecode_byte_qstr(emit, stack_adj, MP_BC_IMPORT_NAME + kind, qst);
  406. }
  407. }
  408. void mp_emit_bc_load_const_tok(emit_t *emit, mp_token_kind_t tok) {
  409. MP_STATIC_ASSERT(MP_BC_LOAD_CONST_FALSE + (MP_TOKEN_KW_NONE - MP_TOKEN_KW_FALSE) == MP_BC_LOAD_CONST_NONE);
  410. MP_STATIC_ASSERT(MP_BC_LOAD_CONST_FALSE + (MP_TOKEN_KW_TRUE - MP_TOKEN_KW_FALSE) == MP_BC_LOAD_CONST_TRUE);
  411. if (tok == MP_TOKEN_ELLIPSIS) {
  412. emit_write_bytecode_byte_obj(emit, 1, MP_BC_LOAD_CONST_OBJ, MP_OBJ_FROM_PTR(&mp_const_ellipsis_obj));
  413. } else {
  414. emit_write_bytecode_byte(emit, 1, MP_BC_LOAD_CONST_FALSE + (tok - MP_TOKEN_KW_FALSE));
  415. }
  416. }
  417. void mp_emit_bc_load_const_small_int(emit_t *emit, mp_int_t arg) {
  418. assert(MP_SMALL_INT_FITS(arg));
  419. if (-MP_BC_LOAD_CONST_SMALL_INT_MULTI_EXCESS <= arg
  420. && arg < MP_BC_LOAD_CONST_SMALL_INT_MULTI_NUM - MP_BC_LOAD_CONST_SMALL_INT_MULTI_EXCESS) {
  421. emit_write_bytecode_byte(emit, 1,
  422. MP_BC_LOAD_CONST_SMALL_INT_MULTI + MP_BC_LOAD_CONST_SMALL_INT_MULTI_EXCESS + arg);
  423. } else {
  424. emit_write_bytecode_byte_int(emit, 1, MP_BC_LOAD_CONST_SMALL_INT, arg);
  425. }
  426. }
  427. void mp_emit_bc_load_const_str(emit_t *emit, qstr qst) {
  428. emit_write_bytecode_byte_qstr(emit, 1, MP_BC_LOAD_CONST_STRING, qst);
  429. }
  430. void mp_emit_bc_load_const_obj(emit_t *emit, mp_obj_t obj) {
  431. emit_write_bytecode_byte_obj(emit, 1, MP_BC_LOAD_CONST_OBJ, obj);
  432. }
  433. void mp_emit_bc_load_null(emit_t *emit) {
  434. emit_write_bytecode_byte(emit, 1, MP_BC_LOAD_NULL);
  435. }
  436. void mp_emit_bc_load_local(emit_t *emit, qstr qst, mp_uint_t local_num, int kind) {
  437. MP_STATIC_ASSERT(MP_BC_LOAD_FAST_N + MP_EMIT_IDOP_LOCAL_FAST == MP_BC_LOAD_FAST_N);
  438. MP_STATIC_ASSERT(MP_BC_LOAD_FAST_N + MP_EMIT_IDOP_LOCAL_DEREF == MP_BC_LOAD_DEREF);
  439. (void)qst;
  440. if (kind == MP_EMIT_IDOP_LOCAL_FAST && local_num <= 15) {
  441. emit_write_bytecode_byte(emit, 1, MP_BC_LOAD_FAST_MULTI + local_num);
  442. } else {
  443. emit_write_bytecode_byte_uint(emit, 1, MP_BC_LOAD_FAST_N + kind, local_num);
  444. }
  445. }
  446. void mp_emit_bc_load_global(emit_t *emit, qstr qst, int kind) {
  447. MP_STATIC_ASSERT(MP_BC_LOAD_NAME + MP_EMIT_IDOP_GLOBAL_NAME == MP_BC_LOAD_NAME);
  448. MP_STATIC_ASSERT(MP_BC_LOAD_NAME + MP_EMIT_IDOP_GLOBAL_GLOBAL == MP_BC_LOAD_GLOBAL);
  449. (void)qst;
  450. emit_write_bytecode_byte_qstr(emit, 1, MP_BC_LOAD_NAME + kind, qst);
  451. }
  452. void mp_emit_bc_load_method(emit_t *emit, qstr qst, bool is_super) {
  453. int stack_adj = 1 - 2 * is_super;
  454. emit_write_bytecode_byte_qstr(emit, stack_adj, is_super ? MP_BC_LOAD_SUPER_METHOD : MP_BC_LOAD_METHOD, qst);
  455. }
  456. void mp_emit_bc_load_build_class(emit_t *emit) {
  457. emit_write_bytecode_byte(emit, 1, MP_BC_LOAD_BUILD_CLASS);
  458. }
  459. void mp_emit_bc_subscr(emit_t *emit, int kind) {
  460. if (kind == MP_EMIT_SUBSCR_LOAD) {
  461. emit_write_bytecode_byte(emit, -1, MP_BC_LOAD_SUBSCR);
  462. } else {
  463. if (kind == MP_EMIT_SUBSCR_DELETE) {
  464. mp_emit_bc_load_null(emit);
  465. mp_emit_bc_rot_three(emit);
  466. }
  467. emit_write_bytecode_byte(emit, -3, MP_BC_STORE_SUBSCR);
  468. }
  469. }
  470. void mp_emit_bc_attr(emit_t *emit, qstr qst, int kind) {
  471. if (kind == MP_EMIT_ATTR_LOAD) {
  472. emit_write_bytecode_byte_qstr(emit, 0, MP_BC_LOAD_ATTR, qst);
  473. } else {
  474. if (kind == MP_EMIT_ATTR_DELETE) {
  475. mp_emit_bc_load_null(emit);
  476. mp_emit_bc_rot_two(emit);
  477. }
  478. emit_write_bytecode_byte_qstr(emit, -2, MP_BC_STORE_ATTR, qst);
  479. }
  480. }
  481. void mp_emit_bc_store_local(emit_t *emit, qstr qst, mp_uint_t local_num, int kind) {
  482. MP_STATIC_ASSERT(MP_BC_STORE_FAST_N + MP_EMIT_IDOP_LOCAL_FAST == MP_BC_STORE_FAST_N);
  483. MP_STATIC_ASSERT(MP_BC_STORE_FAST_N + MP_EMIT_IDOP_LOCAL_DEREF == MP_BC_STORE_DEREF);
  484. (void)qst;
  485. if (kind == MP_EMIT_IDOP_LOCAL_FAST && local_num <= 15) {
  486. emit_write_bytecode_byte(emit, -1, MP_BC_STORE_FAST_MULTI + local_num);
  487. } else {
  488. emit_write_bytecode_byte_uint(emit, -1, MP_BC_STORE_FAST_N + kind, local_num);
  489. }
  490. }
  491. void mp_emit_bc_store_global(emit_t *emit, qstr qst, int kind) {
  492. MP_STATIC_ASSERT(MP_BC_STORE_NAME + MP_EMIT_IDOP_GLOBAL_NAME == MP_BC_STORE_NAME);
  493. MP_STATIC_ASSERT(MP_BC_STORE_NAME + MP_EMIT_IDOP_GLOBAL_GLOBAL == MP_BC_STORE_GLOBAL);
  494. emit_write_bytecode_byte_qstr(emit, -1, MP_BC_STORE_NAME + kind, qst);
  495. }
  496. void mp_emit_bc_delete_local(emit_t *emit, qstr qst, mp_uint_t local_num, int kind) {
  497. MP_STATIC_ASSERT(MP_BC_DELETE_FAST + MP_EMIT_IDOP_LOCAL_FAST == MP_BC_DELETE_FAST);
  498. MP_STATIC_ASSERT(MP_BC_DELETE_FAST + MP_EMIT_IDOP_LOCAL_DEREF == MP_BC_DELETE_DEREF);
  499. (void)qst;
  500. emit_write_bytecode_byte_uint(emit, 0, MP_BC_DELETE_FAST + kind, local_num);
  501. }
  502. void mp_emit_bc_delete_global(emit_t *emit, qstr qst, int kind) {
  503. MP_STATIC_ASSERT(MP_BC_DELETE_NAME + MP_EMIT_IDOP_GLOBAL_NAME == MP_BC_DELETE_NAME);
  504. MP_STATIC_ASSERT(MP_BC_DELETE_NAME + MP_EMIT_IDOP_GLOBAL_GLOBAL == MP_BC_DELETE_GLOBAL);
  505. emit_write_bytecode_byte_qstr(emit, 0, MP_BC_DELETE_NAME + kind, qst);
  506. }
  507. void mp_emit_bc_dup_top(emit_t *emit) {
  508. emit_write_bytecode_byte(emit, 1, MP_BC_DUP_TOP);
  509. }
  510. void mp_emit_bc_dup_top_two(emit_t *emit) {
  511. emit_write_bytecode_byte(emit, 2, MP_BC_DUP_TOP_TWO);
  512. }
  513. void mp_emit_bc_pop_top(emit_t *emit) {
  514. emit_write_bytecode_byte(emit, -1, MP_BC_POP_TOP);
  515. }
  516. void mp_emit_bc_rot_two(emit_t *emit) {
  517. emit_write_bytecode_byte(emit, 0, MP_BC_ROT_TWO);
  518. }
  519. void mp_emit_bc_rot_three(emit_t *emit) {
  520. emit_write_bytecode_byte(emit, 0, MP_BC_ROT_THREE);
  521. }
  522. void mp_emit_bc_jump(emit_t *emit, mp_uint_t label) {
  523. emit_write_bytecode_byte_label(emit, 0, MP_BC_JUMP, label);
  524. emit->suppress = true;
  525. }
  526. void mp_emit_bc_pop_jump_if(emit_t *emit, bool cond, mp_uint_t label) {
  527. if (cond) {
  528. emit_write_bytecode_byte_label(emit, -1, MP_BC_POP_JUMP_IF_TRUE, label);
  529. } else {
  530. emit_write_bytecode_byte_label(emit, -1, MP_BC_POP_JUMP_IF_FALSE, label);
  531. }
  532. }
  533. void mp_emit_bc_jump_if_or_pop(emit_t *emit, bool cond, mp_uint_t label) {
  534. if (cond) {
  535. emit_write_bytecode_byte_label(emit, -1, MP_BC_JUMP_IF_TRUE_OR_POP, label);
  536. } else {
  537. emit_write_bytecode_byte_label(emit, -1, MP_BC_JUMP_IF_FALSE_OR_POP, label);
  538. }
  539. }
  540. void mp_emit_bc_unwind_jump(emit_t *emit, mp_uint_t label, mp_uint_t except_depth) {
  541. if (except_depth == 0) {
  542. if (label & MP_EMIT_BREAK_FROM_FOR) {
  543. // need to pop the iterator if we are breaking out of a for loop
  544. emit_write_bytecode_raw_byte(emit, MP_BC_POP_TOP);
  545. // also pop the iter_buf
  546. for (size_t i = 0; i < MP_OBJ_ITER_BUF_NSLOTS - 1; ++i) {
  547. emit_write_bytecode_raw_byte(emit, MP_BC_POP_TOP);
  548. }
  549. }
  550. emit_write_bytecode_byte_label(emit, 0, MP_BC_JUMP, label & ~MP_EMIT_BREAK_FROM_FOR);
  551. } else {
  552. emit_write_bytecode_byte_label(emit, 0, MP_BC_UNWIND_JUMP, label & ~MP_EMIT_BREAK_FROM_FOR);
  553. emit_write_bytecode_raw_byte(emit, ((label & MP_EMIT_BREAK_FROM_FOR) ? 0x80 : 0) | except_depth);
  554. }
  555. emit->suppress = true;
  556. }
  557. void mp_emit_bc_setup_block(emit_t *emit, mp_uint_t label, int kind) {
  558. MP_STATIC_ASSERT(MP_BC_SETUP_WITH + MP_EMIT_SETUP_BLOCK_WITH == MP_BC_SETUP_WITH);
  559. MP_STATIC_ASSERT(MP_BC_SETUP_WITH + MP_EMIT_SETUP_BLOCK_EXCEPT == MP_BC_SETUP_EXCEPT);
  560. MP_STATIC_ASSERT(MP_BC_SETUP_WITH + MP_EMIT_SETUP_BLOCK_FINALLY == MP_BC_SETUP_FINALLY);
  561. // The SETUP_WITH opcode pops ctx_mgr from the top of the stack
  562. // and then pushes 3 entries: __exit__, ctx_mgr, as_value.
  563. int stack_adj = kind == MP_EMIT_SETUP_BLOCK_WITH ? 2 : 0;
  564. emit_write_bytecode_byte_label(emit, stack_adj, MP_BC_SETUP_WITH + kind, label);
  565. }
  566. void mp_emit_bc_with_cleanup(emit_t *emit, mp_uint_t label) {
  567. mp_emit_bc_load_const_tok(emit, MP_TOKEN_KW_NONE);
  568. mp_emit_bc_label_assign(emit, label);
  569. // The +2 is to ensure we have enough stack space to call the __exit__ method
  570. emit_write_bytecode_byte(emit, 2, MP_BC_WITH_CLEANUP);
  571. // Cancel the +2 above, plus the +2 from mp_emit_bc_setup_block(MP_EMIT_SETUP_BLOCK_WITH)
  572. mp_emit_bc_adjust_stack_size(emit, -4);
  573. }
  574. void mp_emit_bc_end_finally(emit_t *emit) {
  575. emit_write_bytecode_byte(emit, -1, MP_BC_END_FINALLY);
  576. }
  577. void mp_emit_bc_get_iter(emit_t *emit, bool use_stack) {
  578. int stack_adj = use_stack ? MP_OBJ_ITER_BUF_NSLOTS - 1 : 0;
  579. emit_write_bytecode_byte(emit, stack_adj, use_stack ? MP_BC_GET_ITER_STACK : MP_BC_GET_ITER);
  580. }
  581. void mp_emit_bc_for_iter(emit_t *emit, mp_uint_t label) {
  582. emit_write_bytecode_byte_label(emit, 1, MP_BC_FOR_ITER, label);
  583. }
  584. void mp_emit_bc_for_iter_end(emit_t *emit) {
  585. mp_emit_bc_adjust_stack_size(emit, -MP_OBJ_ITER_BUF_NSLOTS);
  586. }
  587. void mp_emit_bc_pop_except_jump(emit_t *emit, mp_uint_t label, bool within_exc_handler) {
  588. (void)within_exc_handler;
  589. emit_write_bytecode_byte_label(emit, 0, MP_BC_POP_EXCEPT_JUMP, label);
  590. emit->suppress = true;
  591. }
  592. void mp_emit_bc_unary_op(emit_t *emit, mp_unary_op_t op) {
  593. emit_write_bytecode_byte(emit, 0, MP_BC_UNARY_OP_MULTI + op);
  594. }
  595. void mp_emit_bc_binary_op(emit_t *emit, mp_binary_op_t op) {
  596. bool invert = false;
  597. if (op == MP_BINARY_OP_NOT_IN) {
  598. invert = true;
  599. op = MP_BINARY_OP_IN;
  600. } else if (op == MP_BINARY_OP_IS_NOT) {
  601. invert = true;
  602. op = MP_BINARY_OP_IS;
  603. }
  604. emit_write_bytecode_byte(emit, -1, MP_BC_BINARY_OP_MULTI + op);
  605. if (invert) {
  606. emit_write_bytecode_byte(emit, 0, MP_BC_UNARY_OP_MULTI + MP_UNARY_OP_NOT);
  607. }
  608. }
  609. void mp_emit_bc_build(emit_t *emit, mp_uint_t n_args, int kind) {
  610. MP_STATIC_ASSERT(MP_BC_BUILD_TUPLE + MP_EMIT_BUILD_TUPLE == MP_BC_BUILD_TUPLE);
  611. MP_STATIC_ASSERT(MP_BC_BUILD_TUPLE + MP_EMIT_BUILD_LIST == MP_BC_BUILD_LIST);
  612. MP_STATIC_ASSERT(MP_BC_BUILD_TUPLE + MP_EMIT_BUILD_MAP == MP_BC_BUILD_MAP);
  613. MP_STATIC_ASSERT(MP_BC_BUILD_TUPLE + MP_EMIT_BUILD_SET == MP_BC_BUILD_SET);
  614. MP_STATIC_ASSERT(MP_BC_BUILD_TUPLE + MP_EMIT_BUILD_SLICE == MP_BC_BUILD_SLICE);
  615. int stack_adj = kind == MP_EMIT_BUILD_MAP ? 1 : 1 - n_args;
  616. emit_write_bytecode_byte_uint(emit, stack_adj, MP_BC_BUILD_TUPLE + kind, n_args);
  617. }
  618. void mp_emit_bc_store_map(emit_t *emit) {
  619. emit_write_bytecode_byte(emit, -2, MP_BC_STORE_MAP);
  620. }
  621. void mp_emit_bc_store_comp(emit_t *emit, scope_kind_t kind, mp_uint_t collection_stack_index) {
  622. int t;
  623. int n;
  624. if (kind == SCOPE_LIST_COMP) {
  625. n = 0;
  626. t = 0;
  627. } else if (!MICROPY_PY_BUILTINS_SET || kind == SCOPE_DICT_COMP) {
  628. n = 1;
  629. t = 1;
  630. } else if (MICROPY_PY_BUILTINS_SET) {
  631. n = 0;
  632. t = 2;
  633. }
  634. // the lower 2 bits of the opcode argument indicate the collection type
  635. emit_write_bytecode_byte_uint(emit, -1 - n, MP_BC_STORE_COMP, ((collection_stack_index + n) << 2) | t);
  636. }
  637. void mp_emit_bc_unpack_sequence(emit_t *emit, mp_uint_t n_args) {
  638. emit_write_bytecode_byte_uint(emit, -1 + n_args, MP_BC_UNPACK_SEQUENCE, n_args);
  639. }
  640. void mp_emit_bc_unpack_ex(emit_t *emit, mp_uint_t n_left, mp_uint_t n_right) {
  641. emit_write_bytecode_byte_uint(emit, -1 + n_left + n_right + 1, MP_BC_UNPACK_EX, n_left | (n_right << 8));
  642. }
  643. void mp_emit_bc_make_function(emit_t *emit, scope_t *scope, mp_uint_t n_pos_defaults, mp_uint_t n_kw_defaults) {
  644. if (n_pos_defaults == 0 && n_kw_defaults == 0) {
  645. emit_write_bytecode_byte_child(emit, 1, MP_BC_MAKE_FUNCTION, scope->raw_code);
  646. } else {
  647. emit_write_bytecode_byte_child(emit, -1, MP_BC_MAKE_FUNCTION_DEFARGS, scope->raw_code);
  648. }
  649. }
  650. void mp_emit_bc_make_closure(emit_t *emit, scope_t *scope, mp_uint_t n_closed_over, mp_uint_t n_pos_defaults, mp_uint_t n_kw_defaults) {
  651. if (n_pos_defaults == 0 && n_kw_defaults == 0) {
  652. int stack_adj = -n_closed_over + 1;
  653. emit_write_bytecode_byte_child(emit, stack_adj, MP_BC_MAKE_CLOSURE, scope->raw_code);
  654. emit_write_bytecode_raw_byte(emit, n_closed_over);
  655. } else {
  656. assert(n_closed_over <= 255);
  657. int stack_adj = -2 - (mp_int_t)n_closed_over + 1;
  658. emit_write_bytecode_byte_child(emit, stack_adj, MP_BC_MAKE_CLOSURE_DEFARGS, scope->raw_code);
  659. emit_write_bytecode_raw_byte(emit, n_closed_over);
  660. }
  661. }
  662. STATIC void emit_bc_call_function_method_helper(emit_t *emit, int stack_adj, mp_uint_t bytecode_base, mp_uint_t n_positional, mp_uint_t n_keyword, mp_uint_t star_flags) {
  663. if (star_flags) {
  664. // each positional arg is one object, each kwarg is two objects, the key
  665. // and the value and one extra object for the star args bitmap.
  666. stack_adj -= (int)n_positional + 2 * (int)n_keyword + 1;
  667. emit_write_bytecode_byte_uint(emit, stack_adj, bytecode_base + 1, (n_keyword << 8) | n_positional); // TODO make it 2 separate uints?
  668. } else {
  669. stack_adj -= (int)n_positional + 2 * (int)n_keyword;
  670. emit_write_bytecode_byte_uint(emit, stack_adj, bytecode_base, (n_keyword << 8) | n_positional); // TODO make it 2 separate uints?
  671. }
  672. }
  673. void mp_emit_bc_call_function(emit_t *emit, mp_uint_t n_positional, mp_uint_t n_keyword, mp_uint_t star_flags) {
  674. emit_bc_call_function_method_helper(emit, 0, MP_BC_CALL_FUNCTION, n_positional, n_keyword, star_flags);
  675. }
  676. void mp_emit_bc_call_method(emit_t *emit, mp_uint_t n_positional, mp_uint_t n_keyword, mp_uint_t star_flags) {
  677. emit_bc_call_function_method_helper(emit, -1, MP_BC_CALL_METHOD, n_positional, n_keyword, star_flags);
  678. }
  679. void mp_emit_bc_return_value(emit_t *emit) {
  680. emit_write_bytecode_byte(emit, -1, MP_BC_RETURN_VALUE);
  681. emit->suppress = true;
  682. }
  683. void mp_emit_bc_raise_varargs(emit_t *emit, mp_uint_t n_args) {
  684. MP_STATIC_ASSERT(MP_BC_RAISE_LAST + 1 == MP_BC_RAISE_OBJ);
  685. MP_STATIC_ASSERT(MP_BC_RAISE_LAST + 2 == MP_BC_RAISE_FROM);
  686. assert(n_args <= 2);
  687. emit_write_bytecode_byte(emit, -n_args, MP_BC_RAISE_LAST + n_args);
  688. emit->suppress = true;
  689. }
  690. void mp_emit_bc_yield(emit_t *emit, int kind) {
  691. MP_STATIC_ASSERT(MP_BC_YIELD_VALUE + 1 == MP_BC_YIELD_FROM);
  692. emit_write_bytecode_byte(emit, -kind, MP_BC_YIELD_VALUE + kind);
  693. emit->scope->scope_flags |= MP_SCOPE_FLAG_GENERATOR;
  694. }
  695. void mp_emit_bc_start_except_handler(emit_t *emit) {
  696. mp_emit_bc_adjust_stack_size(emit, 4); // stack adjust for the exception instance, +3 for possible UNWIND_JUMP state
  697. }
  698. void mp_emit_bc_end_except_handler(emit_t *emit) {
  699. mp_emit_bc_adjust_stack_size(emit, -3); // stack adjust
  700. }
  701. #if MICROPY_EMIT_NATIVE
  702. const emit_method_table_t emit_bc_method_table = {
  703. #if MICROPY_DYNAMIC_COMPILER
  704. NULL,
  705. NULL,
  706. #endif
  707. mp_emit_bc_start_pass,
  708. mp_emit_bc_end_pass,
  709. mp_emit_bc_adjust_stack_size,
  710. mp_emit_bc_set_source_line,
  711. {
  712. mp_emit_bc_load_local,
  713. mp_emit_bc_load_global,
  714. },
  715. {
  716. mp_emit_bc_store_local,
  717. mp_emit_bc_store_global,
  718. },
  719. {
  720. mp_emit_bc_delete_local,
  721. mp_emit_bc_delete_global,
  722. },
  723. mp_emit_bc_label_assign,
  724. mp_emit_bc_import,
  725. mp_emit_bc_load_const_tok,
  726. mp_emit_bc_load_const_small_int,
  727. mp_emit_bc_load_const_str,
  728. mp_emit_bc_load_const_obj,
  729. mp_emit_bc_load_null,
  730. mp_emit_bc_load_method,
  731. mp_emit_bc_load_build_class,
  732. mp_emit_bc_subscr,
  733. mp_emit_bc_attr,
  734. mp_emit_bc_dup_top,
  735. mp_emit_bc_dup_top_two,
  736. mp_emit_bc_pop_top,
  737. mp_emit_bc_rot_two,
  738. mp_emit_bc_rot_three,
  739. mp_emit_bc_jump,
  740. mp_emit_bc_pop_jump_if,
  741. mp_emit_bc_jump_if_or_pop,
  742. mp_emit_bc_unwind_jump,
  743. mp_emit_bc_setup_block,
  744. mp_emit_bc_with_cleanup,
  745. mp_emit_bc_end_finally,
  746. mp_emit_bc_get_iter,
  747. mp_emit_bc_for_iter,
  748. mp_emit_bc_for_iter_end,
  749. mp_emit_bc_pop_except_jump,
  750. mp_emit_bc_unary_op,
  751. mp_emit_bc_binary_op,
  752. mp_emit_bc_build,
  753. mp_emit_bc_store_map,
  754. mp_emit_bc_store_comp,
  755. mp_emit_bc_unpack_sequence,
  756. mp_emit_bc_unpack_ex,
  757. mp_emit_bc_make_function,
  758. mp_emit_bc_make_closure,
  759. mp_emit_bc_call_function,
  760. mp_emit_bc_call_method,
  761. mp_emit_bc_return_value,
  762. mp_emit_bc_raise_varargs,
  763. mp_emit_bc_yield,
  764. mp_emit_bc_start_except_handler,
  765. mp_emit_bc_end_except_handler,
  766. };
  767. #else
  768. const mp_emit_method_table_id_ops_t mp_emit_bc_method_table_load_id_ops = {
  769. mp_emit_bc_load_local,
  770. mp_emit_bc_load_global,
  771. };
  772. const mp_emit_method_table_id_ops_t mp_emit_bc_method_table_store_id_ops = {
  773. mp_emit_bc_store_local,
  774. mp_emit_bc_store_global,
  775. };
  776. const mp_emit_method_table_id_ops_t mp_emit_bc_method_table_delete_id_ops = {
  777. mp_emit_bc_delete_local,
  778. mp_emit_bc_delete_global,
  779. };
  780. #endif
  781. #endif // MICROPY_ENABLE_COMPILER