ll_builder.py 98 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404
  1. """A "low-level" IR builder class.
  2. LowLevelIRBuilder provides core abstractions we use for constructing
  3. IR as well as a number of higher-level ones (accessing attributes,
  4. calling functions and methods, and coercing between types, for
  5. example). The core principle of the low-level IR builder is that all
  6. of its facilities operate solely on the IR level and not the AST
  7. level---it has *no knowledge* of mypy types or expressions.
  8. """
  9. from __future__ import annotations
  10. from typing import Callable, Final, Optional, Sequence, Tuple
  11. from mypy.argmap import map_actuals_to_formals
  12. from mypy.nodes import ARG_POS, ARG_STAR, ARG_STAR2, ArgKind
  13. from mypy.operators import op_methods
  14. from mypy.types import AnyType, TypeOfAny
  15. from mypyc.common import (
  16. BITMAP_BITS,
  17. FAST_ISINSTANCE_MAX_SUBCLASSES,
  18. MAX_LITERAL_SHORT_INT,
  19. MAX_SHORT_INT,
  20. MIN_LITERAL_SHORT_INT,
  21. MIN_SHORT_INT,
  22. PLATFORM_SIZE,
  23. use_method_vectorcall,
  24. use_vectorcall,
  25. )
  26. from mypyc.errors import Errors
  27. from mypyc.ir.class_ir import ClassIR, all_concrete_classes
  28. from mypyc.ir.func_ir import FuncDecl, FuncSignature
  29. from mypyc.ir.ops import (
  30. ERR_FALSE,
  31. ERR_NEVER,
  32. NAMESPACE_MODULE,
  33. NAMESPACE_STATIC,
  34. NAMESPACE_TYPE,
  35. Assign,
  36. AssignMulti,
  37. BasicBlock,
  38. Box,
  39. Branch,
  40. Call,
  41. CallC,
  42. Cast,
  43. ComparisonOp,
  44. Extend,
  45. Float,
  46. FloatComparisonOp,
  47. FloatNeg,
  48. FloatOp,
  49. GetAttr,
  50. GetElementPtr,
  51. Goto,
  52. Integer,
  53. IntOp,
  54. KeepAlive,
  55. LoadAddress,
  56. LoadErrorValue,
  57. LoadLiteral,
  58. LoadMem,
  59. LoadStatic,
  60. MethodCall,
  61. Op,
  62. RaiseStandardError,
  63. Register,
  64. SetMem,
  65. Truncate,
  66. TupleGet,
  67. TupleSet,
  68. Unbox,
  69. Unreachable,
  70. Value,
  71. float_comparison_op_to_id,
  72. float_op_to_id,
  73. int_op_to_id,
  74. )
  75. from mypyc.ir.rtypes import (
  76. PyListObject,
  77. PyObject,
  78. PySetObject,
  79. PyVarObject,
  80. RArray,
  81. RInstance,
  82. RPrimitive,
  83. RTuple,
  84. RType,
  85. RUnion,
  86. bit_rprimitive,
  87. bitmap_rprimitive,
  88. bool_rprimitive,
  89. bytes_rprimitive,
  90. c_int_rprimitive,
  91. c_pointer_rprimitive,
  92. c_pyssize_t_rprimitive,
  93. c_size_t_rprimitive,
  94. check_native_int_range,
  95. dict_rprimitive,
  96. float_rprimitive,
  97. int_rprimitive,
  98. is_bit_rprimitive,
  99. is_bool_rprimitive,
  100. is_bytes_rprimitive,
  101. is_dict_rprimitive,
  102. is_fixed_width_rtype,
  103. is_float_rprimitive,
  104. is_int16_rprimitive,
  105. is_int32_rprimitive,
  106. is_int64_rprimitive,
  107. is_int_rprimitive,
  108. is_list_rprimitive,
  109. is_none_rprimitive,
  110. is_set_rprimitive,
  111. is_short_int_rprimitive,
  112. is_str_rprimitive,
  113. is_tagged,
  114. is_tuple_rprimitive,
  115. is_uint8_rprimitive,
  116. list_rprimitive,
  117. none_rprimitive,
  118. object_pointer_rprimitive,
  119. object_rprimitive,
  120. optional_value_type,
  121. pointer_rprimitive,
  122. short_int_rprimitive,
  123. str_rprimitive,
  124. )
  125. from mypyc.irbuild.mapper import Mapper
  126. from mypyc.irbuild.util import concrete_arg_kind
  127. from mypyc.options import CompilerOptions
  128. from mypyc.primitives.bytes_ops import bytes_compare
  129. from mypyc.primitives.dict_ops import (
  130. dict_build_op,
  131. dict_new_op,
  132. dict_ssize_t_size_op,
  133. dict_update_in_display_op,
  134. )
  135. from mypyc.primitives.exc_ops import err_occurred_op, keep_propagating_op
  136. from mypyc.primitives.float_ops import copysign_op, int_to_float_op
  137. from mypyc.primitives.generic_ops import (
  138. generic_len_op,
  139. generic_ssize_t_len_op,
  140. py_call_op,
  141. py_call_with_kwargs_op,
  142. py_getattr_op,
  143. py_method_call_op,
  144. py_vectorcall_method_op,
  145. py_vectorcall_op,
  146. )
  147. from mypyc.primitives.int_ops import (
  148. int16_divide_op,
  149. int16_mod_op,
  150. int16_overflow,
  151. int32_divide_op,
  152. int32_mod_op,
  153. int32_overflow,
  154. int64_divide_op,
  155. int64_mod_op,
  156. int64_to_int_op,
  157. int_comparison_op_mapping,
  158. int_to_int32_op,
  159. int_to_int64_op,
  160. ssize_t_to_int_op,
  161. uint8_overflow,
  162. )
  163. from mypyc.primitives.list_ops import list_build_op, list_extend_op, new_list_op
  164. from mypyc.primitives.misc_ops import bool_op, fast_isinstance_op, none_object_op
  165. from mypyc.primitives.registry import (
  166. ERR_NEG_INT,
  167. CFunctionDescription,
  168. binary_ops,
  169. method_call_ops,
  170. unary_ops,
  171. )
  172. from mypyc.primitives.set_ops import new_set_op
  173. from mypyc.primitives.str_ops import str_check_if_true, str_ssize_t_size_op, unicode_compare
  174. from mypyc.primitives.tuple_ops import list_tuple_op, new_tuple_op, new_tuple_with_length_op
  175. from mypyc.rt_subtype import is_runtime_subtype
  176. from mypyc.sametype import is_same_type
  177. from mypyc.subtype import is_subtype
  178. DictEntry = Tuple[Optional[Value], Value]
  179. # If the number of items is less than the threshold when initializing
  180. # a list, we would inline the generate IR using SetMem and expanded
  181. # for-loop. Otherwise, we would call `list_build_op` for larger lists.
  182. # TODO: The threshold is a randomly chosen number which needs further
  183. # study on real-world projects for a better balance.
  184. LIST_BUILDING_EXPANSION_THRESHOLD = 10
  185. # From CPython
  186. PY_VECTORCALL_ARGUMENTS_OFFSET: Final = 1 << (PLATFORM_SIZE * 8 - 1)
  187. FIXED_WIDTH_INT_BINARY_OPS: Final = {
  188. "+",
  189. "-",
  190. "*",
  191. "//",
  192. "%",
  193. "&",
  194. "|",
  195. "^",
  196. "<<",
  197. ">>",
  198. "+=",
  199. "-=",
  200. "*=",
  201. "//=",
  202. "%=",
  203. "&=",
  204. "|=",
  205. "^=",
  206. "<<=",
  207. ">>=",
  208. }
  209. # Binary operations on bools that are specialized and don't just promote operands to int
  210. BOOL_BINARY_OPS: Final = {"&", "&=", "|", "|=", "^", "^=", "==", "!=", "<", "<=", ">", ">="}
  211. class LowLevelIRBuilder:
  212. def __init__(
  213. self, current_module: str, errors: Errors, mapper: Mapper, options: CompilerOptions
  214. ) -> None:
  215. self.current_module = current_module
  216. self.errors = errors
  217. self.mapper = mapper
  218. self.options = options
  219. self.args: list[Register] = []
  220. self.blocks: list[BasicBlock] = []
  221. # Stack of except handler entry blocks
  222. self.error_handlers: list[BasicBlock | None] = [None]
  223. # Values that we need to keep alive as long as we have borrowed
  224. # temporaries. Use flush_keep_alives() to mark the end of the live range.
  225. self.keep_alives: list[Value] = []
  226. def set_module(self, module_name: str, module_path: str) -> None:
  227. """Set the name and path of the current module."""
  228. self.module_name = module_name
  229. self.module_path = module_path
  230. # Basic operations
  231. def add(self, op: Op) -> Value:
  232. """Add an op."""
  233. assert not self.blocks[-1].terminated, "Can't add to finished block"
  234. self.blocks[-1].ops.append(op)
  235. return op
  236. def goto(self, target: BasicBlock) -> None:
  237. """Add goto to a basic block."""
  238. if not self.blocks[-1].terminated:
  239. self.add(Goto(target))
  240. def activate_block(self, block: BasicBlock) -> None:
  241. """Add a basic block and make it the active one (target of adds)."""
  242. if self.blocks:
  243. assert self.blocks[-1].terminated
  244. block.error_handler = self.error_handlers[-1]
  245. self.blocks.append(block)
  246. def goto_and_activate(self, block: BasicBlock) -> None:
  247. """Add goto a block and make it the active block."""
  248. self.goto(block)
  249. self.activate_block(block)
  250. def push_error_handler(self, handler: BasicBlock | None) -> None:
  251. self.error_handlers.append(handler)
  252. def pop_error_handler(self) -> BasicBlock | None:
  253. return self.error_handlers.pop()
  254. def self(self) -> Register:
  255. """Return reference to the 'self' argument.
  256. This only works in a method.
  257. """
  258. return self.args[0]
  259. def flush_keep_alives(self) -> None:
  260. if self.keep_alives:
  261. self.add(KeepAlive(self.keep_alives.copy()))
  262. self.keep_alives = []
  263. # Type conversions
  264. def box(self, src: Value) -> Value:
  265. if src.type.is_unboxed:
  266. if isinstance(src, Integer) and is_tagged(src.type):
  267. return self.add(LoadLiteral(src.value >> 1, rtype=object_rprimitive))
  268. return self.add(Box(src))
  269. else:
  270. return src
  271. def unbox_or_cast(
  272. self, src: Value, target_type: RType, line: int, *, can_borrow: bool = False
  273. ) -> Value:
  274. if target_type.is_unboxed:
  275. return self.add(Unbox(src, target_type, line))
  276. else:
  277. if can_borrow:
  278. self.keep_alives.append(src)
  279. return self.add(Cast(src, target_type, line, borrow=can_borrow))
  280. def coerce(
  281. self,
  282. src: Value,
  283. target_type: RType,
  284. line: int,
  285. force: bool = False,
  286. *,
  287. can_borrow: bool = False,
  288. ) -> Value:
  289. """Generate a coercion/cast from one type to other (only if needed).
  290. For example, int -> object boxes the source int; int -> int emits nothing;
  291. object -> int unboxes the object. All conversions preserve object value.
  292. If force is true, always generate an op (even if it is just an assignment) so
  293. that the result will have exactly target_type as the type.
  294. Returns the register with the converted value (may be same as src).
  295. """
  296. src_type = src.type
  297. if src_type.is_unboxed and not target_type.is_unboxed:
  298. # Unboxed -> boxed
  299. return self.box(src)
  300. if (src_type.is_unboxed and target_type.is_unboxed) and not is_runtime_subtype(
  301. src_type, target_type
  302. ):
  303. if (
  304. isinstance(src, Integer)
  305. and is_short_int_rprimitive(src_type)
  306. and is_fixed_width_rtype(target_type)
  307. ):
  308. value = src.numeric_value()
  309. if not check_native_int_range(target_type, value):
  310. self.error(f'Value {value} is out of range for "{target_type}"', line)
  311. return Integer(src.value >> 1, target_type)
  312. elif is_int_rprimitive(src_type) and is_fixed_width_rtype(target_type):
  313. return self.coerce_int_to_fixed_width(src, target_type, line)
  314. elif is_fixed_width_rtype(src_type) and is_int_rprimitive(target_type):
  315. return self.coerce_fixed_width_to_int(src, line)
  316. elif is_short_int_rprimitive(src_type) and is_fixed_width_rtype(target_type):
  317. return self.coerce_short_int_to_fixed_width(src, target_type, line)
  318. elif (
  319. isinstance(src_type, RPrimitive)
  320. and isinstance(target_type, RPrimitive)
  321. and src_type.is_native_int
  322. and target_type.is_native_int
  323. and src_type.size == target_type.size
  324. and src_type.is_signed == target_type.is_signed
  325. ):
  326. # Equivalent types
  327. return src
  328. elif (is_bool_rprimitive(src_type) or is_bit_rprimitive(src_type)) and is_tagged(
  329. target_type
  330. ):
  331. shifted = self.int_op(
  332. bool_rprimitive, src, Integer(1, bool_rprimitive), IntOp.LEFT_SHIFT
  333. )
  334. return self.add(Extend(shifted, target_type, signed=False))
  335. elif (
  336. is_bool_rprimitive(src_type) or is_bit_rprimitive(src_type)
  337. ) and is_fixed_width_rtype(target_type):
  338. return self.add(Extend(src, target_type, signed=False))
  339. elif isinstance(src, Integer) and is_float_rprimitive(target_type):
  340. if is_tagged(src_type):
  341. return Float(float(src.value // 2))
  342. return Float(float(src.value))
  343. elif is_tagged(src_type) and is_float_rprimitive(target_type):
  344. return self.int_to_float(src, line)
  345. elif (
  346. isinstance(src_type, RTuple)
  347. and isinstance(target_type, RTuple)
  348. and len(src_type.types) == len(target_type.types)
  349. ):
  350. # Coerce between two tuple types by coercing each item separately
  351. values = []
  352. for i in range(len(src_type.types)):
  353. v = None
  354. if isinstance(src, TupleSet):
  355. item = src.items[i]
  356. # We can't reuse register values, since they can be modified.
  357. if not isinstance(item, Register):
  358. v = item
  359. if v is None:
  360. v = TupleGet(src, i)
  361. self.add(v)
  362. values.append(v)
  363. return self.add(
  364. TupleSet(
  365. [self.coerce(v, t, line) for v, t in zip(values, target_type.types)], line
  366. )
  367. )
  368. # To go between any other unboxed types, we go through a boxed
  369. # in-between value, for simplicity.
  370. tmp = self.box(src)
  371. return self.unbox_or_cast(tmp, target_type, line)
  372. if (not src_type.is_unboxed and target_type.is_unboxed) or not is_subtype(
  373. src_type, target_type
  374. ):
  375. return self.unbox_or_cast(src, target_type, line, can_borrow=can_borrow)
  376. elif force:
  377. tmp = Register(target_type)
  378. self.add(Assign(tmp, src))
  379. return tmp
  380. return src
  381. def coerce_int_to_fixed_width(self, src: Value, target_type: RType, line: int) -> Value:
  382. assert is_fixed_width_rtype(target_type), target_type
  383. assert isinstance(target_type, RPrimitive)
  384. res = Register(target_type)
  385. fast, slow, end = BasicBlock(), BasicBlock(), BasicBlock()
  386. check = self.check_tagged_short_int(src, line)
  387. self.add(Branch(check, fast, slow, Branch.BOOL))
  388. self.activate_block(fast)
  389. size = target_type.size
  390. if size < int_rprimitive.size:
  391. # Add a range check when the target type is smaller than the source tyoe
  392. fast2, fast3 = BasicBlock(), BasicBlock()
  393. upper_bound = 1 << (size * 8 - 1)
  394. if not target_type.is_signed:
  395. upper_bound *= 2
  396. check2 = self.add(ComparisonOp(src, Integer(upper_bound, src.type), ComparisonOp.SLT))
  397. self.add(Branch(check2, fast2, slow, Branch.BOOL))
  398. self.activate_block(fast2)
  399. if target_type.is_signed:
  400. lower_bound = -upper_bound
  401. else:
  402. lower_bound = 0
  403. check3 = self.add(ComparisonOp(src, Integer(lower_bound, src.type), ComparisonOp.SGE))
  404. self.add(Branch(check3, fast3, slow, Branch.BOOL))
  405. self.activate_block(fast3)
  406. tmp = self.int_op(
  407. c_pyssize_t_rprimitive,
  408. src,
  409. Integer(1, c_pyssize_t_rprimitive),
  410. IntOp.RIGHT_SHIFT,
  411. line,
  412. )
  413. tmp = self.add(Truncate(tmp, target_type))
  414. else:
  415. if size > int_rprimitive.size:
  416. tmp = self.add(Extend(src, target_type, signed=True))
  417. else:
  418. tmp = src
  419. tmp = self.int_op(target_type, tmp, Integer(1, target_type), IntOp.RIGHT_SHIFT, line)
  420. self.add(Assign(res, tmp))
  421. self.goto(end)
  422. self.activate_block(slow)
  423. if is_int64_rprimitive(target_type) or (
  424. is_int32_rprimitive(target_type) and size == int_rprimitive.size
  425. ):
  426. # Slow path calls a library function that handles more complex logic
  427. ptr = self.int_op(
  428. pointer_rprimitive, src, Integer(1, pointer_rprimitive), IntOp.XOR, line
  429. )
  430. ptr2 = Register(c_pointer_rprimitive)
  431. self.add(Assign(ptr2, ptr))
  432. if is_int64_rprimitive(target_type):
  433. conv_op = int_to_int64_op
  434. else:
  435. conv_op = int_to_int32_op
  436. tmp = self.call_c(conv_op, [ptr2], line)
  437. self.add(Assign(res, tmp))
  438. self.add(KeepAlive([src]))
  439. self.goto(end)
  440. elif is_int32_rprimitive(target_type):
  441. # Slow path just always generates an OverflowError
  442. self.call_c(int32_overflow, [], line)
  443. self.add(Unreachable())
  444. elif is_int16_rprimitive(target_type):
  445. # Slow path just always generates an OverflowError
  446. self.call_c(int16_overflow, [], line)
  447. self.add(Unreachable())
  448. elif is_uint8_rprimitive(target_type):
  449. # Slow path just always generates an OverflowError
  450. self.call_c(uint8_overflow, [], line)
  451. self.add(Unreachable())
  452. else:
  453. assert False, target_type
  454. self.activate_block(end)
  455. return res
  456. def coerce_short_int_to_fixed_width(self, src: Value, target_type: RType, line: int) -> Value:
  457. if is_int64_rprimitive(target_type):
  458. return self.int_op(target_type, src, Integer(1, target_type), IntOp.RIGHT_SHIFT, line)
  459. # TODO: i32
  460. assert False, (src.type, target_type)
  461. def coerce_fixed_width_to_int(self, src: Value, line: int) -> Value:
  462. if (
  463. (is_int32_rprimitive(src.type) and PLATFORM_SIZE == 8)
  464. or is_int16_rprimitive(src.type)
  465. or is_uint8_rprimitive(src.type)
  466. ):
  467. # Simple case -- just sign extend and shift.
  468. extended = self.add(Extend(src, c_pyssize_t_rprimitive, signed=src.type.is_signed))
  469. return self.int_op(
  470. int_rprimitive,
  471. extended,
  472. Integer(1, c_pyssize_t_rprimitive),
  473. IntOp.LEFT_SHIFT,
  474. line,
  475. )
  476. assert is_fixed_width_rtype(src.type)
  477. assert isinstance(src.type, RPrimitive)
  478. src_type = src.type
  479. res = Register(int_rprimitive)
  480. fast, fast2, slow, end = BasicBlock(), BasicBlock(), BasicBlock(), BasicBlock()
  481. c1 = self.add(ComparisonOp(src, Integer(MAX_SHORT_INT, src_type), ComparisonOp.SLE))
  482. self.add(Branch(c1, fast, slow, Branch.BOOL))
  483. self.activate_block(fast)
  484. c2 = self.add(ComparisonOp(src, Integer(MIN_SHORT_INT, src_type), ComparisonOp.SGE))
  485. self.add(Branch(c2, fast2, slow, Branch.BOOL))
  486. self.activate_block(slow)
  487. if is_int64_rprimitive(src_type):
  488. conv_op = int64_to_int_op
  489. elif is_int32_rprimitive(src_type):
  490. assert PLATFORM_SIZE == 4
  491. conv_op = ssize_t_to_int_op
  492. else:
  493. assert False, src_type
  494. x = self.call_c(conv_op, [src], line)
  495. self.add(Assign(res, x))
  496. self.goto(end)
  497. self.activate_block(fast2)
  498. if int_rprimitive.size < src_type.size:
  499. tmp = self.add(Truncate(src, c_pyssize_t_rprimitive))
  500. else:
  501. tmp = src
  502. s = self.int_op(int_rprimitive, tmp, Integer(1, tmp.type), IntOp.LEFT_SHIFT, line)
  503. self.add(Assign(res, s))
  504. self.goto(end)
  505. self.activate_block(end)
  506. return res
  507. def coerce_nullable(self, src: Value, target_type: RType, line: int) -> Value:
  508. """Generate a coercion from a potentially null value."""
  509. if src.type.is_unboxed == target_type.is_unboxed and (
  510. (target_type.is_unboxed and is_runtime_subtype(src.type, target_type))
  511. or (not target_type.is_unboxed and is_subtype(src.type, target_type))
  512. ):
  513. return src
  514. target = Register(target_type)
  515. valid, invalid, out = BasicBlock(), BasicBlock(), BasicBlock()
  516. self.add(Branch(src, invalid, valid, Branch.IS_ERROR))
  517. self.activate_block(valid)
  518. coerced = self.coerce(src, target_type, line)
  519. self.add(Assign(target, coerced, line))
  520. self.goto(out)
  521. self.activate_block(invalid)
  522. error = self.add(LoadErrorValue(target_type))
  523. self.add(Assign(target, error, line))
  524. self.goto_and_activate(out)
  525. return target
  526. # Attribute access
  527. def get_attr(
  528. self, obj: Value, attr: str, result_type: RType, line: int, *, borrow: bool = False
  529. ) -> Value:
  530. """Get a native or Python attribute of an object."""
  531. if (
  532. isinstance(obj.type, RInstance)
  533. and obj.type.class_ir.is_ext_class
  534. and obj.type.class_ir.has_attr(attr)
  535. ):
  536. op = GetAttr(obj, attr, line, borrow=borrow)
  537. # For non-refcounted attribute types, the borrow might be
  538. # disabled even if requested, so don't check 'borrow'.
  539. if op.is_borrowed:
  540. self.keep_alives.append(obj)
  541. return self.add(op)
  542. elif isinstance(obj.type, RUnion):
  543. return self.union_get_attr(obj, obj.type, attr, result_type, line)
  544. else:
  545. return self.py_get_attr(obj, attr, line)
  546. def union_get_attr(
  547. self, obj: Value, rtype: RUnion, attr: str, result_type: RType, line: int
  548. ) -> Value:
  549. """Get an attribute of an object with a union type."""
  550. def get_item_attr(value: Value) -> Value:
  551. return self.get_attr(value, attr, result_type, line)
  552. return self.decompose_union_helper(obj, rtype, result_type, get_item_attr, line)
  553. def py_get_attr(self, obj: Value, attr: str, line: int) -> Value:
  554. """Get a Python attribute (slow).
  555. Prefer get_attr() which generates optimized code for native classes.
  556. """
  557. key = self.load_str(attr)
  558. return self.call_c(py_getattr_op, [obj, key], line)
  559. # isinstance() checks
  560. def isinstance_helper(self, obj: Value, class_irs: list[ClassIR], line: int) -> Value:
  561. """Fast path for isinstance() that checks against a list of native classes."""
  562. if not class_irs:
  563. return self.false()
  564. ret = self.isinstance_native(obj, class_irs[0], line)
  565. for class_ir in class_irs[1:]:
  566. def other() -> Value:
  567. return self.isinstance_native(obj, class_ir, line)
  568. ret = self.shortcircuit_helper("or", bool_rprimitive, lambda: ret, other, line)
  569. return ret
  570. def get_type_of_obj(self, obj: Value, line: int) -> Value:
  571. ob_type_address = self.add(GetElementPtr(obj, PyObject, "ob_type", line))
  572. ob_type = self.add(LoadMem(object_rprimitive, ob_type_address))
  573. self.add(KeepAlive([obj]))
  574. return ob_type
  575. def type_is_op(self, obj: Value, type_obj: Value, line: int) -> Value:
  576. typ = self.get_type_of_obj(obj, line)
  577. return self.add(ComparisonOp(typ, type_obj, ComparisonOp.EQ, line))
  578. def isinstance_native(self, obj: Value, class_ir: ClassIR, line: int) -> Value:
  579. """Fast isinstance() check for a native class.
  580. If there are three or fewer concrete (non-trait) classes among the class
  581. and all its children, use even faster type comparison checks `type(obj)
  582. is typ`.
  583. """
  584. concrete = all_concrete_classes(class_ir)
  585. if concrete is None or len(concrete) > FAST_ISINSTANCE_MAX_SUBCLASSES + 1:
  586. return self.call_c(fast_isinstance_op, [obj, self.get_native_type(class_ir)], line)
  587. if not concrete:
  588. # There can't be any concrete instance that matches this.
  589. return self.false()
  590. type_obj = self.get_native_type(concrete[0])
  591. ret = self.type_is_op(obj, type_obj, line)
  592. for c in concrete[1:]:
  593. def other() -> Value:
  594. return self.type_is_op(obj, self.get_native_type(c), line)
  595. ret = self.shortcircuit_helper("or", bool_rprimitive, lambda: ret, other, line)
  596. return ret
  597. # Calls
  598. def _construct_varargs(
  599. self,
  600. args: Sequence[tuple[Value, ArgKind, str | None]],
  601. line: int,
  602. *,
  603. has_star: bool,
  604. has_star2: bool,
  605. ) -> tuple[Value | None, Value | None]:
  606. """Construct *args and **kwargs from a collection of arguments
  607. This is pretty complicated, and almost all of the complication here stems from
  608. one of two things (but mostly the second):
  609. * The handling of ARG_STAR/ARG_STAR2. We want to create as much of the args/kwargs
  610. values in one go as we can, so we collect values until our hand is forced, and
  611. then we emit creation of the list/tuple, and expand it from there if needed.
  612. * Support potentially nullable argument values. This has very narrow applicability,
  613. as this will never be done by our compiled Python code, but is critically used
  614. by gen_glue_method when generating glue methods to mediate between the function
  615. signature of a parent class and its subclasses.
  616. For named-only arguments, this is quite simple: if it is
  617. null, don't put it in the dict.
  618. For positional-or-named arguments, things are much more complicated.
  619. * First, anything that was passed as a positional arg
  620. must be forwarded along as a positional arg. It *must
  621. not* be converted to a named arg. This is because mypy
  622. does not enforce that positional-or-named arguments
  623. have the same name in subclasses, and it is not
  624. uncommon for code to have different names in
  625. subclasses (a bunch of mypy's visitors do this, for
  626. example!). This is arguably a bug in both mypy and code doing
  627. this, and they ought to be using positional-only arguments, but
  628. positional-only arguments are new and ugly.
  629. * On the flip side, we're willing to accept the
  630. infelicity of sometimes turning an argument that was
  631. passed by keyword into a positional argument. It's wrong,
  632. but it's very marginal, and avoiding it would require passing
  633. a bitmask of which arguments were named with every function call,
  634. or something similar.
  635. (See some discussion of this in testComplicatedArgs)
  636. Thus, our strategy for positional-or-named arguments is to
  637. always pass them as positional, except in the one
  638. situation where we can not, and where we can be absolutely
  639. sure they were passed by name: when an *earlier*
  640. positional argument was missing its value.
  641. This means that if we have a method `f(self, x: int=..., y: object=...)`:
  642. * x and y present: args=(x, y), kwargs={}
  643. * x present, y missing: args=(x,), kwargs={}
  644. * x missing, y present: args=(), kwargs={'y': y}
  645. To implement this, when we have multiple optional
  646. positional arguments, we maintain a flag in a register
  647. that tracks whether an argument has been missing, and for
  648. each such optional argument (except the first), we check
  649. the flag to determine whether to append the argument to
  650. the *args list or add it to the **kwargs dict. What a
  651. mess!
  652. This is what really makes everything here such a tangle;
  653. otherwise the *args and **kwargs code could be separated.
  654. The arguments has_star and has_star2 indicate whether the target function
  655. takes an ARG_STAR and ARG_STAR2 argument, respectively.
  656. (These will always be true when making a pycall, and be based
  657. on the actual target signature for a native call.)
  658. """
  659. star_result: Value | None = None
  660. star2_result: Value | None = None
  661. # We aggregate values that need to go into *args and **kwargs
  662. # in these lists. Once all arguments are processed (in the
  663. # happiest case), or we encounter an ARG_STAR/ARG_STAR2 or a
  664. # nullable arg, then we create the list and/or dict.
  665. star_values: list[Value] = []
  666. star2_keys: list[Value] = []
  667. star2_values: list[Value] = []
  668. seen_empty_reg: Register | None = None
  669. for value, kind, name in args:
  670. if kind == ARG_STAR:
  671. if star_result is None:
  672. star_result = self.new_list_op(star_values, line)
  673. self.call_c(list_extend_op, [star_result, value], line)
  674. elif kind == ARG_STAR2:
  675. if star2_result is None:
  676. star2_result = self._create_dict(star2_keys, star2_values, line)
  677. self.call_c(dict_update_in_display_op, [star2_result, value], line=line)
  678. else:
  679. nullable = kind.is_optional()
  680. maybe_pos = kind.is_positional() and has_star
  681. maybe_named = kind.is_named() or (kind.is_optional() and name and has_star2)
  682. # If the argument is nullable, we need to create the
  683. # relevant args/kwargs objects so that we can
  684. # conditionally modify them.
  685. if nullable:
  686. if maybe_pos and star_result is None:
  687. star_result = self.new_list_op(star_values, line)
  688. if maybe_named and star2_result is None:
  689. star2_result = self._create_dict(star2_keys, star2_values, line)
  690. # Easy cases: just collect the argument.
  691. if maybe_pos and star_result is None:
  692. star_values.append(value)
  693. continue
  694. if maybe_named and star2_result is None:
  695. assert name is not None
  696. key = self.load_str(name)
  697. star2_keys.append(key)
  698. star2_values.append(value)
  699. continue
  700. # OK, anything that is nullable or *after* a nullable arg needs to be here
  701. # TODO: We could try harder to avoid creating basic blocks in the common case
  702. new_seen_empty_reg = seen_empty_reg
  703. out = BasicBlock()
  704. if nullable:
  705. # If this is the first nullable positional arg we've seen, create
  706. # a register to track whether anything has been null.
  707. # (We won't *check* the register until the next argument, though.)
  708. if maybe_pos and not seen_empty_reg:
  709. new_seen_empty_reg = Register(bool_rprimitive)
  710. self.add(Assign(new_seen_empty_reg, self.false(), line))
  711. skip = BasicBlock() if maybe_pos else out
  712. keep = BasicBlock()
  713. self.add(Branch(value, skip, keep, Branch.IS_ERROR))
  714. self.activate_block(keep)
  715. # If this could be positional or named and we /might/ have seen a missing
  716. # positional arg, then we need to compile *both* a positional and named
  717. # version! What a pain!
  718. if maybe_pos and maybe_named and seen_empty_reg:
  719. pos_block, named_block = BasicBlock(), BasicBlock()
  720. self.add(Branch(seen_empty_reg, named_block, pos_block, Branch.BOOL))
  721. else:
  722. pos_block = named_block = BasicBlock()
  723. self.goto(pos_block)
  724. if maybe_pos:
  725. self.activate_block(pos_block)
  726. assert star_result
  727. self.translate_special_method_call(
  728. star_result, "append", [value], result_type=None, line=line
  729. )
  730. self.goto(out)
  731. if maybe_named and (not maybe_pos or seen_empty_reg):
  732. self.activate_block(named_block)
  733. assert name is not None
  734. key = self.load_str(name)
  735. assert star2_result
  736. self.translate_special_method_call(
  737. star2_result, "__setitem__", [key, value], result_type=None, line=line
  738. )
  739. self.goto(out)
  740. if nullable and maybe_pos and new_seen_empty_reg:
  741. assert skip is not out
  742. self.activate_block(skip)
  743. self.add(Assign(new_seen_empty_reg, self.true(), line))
  744. self.goto(out)
  745. self.activate_block(out)
  746. seen_empty_reg = new_seen_empty_reg
  747. assert not (star_result or star_values) or has_star
  748. assert not (star2_result or star2_values) or has_star2
  749. if has_star:
  750. # If we managed to make it this far without creating a
  751. # *args list, then we can directly create a
  752. # tuple. Otherwise create the tuple from the list.
  753. if star_result is None:
  754. star_result = self.new_tuple(star_values, line)
  755. else:
  756. star_result = self.call_c(list_tuple_op, [star_result], line)
  757. if has_star2 and star2_result is None:
  758. star2_result = self._create_dict(star2_keys, star2_values, line)
  759. return star_result, star2_result
  760. def py_call(
  761. self,
  762. function: Value,
  763. arg_values: list[Value],
  764. line: int,
  765. arg_kinds: list[ArgKind] | None = None,
  766. arg_names: Sequence[str | None] | None = None,
  767. ) -> Value:
  768. """Call a Python function (non-native and slow).
  769. Use py_call_op or py_call_with_kwargs_op for Python function call.
  770. """
  771. if use_vectorcall(self.options.capi_version):
  772. # More recent Python versions support faster vectorcalls.
  773. result = self._py_vector_call(function, arg_values, line, arg_kinds, arg_names)
  774. if result is not None:
  775. return result
  776. # If all arguments are positional, we can use py_call_op.
  777. if arg_kinds is None or all(kind == ARG_POS for kind in arg_kinds):
  778. return self.call_c(py_call_op, [function] + arg_values, line)
  779. # Otherwise fallback to py_call_with_kwargs_op.
  780. assert arg_names is not None
  781. pos_args_tuple, kw_args_dict = self._construct_varargs(
  782. list(zip(arg_values, arg_kinds, arg_names)), line, has_star=True, has_star2=True
  783. )
  784. assert pos_args_tuple and kw_args_dict
  785. return self.call_c(py_call_with_kwargs_op, [function, pos_args_tuple, kw_args_dict], line)
  786. def _py_vector_call(
  787. self,
  788. function: Value,
  789. arg_values: list[Value],
  790. line: int,
  791. arg_kinds: list[ArgKind] | None = None,
  792. arg_names: Sequence[str | None] | None = None,
  793. ) -> Value | None:
  794. """Call function using the vectorcall API if possible.
  795. Return the return value if successful. Return None if a non-vectorcall
  796. API should be used instead.
  797. """
  798. # We can do this if all args are positional or named (no *args or **kwargs, not optional).
  799. if arg_kinds is None or all(
  800. not kind.is_star() and not kind.is_optional() for kind in arg_kinds
  801. ):
  802. if arg_values:
  803. # Create a C array containing all arguments as boxed values.
  804. coerced_args = [self.coerce(arg, object_rprimitive, line) for arg in arg_values]
  805. arg_ptr = self.setup_rarray(object_rprimitive, coerced_args, object_ptr=True)
  806. else:
  807. arg_ptr = Integer(0, object_pointer_rprimitive)
  808. num_pos = num_positional_args(arg_values, arg_kinds)
  809. keywords = self._vectorcall_keywords(arg_names)
  810. value = self.call_c(
  811. py_vectorcall_op,
  812. [function, arg_ptr, Integer(num_pos, c_size_t_rprimitive), keywords],
  813. line,
  814. )
  815. if arg_values:
  816. # Make sure arguments won't be freed until after the call.
  817. # We need this because RArray doesn't support automatic
  818. # memory management.
  819. self.add(KeepAlive(coerced_args))
  820. return value
  821. return None
  822. def _vectorcall_keywords(self, arg_names: Sequence[str | None] | None) -> Value:
  823. """Return a reference to a tuple literal with keyword argument names.
  824. Return null pointer if there are no keyword arguments.
  825. """
  826. if arg_names:
  827. kw_list = [name for name in arg_names if name is not None]
  828. if kw_list:
  829. return self.add(LoadLiteral(tuple(kw_list), object_rprimitive))
  830. return Integer(0, object_rprimitive)
  831. def py_method_call(
  832. self,
  833. obj: Value,
  834. method_name: str,
  835. arg_values: list[Value],
  836. line: int,
  837. arg_kinds: list[ArgKind] | None,
  838. arg_names: Sequence[str | None] | None,
  839. ) -> Value:
  840. """Call a Python method (non-native and slow)."""
  841. if use_method_vectorcall(self.options.capi_version):
  842. # More recent Python versions support faster vectorcalls.
  843. result = self._py_vector_method_call(
  844. obj, method_name, arg_values, line, arg_kinds, arg_names
  845. )
  846. if result is not None:
  847. return result
  848. if arg_kinds is None or all(kind == ARG_POS for kind in arg_kinds):
  849. # Use legacy method call API
  850. method_name_reg = self.load_str(method_name)
  851. return self.call_c(py_method_call_op, [obj, method_name_reg] + arg_values, line)
  852. else:
  853. # Use py_call since it supports keyword arguments (and vectorcalls).
  854. method = self.py_get_attr(obj, method_name, line)
  855. return self.py_call(method, arg_values, line, arg_kinds=arg_kinds, arg_names=arg_names)
  856. def _py_vector_method_call(
  857. self,
  858. obj: Value,
  859. method_name: str,
  860. arg_values: list[Value],
  861. line: int,
  862. arg_kinds: list[ArgKind] | None,
  863. arg_names: Sequence[str | None] | None,
  864. ) -> Value | None:
  865. """Call method using the vectorcall API if possible.
  866. Return the return value if successful. Return None if a non-vectorcall
  867. API should be used instead.
  868. """
  869. if arg_kinds is None or all(
  870. not kind.is_star() and not kind.is_optional() for kind in arg_kinds
  871. ):
  872. method_name_reg = self.load_str(method_name)
  873. coerced_args = [
  874. self.coerce(arg, object_rprimitive, line) for arg in [obj] + arg_values
  875. ]
  876. arg_ptr = self.setup_rarray(object_rprimitive, coerced_args, object_ptr=True)
  877. num_pos = num_positional_args(arg_values, arg_kinds)
  878. keywords = self._vectorcall_keywords(arg_names)
  879. value = self.call_c(
  880. py_vectorcall_method_op,
  881. [
  882. method_name_reg,
  883. arg_ptr,
  884. Integer((num_pos + 1) | PY_VECTORCALL_ARGUMENTS_OFFSET, c_size_t_rprimitive),
  885. keywords,
  886. ],
  887. line,
  888. )
  889. # Make sure arguments won't be freed until after the call.
  890. # We need this because RArray doesn't support automatic
  891. # memory management.
  892. self.add(KeepAlive(coerced_args))
  893. return value
  894. return None
  895. def call(
  896. self,
  897. decl: FuncDecl,
  898. args: Sequence[Value],
  899. arg_kinds: list[ArgKind],
  900. arg_names: Sequence[str | None],
  901. line: int,
  902. *,
  903. bitmap_args: list[Register] | None = None,
  904. ) -> Value:
  905. """Call a native function.
  906. If bitmap_args is given, they override the values of (some) of the bitmap
  907. arguments used to track the presence of values for certain arguments. By
  908. default, the values of the bitmap arguments are inferred from args.
  909. """
  910. # Normalize args to positionals.
  911. args = self.native_args_to_positional(
  912. args, arg_kinds, arg_names, decl.sig, line, bitmap_args=bitmap_args
  913. )
  914. return self.add(Call(decl, args, line))
  915. def native_args_to_positional(
  916. self,
  917. args: Sequence[Value],
  918. arg_kinds: list[ArgKind],
  919. arg_names: Sequence[str | None],
  920. sig: FuncSignature,
  921. line: int,
  922. *,
  923. bitmap_args: list[Register] | None = None,
  924. ) -> list[Value]:
  925. """Prepare arguments for a native call.
  926. Given args/kinds/names and a target signature for a native call, map
  927. keyword arguments to their appropriate place in the argument list,
  928. fill in error values for unspecified default arguments,
  929. package arguments that will go into *args/**kwargs into a tuple/dict,
  930. and coerce arguments to the appropriate type.
  931. """
  932. sig_args = sig.args
  933. n = sig.num_bitmap_args
  934. if n:
  935. sig_args = sig_args[:-n]
  936. sig_arg_kinds = [arg.kind for arg in sig_args]
  937. sig_arg_names = [arg.name for arg in sig_args]
  938. concrete_kinds = [concrete_arg_kind(arg_kind) for arg_kind in arg_kinds]
  939. formal_to_actual = map_actuals_to_formals(
  940. concrete_kinds,
  941. arg_names,
  942. sig_arg_kinds,
  943. sig_arg_names,
  944. lambda n: AnyType(TypeOfAny.special_form),
  945. )
  946. # First scan for */** and construct those
  947. has_star = has_star2 = False
  948. star_arg_entries = []
  949. for lst, arg in zip(formal_to_actual, sig_args):
  950. if arg.kind.is_star():
  951. star_arg_entries.extend([(args[i], arg_kinds[i], arg_names[i]) for i in lst])
  952. has_star = has_star or arg.kind == ARG_STAR
  953. has_star2 = has_star2 or arg.kind == ARG_STAR2
  954. star_arg, star2_arg = self._construct_varargs(
  955. star_arg_entries, line, has_star=has_star, has_star2=has_star2
  956. )
  957. # Flatten out the arguments, loading error values for default
  958. # arguments, constructing tuples/dicts for star args, and
  959. # coercing everything to the expected type.
  960. output_args: list[Value] = []
  961. for lst, arg in zip(formal_to_actual, sig_args):
  962. if arg.kind == ARG_STAR:
  963. assert star_arg
  964. output_arg = star_arg
  965. elif arg.kind == ARG_STAR2:
  966. assert star2_arg
  967. output_arg = star2_arg
  968. elif not lst:
  969. if is_fixed_width_rtype(arg.type):
  970. output_arg = Integer(0, arg.type)
  971. elif is_float_rprimitive(arg.type):
  972. output_arg = Float(0.0)
  973. else:
  974. output_arg = self.add(LoadErrorValue(arg.type, is_borrowed=True))
  975. else:
  976. base_arg = args[lst[0]]
  977. if arg_kinds[lst[0]].is_optional():
  978. output_arg = self.coerce_nullable(base_arg, arg.type, line)
  979. else:
  980. output_arg = self.coerce(base_arg, arg.type, line)
  981. output_args.append(output_arg)
  982. for i in reversed(range(n)):
  983. if bitmap_args and i < len(bitmap_args):
  984. # Use override provided by caller
  985. output_args.append(bitmap_args[i])
  986. continue
  987. # Infer values of bitmap args
  988. bitmap = 0
  989. c = 0
  990. for lst, arg in zip(formal_to_actual, sig_args):
  991. if arg.kind.is_optional() and arg.type.error_overlap:
  992. if i * BITMAP_BITS <= c < (i + 1) * BITMAP_BITS:
  993. if lst:
  994. bitmap |= 1 << (c & (BITMAP_BITS - 1))
  995. c += 1
  996. output_args.append(Integer(bitmap, bitmap_rprimitive))
  997. return output_args
  998. def gen_method_call(
  999. self,
  1000. base: Value,
  1001. name: str,
  1002. arg_values: list[Value],
  1003. result_type: RType | None,
  1004. line: int,
  1005. arg_kinds: list[ArgKind] | None = None,
  1006. arg_names: list[str | None] | None = None,
  1007. can_borrow: bool = False,
  1008. ) -> Value:
  1009. """Generate either a native or Python method call."""
  1010. # If we have *args, then fallback to Python method call.
  1011. if arg_kinds is not None and any(kind.is_star() for kind in arg_kinds):
  1012. return self.py_method_call(base, name, arg_values, base.line, arg_kinds, arg_names)
  1013. # If the base type is one of ours, do a MethodCall
  1014. if (
  1015. isinstance(base.type, RInstance)
  1016. and base.type.class_ir.is_ext_class
  1017. and not base.type.class_ir.builtin_base
  1018. ):
  1019. if base.type.class_ir.has_method(name):
  1020. decl = base.type.class_ir.method_decl(name)
  1021. if arg_kinds is None:
  1022. assert arg_names is None, "arg_kinds not present but arg_names is"
  1023. arg_kinds = [ARG_POS for _ in arg_values]
  1024. arg_names = [None for _ in arg_values]
  1025. else:
  1026. assert arg_names is not None, "arg_kinds present but arg_names is not"
  1027. # Normalize args to positionals.
  1028. assert decl.bound_sig
  1029. arg_values = self.native_args_to_positional(
  1030. arg_values, arg_kinds, arg_names, decl.bound_sig, line
  1031. )
  1032. return self.add(MethodCall(base, name, arg_values, line))
  1033. elif base.type.class_ir.has_attr(name):
  1034. function = self.add(GetAttr(base, name, line))
  1035. return self.py_call(
  1036. function, arg_values, line, arg_kinds=arg_kinds, arg_names=arg_names
  1037. )
  1038. elif isinstance(base.type, RUnion):
  1039. return self.union_method_call(
  1040. base, base.type, name, arg_values, result_type, line, arg_kinds, arg_names
  1041. )
  1042. # Try to do a special-cased method call
  1043. if not arg_kinds or arg_kinds == [ARG_POS] * len(arg_values):
  1044. target = self.translate_special_method_call(
  1045. base, name, arg_values, result_type, line, can_borrow=can_borrow
  1046. )
  1047. if target:
  1048. return target
  1049. # Fall back to Python method call
  1050. return self.py_method_call(base, name, arg_values, line, arg_kinds, arg_names)
  1051. def union_method_call(
  1052. self,
  1053. base: Value,
  1054. obj_type: RUnion,
  1055. name: str,
  1056. arg_values: list[Value],
  1057. return_rtype: RType | None,
  1058. line: int,
  1059. arg_kinds: list[ArgKind] | None,
  1060. arg_names: list[str | None] | None,
  1061. ) -> Value:
  1062. """Generate a method call with a union type for the object."""
  1063. # Union method call needs a return_rtype for the type of the output register.
  1064. # If we don't have one, use object_rprimitive.
  1065. return_rtype = return_rtype or object_rprimitive
  1066. def call_union_item(value: Value) -> Value:
  1067. return self.gen_method_call(
  1068. value, name, arg_values, return_rtype, line, arg_kinds, arg_names
  1069. )
  1070. return self.decompose_union_helper(base, obj_type, return_rtype, call_union_item, line)
  1071. # Loading various values
  1072. def none(self) -> Value:
  1073. """Load unboxed None value (type: none_rprimitive)."""
  1074. return Integer(1, none_rprimitive)
  1075. def true(self) -> Value:
  1076. """Load unboxed True value (type: bool_rprimitive)."""
  1077. return Integer(1, bool_rprimitive)
  1078. def false(self) -> Value:
  1079. """Load unboxed False value (type: bool_rprimitive)."""
  1080. return Integer(0, bool_rprimitive)
  1081. def none_object(self) -> Value:
  1082. """Load Python None value (type: object_rprimitive)."""
  1083. return self.add(LoadAddress(none_object_op.type, none_object_op.src, line=-1))
  1084. def load_int(self, value: int) -> Value:
  1085. """Load a tagged (Python) integer literal value."""
  1086. if value > MAX_LITERAL_SHORT_INT or value < MIN_LITERAL_SHORT_INT:
  1087. return self.add(LoadLiteral(value, int_rprimitive))
  1088. else:
  1089. return Integer(value)
  1090. def load_float(self, value: float) -> Value:
  1091. """Load a float literal value."""
  1092. return Float(value)
  1093. def load_str(self, value: str) -> Value:
  1094. """Load a str literal value.
  1095. This is useful for more than just str literals; for example, method calls
  1096. also require a PyObject * form for the name of the method.
  1097. """
  1098. return self.add(LoadLiteral(value, str_rprimitive))
  1099. def load_bytes(self, value: bytes) -> Value:
  1100. """Load a bytes literal value."""
  1101. return self.add(LoadLiteral(value, bytes_rprimitive))
  1102. def load_complex(self, value: complex) -> Value:
  1103. """Load a complex literal value."""
  1104. return self.add(LoadLiteral(value, object_rprimitive))
  1105. def load_static_checked(
  1106. self,
  1107. typ: RType,
  1108. identifier: str,
  1109. module_name: str | None = None,
  1110. namespace: str = NAMESPACE_STATIC,
  1111. line: int = -1,
  1112. error_msg: str | None = None,
  1113. ) -> Value:
  1114. if error_msg is None:
  1115. error_msg = f'name "{identifier}" is not defined'
  1116. ok_block, error_block = BasicBlock(), BasicBlock()
  1117. value = self.add(LoadStatic(typ, identifier, module_name, namespace, line=line))
  1118. self.add(Branch(value, error_block, ok_block, Branch.IS_ERROR, rare=True))
  1119. self.activate_block(error_block)
  1120. self.add(RaiseStandardError(RaiseStandardError.NAME_ERROR, error_msg, line))
  1121. self.add(Unreachable())
  1122. self.activate_block(ok_block)
  1123. return value
  1124. def load_module(self, name: str) -> Value:
  1125. return self.add(LoadStatic(object_rprimitive, name, namespace=NAMESPACE_MODULE))
  1126. def get_native_type(self, cls: ClassIR) -> Value:
  1127. """Load native type object."""
  1128. fullname = f"{cls.module_name}.{cls.name}"
  1129. return self.load_native_type_object(fullname)
  1130. def load_native_type_object(self, fullname: str) -> Value:
  1131. module, name = fullname.rsplit(".", 1)
  1132. return self.add(LoadStatic(object_rprimitive, name, module, NAMESPACE_TYPE))
  1133. # Other primitive operations
  1134. def binary_op(self, lreg: Value, rreg: Value, op: str, line: int) -> Value:
  1135. """Perform a binary operation.
  1136. Generate specialized operations based on operand types, with a fallback
  1137. to generic operations.
  1138. """
  1139. ltype = lreg.type
  1140. rtype = rreg.type
  1141. # Special case tuple comparison here so that nested tuples can be supported
  1142. if isinstance(ltype, RTuple) and isinstance(rtype, RTuple) and op in ("==", "!="):
  1143. return self.compare_tuples(lreg, rreg, op, line)
  1144. # Special case == and != when we can resolve the method call statically
  1145. if op in ("==", "!="):
  1146. value = self.translate_eq_cmp(lreg, rreg, op, line)
  1147. if value is not None:
  1148. return value
  1149. # Special case various ops
  1150. if op in ("is", "is not"):
  1151. return self.translate_is_op(lreg, rreg, op, line)
  1152. # TODO: modify 'str' to use same interface as 'compare_bytes' as it avoids
  1153. # call to PyErr_Occurred()
  1154. if is_str_rprimitive(ltype) and is_str_rprimitive(rtype) and op in ("==", "!="):
  1155. return self.compare_strings(lreg, rreg, op, line)
  1156. if is_bytes_rprimitive(ltype) and is_bytes_rprimitive(rtype) and op in ("==", "!="):
  1157. return self.compare_bytes(lreg, rreg, op, line)
  1158. if is_tagged(ltype) and is_tagged(rtype) and op in int_comparison_op_mapping:
  1159. return self.compare_tagged(lreg, rreg, op, line)
  1160. if is_bool_rprimitive(ltype) and is_bool_rprimitive(rtype) and op in BOOL_BINARY_OPS:
  1161. if op in ComparisonOp.signed_ops:
  1162. return self.bool_comparison_op(lreg, rreg, op, line)
  1163. else:
  1164. return self.bool_bitwise_op(lreg, rreg, op[0], line)
  1165. if isinstance(rtype, RInstance) and op in ("in", "not in"):
  1166. return self.translate_instance_contains(rreg, lreg, op, line)
  1167. if is_fixed_width_rtype(ltype):
  1168. if op in FIXED_WIDTH_INT_BINARY_OPS:
  1169. if op.endswith("="):
  1170. op = op[:-1]
  1171. if op != "//":
  1172. op_id = int_op_to_id[op]
  1173. else:
  1174. op_id = IntOp.DIV
  1175. if is_bool_rprimitive(rtype) or is_bit_rprimitive(rtype):
  1176. rreg = self.coerce(rreg, ltype, line)
  1177. rtype = ltype
  1178. if is_fixed_width_rtype(rtype) or is_tagged(rtype):
  1179. return self.fixed_width_int_op(ltype, lreg, rreg, op_id, line)
  1180. if isinstance(rreg, Integer):
  1181. return self.fixed_width_int_op(
  1182. ltype, lreg, self.coerce(rreg, ltype, line), op_id, line
  1183. )
  1184. elif op in ComparisonOp.signed_ops:
  1185. if is_int_rprimitive(rtype):
  1186. rreg = self.coerce_int_to_fixed_width(rreg, ltype, line)
  1187. elif is_bool_rprimitive(rtype) or is_bit_rprimitive(rtype):
  1188. rreg = self.coerce(rreg, ltype, line)
  1189. op_id = ComparisonOp.signed_ops[op]
  1190. if is_fixed_width_rtype(rreg.type):
  1191. return self.comparison_op(lreg, rreg, op_id, line)
  1192. if isinstance(rreg, Integer):
  1193. return self.comparison_op(lreg, self.coerce(rreg, ltype, line), op_id, line)
  1194. elif is_fixed_width_rtype(rtype):
  1195. if op in FIXED_WIDTH_INT_BINARY_OPS:
  1196. if op.endswith("="):
  1197. op = op[:-1]
  1198. if op != "//":
  1199. op_id = int_op_to_id[op]
  1200. else:
  1201. op_id = IntOp.DIV
  1202. if isinstance(lreg, Integer):
  1203. return self.fixed_width_int_op(
  1204. rtype, self.coerce(lreg, rtype, line), rreg, op_id, line
  1205. )
  1206. if is_tagged(ltype):
  1207. return self.fixed_width_int_op(rtype, lreg, rreg, op_id, line)
  1208. if is_bool_rprimitive(ltype) or is_bit_rprimitive(ltype):
  1209. lreg = self.coerce(lreg, rtype, line)
  1210. return self.fixed_width_int_op(rtype, lreg, rreg, op_id, line)
  1211. elif op in ComparisonOp.signed_ops:
  1212. if is_int_rprimitive(ltype):
  1213. lreg = self.coerce_int_to_fixed_width(lreg, rtype, line)
  1214. elif is_bool_rprimitive(ltype) or is_bit_rprimitive(ltype):
  1215. lreg = self.coerce(lreg, rtype, line)
  1216. op_id = ComparisonOp.signed_ops[op]
  1217. if isinstance(lreg, Integer):
  1218. return self.comparison_op(self.coerce(lreg, rtype, line), rreg, op_id, line)
  1219. if is_fixed_width_rtype(lreg.type):
  1220. return self.comparison_op(lreg, rreg, op_id, line)
  1221. # Mixed int comparisons
  1222. if op in ("==", "!="):
  1223. op_id = ComparisonOp.signed_ops[op]
  1224. if is_tagged(ltype) and is_subtype(rtype, ltype):
  1225. rreg = self.coerce(rreg, int_rprimitive, line)
  1226. return self.comparison_op(lreg, rreg, op_id, line)
  1227. if is_tagged(rtype) and is_subtype(ltype, rtype):
  1228. lreg = self.coerce(lreg, int_rprimitive, line)
  1229. return self.comparison_op(lreg, rreg, op_id, line)
  1230. elif op in op in int_comparison_op_mapping:
  1231. if is_tagged(ltype) and is_subtype(rtype, ltype):
  1232. rreg = self.coerce(rreg, short_int_rprimitive, line)
  1233. return self.compare_tagged(lreg, rreg, op, line)
  1234. if is_tagged(rtype) and is_subtype(ltype, rtype):
  1235. lreg = self.coerce(lreg, short_int_rprimitive, line)
  1236. return self.compare_tagged(lreg, rreg, op, line)
  1237. if is_float_rprimitive(ltype) or is_float_rprimitive(rtype):
  1238. if isinstance(lreg, Integer):
  1239. lreg = Float(float(lreg.numeric_value()))
  1240. elif isinstance(rreg, Integer):
  1241. rreg = Float(float(rreg.numeric_value()))
  1242. elif is_int_rprimitive(lreg.type):
  1243. lreg = self.int_to_float(lreg, line)
  1244. elif is_int_rprimitive(rreg.type):
  1245. rreg = self.int_to_float(rreg, line)
  1246. if is_float_rprimitive(lreg.type) and is_float_rprimitive(rreg.type):
  1247. if op in float_comparison_op_to_id:
  1248. return self.compare_floats(lreg, rreg, float_comparison_op_to_id[op], line)
  1249. if op.endswith("="):
  1250. base_op = op[:-1]
  1251. else:
  1252. base_op = op
  1253. if base_op in float_op_to_id:
  1254. return self.float_op(lreg, rreg, base_op, line)
  1255. call_c_ops_candidates = binary_ops.get(op, [])
  1256. target = self.matching_call_c(call_c_ops_candidates, [lreg, rreg], line)
  1257. assert target, "Unsupported binary operation: %s" % op
  1258. return target
  1259. def check_tagged_short_int(self, val: Value, line: int, negated: bool = False) -> Value:
  1260. """Check if a tagged integer is a short integer.
  1261. Return the result of the check (value of type 'bit').
  1262. """
  1263. int_tag = Integer(1, c_pyssize_t_rprimitive, line)
  1264. bitwise_and = self.int_op(c_pyssize_t_rprimitive, val, int_tag, IntOp.AND, line)
  1265. zero = Integer(0, c_pyssize_t_rprimitive, line)
  1266. op = ComparisonOp.NEQ if negated else ComparisonOp.EQ
  1267. check = self.comparison_op(bitwise_and, zero, op, line)
  1268. return check
  1269. def compare_tagged(self, lhs: Value, rhs: Value, op: str, line: int) -> Value:
  1270. """Compare two tagged integers using given operator (value context)."""
  1271. # generate fast binary logic ops on short ints
  1272. if is_short_int_rprimitive(lhs.type) and is_short_int_rprimitive(rhs.type):
  1273. return self.comparison_op(lhs, rhs, int_comparison_op_mapping[op][0], line)
  1274. op_type, c_func_desc, negate_result, swap_op = int_comparison_op_mapping[op]
  1275. result = Register(bool_rprimitive)
  1276. short_int_block, int_block, out = BasicBlock(), BasicBlock(), BasicBlock()
  1277. check_lhs = self.check_tagged_short_int(lhs, line)
  1278. if op in ("==", "!="):
  1279. check = check_lhs
  1280. else:
  1281. # for non-equality logical ops (less/greater than, etc.), need to check both sides
  1282. check_rhs = self.check_tagged_short_int(rhs, line)
  1283. check = self.int_op(bit_rprimitive, check_lhs, check_rhs, IntOp.AND, line)
  1284. self.add(Branch(check, short_int_block, int_block, Branch.BOOL))
  1285. self.activate_block(short_int_block)
  1286. eq = self.comparison_op(lhs, rhs, op_type, line)
  1287. self.add(Assign(result, eq, line))
  1288. self.goto(out)
  1289. self.activate_block(int_block)
  1290. if swap_op:
  1291. args = [rhs, lhs]
  1292. else:
  1293. args = [lhs, rhs]
  1294. call = self.call_c(c_func_desc, args, line)
  1295. if negate_result:
  1296. # TODO: introduce UnaryIntOp?
  1297. call_result = self.unary_op(call, "not", line)
  1298. else:
  1299. call_result = call
  1300. self.add(Assign(result, call_result, line))
  1301. self.goto_and_activate(out)
  1302. return result
  1303. def compare_tagged_condition(
  1304. self, lhs: Value, rhs: Value, op: str, true: BasicBlock, false: BasicBlock, line: int
  1305. ) -> None:
  1306. """Compare two tagged integers using given operator (conditional context).
  1307. Assume lhs and rhs are tagged integers.
  1308. Args:
  1309. lhs: Left operand
  1310. rhs: Right operand
  1311. op: Operation, one of '==', '!=', '<', '<=', '>', '<='
  1312. true: Branch target if comparison is true
  1313. false: Branch target if comparison is false
  1314. """
  1315. is_eq = op in ("==", "!=")
  1316. if (is_short_int_rprimitive(lhs.type) and is_short_int_rprimitive(rhs.type)) or (
  1317. is_eq and (is_short_int_rprimitive(lhs.type) or is_short_int_rprimitive(rhs.type))
  1318. ):
  1319. # We can skip the tag check
  1320. check = self.comparison_op(lhs, rhs, int_comparison_op_mapping[op][0], line)
  1321. self.flush_keep_alives()
  1322. self.add(Branch(check, true, false, Branch.BOOL))
  1323. return
  1324. op_type, c_func_desc, negate_result, swap_op = int_comparison_op_mapping[op]
  1325. int_block, short_int_block = BasicBlock(), BasicBlock()
  1326. check_lhs = self.check_tagged_short_int(lhs, line, negated=True)
  1327. if is_eq or is_short_int_rprimitive(rhs.type):
  1328. self.flush_keep_alives()
  1329. self.add(Branch(check_lhs, int_block, short_int_block, Branch.BOOL))
  1330. else:
  1331. # For non-equality logical ops (less/greater than, etc.), need to check both sides
  1332. rhs_block = BasicBlock()
  1333. self.add(Branch(check_lhs, int_block, rhs_block, Branch.BOOL))
  1334. self.activate_block(rhs_block)
  1335. check_rhs = self.check_tagged_short_int(rhs, line, negated=True)
  1336. self.flush_keep_alives()
  1337. self.add(Branch(check_rhs, int_block, short_int_block, Branch.BOOL))
  1338. # Arbitrary integers (slow path)
  1339. self.activate_block(int_block)
  1340. if swap_op:
  1341. args = [rhs, lhs]
  1342. else:
  1343. args = [lhs, rhs]
  1344. call = self.call_c(c_func_desc, args, line)
  1345. if negate_result:
  1346. self.add(Branch(call, false, true, Branch.BOOL))
  1347. else:
  1348. self.flush_keep_alives()
  1349. self.add(Branch(call, true, false, Branch.BOOL))
  1350. # Short integers (fast path)
  1351. self.activate_block(short_int_block)
  1352. eq = self.comparison_op(lhs, rhs, op_type, line)
  1353. self.add(Branch(eq, true, false, Branch.BOOL))
  1354. def compare_strings(self, lhs: Value, rhs: Value, op: str, line: int) -> Value:
  1355. """Compare two strings"""
  1356. compare_result = self.call_c(unicode_compare, [lhs, rhs], line)
  1357. error_constant = Integer(-1, c_int_rprimitive, line)
  1358. compare_error_check = self.add(
  1359. ComparisonOp(compare_result, error_constant, ComparisonOp.EQ, line)
  1360. )
  1361. exception_check, propagate, final_compare = BasicBlock(), BasicBlock(), BasicBlock()
  1362. branch = Branch(compare_error_check, exception_check, final_compare, Branch.BOOL)
  1363. branch.negated = False
  1364. self.add(branch)
  1365. self.activate_block(exception_check)
  1366. check_error_result = self.call_c(err_occurred_op, [], line)
  1367. null = Integer(0, pointer_rprimitive, line)
  1368. compare_error_check = self.add(
  1369. ComparisonOp(check_error_result, null, ComparisonOp.NEQ, line)
  1370. )
  1371. branch = Branch(compare_error_check, propagate, final_compare, Branch.BOOL)
  1372. branch.negated = False
  1373. self.add(branch)
  1374. self.activate_block(propagate)
  1375. self.call_c(keep_propagating_op, [], line)
  1376. self.goto(final_compare)
  1377. self.activate_block(final_compare)
  1378. op_type = ComparisonOp.EQ if op == "==" else ComparisonOp.NEQ
  1379. return self.add(ComparisonOp(compare_result, Integer(0, c_int_rprimitive), op_type, line))
  1380. def compare_bytes(self, lhs: Value, rhs: Value, op: str, line: int) -> Value:
  1381. compare_result = self.call_c(bytes_compare, [lhs, rhs], line)
  1382. op_type = ComparisonOp.EQ if op == "==" else ComparisonOp.NEQ
  1383. return self.add(ComparisonOp(compare_result, Integer(1, c_int_rprimitive), op_type, line))
  1384. def compare_tuples(self, lhs: Value, rhs: Value, op: str, line: int = -1) -> Value:
  1385. """Compare two tuples item by item"""
  1386. # type cast to pass mypy check
  1387. assert isinstance(lhs.type, RTuple) and isinstance(rhs.type, RTuple)
  1388. equal = True if op == "==" else False
  1389. result = Register(bool_rprimitive)
  1390. # empty tuples
  1391. if len(lhs.type.types) == 0 and len(rhs.type.types) == 0:
  1392. self.add(Assign(result, self.true() if equal else self.false(), line))
  1393. return result
  1394. length = len(lhs.type.types)
  1395. false_assign, true_assign, out = BasicBlock(), BasicBlock(), BasicBlock()
  1396. check_blocks = [BasicBlock() for _ in range(length)]
  1397. lhs_items = [self.add(TupleGet(lhs, i, line)) for i in range(length)]
  1398. rhs_items = [self.add(TupleGet(rhs, i, line)) for i in range(length)]
  1399. if equal:
  1400. early_stop, final = false_assign, true_assign
  1401. else:
  1402. early_stop, final = true_assign, false_assign
  1403. for i in range(len(lhs.type.types)):
  1404. if i != 0:
  1405. self.activate_block(check_blocks[i])
  1406. lhs_item = lhs_items[i]
  1407. rhs_item = rhs_items[i]
  1408. compare = self.binary_op(lhs_item, rhs_item, op, line)
  1409. # Cast to bool if necessary since most types uses comparison returning a object type
  1410. # See generic_ops.py for more information
  1411. if not is_bool_rprimitive(compare.type):
  1412. compare = self.call_c(bool_op, [compare], line)
  1413. if i < len(lhs.type.types) - 1:
  1414. branch = Branch(compare, early_stop, check_blocks[i + 1], Branch.BOOL)
  1415. else:
  1416. branch = Branch(compare, early_stop, final, Branch.BOOL)
  1417. # if op is ==, we branch on false, else branch on true
  1418. branch.negated = equal
  1419. self.add(branch)
  1420. self.activate_block(false_assign)
  1421. self.add(Assign(result, self.false(), line))
  1422. self.goto(out)
  1423. self.activate_block(true_assign)
  1424. self.add(Assign(result, self.true(), line))
  1425. self.goto_and_activate(out)
  1426. return result
  1427. def translate_instance_contains(self, inst: Value, item: Value, op: str, line: int) -> Value:
  1428. res = self.gen_method_call(inst, "__contains__", [item], None, line)
  1429. if not is_bool_rprimitive(res.type):
  1430. res = self.call_c(bool_op, [res], line)
  1431. if op == "not in":
  1432. res = self.bool_bitwise_op(res, Integer(1, rtype=bool_rprimitive), "^", line)
  1433. return res
  1434. def bool_bitwise_op(self, lreg: Value, rreg: Value, op: str, line: int) -> Value:
  1435. if op == "&":
  1436. code = IntOp.AND
  1437. elif op == "|":
  1438. code = IntOp.OR
  1439. elif op == "^":
  1440. code = IntOp.XOR
  1441. else:
  1442. assert False, op
  1443. return self.add(IntOp(bool_rprimitive, lreg, rreg, code, line))
  1444. def bool_comparison_op(self, lreg: Value, rreg: Value, op: str, line: int) -> Value:
  1445. op_id = ComparisonOp.signed_ops[op]
  1446. return self.comparison_op(lreg, rreg, op_id, line)
  1447. def unary_not(self, value: Value, line: int) -> Value:
  1448. mask = Integer(1, value.type, line)
  1449. return self.int_op(value.type, value, mask, IntOp.XOR, line)
  1450. def unary_op(self, value: Value, expr_op: str, line: int) -> Value:
  1451. typ = value.type
  1452. if is_bool_rprimitive(typ) or is_bit_rprimitive(typ):
  1453. if expr_op == "not":
  1454. return self.unary_not(value, line)
  1455. if expr_op == "+":
  1456. return value
  1457. if is_fixed_width_rtype(typ):
  1458. if expr_op == "-":
  1459. # Translate to '0 - x'
  1460. return self.int_op(typ, Integer(0, typ), value, IntOp.SUB, line)
  1461. elif expr_op == "~":
  1462. if typ.is_signed:
  1463. # Translate to 'x ^ -1'
  1464. return self.int_op(typ, value, Integer(-1, typ), IntOp.XOR, line)
  1465. else:
  1466. # Translate to 'x ^ 0xff...'
  1467. mask = (1 << (typ.size * 8)) - 1
  1468. return self.int_op(typ, value, Integer(mask, typ), IntOp.XOR, line)
  1469. elif expr_op == "+":
  1470. return value
  1471. if is_float_rprimitive(typ):
  1472. if expr_op == "-":
  1473. return self.add(FloatNeg(value, line))
  1474. elif expr_op == "+":
  1475. return value
  1476. if isinstance(value, Integer):
  1477. # TODO: Overflow? Unsigned?
  1478. num = value.value
  1479. if is_short_int_rprimitive(typ):
  1480. num >>= 1
  1481. return Integer(-num, typ, value.line)
  1482. if is_tagged(typ) and expr_op == "+":
  1483. return value
  1484. if isinstance(value, Float):
  1485. return Float(-value.value, value.line)
  1486. if isinstance(typ, RInstance):
  1487. if expr_op == "-":
  1488. method = "__neg__"
  1489. elif expr_op == "+":
  1490. method = "__pos__"
  1491. elif expr_op == "~":
  1492. method = "__invert__"
  1493. else:
  1494. method = ""
  1495. if method and typ.class_ir.has_method(method):
  1496. return self.gen_method_call(value, method, [], None, line)
  1497. call_c_ops_candidates = unary_ops.get(expr_op, [])
  1498. target = self.matching_call_c(call_c_ops_candidates, [value], line)
  1499. assert target, "Unsupported unary operation: %s" % expr_op
  1500. return target
  1501. def make_dict(self, key_value_pairs: Sequence[DictEntry], line: int) -> Value:
  1502. result: Value | None = None
  1503. keys: list[Value] = []
  1504. values: list[Value] = []
  1505. for key, value in key_value_pairs:
  1506. if key is not None:
  1507. # key:value
  1508. if result is None:
  1509. keys.append(key)
  1510. values.append(value)
  1511. continue
  1512. self.translate_special_method_call(
  1513. result, "__setitem__", [key, value], result_type=None, line=line
  1514. )
  1515. else:
  1516. # **value
  1517. if result is None:
  1518. result = self._create_dict(keys, values, line)
  1519. self.call_c(dict_update_in_display_op, [result, value], line=line)
  1520. if result is None:
  1521. result = self._create_dict(keys, values, line)
  1522. return result
  1523. def new_list_op_with_length(self, length: Value, line: int) -> Value:
  1524. """This function returns an uninitialized list.
  1525. If the length is non-zero, the caller must initialize the list, before
  1526. it can be made visible to user code -- otherwise the list object is broken.
  1527. You might need further initialization with `new_list_set_item_op` op.
  1528. Args:
  1529. length: desired length of the new list. The rtype should be
  1530. c_pyssize_t_rprimitive
  1531. line: line number
  1532. """
  1533. return self.call_c(new_list_op, [length], line)
  1534. def new_list_op(self, values: list[Value], line: int) -> Value:
  1535. length: list[Value] = [Integer(len(values), c_pyssize_t_rprimitive, line)]
  1536. if len(values) >= LIST_BUILDING_EXPANSION_THRESHOLD:
  1537. return self.call_c(list_build_op, length + values, line)
  1538. # If the length of the list is less than the threshold,
  1539. # LIST_BUILDING_EXPANSION_THRESHOLD, we directly expand the
  1540. # for-loop and inline the SetMem operation, which is faster
  1541. # than list_build_op, however generates more code.
  1542. result_list = self.call_c(new_list_op, length, line)
  1543. if not values:
  1544. return result_list
  1545. args = [self.coerce(item, object_rprimitive, line) for item in values]
  1546. ob_item_ptr = self.add(GetElementPtr(result_list, PyListObject, "ob_item", line))
  1547. ob_item_base = self.add(LoadMem(pointer_rprimitive, ob_item_ptr, line))
  1548. for i in range(len(values)):
  1549. if i == 0:
  1550. item_address = ob_item_base
  1551. else:
  1552. offset = Integer(PLATFORM_SIZE * i, c_pyssize_t_rprimitive, line)
  1553. item_address = self.add(
  1554. IntOp(pointer_rprimitive, ob_item_base, offset, IntOp.ADD, line)
  1555. )
  1556. self.add(SetMem(object_rprimitive, item_address, args[i], line))
  1557. self.add(KeepAlive([result_list]))
  1558. return result_list
  1559. def new_set_op(self, values: list[Value], line: int) -> Value:
  1560. return self.call_c(new_set_op, values, line)
  1561. def setup_rarray(
  1562. self, item_type: RType, values: Sequence[Value], *, object_ptr: bool = False
  1563. ) -> Value:
  1564. """Declare and initialize a new RArray, returning its address."""
  1565. array = Register(RArray(item_type, len(values)))
  1566. self.add(AssignMulti(array, list(values)))
  1567. return self.add(
  1568. LoadAddress(object_pointer_rprimitive if object_ptr else c_pointer_rprimitive, array)
  1569. )
  1570. def shortcircuit_helper(
  1571. self,
  1572. op: str,
  1573. expr_type: RType,
  1574. left: Callable[[], Value],
  1575. right: Callable[[], Value],
  1576. line: int,
  1577. ) -> Value:
  1578. # Having actual Phi nodes would be really nice here!
  1579. target = Register(expr_type)
  1580. # left_body takes the value of the left side, right_body the right
  1581. left_body, right_body, next_block = BasicBlock(), BasicBlock(), BasicBlock()
  1582. # true_body is taken if the left is true, false_body if it is false.
  1583. # For 'and' the value is the right side if the left is true, and for 'or'
  1584. # it is the right side if the left is false.
  1585. true_body, false_body = (right_body, left_body) if op == "and" else (left_body, right_body)
  1586. left_value = left()
  1587. self.add_bool_branch(left_value, true_body, false_body)
  1588. self.activate_block(left_body)
  1589. left_coerced = self.coerce(left_value, expr_type, line)
  1590. self.add(Assign(target, left_coerced))
  1591. self.goto(next_block)
  1592. self.activate_block(right_body)
  1593. right_value = right()
  1594. right_coerced = self.coerce(right_value, expr_type, line)
  1595. self.add(Assign(target, right_coerced))
  1596. self.goto(next_block)
  1597. self.activate_block(next_block)
  1598. return target
  1599. def bool_value(self, value: Value) -> Value:
  1600. """Return bool(value).
  1601. The result type can be bit_rprimitive or bool_rprimitive.
  1602. """
  1603. if is_bool_rprimitive(value.type) or is_bit_rprimitive(value.type):
  1604. result = value
  1605. elif is_runtime_subtype(value.type, int_rprimitive):
  1606. zero = Integer(0, short_int_rprimitive)
  1607. result = self.comparison_op(value, zero, ComparisonOp.NEQ, value.line)
  1608. elif is_fixed_width_rtype(value.type):
  1609. zero = Integer(0, value.type)
  1610. result = self.add(ComparisonOp(value, zero, ComparisonOp.NEQ))
  1611. elif is_same_type(value.type, str_rprimitive):
  1612. result = self.call_c(str_check_if_true, [value], value.line)
  1613. elif is_same_type(value.type, list_rprimitive) or is_same_type(
  1614. value.type, dict_rprimitive
  1615. ):
  1616. length = self.builtin_len(value, value.line)
  1617. zero = Integer(0)
  1618. result = self.binary_op(length, zero, "!=", value.line)
  1619. elif (
  1620. isinstance(value.type, RInstance)
  1621. and value.type.class_ir.is_ext_class
  1622. and value.type.class_ir.has_method("__bool__")
  1623. ):
  1624. # Directly call the __bool__ method on classes that have it.
  1625. result = self.gen_method_call(value, "__bool__", [], bool_rprimitive, value.line)
  1626. elif is_float_rprimitive(value.type):
  1627. result = self.compare_floats(value, Float(0.0), FloatComparisonOp.NEQ, value.line)
  1628. else:
  1629. value_type = optional_value_type(value.type)
  1630. if value_type is not None:
  1631. not_none = self.translate_is_op(value, self.none_object(), "is not", value.line)
  1632. always_truthy = False
  1633. if isinstance(value_type, RInstance):
  1634. # check whether X.__bool__ is always just the default (object.__bool__)
  1635. if not value_type.class_ir.has_method(
  1636. "__bool__"
  1637. ) and value_type.class_ir.is_method_final("__bool__"):
  1638. always_truthy = True
  1639. if always_truthy:
  1640. result = not_none
  1641. else:
  1642. # "X | None" where X may be falsey and requires a check
  1643. result = Register(bit_rprimitive)
  1644. true, false, end = BasicBlock(), BasicBlock(), BasicBlock()
  1645. branch = Branch(not_none, true, false, Branch.BOOL)
  1646. self.add(branch)
  1647. self.activate_block(true)
  1648. # unbox_or_cast instead of coerce because we want the
  1649. # type to change even if it is a subtype.
  1650. remaining = self.unbox_or_cast(value, value_type, value.line)
  1651. as_bool = self.bool_value(remaining)
  1652. self.add(Assign(result, as_bool))
  1653. self.goto(end)
  1654. self.activate_block(false)
  1655. self.add(Assign(result, Integer(0, bit_rprimitive)))
  1656. self.goto(end)
  1657. self.activate_block(end)
  1658. else:
  1659. result = self.call_c(bool_op, [value], value.line)
  1660. return result
  1661. def add_bool_branch(self, value: Value, true: BasicBlock, false: BasicBlock) -> None:
  1662. opt_value_type = optional_value_type(value.type)
  1663. if opt_value_type is None:
  1664. bool_value = self.bool_value(value)
  1665. self.add(Branch(bool_value, true, false, Branch.BOOL))
  1666. else:
  1667. # Special-case optional types
  1668. is_none = self.translate_is_op(value, self.none_object(), "is not", value.line)
  1669. branch = Branch(is_none, true, false, Branch.BOOL)
  1670. self.add(branch)
  1671. always_truthy = False
  1672. if isinstance(opt_value_type, RInstance):
  1673. # check whether X.__bool__ is always just the default (object.__bool__)
  1674. if not opt_value_type.class_ir.has_method(
  1675. "__bool__"
  1676. ) and opt_value_type.class_ir.is_method_final("__bool__"):
  1677. always_truthy = True
  1678. if not always_truthy:
  1679. # Optional[X] where X may be falsey and requires a check
  1680. branch.true = BasicBlock()
  1681. self.activate_block(branch.true)
  1682. # unbox_or_cast instead of coerce because we want the
  1683. # type to change even if it is a subtype.
  1684. remaining = self.unbox_or_cast(value, opt_value_type, value.line)
  1685. self.add_bool_branch(remaining, true, false)
  1686. def call_c(
  1687. self,
  1688. desc: CFunctionDescription,
  1689. args: list[Value],
  1690. line: int,
  1691. result_type: RType | None = None,
  1692. ) -> Value:
  1693. """Call function using C/native calling convention (not a Python callable)."""
  1694. # Handle void function via singleton RVoid instance
  1695. coerced = []
  1696. # Coerce fixed number arguments
  1697. for i in range(min(len(args), len(desc.arg_types))):
  1698. formal_type = desc.arg_types[i]
  1699. arg = args[i]
  1700. arg = self.coerce(arg, formal_type, line)
  1701. coerced.append(arg)
  1702. # Reorder args if necessary
  1703. if desc.ordering is not None:
  1704. assert desc.var_arg_type is None
  1705. coerced = [coerced[i] for i in desc.ordering]
  1706. # Coerce any var_arg
  1707. var_arg_idx = -1
  1708. if desc.var_arg_type is not None:
  1709. var_arg_idx = len(desc.arg_types)
  1710. for i in range(len(desc.arg_types), len(args)):
  1711. arg = args[i]
  1712. arg = self.coerce(arg, desc.var_arg_type, line)
  1713. coerced.append(arg)
  1714. # Add extra integer constant if any
  1715. for item in desc.extra_int_constants:
  1716. val, typ = item
  1717. extra_int_constant = Integer(val, typ, line)
  1718. coerced.append(extra_int_constant)
  1719. error_kind = desc.error_kind
  1720. if error_kind == ERR_NEG_INT:
  1721. # Handled with an explicit comparison
  1722. error_kind = ERR_NEVER
  1723. target = self.add(
  1724. CallC(
  1725. desc.c_function_name,
  1726. coerced,
  1727. desc.return_type,
  1728. desc.steals,
  1729. desc.is_borrowed,
  1730. error_kind,
  1731. line,
  1732. var_arg_idx,
  1733. )
  1734. )
  1735. if desc.is_borrowed:
  1736. # If the result is borrowed, force the arguments to be
  1737. # kept alive afterwards, as otherwise the result might be
  1738. # immediately freed, at the risk of a dangling pointer.
  1739. for arg in coerced:
  1740. if not isinstance(arg, (Integer, LoadLiteral)):
  1741. self.keep_alives.append(arg)
  1742. if desc.error_kind == ERR_NEG_INT:
  1743. comp = ComparisonOp(target, Integer(0, desc.return_type, line), ComparisonOp.SGE, line)
  1744. comp.error_kind = ERR_FALSE
  1745. self.add(comp)
  1746. if desc.truncated_type is None:
  1747. result = target
  1748. else:
  1749. truncate = self.add(Truncate(target, desc.truncated_type))
  1750. result = truncate
  1751. if result_type and not is_runtime_subtype(result.type, result_type):
  1752. if is_none_rprimitive(result_type):
  1753. # Special case None return. The actual result may actually be a bool
  1754. # and so we can't just coerce it.
  1755. result = self.none()
  1756. else:
  1757. result = self.coerce(target, result_type, line, can_borrow=desc.is_borrowed)
  1758. return result
  1759. def matching_call_c(
  1760. self,
  1761. candidates: list[CFunctionDescription],
  1762. args: list[Value],
  1763. line: int,
  1764. result_type: RType | None = None,
  1765. can_borrow: bool = False,
  1766. ) -> Value | None:
  1767. matching: CFunctionDescription | None = None
  1768. for desc in candidates:
  1769. if len(desc.arg_types) != len(args):
  1770. continue
  1771. if all(
  1772. is_subtype(actual.type, formal) for actual, formal in zip(args, desc.arg_types)
  1773. ) and (not desc.is_borrowed or can_borrow):
  1774. if matching:
  1775. assert matching.priority != desc.priority, "Ambiguous:\n1) {}\n2) {}".format(
  1776. matching, desc
  1777. )
  1778. if desc.priority > matching.priority:
  1779. matching = desc
  1780. else:
  1781. matching = desc
  1782. if matching:
  1783. target = self.call_c(matching, args, line, result_type)
  1784. return target
  1785. return None
  1786. def int_op(self, type: RType, lhs: Value, rhs: Value, op: int, line: int = -1) -> Value:
  1787. """Generate a native integer binary op.
  1788. Use native/C semantics, which sometimes differ from Python
  1789. semantics.
  1790. Args:
  1791. type: Either int64_rprimitive or int32_rprimitive
  1792. op: IntOp.* constant (e.g. IntOp.ADD)
  1793. """
  1794. return self.add(IntOp(type, lhs, rhs, op, line))
  1795. def float_op(self, lhs: Value, rhs: Value, op: str, line: int) -> Value:
  1796. """Generate a native float binary arithmetic operation.
  1797. This follows Python semantics (e.g. raise exception on division by zero).
  1798. Add a FloatOp directly if you want low-level semantics.
  1799. Args:
  1800. op: Binary operator (e.g. '+' or '*')
  1801. """
  1802. op_id = float_op_to_id[op]
  1803. if op_id in (FloatOp.DIV, FloatOp.MOD):
  1804. if not (isinstance(rhs, Float) and rhs.value != 0.0):
  1805. c = self.compare_floats(rhs, Float(0.0), FloatComparisonOp.EQ, line)
  1806. err, ok = BasicBlock(), BasicBlock()
  1807. self.add(Branch(c, err, ok, Branch.BOOL, rare=True))
  1808. self.activate_block(err)
  1809. if op_id == FloatOp.DIV:
  1810. msg = "float division by zero"
  1811. else:
  1812. msg = "float modulo"
  1813. self.add(RaiseStandardError(RaiseStandardError.ZERO_DIVISION_ERROR, msg, line))
  1814. self.add(Unreachable())
  1815. self.activate_block(ok)
  1816. if op_id == FloatOp.MOD:
  1817. # Adjust the result to match Python semantics (FloatOp follows C semantics).
  1818. return self.float_mod(lhs, rhs, line)
  1819. else:
  1820. return self.add(FloatOp(lhs, rhs, op_id, line))
  1821. def float_mod(self, lhs: Value, rhs: Value, line: int) -> Value:
  1822. """Perform x % y on floats using Python semantics."""
  1823. mod = self.add(FloatOp(lhs, rhs, FloatOp.MOD, line))
  1824. res = Register(float_rprimitive)
  1825. self.add(Assign(res, mod))
  1826. tricky, adjust, copysign, done = BasicBlock(), BasicBlock(), BasicBlock(), BasicBlock()
  1827. is_zero = self.add(FloatComparisonOp(res, Float(0.0), FloatComparisonOp.EQ, line))
  1828. self.add(Branch(is_zero, copysign, tricky, Branch.BOOL))
  1829. self.activate_block(tricky)
  1830. same_signs = self.is_same_float_signs(lhs, rhs, line)
  1831. self.add(Branch(same_signs, done, adjust, Branch.BOOL))
  1832. self.activate_block(adjust)
  1833. adj = self.float_op(res, rhs, "+", line)
  1834. self.add(Assign(res, adj))
  1835. self.add(Goto(done))
  1836. self.activate_block(copysign)
  1837. # If the remainder is zero, CPython ensures the result has the
  1838. # same sign as the denominator.
  1839. adj = self.call_c(copysign_op, [Float(0.0), rhs], line)
  1840. self.add(Assign(res, adj))
  1841. self.add(Goto(done))
  1842. self.activate_block(done)
  1843. return res
  1844. def compare_floats(self, lhs: Value, rhs: Value, op: int, line: int) -> Value:
  1845. return self.add(FloatComparisonOp(lhs, rhs, op, line))
  1846. def fixed_width_int_op(
  1847. self, type: RPrimitive, lhs: Value, rhs: Value, op: int, line: int
  1848. ) -> Value:
  1849. """Generate a binary op using Python fixed-width integer semantics.
  1850. These may differ in overflow/rounding behavior from native/C ops.
  1851. Args:
  1852. type: Either int64_rprimitive or int32_rprimitive
  1853. op: IntOp.* constant (e.g. IntOp.ADD)
  1854. """
  1855. lhs = self.coerce(lhs, type, line)
  1856. rhs = self.coerce(rhs, type, line)
  1857. if op == IntOp.DIV:
  1858. if isinstance(rhs, Integer) and rhs.value not in (-1, 0):
  1859. if not type.is_signed:
  1860. return self.int_op(type, lhs, rhs, IntOp.DIV, line)
  1861. else:
  1862. # Inline simple division by a constant, so that C
  1863. # compilers can optimize more
  1864. return self.inline_fixed_width_divide(type, lhs, rhs, line)
  1865. if is_int64_rprimitive(type):
  1866. prim = int64_divide_op
  1867. elif is_int32_rprimitive(type):
  1868. prim = int32_divide_op
  1869. elif is_int16_rprimitive(type):
  1870. prim = int16_divide_op
  1871. elif is_uint8_rprimitive(type):
  1872. self.check_for_zero_division(rhs, type, line)
  1873. return self.int_op(type, lhs, rhs, op, line)
  1874. else:
  1875. assert False, type
  1876. return self.call_c(prim, [lhs, rhs], line)
  1877. if op == IntOp.MOD:
  1878. if isinstance(rhs, Integer) and rhs.value not in (-1, 0):
  1879. if not type.is_signed:
  1880. return self.int_op(type, lhs, rhs, IntOp.MOD, line)
  1881. else:
  1882. # Inline simple % by a constant, so that C
  1883. # compilers can optimize more
  1884. return self.inline_fixed_width_mod(type, lhs, rhs, line)
  1885. if is_int64_rprimitive(type):
  1886. prim = int64_mod_op
  1887. elif is_int32_rprimitive(type):
  1888. prim = int32_mod_op
  1889. elif is_int16_rprimitive(type):
  1890. prim = int16_mod_op
  1891. elif is_uint8_rprimitive(type):
  1892. self.check_for_zero_division(rhs, type, line)
  1893. return self.int_op(type, lhs, rhs, op, line)
  1894. else:
  1895. assert False, type
  1896. return self.call_c(prim, [lhs, rhs], line)
  1897. return self.int_op(type, lhs, rhs, op, line)
  1898. def check_for_zero_division(self, rhs: Value, type: RType, line: int) -> None:
  1899. err, ok = BasicBlock(), BasicBlock()
  1900. is_zero = self.binary_op(rhs, Integer(0, type), "==", line)
  1901. self.add(Branch(is_zero, err, ok, Branch.BOOL))
  1902. self.activate_block(err)
  1903. self.add(
  1904. RaiseStandardError(
  1905. RaiseStandardError.ZERO_DIVISION_ERROR, "integer division or modulo by zero", line
  1906. )
  1907. )
  1908. self.add(Unreachable())
  1909. self.activate_block(ok)
  1910. def inline_fixed_width_divide(self, type: RType, lhs: Value, rhs: Value, line: int) -> Value:
  1911. # Perform floor division (native division truncates)
  1912. res = Register(type)
  1913. div = self.int_op(type, lhs, rhs, IntOp.DIV, line)
  1914. self.add(Assign(res, div))
  1915. same_signs = self.is_same_native_int_signs(type, lhs, rhs, line)
  1916. tricky, adjust, done = BasicBlock(), BasicBlock(), BasicBlock()
  1917. self.add(Branch(same_signs, done, tricky, Branch.BOOL))
  1918. self.activate_block(tricky)
  1919. mul = self.int_op(type, res, rhs, IntOp.MUL, line)
  1920. mul_eq = self.add(ComparisonOp(mul, lhs, ComparisonOp.EQ, line))
  1921. self.add(Branch(mul_eq, done, adjust, Branch.BOOL))
  1922. self.activate_block(adjust)
  1923. adj = self.int_op(type, res, Integer(1, type), IntOp.SUB, line)
  1924. self.add(Assign(res, adj))
  1925. self.add(Goto(done))
  1926. self.activate_block(done)
  1927. return res
  1928. def inline_fixed_width_mod(self, type: RType, lhs: Value, rhs: Value, line: int) -> Value:
  1929. # Perform floor modulus
  1930. res = Register(type)
  1931. mod = self.int_op(type, lhs, rhs, IntOp.MOD, line)
  1932. self.add(Assign(res, mod))
  1933. same_signs = self.is_same_native_int_signs(type, lhs, rhs, line)
  1934. tricky, adjust, done = BasicBlock(), BasicBlock(), BasicBlock()
  1935. self.add(Branch(same_signs, done, tricky, Branch.BOOL))
  1936. self.activate_block(tricky)
  1937. is_zero = self.add(ComparisonOp(res, Integer(0, type), ComparisonOp.EQ, line))
  1938. self.add(Branch(is_zero, done, adjust, Branch.BOOL))
  1939. self.activate_block(adjust)
  1940. adj = self.int_op(type, res, rhs, IntOp.ADD, line)
  1941. self.add(Assign(res, adj))
  1942. self.add(Goto(done))
  1943. self.activate_block(done)
  1944. return res
  1945. def is_same_native_int_signs(self, type: RType, a: Value, b: Value, line: int) -> Value:
  1946. neg1 = self.add(ComparisonOp(a, Integer(0, type), ComparisonOp.SLT, line))
  1947. neg2 = self.add(ComparisonOp(b, Integer(0, type), ComparisonOp.SLT, line))
  1948. return self.add(ComparisonOp(neg1, neg2, ComparisonOp.EQ, line))
  1949. def is_same_float_signs(self, a: Value, b: Value, line: int) -> Value:
  1950. neg1 = self.add(FloatComparisonOp(a, Float(0.0), FloatComparisonOp.LT, line))
  1951. neg2 = self.add(FloatComparisonOp(b, Float(0.0), FloatComparisonOp.LT, line))
  1952. return self.add(ComparisonOp(neg1, neg2, ComparisonOp.EQ, line))
  1953. def comparison_op(self, lhs: Value, rhs: Value, op: int, line: int) -> Value:
  1954. return self.add(ComparisonOp(lhs, rhs, op, line))
  1955. def builtin_len(self, val: Value, line: int, use_pyssize_t: bool = False) -> Value:
  1956. """Generate len(val).
  1957. Return short_int_rprimitive by default.
  1958. Return c_pyssize_t if use_pyssize_t is true (unshifted).
  1959. """
  1960. typ = val.type
  1961. size_value = None
  1962. if is_list_rprimitive(typ) or is_tuple_rprimitive(typ) or is_bytes_rprimitive(typ):
  1963. elem_address = self.add(GetElementPtr(val, PyVarObject, "ob_size"))
  1964. size_value = self.add(LoadMem(c_pyssize_t_rprimitive, elem_address))
  1965. self.add(KeepAlive([val]))
  1966. elif is_set_rprimitive(typ):
  1967. elem_address = self.add(GetElementPtr(val, PySetObject, "used"))
  1968. size_value = self.add(LoadMem(c_pyssize_t_rprimitive, elem_address))
  1969. self.add(KeepAlive([val]))
  1970. elif is_dict_rprimitive(typ):
  1971. size_value = self.call_c(dict_ssize_t_size_op, [val], line)
  1972. elif is_str_rprimitive(typ):
  1973. size_value = self.call_c(str_ssize_t_size_op, [val], line)
  1974. if size_value is not None:
  1975. if use_pyssize_t:
  1976. return size_value
  1977. offset = Integer(1, c_pyssize_t_rprimitive, line)
  1978. return self.int_op(short_int_rprimitive, size_value, offset, IntOp.LEFT_SHIFT, line)
  1979. if isinstance(typ, RInstance):
  1980. # TODO: Support use_pyssize_t
  1981. assert not use_pyssize_t
  1982. length = self.gen_method_call(val, "__len__", [], int_rprimitive, line)
  1983. length = self.coerce(length, int_rprimitive, line)
  1984. ok, fail = BasicBlock(), BasicBlock()
  1985. self.compare_tagged_condition(length, Integer(0), ">=", ok, fail, line)
  1986. self.activate_block(fail)
  1987. self.add(
  1988. RaiseStandardError(
  1989. RaiseStandardError.VALUE_ERROR, "__len__() should return >= 0", line
  1990. )
  1991. )
  1992. self.add(Unreachable())
  1993. self.activate_block(ok)
  1994. return length
  1995. # generic case
  1996. if use_pyssize_t:
  1997. return self.call_c(generic_ssize_t_len_op, [val], line)
  1998. else:
  1999. return self.call_c(generic_len_op, [val], line)
  2000. def new_tuple(self, items: list[Value], line: int) -> Value:
  2001. size: Value = Integer(len(items), c_pyssize_t_rprimitive)
  2002. return self.call_c(new_tuple_op, [size] + items, line)
  2003. def new_tuple_with_length(self, length: Value, line: int) -> Value:
  2004. """This function returns an uninitialized tuple.
  2005. If the length is non-zero, the caller must initialize the tuple, before
  2006. it can be made visible to user code -- otherwise the tuple object is broken.
  2007. You might need further initialization with `new_tuple_set_item_op` op.
  2008. Args:
  2009. length: desired length of the new tuple. The rtype should be
  2010. c_pyssize_t_rprimitive
  2011. line: line number
  2012. """
  2013. return self.call_c(new_tuple_with_length_op, [length], line)
  2014. def int_to_float(self, n: Value, line: int) -> Value:
  2015. return self.call_c(int_to_float_op, [n], line)
  2016. # Internal helpers
  2017. def decompose_union_helper(
  2018. self,
  2019. obj: Value,
  2020. rtype: RUnion,
  2021. result_type: RType,
  2022. process_item: Callable[[Value], Value],
  2023. line: int,
  2024. ) -> Value:
  2025. """Generate isinstance() + specialized operations for union items.
  2026. Say, for Union[A, B] generate ops resembling this (pseudocode):
  2027. if isinstance(obj, A):
  2028. result = <result of process_item(cast(A, obj)>
  2029. else:
  2030. result = <result of process_item(cast(B, obj)>
  2031. Args:
  2032. obj: value with a union type
  2033. rtype: the union type
  2034. result_type: result of the operation
  2035. process_item: callback to generate op for a single union item (arg is coerced
  2036. to union item type)
  2037. line: line number
  2038. """
  2039. # TODO: Optimize cases where a single operation can handle multiple union items
  2040. # (say a method is implemented in a common base class)
  2041. fast_items = []
  2042. rest_items = []
  2043. for item in rtype.items:
  2044. if isinstance(item, RInstance):
  2045. fast_items.append(item)
  2046. else:
  2047. # For everything but RInstance we fall back to C API
  2048. rest_items.append(item)
  2049. exit_block = BasicBlock()
  2050. result = Register(result_type)
  2051. for i, item in enumerate(fast_items):
  2052. more_types = i < len(fast_items) - 1 or rest_items
  2053. if more_types:
  2054. # We are not at the final item so we need one more branch
  2055. op = self.isinstance_native(obj, item.class_ir, line)
  2056. true_block, false_block = BasicBlock(), BasicBlock()
  2057. self.add_bool_branch(op, true_block, false_block)
  2058. self.activate_block(true_block)
  2059. coerced = self.coerce(obj, item, line)
  2060. temp = process_item(coerced)
  2061. temp2 = self.coerce(temp, result_type, line)
  2062. self.add(Assign(result, temp2))
  2063. self.goto(exit_block)
  2064. if more_types:
  2065. self.activate_block(false_block)
  2066. if rest_items:
  2067. # For everything else we use generic operation. Use force=True to drop the
  2068. # union type.
  2069. coerced = self.coerce(obj, object_rprimitive, line, force=True)
  2070. temp = process_item(coerced)
  2071. temp2 = self.coerce(temp, result_type, line)
  2072. self.add(Assign(result, temp2))
  2073. self.goto(exit_block)
  2074. self.activate_block(exit_block)
  2075. return result
  2076. def translate_special_method_call(
  2077. self,
  2078. base_reg: Value,
  2079. name: str,
  2080. args: list[Value],
  2081. result_type: RType | None,
  2082. line: int,
  2083. can_borrow: bool = False,
  2084. ) -> Value | None:
  2085. """Translate a method call which is handled nongenerically.
  2086. These are special in the sense that we have code generated specifically for them.
  2087. They tend to be method calls which have equivalents in C that are more direct
  2088. than calling with the PyObject api.
  2089. Return None if no translation found; otherwise return the target register.
  2090. """
  2091. call_c_ops_candidates = method_call_ops.get(name, [])
  2092. call_c_op = self.matching_call_c(
  2093. call_c_ops_candidates, [base_reg] + args, line, result_type, can_borrow=can_borrow
  2094. )
  2095. return call_c_op
  2096. def translate_eq_cmp(self, lreg: Value, rreg: Value, expr_op: str, line: int) -> Value | None:
  2097. """Add a equality comparison operation.
  2098. Args:
  2099. expr_op: either '==' or '!='
  2100. """
  2101. ltype = lreg.type
  2102. rtype = rreg.type
  2103. if not (isinstance(ltype, RInstance) and ltype == rtype):
  2104. return None
  2105. class_ir = ltype.class_ir
  2106. # Check whether any subclasses of the operand redefines __eq__
  2107. # or it might be redefined in a Python parent class or by
  2108. # dataclasses
  2109. cmp_varies_at_runtime = (
  2110. not class_ir.is_method_final("__eq__")
  2111. or not class_ir.is_method_final("__ne__")
  2112. or class_ir.inherits_python
  2113. or class_ir.is_augmented
  2114. )
  2115. if cmp_varies_at_runtime:
  2116. # We might need to call left.__eq__(right) or right.__eq__(left)
  2117. # depending on which is the more specific type.
  2118. return None
  2119. if not class_ir.has_method("__eq__"):
  2120. # There's no __eq__ defined, so just use object identity.
  2121. identity_ref_op = "is" if expr_op == "==" else "is not"
  2122. return self.translate_is_op(lreg, rreg, identity_ref_op, line)
  2123. return self.gen_method_call(lreg, op_methods[expr_op], [rreg], ltype, line)
  2124. def translate_is_op(self, lreg: Value, rreg: Value, expr_op: str, line: int) -> Value:
  2125. """Create equality comparison operation between object identities
  2126. Args:
  2127. expr_op: either 'is' or 'is not'
  2128. """
  2129. op = ComparisonOp.EQ if expr_op == "is" else ComparisonOp.NEQ
  2130. lhs = self.coerce(lreg, object_rprimitive, line)
  2131. rhs = self.coerce(rreg, object_rprimitive, line)
  2132. return self.add(ComparisonOp(lhs, rhs, op, line))
  2133. def _create_dict(self, keys: list[Value], values: list[Value], line: int) -> Value:
  2134. """Create a dictionary(possibly empty) using keys and values"""
  2135. # keys and values should have the same number of items
  2136. size = len(keys)
  2137. if size > 0:
  2138. size_value: Value = Integer(size, c_pyssize_t_rprimitive)
  2139. # merge keys and values
  2140. items = [i for t in list(zip(keys, values)) for i in t]
  2141. return self.call_c(dict_build_op, [size_value] + items, line)
  2142. else:
  2143. return self.call_c(dict_new_op, [], line)
  2144. def error(self, msg: str, line: int) -> None:
  2145. self.errors.error(msg, self.module_path, line)
  2146. def num_positional_args(arg_values: list[Value], arg_kinds: list[ArgKind] | None) -> int:
  2147. if arg_kinds is None:
  2148. return len(arg_values)
  2149. num_pos = 0
  2150. for kind in arg_kinds:
  2151. if kind == ARG_POS:
  2152. num_pos += 1
  2153. return num_pos