assembler.scm 115 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075
  1. ;;; Guile bytecode assembler
  2. ;;; Copyright (C) 2001, 2009-2021 Free Software Foundation, Inc.
  3. ;;;
  4. ;;; This library is free software; you can redistribute it and/or
  5. ;;; modify it under the terms of the GNU Lesser General Public
  6. ;;; License as published by the Free Software Foundation; either
  7. ;;; version 3 of the License, or (at your option) any later version.
  8. ;;;
  9. ;;; This library is distributed in the hope that it will be useful,
  10. ;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  12. ;;; Lesser General Public License for more details.
  13. ;;;
  14. ;;; You should have received a copy of the GNU Lesser General Public
  15. ;;; License along with this library; if not, write to the Free Software
  16. ;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  17. ;;; Commentary:
  18. ;;;
  19. ;;; This module implements an assembler that creates an ELF image from
  20. ;;; bytecode assembly and macro-assembly. The input can be given in
  21. ;;; s-expression form, like ((OP ARG ...) ...). Internally there is a
  22. ;;; procedural interface, the emit-OP procedures, but that is not
  23. ;;; currently exported.
  24. ;;;
  25. ;;; "Primitive instructions" correspond to VM operations. Assemblers
  26. ;;; for primitive instructions are generated programmatically from
  27. ;;; (instruction-list), which itself is derived from the VM sources.
  28. ;;; There are also "macro-instructions" like "label" or "load-constant"
  29. ;;; that expand to 0 or more primitive instructions.
  30. ;;;
  31. ;;; The assembler also handles some higher-level tasks, like creating
  32. ;;; the symbol table, other metadata sections, creating a constant table
  33. ;;; for the whole compilation unit, and writing the dynamic section of
  34. ;;; the ELF file along with the appropriate initialization routines.
  35. ;;;
  36. ;;; Most compilers will want to use the trio of make-assembler,
  37. ;;; emit-text, and link-assembly. That will result in the creation of
  38. ;;; an ELF image as a bytevector, which can then be loaded using
  39. ;;; load-thunk-from-memory, or written to disk as a .go file.
  40. ;;;
  41. ;;; Code:
  42. (define-module (system vm assembler)
  43. #:use-module (system base target)
  44. #:use-module (system base types internal)
  45. #:use-module (system vm dwarf)
  46. #:use-module (system vm elf)
  47. #:use-module (system vm linker)
  48. #:use-module (system syntax internal)
  49. #:use-module (language bytecode)
  50. #:use-module (rnrs bytevectors)
  51. #:use-module (ice-9 binary-ports)
  52. #:use-module (ice-9 vlist)
  53. #:use-module (ice-9 match)
  54. #:use-module (srfi srfi-1)
  55. #:use-module (srfi srfi-4)
  56. #:use-module (srfi srfi-9)
  57. #:use-module (srfi srfi-11)
  58. #:export (make-assembler
  59. (emit-receive* . emit-receive)
  60. (emit-mov* . emit-mov)
  61. (emit-fmov* . emit-fmov)
  62. emit-u64=?
  63. emit-u64<?
  64. emit-u64-imm<?
  65. emit-imm-u64<?
  66. emit-s64-imm=?
  67. emit-s64<?
  68. emit-s64-imm<?
  69. emit-imm-s64<?
  70. emit-f64=?
  71. emit-f64<?
  72. emit-=?
  73. emit-<?
  74. emit-arguments<=?
  75. emit-positional-arguments<=?
  76. emit-immediate-tag=?
  77. emit-heap-tag=?
  78. emit-eq?
  79. emit-eq-immediate?
  80. emit-heap-numbers-equal?
  81. emit-j
  82. emit-jl
  83. emit-je
  84. emit-jnl
  85. emit-jne
  86. emit-jge
  87. emit-jnge
  88. emit-jtable
  89. emit-fixnum?
  90. emit-heap-object?
  91. emit-char?
  92. emit-undefined?
  93. emit-null?
  94. emit-false?
  95. emit-nil?
  96. emit-untag-fixnum
  97. emit-tag-fixnum
  98. emit-untag-char
  99. emit-tag-char
  100. emit-s64->f64
  101. emit-throw
  102. (emit-throw/value* . emit-throw/value)
  103. (emit-throw/value+data* . emit-throw/value+data)
  104. emit-pair?
  105. emit-struct?
  106. emit-symbol?
  107. emit-variable?
  108. emit-vector?
  109. emit-mutable-vector?
  110. emit-immutable-vector?
  111. emit-weak-vector?
  112. emit-string?
  113. emit-heap-number?
  114. emit-hash-table?
  115. emit-pointer?
  116. emit-fluid?
  117. emit-stringbuf?
  118. emit-dynamic-state?
  119. emit-frame?
  120. emit-keyword?
  121. emit-syntax?
  122. emit-program?
  123. emit-vm-continuation?
  124. emit-bytevector?
  125. emit-weak-set?
  126. emit-weak-table?
  127. emit-array?
  128. emit-bitvector?
  129. emit-port?
  130. emit-smob?
  131. emit-bignum?
  132. emit-flonum?
  133. emit-compnum?
  134. emit-fracnum?
  135. emit-allocate-words
  136. emit-allocate-words/immediate
  137. emit-allocate-pointerless-words
  138. emit-allocate-pointerless-words/immediate
  139. emit-scm-ref
  140. emit-scm-set!
  141. emit-scm-ref/tag
  142. emit-scm-set!/tag
  143. emit-scm-ref/immediate
  144. emit-scm-set!/immediate
  145. emit-word-ref
  146. emit-word-set!
  147. emit-word-ref/immediate
  148. emit-word-set!/immediate
  149. emit-pointer-ref/immediate
  150. emit-pointer-set!/immediate
  151. emit-tail-pointer-ref/immediate
  152. emit-u8-ref
  153. emit-s8-ref
  154. emit-u16-ref
  155. emit-s16-ref
  156. emit-u32-ref
  157. emit-s32-ref
  158. emit-u64-ref
  159. emit-s64-ref
  160. emit-f32-ref
  161. emit-f64-ref
  162. emit-u8-set!
  163. emit-s8-set!
  164. emit-u16-set!
  165. emit-s16-set!
  166. emit-u32-set!
  167. emit-s32-set!
  168. emit-u64-set!
  169. emit-s64-set!
  170. emit-f32-set!
  171. emit-f64-set!
  172. emit-atomic-scm-ref/immediate
  173. emit-atomic-scm-set!/immediate
  174. emit-atomic-scm-swap!/immediate
  175. emit-atomic-scm-compare-and-swap!/immediate
  176. ;; Intrinsics.
  177. emit-add
  178. emit-add/immediate
  179. emit-sub
  180. emit-sub/immediate
  181. emit-mul
  182. emit-div
  183. emit-quo
  184. emit-rem
  185. emit-mod
  186. emit-inexact
  187. emit-abs
  188. emit-sqrt
  189. emit-floor
  190. emit-ceiling
  191. emit-sin
  192. emit-cos
  193. emit-tan
  194. emit-asin
  195. emit-acos
  196. emit-atan
  197. emit-atan2
  198. emit-fabs
  199. emit-fsqrt
  200. emit-ffloor
  201. emit-fceiling
  202. emit-fsin
  203. emit-fcos
  204. emit-ftan
  205. emit-fasin
  206. emit-facos
  207. emit-fatan
  208. emit-fatan2
  209. emit-logand
  210. emit-logior
  211. emit-logxor
  212. emit-logsub
  213. emit-string-set!
  214. emit-string->number
  215. emit-string->symbol
  216. emit-symbol->keyword
  217. emit-class-of
  218. emit-scm->f64
  219. emit-scm->u64
  220. emit-scm->u64/truncate
  221. emit-scm->s64
  222. emit-u64->scm
  223. emit-s64->scm
  224. emit-wind
  225. emit-unwind
  226. emit-push-fluid
  227. emit-pop-fluid
  228. emit-fluid-ref
  229. emit-fluid-set!
  230. emit-push-dynamic-state
  231. emit-pop-dynamic-state
  232. emit-lsh
  233. emit-rsh
  234. emit-lsh/immediate
  235. emit-rsh/immediate
  236. emit-resolve-module
  237. emit-module-variable
  238. emit-lookup
  239. emit-lookup-bound
  240. emit-define!
  241. emit-current-module
  242. ;; Intrinsics for use by the baseline compiler.
  243. emit-$car
  244. emit-$cdr
  245. emit-$set-car!
  246. emit-$set-cdr!
  247. emit-$variable-ref
  248. emit-$variable-set!
  249. emit-$vector-length
  250. emit-$vector-ref
  251. emit-$vector-set!
  252. emit-$vector-ref/immediate
  253. emit-$vector-set!/immediate
  254. emit-$allocate-struct
  255. emit-$struct-vtable
  256. emit-$struct-ref
  257. emit-$struct-set!
  258. emit-$struct-ref/immediate
  259. emit-$struct-set!/immediate
  260. emit-cache-ref
  261. emit-cache-set!
  262. emit-call
  263. emit-call-label
  264. emit-tail-call
  265. emit-tail-call-label
  266. (emit-instrument-entry* . emit-instrument-entry)
  267. (emit-instrument-loop* . emit-instrument-loop)
  268. emit-receive-values
  269. emit-return-values
  270. emit-shuffle-down
  271. emit-call/cc
  272. emit-abort
  273. emit-builtin-ref
  274. emit-assert-nargs-ee
  275. emit-assert-nargs-ge
  276. emit-assert-nargs-le
  277. emit-reset-frame
  278. emit-assert-nargs-ee/locals
  279. emit-bind-kwargs
  280. emit-bind-rest
  281. emit-load-label
  282. emit-resolve
  283. emit-prompt
  284. emit-current-thread
  285. emit-fadd
  286. emit-fsub
  287. emit-fmul
  288. emit-fdiv
  289. emit-uadd
  290. emit-usub
  291. emit-umul
  292. emit-uadd/immediate
  293. emit-usub/immediate
  294. emit-umul/immediate
  295. emit-ulogand
  296. emit-ulogior
  297. emit-ulogxor
  298. emit-ulogsub
  299. emit-ursh
  300. emit-srsh
  301. emit-ulsh
  302. emit-ursh/immediate
  303. emit-srsh/immediate
  304. emit-ulsh/immediate
  305. emit-make-array
  306. emit-load-f64
  307. emit-load-u64
  308. emit-load-s64
  309. emit-handle-interrupts
  310. emit-text
  311. link-assembly))
  312. ;; Like define-inlinable, but only for first-order uses of the defined
  313. ;; routine. Should residualize less code.
  314. (eval-when (expand)
  315. (define-syntax define-inline
  316. (lambda (x)
  317. (syntax-case x ()
  318. ((_ (name arg ...) body ...)
  319. (with-syntax (((temp ...) (generate-temporaries #'(arg ...))))
  320. #`(eval-when (expand)
  321. (define-syntax-rule (name temp ...)
  322. (let ((arg temp) ...)
  323. body ...)))))))))
  324. ;;; Bytecode consists of 32-bit units, often subdivided in some way.
  325. ;;; These helpers create one 32-bit unit from multiple components.
  326. (define-inline (check-urange x mask)
  327. (unless (and (exact-integer? x) (= x (logand x mask)))
  328. (error "out of range" x))
  329. x)
  330. (define-inline (check-srange x mask)
  331. (let ((x* (logand x mask)))
  332. (unless (if (negative? x)
  333. (= (+ x mask 1) x*)
  334. (= x x*))
  335. (error "out of range" x))
  336. x*))
  337. (define-inline (pack-u8-u24 x y)
  338. (let ((x (check-urange x #xff))
  339. (y (check-urange y #xffffff)))
  340. (logior x (ash y 8))))
  341. (define-inline (pack-u8-s24 x y)
  342. (let ((x (check-urange x #xff))
  343. (y (check-srange y #xffffff)))
  344. (logior x (ash y 8))))
  345. (define-inline (pack-u16-u16 x y)
  346. (let ((x (check-urange x #xffff))
  347. (y (check-urange y #xffff)))
  348. (logior x (ash y 16))))
  349. (define-inline (pack-u1-u7-u24 x y z)
  350. (let ((x (check-urange x #x1))
  351. (y (check-urange y #x7f))
  352. (z (check-urange z #xffffff)))
  353. (logior x (ash y 1) (ash z 8))))
  354. (define-inline (pack-u8-u12-u12 x y z)
  355. (let ((x (check-urange x #xff))
  356. (y (check-urange y #xfff))
  357. (z (check-urange z #xfff)))
  358. (logior x (ash y 8) (ash z 20))))
  359. (define-inline (pack-u8-u12-s12 x y z)
  360. (let ((x (check-urange x #xff))
  361. (y (check-urange y #xfff))
  362. (z (check-srange z #xfff)))
  363. (logior x (ash y 8) (ash z 20))))
  364. (define-inline (pack-u8-u8-u16 x y z)
  365. (let ((x (check-urange x #xff))
  366. (y (check-urange y #xff))
  367. (z (check-urange z #xffff)))
  368. (logior x (ash y 8) (ash z 16))))
  369. (define-inline (pack-u8-u8-u8-u8 x y z w)
  370. (let ((x (check-urange x #xff))
  371. (y (check-urange y #xff))
  372. (z (check-urange z #xff))
  373. (w (check-urange w #xff)))
  374. (logior x (ash y 8) (ash z 16) (ash w 24))))
  375. (eval-when (expand)
  376. (define-syntax pack-flags
  377. (syntax-rules ()
  378. ;; Add clauses as needed.
  379. ((pack-flags f1 f2) (logior (if f1 (ash 1 0) 0)
  380. (if f2 (ash 1 1) 0))))))
  381. (define-syntax-rule (define-byte-order-swapper name size ref set)
  382. (define* (name buf #:optional (start 0) (end (bytevector-length buf)))
  383. "Patch up the text buffer @var{buf}, swapping the endianness of each
  384. N-byte unit."
  385. (unless (zero? (modulo (- end start) size))
  386. (error "unexpected length"))
  387. (let lp ((pos start))
  388. (when (< pos end)
  389. (set buf pos (ref buf pos (endianness big)) (endianness little))
  390. (lp (+ pos size))))))
  391. (define-byte-order-swapper byte-swap/2!
  392. 2 bytevector-u16-ref bytevector-u16-set!)
  393. (define-byte-order-swapper byte-swap/4!
  394. 4 bytevector-u32-ref bytevector-u32-set!)
  395. (define-byte-order-swapper byte-swap/8!
  396. 8 bytevector-u64-ref bytevector-u64-set!)
  397. ;;; A <meta> entry collects metadata for one procedure. Procedures are
  398. ;;; written as contiguous ranges of bytecode.
  399. ;;;
  400. (eval-when (expand)
  401. (define-syntax-rule (assert-match arg pattern kind)
  402. (let ((x arg))
  403. (unless (match x (pattern #t) (_ #f))
  404. (error (string-append "expected " kind) x)))))
  405. (define-record-type <jit-data>
  406. (make-jit-data low-pc high-pc)
  407. jit-data?
  408. (low-pc jit-data-low-pc)
  409. (high-pc jit-data-high-pc))
  410. (define-record-type <meta>
  411. (%make-meta label properties low-pc high-pc arities jit-data-label)
  412. meta?
  413. (label meta-label)
  414. (properties meta-properties set-meta-properties!)
  415. (low-pc meta-low-pc)
  416. (high-pc meta-high-pc set-meta-high-pc!)
  417. (arities meta-arities set-meta-arities!)
  418. (jit-data-label meta-jit-data-label))
  419. (define (make-meta label properties low-pc)
  420. (assert-match label (or (? exact-integer?) (? symbol?)) "symbol")
  421. (assert-match properties (((? symbol?) . _) ...) "alist with symbolic keys")
  422. (%make-meta label properties low-pc #f '() (gensym "jit-data")))
  423. (define (meta-name meta)
  424. (assq-ref (meta-properties meta) 'name))
  425. ;; Metadata for one <lambda-case>.
  426. (define-record-type <arity>
  427. (make-arity req opt rest kw-indices allow-other-keys? has-closure?
  428. low-pc high-pc definitions)
  429. arity?
  430. (req arity-req)
  431. (opt arity-opt)
  432. (rest arity-rest)
  433. (kw-indices arity-kw-indices)
  434. (allow-other-keys? arity-allow-other-keys?)
  435. (has-closure? arity-has-closure?)
  436. (low-pc arity-low-pc)
  437. (high-pc arity-high-pc set-arity-high-pc!)
  438. (definitions arity-definitions set-arity-definitions!))
  439. ;;; An assembler collects all of the words emitted during assembly, and
  440. ;;; also maintains ancillary information such as the constant table, a
  441. ;;; relocation list, and so on.
  442. ;;;
  443. ;;; Bytecode consists of 32-bit units. We emit bytecode using native
  444. ;;; endianness. If we're targeting a foreign endianness, we byte-swap
  445. ;;; the bytevector as a whole instead of conditionalizing each access.
  446. ;;;
  447. (define-record-type <asm>
  448. (make-asm buf pos start
  449. labels relocs
  450. word-size endianness
  451. constants inits
  452. shstrtab next-section-number
  453. meta sources
  454. slot-maps)
  455. asm?
  456. ;; We write bytecode into a bytevector, growing the bytevector as
  457. ;; needed. asm-cur is that bytevector, and asm-pos is the byte offset
  458. ;; into the vector at which the next word should be written.
  459. ;;
  460. (buf asm-buf set-asm-buf!)
  461. (pos asm-pos set-asm-pos!)
  462. ;; asm-start is an absolute position, indicating the byte offset of
  463. ;; the beginning of an instruction. It is updated after writing all
  464. ;; the words for one primitive instruction. It models the position of
  465. ;; the instruction pointer during execution, given that the VM updates
  466. ;; the IP only at the end of executing the instruction, and is thus
  467. ;; useful for computing offsets between two points in a program.
  468. ;;
  469. (start asm-start set-asm-start!)
  470. ;; An alist of symbol -> position pairs, indicating the labels defined
  471. ;; in this compilation unit.
  472. ;;
  473. (labels asm-labels set-asm-labels!)
  474. ;; A list of relocations needed by the program text. We use an
  475. ;; internal representation for relocations, and handle textual
  476. ;; relative relocations in the assembler. Other kinds of relocations
  477. ;; are later reified as linker relocations and resolved by the linker.
  478. ;;
  479. (relocs asm-relocs set-asm-relocs!)
  480. ;; Target information.
  481. ;;
  482. (word-size asm-word-size)
  483. (endianness asm-endianness)
  484. ;; The constant table, as a vhash of object -> label. All constants
  485. ;; get de-duplicated and written into separate sections -- either the
  486. ;; .rodata section, for read-only data, or .data, for constants that
  487. ;; need initialization at load-time (like symbols). Constants can
  488. ;; depend on other constants (e.g. a symbol depending on a stringbuf),
  489. ;; so order in this table is important.
  490. ;;
  491. (constants asm-constants set-asm-constants!)
  492. ;; A vhash of label to init descriptors, where an init descriptor is
  493. ;; #(EMIT-INIT STATIC? PATCHES). EMIT-INIT, if present, is a
  494. ;; procedure taking the asm and the label as arguments. Unless the
  495. ;; object is statically allocatable, in which case it can be loaded
  496. ;; via make-non-immediate rather than static-ref, EMIT-INIT should
  497. ;; also initialize the corresponding cell for any later static-ref.
  498. ;; If STATIC? is true, the value can be loaded with
  499. ;; emit-make-non-immediate, otherwise it's emit-static-ref. A bit
  500. ;; confusing but that's how it is. PATCHES is a list of (DEST-LABEL
  501. ;; . FIELD) pairs, indicating locations to which to patch the value.
  502. ;; Like asm-constants, order is important.
  503. ;;
  504. (inits asm-inits set-asm-inits!)
  505. ;; The shstrtab, for section names.
  506. ;;
  507. (shstrtab asm-shstrtab set-asm-shstrtab!)
  508. ;; The section number for the next section to be written.
  509. ;;
  510. (next-section-number asm-next-section-number set-asm-next-section-number!)
  511. ;; A list of <meta>, corresponding to procedure metadata.
  512. ;;
  513. (meta asm-meta set-asm-meta!)
  514. ;; A list of (pos . source) pairs, indicating source information. POS
  515. ;; is relative to the beginning of the text section, and SOURCE is in
  516. ;; the same format that source-properties returns.
  517. ;;
  518. (sources asm-sources set-asm-sources!)
  519. ;; A list of (pos . slot-map) pairs, indicating slot maps. POS is
  520. ;; relative to the beginning of the text section. SLOT-MAP is a
  521. ;; bitfield describing the stack at call sites, as an integer.
  522. ;;
  523. (slot-maps asm-slot-maps set-asm-slot-maps!))
  524. (define* (make-assembler #:key (word-size (target-word-size))
  525. (endianness (target-endianness)))
  526. "Create an assembler for a given target @var{word-size} and
  527. @var{endianness}, falling back to appropriate values for the configured
  528. target."
  529. (make-asm (make-u32vector 1000) 0 0
  530. (make-hash-table) '()
  531. word-size endianness
  532. vlist-null vlist-null
  533. (make-string-table) 1
  534. '() '() '()))
  535. (define (intern-section-name! asm string)
  536. "Add a string to the section name table (shstrtab)."
  537. (string-table-intern! (asm-shstrtab asm) string))
  538. (define (grow-buffer! asm)
  539. "Grow the code buffer of the asm."
  540. (let* ((buf (asm-buf asm))
  541. (len (bytevector-length buf))
  542. (new (make-u32vector (ash len -1) 0)))
  543. (bytevector-copy! buf 0 new 0 len)
  544. (set-asm-buf! asm new)
  545. #f))
  546. (define-inline (emit asm u32)
  547. "Emit one 32-bit word into the instruction stream. Assumes that there
  548. is space for the word."
  549. (bytevector-u32-native-set! (asm-buf asm) (asm-pos asm) u32)
  550. (set-asm-pos! asm (+ (asm-pos asm) 4)))
  551. (define-inline (make-reloc type label base word)
  552. "Make an internal relocation of type @var{type} referencing symbol
  553. @var{label}, @var{word} words after position @var{start}. @var{type}
  554. may be x8-s24, indicating a 24-bit relative label reference that can be
  555. fixed up by the assembler, or s32, indicating a 32-bit relative
  556. reference that needs to be fixed up by the linker."
  557. (list type label base word))
  558. (define-inline (reset-asm-start! asm)
  559. "Reset the asm-start after writing the words for one instruction."
  560. (set-asm-start! asm (asm-pos asm)))
  561. (define (record-label-reference asm label)
  562. "Record an x8-s24 local label reference. This value will get patched
  563. up later by the assembler."
  564. (let* ((start (asm-start asm))
  565. (pos (asm-pos asm))
  566. (reloc (make-reloc 'x8-s24 label start (- pos start))))
  567. (set-asm-relocs! asm (cons reloc (asm-relocs asm)))))
  568. (define* (record-far-label-reference asm label #:optional (offset 0))
  569. "Record an s32 far label reference. This value will get patched up
  570. later by the linker."
  571. (let* ((start (- (asm-start asm) offset))
  572. (pos (asm-pos asm))
  573. (reloc (make-reloc 's32 label start (- pos start))))
  574. (set-asm-relocs! asm (cons reloc (asm-relocs asm)))))
  575. (define (immediate-bits asm x)
  576. (let ((bits (scm->immediate-bits x)))
  577. (and bits (truncate-bits bits (* 8 (asm-word-size asm)) #t))))
  578. ;;;
  579. ;;; Primitive assemblers are defined by expanding `assembler' for each
  580. ;;; opcode in `(instruction-list)'.
  581. ;;;
  582. (eval-when (expand)
  583. (define (id-append ctx a b)
  584. (datum->syntax ctx (symbol-append (syntax->datum a) (syntax->datum b))))
  585. (define-syntax encoder
  586. (lambda (x)
  587. (define-syntax op-case
  588. (lambda (x)
  589. (syntax-case x ()
  590. ((_ asm name ((type arg ...) code ...) clause ...)
  591. #`(if (eq? name 'type)
  592. (with-syntax (((arg ...) (generate-temporaries #'(arg ...))))
  593. #'((arg ...)
  594. code ...))
  595. (op-case asm name clause ...)))
  596. ((_ asm name)
  597. #'(error "unmatched name" name)))))
  598. (define (pack-first-word asm opcode type)
  599. (with-syntax ((opcode opcode))
  600. (op-case
  601. asm type
  602. ((X32)
  603. (emit asm opcode))
  604. ((X8_S24 arg)
  605. (emit asm (pack-u8-u24 opcode arg)))
  606. ((X8_F24 arg)
  607. (emit asm (pack-u8-u24 opcode arg)))
  608. ((X8_C24 arg)
  609. (emit asm (pack-u8-u24 opcode arg)))
  610. ((X8_L24 label)
  611. (record-label-reference asm label)
  612. (emit asm opcode))
  613. ((X8_S8_I16 a imm)
  614. (let ((bits (truncate-bits (scm->immediate-bits imm) 16 #f)))
  615. (emit asm (pack-u8-u8-u16 opcode a bits))))
  616. ((X8_S8_ZI16 a imm)
  617. (let ((bits (truncate-bits (scm->immediate-bits imm) 16 #t)))
  618. (emit asm (pack-u8-u8-u16 opcode a bits))))
  619. ((X8_S12_S12 a b)
  620. (emit asm (pack-u8-u12-u12 opcode a b)))
  621. ((X8_S12_C12 a b)
  622. (emit asm (pack-u8-u12-u12 opcode a b)))
  623. ((X8_S12_Z12 a b)
  624. (emit asm (pack-u8-u12-s12 opcode a b)))
  625. ((X8_C12_C12 a b)
  626. (emit asm (pack-u8-u12-u12 opcode a b)))
  627. ((X8_F12_F12 a b)
  628. (emit asm (pack-u8-u12-u12 opcode a b)))
  629. ((X8_S8_S8_S8 a b c)
  630. (emit asm (pack-u8-u8-u8-u8 opcode a b c)))
  631. ((X8_S8_S8_C8 a b c)
  632. (emit asm (pack-u8-u8-u8-u8 opcode a b c)))
  633. ((X8_S8_C8_S8 a b c)
  634. (emit asm (pack-u8-u8-u8-u8 opcode a b c))))))
  635. (define (pack-tail-word asm type)
  636. (op-case
  637. asm type
  638. ((C32 a)
  639. (emit asm a))
  640. ((I32 imm)
  641. (let ((val (immediate-bits asm imm)))
  642. (emit asm val)))
  643. ((A32 imm)
  644. (unless (= (asm-word-size asm) 8)
  645. (error "make-long-immediate unavailable for this target"))
  646. (let ((bits (immediate-bits asm imm)))
  647. (emit asm (ash bits -32))
  648. (emit asm (logand bits (1- (ash 1 32))))))
  649. ((AF32 f64)
  650. (let ((u64 (u64vector-ref (f64vector f64) 0)))
  651. (emit asm (ash u64 -32))
  652. (emit asm (logand u64 (1- (ash 1 32))))))
  653. ((AU32 u64)
  654. (emit asm (ash u64 -32))
  655. (emit asm (logand u64 (1- (ash 1 32)))))
  656. ((AS32 s64)
  657. (let ((u64 (u64vector-ref (s64vector s64) 0)))
  658. (emit asm (ash u64 -32))
  659. (emit asm (logand u64 (1- (ash 1 32))))))
  660. ((B32))
  661. ((BU32))
  662. ((BS32))
  663. ((BF32))
  664. ((N32 label)
  665. (record-far-label-reference asm label)
  666. (emit asm 0))
  667. ((R32 label)
  668. (record-far-label-reference asm label)
  669. (emit asm 0))
  670. ((L32 label)
  671. (record-far-label-reference asm label)
  672. (emit asm 0))
  673. ((LO32 label offset)
  674. (record-far-label-reference asm label
  675. (* offset (asm-word-size asm)))
  676. (emit asm 0))
  677. ((C8_C24 a b)
  678. (emit asm (pack-u8-u24 a b)))
  679. ((C8_S24 a b)
  680. (emit asm (pack-u8-u24 a b)))
  681. ((C16_C16 a b)
  682. (emit asm (pack-u16-u16 a b)))
  683. ((V32_X8_L24 labels)
  684. (let ((len (vector-length labels)))
  685. (emit asm len)
  686. (let lp ()
  687. (unless (<= (+ (asm-pos asm) (* 4 len))
  688. (bytevector-length (asm-buf asm)))
  689. (grow-buffer! asm)
  690. (lp)))
  691. (let lp ((n 0))
  692. (when (< n len)
  693. (record-label-reference asm (vector-ref labels n))
  694. (emit asm 0)
  695. (lp (1+ n))))))
  696. ((B1_X7_L24 a label)
  697. (record-label-reference asm label)
  698. (emit asm (pack-u1-u7-u24 (if a 1 0) 0 0)))
  699. ((B1_C7_L24 a b label)
  700. (record-label-reference asm label)
  701. (emit asm (pack-u1-u7-u24 (if a 1 0) b 0)))
  702. ((B1_X31 a)
  703. (emit asm (pack-u1-u7-u24 (if a 1 0) 0 0)))
  704. ((B1_X7_S24 a b)
  705. (emit asm (pack-u1-u7-u24 (if a 1 0) 0 b)))
  706. ((B1_X7_F24 a b)
  707. (emit asm (pack-u1-u7-u24 (if a 1 0) 0 b)))
  708. ((B1_X7_C24 a b)
  709. (emit asm (pack-u1-u7-u24 (if a 1 0) 0 b)))
  710. ((X8_S24 a)
  711. (emit asm (pack-u8-u24 0 a)))
  712. ((X8_F24 a)
  713. (emit asm (pack-u8-u24 0 a)))
  714. ((X8_C24 a)
  715. (emit asm (pack-u8-u24 0 a)))
  716. ((X8_L24 label)
  717. (record-label-reference asm label)
  718. (emit asm 0))))
  719. (syntax-case x ()
  720. ((_ word0 word* ...)
  721. (with-syntax ((((formal0 ...)
  722. code0 ...)
  723. (pack-first-word #'asm #'opcode
  724. (syntax->datum #'word0)))
  725. ((((formal* ...)
  726. code* ...) ...)
  727. (map (lambda (word) (pack-tail-word #'asm word))
  728. (syntax->datum #'(word* ...)))))
  729. ;; The opcode is the last argument, so that assemblers don't
  730. ;; have to shuffle their arguments before tail-calling an
  731. ;; encoder.
  732. #'(lambda (asm formal0 ... formal* ... ... opcode)
  733. (let lp ()
  734. (let ((words (length '(word0 word* ...))))
  735. (unless (<= (+ (asm-pos asm) (* 4 words))
  736. (bytevector-length (asm-buf asm)))
  737. (grow-buffer! asm)
  738. (lp))))
  739. code0 ...
  740. code* ... ...
  741. (reset-asm-start! asm)))))))
  742. (define (encoder-name operands)
  743. (let lp ((operands operands) (out #'encode))
  744. (syntax-case operands ()
  745. (() out)
  746. ((operand . operands)
  747. (lp #'operands
  748. (id-append #'operand (id-append out out #'-) #'operand))))))
  749. (define-syntax define-encoder
  750. (lambda (x)
  751. (syntax-case x ()
  752. ((_ operand ...)
  753. (with-syntax ((encode (encoder-name #'(operand ...))))
  754. #'(define encode (encoder operand ...)))))))
  755. (define-syntax visit-instruction-kinds
  756. (lambda (x)
  757. (syntax-case x ()
  758. ((visit-instruction-kinds macro arg ...)
  759. (with-syntax (((operands ...)
  760. (delete-duplicates
  761. (map (match-lambda
  762. ((name opcode kind . operands)
  763. (datum->syntax #'macro operands)))
  764. (instruction-list)))))
  765. #'(begin
  766. (macro arg ... . operands)
  767. ...)))))))
  768. (visit-instruction-kinds define-encoder)
  769. ;; In Guile's VM, locals are usually addressed via the stack pointer
  770. ;; (SP). There can be up to 2^24 slots for local variables in a
  771. ;; frame. Some instructions encode their operands using a restricted
  772. ;; subset of the full 24-bit local address space, in order to make the
  773. ;; bytecode more dense in the usual case that a function needs few
  774. ;; local slots. To allow these instructions to be used when there are
  775. ;; many local slots, we can temporarily push the values on the stack,
  776. ;; operate on them there, and then store back any result as we pop the
  777. ;; SP to its original position.
  778. ;;
  779. ;; We implement this shuffling via wrapper encoders that have the same
  780. ;; arity as the encoder they wrap, e.g. encode-X8_S12_S12/shuffle that
  781. ;; wraps encode-X8_S12_S12. We make the emit-cons public interface
  782. ;; use the shuffling encoder. That way we solve the problem fully and
  783. ;; in just one place.
  784. (define (encode-X8_S12_S12!/shuffle asm a b opcode)
  785. (cond
  786. ((< (logior a b) (ash 1 12))
  787. (encode-X8_S12_S12 asm a b opcode))
  788. (else
  789. (emit-push asm a)
  790. (emit-push asm (1+ b))
  791. (encode-X8_S12_S12 asm 1 0 opcode)
  792. (emit-drop asm 2))))
  793. (define (encode-X8_S12_S12<-/shuffle asm dst a opcode)
  794. (cond
  795. ((< (logior dst a) (ash 1 12))
  796. (encode-X8_S12_S12 asm dst a opcode))
  797. (else
  798. (emit-push asm a)
  799. (encode-X8_S12_S12 asm 0 0 opcode)
  800. (emit-pop asm dst))))
  801. (define (encode-X8_S12_C12!/shuffle asm a const opcode)
  802. (cond
  803. ((< a (ash 1 12))
  804. (encode-X8_S12_C12 asm a const opcode))
  805. (else
  806. (emit-push asm a)
  807. (encode-X8_S12_C12 asm 0 const opcode)
  808. (emit-drop asm 1))))
  809. (define (encode-X8_S12_C12<-/shuffle asm dst const opcode)
  810. (cond
  811. ((< dst (ash 1 12))
  812. (encode-X8_S12_C12 asm dst const opcode))
  813. (else
  814. ;; Push garbage value to make space for dst.
  815. (emit-push asm dst)
  816. (encode-X8_S12_C12 asm 0 const opcode)
  817. (emit-pop asm dst))))
  818. (define (encode-X8_S12_Z12!/shuffle asm a const opcode)
  819. (cond
  820. ((< a (ash 1 12))
  821. (encode-X8_S12_Z12 asm a const opcode))
  822. (else
  823. (emit-push asm a)
  824. (encode-X8_S12_Z12 asm 0 const opcode)
  825. (emit-drop asm 1))))
  826. (define (encode-X8_S8_I16<-/shuffle asm dst imm opcode)
  827. (cond
  828. ((< dst (ash 1 8))
  829. (encode-X8_S8_I16 asm dst imm opcode))
  830. (else
  831. ;; Push garbage value to make space for dst.
  832. (emit-push asm dst)
  833. (encode-X8_S8_I16 asm 0 imm opcode)
  834. (emit-pop asm dst))))
  835. (define (encode-X8_S8_ZI16!/shuffle asm a imm opcode)
  836. (cond
  837. ((< a (ash 1 8))
  838. (encode-X8_S8_ZI16 asm a imm opcode))
  839. (else
  840. (emit-push asm a)
  841. (encode-X8_S8_ZI16 asm 0 imm opcode)
  842. (emit-drop asm 1))))
  843. (define (encode-X8_S8_ZI16<-/shuffle asm dst imm opcode)
  844. (cond
  845. ((< dst (ash 1 8))
  846. (encode-X8_S8_ZI16 asm dst imm opcode))
  847. (else
  848. ;; Push garbage value to make space for dst.
  849. (emit-push asm dst)
  850. (encode-X8_S8_ZI16 asm 0 imm opcode)
  851. (emit-pop asm dst))))
  852. (define (encode-X8_S8_S8_S8!/shuffle asm a b c opcode)
  853. (cond
  854. ((< (logior a b c) (ash 1 8))
  855. (encode-X8_S8_S8_S8 asm a b c opcode))
  856. (else
  857. (emit-push asm a)
  858. (emit-push asm (+ b 1))
  859. (emit-push asm (+ c 2))
  860. (encode-X8_S8_S8_S8 asm 2 1 0 opcode)
  861. (emit-drop asm 3))))
  862. (define (encode-X8_S8_S8_S8<-/shuffle asm dst a b opcode)
  863. (cond
  864. ((< (logior dst a b) (ash 1 8))
  865. (encode-X8_S8_S8_S8 asm dst a b opcode))
  866. (else
  867. (emit-push asm a)
  868. (emit-push asm (1+ b))
  869. (encode-X8_S8_S8_S8 asm 1 1 0 opcode)
  870. (emit-drop asm 1)
  871. (emit-pop asm dst))))
  872. (define (encode-X8_S8_S8_C8<-/shuffle asm dst a const opcode)
  873. (cond
  874. ((< (logior dst a) (ash 1 8))
  875. (encode-X8_S8_S8_C8 asm dst a const opcode))
  876. (else
  877. (emit-push asm a)
  878. (encode-X8_S8_S8_C8 asm 0 0 const opcode)
  879. (emit-pop asm dst))))
  880. (define (encode-X8_S8_C8_S8!/shuffle asm a const b opcode)
  881. (cond
  882. ((< (logior a b) (ash 1 8))
  883. (encode-X8_S8_C8_S8 asm a const b opcode))
  884. (else
  885. (emit-push asm a)
  886. (emit-push asm (1+ b))
  887. (encode-X8_S8_C8_S8 asm 1 const 0 opcode)
  888. (emit-drop asm 2))))
  889. (define (encode-X8_S8_C8_S8<-/shuffle asm dst const a opcode)
  890. (cond
  891. ((< (logior dst a) (ash 1 8))
  892. (encode-X8_S8_C8_S8 asm dst const a opcode))
  893. (else
  894. (emit-push asm a)
  895. (encode-X8_S8_C8_S8 asm 0 const 0 opcode)
  896. (emit-pop asm dst))))
  897. (define (encode-X8_S8_S8_S8-C32!/shuffle asm a b c const opcode)
  898. (cond
  899. ((< (logior a b c) (ash 1 8))
  900. (encode-X8_S8_S8_S8-C32 asm a b c const opcode))
  901. (else
  902. (emit-push asm a)
  903. (emit-push asm (+ b 1))
  904. (emit-push asm (+ c 2))
  905. (encode-X8_S8_S8_S8-C32 asm 2 1 0 const opcode)
  906. (emit-drop asm 3))))
  907. (define (encode-X8_S8_S8_S8-C32<-/shuffle asm dst a b c32 opcode)
  908. (cond
  909. ((< (logior dst a b) (ash 1 8))
  910. (encode-X8_S8_S8_S8-C32 asm dst a b c32 opcode))
  911. (else
  912. (emit-push asm a)
  913. (emit-push asm (1+ b))
  914. (encode-X8_S8_S8_S8-C32 asm 1 1 0 c32 opcode)
  915. (emit-drop asm 1)
  916. (emit-pop asm dst))))
  917. (define (encode-X8_S8_S8_C8-C32<-/shuffle asm dst a const c32 opcode)
  918. (cond
  919. ((< (logior dst a) (ash 1 8))
  920. (encode-X8_S8_S8_C8-C32 asm dst a const c32 opcode))
  921. (else
  922. (emit-push asm a)
  923. (encode-X8_S8_S8_C8-C32 asm 0 0 const c32 opcode)
  924. (emit-pop asm dst))))
  925. (define (encode-X8_S8_S8_S8-C32!/shuffle asm a b c c32 opcode)
  926. (cond
  927. ((< (logior a b c) (ash 1 8))
  928. (encode-X8_S8_S8_S8-C32 asm a b c c32 opcode))
  929. (else
  930. (emit-push asm a)
  931. (emit-push asm (+ b 1))
  932. (emit-push asm (+ c 2))
  933. (encode-X8_S8_S8_S8-C32 asm 2 1 0 c32 opcode)
  934. (emit-drop asm 3))))
  935. (define (encode-X8_S8_C8_S8-C32!/shuffle asm a const b c32 opcode)
  936. (cond
  937. ((< (logior a b) (ash 1 8))
  938. (encode-X8_S8_C8_S8-C32 asm a const b c32 opcode))
  939. (else
  940. (emit-push asm a)
  941. (emit-push asm (+ b 1))
  942. (encode-X8_S8_C8_S8-C32 asm 1 const 0 c32 opcode)
  943. (emit-drop asm 2))))
  944. (define (encode-X8_S12_S12-C32<-/shuffle asm dst src c32 opcode)
  945. (cond
  946. ((< (logior dst src) (ash 1 12))
  947. (encode-X8_S12_S12-C32 asm dst src c32 opcode))
  948. (else
  949. (emit-push asm src)
  950. (encode-X8_S12_S12-C32 asm 0 0 c32 opcode)
  951. (emit-pop asm dst))))
  952. (define (encode-X8_S12_S12-C32!/shuffle asm a b c32 opcode)
  953. (cond
  954. ((< (logior a b) (ash 1 12))
  955. (encode-X8_S12_S12-C32 asm a b c32 opcode))
  956. (else
  957. (emit-push asm a)
  958. (emit-push asm b)
  959. (encode-X8_S12_S12-C32 asm 1 0 c32 opcode)
  960. (emit-drop asm 2))))
  961. (eval-when (expand)
  962. (define (id-append ctx a b)
  963. (datum->syntax ctx (symbol-append (syntax->datum a) (syntax->datum b))))
  964. (define (shuffling-encoder-name kind operands)
  965. (match (cons (syntax->datum kind) (syntax->datum operands))
  966. (('! 'X8_S12_S12) #'encode-X8_S12_S12!/shuffle)
  967. (('<- 'X8_S12_S12) #'encode-X8_S12_S12<-/shuffle)
  968. (('! 'X8_S12_S12 'X8_C24) #'encode-X8_S12_S12-X8_C24!/shuffle)
  969. (('<- 'X8_S12_S12 'X8_C24) #'encode-X8_S12_S12-X8_C24<-/shuffle)
  970. (('! 'X8_S12_C12) #'encode-X8_S12_C12!/shuffle)
  971. (('<- 'X8_S12_C12) #'encode-X8_S12_C12<-/shuffle)
  972. (('! 'X8_S12_Z12) #'encode-X8_S12_Z12!/shuffle)
  973. (('<- 'X8_S8_I16) #'encode-X8_S8_I16<-/shuffle)
  974. (('! 'X8_S8_ZI16) #'encode-X8_S8_ZI16!/shuffle)
  975. (('<- 'X8_S8_ZI16) #'encode-X8_S8_ZI16<-/shuffle)
  976. (('! 'X8_S8_S8_S8) #'encode-X8_S8_S8_S8!/shuffle)
  977. (('<- 'X8_S8_S8_S8) #'encode-X8_S8_S8_S8<-/shuffle)
  978. (('<- 'X8_S8_S8_C8) #'encode-X8_S8_S8_C8<-/shuffle)
  979. (('! 'X8_S8_S8_S8 'C32) #'encode-X8_S8_S8_S8-C32!/shuffle)
  980. (('! 'X8_S8_C8_S8 'C32) #'encode-X8_S8_C8_S8-C32!/shuffle)
  981. (('<- 'X8_S8_S8_S8 'C32) #'encode-X8_S8_S8_S8-C32<-/shuffle)
  982. (('<- 'X8_S8_S8_C8 'C32) #'encode-X8_S8_S8_C8-C32<-/shuffle)
  983. (('<- 'X8_S12_S12 'C32) #'encode-X8_S12_S12-C32<-/shuffle)
  984. (('! 'X8_S12_S12 'C32) #'encode-X8_S12_S12-C32!/shuffle)
  985. (('! 'X8_S8_C8_S8) #'encode-X8_S8_C8_S8!/shuffle)
  986. (('<- 'X8_S8_C8_S8) #'encode-X8_S8_C8_S8<-/shuffle)
  987. (else (encoder-name operands))))
  988. (define-syntax assembler
  989. (lambda (x)
  990. (define (word-args word)
  991. (match word
  992. ('C32 #'(a))
  993. ('I32 #'(imm))
  994. ('A32 #'(imm))
  995. ('AF32 #'(f64))
  996. ('AU32 #'(u64))
  997. ('AS32 #'(s64))
  998. ('B32 #'())
  999. ('BU32 #'())
  1000. ('BS32 #'())
  1001. ('BF32 #'())
  1002. ('N32 #'(label))
  1003. ('R32 #'(label))
  1004. ('L32 #'(label))
  1005. ('LO32 #'(label offset))
  1006. ('C8_C24 #'(a b))
  1007. ('C8_S24 #'(a b))
  1008. ('C16_C16 #'(a b))
  1009. ('V32_X8_L24 #'(labels))
  1010. ('B1_X7_L24 #'(a label))
  1011. ('B1_C7_L24 #'(a b label))
  1012. ('B1_X31 #'(a))
  1013. ('B1_X7_S24 #'(a b))
  1014. ('B1_X7_F24 #'(a b))
  1015. ('B1_X7_C24 #'(a b))
  1016. ('X8_S24 #'(arg))
  1017. ('X8_F24 #'(arg))
  1018. ('X8_C24 #'(arg))
  1019. ('X8_L24 #'(label))
  1020. ('X8_S8_I16 #'(a imm))
  1021. ('X8_S8_ZI16 #'(a imm))
  1022. ('X8_S12_S12 #'(a b))
  1023. ('X8_S12_C12 #'(a b))
  1024. ('X8_S12_Z12 #'(a b))
  1025. ('X8_C12_C12 #'(a b))
  1026. ('X8_F12_F12 #'(a b))
  1027. ('X8_S8_S8_S8 #'(a b c))
  1028. ('X8_S8_S8_C8 #'(a b c))
  1029. ('X8_S8_C8_S8 #'(a b c))
  1030. ('X32 #'())))
  1031. (syntax-case x ()
  1032. ((_ name opcode kind word ...)
  1033. (with-syntax (((formal ...)
  1034. (generate-temporaries
  1035. (append-map word-args (syntax->datum #'(word ...)))))
  1036. (encode (shuffling-encoder-name #'kind #'(word ...))))
  1037. #'(lambda (asm formal ...)
  1038. (encode asm formal ... opcode))))))))
  1039. (define assemblers (make-hash-table))
  1040. (eval-when (expand)
  1041. (define-syntax define-assembler
  1042. (lambda (x)
  1043. (syntax-case x ()
  1044. ((_ name opcode kind arg ...)
  1045. (with-syntax ((emit (id-append #'name #'emit- #'name)))
  1046. #'(define emit
  1047. (let ((emit (assembler name opcode kind arg ...)))
  1048. (hashq-set! assemblers 'name emit)
  1049. emit)))))))
  1050. (define-syntax visit-opcodes
  1051. (lambda (x)
  1052. (syntax-case x ()
  1053. ((visit-opcodes macro arg ...)
  1054. (with-syntax (((inst ...)
  1055. (map (lambda (x) (datum->syntax #'macro x))
  1056. (instruction-list))))
  1057. #'(begin
  1058. (macro arg ... . inst)
  1059. ...)))))))
  1060. (visit-opcodes define-assembler)
  1061. ;; Shuffling is a general mechanism to get around address space
  1062. ;; limitations for SP-relative variable references. FP-relative
  1063. ;; variables need special support. Also, some instructions like `mov'
  1064. ;; have multiple variations with different addressing limits.
  1065. (define (emit-mov* asm dst src)
  1066. (if (and (< dst (ash 1 12)) (< src (ash 1 12)))
  1067. (emit-mov asm dst src)
  1068. (emit-long-mov asm dst src)))
  1069. (define (emit-fmov* asm dst src)
  1070. (emit-long-fmov asm dst src))
  1071. (define (emit-receive* asm dst proc nlocals)
  1072. (if (and (< dst (ash 1 12)) (< proc (ash 1 12)))
  1073. (emit-receive asm dst proc nlocals)
  1074. (begin
  1075. (emit-receive-values asm proc #t 1)
  1076. (emit-fmov* asm dst (1+ proc))
  1077. (emit-reset-frame asm nlocals))))
  1078. (define (emit-throw/value* asm val param)
  1079. (emit-throw/value asm val (intern-non-immediate asm param)))
  1080. (define (emit-throw/value+data* asm val param)
  1081. (emit-throw/value+data asm val (intern-non-immediate asm param)))
  1082. (define (emit-instrument-entry* asm)
  1083. (let ((meta (car (asm-meta asm))))
  1084. (emit-instrument-entry asm (meta-jit-data-label meta))))
  1085. (define (emit-instrument-loop* asm)
  1086. (let ((meta (car (asm-meta asm))))
  1087. (emit-instrument-loop asm (meta-jit-data-label meta))))
  1088. (define (emit-text asm instructions)
  1089. "Assemble @var{instructions} using the assembler @var{asm}.
  1090. @var{instructions} is a sequence of instructions, expressed as a list of
  1091. lists. This procedure can be called many times before calling
  1092. @code{link-assembly}."
  1093. (for-each (lambda (inst)
  1094. (apply (or (hashq-ref assemblers (car inst))
  1095. (error 'bad-instruction inst))
  1096. asm
  1097. (cdr inst)))
  1098. instructions))
  1099. ;;;
  1100. ;;; The constant table records a topologically sorted set of literal
  1101. ;;; constants used by a program. For example, a pair uses its car and
  1102. ;;; cdr, a string uses its stringbuf, etc.
  1103. ;;;
  1104. ;;; Some things we want to add to the constant table are not actually
  1105. ;;; Scheme objects: for example, stringbufs, cache cells for toplevel
  1106. ;;; references, or cache cells for non-closure procedures. For these we
  1107. ;;; define special record types and add instances of those record types
  1108. ;;; to the table.
  1109. ;;;
  1110. (define-record-type <stringbuf>
  1111. (make-stringbuf string)
  1112. stringbuf?
  1113. (string stringbuf-string))
  1114. (define-record-type <static-procedure>
  1115. (make-static-procedure code)
  1116. static-procedure?
  1117. (code static-procedure-code))
  1118. (define-record-type <uniform-vector-backing-store>
  1119. (make-uniform-vector-backing-store bytes element-size)
  1120. uniform-vector-backing-store?
  1121. (bytes uniform-vector-backing-store-bytes)
  1122. (element-size uniform-vector-backing-store-element-size))
  1123. (define-record-type <cache-cell>
  1124. (make-cache-cell key)
  1125. cache-cell?
  1126. (key cache-cell-key))
  1127. (define (simple-vector? obj)
  1128. (and (vector? obj)
  1129. (equal? (array-shape obj) (list (list 0 (1- (vector-length obj)))))))
  1130. (define (simple-uniform-vector? obj)
  1131. (and (array? obj)
  1132. (symbol? (array-type obj))
  1133. (match (array-shape obj)
  1134. (((0 n)) #t)
  1135. (else #f))))
  1136. (define (statically-allocatable? x)
  1137. "Return @code{#t} if a non-immediate constant can be allocated
  1138. statically, and @code{#f} if it would need some kind of runtime
  1139. allocation."
  1140. (or (pair? x) (string? x) (stringbuf? x) (static-procedure? x)
  1141. (array? x) (syntax? x)))
  1142. (define (intern-constant asm obj)
  1143. "Add an object to the constant table, and return a label that can be
  1144. used to reference it. If the object is already present in the constant
  1145. table, its existing label is used directly."
  1146. (define (recur obj)
  1147. (intern-constant asm obj))
  1148. (define (add-desc! label desc)
  1149. (set-asm-inits! asm (vhash-consq label desc (asm-inits asm))))
  1150. (define (init-descriptor obj)
  1151. (let ((label (recur obj)))
  1152. (cond
  1153. ((not label) #f)
  1154. ((vhash-assq label (asm-inits asm)) => cdr)
  1155. (else
  1156. (let ((desc (vector #f #t '())))
  1157. (add-desc! label desc)
  1158. desc)))))
  1159. (define (add-patch! dst field obj)
  1160. (match (init-descriptor obj)
  1161. (#f #f)
  1162. ((and desc #(emit-init emit-load patches))
  1163. (vector-set! desc 2 (acons dst field patches)))))
  1164. (define (add-init! dst init)
  1165. (add-desc! dst (vector init #f '())))
  1166. (define (intern! obj label)
  1167. (define (patch! field obj) (add-patch! label field obj))
  1168. (define (init! emit-init) (add-init! label emit-init))
  1169. (cond
  1170. ((pair? obj)
  1171. (patch! 0 (car obj))
  1172. (patch! 1 (cdr obj)))
  1173. ((simple-vector? obj)
  1174. (let lp ((i 0))
  1175. (when (< i (vector-length obj))
  1176. (patch! (1+ i) (vector-ref obj i))
  1177. (lp (1+ i)))))
  1178. ((syntax? obj)
  1179. (patch! 1 (syntax-expression obj))
  1180. (patch! 2 (syntax-wrap obj))
  1181. (patch! 3 (syntax-module obj))
  1182. (patch! 4 (syntax-sourcev obj)))
  1183. ((stringbuf? obj))
  1184. ((static-procedure? obj)
  1185. ;; Special case, as we can't load the procedure's code using
  1186. ;; make-non-immediate.
  1187. (let* ((code (static-procedure-code obj))
  1188. (init (lambda (asm label)
  1189. (emit-static-patch! asm label 1 code)
  1190. #f)))
  1191. (add-desc! label (vector init #t '()))))
  1192. ((cache-cell? obj))
  1193. ((symbol? obj)
  1194. (unless (symbol-interned? obj)
  1195. (error "uninterned symbol cannot be saved to object file" obj))
  1196. (let ((str-label (recur (symbol->string obj))))
  1197. (init! (lambda (asm label)
  1198. (emit-make-non-immediate asm 1 str-label)
  1199. (emit-string->symbol asm 1 1)
  1200. (emit-static-set! asm 1 label 0)
  1201. 1))))
  1202. ((string? obj)
  1203. (patch! 1 (make-stringbuf obj)))
  1204. ((keyword? obj)
  1205. (let ((sym-label (recur (keyword->symbol obj))))
  1206. (init! (lambda (asm label)
  1207. (emit-static-ref asm 1 sym-label)
  1208. (emit-symbol->keyword asm 1 1)
  1209. (emit-static-set! asm 1 label 0)
  1210. 1))))
  1211. ((number? obj)
  1212. (let ((str-label (recur (number->string obj))))
  1213. (init! (lambda (asm label)
  1214. (emit-make-non-immediate asm 1 str-label)
  1215. (emit-string->number asm 1 1)
  1216. (emit-static-set! asm 1 label 0)
  1217. 1))))
  1218. ((uniform-vector-backing-store? obj))
  1219. ((simple-uniform-vector? obj)
  1220. (let ((width (case (array-type obj)
  1221. ((vu8 u8 s8) 1)
  1222. ((u16 s16) 2)
  1223. ;; Bitvectors are addressed in 32-bit units.
  1224. ;; Although a complex number is 8 or 16 bytes wide,
  1225. ;; it should be byteswapped in 4 or 8 byte units.
  1226. ((u32 s32 f32 c32 b) 4)
  1227. ((u64 s64 f64 c64) 8)
  1228. (else
  1229. (error "unhandled array type" obj)))))
  1230. (patch! 2
  1231. (make-uniform-vector-backing-store
  1232. (uniform-array->bytevector obj)
  1233. width))))
  1234. ((array? obj)
  1235. (patch! 1 (shared-array-root obj)))
  1236. (else
  1237. (error "don't know how to intern" obj))))
  1238. (cond
  1239. ((immediate-bits asm obj) #f)
  1240. ((vhash-assoc obj (asm-constants asm)) => cdr)
  1241. (else
  1242. (let ((label (gensym "constant")))
  1243. ;; Note that calling intern may mutate asm-constants and asm-inits.
  1244. (intern! obj label)
  1245. (set-asm-constants! asm (vhash-cons obj label (asm-constants asm)))
  1246. label))))
  1247. (define (intern-non-immediate asm obj)
  1248. "Intern a non-immediate into the constant table, and return its
  1249. label."
  1250. (when (immediate-bits asm obj)
  1251. (error "expected a non-immediate" obj))
  1252. (intern-constant asm obj))
  1253. (define (intern-cache-cell asm key)
  1254. "Intern a cache cell into the constant table, and return its label.
  1255. If there is already a cache cell with the given scope and key, it is
  1256. returned instead."
  1257. (intern-constant asm (make-cache-cell key)))
  1258. ;;;
  1259. ;;; Macro assemblers bridge the gap between primitive instructions and
  1260. ;;; some higher-level operations.
  1261. ;;;
  1262. (eval-when (expand)
  1263. (define-syntax define-macro-assembler
  1264. (lambda (x)
  1265. (syntax-case x ()
  1266. ((_ (name arg ...) body body* ...)
  1267. (with-syntax ((emit (id-append #'name #'emit- #'name)))
  1268. #'(begin
  1269. (define emit
  1270. (let ((emit (lambda (arg ...) body body* ...)))
  1271. (hashq-set! assemblers 'name emit)
  1272. emit))
  1273. (export emit))))))))
  1274. (define-macro-assembler (load-constant asm dst obj)
  1275. (cond
  1276. ((scm->immediate-bits obj)
  1277. => (lambda (bits)
  1278. (cond
  1279. ((and (< dst 256) (truncate-bits bits 16 #t))
  1280. (emit-make-immediate asm dst obj))
  1281. ((and (< dst 256) (truncate-bits bits 16 #f))
  1282. (emit-make-short-immediate asm dst obj))
  1283. ((truncate-bits bits 32 (eqv? (asm-word-size asm) 4))
  1284. (emit-make-long-immediate asm dst obj))
  1285. ((and (eqv? (asm-word-size asm) 8)
  1286. (truncate-bits bits 64 #t))
  1287. (emit-make-long-long-immediate asm dst obj))
  1288. (else
  1289. (emit-static-ref asm dst (intern-non-immediate asm obj))))))
  1290. ((statically-allocatable? obj)
  1291. (emit-make-non-immediate asm dst (intern-non-immediate asm obj)))
  1292. (else
  1293. (emit-static-ref asm dst (intern-non-immediate asm obj)))))
  1294. (define-macro-assembler (load-static-procedure asm dst label)
  1295. (let ((loc (intern-constant asm (make-static-procedure label))))
  1296. (emit-make-non-immediate asm dst loc)))
  1297. (define-syntax define-immediate-tag=?-macro-assembler
  1298. (syntax-rules ()
  1299. ((_ name #f mask tag) #f)
  1300. ((_ name pred mask tag)
  1301. (define-macro-assembler (pred asm slot)
  1302. (emit-immediate-tag=? asm slot mask tag)))))
  1303. (visit-immediate-tags define-immediate-tag=?-macro-assembler)
  1304. (define-syntax-rule (define-heap-tag=?-macro-assembler name pred mask tag)
  1305. (define-macro-assembler (pred asm slot)
  1306. (emit-heap-tag=? asm slot mask tag)))
  1307. (visit-heap-tags define-heap-tag=?-macro-assembler)
  1308. (define-syntax-rule (define-scm<-scm-scm-intrinsic name)
  1309. (define-macro-assembler (name asm dst a b)
  1310. (emit-call-scm<-scm-scm asm dst a b (intrinsic-name->index 'name))))
  1311. (define-syntax-rule (define-scm<-scm-uimm-intrinsic name)
  1312. (define-macro-assembler (name asm dst a b)
  1313. (emit-call-scm<-scm-uimm asm dst a b (intrinsic-name->index 'name))))
  1314. (define-syntax-rule (define-scm-sz-u32-intrinsic name)
  1315. (define-macro-assembler (name asm a b c)
  1316. (emit-call-scm-sz-u32 asm a b c (intrinsic-name->index 'name))))
  1317. (define-syntax-rule (define-scm<-scm-intrinsic name)
  1318. (define-macro-assembler (name asm dst src)
  1319. (emit-call-scm<-scm asm dst src (intrinsic-name->index 'name))))
  1320. (define-syntax-rule (define-f64<-scm-intrinsic name)
  1321. (define-macro-assembler (name asm dst src)
  1322. (emit-call-f64<-scm asm dst src (intrinsic-name->index 'name))))
  1323. (define-syntax-rule (define-f64<-f64-intrinsic name)
  1324. (define-macro-assembler (name asm dst src)
  1325. (emit-call-f64<-f64 asm dst src (intrinsic-name->index 'name))))
  1326. (define-syntax-rule (define-f64<-f64-f64-intrinsic name)
  1327. (define-macro-assembler (name asm dst a b)
  1328. (emit-call-f64<-f64-f64 asm dst a b (intrinsic-name->index 'name))))
  1329. (define-syntax-rule (define-u64<-scm-intrinsic name)
  1330. (define-macro-assembler (name asm dst src)
  1331. (emit-call-u64<-scm asm dst src (intrinsic-name->index 'name))))
  1332. (define-syntax-rule (define-s64<-scm-intrinsic name)
  1333. (define-macro-assembler (name asm dst src)
  1334. (emit-call-s64<-scm asm dst src (intrinsic-name->index 'name))))
  1335. (define-syntax-rule (define-scm<-u64-intrinsic name)
  1336. (define-macro-assembler (name asm dst src)
  1337. (emit-call-scm<-u64 asm dst src (intrinsic-name->index 'name))))
  1338. (define-syntax-rule (define-scm<-s64-intrinsic name)
  1339. (define-macro-assembler (name asm dst src)
  1340. (emit-call-scm<-s64 asm dst src (intrinsic-name->index 'name))))
  1341. (define-syntax-rule (define-thread-intrinsic name)
  1342. (define-macro-assembler (name asm)
  1343. (emit-call-thread asm (intrinsic-name->index 'name))))
  1344. (define-syntax-rule (define-thread-scm-intrinsic name)
  1345. (define-macro-assembler (name asm a)
  1346. (emit-call-thread-scm asm a (intrinsic-name->index 'name))))
  1347. (define-syntax-rule (define-thread-scm-scm-intrinsic name)
  1348. (define-macro-assembler (name asm a b)
  1349. (emit-call-thread-scm-scm asm a b (intrinsic-name->index 'name))))
  1350. (define-syntax-rule (define-scm<-thread-scm-intrinsic name)
  1351. (define-macro-assembler (name asm dst src)
  1352. (emit-call-scm<-thread-scm asm dst src (intrinsic-name->index 'name))))
  1353. (define-syntax-rule (define-scm<-scm-u64-intrinsic name)
  1354. (define-macro-assembler (name asm dst a b)
  1355. (emit-call-scm<-scm-u64 asm dst a b (intrinsic-name->index 'name))))
  1356. (define-syntax-rule (define-scm<-scm-bool-intrinsic name)
  1357. (define-macro-assembler (name asm dst a b)
  1358. (emit-call-scm<-scm-uimm asm dst a (if b 1 0) (intrinsic-name->index 'name))))
  1359. (define-syntax-rule (define-scm<-thread-intrinsic name)
  1360. (define-macro-assembler (name asm dst)
  1361. (emit-call-scm<-thread asm dst (intrinsic-name->index 'name))))
  1362. (define-syntax-rule (define-scm-scm-intrinsic name)
  1363. (define-macro-assembler (name asm a b)
  1364. (emit-call-scm-scm asm a b (intrinsic-name->index 'name))))
  1365. (define-syntax-rule (define-scm-uimm-scm-intrinsic name)
  1366. (define-macro-assembler (name asm a b c)
  1367. (emit-call-scm-uimm-scm asm a b c (intrinsic-name->index 'name))))
  1368. (define-syntax-rule (define-scm-scm-scm-intrinsic name)
  1369. (define-macro-assembler (name asm a b c)
  1370. (emit-call-scm-scm-scm asm a b c (intrinsic-name->index 'name))))
  1371. (define-scm<-scm-scm-intrinsic add)
  1372. (define-scm<-scm-uimm-intrinsic add/immediate)
  1373. (define-scm<-scm-scm-intrinsic sub)
  1374. (define-scm<-scm-uimm-intrinsic sub/immediate)
  1375. (define-scm<-scm-scm-intrinsic mul)
  1376. (define-scm<-scm-scm-intrinsic div)
  1377. (define-scm<-scm-scm-intrinsic quo)
  1378. (define-scm<-scm-scm-intrinsic rem)
  1379. (define-scm<-scm-scm-intrinsic mod)
  1380. (define-scm<-scm-intrinsic inexact)
  1381. (define-scm<-scm-intrinsic abs)
  1382. (define-scm<-scm-intrinsic sqrt)
  1383. (define-scm<-scm-intrinsic floor)
  1384. (define-scm<-scm-intrinsic ceiling)
  1385. (define-scm<-scm-intrinsic sin)
  1386. (define-scm<-scm-intrinsic cos)
  1387. (define-scm<-scm-intrinsic tan)
  1388. (define-scm<-scm-intrinsic asin)
  1389. (define-scm<-scm-intrinsic acos)
  1390. (define-scm<-scm-intrinsic atan)
  1391. (define-scm<-scm-scm-intrinsic atan2)
  1392. (define-f64<-f64-intrinsic fabs)
  1393. (define-f64<-f64-intrinsic fsqrt)
  1394. (define-f64<-f64-intrinsic ffloor)
  1395. (define-f64<-f64-intrinsic fceiling)
  1396. (define-f64<-f64-intrinsic fsin)
  1397. (define-f64<-f64-intrinsic fcos)
  1398. (define-f64<-f64-intrinsic ftan)
  1399. (define-f64<-f64-intrinsic fasin)
  1400. (define-f64<-f64-intrinsic facos)
  1401. (define-f64<-f64-intrinsic fatan)
  1402. (define-f64<-f64-f64-intrinsic fatan2)
  1403. (define-scm<-scm-scm-intrinsic logand)
  1404. (define-scm<-scm-scm-intrinsic logior)
  1405. (define-scm<-scm-scm-intrinsic logxor)
  1406. (define-scm<-scm-scm-intrinsic logsub)
  1407. (define-scm-sz-u32-intrinsic string-set!)
  1408. (define-scm<-scm-intrinsic string->number)
  1409. (define-scm<-scm-intrinsic string->symbol)
  1410. (define-scm<-scm-intrinsic symbol->keyword)
  1411. (define-scm<-scm-intrinsic class-of)
  1412. (define-f64<-scm-intrinsic scm->f64)
  1413. (define-u64<-scm-intrinsic scm->u64)
  1414. (define-u64<-scm-intrinsic scm->u64/truncate)
  1415. (define-s64<-scm-intrinsic scm->s64)
  1416. (define-scm<-u64-intrinsic u64->scm)
  1417. (define-scm<-s64-intrinsic s64->scm)
  1418. (define-thread-scm-scm-intrinsic wind)
  1419. (define-thread-intrinsic unwind)
  1420. (define-thread-scm-scm-intrinsic push-fluid)
  1421. (define-thread-intrinsic pop-fluid)
  1422. (define-scm<-thread-scm-intrinsic fluid-ref)
  1423. (define-thread-scm-scm-intrinsic fluid-set!)
  1424. (define-thread-scm-intrinsic push-dynamic-state)
  1425. (define-thread-intrinsic pop-dynamic-state)
  1426. (define-scm<-scm-u64-intrinsic lsh)
  1427. (define-scm<-scm-u64-intrinsic rsh)
  1428. (define-scm<-scm-uimm-intrinsic lsh/immediate)
  1429. (define-scm<-scm-uimm-intrinsic rsh/immediate)
  1430. (define-scm<-scm-bool-intrinsic resolve-module)
  1431. (define-scm<-scm-scm-intrinsic module-variable)
  1432. (define-scm<-scm-scm-intrinsic lookup)
  1433. (define-scm<-scm-scm-intrinsic lookup-bound)
  1434. (define-scm<-scm-scm-intrinsic define!)
  1435. (define-scm<-thread-intrinsic current-module)
  1436. (define-scm<-scm-intrinsic $car)
  1437. (define-scm<-scm-intrinsic $cdr)
  1438. (define-scm-scm-intrinsic $set-car!)
  1439. (define-scm-scm-intrinsic $set-cdr!)
  1440. (define-scm<-scm-intrinsic $variable-ref)
  1441. (define-scm-scm-intrinsic $variable-set!)
  1442. (define-scm<-scm-intrinsic $vector-length)
  1443. (define-scm<-scm-scm-intrinsic $vector-ref)
  1444. (define-scm-scm-scm-intrinsic $vector-set!)
  1445. (define-scm<-scm-uimm-intrinsic $vector-ref/immediate)
  1446. (define-scm-uimm-scm-intrinsic $vector-set!/immediate)
  1447. (define-scm<-scm-scm-intrinsic $allocate-struct)
  1448. (define-scm<-scm-intrinsic $struct-vtable)
  1449. (define-scm<-scm-scm-intrinsic $struct-ref)
  1450. (define-scm-scm-scm-intrinsic $struct-set!)
  1451. (define-scm<-scm-uimm-intrinsic $struct-ref/immediate)
  1452. (define-scm-uimm-scm-intrinsic $struct-set!/immediate)
  1453. (define-macro-assembler (begin-program asm label properties)
  1454. (emit-label asm label)
  1455. (let ((meta (make-meta label properties (asm-start asm))))
  1456. (set-asm-meta! asm (cons meta (asm-meta asm))))
  1457. (emit-instrument-entry* asm))
  1458. (define-macro-assembler (end-program asm)
  1459. (let ((meta (car (asm-meta asm))))
  1460. (set-meta-high-pc! meta (asm-start asm))
  1461. (set-meta-arities! meta (reverse (meta-arities meta)))
  1462. (set-asm-constants!
  1463. asm
  1464. (vhash-cons (make-jit-data (meta-low-pc meta) (meta-high-pc meta))
  1465. (meta-jit-data-label meta)
  1466. (asm-constants asm)))))
  1467. (define-macro-assembler (begin-standard-arity asm has-closure? req nlocals
  1468. alternate)
  1469. (emit-begin-opt-arity asm has-closure? req '() #f nlocals alternate))
  1470. (define-macro-assembler (begin-opt-arity asm has-closure? req opt rest nlocals
  1471. alternate)
  1472. (emit-begin-kw-arity asm has-closure? req opt rest '() #f nlocals alternate))
  1473. (define-macro-assembler (begin-kw-arity asm has-closure? req opt rest kw-indices
  1474. allow-other-keys? nlocals alternate)
  1475. (assert-match req ((? symbol?) ...) "list of symbols")
  1476. (assert-match opt ((? symbol?) ...) "list of symbols")
  1477. (assert-match rest (or #f (? symbol?)) "#f or symbol")
  1478. (assert-match kw-indices (((? keyword?) . (? integer?)) ...)
  1479. "alist of keyword -> integer")
  1480. (assert-match allow-other-keys? (? boolean?) "boolean")
  1481. (assert-match nlocals (? integer?) "integer")
  1482. (assert-match alternate (or #f (? exact-integer?) (? symbol?)) "#f or symbol")
  1483. (let* ((meta (car (asm-meta asm)))
  1484. (arity (make-arity req opt rest kw-indices allow-other-keys?
  1485. has-closure?
  1486. ;; Include the initial instrument-entry in
  1487. ;; the first arity.
  1488. (if (null? (meta-arities meta))
  1489. (meta-low-pc meta)
  1490. (asm-start asm))
  1491. #f '()))
  1492. ;; The procedure itself is in slot 0, in the standard calling
  1493. ;; convention. For procedure prologues, nreq includes the
  1494. ;; procedure, so here we add 1.
  1495. (nclosure (if has-closure? 1 0))
  1496. (nreq (+ nclosure (length req)))
  1497. (nopt (length opt))
  1498. (rest? (->bool rest)))
  1499. (set-meta-arities! meta (cons arity (meta-arities meta)))
  1500. (cond
  1501. ((or allow-other-keys? (pair? kw-indices))
  1502. (emit-kw-prelude asm nreq nopt rest? kw-indices allow-other-keys?
  1503. nlocals alternate))
  1504. ((or rest? (pair? opt))
  1505. (emit-opt-prelude asm nreq nopt rest? nlocals alternate))
  1506. (else
  1507. (emit-standard-prelude asm nreq nlocals alternate)))))
  1508. (define-macro-assembler (end-arity asm)
  1509. (let ((arity (car (meta-arities (car (asm-meta asm))))))
  1510. (set-arity-definitions! arity (reverse (arity-definitions arity)))
  1511. (set-arity-high-pc! arity (asm-start asm))))
  1512. (define-macro-assembler (standard-prelude asm nreq nlocals alternate)
  1513. (cond
  1514. (alternate
  1515. (emit-arguments<=? asm nreq)
  1516. (emit-jne asm alternate)
  1517. (emit-alloc-frame asm nlocals))
  1518. ((and (< nreq (ash 1 12)) (< (- nlocals nreq) (ash 1 12)))
  1519. (emit-assert-nargs-ee/locals asm nreq (- nlocals nreq)))
  1520. (else
  1521. (emit-assert-nargs-ee asm nreq)
  1522. (emit-alloc-frame asm nlocals))))
  1523. (define-macro-assembler (opt-prelude asm nreq nopt rest? nlocals alternate)
  1524. (if alternate
  1525. (begin
  1526. (emit-arguments<=? asm nreq)
  1527. (emit-jl asm alternate))
  1528. (emit-assert-nargs-ge asm nreq))
  1529. (cond
  1530. (rest?
  1531. (unless (zero? nopt)
  1532. (emit-bind-optionals asm (+ nreq nopt)))
  1533. (emit-bind-rest asm (+ nreq nopt)))
  1534. (alternate
  1535. (emit-arguments<=? asm (+ nreq nopt))
  1536. ;; The arguments<=? instruction sets NONE to indicate greater-than,
  1537. ;; whereas for <, NONE usually indicates greater-than-or-equal,
  1538. ;; hence the name jge. Perhaps we just need to rename jge to
  1539. ;; br-if-none.
  1540. (emit-jge asm alternate)
  1541. (unless (zero? nopt)
  1542. (emit-bind-optionals asm (+ nreq nopt))))
  1543. (else
  1544. (emit-assert-nargs-le asm (+ nreq nopt))
  1545. (unless (zero? nopt)
  1546. (emit-bind-optionals asm (+ nreq nopt)))))
  1547. (emit-alloc-frame asm nlocals))
  1548. (define-macro-assembler (kw-prelude asm nreq nopt rest? kw-indices
  1549. allow-other-keys? nlocals alternate)
  1550. (if alternate
  1551. (begin
  1552. (emit-arguments<=? asm nreq)
  1553. (emit-jl asm alternate)
  1554. (unless rest?
  1555. (emit-positional-arguments<=? asm nreq (+ nreq nopt))
  1556. (emit-jge asm alternate)))
  1557. (emit-assert-nargs-ge asm nreq))
  1558. (let ((ntotal (fold (lambda (kw ntotal)
  1559. (match kw
  1560. (((? keyword?) . idx)
  1561. (max (1+ idx) ntotal))))
  1562. (+ nreq nopt) kw-indices)))
  1563. ;; FIXME: port 581f410f
  1564. (emit-bind-kwargs asm nreq
  1565. (pack-flags allow-other-keys? rest?)
  1566. (+ nreq nopt)
  1567. ntotal
  1568. (intern-constant asm kw-indices))
  1569. (emit-alloc-frame asm nlocals)))
  1570. (define-macro-assembler (label asm sym)
  1571. (hashq-set! (asm-labels asm) sym (asm-start asm)))
  1572. (define-macro-assembler (source asm source)
  1573. (set-asm-sources! asm (acons (asm-start asm) source (asm-sources asm))))
  1574. (define-macro-assembler (definition asm name slot representation)
  1575. (let* ((arity (car (meta-arities (car (asm-meta asm)))))
  1576. (def (vector name slot representation
  1577. (- (asm-start asm) (arity-low-pc arity)))))
  1578. (set-arity-definitions! arity (cons def (arity-definitions arity)))))
  1579. (define-macro-assembler (cache-ref asm dst key)
  1580. (emit-static-ref asm dst (intern-cache-cell asm key)))
  1581. (define-macro-assembler (cache-set! asm key val)
  1582. (emit-static-set! asm val (intern-cache-cell asm key) 0))
  1583. (define-macro-assembler (slot-map asm proc-slot slot-map)
  1584. (unless (zero? slot-map)
  1585. (set-asm-slot-maps! asm (cons
  1586. (cons* (asm-start asm) proc-slot slot-map)
  1587. (asm-slot-maps asm)))))
  1588. ;;;
  1589. ;;; Helper for linking objects.
  1590. ;;;
  1591. (define (make-object asm name bv relocs labels . kwargs)
  1592. "Make a linker object. This helper handles interning the name in the
  1593. shstrtab, assigning the size, allocating a fresh index, and defining a
  1594. corresponding linker symbol for the start of the section."
  1595. (let ((name-idx (intern-section-name! asm (symbol->string name)))
  1596. (index (asm-next-section-number asm)))
  1597. (set-asm-next-section-number! asm (1+ index))
  1598. (make-linker-object (symbol->string name)
  1599. (apply make-elf-section
  1600. #:index index
  1601. #:name name-idx
  1602. #:size (bytevector-length bv)
  1603. kwargs)
  1604. bv relocs
  1605. (cons (make-linker-symbol name 0) labels))))
  1606. ;;;
  1607. ;;; Linking the constant table. This code is somewhat intertwingled
  1608. ;;; with the intern-constant code above, as that procedure also
  1609. ;;; residualizes instructions to initialize constants at load time.
  1610. ;;;
  1611. (define (write-immediate asm buf pos bits)
  1612. (let ((endianness (asm-endianness asm)))
  1613. (case (asm-word-size asm)
  1614. ((4) (bytevector-u32-set! buf pos bits endianness))
  1615. ((8) (bytevector-u64-set! buf pos bits endianness))
  1616. (else (error "bad word size" asm)))))
  1617. (define (write-placeholder asm buf pos)
  1618. (write-immediate asm buf pos (immediate-bits asm #f)))
  1619. (define (emit-init-constants asm)
  1620. "If there is writable data that needs initialization at runtime, emit
  1621. a procedure to do that and return its label. Otherwise return
  1622. @code{#f}."
  1623. (let* ((inits (asm-inits asm)))
  1624. (and (not (vlist-null? inits))
  1625. (let ((label (gensym "init-constants")))
  1626. (emit-begin-program asm label '())
  1627. (emit-assert-nargs-ee/locals asm 1 1)
  1628. (let lp ((n (1- (vlist-length inits))))
  1629. (match (vlist-ref inits n)
  1630. ((label . #(#f #t ((dst . field))))
  1631. ;; Special case in which emit-static-patch is actually
  1632. ;; an optimization.
  1633. (emit-static-patch! asm dst field label))
  1634. ((label . #(emit-init static? patches))
  1635. (let ((slot-from-init (and emit-init (emit-init asm label))))
  1636. (unless (null? patches)
  1637. (let ((slot (or slot-from-init
  1638. (begin
  1639. (if static?
  1640. (emit-make-non-immediate asm 1 label)
  1641. (emit-static-ref asm 1 label))
  1642. 1))))
  1643. (for-each (match-lambda
  1644. ((dst . offset)
  1645. (emit-static-set! asm slot dst offset)))
  1646. patches))))))
  1647. (unless (zero? n)
  1648. (lp (1- n))))
  1649. (emit-reset-frame asm 1)
  1650. (emit-load-constant asm 0 *unspecified*)
  1651. (emit-return-values asm)
  1652. (emit-end-program asm)
  1653. label))))
  1654. (define (link-data asm data name)
  1655. "Link the static data for a program into the @var{name} section (which
  1656. should be .data or .rodata), and return the resulting linker object.
  1657. @var{data} should be a vhash mapping objects to labels."
  1658. (define (align address alignment)
  1659. (+ address
  1660. (modulo (- alignment (modulo address alignment)) alignment)))
  1661. (define tc7-vector #x0d)
  1662. (define vector-immutable-flag #x80)
  1663. (define tc7-string #x15)
  1664. (define string-read-only-flag #x200)
  1665. (define tc7-stringbuf #x27)
  1666. (define stringbuf-wide-flag #x400)
  1667. (define tc7-syntax #x3d)
  1668. (define syntax-has-source-flag #x100)
  1669. (define tc7-program #x45)
  1670. (define tc7-bytevector #x4d)
  1671. ;; This flag is intended to be left-shifted by 7 bits.
  1672. (define bytevector-immutable-flag #x200)
  1673. (define tc7-array #x5d)
  1674. (define tc7-bitvector #x5f)
  1675. (define bitvector-immutable-flag #x80)
  1676. (let ((word-size (asm-word-size asm))
  1677. (endianness (asm-endianness asm)))
  1678. (define (byte-length x)
  1679. (cond
  1680. ((stringbuf? x)
  1681. (let ((x (stringbuf-string x)))
  1682. (+ (* 2 word-size)
  1683. (case (string-bytes-per-char x)
  1684. ((1) (1+ (string-length x)))
  1685. ((4) (* (1+ (string-length x)) 4))
  1686. (else (error "bad string bytes per char" x))))))
  1687. ((static-procedure? x)
  1688. (* 2 word-size))
  1689. ((string? x)
  1690. (* 4 word-size))
  1691. ((pair? x)
  1692. (* 2 word-size))
  1693. ((simple-vector? x)
  1694. (* (1+ (vector-length x)) word-size))
  1695. ((syntax? x)
  1696. (* 5 word-size))
  1697. ((jit-data? x)
  1698. (case word-size
  1699. ((4) (+ word-size (* 4 3)))
  1700. ((8) (+ word-size (* 4 4))) ;; One additional uint32_t for padding.
  1701. (else (error word-size))))
  1702. ((simple-uniform-vector? x)
  1703. (* 4 word-size))
  1704. ((uniform-vector-backing-store? x)
  1705. (bytevector-length (uniform-vector-backing-store-bytes x)))
  1706. ((array? x)
  1707. (* word-size (+ 3 (* 3 (array-rank x)))))
  1708. (else
  1709. word-size)))
  1710. (define (write-constant-reference buf pos x)
  1711. (let ((bits (immediate-bits asm x)))
  1712. (if bits
  1713. (write-immediate asm buf pos bits)
  1714. ;; The asm-inits will fix up any reference to a
  1715. ;; non-immediate.
  1716. (write-placeholder asm buf pos))))
  1717. (define (write buf pos obj)
  1718. (cond
  1719. ((stringbuf? obj)
  1720. (let* ((x (stringbuf-string obj))
  1721. (len (string-length x))
  1722. (tag (logior tc7-stringbuf
  1723. (if (= (string-bytes-per-char x) 1)
  1724. 0
  1725. stringbuf-wide-flag))))
  1726. (case word-size
  1727. ((4)
  1728. (bytevector-u32-set! buf pos tag endianness)
  1729. (bytevector-u32-set! buf (+ pos 4) len endianness))
  1730. ((8)
  1731. (bytevector-u64-set! buf pos tag endianness)
  1732. (bytevector-u64-set! buf (+ pos 8) len endianness))
  1733. (else
  1734. (error "bad word size" asm)))
  1735. (let ((pos (+ pos (* word-size 2))))
  1736. (case (string-bytes-per-char x)
  1737. ((1)
  1738. (let lp ((i 0))
  1739. (if (< i len)
  1740. (let ((u8 (char->integer (string-ref x i))))
  1741. (bytevector-u8-set! buf (+ pos i) u8)
  1742. (lp (1+ i)))
  1743. (bytevector-u8-set! buf (+ pos i) 0))))
  1744. ((4)
  1745. (let lp ((i 0))
  1746. (if (< i len)
  1747. (let ((u32 (char->integer (string-ref x i))))
  1748. (bytevector-u32-set! buf (+ pos (* i 4)) u32 endianness)
  1749. (lp (1+ i)))
  1750. (bytevector-u32-set! buf (+ pos (* i 4)) 0 endianness))))
  1751. (else (error "bad string bytes per char" x))))))
  1752. ((static-procedure? obj)
  1753. (case word-size
  1754. ((4)
  1755. (bytevector-u32-set! buf pos tc7-program endianness)
  1756. (bytevector-u32-set! buf (+ pos 4) 0 endianness))
  1757. ((8)
  1758. (bytevector-u64-set! buf pos tc7-program endianness)
  1759. (bytevector-u64-set! buf (+ pos 8) 0 endianness))
  1760. (else (error "bad word size"))))
  1761. ((cache-cell? obj)
  1762. (write-placeholder asm buf pos))
  1763. ((jit-data? obj)
  1764. ;; Default initialization of 0.
  1765. (values))
  1766. ((string? obj)
  1767. (let ((tag (logior tc7-string string-read-only-flag)))
  1768. (case word-size
  1769. ((4)
  1770. (bytevector-u32-set! buf pos tag endianness)
  1771. (write-placeholder asm buf (+ pos 4)) ; stringbuf
  1772. (bytevector-u32-set! buf (+ pos 8) 0 endianness)
  1773. (bytevector-u32-set! buf (+ pos 12) (string-length obj) endianness))
  1774. ((8)
  1775. (bytevector-u64-set! buf pos tag endianness)
  1776. (write-placeholder asm buf (+ pos 8)) ; stringbuf
  1777. (bytevector-u64-set! buf (+ pos 16) 0 endianness)
  1778. (bytevector-u64-set! buf (+ pos 24) (string-length obj) endianness))
  1779. (else (error "bad word size")))))
  1780. ((pair? obj)
  1781. (write-constant-reference buf pos (car obj))
  1782. (write-constant-reference buf (+ pos word-size) (cdr obj)))
  1783. ((simple-vector? obj)
  1784. (let* ((len (vector-length obj))
  1785. (tag (logior tc7-vector vector-immutable-flag (ash len 8))))
  1786. (case word-size
  1787. ((4) (bytevector-u32-set! buf pos tag endianness))
  1788. ((8) (bytevector-u64-set! buf pos tag endianness))
  1789. (else (error "bad word size")))
  1790. (let lp ((i 0))
  1791. (when (< i (vector-length obj))
  1792. (let ((pos (+ pos word-size (* i word-size)))
  1793. (elt (vector-ref obj i)))
  1794. (write-constant-reference buf pos elt)
  1795. (lp (1+ i)))))))
  1796. ((symbol? obj)
  1797. (write-placeholder asm buf pos))
  1798. ((keyword? obj)
  1799. (write-placeholder asm buf pos))
  1800. ((syntax? obj)
  1801. (let ((tag (logior tc7-syntax syntax-has-source-flag)))
  1802. (case word-size
  1803. ((4) (bytevector-u32-set! buf pos tag endianness))
  1804. ((8) (bytevector-u64-set! buf pos tag endianness))
  1805. (else (error "bad word size"))))
  1806. (write-constant-reference buf (+ pos (* 1 word-size))
  1807. (syntax-expression obj))
  1808. (write-constant-reference buf (+ pos (* 2 word-size))
  1809. (syntax-wrap obj))
  1810. (write-constant-reference buf (+ pos (* 3 word-size))
  1811. (syntax-module obj))
  1812. (write-constant-reference buf (+ pos (* 4 word-size))
  1813. (syntax-sourcev obj)))
  1814. ((number? obj)
  1815. (write-placeholder asm buf pos))
  1816. ((simple-uniform-vector? obj)
  1817. (let ((tag (if (bitvector? obj)
  1818. (logior tc7-bitvector
  1819. bitvector-immutable-flag)
  1820. (logior tc7-bytevector
  1821. ;; Bytevector immutable flag also shifted
  1822. ;; left.
  1823. (ash (logior bytevector-immutable-flag
  1824. (array-type-code obj))
  1825. 7)))))
  1826. (case word-size
  1827. ((4)
  1828. (bytevector-u32-set! buf pos tag endianness)
  1829. (bytevector-u32-set! buf (+ pos 4)
  1830. (if (bitvector? obj)
  1831. (bitvector-length obj)
  1832. (bytevector-length obj))
  1833. endianness) ; length
  1834. (bytevector-u32-set! buf (+ pos 8) 0 endianness) ; pointer
  1835. (write-placeholder asm buf (+ pos 12))) ; owner
  1836. ((8)
  1837. (bytevector-u64-set! buf pos tag endianness)
  1838. (bytevector-u64-set! buf (+ pos 8)
  1839. (if (bitvector? obj)
  1840. (bitvector-length obj)
  1841. (bytevector-length obj))
  1842. endianness) ; length
  1843. (bytevector-u64-set! buf (+ pos 16) 0 endianness) ; pointer
  1844. (write-placeholder asm buf (+ pos 24))) ; owner
  1845. (else (error "bad word size")))))
  1846. ((uniform-vector-backing-store? obj)
  1847. (let ((bv (uniform-vector-backing-store-bytes obj)))
  1848. (bytevector-copy! bv 0 buf pos (bytevector-length bv))
  1849. (unless (eq? endianness (native-endianness))
  1850. (case (uniform-vector-backing-store-element-size obj)
  1851. ((1) #f) ;; Nothing to do.
  1852. ((2) (byte-swap/2! buf pos (+ pos (bytevector-length bv))))
  1853. ((4) (byte-swap/4! buf pos (+ pos (bytevector-length bv))))
  1854. ((8) (byte-swap/8! buf pos (+ pos (bytevector-length bv))))
  1855. (else (error "FIXME: Implement byte order swap"))))))
  1856. ((array? obj)
  1857. (let-values
  1858. ;; array tag + rank + contp flag: see libguile/arrays.h .
  1859. (((tag) (logior tc7-array (ash (array-rank obj) 17) (ash 1 16)))
  1860. ((bv-set! bvs-set!)
  1861. (case word-size
  1862. ((4) (values bytevector-u32-set! bytevector-s32-set!))
  1863. ((8) (values bytevector-u64-set! bytevector-s64-set!))
  1864. (else (error "bad word size")))))
  1865. (bv-set! buf pos tag endianness)
  1866. (write-placeholder asm buf (+ pos word-size)) ; root vector (fixed later)
  1867. (bv-set! buf (+ pos (* word-size 2)) 0 endianness) ; base
  1868. (let lp ((pos (+ pos (* word-size 3)))
  1869. (bounds (array-shape obj))
  1870. (incs (shared-array-increments obj)))
  1871. (when (pair? bounds)
  1872. (bvs-set! buf pos (first (first bounds)) endianness)
  1873. (bvs-set! buf (+ pos word-size) (second (first bounds)) endianness)
  1874. (bvs-set! buf (+ pos (* word-size 2)) (first incs) endianness)
  1875. (lp (+ pos (* 3 word-size)) (cdr bounds) (cdr incs))))))
  1876. (else
  1877. (error "unrecognized object" obj))))
  1878. (define (add-relocs obj pos relocs)
  1879. (match obj
  1880. (($ <jit-data> low-pc high-pc)
  1881. ;; Patch "start" and "end" fields of "struct jit_data".
  1882. (cons* (make-linker-reloc 'rel32/1 (+ pos word-size 4)
  1883. (+ low-pc word-size 4)
  1884. '.rtl-text)
  1885. (make-linker-reloc 'rel32/1 (+ pos word-size 8)
  1886. (+ high-pc word-size 8)
  1887. '.rtl-text)
  1888. relocs))
  1889. (_ relocs)))
  1890. (cond
  1891. ((vlist-null? data) #f)
  1892. (else
  1893. (let* ((byte-len (vhash-fold (lambda (k v len)
  1894. (+ (byte-length k) (align len 8)))
  1895. 0 data))
  1896. (buf (make-bytevector byte-len 0)))
  1897. (let lp ((i 0) (pos 0) (relocs '()) (symbols '()))
  1898. (if (< i (vlist-length data))
  1899. (match (vlist-ref data i)
  1900. ((obj . obj-label)
  1901. (write buf pos obj)
  1902. (lp (1+ i)
  1903. (align (+ (byte-length obj) pos) 8)
  1904. (add-relocs obj pos relocs)
  1905. (cons (make-linker-symbol obj-label pos) symbols))))
  1906. (make-object asm name buf relocs symbols
  1907. #:flags (match name
  1908. ('.data (logior SHF_ALLOC SHF_WRITE))
  1909. ('.rodata SHF_ALLOC))))))))))
  1910. (define (link-constants asm)
  1911. "Link sections to hold constants needed by the program text emitted
  1912. using @var{asm}.
  1913. Returns three values: an object for the .rodata section, an object for
  1914. the .data section, and a label for an initialization procedure. Any of
  1915. these may be @code{#f}."
  1916. (define (shareable? x)
  1917. (cond
  1918. ((stringbuf? x) #t)
  1919. ((pair? x)
  1920. (and (immediate-bits asm (car x)) (immediate-bits asm (cdr x))))
  1921. ((simple-vector? x)
  1922. (let lp ((i 0))
  1923. (or (= i (vector-length x))
  1924. (and (immediate-bits asm (vector-ref x i))
  1925. (lp (1+ i))))))
  1926. ((uniform-vector-backing-store? x) #t)
  1927. (else #f)))
  1928. (let* ((init-constants (emit-init-constants asm))
  1929. (constants (asm-constants asm))
  1930. (len (vlist-length constants)))
  1931. (let lp ((i 0)
  1932. (ro vlist-null)
  1933. (rw vlist-null))
  1934. (if (= i len)
  1935. (values (link-data asm ro '.rodata)
  1936. (link-data asm rw '.data)
  1937. init-constants)
  1938. (match (vlist-ref constants i)
  1939. ((obj . label)
  1940. (if (shareable? obj)
  1941. (lp (1+ i) (vhash-consq obj label ro) rw)
  1942. (lp (1+ i) ro (vhash-consq obj label rw)))))))))
  1943. ;;;
  1944. ;;; Linking program text.
  1945. ;;;
  1946. (define (process-relocs buf relocs labels)
  1947. "Patch up internal x8-s24 relocations, and any s32 relocations that
  1948. reference symbols in the text section. Return a list of linker
  1949. relocations for references to symbols defined outside the text section."
  1950. (fold
  1951. (lambda (reloc tail)
  1952. (match reloc
  1953. ((type label base offset)
  1954. (let ((abs (hashq-ref labels label))
  1955. (dst (+ base offset)))
  1956. (case type
  1957. ((s32)
  1958. (if abs
  1959. (let ((rel (- abs base)))
  1960. (unless (zero? (logand rel #x3))
  1961. (error "reloc not in 32-bit units!"))
  1962. (bytevector-s32-native-set! buf dst (ash rel -2))
  1963. tail)
  1964. (cons (make-linker-reloc 'rel32/4 dst offset label)
  1965. tail)))
  1966. ((x8-s24)
  1967. (unless abs
  1968. (error "unbound near relocation" reloc))
  1969. (let ((rel (- abs base))
  1970. (u32 (bytevector-u32-native-ref buf dst)))
  1971. (unless (zero? (logand rel #x3))
  1972. (error "reloc not in 32-bit units!"))
  1973. (bytevector-u32-native-set! buf dst
  1974. (pack-u8-s24 (logand u32 #xff)
  1975. (ash rel -2)))
  1976. tail))
  1977. (else (error "bad relocation kind" reloc)))))))
  1978. '()
  1979. relocs))
  1980. (define (process-labels labels)
  1981. "Define linker symbols for the label-offset map in @var{labels}.
  1982. The offsets are expected to be expressed in words."
  1983. (hash-map->list (lambda (label loc)
  1984. (make-linker-symbol label loc))
  1985. labels))
  1986. (define (link-text-object asm)
  1987. "Link the .rtl-text section, swapping the endianness of the bytes if
  1988. needed."
  1989. (let ((buf (make-bytevector (asm-pos asm))))
  1990. (bytevector-copy! (asm-buf asm) 0 buf 0 (bytevector-length buf))
  1991. (unless (eq? (asm-endianness asm) (native-endianness))
  1992. (byte-swap/4! buf))
  1993. (make-object asm '.rtl-text
  1994. buf
  1995. (process-relocs buf (asm-relocs asm)
  1996. (asm-labels asm))
  1997. (process-labels (asm-labels asm)))))
  1998. ;;;
  1999. ;;; Create the frame maps. These maps are used by GC to identify dead
  2000. ;;; slots in pending call frames, to avoid marking them. We only do
  2001. ;;; this when frame makes a non-tail call, as that is the common case.
  2002. ;;; Only the topmost frame will see a GC at any other point, but we mark
  2003. ;;; top frames conservatively as serializing live slot maps at every
  2004. ;;; instruction would take up too much space in the object file.
  2005. ;;;
  2006. ;; The .guile.frame-maps section starts with two packed u32 values: one
  2007. ;; indicating the offset of the first byte of the .rtl-text section, and
  2008. ;; another indicating the relative offset in bytes of the slots data.
  2009. (define frame-maps-prefix-len 8)
  2010. ;; Each header is 8 bytes: 4 for the offset from .rtl_text, and 4 for
  2011. ;; the offset of the slot map from the beginning of the
  2012. ;; .guile.frame-maps section. The length of a frame map depends on the
  2013. ;; frame size at the call site, and is not encoded into this section as
  2014. ;; it is available at run-time.
  2015. (define frame-map-header-len 8)
  2016. (define (link-frame-maps asm)
  2017. (define (map-byte-length proc-slot)
  2018. (ceiling-quotient (* 2 (- proc-slot 2)) 8))
  2019. (define (make-frame-maps maps count map-len)
  2020. (let* ((endianness (asm-endianness asm))
  2021. (header-pos frame-maps-prefix-len)
  2022. (map-pos (+ header-pos (* count frame-map-header-len)))
  2023. (bv (make-bytevector (+ map-pos map-len) 0)))
  2024. (bytevector-u32-set! bv 4 map-pos endianness)
  2025. (let lp ((maps maps) (header-pos header-pos) (map-pos map-pos))
  2026. (match maps
  2027. (()
  2028. (make-object asm '.guile.frame-maps bv
  2029. (list (make-linker-reloc 'abs32/1 0 0 '.rtl-text))
  2030. '() #:type SHT_PROGBITS #:flags SHF_ALLOC))
  2031. (((pos proc-slot . map) . maps)
  2032. (bytevector-u32-set! bv header-pos pos endianness)
  2033. (bytevector-u32-set! bv (+ header-pos 4) map-pos endianness)
  2034. (let write-bytes ((map-pos map-pos)
  2035. (map map)
  2036. (byte-length (map-byte-length proc-slot)))
  2037. (if (zero? byte-length)
  2038. (lp maps (+ header-pos frame-map-header-len) map-pos)
  2039. (begin
  2040. (bytevector-u8-set! bv map-pos (logand map #xff))
  2041. (write-bytes (1+ map-pos) (ash map -8)
  2042. (1- byte-length))))))))))
  2043. (match (asm-slot-maps asm)
  2044. (() #f)
  2045. (in
  2046. (let lp ((in in) (out '()) (count 0) (map-len 0))
  2047. (match in
  2048. (() (make-frame-maps out count map-len))
  2049. (((and head (pos proc-slot . map)) . in)
  2050. (lp in (cons head out)
  2051. (1+ count)
  2052. (+ (map-byte-length proc-slot) map-len))))))))
  2053. ;;;
  2054. ;;; Linking other sections of the ELF file, like the dynamic segment,
  2055. ;;; the symbol table, etc.
  2056. ;;;
  2057. ;; FIXME: Define these somewhere central, shared with C.
  2058. (define *bytecode-major-version* #x0300)
  2059. (define *bytecode-minor-version* 4)
  2060. (define (link-dynamic-section asm text rw rw-init frame-maps)
  2061. "Link the dynamic section for an ELF image with bytecode @var{text},
  2062. given the writable data section @var{rw} needing fixup from the
  2063. procedure with label @var{rw-init}. @var{rw-init} may be false. If
  2064. @var{rw} is true, it will be added to the GC roots at runtime."
  2065. (define-syntax-rule (emit-dynamic-section word-size %set-uword! reloc-type)
  2066. (let* ((endianness (asm-endianness asm))
  2067. (words 6)
  2068. (words (if rw (+ words 4) words))
  2069. (words (if rw-init (+ words 2) words))
  2070. (words (if frame-maps (+ words 2) words))
  2071. (bv (make-bytevector (* word-size words) 0))
  2072. (set-uword!
  2073. (lambda (i uword)
  2074. (%set-uword! bv (* i word-size) uword endianness)))
  2075. (relocs '())
  2076. (set-label!
  2077. (lambda (i label)
  2078. (set! relocs (cons (make-linker-reloc 'reloc-type
  2079. (* i word-size) 0 label)
  2080. relocs))
  2081. (%set-uword! bv (* i word-size) 0 endianness))))
  2082. (set-uword! 0 DT_GUILE_VM_VERSION)
  2083. (set-uword! 1 (logior (ash *bytecode-major-version* 16)
  2084. *bytecode-minor-version*))
  2085. (set-uword! 2 DT_GUILE_ENTRY)
  2086. (set-label! 3 '.rtl-text)
  2087. (when rw
  2088. ;; Add roots to GC.
  2089. (set-uword! 4 DT_GUILE_GC_ROOT)
  2090. (set-label! 5 '.data)
  2091. (set-uword! 6 DT_GUILE_GC_ROOT_SZ)
  2092. (set-uword! 7 (bytevector-length (linker-object-bv rw)))
  2093. (when rw-init
  2094. (set-uword! 8 DT_INIT) ; constants
  2095. (set-label! 9 rw-init)))
  2096. (when frame-maps
  2097. (set-uword! (- words 4) DT_GUILE_FRAME_MAPS)
  2098. (set-label! (- words 3) '.guile.frame-maps))
  2099. (set-uword! (- words 2) DT_NULL)
  2100. (set-uword! (- words 1) 0)
  2101. (make-object asm '.dynamic bv relocs '()
  2102. #:type SHT_DYNAMIC #:flags SHF_ALLOC)))
  2103. (case (asm-word-size asm)
  2104. ((4) (emit-dynamic-section 4 bytevector-u32-set! abs32/1))
  2105. ((8) (emit-dynamic-section 8 bytevector-u64-set! abs64/1))
  2106. (else (error "bad word size" asm))))
  2107. (define (link-shstrtab asm)
  2108. "Link the string table for the section headers."
  2109. (intern-section-name! asm ".shstrtab")
  2110. (make-object asm '.shstrtab
  2111. (link-string-table! (asm-shstrtab asm))
  2112. '() '()
  2113. #:type SHT_STRTAB #:flags 0))
  2114. (define (link-symtab text-section asm)
  2115. (let* ((endianness (asm-endianness asm))
  2116. (word-size (asm-word-size asm))
  2117. (size (elf-symbol-len word-size))
  2118. (meta (reverse (asm-meta asm)))
  2119. (n (length meta))
  2120. (strtab (make-string-table))
  2121. (bv (make-bytevector (* n size) 0)))
  2122. (define (intern-string! name)
  2123. (string-table-intern! strtab (if name (symbol->string name) "")))
  2124. (for-each
  2125. (lambda (meta n)
  2126. (let ((name (intern-string! (meta-name meta))))
  2127. (write-elf-symbol bv (* n size) endianness word-size
  2128. (make-elf-symbol
  2129. #:name name
  2130. ;; Symbol value and size are measured in
  2131. ;; bytes, not u32s.
  2132. #:value (meta-low-pc meta)
  2133. #:size (- (meta-high-pc meta)
  2134. (meta-low-pc meta))
  2135. #:type STT_FUNC
  2136. #:visibility STV_HIDDEN
  2137. #:shndx (elf-section-index text-section)))))
  2138. meta (iota n))
  2139. (let ((strtab (make-object asm '.strtab
  2140. (link-string-table! strtab)
  2141. '() '()
  2142. #:type SHT_STRTAB #:flags 0)))
  2143. (values (make-object asm '.symtab
  2144. bv
  2145. '() '()
  2146. #:type SHT_SYMTAB #:flags 0 #:entsize size
  2147. #:link (elf-section-index
  2148. (linker-object-section strtab)))
  2149. strtab))))
  2150. ;;; The .guile.arities section describes the arities that a function can
  2151. ;;; have. It is in two parts: a sorted array of headers describing
  2152. ;;; basic arities, and an array of links out to a string table (and in
  2153. ;;; the case of keyword arguments, to the data section) for argument
  2154. ;;; names. The whole thing is prefixed by a uint32 indicating the
  2155. ;;; offset of the end of the headers array.
  2156. ;;;
  2157. ;;; The arity headers array is a packed array of structures of the form:
  2158. ;;;
  2159. ;;; struct arity_header {
  2160. ;;; uint32_t low_pc;
  2161. ;;; uint32_t high_pc;
  2162. ;;; uint32_t offset;
  2163. ;;; uint32_t flags;
  2164. ;;; uint32_t nreq;
  2165. ;;; uint32_t nopt;
  2166. ;;; uint32_t nlocals;
  2167. ;;; }
  2168. ;;;
  2169. ;;; All of the offsets and addresses are 32 bits. We can expand in the
  2170. ;;; future to use 64-bit offsets if appropriate, but there are other
  2171. ;;; aspects of bytecode that constrain us to a total image that fits in
  2172. ;;; 32 bits, so for the moment we'll simplify the problem space.
  2173. ;;;
  2174. ;;; The following flags values are defined:
  2175. ;;;
  2176. ;;; #x1: has-rest?
  2177. ;;; #x2: allow-other-keys?
  2178. ;;; #x4: has-keyword-args?
  2179. ;;; #x8: is-case-lambda?
  2180. ;;; #x10: is-in-case-lambda?
  2181. ;;; #x20: elided-closure?
  2182. ;;;
  2183. ;;; Functions with a single arity specify their number of required and
  2184. ;;; optional arguments in nreq and nopt, and do not have the
  2185. ;;; is-case-lambda? flag set. Their "offset" member links to an array
  2186. ;;; of pointers into the associated .guile.arities.strtab string table,
  2187. ;;; identifying the argument names. This offset is relative to the
  2188. ;;; start of the .guile.arities section.
  2189. ;;;
  2190. ;;; If the arity has keyword arguments -- if has-keyword-args? is set in
  2191. ;;; the flags -- the first uint32 pointed to by offset encodes a link to
  2192. ;;; the "keyword indices" literal, in the data section. Then follow the
  2193. ;;; names for all locals, in order, as uleb128 values. The required
  2194. ;;; arguments will be the first locals, followed by the optionals,
  2195. ;;; followed by the rest argument if if has-rest? is set. The names
  2196. ;;; point into the associated string table section.
  2197. ;;;
  2198. ;;; Functions with no arities have no arities information present in the
  2199. ;;; .guile.arities section.
  2200. ;;;
  2201. ;;; Functions with multiple arities are preceded by a header with
  2202. ;;; is-case-lambda? set. All other fields are 0, except low-pc and
  2203. ;;; high-pc which should be the bounds of the whole function. Headers
  2204. ;;; for the individual arities follow, with the is-in-case-lambda? flag
  2205. ;;; set. In this way the whole headers array is sorted in increasing
  2206. ;;; low-pc order, and case-lambda clauses are contained within the
  2207. ;;; [low-pc, high-pc] of the case-lambda header.
  2208. ;;;
  2209. ;;; Normally the 0th argument is the closure for the function being
  2210. ;;; called. However if the function is "well-known" -- all of its call
  2211. ;;; sites are visible -- then the compiler may elide the closure, and
  2212. ;;; the 0th argument is the first user-visible argument.
  2213. ;; Length of the prefix to the arities section, in bytes.
  2214. (define arities-prefix-len 4)
  2215. ;; Length of an arity header, in bytes.
  2216. (define arity-header-len (* 7 4))
  2217. ;; Some helpers.
  2218. (define (put-uleb128 port val)
  2219. (let lp ((val val))
  2220. (let ((next (ash val -7)))
  2221. (if (zero? next)
  2222. (put-u8 port val)
  2223. (begin
  2224. (put-u8 port (logior #x80 (logand val #x7f)))
  2225. (lp next))))))
  2226. (define (put-sleb128 port val)
  2227. (let lp ((val val))
  2228. (if (<= 0 (+ val 64) 127)
  2229. (put-u8 port (logand val #x7f))
  2230. (begin
  2231. (put-u8 port (logior #x80 (logand val #x7f)))
  2232. (lp (ash val -7))))))
  2233. (define (port-position port)
  2234. (seek port 0 SEEK_CUR))
  2235. (define-inline (pack-arity-flags has-rest? allow-other-keys?
  2236. has-keyword-args? is-case-lambda?
  2237. is-in-case-lambda? elided-closure?)
  2238. (logior (if has-rest? (ash 1 0) 0)
  2239. (if allow-other-keys? (ash 1 1) 0)
  2240. (if has-keyword-args? (ash 1 2) 0)
  2241. (if is-case-lambda? (ash 1 3) 0)
  2242. (if is-in-case-lambda? (ash 1 4) 0)
  2243. (if elided-closure? (ash 1 5) 0)))
  2244. (define (write-arities asm metas headers names-port strtab)
  2245. (define (write-header pos low-pc high-pc offset flags nreq nopt nlocals)
  2246. (unless (<= (+ nreq nopt) nlocals)
  2247. (error "forgot to emit definition instructions?"))
  2248. (bytevector-u32-set! headers pos low-pc (asm-endianness asm))
  2249. (bytevector-u32-set! headers (+ pos 4) high-pc (asm-endianness asm))
  2250. (bytevector-u32-set! headers (+ pos 8) offset (asm-endianness asm))
  2251. (bytevector-u32-set! headers (+ pos 12) flags (asm-endianness asm))
  2252. (bytevector-u32-set! headers (+ pos 16) nreq (asm-endianness asm))
  2253. (bytevector-u32-set! headers (+ pos 20) nopt (asm-endianness asm))
  2254. (bytevector-u32-set! headers (+ pos 24) nlocals (asm-endianness asm)))
  2255. (define (write-kw-indices kw-indices relocs)
  2256. ;; FIXME: Assert that kw-indices is already interned.
  2257. (if (pair? kw-indices)
  2258. (let ((pos (+ (bytevector-length headers)
  2259. (port-position names-port)))
  2260. (label (intern-constant asm kw-indices)))
  2261. (put-bytevector names-port #vu8(0 0 0 0))
  2262. (cons (make-linker-reloc 'abs32/1 pos 0 label) relocs))
  2263. relocs))
  2264. (define (write-arity pos arity in-case-lambda? relocs)
  2265. (write-header pos (arity-low-pc arity)
  2266. (arity-high-pc arity)
  2267. ;; FIXME: Seems silly to add on bytevector-length of
  2268. ;; headers, given the arities-prefix.
  2269. (+ (bytevector-length headers) (port-position names-port))
  2270. (pack-arity-flags (arity-rest arity)
  2271. (arity-allow-other-keys? arity)
  2272. (pair? (arity-kw-indices arity))
  2273. #f
  2274. in-case-lambda?
  2275. (not (arity-has-closure? arity)))
  2276. (length (arity-req arity))
  2277. (length (arity-opt arity))
  2278. (length (arity-definitions arity)))
  2279. (let ((relocs (write-kw-indices (arity-kw-indices arity) relocs)))
  2280. ;; Write local names.
  2281. (let lp ((definitions (arity-definitions arity)))
  2282. (match definitions
  2283. (() relocs)
  2284. ((#(name slot representation def) . definitions)
  2285. (let ((sym (if (symbol? name)
  2286. (string-table-intern! strtab (symbol->string name))
  2287. 0)))
  2288. (put-uleb128 names-port sym)
  2289. (lp definitions)))))
  2290. ;; Now write their definitions.
  2291. (let lp ((definitions (arity-definitions arity)))
  2292. (match definitions
  2293. (() relocs)
  2294. ((#(name slot representation def) . definitions)
  2295. (put-uleb128 names-port def)
  2296. (let ((tag (case representation
  2297. ((scm) 0)
  2298. ((f64) 1)
  2299. ((u64) 2)
  2300. ((s64) 3)
  2301. ((ptr) 4)
  2302. (else (error "what!" representation)))))
  2303. (put-uleb128 names-port (logior (ash slot 3) tag)))
  2304. (lp definitions))))))
  2305. (let lp ((metas metas) (pos arities-prefix-len) (relocs '()))
  2306. (match metas
  2307. (()
  2308. (unless (= pos (bytevector-length headers))
  2309. (error "expected to fully fill the bytevector"
  2310. pos (bytevector-length headers)))
  2311. relocs)
  2312. ((meta . metas)
  2313. (match (meta-arities meta)
  2314. (() (lp metas pos relocs))
  2315. ((arity)
  2316. (lp metas
  2317. (+ pos arity-header-len)
  2318. (write-arity pos arity #f relocs)))
  2319. (arities
  2320. ;; Write a case-lambda header, then individual arities.
  2321. ;; The case-lambda header's offset link is 0.
  2322. (write-header pos (meta-low-pc meta) (meta-high-pc meta) 0
  2323. (pack-arity-flags #f #f #f #t #f #f) 0 0 0)
  2324. (let lp* ((arities arities) (pos (+ pos arity-header-len))
  2325. (relocs relocs))
  2326. (match arities
  2327. (() (lp metas pos relocs))
  2328. ((arity . arities)
  2329. (lp* arities
  2330. (+ pos arity-header-len)
  2331. (write-arity pos arity #t relocs)))))))))))
  2332. (define (link-arities asm)
  2333. (define (meta-arities-header-size meta)
  2334. (define (lambda-size arity)
  2335. arity-header-len)
  2336. (define (case-lambda-size arities)
  2337. (fold +
  2338. arity-header-len ;; case-lambda header
  2339. (map lambda-size arities))) ;; the cases
  2340. (match (meta-arities meta)
  2341. (() 0)
  2342. ((arity) (lambda-size arity))
  2343. (arities (case-lambda-size arities))))
  2344. (define (bytevector-append a b)
  2345. (let ((out (make-bytevector (+ (bytevector-length a)
  2346. (bytevector-length b)))))
  2347. (bytevector-copy! a 0 out 0 (bytevector-length a))
  2348. (bytevector-copy! b 0 out (bytevector-length a) (bytevector-length b))
  2349. out))
  2350. (let* ((endianness (asm-endianness asm))
  2351. (metas (reverse (asm-meta asm)))
  2352. (header-size (fold (lambda (meta size)
  2353. (+ size (meta-arities-header-size meta)))
  2354. arities-prefix-len
  2355. metas))
  2356. (strtab (make-string-table))
  2357. (headers (make-bytevector header-size 0)))
  2358. (bytevector-u32-set! headers 0 (bytevector-length headers) endianness)
  2359. (let-values (((names-port get-name-bv) (open-bytevector-output-port)))
  2360. (let* ((relocs (write-arities asm metas headers names-port strtab))
  2361. (strtab (make-object asm '.guile.arities.strtab
  2362. (link-string-table! strtab)
  2363. '() '()
  2364. #:type SHT_STRTAB #:flags 0)))
  2365. (values (make-object asm '.guile.arities
  2366. (bytevector-append headers (get-name-bv))
  2367. relocs '()
  2368. #:type SHT_PROGBITS #:flags 0
  2369. #:link (elf-section-index
  2370. (linker-object-section strtab)))
  2371. strtab)))))
  2372. ;;;
  2373. ;;; The .guile.docstrs section is a packed, sorted array of (pc, str)
  2374. ;;; values. Pc and str are both 32 bits wide. (Either could change to
  2375. ;;; 64 bits if appropriate in the future.) Pc is the address of the
  2376. ;;; entry to a program, relative to the start of the text section, in
  2377. ;;; bytes, and str is an index into the associated .guile.docstrs.strtab
  2378. ;;; string table section.
  2379. ;;;
  2380. ;; The size of a docstrs entry, in bytes.
  2381. (define docstr-size 8)
  2382. (define (link-docstrs asm)
  2383. (define (find-docstrings)
  2384. (filter-map (lambda (meta)
  2385. (define (is-documentation? pair)
  2386. (eq? (car pair) 'documentation))
  2387. (let* ((props (meta-properties meta))
  2388. (tail (find-tail is-documentation? props)))
  2389. (and tail
  2390. (not (find-tail is-documentation? (cdr tail)))
  2391. (string? (cdar tail))
  2392. (cons (meta-low-pc meta) (cdar tail)))))
  2393. (reverse (asm-meta asm))))
  2394. (let* ((endianness (asm-endianness asm))
  2395. (docstrings (find-docstrings))
  2396. (strtab (make-string-table))
  2397. (bv (make-bytevector (* (length docstrings) docstr-size) 0)))
  2398. (fold (lambda (pair pos)
  2399. (match pair
  2400. ((pc . string)
  2401. (bytevector-u32-set! bv pos pc endianness)
  2402. (bytevector-u32-set! bv (+ pos 4)
  2403. (string-table-intern! strtab string)
  2404. endianness)
  2405. (+ pos docstr-size))))
  2406. 0
  2407. docstrings)
  2408. (let ((strtab (make-object asm '.guile.docstrs.strtab
  2409. (link-string-table! strtab)
  2410. '() '()
  2411. #:type SHT_STRTAB #:flags 0)))
  2412. (values (make-object asm '.guile.docstrs
  2413. bv
  2414. '() '()
  2415. #:type SHT_PROGBITS #:flags 0
  2416. #:link (elf-section-index
  2417. (linker-object-section strtab)))
  2418. strtab))))
  2419. ;;;
  2420. ;;; The .guile.procprops section is a packed, sorted array of (pc, addr)
  2421. ;;; values. Pc and addr are both 32 bits wide. (Either could change to
  2422. ;;; 64 bits if appropriate in the future.) Pc is the address of the
  2423. ;;; entry to a program, relative to the start of the text section, and
  2424. ;;; addr is the address of the associated properties alist, relative to
  2425. ;;; the start of the ELF image.
  2426. ;;;
  2427. ;;; Since procedure properties are stored in the data sections, we need
  2428. ;;; to link the procedures property section first. (Note that this
  2429. ;;; constraint does not apply to the arities section, which may
  2430. ;;; reference the data sections via the kw-indices literal, because
  2431. ;;; assembling the text section already makes sure that the kw-indices
  2432. ;;; are interned.)
  2433. ;;;
  2434. ;; The size of a procprops entry, in bytes.
  2435. (define procprops-size 8)
  2436. (define (link-procprops asm)
  2437. (define (assoc-remove-one alist key value-pred)
  2438. (match alist
  2439. (() '())
  2440. ((((? (lambda (x) (eq? x key))) . value) . alist)
  2441. (if (value-pred value)
  2442. alist
  2443. (acons key value alist)))
  2444. (((k . v) . alist)
  2445. (acons k v (assoc-remove-one alist key value-pred)))))
  2446. (define (props-without-name-or-docstring meta)
  2447. (assoc-remove-one
  2448. (assoc-remove-one (meta-properties meta) 'name (lambda (x) #t))
  2449. 'documentation
  2450. string?))
  2451. (define (find-procprops)
  2452. (filter-map (lambda (meta)
  2453. (let ((props (props-without-name-or-docstring meta)))
  2454. (and (pair? props)
  2455. (cons (meta-low-pc meta) props))))
  2456. (reverse (asm-meta asm))))
  2457. (let* ((endianness (asm-endianness asm))
  2458. (procprops (find-procprops))
  2459. (bv (make-bytevector (* (length procprops) procprops-size) 0)))
  2460. (let lp ((procprops procprops) (pos 0) (relocs '()))
  2461. (match procprops
  2462. (()
  2463. (make-object asm '.guile.procprops
  2464. bv
  2465. relocs '()
  2466. #:type SHT_PROGBITS #:flags 0))
  2467. (((pc . props) . procprops)
  2468. (bytevector-u32-set! bv pos pc endianness)
  2469. (lp procprops
  2470. (+ pos procprops-size)
  2471. (cons (make-linker-reloc 'abs32/1 (+ pos 4) 0
  2472. (intern-constant asm props))
  2473. relocs)))))))
  2474. ;;;
  2475. ;;; The DWARF .debug_info, .debug_abbrev, .debug_str, and .debug_loc
  2476. ;;; sections provide line number and local variable liveness
  2477. ;;; information. Their format is defined by the DWARF
  2478. ;;; specifications.
  2479. ;;;
  2480. (define (asm-language asm)
  2481. ;; FIXME: Plumb language through to the assembler.
  2482. 'scheme)
  2483. ;; -> 5 values: .debug_info, .debug_abbrev, .debug_str, .debug_loc, .debug_lines
  2484. (define (link-debug asm)
  2485. (define (put-s8 port val)
  2486. (let ((bv (make-bytevector 1)))
  2487. (bytevector-s8-set! bv 0 val)
  2488. (put-bytevector port bv)))
  2489. (define (put-u16 port val)
  2490. (let ((bv (make-bytevector 2)))
  2491. (bytevector-u16-set! bv 0 val (asm-endianness asm))
  2492. (put-bytevector port bv)))
  2493. (define (put-u32 port val)
  2494. (let ((bv (make-bytevector 4)))
  2495. (bytevector-u32-set! bv 0 val (asm-endianness asm))
  2496. (put-bytevector port bv)))
  2497. (define (put-u64 port val)
  2498. (let ((bv (make-bytevector 8)))
  2499. (bytevector-u64-set! bv 0 val (asm-endianness asm))
  2500. (put-bytevector port bv)))
  2501. (define (meta->subprogram-die meta)
  2502. `(subprogram
  2503. (@ ,@(cond
  2504. ((meta-name meta)
  2505. => (lambda (name) `((name ,(symbol->string name)))))
  2506. (else
  2507. '()))
  2508. (low-pc ,(meta-label meta))
  2509. (high-pc ,(- (meta-high-pc meta) (meta-low-pc meta))))))
  2510. (define (make-compile-unit-die asm)
  2511. `(compile-unit
  2512. (@ (producer ,(string-append "Guile " (version)))
  2513. (language ,(asm-language asm))
  2514. (low-pc .rtl-text)
  2515. (high-pc ,(asm-pos asm))
  2516. (stmt-list 0))
  2517. ,@(map meta->subprogram-die (reverse (asm-meta asm)))))
  2518. (let-values (((die-port get-die-bv) (open-bytevector-output-port))
  2519. ((die-relocs) '())
  2520. ((abbrev-port get-abbrev-bv) (open-bytevector-output-port))
  2521. ;; (tag has-kids? attrs forms) -> code
  2522. ((abbrevs) vlist-null)
  2523. ((strtab) (make-string-table))
  2524. ((line-port get-line-bv) (open-bytevector-output-port))
  2525. ((line-relocs) '())
  2526. ;; file -> code
  2527. ((files) vlist-null))
  2528. (define (write-abbrev code tag has-children? attrs forms)
  2529. (put-uleb128 abbrev-port code)
  2530. (put-uleb128 abbrev-port (tag-name->code tag))
  2531. (put-u8 abbrev-port (children-name->code (if has-children? 'yes 'no)))
  2532. (for-each (lambda (attr form)
  2533. (put-uleb128 abbrev-port (attribute-name->code attr))
  2534. (put-uleb128 abbrev-port (form-name->code form)))
  2535. attrs forms)
  2536. (put-uleb128 abbrev-port 0)
  2537. (put-uleb128 abbrev-port 0))
  2538. (define (intern-abbrev tag has-children? attrs forms)
  2539. (let ((key (list tag has-children? attrs forms)))
  2540. (match (vhash-assoc key abbrevs)
  2541. ((_ . code) code)
  2542. (#f (let ((code (1+ (vlist-length abbrevs))))
  2543. (set! abbrevs (vhash-cons key code abbrevs))
  2544. (write-abbrev code tag has-children? attrs forms)
  2545. code)))))
  2546. (define (intern-file file)
  2547. (match (vhash-assoc file files)
  2548. ((_ . code) code)
  2549. (#f (let ((code (1+ (vlist-length files))))
  2550. (set! files (vhash-cons file code files))
  2551. code))))
  2552. (define (write-sources)
  2553. ;; Choose line base and line range values that will allow for an
  2554. ;; address advance range of 16 words. The special opcode range is
  2555. ;; from 10 to 255, so 246 values.
  2556. (define base -4)
  2557. (define range 15)
  2558. (define min-inc 4) ; Minimum PC increment.
  2559. (let lp ((sources (asm-sources asm)) (out '()))
  2560. (match sources
  2561. (((pc . s) . sources)
  2562. (let ((file (assq-ref s 'filename))
  2563. (line (assq-ref s 'line))
  2564. (col (assq-ref s 'column)))
  2565. (lp sources
  2566. ;; Guile line and column numbers are 0-indexed, but
  2567. ;; they are 1-indexed for DWARF.
  2568. (if (and line col)
  2569. (cons (list pc
  2570. (if (string? file) (intern-file file) 0)
  2571. (1+ line)
  2572. (1+ col))
  2573. out)
  2574. out))))
  2575. (()
  2576. ;; Compilation unit header for .debug_line. We write in
  2577. ;; DWARF 2 format because more tools understand it than DWARF
  2578. ;; 4, which incompatibly adds another field to this header.
  2579. (put-u32 line-port 0) ; Length; will patch later.
  2580. (put-u16 line-port 2) ; DWARF 2 format.
  2581. (put-u32 line-port 0) ; Prologue length; will patch later.
  2582. (put-u8 line-port min-inc) ; Minimum instruction length: 4 bytes.
  2583. (put-u8 line-port 1) ; Default is-stmt: true.
  2584. (put-s8 line-port base) ; Line base. See the DWARF standard.
  2585. (put-u8 line-port range) ; Line range. See the DWARF standard.
  2586. (put-u8 line-port 10) ; Opcode base: the first "special" opcode.
  2587. ;; A table of the number of uleb128 arguments taken by each
  2588. ;; of the standard opcodes.
  2589. (put-u8 line-port 0) ; 1: copy
  2590. (put-u8 line-port 1) ; 2: advance-pc
  2591. (put-u8 line-port 1) ; 3: advance-line
  2592. (put-u8 line-port 1) ; 4: set-file
  2593. (put-u8 line-port 1) ; 5: set-column
  2594. (put-u8 line-port 0) ; 6: negate-stmt
  2595. (put-u8 line-port 0) ; 7: set-basic-block
  2596. (put-u8 line-port 0) ; 8: const-add-pc
  2597. (put-u8 line-port 1) ; 9: fixed-advance-pc
  2598. ;; Include directories, as a zero-terminated sequence of
  2599. ;; nul-terminated strings. Nothing, for the moment.
  2600. (put-u8 line-port 0)
  2601. ;; File table. For each file that contributes to this
  2602. ;; compilation unit, a nul-terminated file name string, and a
  2603. ;; uleb128 for each of directory the file was found in, the
  2604. ;; modification time, and the file's size in bytes. We pass
  2605. ;; zero for the latter three fields.
  2606. (vlist-fold-right
  2607. (lambda (pair seed)
  2608. (match pair
  2609. ((file . code)
  2610. (put-bytevector line-port (string->utf8 file))
  2611. (put-u8 line-port 0)
  2612. (put-uleb128 line-port 0) ; directory
  2613. (put-uleb128 line-port 0) ; mtime
  2614. (put-uleb128 line-port 0))) ; size
  2615. seed)
  2616. #f
  2617. files)
  2618. (put-u8 line-port 0) ; 0 byte terminating file list.
  2619. ;; Patch prologue length.
  2620. (let ((offset (port-position line-port)))
  2621. (seek line-port 6 SEEK_SET)
  2622. (put-u32 line-port (- offset 10))
  2623. (seek line-port offset SEEK_SET))
  2624. ;; Now write the statement program.
  2625. (let ()
  2626. (define (extended-op opcode payload-len)
  2627. (put-u8 line-port 0) ; extended op
  2628. (put-uleb128 line-port (1+ payload-len)) ; payload-len + opcode
  2629. (put-uleb128 line-port opcode))
  2630. (define (set-address sym)
  2631. (define (add-reloc! kind)
  2632. (set! line-relocs
  2633. (cons (make-linker-reloc kind
  2634. (port-position line-port)
  2635. 0
  2636. sym)
  2637. line-relocs)))
  2638. (match (asm-word-size asm)
  2639. (4
  2640. (extended-op 2 4)
  2641. (add-reloc! 'abs32/1)
  2642. (put-u32 line-port 0))
  2643. (8
  2644. (extended-op 2 8)
  2645. (add-reloc! 'abs64/1)
  2646. (put-u64 line-port 0))))
  2647. (define (end-sequence pc)
  2648. (let ((pc-inc (/ (- (asm-pos asm) pc) min-inc)))
  2649. (put-u8 line-port 2) ; advance-pc
  2650. (put-uleb128 line-port pc-inc))
  2651. (extended-op 1 0))
  2652. (define (advance-pc pc-inc line-inc)
  2653. (let ((spec (+ (- line-inc base)
  2654. (* (/ pc-inc min-inc) range)
  2655. 10)))
  2656. (cond
  2657. ((or (< line-inc base) (>= line-inc (+ base range)))
  2658. (advance-line line-inc)
  2659. (advance-pc pc-inc 0))
  2660. ((<= spec 255)
  2661. (put-u8 line-port spec))
  2662. ((< spec 500)
  2663. (put-u8 line-port 8) ; const-advance-pc
  2664. (advance-pc (- pc-inc (* (floor/ (- 255 10) range) min-inc))
  2665. line-inc))
  2666. (else
  2667. (put-u8 line-port 2) ; advance-pc
  2668. (put-uleb128 line-port (/ pc-inc min-inc))
  2669. (advance-pc 0 line-inc)))))
  2670. (define (advance-line inc)
  2671. (put-u8 line-port 3)
  2672. (put-sleb128 line-port inc))
  2673. (define (set-file file)
  2674. (put-u8 line-port 4)
  2675. (put-uleb128 line-port file))
  2676. (define (set-column col)
  2677. (put-u8 line-port 5)
  2678. (put-uleb128 line-port col))
  2679. (set-address '.rtl-text)
  2680. (let lp ((in out) (pc 0) (file 1) (line 1) (col 0))
  2681. (match in
  2682. (()
  2683. (when (null? out)
  2684. ;; There was no source info in the first place. Set
  2685. ;; file register to 0 before adding final row.
  2686. (set-file 0))
  2687. (end-sequence pc))
  2688. (((pc* file* line* col*) . in*)
  2689. (cond
  2690. ((and (eqv? file file*) (eqv? line line*) (eqv? col col*))
  2691. (lp in* pc file line col))
  2692. (else
  2693. (unless (eqv? col col*)
  2694. (set-column col*))
  2695. (unless (eqv? file file*)
  2696. (set-file file*))
  2697. (advance-pc (- pc* pc) (- line* line))
  2698. (lp in* pc* file* line* col*)))))))))))
  2699. (define (compute-code attr val)
  2700. (match attr
  2701. ('name (string-table-intern! strtab val))
  2702. ('low-pc val)
  2703. ('high-pc val)
  2704. ('producer (string-table-intern! strtab val))
  2705. ('language (language-name->code val))
  2706. ('stmt-list val)))
  2707. (define (choose-form attr val code)
  2708. (cond
  2709. ((string? val) 'strp)
  2710. ((eq? attr 'stmt-list) 'sec-offset)
  2711. ((eq? attr 'low-pc) 'addr)
  2712. ((exact-integer? code)
  2713. (cond
  2714. ((< code 0) 'sleb128)
  2715. ((<= code #xff) 'data1)
  2716. ((<= code #xffff) 'data2)
  2717. ((<= code #xffffffff) 'data4)
  2718. ((<= code #xffffffffffffffff) 'data8)
  2719. (else 'uleb128)))
  2720. (else (error "unhandled case" attr val code))))
  2721. (define (add-die-relocation! kind sym)
  2722. (set! die-relocs
  2723. (cons (make-linker-reloc kind (port-position die-port) 0 sym)
  2724. die-relocs)))
  2725. (define (write-value code form)
  2726. (match form
  2727. ('data1 (put-u8 die-port code))
  2728. ('data2 (put-u16 die-port code))
  2729. ('data4 (put-u32 die-port code))
  2730. ('data8 (put-u64 die-port code))
  2731. ('uleb128 (put-uleb128 die-port code))
  2732. ('sleb128 (put-sleb128 die-port code))
  2733. ('addr
  2734. (match (asm-word-size asm)
  2735. (4
  2736. (add-die-relocation! 'abs32/1 code)
  2737. (put-u32 die-port 0))
  2738. (8
  2739. (add-die-relocation! 'abs64/1 code)
  2740. (put-u64 die-port 0))))
  2741. ('sec-offset (put-u32 die-port code))
  2742. ('strp (put-u32 die-port code))))
  2743. (define (write-die die)
  2744. (match die
  2745. ((tag ('@ (attrs vals) ...) children ...)
  2746. (let* ((codes (map compute-code attrs vals))
  2747. (forms (map choose-form attrs vals codes))
  2748. (has-children? (not (null? children)))
  2749. (abbrev-code (intern-abbrev tag has-children? attrs forms)))
  2750. (put-uleb128 die-port abbrev-code)
  2751. (for-each write-value codes forms)
  2752. (when has-children?
  2753. (for-each write-die children)
  2754. (put-uleb128 die-port 0))))))
  2755. ;; Compilation unit header.
  2756. (put-u32 die-port 0) ; Length; will patch later.
  2757. (put-u16 die-port 4) ; DWARF 4.
  2758. (put-u32 die-port 0) ; Abbrevs offset.
  2759. (put-u8 die-port (asm-word-size asm)) ; Address size.
  2760. (write-die (make-compile-unit-die asm))
  2761. ;; Terminate the abbrevs list.
  2762. (put-uleb128 abbrev-port 0)
  2763. (write-sources)
  2764. (values (let ((bv (get-die-bv)))
  2765. ;; Patch DWARF32 length.
  2766. (bytevector-u32-set! bv 0 (- (bytevector-length bv) 4)
  2767. (asm-endianness asm))
  2768. (make-object asm '.debug_info bv die-relocs '()
  2769. #:type SHT_PROGBITS #:flags 0))
  2770. (make-object asm '.debug_abbrev (get-abbrev-bv) '() '()
  2771. #:type SHT_PROGBITS #:flags 0)
  2772. (make-object asm '.debug_str (link-string-table! strtab) '() '()
  2773. #:type SHT_PROGBITS #:flags 0)
  2774. (make-object asm '.debug_loc #vu8() '() '()
  2775. #:type SHT_PROGBITS #:flags 0)
  2776. (let ((bv (get-line-bv)))
  2777. ;; Patch DWARF32 length.
  2778. (bytevector-u32-set! bv 0 (- (bytevector-length bv) 4)
  2779. (asm-endianness asm))
  2780. (make-object asm '.debug_line bv line-relocs '()
  2781. #:type SHT_PROGBITS #:flags 0)))))
  2782. (define (link-objects asm)
  2783. (let*-values (;; Link procprops before constants, because it probably
  2784. ;; interns more constants.
  2785. ((procprops) (link-procprops asm))
  2786. ((ro rw rw-init) (link-constants asm))
  2787. ;; Link text object after constants, so that the
  2788. ;; constants initializer gets included.
  2789. ((text) (link-text-object asm))
  2790. ((frame-maps) (link-frame-maps asm))
  2791. ((dt) (link-dynamic-section asm text rw rw-init frame-maps))
  2792. ((symtab strtab) (link-symtab (linker-object-section text) asm))
  2793. ((arities arities-strtab) (link-arities asm))
  2794. ((docstrs docstrs-strtab) (link-docstrs asm))
  2795. ((dinfo dabbrev dstrtab dloc dline) (link-debug asm))
  2796. ;; This needs to be linked last, because linking other
  2797. ;; sections adds entries to the string table.
  2798. ((shstrtab) (link-shstrtab asm)))
  2799. (filter identity
  2800. (list text ro frame-maps rw dt symtab strtab
  2801. arities arities-strtab
  2802. docstrs docstrs-strtab procprops
  2803. dinfo dabbrev dstrtab dloc dline
  2804. shstrtab))))
  2805. ;;;
  2806. ;;; High-level public interfaces.
  2807. ;;;
  2808. (define* (link-assembly asm #:key (page-aligned? #t))
  2809. "Produce an ELF image from the code and data emitted into @var{asm}.
  2810. The result is a bytevector, by default linked so that read-only and
  2811. writable data are on separate pages. Pass @code{#:page-aligned? #f} to
  2812. disable this behavior."
  2813. (link-elf (link-objects asm) #:page-aligned? page-aligned?))