bytecode_transformation.py 49 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364
  1. # mypy: allow-untyped-defs
  2. import copy
  3. import dataclasses
  4. import dis
  5. import itertools
  6. import sys
  7. import types
  8. from typing import Any, Callable, cast, Dict, Iterator, List, Optional, Tuple
  9. from .bytecode_analysis import (
  10. get_indexof,
  11. propagate_line_nums,
  12. remove_extra_line_nums,
  13. stacksize_analysis,
  14. )
  15. @dataclasses.dataclass
  16. class InstructionExnTabEntry:
  17. start: "Instruction"
  18. end: "Instruction"
  19. target: "Instruction"
  20. depth: int
  21. lasti: bool
  22. def __repr__(self) -> str:
  23. return (
  24. f"InstructionExnTabEntry(start={self.start.short_inst_repr()}, "
  25. f"end={self.end.short_inst_repr()}, "
  26. f"target={self.target.short_inst_repr()}, "
  27. f"depth={self.depth}, lasti={self.lasti})"
  28. )
  29. def __eq__(self, o) -> bool:
  30. return (
  31. self.start is o.start
  32. and self.end is o.end
  33. and self.target is o.target
  34. and self.depth == o.depth
  35. and self.lasti == o.lasti
  36. )
  37. @dataclasses.dataclass
  38. class Instruction:
  39. """A mutable version of dis.Instruction"""
  40. opcode: int
  41. opname: str
  42. arg: Optional[int]
  43. argval: Any
  44. offset: Optional[int] = None
  45. starts_line: Optional[int] = None
  46. is_jump_target: bool = False
  47. positions: Optional["dis.Positions"] = None
  48. # extra fields to make modification easier:
  49. target: Optional["Instruction"] = None
  50. exn_tab_entry: Optional[InstructionExnTabEntry] = None
  51. def __hash__(self) -> int:
  52. return id(self)
  53. def __eq__(self, other) -> bool:
  54. return id(self) == id(other)
  55. def short_inst_repr(self) -> str:
  56. return f"Instruction(opname={self.opname}, offset={self.offset})"
  57. def convert_instruction(i: dis.Instruction) -> Instruction:
  58. return Instruction(
  59. i.opcode,
  60. i.opname,
  61. i.arg,
  62. i.argval,
  63. i.offset,
  64. i.starts_line,
  65. i.is_jump_target,
  66. getattr(i, "positions", None),
  67. )
  68. class _NotProvided:
  69. def __repr__(self) -> str:
  70. return "_NotProvided"
  71. def create_instruction(
  72. name, *, arg=None, argval=_NotProvided, target=None
  73. ) -> Instruction:
  74. """
  75. At most one of `arg`, `argval`, and `target` can be not None/_NotProvided.
  76. This is to prevent ambiguity, e.g. does
  77. create_instruction("LOAD_CONST", 5)
  78. mean load the constant at co_consts[5], or load the constant 5?
  79. If `arg` is not provided, it will be computed during assembly from
  80. `argval` or `target`.
  81. Do not use for LOAD_GLOBAL - use create_load_global instead.
  82. Do not use for LOAD_ATTR - use create_load_attr instead.
  83. Do not use for LOAD_SUPER_ATTR - if you need to create this instruction,
  84. implement a create_load_super_attr function.
  85. """
  86. if name in ("LOAD_GLOBAL", "LOAD_ATTR", "LOAD_SUPER_ATTR"):
  87. raise RuntimeError(f"cannot create_instruction with {name}")
  88. cnt = (arg is not None) + (argval is not _NotProvided) + (target is not None)
  89. if cnt > 1:
  90. raise RuntimeError(
  91. "only one of arg, argval, and target can be not None/_NotProvided"
  92. )
  93. if arg is not None and not isinstance(arg, int):
  94. raise RuntimeError("instruction arg must be int or None")
  95. return Instruction(
  96. opcode=dis.opmap[name], opname=name, arg=arg, argval=argval, target=target
  97. )
  98. # Python 3.11 remaps
  99. def create_jump_absolute(target) -> Instruction:
  100. inst = "JUMP_FORWARD" if sys.version_info >= (3, 11) else "JUMP_ABSOLUTE"
  101. return create_instruction(inst, target=target)
  102. def create_load_global(name, push_null) -> Instruction:
  103. """
  104. `name` is the name of the global to be loaded.
  105. `push_null` specifies whether or not a NULL should be pushed to the stack
  106. before the global (Python 3.11+ only).
  107. Python 3.11 changed the LOAD_GLOBAL instruction in that the first bit of
  108. the instruction arg specifies whether a NULL should be pushed to the stack
  109. before the global. The remaining bits of the instruction arg contain the
  110. name index. See `create_call_function` for why this NULL is needed.
  111. The instruction's `arg` is actually computed when assembling the bytecode.
  112. For Python 3.11, push_null information is propagated through the arg.
  113. NOTE: we don't use create_instruction since LOAD_GLOBAL is the only instruction
  114. where both arg and argval need to be specified.
  115. """
  116. return Instruction(
  117. opcode=dis.opmap["LOAD_GLOBAL"],
  118. opname="LOAD_GLOBAL",
  119. arg=push_null,
  120. argval=name,
  121. )
  122. def create_dup_top() -> Instruction:
  123. if sys.version_info >= (3, 11):
  124. return create_instruction("COPY", arg=1)
  125. return create_instruction("DUP_TOP")
  126. def create_rot_n(n) -> List[Instruction]:
  127. """
  128. Returns a "simple" sequence of instructions that rotates TOS to the n-th
  129. position in the stack. For Python < 3.11, returns a single ROT_*
  130. instruction. If no such instruction exists, an error is raised and the
  131. caller is expected to generate an equivalent sequence of instructions.
  132. For Python >= 3.11, any rotation can be expressed as a simple sequence of
  133. swaps.
  134. """
  135. if n <= 1:
  136. # don't rotate
  137. return []
  138. if sys.version_info >= (3, 11):
  139. # rotate can be expressed as a sequence of swap operations
  140. # e.g. rotate 3 is equivalent to swap 3, swap 2
  141. return [create_instruction("SWAP", arg=i) for i in range(n, 1, -1)]
  142. # ensure desired rotate function exists
  143. if sys.version_info < (3, 8) and n >= 4:
  144. raise AttributeError(f"rotate {n} not supported for Python < 3.8")
  145. if sys.version_info < (3, 10) and n >= 5:
  146. raise AttributeError(f"rotate {n} not supported for Python < 3.10")
  147. if n <= 4:
  148. return [create_instruction("ROT_" + ["TWO", "THREE", "FOUR"][n - 2])]
  149. return [create_instruction("ROT_N", arg=n)]
  150. def create_call_function(nargs, push_null) -> List[Instruction]:
  151. """
  152. Creates a sequence of instructions that makes a function call.
  153. `push_null` is used in Python 3.11+ only. It is used in codegen when
  154. a function call is intended to be made with the NULL + fn convention,
  155. and we know that the NULL has not been pushed yet. We will push a
  156. NULL and rotate it to the correct position immediately before making
  157. the function call.
  158. push_null should default to True unless you know you are calling a function
  159. that you codegen'd with a null already pushed, for example
  160. (assume `math` is available in the global scope),
  161. create_load_global("math", True) # pushes a null
  162. create_load_attr("sqrt")
  163. create_instruction("LOAD_CONST", argval=25)
  164. create_call_function(1, False)
  165. """
  166. if sys.version_info >= (3, 11):
  167. output = []
  168. if push_null:
  169. output.append(create_instruction("PUSH_NULL"))
  170. output.extend(create_rot_n(nargs + 2))
  171. if sys.version_info < (3, 12):
  172. output.append(create_instruction("PRECALL", arg=nargs))
  173. output.append(create_instruction("CALL", arg=nargs))
  174. return output
  175. return [create_instruction("CALL_FUNCTION", arg=nargs)]
  176. def create_call_method(nargs) -> List[Instruction]:
  177. if sys.version_info >= (3, 12):
  178. return [create_instruction("CALL", arg=nargs)]
  179. if sys.version_info >= (3, 11):
  180. return [
  181. create_instruction("PRECALL", arg=nargs),
  182. create_instruction("CALL", arg=nargs),
  183. ]
  184. return [create_instruction("CALL_METHOD", arg=nargs)]
  185. def create_load_attr(name) -> Instruction:
  186. # in 3.12, create a LOAD_ATTR instruction with the low bit unset
  187. return Instruction(
  188. opcode=dis.opmap["LOAD_ATTR"],
  189. opname="LOAD_ATTR",
  190. arg=False, # lowbit for 3.12
  191. argval=name,
  192. )
  193. def create_load_method(name) -> Instruction:
  194. if sys.version_info >= (3, 12):
  195. # in 3.12, create a LOAD_ATTR instruction with the low bit set
  196. return Instruction(
  197. opcode=dis.opmap["LOAD_ATTR"],
  198. opname="LOAD_ATTR",
  199. arg=True, # lowbit for 3.12
  200. argval=name,
  201. )
  202. return create_instruction("LOAD_METHOD", argval=name)
  203. def create_setup_with(target) -> Instruction:
  204. opname = "BEFORE_WITH" if sys.version_info >= (3, 11) else "SETUP_WITH"
  205. return create_instruction(opname, target=target)
  206. def create_swap(n) -> List[Instruction]:
  207. if sys.version_info >= (3, 11):
  208. return [create_instruction("SWAP", arg=n)]
  209. # in Python < 3.11, SWAP is a macro that expands to multiple instructions
  210. if n == 1:
  211. return []
  212. """
  213. e.g. swap "a" and "b" in this stack:
  214. 0 a 1 2 3 b
  215. 0 a [1 2 3 b]
  216. 0 a [1 2 3 b] [1 2 3 b]
  217. 0 a [1 2 3 b] [1 2 3 b] -1
  218. 0 a [1 2 3 b] b
  219. 0 b a [1 2 3 b]
  220. 0 b a [1 2 3 b] [1 2 3 b]
  221. 0 b [1 2 3 b] a [1 2 3 b]
  222. 0 b [1 2 3 b] a [1 2 3 b] -1
  223. 0 b [1 2 3 a]
  224. 0 b [1 2 3 a] [1 2 3 a]
  225. 0 b [1 2 3 a] [1 2 3 a] reverse
  226. 0 b [a 3 2 1] None
  227. 0 b [a 3 2 1]
  228. 0 b 1 2 3 a
  229. """
  230. return [
  231. create_instruction("BUILD_LIST", arg=n - 1),
  232. create_instruction("DUP_TOP"),
  233. create_instruction("LOAD_CONST", argval=-1),
  234. create_instruction("BINARY_SUBSCR"),
  235. create_instruction("ROT_THREE"),
  236. create_instruction("DUP_TOP"),
  237. create_instruction("ROT_THREE"),
  238. create_instruction("LOAD_CONST", argval=-1),
  239. create_instruction("STORE_SUBSCR"),
  240. create_instruction("DUP_TOP"),
  241. create_load_method("reverse"),
  242. *create_call_method(0),
  243. create_instruction("POP_TOP"),
  244. create_instruction("UNPACK_SEQUENCE", arg=n - 1),
  245. ]
  246. def lnotab_writer(
  247. lineno: int, byteno: int = 0
  248. ) -> Tuple[List[int], Callable[[int, int], None]]:
  249. """
  250. Used to create typing.CodeType.co_lnotab
  251. See https://github.com/python/cpython/blob/main/Objects/lnotab_notes.txt
  252. This is the internal format of the line number table if Python < 3.10
  253. """
  254. assert sys.version_info < (3, 10)
  255. lnotab: List[int] = []
  256. def update(lineno_new, byteno_new):
  257. nonlocal byteno, lineno
  258. while byteno_new != byteno or lineno_new != lineno:
  259. byte_offset = max(0, min(byteno_new - byteno, 255))
  260. line_offset = max(-128, min(lineno_new - lineno, 127))
  261. assert byte_offset != 0 or line_offset != 0
  262. byteno += byte_offset
  263. lineno += line_offset
  264. lnotab.extend((byte_offset, line_offset & 0xFF))
  265. return lnotab, update
  266. def linetable_310_writer(first_lineno):
  267. """
  268. Used to create typing.CodeType.co_linetable
  269. See https://github.com/python/cpython/blob/main/Objects/lnotab_notes.txt
  270. This is the internal format of the line number table for Python 3.10
  271. """
  272. assert sys.version_info >= (3, 10) and sys.version_info < (3, 11)
  273. linetable: List[int] = []
  274. lineno = first_lineno
  275. lineno_delta = 0
  276. byteno = 0
  277. def _update(byteno_delta, lineno_delta):
  278. while byteno_delta != 0 or lineno_delta != 0:
  279. byte_offset = max(0, min(byteno_delta, 254))
  280. line_offset = max(-127, min(lineno_delta, 127))
  281. assert byte_offset != 0 or line_offset != 0
  282. byteno_delta -= byte_offset
  283. lineno_delta -= line_offset
  284. linetable.extend((byte_offset, line_offset & 0xFF))
  285. def update(lineno_new, byteno_new):
  286. nonlocal lineno, lineno_delta, byteno
  287. byteno_delta = byteno_new - byteno
  288. byteno = byteno_new
  289. _update(byteno_delta, lineno_delta)
  290. lineno_delta = lineno_new - lineno
  291. lineno = lineno_new
  292. def end(total_bytes):
  293. _update(total_bytes - byteno, lineno_delta)
  294. return linetable, update, end
  295. def encode_varint(n: int) -> List[int]:
  296. """
  297. 6-bit chunk encoding of an unsigned integer
  298. See https://github.com/python/cpython/blob/3.11/Objects/locations.md
  299. """
  300. assert n >= 0
  301. b = [n & 63]
  302. n >>= 6
  303. while n > 0:
  304. b[-1] |= 64
  305. b.append(n & 63)
  306. n >>= 6
  307. return b
  308. def linetable_311_writer(first_lineno: int):
  309. """
  310. Used to create typing.CodeType.co_linetable
  311. See https://github.com/python/cpython/blob/3.11/Objects/locations.md
  312. This is the internal format of the line number table for Python 3.11
  313. """
  314. assert sys.version_info >= (3, 11)
  315. linetable = []
  316. lineno = first_lineno
  317. def update(positions: "dis.Positions", inst_size):
  318. nonlocal lineno
  319. lineno_new = positions.lineno if positions else None
  320. def _update(delta, size):
  321. assert 0 < size <= 8
  322. # first byte - use 13 (no column info) is positions is
  323. # malformed, otherwise use 14 (long form)
  324. other_varints: Tuple[int, ...] = ()
  325. if (
  326. positions
  327. and positions.lineno is not None
  328. and positions.end_lineno is not None
  329. and positions.col_offset is not None
  330. and positions.end_col_offset is not None
  331. ):
  332. linetable.append(0b1_1110_000 + size - 1)
  333. # for whatever reason, column offset needs `+ 1`
  334. # https://github.com/python/cpython/blob/1931c2a438c50e6250725c84dff94fc760b9b951/Python/compile.c#L7603
  335. other_varints = (
  336. positions.end_lineno - positions.lineno,
  337. positions.col_offset + 1,
  338. positions.end_col_offset + 1,
  339. )
  340. else:
  341. linetable.append(0b1_1101_000 + size - 1)
  342. # encode signed int
  343. if delta < 0:
  344. delta = ((-delta) << 1) | 1
  345. else:
  346. delta <<= 1
  347. # encode unsigned int
  348. linetable.extend(encode_varint(delta))
  349. for n in other_varints:
  350. linetable.extend(encode_varint(n))
  351. if lineno_new is None:
  352. lineno_delta = 0
  353. else:
  354. lineno_delta = lineno_new - lineno
  355. lineno = lineno_new
  356. while inst_size > 8:
  357. _update(lineno_delta, 8)
  358. inst_size -= 8
  359. _update(lineno_delta, inst_size)
  360. return linetable, update
  361. @dataclasses.dataclass
  362. class ExceptionTableEntry:
  363. start: int
  364. end: int
  365. target: int
  366. depth: int
  367. lasti: bool
  368. def encode_exception_table_varint(n: int) -> List[int]:
  369. """
  370. Similar to `encode_varint`, but the 6-bit chunks are ordered in reverse.
  371. """
  372. assert n >= 0
  373. b = [n & 63]
  374. n >>= 6
  375. while n > 0:
  376. b.append(n & 63)
  377. n >>= 6
  378. b.reverse()
  379. for i in range(len(b) - 1):
  380. b[i] |= 64
  381. return b
  382. def decode_exception_table_varint(bytes_iter: Iterator[int]) -> int:
  383. """
  384. Inverse of `encode_exception_table_varint`.
  385. """
  386. b = next(bytes_iter)
  387. val = b & 63
  388. while b & 64:
  389. val <<= 6
  390. b = next(bytes_iter)
  391. val |= b & 63
  392. return val
  393. def check_exception_table(tab: List[ExceptionTableEntry]) -> None:
  394. """
  395. Verifies that a list of ExceptionTableEntries will make a well-formed
  396. jump table: entries are non-empty, sorted, and do not overlap.
  397. """
  398. for i in range(len(tab) - 1):
  399. assert (
  400. tab[i].start <= tab[i].end
  401. and tab[i].end < tab[i + 1].start
  402. and tab[i + 1].start <= tab[i + 1].end
  403. )
  404. def parse_exception_table(exntab: bytes) -> List[ExceptionTableEntry]:
  405. """
  406. Parse the exception table according to
  407. https://github.com/python/cpython/blob/3.11/Objects/exception_handling_notes.txt
  408. """
  409. exntab_iter = iter(exntab)
  410. tab = []
  411. try:
  412. while True:
  413. start = decode_exception_table_varint(exntab_iter) * 2
  414. length = decode_exception_table_varint(exntab_iter) * 2
  415. end = start + length - 2
  416. target = decode_exception_table_varint(exntab_iter) * 2
  417. dl = decode_exception_table_varint(exntab_iter)
  418. depth = dl >> 1
  419. lasti = bool(dl & 1)
  420. tab.append(ExceptionTableEntry(start, end, target, depth, lasti))
  421. except StopIteration:
  422. check_exception_table(tab)
  423. return tab
  424. def assemble_exception_table(tab: List[ExceptionTableEntry]) -> bytes:
  425. """
  426. Inverse of parse_exception_table - encodes list of exception
  427. table entries into bytes.
  428. """
  429. b = []
  430. for entry in tab:
  431. first_entry = encode_exception_table_varint(entry.start // 2)
  432. first_entry[0] |= 1 << 7
  433. b.extend(first_entry)
  434. length = entry.end - entry.start + 2
  435. b.extend(encode_exception_table_varint(length // 2))
  436. b.extend(encode_exception_table_varint(entry.target // 2))
  437. dl = (entry.depth << 1) + entry.lasti
  438. b.extend(encode_exception_table_varint(dl))
  439. return bytes(b)
  440. def assemble(instructions: List[Instruction], firstlineno: int) -> Tuple[bytes, bytes]:
  441. """Do the opposite of dis.get_instructions()"""
  442. code: List[int] = []
  443. if sys.version_info >= (3, 11):
  444. lnotab, update_lineno = linetable_311_writer(firstlineno)
  445. num_ext = 0
  446. for i, inst in enumerate(instructions):
  447. if inst.opname == "EXTENDED_ARG":
  448. inst_size = 1
  449. num_ext += 1
  450. # copy positions from the actual instruction
  451. for j in (1, 2, 3):
  452. if instructions[i + j].opname != "EXTENDED_ARG":
  453. inst.positions = instructions[i + j].positions
  454. break
  455. else:
  456. inst_size = instruction_size(inst) // 2 + num_ext
  457. num_ext = 0
  458. update_lineno(inst.positions, inst_size)
  459. num_ext = 0
  460. arg = inst.arg or 0
  461. code.extend((inst.opcode, arg & 0xFF))
  462. for _ in range(instruction_size(inst) // 2 - 1):
  463. code.extend((0, 0))
  464. else:
  465. if sys.version_info < (3, 10):
  466. lnotab, update_lineno = lnotab_writer(firstlineno)
  467. else:
  468. lnotab, update_lineno, end = linetable_310_writer(firstlineno)
  469. for inst in instructions:
  470. if inst.starts_line is not None:
  471. update_lineno(inst.starts_line, len(code))
  472. arg = inst.arg or 0
  473. code.extend((inst.opcode, arg & 0xFF))
  474. if sys.version_info >= (3, 10):
  475. end(len(code))
  476. return bytes(code), bytes(lnotab)
  477. def _get_instruction_by_offset(offset_to_inst: Dict[int, Instruction], offset: int):
  478. """
  479. Get the instruction located at a given offset, accounting for EXTENDED_ARGs
  480. """
  481. for n in (0, 2, 4, 6):
  482. if offset_to_inst[offset + n].opcode != dis.EXTENDED_ARG:
  483. return offset_to_inst[offset + n]
  484. return None
  485. def virtualize_jumps(instructions) -> None:
  486. """Replace jump targets with pointers to make editing easier"""
  487. jump_targets = {inst.offset: inst for inst in instructions}
  488. for inst in instructions:
  489. if inst.opcode in dis.hasjabs or inst.opcode in dis.hasjrel:
  490. inst.target = _get_instruction_by_offset(jump_targets, inst.argval)
  491. _REL_JUMPS = set(dis.hasjrel)
  492. def flip_jump_direction(instruction: Instruction) -> None:
  493. if sys.version_info < (3, 11):
  494. raise RuntimeError("Cannot flip jump direction in Python < 3.11")
  495. if "FORWARD" in instruction.opname:
  496. instruction.opname = instruction.opname.replace("FORWARD", "BACKWARD")
  497. elif "BACKWARD" in instruction.opname:
  498. instruction.opname = instruction.opname.replace("BACKWARD", "FORWARD")
  499. else:
  500. raise AttributeError("Instruction is not a forward or backward jump")
  501. instruction.opcode = dis.opmap[instruction.opname]
  502. assert instruction.opcode in _REL_JUMPS
  503. def _get_instruction_front(instructions: List[Instruction], idx: int):
  504. """
  505. i.e. get the first EXTENDED_ARG instruction (if any) when targeting
  506. instructions[idx] with a jump.
  507. """
  508. target = instructions[idx]
  509. for offset in (1, 2, 3):
  510. if idx >= offset and instructions[idx - offset].opcode == dis.EXTENDED_ARG:
  511. target = instructions[idx - offset]
  512. else:
  513. break
  514. return target
  515. def devirtualize_jumps(instructions):
  516. """Fill in args for virtualized jump target after instructions may have moved"""
  517. indexof = get_indexof(instructions)
  518. jumps = set(dis.hasjabs).union(set(dis.hasjrel))
  519. for inst in instructions:
  520. if inst.opcode in jumps:
  521. target = _get_instruction_front(instructions, indexof[inst.target])
  522. if inst.opcode in dis.hasjabs:
  523. if sys.version_info < (3, 10):
  524. inst.arg = target.offset
  525. elif sys.version_info < (3, 11):
  526. # `arg` is expected to be bytecode offset, whereas `offset` is byte offset.
  527. # Divide since bytecode is 2 bytes large.
  528. inst.arg = int(target.offset / 2)
  529. else:
  530. raise RuntimeError("Python 3.11+ should not have absolute jumps")
  531. else: # relative jump
  532. # byte offset between target and next instruction
  533. inst.arg = int(target.offset - inst.offset - instruction_size(inst))
  534. if inst.arg < 0:
  535. if sys.version_info < (3, 11):
  536. raise RuntimeError("Got negative jump offset for Python < 3.11")
  537. inst.arg = -inst.arg
  538. # forward jumps become backward
  539. if "FORWARD" in inst.opname:
  540. flip_jump_direction(inst)
  541. elif inst.arg > 0:
  542. # backward jumps become forward
  543. if sys.version_info >= (3, 11) and "BACKWARD" in inst.opname:
  544. flip_jump_direction(inst)
  545. if sys.version_info >= (3, 10):
  546. # see bytecode size comment in the absolute jump case above
  547. inst.arg //= 2
  548. inst.argval = target.offset
  549. inst.argrepr = f"to {target.offset}"
  550. def virtualize_exception_table(exn_tab_bytes: bytes, instructions: List[Instruction]):
  551. """Replace exception table entries with pointers to make editing easier"""
  552. exn_tab = parse_exception_table(exn_tab_bytes)
  553. offset_to_inst = {cast(int, inst.offset): inst for inst in instructions}
  554. offsets = sorted(offset_to_inst.keys())
  555. end_offset_idx = 0
  556. exn_tab_iter = iter(exn_tab)
  557. try:
  558. def step():
  559. nonlocal end_offset_idx
  560. entry = next(exn_tab_iter)
  561. # find rightmost offset <= entry.end, since entry.end may not be
  562. # an actual instruction, e.g. if the end instruction is LOAD_GLOBAL,
  563. # which takes more than 2 bytes, then entry.end points to the end
  564. # of the LOAD_GLOBAL instruction, not the beginning.
  565. while (
  566. end_offset_idx < len(offsets) and offsets[end_offset_idx] <= entry.end
  567. ):
  568. end_offset_idx += 1
  569. assert end_offset_idx > 0
  570. end_offset = offsets[end_offset_idx - 1]
  571. inst_entry = InstructionExnTabEntry(
  572. _get_instruction_by_offset(offset_to_inst, entry.start),
  573. _get_instruction_by_offset(offset_to_inst, end_offset),
  574. _get_instruction_by_offset(offset_to_inst, entry.target),
  575. entry.depth,
  576. entry.lasti,
  577. )
  578. return entry, inst_entry
  579. entry, inst_entry = step()
  580. for inst in instructions:
  581. while inst.offset > entry.end:
  582. entry, inst_entry = step()
  583. if inst.offset >= entry.start:
  584. inst.exn_tab_entry = copy.copy(inst_entry)
  585. except StopIteration:
  586. pass
  587. def compute_exception_table(
  588. instructions: List[Instruction],
  589. ) -> List[ExceptionTableEntry]:
  590. """Compute exception table in list format from instructions with exn_tab_entries"""
  591. exn_dict: Dict[Tuple[int, int], Tuple[int, int, bool]] = {}
  592. indexof = get_indexof(instructions)
  593. for inst in instructions:
  594. if inst.exn_tab_entry:
  595. # account for prefixed EXTENDED_ARGS
  596. start = _get_instruction_front(
  597. instructions, indexof[inst.exn_tab_entry.start]
  598. ).offset
  599. # point to the last 2 bytes of the end instruction
  600. end = (
  601. cast(int, inst.exn_tab_entry.end.offset)
  602. + instruction_size(inst.exn_tab_entry.end)
  603. - 2
  604. )
  605. target = _get_instruction_front(
  606. instructions, indexof[inst.exn_tab_entry.target]
  607. ).offset
  608. key = (start, end)
  609. val = (target, inst.exn_tab_entry.depth, inst.exn_tab_entry.lasti)
  610. if key in exn_dict:
  611. assert exn_dict[key] == val
  612. exn_dict[key] = val
  613. # Dynamo may construct nested exception table entries for convenience,
  614. # but Python expects exception table entries to not overlap.
  615. # NOTE: below, "keys" refer to old instruction entries' starts and ends,
  616. # and "entries" refer to the generated exception table entries.
  617. # Sort keys by increasing start, then decreasing end
  618. keys_sorted = sorted(exn_dict.keys(), key=lambda t: (t[0], -t[1]))
  619. # smallest byte that the next exception table entry can start at
  620. nexti = 0
  621. # stack of current nested keys
  622. key_stack: List[Tuple[int, int]] = []
  623. exn_tab: List[ExceptionTableEntry] = []
  624. def pop():
  625. """
  626. Pop the key_stack and append an exception table entry if possible.
  627. """
  628. nonlocal nexti
  629. if key_stack:
  630. key = key_stack.pop()
  631. if nexti <= key[1]:
  632. exn_tab.append(
  633. ExceptionTableEntry(max(key[0], nexti), key[1], *exn_dict[key])
  634. )
  635. nexti = key[1] + 2
  636. for key in keys_sorted:
  637. # pop keys that are no longer nested over the current key
  638. while key_stack and key_stack[-1][1] < key[0]:
  639. pop()
  640. if key_stack:
  641. # create an entry covering to the current key, if possible
  642. assert key_stack[-1][0] <= key[0] <= key[1] <= key_stack[-1][1]
  643. left = max(nexti, key_stack[-1][0])
  644. if left < key[0]:
  645. exn_tab.append(
  646. ExceptionTableEntry(left, key[0] - 2, *exn_dict[key_stack[-1]])
  647. )
  648. nexti = key[0]
  649. key_stack.append(key)
  650. while key_stack:
  651. pop()
  652. check_exception_table(exn_tab)
  653. return exn_tab
  654. def check_inst_exn_tab_entries_nested(
  655. tab: List[InstructionExnTabEntry], indexof
  656. ) -> None:
  657. """
  658. Checks `tab` is a properly sorted list of nested InstructionExnTabEntry's,
  659. i.e. no entries partially overlap.
  660. "Properly sorted" means entries are sorted by increasing starts, then
  661. decreasing ends.
  662. """
  663. entry_stack: List[Tuple[int, int]] = []
  664. for entry in tab:
  665. key = (indexof[entry.start], indexof[entry.end])
  666. while entry_stack and entry_stack[-1][1] < key[0]:
  667. entry_stack.pop()
  668. if entry_stack:
  669. assert entry_stack[-1][0] <= key[0] <= key[1] <= entry_stack[-1][1]
  670. entry_stack.append(key)
  671. def propagate_inst_exn_table_entries(instructions: List[Instruction]) -> None:
  672. """
  673. Copies exception table entries to all instructions in an entry's range.
  674. Supports nested exception table entries.
  675. """
  676. indexof = get_indexof(instructions)
  677. entries: Dict[Tuple[int, int], InstructionExnTabEntry] = {}
  678. for inst in instructions:
  679. if inst.exn_tab_entry:
  680. key = (
  681. indexof[inst.exn_tab_entry.start],
  682. indexof[inst.exn_tab_entry.end],
  683. )
  684. if key in entries:
  685. assert inst.exn_tab_entry == entries[key]
  686. entries[key] = inst.exn_tab_entry
  687. sorted_entries = [
  688. entries[key] for key in sorted(entries.keys(), key=lambda t: (t[0], -t[1]))
  689. ]
  690. check_inst_exn_tab_entries_nested(sorted_entries, indexof)
  691. # Propagation of nested entries works since nested entries come later
  692. # in sorted order.
  693. for entry in sorted_entries:
  694. for i in range(indexof[entry.start], indexof[entry.end] + 1):
  695. instructions[i].exn_tab_entry = copy.copy(entry)
  696. def check_inst_exn_tab_entries_valid(instructions: List[Instruction]):
  697. """
  698. Checks that exn_tab_entries of instructions are valid.
  699. An entry's start, end, and target must be in instructions.
  700. Instructions with an exn_tab_entry are located within
  701. the entry's start and end instructions.
  702. Instructions do not share exn_tab_entries.
  703. Implicitly checks for no duplicate instructions.
  704. """
  705. indexof = get_indexof(instructions)
  706. exn_tab_entry_set = set()
  707. for i, inst in enumerate(instructions):
  708. if inst.exn_tab_entry:
  709. assert sys.version_info >= (3, 11)
  710. assert id(inst.exn_tab_entry) not in exn_tab_entry_set
  711. exn_tab_entry_set.add(id(inst.exn_tab_entry))
  712. entry = inst.exn_tab_entry
  713. assert entry.start in indexof
  714. assert entry.end in indexof
  715. assert entry.target in indexof
  716. assert indexof[entry.start] <= i <= indexof[entry.end]
  717. def strip_extended_args(instructions: List[Instruction]) -> None:
  718. instructions[:] = [i for i in instructions if i.opcode != dis.EXTENDED_ARG]
  719. def remove_load_call_method(instructions: List[Instruction]) -> List[Instruction]:
  720. """LOAD_METHOD puts a NULL on the stack which causes issues, so remove it"""
  721. assert sys.version_info < (3, 11)
  722. rewrites = {"LOAD_METHOD": "LOAD_ATTR", "CALL_METHOD": "CALL_FUNCTION"}
  723. for inst in instructions:
  724. if inst.opname in rewrites:
  725. inst.opname = rewrites[inst.opname]
  726. inst.opcode = dis.opmap[inst.opname]
  727. return instructions
  728. def remove_jump_if_none(instructions: List[Instruction]) -> None:
  729. new_insts = []
  730. for inst in instructions:
  731. new_insts.append(inst)
  732. if "_NONE" in inst.opname:
  733. is_op = create_instruction("IS_OP", arg=int("NOT" in inst.opname))
  734. is_op.argval = is_op.arg
  735. is_op.positions = inst.positions
  736. if sys.version_info < (3, 12):
  737. jump_op = create_instruction(
  738. "POP_JUMP_FORWARD_IF_TRUE"
  739. if "FORWARD" in inst.opname
  740. else "POP_JUMP_BACKWARD_IF_TRUE",
  741. target=inst.target,
  742. )
  743. else:
  744. jump_op = create_instruction("POP_JUMP_IF_TRUE", target=inst.target)
  745. jump_op.positions = inst.positions
  746. # update inst.exn_tab_entry.end if necessary
  747. if inst.exn_tab_entry and inst.exn_tab_entry.end is inst:
  748. inst.exn_tab_entry.end = jump_op
  749. # preserve exception table entries
  750. is_op.exn_tab_entry = copy.copy(inst.exn_tab_entry)
  751. jump_op.exn_tab_entry = copy.copy(inst.exn_tab_entry)
  752. # modify inst in-place to preserve jump target
  753. inst.opcode = dis.opmap["LOAD_CONST"]
  754. inst.opname = "LOAD_CONST"
  755. inst.arg = None
  756. inst.argval = None
  757. new_insts.extend([is_op, jump_op])
  758. instructions[:] = new_insts
  759. def remove_binary_store_slice(instructions: List[Instruction]) -> None:
  760. new_insts = []
  761. for inst in instructions:
  762. new_insts.append(inst)
  763. if inst.opname in ("BINARY_SLICE", "STORE_SLICE"):
  764. # new instruction
  765. subscr_inst = create_instruction(inst.opname.replace("SLICE", "SUBSCR"))
  766. if inst.exn_tab_entry and inst.exn_tab_entry.end is inst:
  767. inst.exn_tab_entry.end = subscr_inst
  768. subscr_inst.exn_tab_entry = copy.copy(inst.exn_tab_entry)
  769. subscr_inst.positions = inst.positions
  770. # modify inst in-place to preserve jump target
  771. inst.opcode = dis.opmap["BUILD_SLICE"]
  772. inst.opname = "BUILD_SLICE"
  773. inst.arg = 2
  774. inst.argval = 2
  775. new_insts.append(subscr_inst)
  776. instructions[:] = new_insts
  777. def explicit_super(code: types.CodeType, instructions: List[Instruction]) -> None:
  778. """convert super() with no args into explicit arg form"""
  779. cell_and_free = (code.co_cellvars or tuple()) + (code.co_freevars or tuple())
  780. if not len(code.co_varnames):
  781. # A function with no argument cannot contain a valid "super()" call
  782. return
  783. output = []
  784. for idx, inst in enumerate(instructions):
  785. output.append(inst)
  786. if inst.opname == "LOAD_GLOBAL" and inst.argval == "super":
  787. nexti = instructions[idx + 1]
  788. if nexti.arg == 0 and (
  789. (sys.version_info >= (3, 12) and nexti.opname == "CALL")
  790. or (
  791. sys.version_info >= (3, 11)
  792. and sys.version_info < (3, 12)
  793. and nexti.opname == "PRECALL"
  794. )
  795. or (sys.version_info < (3, 11) and nexti.opname == "CALL_FUNCTION")
  796. ):
  797. assert "__class__" in cell_and_free
  798. output.append(create_instruction("LOAD_DEREF", argval="__class__"))
  799. first_var = code.co_varnames[0]
  800. if first_var in cell_and_free:
  801. output.append(create_instruction("LOAD_DEREF", argval=first_var))
  802. else:
  803. output.append(create_instruction("LOAD_FAST", argval=first_var))
  804. nexti.arg = 2
  805. nexti.argval = 2
  806. if nexti.opname == "PRECALL":
  807. # also update the following CALL instruction
  808. call_inst = instructions[idx + 2]
  809. call_inst.arg = 2
  810. call_inst.argval = 2
  811. instructions[:] = output
  812. def fix_extended_args(instructions: List[Instruction]) -> int:
  813. """Fill in correct argvals for EXTENDED_ARG ops"""
  814. output: List[Instruction] = []
  815. def maybe_pop_n(n):
  816. for _ in range(n):
  817. if output and output[-1].opcode == dis.EXTENDED_ARG:
  818. output.pop()
  819. for inst in instructions:
  820. if inst.opcode == dis.EXTENDED_ARG:
  821. # Leave this instruction alone for now so we never shrink code
  822. inst.arg = 0
  823. elif inst.arg and inst.arg > 0xFFFFFF:
  824. maybe_pop_n(3)
  825. output.append(create_instruction("EXTENDED_ARG", arg=inst.arg >> 24))
  826. output.append(create_instruction("EXTENDED_ARG", arg=inst.arg >> 16))
  827. output.append(create_instruction("EXTENDED_ARG", arg=inst.arg >> 8))
  828. elif inst.arg and inst.arg > 0xFFFF:
  829. maybe_pop_n(2)
  830. output.append(create_instruction("EXTENDED_ARG", arg=inst.arg >> 16))
  831. output.append(create_instruction("EXTENDED_ARG", arg=inst.arg >> 8))
  832. elif inst.arg and inst.arg > 0xFF:
  833. maybe_pop_n(1)
  834. output.append(create_instruction("EXTENDED_ARG", arg=inst.arg >> 8))
  835. output.append(inst)
  836. added = len(output) - len(instructions)
  837. assert added >= 0
  838. instructions[:] = output
  839. return added
  840. def instruction_size(inst) -> int:
  841. import torch
  842. if sys.version_info >= (3, 11):
  843. return 2 * (torch._C._dynamo.eval_frame.py_opcode_caches[inst.opcode] + 1)
  844. return 2
  845. def check_offsets(instructions) -> None:
  846. offset = 0
  847. for inst in instructions:
  848. assert inst.offset == offset
  849. offset += instruction_size(inst)
  850. def update_offsets(instructions) -> None:
  851. offset = 0
  852. for inst in instructions:
  853. inst.offset = offset
  854. offset += instruction_size(inst)
  855. def debug_bytes(*args) -> str:
  856. index = range(max(map(len, args)))
  857. result = []
  858. for arg in (
  859. [index] + list(args) + [[int(a != b) for a, b in zip(args[-1], args[-2])]]
  860. ):
  861. result.append(" ".join(f"{x:03}" for x in arg))
  862. return "bytes mismatch\n" + "\n".join(result)
  863. def debug_checks(code):
  864. """Make sure our assembler produces same bytes as we start with"""
  865. dode = transform_code_object(code, lambda x, y: None, safe=True)
  866. assert code.co_code == dode.co_code, debug_bytes(code.co_code, dode.co_code)
  867. assert code.co_lnotab == dode.co_lnotab, debug_bytes(code.co_lnotab, dode.co_lnotab)
  868. HAS_LOCAL = set(dis.haslocal)
  869. HAS_NAME = set(dis.hasname)
  870. HAS_FREE = set(dis.hasfree)
  871. HAS_CONST = set(dis.hasconst)
  872. def get_const_index(code_options, val) -> int:
  873. for i, v in enumerate(code_options["co_consts"]):
  874. # NOTE: stronger comparison is required, since we have
  875. # examples where two values compare equal but have
  876. # different semantic meaning in some cases, e.g.
  877. # 0.0 == -0.0 but have different effects in torch.copysign.
  878. if val is v:
  879. return i
  880. code_options["co_consts"] += (val,)
  881. return len(code_options["co_consts"]) - 1
  882. def fix_vars(instructions: List[Instruction], code_options, varname_from_oparg=None):
  883. # compute instruction arg from argval if arg is not provided
  884. names = {name: idx for idx, name in enumerate(code_options["co_names"])}
  885. def get_name_index(name) -> int:
  886. try:
  887. idx = names[name]
  888. except KeyError:
  889. # Add a missing item to co_names
  890. idx = names[name] = len(names)
  891. code_options["co_names"] = (*code_options["co_names"], name)
  892. assert len(code_options["co_names"]) == len(names)
  893. return idx
  894. if sys.version_info < (3, 11):
  895. assert varname_from_oparg is None
  896. varnames = {name: idx for idx, name in enumerate(code_options["co_varnames"])}
  897. freenames = {
  898. name: idx
  899. for idx, name in enumerate(
  900. code_options["co_cellvars"] + code_options["co_freevars"]
  901. )
  902. }
  903. else:
  904. assert callable(varname_from_oparg)
  905. allnames = {}
  906. for idx in itertools.count():
  907. try:
  908. name = varname_from_oparg(idx)
  909. allnames[name] = idx
  910. except IndexError:
  911. break
  912. varnames = {name: allnames[name] for name in code_options["co_varnames"]}
  913. freenames = {
  914. name: allnames[name]
  915. for name in code_options["co_cellvars"] + code_options["co_freevars"]
  916. }
  917. for i in range(len(instructions)):
  918. def should_compute_arg():
  919. # argval is prioritized over arg
  920. return instructions[i].argval is not _NotProvided
  921. if instructions[i].opname == "LOAD_GLOBAL":
  922. # 3.11 LOAD_GLOBAL requires both arg and argval - see create_load_global
  923. assert instructions[i].arg is not None
  924. assert instructions[i].argval is not _NotProvided
  925. if sys.version_info >= (3, 11):
  926. instructions[i].arg = (get_name_index(instructions[i].argval) << 1) + (
  927. cast(int, instructions[i].arg) % 2
  928. )
  929. else:
  930. instructions[i].arg = get_name_index(instructions[i].argval)
  931. elif instructions[i].opname == "LOAD_ATTR":
  932. # 3.12 LOAD_ATTR requires both arg and argval, like LOAD_GLOBAL
  933. assert instructions[i].arg is not None
  934. assert instructions[i].argval is not _NotProvided
  935. if sys.version_info >= (3, 12):
  936. instructions[i].arg = (get_name_index(instructions[i].argval) << 1) + (
  937. cast(int, instructions[i].arg) % 2
  938. )
  939. else:
  940. instructions[i].arg = get_name_index(instructions[i].argval)
  941. elif instructions[i].opname == "LOAD_SUPER_ATTR":
  942. assert instructions[i].arg is not None
  943. assert instructions[i].argval is not _NotProvided
  944. # Copy low bit, force second bit on for explicit super (the "+ 2")
  945. instructions[i].arg = (
  946. (get_name_index(instructions[i].argval) << 2)
  947. + (cast(int, instructions[i].arg) % 2)
  948. + 2
  949. )
  950. elif instructions[i].opcode in HAS_LOCAL:
  951. if should_compute_arg():
  952. instructions[i].arg = varnames[instructions[i].argval]
  953. elif instructions[i].opcode in HAS_NAME:
  954. if should_compute_arg():
  955. instructions[i].arg = get_name_index(instructions[i].argval)
  956. elif instructions[i].opcode in HAS_FREE:
  957. if should_compute_arg():
  958. instructions[i].arg = freenames[instructions[i].argval]
  959. elif instructions[i].opcode in HAS_CONST:
  960. # NOTE: only update argval if arg is not provided. This assumes
  961. # that any additions to co_consts are appended.
  962. if instructions[i].arg is None:
  963. # cannot use a dictionary since consts may not be hashable
  964. idx = get_const_index(code_options, instructions[i].argval)
  965. assert idx >= 0
  966. instructions[i].arg = idx
  967. def clear_instruction_args(instructions):
  968. # Clear the instruction arg for instructions that have argvals.
  969. # Useful for using dis'd bytecode within generated bytecode.
  970. for inst in instructions:
  971. if (
  972. inst.argval is not _NotProvided
  973. and (
  974. inst.opcode in HAS_LOCAL
  975. or inst.opcode in HAS_NAME
  976. or inst.opcode in HAS_FREE
  977. or inst.opcode in HAS_CONST
  978. )
  979. and inst.opname not in ("LOAD_GLOBAL", "LOAD_ATTR", "LOAD_SUPER_ATTR")
  980. ):
  981. inst.arg = None
  982. def get_code_keys() -> List[str]:
  983. # Python 3.11 changes to code keys are not fully documented.
  984. # See https://github.com/python/cpython/blob/3.11/Objects/clinic/codeobject.c.h#L24
  985. # for new format.
  986. keys = ["co_argcount"]
  987. keys.append("co_posonlyargcount")
  988. keys.extend(
  989. [
  990. "co_kwonlyargcount",
  991. "co_nlocals",
  992. "co_stacksize",
  993. "co_flags",
  994. "co_code",
  995. "co_consts",
  996. "co_names",
  997. "co_varnames",
  998. "co_filename",
  999. "co_name",
  1000. ]
  1001. )
  1002. if sys.version_info >= (3, 11):
  1003. keys.append("co_qualname")
  1004. keys.append("co_firstlineno")
  1005. if sys.version_info >= (3, 10):
  1006. keys.append("co_linetable")
  1007. else:
  1008. keys.append("co_lnotab")
  1009. if sys.version_info >= (3, 11):
  1010. # not documented, but introduced in https://github.com/python/cpython/issues/84403
  1011. keys.append("co_exceptiontable")
  1012. keys.extend(
  1013. [
  1014. "co_freevars",
  1015. "co_cellvars",
  1016. ]
  1017. )
  1018. return keys
  1019. def transform_code_object(code, transformations, safe=False) -> types.CodeType:
  1020. keys = get_code_keys()
  1021. code_options = {k: getattr(code, k) for k in keys}
  1022. assert len(code_options["co_varnames"]) == code_options["co_nlocals"]
  1023. instructions = cleaned_instructions(code, safe)
  1024. propagate_line_nums(instructions)
  1025. transformations(instructions, code_options)
  1026. return clean_and_assemble_instructions(instructions, keys, code_options)[1]
  1027. def clean_and_assemble_instructions(
  1028. instructions: List[Instruction], keys: List[str], code_options: Dict[str, Any]
  1029. ) -> Tuple[List[Instruction], types.CodeType]:
  1030. # also implicitly checks for no duplicate instructions
  1031. check_inst_exn_tab_entries_valid(instructions)
  1032. code_options["co_nlocals"] = len(code_options["co_varnames"])
  1033. varname_from_oparg = None
  1034. if sys.version_info >= (3, 11):
  1035. # temporary code object with updated names
  1036. tmp_code = types.CodeType(*[code_options[k] for k in keys])
  1037. varname_from_oparg = tmp_code._varname_from_oparg # type: ignore[attr-defined]
  1038. fix_vars(instructions, code_options, varname_from_oparg=varname_from_oparg)
  1039. dirty = True
  1040. while dirty:
  1041. update_offsets(instructions)
  1042. devirtualize_jumps(instructions)
  1043. # this pass might change offsets, if so we need to try again
  1044. dirty = bool(fix_extended_args(instructions))
  1045. remove_extra_line_nums(instructions)
  1046. bytecode, lnotab = assemble(instructions, code_options["co_firstlineno"])
  1047. if sys.version_info < (3, 10):
  1048. code_options["co_lnotab"] = lnotab
  1049. else:
  1050. code_options["co_linetable"] = lnotab
  1051. code_options["co_code"] = bytecode
  1052. code_options["co_stacksize"] = stacksize_analysis(instructions)
  1053. assert set(keys) - {"co_posonlyargcount"} == set(code_options.keys()) - {
  1054. "co_posonlyargcount"
  1055. }
  1056. if sys.version_info >= (3, 11):
  1057. code_options["co_exceptiontable"] = assemble_exception_table(
  1058. compute_exception_table(instructions)
  1059. )
  1060. return instructions, types.CodeType(*[code_options[k] for k in keys])
  1061. def populate_kw_names_argval(instructions, consts):
  1062. for inst in instructions:
  1063. if inst.opname == "KW_NAMES":
  1064. inst.argval = consts[inst.arg]
  1065. def cleaned_instructions(code, safe=False) -> List[Instruction]:
  1066. instructions = list(map(convert_instruction, dis.get_instructions(code)))
  1067. check_offsets(instructions)
  1068. if sys.version_info >= (3, 11):
  1069. populate_kw_names_argval(instructions, code.co_consts)
  1070. virtualize_exception_table(code.co_exceptiontable, instructions)
  1071. virtualize_jumps(instructions)
  1072. strip_extended_args(instructions)
  1073. if not safe:
  1074. if sys.version_info < (3, 11):
  1075. remove_load_call_method(instructions)
  1076. if sys.version_info < (3, 12):
  1077. explicit_super(code, instructions)
  1078. if sys.version_info >= (3, 11):
  1079. remove_jump_if_none(instructions)
  1080. if sys.version_info >= (3, 12):
  1081. remove_binary_store_slice(instructions)
  1082. update_offsets(instructions)
  1083. devirtualize_jumps(instructions)
  1084. return instructions
  1085. _unique_id_counter = itertools.count()
  1086. def unique_id(name) -> str:
  1087. return f"{name}_{next(_unique_id_counter)}"
  1088. def is_generator(code: types.CodeType) -> bool:
  1089. co_generator = 0x20
  1090. return (code.co_flags & co_generator) > 0
  1091. def bytecode_from_template(fn, varname_map=None, noreturn=True, noprefix=True):
  1092. """Generates bytecode from a template function `fn` for use in
  1093. dynamo bytecode generation.
  1094. For example, we can generate Python-version-independent bytecode
  1095. for looping through a dictionary and copying the values to a new dictionary.
  1096. def template(d1, d2):
  1097. for k, v in d1.items():
  1098. d2[k] = v
  1099. or a try block:
  1100. def template():
  1101. try:
  1102. dummy1
  1103. except:
  1104. dummy2
  1105. raise
  1106. dummy3
  1107. Args:
  1108. fn: a function template to generate bytecode from
  1109. varname_map: a mapping of `fn`'s varnames to new names. This
  1110. map will be applied to the generated bytecode's varnames.
  1111. For example, local variables in `fn` can be replaced with
  1112. new names that are generated by `OutputGraph.new_var`.
  1113. noreturn: remove all RETURN_* bytecodes and replace them with a jump
  1114. to the end of the bytecode.
  1115. noprefix: remove prefix bytecodes (all bytecode before the first RESUME, inclusive).
  1116. """
  1117. insts = cleaned_instructions(fn.__code__)
  1118. clear_instruction_args(insts)
  1119. if noprefix:
  1120. for i, inst in enumerate(insts):
  1121. if inst.opname == "RESUME":
  1122. insts = insts[i + 1 :]
  1123. break
  1124. for inst in insts:
  1125. # If we don't reset starts_line, then the generated
  1126. # bytecode's line number will be based on fn's.
  1127. inst.starts_line = None
  1128. if varname_map and inst.argval in varname_map:
  1129. inst.argval = varname_map[inst.argval]
  1130. if noreturn:
  1131. if sys.version_info >= (3, 12):
  1132. # replace RETURN_CONST with LOAD_CONST RETURN_VALUE
  1133. new_insts = []
  1134. for inst in insts:
  1135. if inst.opname == "RETURN_CONST":
  1136. inst.opcode = dis.opmap["LOAD_CONST"]
  1137. inst.opname = "LOAD_CONST"
  1138. new_insts.append(inst)
  1139. # no need to propagate target/exn table
  1140. new_insts.append(create_instruction("RETURN_VALUE"))
  1141. else:
  1142. new_insts.append(inst)
  1143. insts = new_insts
  1144. returns = []
  1145. for inst in insts:
  1146. if inst.opname == "RETURN_VALUE":
  1147. returns.append(inst)
  1148. if len(returns) == 1 and returns[0] is insts[-1]:
  1149. # only 1 return at the end - just pop it
  1150. insts.pop(-1)
  1151. elif len(returns) > 0:
  1152. # create jump target - if the last inst is a return,
  1153. # we can replace it with a NOP and make that the jump target.
  1154. if insts[-1] is returns[-1]:
  1155. insts[-1].opname = "NOP"
  1156. insts[-1].opcode = dis.opmap["NOP"]
  1157. insts[-1].arg = None
  1158. insts[-1].argval = _NotProvided
  1159. returns.pop(-1)
  1160. else:
  1161. insts.append(create_instruction("NOP"))
  1162. # replace returns with jumps
  1163. for inst in returns:
  1164. # don't replace inst with new instruction
  1165. # due to targetting/exn table/etc.
  1166. jump_inst = create_jump_absolute(insts[-1])
  1167. inst.opname = jump_inst.opname
  1168. inst.opcode = jump_inst.opcode
  1169. inst.arg = jump_inst.arg
  1170. inst.argval = jump_inst.argval
  1171. inst.target = jump_inst.target
  1172. return insts